@elizaos/plugin-twitter 1.0.9 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/actions/spaceJoin.ts","../src/spaces.ts","../src/client/api.ts","../src/client/errors.ts","../src/client/platform/platform-interface.ts","../src/client/platform/index.ts","../src/client/requests.ts","../src/client/auth.ts","../src/client/browser-fingerprint.ts","../src/client/auth-user.ts","../src/client/profile.ts","../src/client/grok.ts","../src/client/messages.ts","../src/client/relationships.ts","../src/client/timeline-async.ts","../src/client/timeline-relationship.ts","../src/client/search.ts","../src/client/type-util.ts","../src/client/timeline-tweet-util.ts","../src/client/timeline-v2.ts","../src/client/timeline-search.ts","../src/client/spaces.ts","../src/client/timeline-following.ts","../src/client/timeline-home.ts","../src/client/trends.ts","../src/client/api-data.ts","../src/client/timeline-list.ts","../src/client/tweets.ts","../src/client/client.ts","../src/client/spaces/core/Space.ts","../src/client/spaces/logger.ts","../src/client/spaces/utils.ts","../src/client/spaces/core/ChatClient.ts","../src/client/spaces/core/JanusClient.ts","../src/client/spaces/core/JanusAudio.ts","../src/client/spaces/core/SpaceParticipant.ts","../src/client/spaces/plugins/SttTtsPlugin.ts","../src/client/spaces/plugins/RecordToDiskPlugin.ts","../src/client/spaces/plugins/MonitorAudioPlugin.ts","../src/client/spaces/plugins/IdleMonitorPlugin.ts","../src/client/spaces/plugins/HlsRecordPlugin.ts","../src/sttTtsSpaces.ts","../src/utils.ts","../src/constants.ts","../src/base.ts","../src/interactions.ts","../src/environment.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/post.ts","../src/timeline.ts","../src/templates.ts","../src/tests.ts"],"sourcesContent":["import {\n ChannelType,\n type Entity,\n EventType,\n type IAgentRuntime,\n type Plugin,\n Role,\n type Room,\n Service,\n type UUID,\n type World,\n createUniqueUuid,\n logger,\n} from '@elizaos/core';\nimport spaceJoin from './actions/spaceJoin';\nimport { ClientBase } from './base';\nimport { TWITTER_SERVICE_NAME } from './constants';\nimport type { TwitterConfig } from './environment';\nimport { TwitterInteractionClient } from './interactions';\nimport { TwitterPostClient } from './post';\nimport { TwitterSpaceClient } from './spaces';\nimport { TwitterTimelineClient } from './timeline';\nimport { ClientBaseTestSuite } from './tests';\nimport { type ITwitterClient, TwitterEventTypes } from './types';\n\nconsole.log(`Twitter plugin loaded with service name: ${TWITTER_SERVICE_NAME}`);\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 * - search: searching tweets / replying logic\n * - interaction: handling mentions, replies\n * - space: launching and managing Twitter Spaces (optional)\n */\n/**\n * TwitterClientInstance class that implements ITwitterClient interface.\n *\n * @class\n * @implements {ITwitterClient}\n */\n\nexport class TwitterClientInstance implements ITwitterClient {\n client: ClientBase;\n post: TwitterPostClient;\n interaction: TwitterInteractionClient;\n timeline?: TwitterTimelineClient;\n space?: TwitterSpaceClient;\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 if (runtime.getSetting('TWITTER_ENABLE_POST_GENERATION') === true) {\n this.post = new TwitterPostClient(this.client, runtime, state);\n }\n\n // Mentions and interactions\n if (runtime.getSetting('TWITTER_INTERACTION_ENABLE') !== false) {\n this.interaction = new TwitterInteractionClient(this.client, runtime, state);\n }\n\n // handle timeline\n if (runtime.getSetting('TWITTER_TIMELINE_ENABLE') === true) {\n this.timeline = new TwitterTimelineClient(this.client, runtime, state);\n }\n\n // Optional Spaces logic (enabled if TWITTER_SPACES_ENABLE is true)\n if (runtime.getSetting('TWITTER_SPACES_ENABLE') === true) {\n this.space = new TwitterSpaceClient(this.client, runtime);\n }\n\n this.service = TwitterService.getInstance();\n }\n}\n\nexport class TwitterService extends Service {\n static serviceType: string = TWITTER_SERVICE_NAME;\n capabilityDescription = 'The agent is able to send and receive messages on twitter';\n private static instance: TwitterService;\n private clients: Map<string, TwitterClientInstance> = new Map();\n\n static getInstance(): TwitterService {\n if (!TwitterService.instance) {\n TwitterService.instance = new TwitterService();\n }\n return TwitterService.instance;\n }\n\n async createClient(\n runtime: IAgentRuntime,\n clientId: string,\n state: any\n ): Promise<TwitterClientInstance> {\n if (runtime.getSetting('TWITTER_2FA_SECRET') === null) {\n runtime.setSetting('TWITTER_2FA_SECRET', undefined, false);\n }\n try {\n // Check if client already exists\n const existingClient = this.getClient(clientId, runtime.agentId);\n if (existingClient) {\n logger.info(`Twitter client already exists for ${clientId}`);\n return existingClient;\n }\n\n // Create new client instance\n const client = new TwitterClientInstance(runtime, state);\n\n // Initialize the client\n await client.client.init();\n\n if (client.space) {\n client.space.startPeriodicSpaceCheck();\n }\n\n if (client.post) {\n client.post.start();\n }\n\n if (client.interaction) {\n client.interaction.start();\n }\n\n if (client.timeline) {\n client.timeline.start();\n }\n\n // Store the client instance\n this.clients.set(this.getClientKey(clientId, runtime.agentId), client);\n\n // Emit standardized WORLD_JOINED event once we have client profile\n await this.emitServerJoinedEvent(runtime, client);\n\n logger.info(`Created Twitter client for ${clientId}`);\n return client;\n } catch (error) {\n logger.error(`Failed to create Twitter client for ${clientId}:`, error);\n throw error;\n }\n }\n\n /**\n * Emits a standardized WORLD_JOINED event for Twitter\n * @param runtime The agent runtime\n * @param client The Twitter client instance\n */\n private async emitServerJoinedEvent(\n runtime: IAgentRuntime,\n client: TwitterClientInstance\n ): Promise<void> {\n try {\n if (!client.client.profile) {\n logger.warn(\"Twitter profile not available yet, can't emit WORLD_JOINED event\");\n return;\n }\n\n const profile = client.client.profile;\n const twitterId = profile.id;\n const username = profile.username;\n\n // Create the world ID based on the twitter user ID\n const worldId = createUniqueUuid(runtime, twitterId) as UUID;\n\n // For Twitter, we create a single world representing the user's Twitter account\n const world: World = {\n id: worldId,\n name: `${username}'s Twitter`,\n agentId: runtime.agentId,\n serverId: twitterId,\n metadata: {\n ownership: { ownerId: twitterId },\n roles: {\n [twitterId]: Role.OWNER,\n },\n twitter: {\n username: username,\n id: twitterId,\n },\n },\n };\n\n // We'll create a \"home timeline\" room\n const homeTimelineRoomId = createUniqueUuid(runtime, `${twitterId}-home`) as UUID;\n const homeTimelineRoom: Room = {\n id: homeTimelineRoomId,\n name: `${username}'s Timeline`,\n source: 'twitter',\n type: ChannelType.FEED,\n channelId: `${twitterId}-home`,\n serverId: twitterId,\n worldId: worldId,\n };\n\n // Create a \"mentions\" room\n const mentionsRoomId = createUniqueUuid(runtime, `${twitterId}-mentions`) as UUID;\n const mentionsRoom: Room = {\n id: mentionsRoomId,\n name: `${username}'s Mentions`,\n source: 'twitter',\n type: ChannelType.GROUP,\n channelId: `${twitterId}-mentions`,\n serverId: twitterId,\n worldId: worldId,\n };\n\n // Create an entity for the Twitter user\n const twitterUserId = createUniqueUuid(runtime, twitterId) as UUID;\n const twitterUser: Entity = {\n id: twitterUserId,\n names: [profile.screenName || username],\n agentId: runtime.agentId,\n metadata: {\n twitter: {\n id: twitterId,\n username: username,\n screenName: profile.screenName || username,\n name: profile.screenName || username,\n },\n },\n };\n\n // Emit the WORLD_JOINED event\n runtime.emitEvent([TwitterEventTypes.WORLD_JOINED, EventType.WORLD_JOINED], {\n runtime: runtime,\n world: world,\n rooms: [homeTimelineRoom, mentionsRoom],\n entities: [twitterUser],\n source: 'twitter',\n });\n\n logger.info(`Emitted WORLD_JOINED event for Twitter account ${username}`);\n } catch (error) {\n logger.error('Failed to emit WORLD_JOINED event for Twitter:', error);\n }\n }\n\n getClient(clientId: string, agentId: UUID): TwitterClientInstance | undefined {\n return this.clients.get(this.getClientKey(clientId, agentId));\n }\n\n async stopClient(clientId: string, agentId: UUID): Promise<void> {\n const key = this.getClientKey(clientId, agentId);\n const client = this.clients.get(key);\n if (client) {\n try {\n await client.service.stop();\n this.clients.delete(key);\n logger.info(`Stopped Twitter client for ${clientId}`);\n } catch (error) {\n logger.error(`Error stopping Twitter client for ${clientId}:`, error);\n }\n }\n }\n\n static async start(runtime: IAgentRuntime) {\n const twitterClientManager = TwitterService.getInstance();\n\n // Check for character-level Twitter credentials\n const twitterConfig: Partial<TwitterConfig> = {\n TWITTER_USERNAME:\n (runtime.getSetting('TWITTER_USERNAME') as string) ||\n runtime.character.settings?.TWITTER_USERNAME ||\n runtime.character.secrets?.TWITTER_USERNAME,\n TWITTER_PASSWORD:\n (runtime.getSetting('TWITTER_PASSWORD') as string) ||\n runtime.character.settings?.TWITTER_PASSWORD ||\n runtime.character.secrets?.TWITTER_PASSWORD,\n TWITTER_EMAIL:\n (runtime.getSetting('TWITTER_EMAIL') as string) ||\n runtime.character.settings?.TWITTER_EMAIL ||\n runtime.character.secrets?.TWITTER_EMAIL,\n TWITTER_2FA_SECRET:\n (runtime.getSetting('TWITTER_2FA_SECRET') as string) ||\n runtime.character.settings?.TWITTER_2FA_SECRET ||\n runtime.character.secrets?.TWITTER_2FA_SECRET,\n };\n\n // Filter out undefined values\n const config = Object.fromEntries(\n Object.entries(twitterConfig).filter(([_, v]) => v !== undefined)\n ) as TwitterConfig;\n\n // If we have enough settings to create a client, do so\n try {\n if (\n config.TWITTER_USERNAME &&\n // Basic auth\n config.TWITTER_PASSWORD &&\n config.TWITTER_EMAIL\n // ||\n // // API auth\n // (config.TWITTER_API_KEY && config.TWITTER_API_SECRET &&\n // config.TWITTER_ACCESS_TOKEN && config.TWITTER_ACCESS_TOKEN_SECRET)\n ) {\n logger.info('Creating default Twitter client from character settings');\n await twitterClientManager.createClient(runtime, runtime.agentId, config);\n }\n } catch (error) {\n logger.error('Failed to create default Twitter client:', error);\n throw error;\n }\n\n return twitterClientManager;\n }\n\n async stop(): Promise<void> {\n await this.stopAllClients();\n }\n\n async stopAllClients(): Promise<void> {\n for (const [key, client] of this.clients.entries()) {\n try {\n await client.service.stop();\n this.clients.delete(key);\n } catch (error) {\n logger.error(`Error stopping Twitter client ${key}:`, error);\n }\n }\n }\n\n private getClientKey(clientId: string, agentId: UUID): string {\n return `${clientId}-${agentId}`;\n }\n}\n\nconst twitterPlugin: Plugin = {\n name: TWITTER_SERVICE_NAME,\n description: 'Twitter client with per-server instance management',\n services: [TwitterService],\n actions: [spaceJoin],\n tests: [new ClientBaseTestSuite()],\n};\n\nexport default twitterPlugin;\n","import {\n type Action,\n type ActionExample,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type State,\n logger,\n} from \"@elizaos/core\";\nimport type { Tweet } from \"../client\";\nimport { SpaceActivity } from \"../spaces\";\n\nexport default {\n name: \"JOIN_TWITTER_SPACE\",\n similes: [\n \"JOIN_TWITTER_SPACE\",\n \"JOIN_SPACE\",\n \"JOIN_TWITTER_AUDIO\",\n \"JOIN_TWITTER_CALL\",\n \"JOIN_LIVE_CONVERSATION\",\n ],\n validate: async (runtime: IAgentRuntime, message: Memory, _state: State) => {\n if (message?.content?.source !== \"twitter\") {\n return false;\n }\n\n if (!message?.content?.tweet) {\n return false;\n }\n\n const spaceEnable = runtime.getSetting(\"TWITTER_SPACES_ENABLE\") === true;\n return spaceEnable;\n },\n description:\n \"Join a Twitter Space to participate in live audio conversations.\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n state: State,\n _options: any,\n callback: HandlerCallback,\n responses: Memory[]\n ): Promise<boolean> => {\n if (!state) {\n logger.error(\"State is not available.\");\n return false;\n }\n\n for (const response of responses) {\n await callback(response.content);\n }\n\n const service = runtime.getService(\"twitter\") as any;\n if (!service) {\n throw new Error(\"Twitter service not found\");\n }\n\n const manager = service.getClient(runtime.agentId, runtime.agentId);\n const client = manager.client;\n const spaceManager = manager.space;\n\n if (!spaceManager) {\n logger.error(\"space action - no space manager found\");\n return false;\n }\n\n if (spaceManager.spaceStatus !== SpaceActivity.IDLE) {\n logger.warn(\"currently hosting/participating a space\");\n return false;\n }\n\n const tweet = message.content.tweet as Tweet;\n if (!tweet) {\n logger.warn(\"space action - no tweet found in message\");\n return false;\n }\n\n async function joinSpaceByUrls(tweet: Tweet): Promise<boolean> {\n if (!tweet.urls) return false;\n\n for (const url of tweet.urls) {\n const match = url.match(/https:\\/\\/x\\.com\\/i\\/spaces\\/([a-zA-Z0-9]+)/);\n if (match) {\n const spaceId = match[1];\n try {\n const spaceInfo =\n await client.twitterClient.getAudioSpaceById(spaceId);\n if (spaceInfo?.metadata?.state === \"Running\") {\n const spaceJoined = await spaceManager.startParticipant(spaceId);\n return !!spaceJoined;\n }\n } catch (error) {\n logger.error(\"Error joining Twitter Space:\", error);\n }\n }\n }\n return false;\n }\n\n async function joinSpaceByUserName(userName: string): Promise<boolean> {\n try {\n const tweetGenerator = client.twitterClient.getTweets(userName);\n for await (const userTweet of tweetGenerator) {\n if (await joinSpaceByUrls(userTweet)) {\n return true;\n }\n }\n } catch (error) {\n logger.error(`Error fetching tweets for ${userName}:`, error);\n }\n return false;\n }\n\n // Attempt to join a Twitter Space from URLs in the tweet\n const spaceJoined = await joinSpaceByUrls(tweet);\n if (spaceJoined) return true;\n\n // If no Space was found in the URLs, check if the tweet author has an active Space\n const authorJoined = await joinSpaceByUserName(tweet.username);\n if (authorJoined) return true;\n\n // If the tweet author isn't hosting a Space, check if any mentioned users are currently hosting one\n const agentName = client.state.TWITTER_USERNAME;\n for (const mention of tweet.mentions) {\n if (mention.username !== agentName) {\n const mentionJoined = await joinSpaceByUserName(mention.username);\n if (mentionJoined) return true;\n }\n }\n await callback({\n text: \"I couldn't determine which Twitter Space to join.\",\n source: \"twitter\",\n });\n\n return false;\n },\n examples: [\n [\n {\n name: \"{{name1}}\",\n content: {\n text: \"Hey, let's join the 'Crypto Talk' Twitter Space!\",\n },\n },\n {\n name: \"{{name2}}\",\n content: {\n text: \"On my way\",\n actions: [\"JOIN_TWITTER_SPACE\"],\n },\n },\n ],\n [\n {\n name: \"{{name1}}\",\n content: {\n text: \"@{{name2}}, jump into the 'AI Revolution' Space!\",\n },\n },\n {\n name: \"{{name2}}\",\n content: {\n text: \"Joining now!\",\n actions: [\"JOIN_TWITTER_SPACE\"],\n },\n },\n ],\n ] as ActionExample[][],\n} as Action;\n","import {\n type IAgentRuntime,\n ModelType,\n createUniqueUuid,\n logger,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base\";\nimport {\n type Client,\n IdleMonitorPlugin,\n Space,\n type SpaceConfig,\n SpaceParticipant,\n type SpeakerRequest,\n} from \"./client/index\";\nimport { SttTtsPlugin } from \"./sttTtsSpaces\";\nimport { generateTopicsIfEmpty, isAgentInSpace, speakFiller } from \"./utils\";\n\n/**\n * Interface representing options for deciding on creating a Twitter Space.\n * @typedef {Object} TwitterSpaceDecisionOptions\n * @property {number} [maxSpeakers] - Maximum number of speakers allowed in the Twitter Space.\n * @property {number} [typicalDurationMinutes] - Typical duration of the Twitter Space in minutes.\n * @property {number} [idleKickTimeoutMs] - Timeout in milliseconds for kicking idle users from the Twitter Space.\n * @property {number} [minIntervalBetweenSpacesMinutes] - Minimum interval between creating new Twitter Spaces in minutes.\n * @property {boolean} [enableIdleMonitor] - Flag to enable or disable idle user monitoring in the Twitter Space.\n * @property {boolean} enableSpaceHosting - Flag to enable or disable space hosting in the Twitter Space.\n * @property {boolean} [enableRecording] - Flag to enable or disable recording of the Twitter Space.\n * @property {number} [speakerMaxDurationMs] - Maximum duration in milliseconds for each speaker in the Twitter Space.\n */\nexport interface TwitterSpaceDecisionOptions {\n maxSpeakers?: number;\n typicalDurationMinutes?: number;\n idleKickTimeoutMs?: number;\n minIntervalBetweenSpacesMinutes?: number;\n enableIdleMonitor?: boolean;\n enableSpaceHosting: boolean;\n enableRecording?: boolean;\n speakerMaxDurationMs?: number;\n}\n\n/**\n * Represents the state of the current speaker in a session.\n * @typedef { Object } CurrentSpeakerState\n * @property { string } userId - The unique identifier of the user who is the current speaker.\n * @property { string } sessionUUID - The unique identifier of the session the speaker is in.\n * @property { string } username - The username of the current speaker.\n * @property { number } startTime - The timestamp when the current speaker started speaking.\n */\ninterface CurrentSpeakerState {\n userId: string;\n sessionUUID: string;\n username: string;\n startTime: number;\n}\n\n/**\n * Enum representing space activity options.\n *\n * @enum {string}\n * @readonly\n * @property {string} HOSTING - Indicates that the space is being used for hosting an event.\n * @property {string} PARTICIPATING - Indicates that the space is being used for participating in an event.\n * @property {string} IDLE - Indicates that the space is not currently being used.\n */\nexport enum SpaceActivity {\n HOSTING = \"hosting\",\n PARTICIPATING = \"participating\",\n IDLE = \"idle\",\n}\n\n/**\n * An enum representing the activity role of a participant.\n * @enum {string}\n * @readonly\n * @property {string} LISTENER - Represents a participant who is a listener.\n * @property {string} SPEAKER - Represents a participant who is a speaker.\n * @property {string} PENDING - Represents a participant whose activity is pending.\n */\nexport enum ParticipantActivity {\n LISTENER = \"listener\",\n SPEAKER = \"speaker\",\n PENDING = \"pending\",\n}\n\n/**\n * Main class: manage a Twitter Space with N speakers max, speaker queue, filler messages, etc.\n */\n/**\n * Represents a client for interacting with Twitter Spaces.\n * * @class\n * @property { IAgentRuntime } runtime - The agent runtime for the client.\n * @property { ClientBase } client - The base client for making requests.\n * @property { Client } twitterClient - The Twitter client for interacting with Twitter API.\n * @property {Space | undefined} currentSpace - The current Twitter Space the client is connected to (if any).\n * @property {string | undefined} spaceId - The ID of the Twitter Space the client is connected to (if any).\n * @property {number | undefined} startedAt - The timestamp when the client was started.\n * @property {NodeJS.Timeout | undefined} checkInterval - The interval for checking the status of the Twitter Space.\n * @property {number | undefined} lastSpaceEndedAt - The timestamp of when the last Twitter Space ended.\n */\nexport class TwitterSpaceClient {\n private runtime: IAgentRuntime;\n private client: ClientBase;\n private twitterClient: Client;\n private currentSpace?: Space;\n private spaceId?: string;\n private startedAt?: number;\n private checkInterval?: NodeJS.Timeout;\n private lastSpaceEndedAt?: number;\n private sttTtsPlugin?: SttTtsPlugin;\n public spaceStatus: SpaceActivity = SpaceActivity.IDLE;\n private spaceParticipant: SpaceParticipant | null = null;\n public participantStatus: ParticipantActivity = ParticipantActivity.LISTENER;\n\n /**\n * We now store an array of active speakers, not just 1\n */\n private activeSpeakers: CurrentSpeakerState[] = [];\n private speakerQueue: SpeakerRequest[] = [];\n\n private decisionOptions: TwitterSpaceDecisionOptions;\n\n constructor(client: ClientBase, runtime: IAgentRuntime) {\n this.client = client;\n this.twitterClient = client.twitterClient;\n this.runtime = runtime;\n\n this.sttTtsPlugin = new SttTtsPlugin();\n\n // TODO: Spaces should be added to and removed from cache probably, and it should be possible to join or leave a space from an action, etc\n const charSpaces = runtime.character.settings?.twitter?.spaces || {};\n this.decisionOptions = {\n maxSpeakers: charSpaces.maxSpeakers ?? 1,\n typicalDurationMinutes: charSpaces.typicalDurationMinutes ?? 30,\n idleKickTimeoutMs: charSpaces.idleKickTimeoutMs ?? 5 * 60_000,\n minIntervalBetweenSpacesMinutes:\n charSpaces.minIntervalBetweenSpacesMinutes ?? 60,\n enableIdleMonitor: charSpaces.enableIdleMonitor !== false,\n enableRecording: charSpaces.enableRecording !== false,\n enableSpaceHosting: charSpaces.enableSpaceHosting || false,\n speakerMaxDurationMs: charSpaces.speakerMaxDurationMs ?? 4 * 60_000,\n };\n }\n\n /**\n * Periodic check to launch or manage space\n */\n public async startPeriodicSpaceCheck() {\n logger.log(\"[Space] Starting periodic check routine...\");\n\n const interval = 20_000;\n\n const routine = async () => {\n try {\n if (this.spaceStatus === SpaceActivity.IDLE) {\n if (this.decisionOptions.enableSpaceHosting) {\n // Space not running => check if we should launch\n const launch = await this.shouldLaunchSpace();\n if (launch) {\n const config = await this.generateSpaceConfig();\n await this.startSpace(config);\n }\n }\n } else {\n if (this.spaceStatus === SpaceActivity.HOSTING) {\n await this.manageCurrentSpace();\n } else if (this.spaceStatus === SpaceActivity.PARTICIPATING) {\n await this.manageParticipant();\n }\n }\n this.checkInterval = setTimeout(routine, interval) as any;\n } catch (error) {\n logger.error(\"[Space] Error in routine =>\", error);\n // In case of error, still schedule next iteration\n this.checkInterval = setTimeout(routine, interval) as any;\n }\n };\n\n routine();\n }\n\n stopPeriodicCheck() {\n if (this.checkInterval) {\n clearTimeout(this.checkInterval);\n this.checkInterval = undefined;\n }\n }\n\n private async shouldLaunchSpace(): Promise<boolean> {\n // Interval\n const now = Date.now();\n if (this.lastSpaceEndedAt) {\n const minIntervalMs =\n (this.decisionOptions.minIntervalBetweenSpacesMinutes ?? 60) * 60_000;\n if (now - this.lastSpaceEndedAt < minIntervalMs) {\n logger.log(\"[Space] Too soon since last space => skip\");\n return false;\n }\n }\n\n logger.log(\"[Space] Deciding to launch a new Space...\");\n return true;\n }\n\n private async generateSpaceConfig(): Promise<SpaceConfig> {\n let chosenTopic = \"Random Tech Chat\";\n let topics = this.runtime.character.topics || [];\n if (!topics.length) {\n const newTopics = await generateTopicsIfEmpty(this.client.runtime);\n topics = newTopics;\n }\n\n chosenTopic = topics[Math.floor(Math.random() * topics.length)];\n\n return {\n record: this.decisionOptions.enableRecording,\n mode: \"INTERACTIVE\",\n title: chosenTopic,\n description: `Discussion about ${chosenTopic}`,\n languages: [\"en\"],\n };\n }\n\n public async startSpace(config: SpaceConfig) {\n logger.log(\"[Space] Starting a new Twitter Space...\");\n\n try {\n this.currentSpace = new Space(this.twitterClient);\n this.spaceStatus = SpaceActivity.IDLE;\n this.spaceId = undefined;\n this.startedAt = Date.now();\n\n // Reset states\n this.activeSpeakers = [];\n this.speakerQueue = [];\n\n const broadcastInfo = await this.currentSpace.initialize(config);\n this.spaceId = broadcastInfo.room_id;\n\n // Create standardized world and room IDs for the space\n const userId = this.client.profile.id;\n const worldId = createUniqueUuid(this.runtime, userId);\n const spaceRoomId = createUniqueUuid(\n this.runtime,\n `${userId}-space-${this.spaceId}`\n );\n\n // Ensure world exists first\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${this.client.profile.username}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: userId,\n metadata: {\n ownership: { ownerId: userId },\n twitter: {\n username: this.client.profile.username,\n id: userId,\n },\n spaceInfo: {\n title: config.title,\n description: config.description,\n startedAt: Date.now(),\n mode: config.mode,\n languages: config.languages,\n isRecording: config.record,\n },\n },\n });\n\n if (\n this.runtime.getModel(ModelType.TEXT_TO_SPEECH) &&\n this.runtime.getModel(ModelType.TRANSCRIPTION)\n ) {\n logger.log(\"[Space] Using SttTtsPlugin\");\n this.currentSpace.use(this.sttTtsPlugin as any, {\n runtime: this.runtime,\n spaceId: this.spaceId,\n });\n }\n\n if (this.decisionOptions.enableIdleMonitor) {\n logger.log(\"[Space] Using IdleMonitorPlugin\");\n this.currentSpace.use(\n new IdleMonitorPlugin(\n this.decisionOptions.idleKickTimeoutMs ?? 60_000,\n 10_000\n )\n );\n }\n this.spaceStatus = SpaceActivity.HOSTING;\n\n // Create tweet announcing the space\n const spaceUrl = broadcastInfo.share_url.replace(\"broadcasts\", \"spaces\");\n await this.twitterClient.sendTweet(spaceUrl);\n\n logger.log(`[Space] Space started => ${spaceUrl}`);\n\n // Greet\n await speakFiller(this.client.runtime, this.sttTtsPlugin, \"WELCOME\");\n\n // Events\n this.currentSpace.on(\"occupancyUpdate\", (update) => {\n logger.log(`[Space] Occupancy => ${update.occupancy} participant(s).`);\n });\n\n this.currentSpace.on(\"speakerRequest\", async (req: SpeakerRequest) => {\n logger.log(\n `[Space] Speaker request from @${req.username} (${req.userId}).`\n );\n await this.handleSpeakerRequest(req);\n });\n\n this.currentSpace.on(\"idleTimeout\", async (info) => {\n logger.log(`[Space] idleTimeout => no audio for ${info.idleMs} ms.`);\n await speakFiller(\n this.client.runtime,\n this.sttTtsPlugin,\n \"IDLE_ENDING\"\n );\n await this.stopSpace();\n });\n\n process.on(\"SIGINT\", async () => {\n logger.log(\"[Space] SIGINT => stopping space\");\n await speakFiller(this.client.runtime, this.sttTtsPlugin, \"CLOSING\");\n await this.stopSpace();\n process.exit(0);\n });\n } catch (error) {\n logger.error(\"[Space] Error launching Space =>\", error);\n this.spaceStatus = SpaceActivity.IDLE;\n throw error;\n }\n }\n\n /**\n * Periodic management: check durations, remove extras, maybe accept new from queue\n */\n private async manageCurrentSpace() {\n if (!this.spaceId || !this.currentSpace) return;\n try {\n const audioSpace = await this.twitterClient.getAudioSpaceById(\n this.spaceId\n );\n const { participants } = audioSpace;\n const numSpeakers = participants.speakers?.length || 0;\n const totalListeners = participants.listeners?.length || 0;\n\n // 1) Remove any speaker who exceeded speakerMaxDurationMs\n const maxDur = this.decisionOptions.speakerMaxDurationMs ?? 240_000;\n const now = Date.now();\n\n for (let i = this.activeSpeakers.length - 1; i >= 0; i--) {\n const speaker = this.activeSpeakers[i];\n const elapsed = now - speaker.startTime;\n if (elapsed > maxDur) {\n logger.log(\n `[Space] Speaker @${speaker.username} exceeded max duration => removing`\n );\n await this.removeSpeaker(speaker.userId);\n this.activeSpeakers.splice(i, 1);\n\n // Possibly speak a short \"SPEAKER_LEFT\" filler\n await speakFiller(\n this.client.runtime,\n this.sttTtsPlugin,\n \"SPEAKER_LEFT\"\n );\n }\n }\n\n // 2) If we have capacity for new speakers from the queue, accept them\n await this.acceptSpeakersFromQueueIfNeeded();\n\n // 3) If somehow more than maxSpeakers are active, remove the extras\n if (numSpeakers > (this.decisionOptions.maxSpeakers ?? 1)) {\n logger.log(\"[Space] More than maxSpeakers => removing extras...\");\n await this.kickExtraSpeakers(participants.speakers);\n }\n\n // 4) Possibly stop the space if empty or time exceeded\n const elapsedMinutes = (now - (this.startedAt || 0)) / 60000;\n if (\n elapsedMinutes > (this.decisionOptions.typicalDurationMinutes ?? 30) ||\n (numSpeakers === 0 && totalListeners === 0 && elapsedMinutes > 5)\n ) {\n logger.log(\"[Space] Condition met => stopping the Space...\");\n await speakFiller(\n this.client.runtime,\n this.sttTtsPlugin,\n \"CLOSING\",\n 4000\n );\n await this.stopSpace();\n }\n } catch (error) {\n logger.error(\"[Space] Error in manageCurrentSpace =>\", error);\n }\n }\n\n /**\n * If we have available slots, accept new speakers from the queue\n */\n private async acceptSpeakersFromQueueIfNeeded() {\n // while queue not empty and activeSpeakers < maxSpeakers, accept next\n const ms = this.decisionOptions.maxSpeakers ?? 1;\n while (this.speakerQueue.length > 0 && this.activeSpeakers.length < ms) {\n const nextReq = this.speakerQueue.shift();\n if (nextReq) {\n await speakFiller(this.client.runtime, this.sttTtsPlugin, \"PRE_ACCEPT\");\n await this.acceptSpeaker(nextReq);\n }\n }\n }\n\n private async handleSpeakerRequest(req: SpeakerRequest) {\n if (!this.spaceId || !this.currentSpace) return;\n\n const audioSpace = await this.twitterClient.getAudioSpaceById(this.spaceId);\n const janusSpeakers = audioSpace?.participants?.speakers || [];\n\n // If we haven't reached maxSpeakers, accept immediately\n if (janusSpeakers.length < (this.decisionOptions.maxSpeakers ?? 1)) {\n logger.log(`[Space] Accepting speaker @${req.username} now`);\n await speakFiller(this.client.runtime, this.sttTtsPlugin, \"PRE_ACCEPT\");\n await this.acceptSpeaker(req);\n } else {\n logger.log(`[Space] Adding speaker @${req.username} to the queue`);\n this.speakerQueue.push(req);\n }\n }\n\n private async acceptSpeaker(req: SpeakerRequest) {\n if (!this.currentSpace) return;\n try {\n await this.currentSpace.approveSpeaker(req.userId, req.sessionUUID);\n this.activeSpeakers.push({\n userId: req.userId,\n sessionUUID: req.sessionUUID,\n username: req.username,\n startTime: Date.now(),\n });\n logger.log(`[Space] Speaker @${req.username} is now live`);\n } catch (err) {\n logger.error(`[Space] Error approving speaker @${req.username}:`, err);\n }\n }\n\n private async removeSpeaker(userId: string) {\n if (!this.currentSpace) return;\n try {\n await this.currentSpace.removeSpeaker(userId);\n logger.log(`[Space] Removed speaker userId=${userId}`);\n } catch (error) {\n logger.error(`[Space] Error removing speaker userId=${userId} =>`, error);\n }\n }\n\n /**\n * If more than maxSpeakers are found, remove extras\n * Also update activeSpeakers array\n */\n private async kickExtraSpeakers(speakers: any[]) {\n if (!this.currentSpace) return;\n const ms = this.decisionOptions.maxSpeakers ?? 1;\n\n // sort by who joined first if needed, or just slice\n const extras = speakers.slice(ms);\n for (const sp of extras) {\n logger.log(`[Space] Removing extra speaker => userId=${sp.user_id}`);\n await this.removeSpeaker(sp.user_id);\n\n // remove from activeSpeakers array\n const idx = this.activeSpeakers.findIndex((s) => s.userId === sp.user_id);\n if (idx !== -1) {\n this.activeSpeakers.splice(idx, 1);\n }\n }\n }\n\n public async stopSpace() {\n if (!this.currentSpace || this.spaceStatus !== SpaceActivity.HOSTING)\n return;\n try {\n logger.log(\"[Space] Stopping the current Space...\");\n await this.currentSpace.stop();\n } catch (err) {\n logger.error(\"[Space] Error stopping Space =>\", err);\n } finally {\n this.spaceStatus = SpaceActivity.IDLE;\n this.spaceId = undefined;\n this.currentSpace = undefined;\n this.startedAt = undefined;\n this.lastSpaceEndedAt = Date.now();\n this.activeSpeakers = [];\n this.speakerQueue = [];\n }\n }\n\n async startParticipant(spaceId: string) {\n if (this.spaceStatus !== SpaceActivity.IDLE) {\n logger.warn(\"currently hosting/participating a space\");\n return null;\n }\n\n this.spaceParticipant = new SpaceParticipant(this.client.twitterClient, {\n spaceId,\n debug: false,\n });\n\n if (this.spaceParticipant) {\n try {\n await this.spaceParticipant.joinAsListener();\n\n this.spaceId = spaceId;\n this.spaceStatus = SpaceActivity.PARTICIPATING;\n\n return spaceId;\n } catch (error) {\n logger.error(`failed to join space ${error}`);\n return null;\n }\n }\n }\n\n async manageParticipant() {\n if (!this.spaceParticipant || !this.spaceId) {\n this.stopParticipant();\n return;\n }\n\n const isParticipant = await isAgentInSpace(this.client, this.spaceId);\n\n if (!isParticipant) {\n this.stopParticipant();\n return;\n }\n\n // Check if we should request to speak\n if (this.participantStatus === ParticipantActivity.LISTENER) {\n logger.log(\n \"[SpaceParticipant] Checking if we should request to speak...\"\n );\n\n this.participantStatus = ParticipantActivity.PENDING;\n\n const { sessionUUID } = await this.spaceParticipant.requestSpeaker();\n\n const handleSpeakerRemove = async (evt: { sessionUUID: string }) => {\n if (evt.sessionUUID === sessionUUID) {\n logger.debug(\"[SpaceParticipant] Speaker removed:\", evt);\n try {\n await this.spaceParticipant.removeFromSpeaker();\n } catch (err) {\n console.error(\"[SpaceParticipant] Failed to become speaker:\", err);\n }\n this.participantStatus = ParticipantActivity.LISTENER;\n this.spaceParticipant?.off(\"newSpeakerRemoved\", handleSpeakerRemove);\n }\n };\n\n // Attach listener for speaker removal\n this.spaceParticipant.on(\"newSpeakerRemoved\", handleSpeakerRemove);\n\n this.waitForApproval(this.spaceParticipant, sessionUUID, 15000)\n .then(() => {\n this.participantStatus = ParticipantActivity.SPEAKER;\n this.spaceParticipant.use(this.sttTtsPlugin as any, {\n runtime: this.runtime,\n spaceId: this.spaceId,\n });\n })\n .catch(async (err) => {\n console.error(\"[SpaceParticipant] Approval error or timeout =>\", err);\n\n this.participantStatus = ParticipantActivity.LISTENER;\n\n try {\n await this.spaceParticipant.cancelSpeakerRequest();\n logger.debug(\n \"[SpaceParticipant] Speaker request canceled after timeout or error.\"\n );\n } catch (cancelErr) {\n console.error(\n \"[SpaceParticipant] Could not cancel the request =>\",\n cancelErr\n );\n }\n });\n }\n }\n\n public async stopParticipant() {\n if (\n !this.spaceParticipant ||\n this.spaceStatus !== SpaceActivity.PARTICIPATING\n )\n return;\n try {\n logger.log(\n \"[SpaceParticipant] Stopping the current space participant...\"\n );\n await this.spaceParticipant.leaveSpace();\n } catch (err) {\n logger.error(\n \"[SpaceParticipant] Error stopping space participant =>\",\n err\n );\n } finally {\n this.spaceStatus = SpaceActivity.IDLE;\n this.participantStatus = ParticipantActivity.LISTENER;\n this.spaceId = undefined;\n this.spaceParticipant = undefined;\n }\n }\n\n /**\n * waitForApproval waits until \"newSpeakerAccepted\" matches our sessionUUID,\n * then calls becomeSpeaker() or rejects after a given timeout.\n */\n async waitForApproval(\n participant: SpaceParticipant,\n sessionUUID: string,\n timeoutMs = 10000\n ): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let resolved = false;\n\n const handler = async (evt: { sessionUUID: string }) => {\n if (evt.sessionUUID === sessionUUID) {\n resolved = true;\n participant.off(\"newSpeakerAccepted\", handler);\n try {\n await participant.becomeSpeaker();\n logger.debug(\"[SpaceParticipant] Successfully became speaker!\");\n resolve();\n } catch (err) {\n reject(err);\n }\n }\n };\n\n // Listen to \"newSpeakerAccepted\" from participant\n participant.on(\"newSpeakerAccepted\", handler);\n\n // Timeout to reject if not approved in time\n setTimeout(() => {\n if (!resolved) {\n participant.off(\"newSpeakerAccepted\", handler);\n reject(\n new Error(\n `[SpaceParticipant] Timed out waiting for speaker approval after ${timeoutMs}ms.`\n )\n );\n }\n }, timeoutMs);\n });\n }\n}\n","import { Headers } from \"headers-polyfill\";\nimport type { TwitterAuth } from \"./auth\";\nimport { ApiError } from \"./errors\";\nimport { Platform, type PlatformExtensions } from \"./platform\";\nimport { updateCookieJar } from \"./requests\";\n\n// For some reason using Parameters<typeof fetch> reduces the request transform function to\n// `(url: string) => string` in tests.\n/**\n * Represents an array type for parameters used in the fetch function,\n * with the first element being input of type RequestInfo or URL,\n * and the second element being init of type RequestInit or optional if not provided.\n */\ntype FetchParameters = [input: RequestInfo | URL, init?: RequestInit];\n\n/**\n * @typedef {Object} FetchTransformOptions\n * @property {Function} request Transforms the request options before a request is made. This executes after all of the default\n * parameters have been configured, and is stateless. It is safe to return new request options\n * objects.\n * @param {FetchParameters} args The request options.\n * @returns {FetchParameters|Promise<FetchParameters>} The transformed request options.\n *\n * @property {Function} response Transforms the response after a request completes. This executes immediately after the request\n * completes, and is stateless. It is safe to return a new response object.\n * @param {Response} response The response object.\n * @returns {Response|Promise<Response>} The transformed response object.\n */\n\nexport interface FetchTransformOptions {\n /**\n * Transforms the request options before a request is made. This executes after all of the default\n * parameters have been configured, and is stateless. It is safe to return new request options\n * objects.\n * @param args The request options.\n * @returns The transformed request options.\n */\n request: (\n ...args: FetchParameters\n ) => FetchParameters | Promise<FetchParameters>;\n\n /**\n * Transforms the response after a request completes. This executes immediately after the request\n * completes, and is stateless. It is safe to return a new response object.\n * @param response The response object.\n * @returns The transformed response object.\n */\n response: (response: Response) => Response | Promise<Response>;\n}\n\nexport const bearerToken =\n \"AAAAAAAAAAAAAAAAAAAAAFQODgEAAAAAVHTp76lzh3rFzcHbmHVvQxYYpTw%3DckAlMINMjmCwxUcaXbAN4XqJVdgMJaHqNOFgPMK0zN1qLqLQCF\";\n\n/**\n * An API result container.\n */\nexport type RequestApiResult<T> =\n | { success: true; value: T }\n | { success: false; err: Error };\n\n/**\n * Used internally to send HTTP requests to the Twitter API.\n * @internal\n * @param url - The URL to send the request to.\n * @param auth - The instance of {@link TwitterAuth} that will be used to authorize this request.\n * @param method - The HTTP method used when sending this request.\n */\nexport async function requestApi<T>(\n url: string,\n auth: TwitterAuth,\n method: \"GET\" | \"POST\" = \"GET\",\n platform: PlatformExtensions = new Platform(),\n body?: any\n): Promise<RequestApiResult<T>> {\n const headers = new Headers();\n await auth.installTo(headers, url);\n await platform.randomizeCiphers();\n\n let res: Response;\n do {\n try {\n res = await auth.fetch(url, {\n method,\n headers: headers as any,\n credentials: \"include\",\n ...(body && { body: JSON.stringify(body) }),\n });\n } catch (err) {\n if (!(err instanceof Error)) {\n throw err;\n }\n return {\n success: false,\n err: new Error(\"Failed to perform request.\"),\n };\n }\n\n await updateCookieJar(auth.cookieJar(), res.headers);\n\n if (res.status === 429) {\n /*\n Known headers at this point:\n - x-rate-limit-limit: Maximum number of requests per time period?\n - x-rate-limit-reset: UNIX timestamp when the current rate limit will be reset.\n - x-rate-limit-remaining: Number of requests remaining in current time period?\n */\n const xRateLimitRemaining = res.headers.get(\"x-rate-limit-remaining\");\n const xRateLimitReset = res.headers.get(\"x-rate-limit-reset\");\n if (xRateLimitRemaining === \"0\" && xRateLimitReset) {\n const currentTime = new Date().valueOf() / 1000;\n const timeDeltaMs =\n 1000 * (Number.parseInt(xRateLimitReset) - currentTime);\n\n // I have seen this block for 800s (~13 *minutes*)\n await new Promise((resolve) => setTimeout(resolve, timeDeltaMs));\n }\n }\n } while (res.status === 429);\n\n if (!res.ok) {\n return {\n success: false,\n err: await ApiError.fromResponse(res),\n };\n }\n\n // Check if response is chunked\n const transferEncoding = res.headers.get(\"transfer-encoding\");\n if (transferEncoding === \"chunked\") {\n // Handle streaming response, if a reader is present\n const reader =\n typeof res.body?.getReader === \"function\" ? res.body.getReader() : null;\n if (!reader) {\n try {\n const text = await res.text();\n try {\n const value = JSON.parse(text);\n return { success: true, value };\n } catch (_e) {\n // Return if just a normal string\n return { success: true, value: { text } as any };\n }\n } catch (_e) {\n return {\n success: false,\n err: new Error(\"No readable stream available and cant parse\"),\n };\n }\n }\n\n let chunks: any = \"\";\n // Read all chunks before attempting to parse\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n // Convert chunk to text and append\n chunks += new TextDecoder().decode(value);\n }\n\n // Now try to parse the complete accumulated response\n try {\n const value = JSON.parse(chunks);\n return { success: true, value };\n } catch (_e) {\n // If we can't parse as JSON, return the raw text\n return { success: true, value: { text: chunks } as any };\n }\n }\n\n // Handle non-streaming responses as before\n const contentType = res.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n const value: T = await res.json();\n if (res.headers.get(\"x-rate-limit-incoming\") === \"0\") {\n auth.deleteToken();\n }\n return { success: true, value };\n }\n\n return { success: true, value: {} as T };\n}\n\n/** @internal */\nexport function addApiFeatures(o: object) {\n return {\n ...o,\n rweb_lists_timeline_redesign_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n tweetypie_unmention_optimization_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n longform_notetweets_rich_text_read_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n subscriptions_verification_info_enabled: true,\n subscriptions_verification_info_reason_enabled: true,\n subscriptions_verification_info_verified_since_enabled: true,\n super_follow_badge_privacy_enabled: false,\n super_follow_exclusive_tweet_notifications_enabled: false,\n super_follow_tweet_api_enabled: false,\n super_follow_user_api_enabled: false,\n android_graphql_skip_api_media_color_palette: false,\n creator_subscriptions_subscription_count_enabled: false,\n blue_business_profile_image_shape_enabled: false,\n unified_cards_ad_metadata_container_dynamic_card_content_query_enabled:\n false,\n };\n}\n\nexport function addApiParams(\n params: URLSearchParams,\n includeTweetReplies: boolean\n): URLSearchParams {\n params.set(\"include_profile_interstitial_type\", \"1\");\n params.set(\"include_blocking\", \"1\");\n params.set(\"include_blocked_by\", \"1\");\n params.set(\"include_followed_by\", \"1\");\n params.set(\"include_want_retweets\", \"1\");\n params.set(\"include_mute_edge\", \"1\");\n params.set(\"include_can_dm\", \"1\");\n params.set(\"include_can_media_tag\", \"1\");\n params.set(\"include_ext_has_nft_avatar\", \"1\");\n params.set(\"include_ext_is_blue_verified\", \"1\");\n params.set(\"include_ext_verified_type\", \"1\");\n params.set(\"skip_status\", \"1\");\n params.set(\"cards_platform\", \"Web-12\");\n params.set(\"include_cards\", \"1\");\n params.set(\"include_ext_alt_text\", \"true\");\n params.set(\"include_ext_limited_action_results\", \"false\");\n params.set(\"include_quote_count\", \"true\");\n params.set(\"include_reply_count\", \"1\");\n params.set(\"tweet_mode\", \"extended\");\n params.set(\"include_ext_collab_control\", \"true\");\n params.set(\"include_ext_views\", \"true\");\n params.set(\"include_entities\", \"true\");\n params.set(\"include_user_entities\", \"true\");\n params.set(\"include_ext_media_color\", \"true\");\n params.set(\"include_ext_media_availability\", \"true\");\n params.set(\"include_ext_sensitive_media_warning\", \"true\");\n params.set(\"include_ext_trusted_friends_metadata\", \"true\");\n params.set(\"send_error_codes\", \"true\");\n params.set(\"simple_quoted_tweet\", \"true\");\n params.set(\"include_tweet_replies\", `${includeTweetReplies}`);\n params.set(\n \"ext\",\n \"mediaStats,highlightedLabel,hasNftAvatar,voiceInfo,birdwatchPivot,enrichments,superFollowMetadata,unmentionInfo,editControl,collab_control,vibe\"\n );\n return params;\n}\n","/**\n * Class representing an API error.\n */\n\nexport class ApiError extends Error {\n /**\n * Constructor for creating a new instance of the class.\n *\n * @param response The response object.\n * @param data The data object.\n * @param message The message string.\n */\n private constructor(\n readonly response: Response,\n readonly data: any,\n message: string\n ) {\n super(message);\n }\n\n /**\n * Creates an instance of ApiError based on a Response object.\n *\n * @param {Response} response The Response object to parse.\n * @returns {Promise<ApiError>} A new instance of ApiError with the parsed data and status.\n */\n static async fromResponse(response: Response) {\n // Try our best to parse the result, but don't bother if we can't\n let data: string | object | undefined = undefined;\n try {\n data = await response.json();\n } catch {\n try {\n data = await response.text();\n } catch {}\n }\n\n return new ApiError(response, data, `Response status: ${response.status}`);\n }\n}\n\n/**\n * Represents a position in a file with line and column information.\n * @interface Position\n * @property {number} line - The line number of the position.\n * @property {number} column - The column number of the position.\n */\ninterface Position {\n line: number;\n column: number;\n}\n\n/**\n * Interface representing trace information.\n * @property { string } trace_id - The ID of the trace.\n */\ninterface TraceInfo {\n trace_id: string;\n}\n\n/**\n * Interface representing additional information that can be included in Twitter API error objects.\n * @typedef { Object } TwitterApiErrorExtensions\n * @property { number } [code] - The error code associated with the error.\n * @property { string } [kind] - The kind of error that occurred.\n * @property { string } [name] - The name of the error.\n * @property { string } [source] - The source of the error.\n * @property { TraceInfo } [tracing] - Information about the tracing of the error.\n */\ninterface TwitterApiErrorExtensions {\n code?: number;\n kind?: string;\n name?: string;\n source?: string;\n tracing?: TraceInfo;\n}\n\n/**\n * Interface representing a raw Twitter API error object.\n * @interface\n * @extends {TwitterApiErrorExtensions}\n * @property {string} [message] The error message.\n * @property {Position[]} [locations] An array of positions.\n * @property {string[]} [path] An array representing the path of the error.\n * @property {TwitterApiErrorExtensions} [extensions] Additional error extensions.\n */\nexport interface TwitterApiErrorRaw extends TwitterApiErrorExtensions {\n message?: string;\n locations?: Position[];\n path?: string[];\n extensions?: TwitterApiErrorExtensions;\n}\n","/**\n * Randomizes the runtime's TLS ciphers to bypass TLS client fingerprinting, which\n * hopefully avoids random 404s on some requests.\n *\n * **References:**\n * - https://github.com/imputnet/cobalt/pull/574\n */\nexport interface PlatformExtensions {\n /**\n * Randomizes the runtime's TLS ciphers to bypass TLS client fingerprinting, which\n * hopefully avoids random 404s on some requests.\n *\n * **References:**\n * - https://github.com/imputnet/cobalt/pull/574\n */\n randomizeCiphers(): Promise<void>;\n}\n\nexport const genericPlatform = new (class implements PlatformExtensions {\n randomizeCiphers(): Promise<void> {\n return Promise.resolve();\n }\n})();\n","import { type PlatformExtensions, genericPlatform } from './platform-interface.js';\n\nexport * from './platform-interface.js';\n\nconst PLATFORM_NODE: boolean = typeof process !== 'undefined';\n\n/**\n * Class representing a platform with cipher randomization functionality.\n */\nexport class Platform implements PlatformExtensions {\n /**\n * Asynchronously generates random ciphers using the imported platform\n */\n async randomizeCiphers() {\n const platform = await Platform.importPlatform();\n await platform?.randomizeCiphers();\n }\n\n /**\n * Imports and returns the platform extensions based on the current platform.\n * @returns A Promise that resolves to the platform extensions, or null if the platform is not supported.\n */\n private static async importPlatform(): Promise<null | PlatformExtensions> {\n if (PLATFORM_NODE) {\n const { platform } = await import('./node/index.js');\n return platform as PlatformExtensions;\n }\n\n return genericPlatform;\n }\n}\n","import type { Headers as HeadersPolyfill } from \"headers-polyfill\";\nimport setCookie from \"set-cookie-parser\";\nimport { Cookie, type CookieJar } from \"tough-cookie\";\n\n/**\n * Updates a cookie jar with the Set-Cookie headers from the provided Headers instance.\n * @param cookieJar The cookie jar to update.\n * @param headers The response headers to populate the cookie jar with.\n */\n/**\n * Updates the provided CookieJar with cookies from the given Headers or document.cookie.\n * @param {CookieJar} cookieJar - The CookieJar to update.\n * @param {Headers | HeadersPolyfill} headers - The Headers object containing cookie information.\n * @returns {Promise<void>} - A Promise that resolves once the update is complete.\n */\nexport async function updateCookieJar(\n cookieJar: CookieJar,\n headers: Headers | HeadersPolyfill\n) {\n const setCookieHeader = headers.get(\"set-cookie\");\n if (setCookieHeader) {\n const cookies = setCookie.splitCookiesString(setCookieHeader);\n for (const cookie of cookies.map((c) => Cookie.parse(c))) {\n if (!cookie) continue;\n await cookieJar.setCookie(\n cookie,\n `${cookie.secure ? \"https\" : \"http\"}://${cookie.domain}${cookie.path}`\n );\n }\n } else if (typeof document !== \"undefined\") {\n for (const cookie of document.cookie.split(\";\")) {\n const hardCookie = Cookie.parse(cookie);\n if (hardCookie) {\n await cookieJar.setCookie(hardCookie, document.location.toString());\n }\n }\n }\n}\n","import { Headers } from 'headers-polyfill';\nimport { type Cookie, CookieJar } from 'tough-cookie';\nimport { TwitterApi } from 'twitter-api-v2';\nimport type { FetchTransformOptions } from './api';\nimport { getTwitterApiHeaders } from './browser-fingerprint';\nimport { Profile } from './profile';\nimport { updateCookieJar } from './requests';\n\n/**\n * Represents the TwitterAuthOptions interface that defines the properties required for Twitter authentication.\n * @property {typeof fetch} fetch - The fetch function to use for making HTTP requests.\n * @property {Partial<FetchTransformOptions>} transform - The partial options for transforming fetch requests.\n */\nexport interface TwitterAuthOptions {\n fetch: typeof fetch;\n transform: Partial<FetchTransformOptions>;\n}\n\n/**\n * Interface for Twitter authentication functionality.\n * @interface\n */\n\nexport interface TwitterAuth {\n fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\n /**\n * Returns the current cookie jar.\n */\n cookieJar(): CookieJar;\n\n /**\n * Logs into a Twitter account using the v2 API\n */\n loginWithV2(appKey: string, appSecret: string, accessToken: string, accessSecret: string): void;\n\n /**\n * Get v2 API client if it exists\n */\n getV2Client(): TwitterApi | null;\n\n /**\n * Returns if a user is logged-in to Twitter through this instance.\n * @returns `true` if a user is logged-in; otherwise `false`.\n */\n isLoggedIn(): Promise<boolean>;\n\n /**\n * Fetches the current user's profile.\n */\n me(): Promise<Profile | undefined>;\n\n /**\n * Logs into a Twitter account.\n * @param username The username to log in with.\n * @param password The password to log in with.\n * @param email The email to log in with, if you have email confirmation enabled.\n * @param twoFactorSecret The secret to generate two factor authentication tokens with, if you have two factor authentication enabled.\n */\n login(\n username: string,\n password: string,\n email?: string,\n twoFactorSecret?: string\n ): Promise<void>;\n\n /**\n * Logs out of the current session.\n */\n logout(): Promise<void>;\n\n /**\n * Deletes the current guest token token.\n */\n deleteToken(): void;\n\n /**\n * Returns if the authentication state has a token.\n * @returns `true` if the authentication state has a token; `false` otherwise.\n */\n hasToken(): boolean;\n\n /**\n * Returns the time that authentication was performed.\n * @returns The time at which the authentication token was created, or `null` if it hasn't been created yet.\n */\n authenticatedAt(): Date | null;\n\n /**\n * Installs the authentication information into a headers-like object. If needed, the\n * authentication token will be updated from the API automatically.\n * @param headers A Headers instance representing a request's headers.\n */\n installTo(headers: Headers, url: string): Promise<void>;\n}\n\n/**\n * Wraps the provided fetch function with transforms.\n * @param fetchFn The fetch function.\n * @param transform The transform options.\n * @returns The input fetch function, wrapped with the provided transforms.\n */\nfunction withTransform(\n fetchFn: typeof fetch,\n transform?: Partial<FetchTransformOptions>\n): (input: RequestInfo | URL, init?: RequestInit | undefined) => Promise<Response> {\n return async (input, init) => {\n const fetchArgs = (await transform?.request?.(input, init)) ?? [input, init];\n const res = await fetchFn(...fetchArgs);\n return (await transform?.response?.(res)) ?? res;\n };\n}\n\n/**\n * A guest authentication token manager. Automatically handles token refreshes.\n */\nexport class TwitterGuestAuth implements TwitterAuth {\n protected bearerToken: string;\n protected jar: CookieJar;\n protected guestToken?: string;\n protected guestCreatedAt?: Date;\n protected v2Client: TwitterApi | null;\n\n fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\n constructor(\n bearerToken: string,\n protected readonly options?: Partial<TwitterAuthOptions>\n ) {\n this.fetch = withTransform(options?.fetch ?? fetch, options?.transform);\n this.bearerToken = bearerToken;\n this.jar = new CookieJar();\n this.v2Client = null;\n }\n\n cookieJar(): CookieJar {\n return this.jar;\n }\n\n getV2Client(): TwitterApi | null {\n return this.v2Client ?? null;\n }\n\n loginWithV2(appKey: string, appSecret: string, accessToken: string, accessSecret: string): void {\n const v2Client = new TwitterApi({\n appKey,\n appSecret,\n accessToken,\n accessSecret,\n });\n this.v2Client = v2Client;\n }\n\n isLoggedIn(): Promise<boolean> {\n return Promise.resolve(false);\n }\n\n async me(): Promise<Profile | undefined> {\n return undefined;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n login(_username: string, _password: string, _email?: string): Promise<void> {\n return this.updateGuestToken();\n }\n\n logout(): Promise<void> {\n this.deleteToken();\n this.jar = new CookieJar();\n return Promise.resolve();\n }\n\n deleteToken() {\n this.guestToken = undefined;\n this.guestCreatedAt = undefined;\n }\n\n hasToken(): boolean {\n return this.guestToken != null;\n }\n\n authenticatedAt(): Date | null {\n if (this.guestCreatedAt == null) {\n return null;\n }\n\n return new Date(this.guestCreatedAt);\n }\n\n async installTo(headers: Headers): Promise<void> {\n if (this.shouldUpdate()) {\n await this.updateGuestToken();\n }\n\n const token = this.guestToken;\n if (token == null) {\n throw new Error('Authentication token is null or undefined.');\n }\n\n headers.set('authorization', `Bearer ${this.bearerToken}`);\n headers.set('x-guest-token', token);\n\n const cookies = await this.getCookies();\n const xCsrfToken = cookies.find((cookie) => cookie.key === 'ct0');\n if (xCsrfToken) {\n headers.set('x-csrf-token', xCsrfToken.value);\n }\n\n headers.set('cookie', await this.getCookieString());\n }\n\n protected getCookies(): Promise<Cookie[]> {\n return this.jar.getCookies(this.getCookieJarUrl());\n }\n\n protected getCookieString(): Promise<string> {\n return this.jar.getCookieString(this.getCookieJarUrl());\n }\n\n protected async removeCookie(key: string): Promise<void> {\n const store = this.jar.store;\n const cookies = await this.jar.getCookies(this.getCookieJarUrl());\n for (const cookie of cookies) {\n if (!cookie.domain || !cookie.path) continue;\n store.removeCookie(cookie.domain, cookie.path, key);\n\n if (typeof document !== 'undefined') {\n document.cookie = `${cookie.key}=; Max-Age=0; path=${cookie.path}; domain=${cookie.domain}`;\n }\n }\n }\n\n private getCookieJarUrl(): string {\n return typeof document !== 'undefined' ? document.location.toString() : 'https://twitter.com';\n }\n\n /**\n * Updates the authentication state with a new guest token from the Twitter API.\n */\n protected async updateGuestToken() {\n const guestActivateUrl = 'https://api.twitter.com/1.1/guest/activate.json';\n\n const headers = new Headers({\n Authorization: `Bearer ${this.bearerToken}`,\n Cookie: await this.getCookieString(),\n });\n\n // Apply browser fingerprinting for better anti-detection\n const browserHeaders = await getTwitterApiHeaders();\n for (const [key, value] of browserHeaders.entries()) {\n if (\n !headers.has(key) &&\n key.toLowerCase() !== 'authorization' &&\n key.toLowerCase() !== 'cookie'\n ) {\n headers.set(key, value);\n }\n }\n\n const res = await this.fetch(guestActivateUrl, {\n method: 'POST',\n headers: headers as any,\n referrerPolicy: 'no-referrer',\n });\n\n await updateCookieJar(this.jar, res.headers);\n\n if (!res.ok) {\n throw new Error(await res.text());\n }\n\n const o = await res.json();\n if (o == null || o.guest_token == null) {\n throw new Error('guest_token not found.');\n }\n\n const newGuestToken = o.guest_token;\n if (typeof newGuestToken !== 'string') {\n throw new Error('guest_token was not a string.');\n }\n\n this.guestToken = newGuestToken;\n this.guestCreatedAt = new Date();\n }\n\n /**\n * Returns if the authentication token needs to be updated or not.\n * @returns `true` if the token needs to be updated; `false` otherwise.\n */\n private shouldUpdate(): boolean {\n return (\n !this.hasToken() ||\n (this.guestCreatedAt != null &&\n this.guestCreatedAt < new Date(new Date().valueOf() - 3 * 60 * 60 * 1000))\n );\n }\n}\n","/**\n * Advanced browser fingerprinting and anti-detection utilities for bypassing Cloudflare and other bot detection systems.\n * Implements sophisticated techniques including request timing, header ordering, and behavioral mimicry.\n */\nimport { Headers } from \"headers-polyfill\";\nimport crypto from \"crypto\";\n\nexport interface BrowserFingerprint {\n userAgent: string;\n acceptLanguage: string;\n acceptEncoding: string;\n accept: string;\n secFetchDest: string;\n secFetchMode: string;\n secFetchSite: string;\n secChUa: string;\n secChUaMobile: string;\n secChUaPlatform: string;\n dnt: string;\n upgradeInsecureRequests: string;\n cacheControl: string;\n pragma: string;\n connection: string;\n // New anti-detection fields\n viewportWidth: number;\n viewportHeight: number;\n timezone: string;\n cookieEnabled: boolean;\n doNotTrack: string;\n sessionId: string;\n requestDelay: number; // Milliseconds to delay before request\n}\n\nexport interface AntiDetectionConfig {\n enableRequestDelay: boolean;\n enableHeaderRandomization: boolean;\n enableJitter: boolean;\n maxDelayMs: number;\n minDelayMs: number;\n}\n\n/**\n * Modern Chrome User-Agents for different platforms\n */\nconst CHROME_USER_AGENTS = [\n // Windows Chrome\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\",\n \n // macOS Chrome\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\",\n \n // Linux Chrome\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36\",\n];\n\n/**\n * Firefox User-Agents for different platforms\n */\nconst FIREFOX_USER_AGENTS = [\n // Windows Firefox\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0\",\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0\",\n \"Mozilla/5.0 (Windows NT 11.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0\",\n \n // macOS Firefox\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:121.0) Gecko/20100101 Firefox/121.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:120.0) Gecko/20100101 Firefox/120.0\",\n \n // Linux Firefox\n \"Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0\",\n \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0\",\n];\n\n/**\n * Safari User-Agents\n */\nconst SAFARI_USER_AGENTS = [\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Safari/605.1.15\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 14_1) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15\",\n];\n\n/**\n * Mobile User-Agents (for occasional mobile requests)\n */\nconst MOBILE_USER_AGENTS = [\n // iPhone\n \"Mozilla/5.0 (iPhone; CPU iPhone OS 17_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Mobile/15E148 Safari/604.1\",\n \"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1\",\n \n // Android Chrome\n \"Mozilla/5.0 (Linux; Android 14; SM-G998B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36\",\n \"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Mobile Safari/537.36\",\n];\n\nconst ALL_USER_AGENTS = [\n ...CHROME_USER_AGENTS,\n ...FIREFOX_USER_AGENTS,\n ...SAFARI_USER_AGENTS,\n // Include mobile occasionally (10% chance)\n ...(Math.random() < 0.1 ? MOBILE_USER_AGENTS : []),\n];\n\n/**\n * Language preferences with realistic weights\n */\nconst ACCEPT_LANGUAGES = [\n \"en-US,en;q=0.9\",\n \"en-US,en;q=0.9,es;q=0.8\",\n \"en-US,en;q=0.9,fr;q=0.8\",\n \"en-GB,en;q=0.9\",\n \"en-US,en;q=0.9,de;q=0.8\",\n \"en,en-US;q=0.9\",\n \"en-US,en;q=0.8,es;q=0.7\",\n];\n\n/**\n * Get Sec-CH-UA header based on User-Agent\n */\nfunction getSecChUa(userAgent: string): string {\n if (userAgent.includes('Chrome/120')) {\n return '\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"';\n } else if (userAgent.includes('Chrome/119')) {\n return '\"Google Chrome\";v=\"119\", \"Chromium\";v=\"119\", \"Not?A_Brand\";v=\"24\"';\n } else if (userAgent.includes('Chrome/118')) {\n return '\"Chromium\";v=\"118\", \"Google Chrome\";v=\"118\", \"Not=A?Brand\";v=\"99\"';\n } else if (userAgent.includes('Firefox')) {\n return ''; // Firefox doesn't send sec-ch-ua\n } else if (userAgent.includes('Safari') && !userAgent.includes('Chrome')) {\n return ''; // Safari doesn't send sec-ch-ua\n }\n return '\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\"';\n}\n\n/**\n * Get Sec-CH-UA-Platform based on User-Agent\n */\nfunction getSecChUaPlatform(userAgent: string): string {\n if (userAgent.includes('Windows NT 10.0')) return '\"Windows\"';\n if (userAgent.includes('Windows NT 11.0')) return '\"Windows\"';\n if (userAgent.includes('Macintosh')) return '\"macOS\"';\n if (userAgent.includes('Linux')) return '\"Linux\"';\n if (userAgent.includes('iPhone')) return '\"iOS\"';\n if (userAgent.includes('Android')) return '\"Android\"';\n return '\"Windows\"';\n}\n\n/**\n * Determine if User-Agent is mobile\n */\nfunction isMobile(userAgent: string): boolean {\n return userAgent.includes('Mobile') || userAgent.includes('iPhone') || userAgent.includes('Android');\n}\n\n/**\n * Generate a random but realistic browser fingerprint with advanced anti-detection features\n */\nexport function generateBrowserFingerprint(): BrowserFingerprint {\n const userAgent = ALL_USER_AGENTS[Math.floor(Math.random() * ALL_USER_AGENTS.length)];\n const acceptLanguage = ACCEPT_LANGUAGES[Math.floor(Math.random() * ACCEPT_LANGUAGES.length)];\n const mobile = isMobile(userAgent);\n \n // Generate realistic viewport dimensions\n const commonResolutions = [\n [1920, 1080], [1366, 768], [1440, 900], [1536, 864], [1280, 720],\n [1600, 900], [1024, 768], [1280, 800], [1680, 1050], [2560, 1440]\n ];\n const [viewportWidth, viewportHeight] = commonResolutions[Math.floor(Math.random() * commonResolutions.length)];\n \n // Generate realistic timezone\n const timezones = [\n \"America/New_York\", \"America/Los_Angeles\", \"America/Chicago\", \"America/Denver\",\n \"Europe/London\", \"Europe/Paris\", \"Europe/Berlin\", \"Asia/Tokyo\", \"Australia/Sydney\"\n ];\n const timezone = timezones[Math.floor(Math.random() * timezones.length)];\n \n // Generate session ID\n const sessionId = crypto.randomBytes(16).toString('hex');\n \n // Calculate request delay (100-2000ms with realistic distribution)\n const requestDelay = Math.floor(Math.random() * 1900) + 100;\n \n return {\n userAgent,\n acceptLanguage,\n acceptEncoding: \"gzip, deflate, br\",\n accept: \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7\",\n secFetchDest: \"document\",\n secFetchMode: \"navigate\",\n secFetchSite: \"none\",\n secChUa: getSecChUa(userAgent),\n secChUaMobile: mobile ? \"?1\" : \"?0\",\n secChUaPlatform: getSecChUaPlatform(userAgent),\n dnt: Math.random() < 0.3 ? \"1\" : \"0\", // 30% chance of DNT\n upgradeInsecureRequests: \"1\",\n cacheControl: Math.random() < 0.1 ? \"no-cache\" : \"max-age=0\", // Occasionally no-cache\n pragma: Math.random() < 0.1 ? \"no-cache\" : \"\",\n connection: \"keep-alive\",\n // New anti-detection fields\n viewportWidth,\n viewportHeight,\n timezone,\n cookieEnabled: Math.random() < 0.95, // 95% have cookies enabled\n doNotTrack: Math.random() < 0.2 ? \"1\" : \"0\", // 20% enable DNT\n sessionId,\n requestDelay,\n };\n}\n\n/**\n * Apply browser fingerprint headers to a Headers object\n */\nexport function applyBrowserHeaders(headers: Headers, fingerprint: BrowserFingerprint, url?: string): void {\n headers.set(\"User-Agent\", fingerprint.userAgent);\n headers.set(\"Accept-Language\", fingerprint.acceptLanguage);\n headers.set(\"Accept-Encoding\", fingerprint.acceptEncoding);\n headers.set(\"Accept\", fingerprint.accept);\n headers.set(\"DNT\", fingerprint.dnt);\n headers.set(\"Upgrade-Insecure-Requests\", fingerprint.upgradeInsecureRequests);\n headers.set(\"Connection\", fingerprint.connection);\n \n // Only add Sec-Fetch headers for HTTPS requests\n if (!url || url.startsWith('https://')) {\n headers.set(\"Sec-Fetch-Dest\", fingerprint.secFetchDest);\n headers.set(\"Sec-Fetch-Mode\", fingerprint.secFetchMode);\n headers.set(\"Sec-Fetch-Site\", fingerprint.secFetchSite);\n }\n \n // Only add Sec-CH-UA headers for Chromium-based browsers\n if (fingerprint.secChUa) {\n headers.set(\"Sec-CH-UA\", fingerprint.secChUa);\n headers.set(\"Sec-CH-UA-Mobile\", fingerprint.secChUaMobile);\n headers.set(\"Sec-CH-UA-Platform\", fingerprint.secChUaPlatform);\n }\n \n // Add cache control headers\n if (fingerprint.cacheControl) {\n headers.set(\"Cache-Control\", fingerprint.cacheControl);\n }\n if (fingerprint.pragma) {\n headers.set(\"Pragma\", fingerprint.pragma);\n }\n}\n\n/**\n * Singleton class to manage browser fingerprint rotation with advanced anti-detection\n */\nclass BrowserFingerprintManager {\n private currentFingerprint: BrowserFingerprint | null = null;\n private lastRotation: number = 0;\n private readonly rotationInterval: number = 300000; // 5 minutes\n private requestCount: number = 0;\n private lastRequestTime: number = 0;\n\n /**\n * Get current fingerprint, rotating if necessary\n */\n getCurrentFingerprint(): BrowserFingerprint {\n const now = Date.now();\n if (!this.currentFingerprint || (now - this.lastRotation) > this.rotationInterval) {\n this.currentFingerprint = generateBrowserFingerprint();\n this.lastRotation = now;\n this.requestCount = 0; // Reset request count on rotation\n }\n return this.currentFingerprint;\n }\n\n /**\n * Force fingerprint rotation\n */\n rotateFingerprint(): BrowserFingerprint {\n this.currentFingerprint = generateBrowserFingerprint();\n this.lastRotation = Date.now();\n this.requestCount = 0;\n return this.currentFingerprint;\n }\n\n /**\n * Get request delay with jitter to avoid detection\n */\n getRequestDelay(): number {\n this.requestCount++;\n const fingerprint = this.getCurrentFingerprint();\n \n // Add jitter based on request count to avoid patterns\n const baseDelay = fingerprint.requestDelay;\n const jitter = Math.random() * 500; // 0-500ms jitter\n const countMultiplier = Math.min(this.requestCount * 50, 1000); // Increase delay with request count\n \n return baseDelay + jitter + countMultiplier;\n }\n\n /**\n * Check if we should delay before making a request\n */\n async waitForRequest(): Promise<void> {\n const now = Date.now();\n const timeSinceLastRequest = now - this.lastRequestTime;\n const requiredDelay = this.getRequestDelay();\n \n if (timeSinceLastRequest < requiredDelay) {\n const waitTime = requiredDelay - timeSinceLastRequest;\n await new Promise(resolve => setTimeout(resolve, waitTime));\n }\n \n this.lastRequestTime = Date.now();\n }\n}\n\nexport const browserFingerprintManager = new BrowserFingerprintManager();\n\n/**\n * Apply advanced anti-detection headers in realistic order\n */\nexport function applyAdvancedBrowserHeaders(headers: Headers, fingerprint: BrowserFingerprint, url?: string): void {\n // Headers should be applied in a specific order that matches real browsers\n const orderedHeaders = [\n [\"Host\", new URL(url || \"https://api.twitter.com\").host],\n [\"User-Agent\", fingerprint.userAgent],\n [\"Accept\", fingerprint.accept],\n [\"Accept-Language\", fingerprint.acceptLanguage],\n [\"Accept-Encoding\", fingerprint.acceptEncoding],\n [\"DNT\", fingerprint.dnt],\n [\"Connection\", fingerprint.connection],\n [\"Upgrade-Insecure-Requests\", fingerprint.upgradeInsecureRequests],\n ];\n\n // Add Sec-Fetch headers for HTTPS requests (Chromium browsers)\n if (!url || url.startsWith('https://')) {\n orderedHeaders.push(\n [\"Sec-Fetch-Dest\", fingerprint.secFetchDest],\n [\"Sec-Fetch-Mode\", fingerprint.secFetchMode],\n [\"Sec-Fetch-Site\", fingerprint.secFetchSite]\n );\n }\n\n // Add Sec-CH-UA headers for Chromium-based browsers\n if (fingerprint.secChUa) {\n orderedHeaders.push(\n [\"Sec-CH-UA\", fingerprint.secChUa],\n [\"Sec-CH-UA-Mobile\", fingerprint.secChUaMobile],\n [\"Sec-CH-UA-Platform\", fingerprint.secChUaPlatform]\n );\n }\n\n // Add cache control headers\n if (fingerprint.cacheControl) {\n orderedHeaders.push([\"Cache-Control\", fingerprint.cacheControl]);\n }\n if (fingerprint.pragma) {\n orderedHeaders.push([\"Pragma\", fingerprint.pragma]);\n }\n\n // Apply headers in order\n for (const [key, value] of orderedHeaders) {\n if (value) {\n headers.set(key, value);\n }\n }\n\n // Add some randomization to header casing (some servers check this)\n if (Math.random() < 0.1) {\n const userAgent = headers.get(\"User-Agent\");\n if (userAgent) {\n headers.delete(\"User-Agent\");\n headers.set(\"user-agent\", userAgent);\n }\n }\n}\n\n/**\n * Get headers optimized for Twitter API requests with advanced anti-detection\n */\nexport async function getTwitterApiHeaders(baseHeaders?: Record<string, string>): Promise<Headers> {\n // Wait for appropriate delay before making request\n await browserFingerprintManager.waitForRequest();\n \n const fingerprint = browserFingerprintManager.getCurrentFingerprint();\n const headers = new Headers(baseHeaders);\n \n // Apply advanced browser fingerprint with realistic header ordering\n applyAdvancedBrowserHeaders(headers, fingerprint, \"https://api.twitter.com\");\n \n // Twitter-specific headers with realistic values\n headers.set(\"Referer\", \"https://twitter.com/\");\n headers.set(\"Origin\", \"https://twitter.com\");\n headers.set(\"X-Twitter-Active-User\", \"yes\");\n headers.set(\"X-Twitter-Client-Language\", \"en\");\n \n // Adjust accept header for API requests\n headers.set(\"Accept\", \"application/json, text/plain, */*\");\n \n // Add realistic timing headers\n headers.set(\"X-Requested-With\", \"XMLHttpRequest\");\n \n // Add session-based headers\n headers.set(\"X-Client-Transaction-Id\", fingerprint.sessionId);\n \n // Occasionally add additional anti-bot headers\n if (Math.random() < 0.3) {\n headers.set(\"Purpose\", \"prefetch\");\n }\n \n if (Math.random() < 0.2) {\n headers.set(\"X-Forwarded-For\", generateRandomIP());\n }\n \n return headers;\n}\n\n/**\n * Get headers for Twitter web requests (non-API)\n */\nexport async function getTwitterWebHeaders(baseHeaders?: Record<string, string>): Promise<Headers> {\n await browserFingerprintManager.waitForRequest();\n \n const fingerprint = browserFingerprintManager.getCurrentFingerprint();\n const headers = new Headers(baseHeaders);\n \n // Apply browser fingerprint\n applyAdvancedBrowserHeaders(headers, fingerprint, \"https://twitter.com\");\n \n // Web-specific headers\n headers.set(\"Referer\", \"https://twitter.com/home\");\n headers.set(\"Origin\", \"https://twitter.com\");\n \n return headers;\n}\n\n/**\n * Generate a random IP address for X-Forwarded-For header\n */\nfunction generateRandomIP(): string {\n const ranges = [\n // Common residential IP ranges\n [10, 0, 0, 0], [172, 16, 0, 0], [192, 168, 0, 0],\n // Common ISP ranges (safe examples)\n [24, 0, 0, 0], [76, 0, 0, 0], [98, 0, 0, 0]\n ];\n \n const range = ranges[Math.floor(Math.random() * ranges.length)];\n return `${range[0]}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}`;\n}\n\n/**\n * Force rotation of browser fingerprint (useful after detection)\n */\nexport function rotateBrowserFingerprint(): void {\n browserFingerprintManager.rotateFingerprint();\n}\n\n/**\n * Get current fingerprint info (for debugging)\n */\nexport function getCurrentFingerprintInfo(): BrowserFingerprint {\n return browserFingerprintManager.getCurrentFingerprint();\n}\n","import { type Static, Type } from \"@sinclair/typebox\";\nimport { Check } from \"@sinclair/typebox/value\";\nimport { Headers } from \"headers-polyfill\";\nimport * as OTPAuth from \"otpauth\";\nimport { CookieJar } from \"tough-cookie\";\nimport { requestApi } from \"./api\";\nimport { TwitterGuestAuth } from \"./auth\";\nimport { getTwitterApiHeaders } from \"./browser-fingerprint\";\nimport type { TwitterApiErrorRaw } from \"./errors\";\nimport { type LegacyUserRaw, type Profile, parseProfile } from \"./profile\";\nimport { updateCookieJar } from \"./requests\";\n\n/**\n * Interface representing the init request for a Twitter user authentication flow.\n * @typedef {Object} TwitterUserAuthFlowInitRequest\n * @property {string} flow_name - The name of the flow.\n * @property {Record<string, unknown>} input_flow_data - The input flow data.\n */\ninterface TwitterUserAuthFlowInitRequest {\n flow_name: string;\n input_flow_data: Record<string, unknown>;\n}\n\n/**\n * Interface representing a request for a subtask in the Twitter user authentication flow.\n * @typedef {object} TwitterUserAuthFlowSubtaskRequest\n * @property {string} flow_token - The token representing the flow.\n * @property {object[]} subtask_inputs - An array of subtask inputs, each containing a subtask ID and other unknown properties.\n */\ninterface TwitterUserAuthFlowSubtaskRequest {\n flow_token: string;\n subtask_inputs: ({\n subtask_id: string;\n } & Record<string, unknown>)[];\n}\n\n/**\n * Represents a request for a Twitter user authentication flow, which can be either an init request\n * or a subtask request.\n */\n\ntype TwitterUserAuthFlowRequest =\n | TwitterUserAuthFlowInitRequest\n | TwitterUserAuthFlowSubtaskRequest;\n\n/**\n * Interface representing the response object of the Twitter user authentication flow.\n * @property {TwitterApiErrorRaw[]} [errors] The errors occurred during the authentication flow.\n * @property {string} [flow_token] The token associated with the authentication flow.\n * @property {string} [status] The status of the authentication flow.\n * @property {TwitterUserAuthSubtask[]} [subtasks] The subtasks involved in the authentication flow.\n */\ninterface TwitterUserAuthFlowResponse {\n errors?: TwitterApiErrorRaw[];\n flow_token?: string;\n status?: string;\n subtasks?: TwitterUserAuthSubtask[];\n}\n\n/**\n * Interface representing the response structure for verifying Twitter user authentication credentials.\n *\n * @property {TwitterApiErrorRaw[]} [errors] Optional array of Twitter API errors.\n */\ninterface TwitterUserAuthVerifyCredentials {\n errors?: TwitterApiErrorRaw[];\n}\n\nconst TwitterUserAuthSubtask = Type.Object({\n subtask_id: Type.String(),\n enter_text: Type.Optional(Type.Object({})),\n});\n/**\n * Represents the type of a Twitter user authentication subtask.\n */\ntype TwitterUserAuthSubtask = Static<typeof TwitterUserAuthSubtask>;\n\n/**\n * Represents the result of a successful flow token generation.\n * @typedef {Object} FlowTokenResultSuccess\n * @property {string} status - The status of the result (always \"success\").\n * @property {string} flowToken - The generated flow token.\n * @property {TwitterUserAuthSubtask} [subtask] - Optional subtask related to Twitter user authentication.\n */\ntype FlowTokenResultSuccess = {\n status: \"success\";\n flowToken: string;\n subtask?: TwitterUserAuthSubtask;\n};\n\n/**\n * Represents the result of a FlowToken operation, which can either be a success with the token or an error with the error details.\n * @typedef {FlowTokenResultSuccess | { status: \"error\"; err: Error }} FlowTokenResult\n */\ntype FlowTokenResult = FlowTokenResultSuccess | { status: \"error\"; err: Error };\n\n/**\n * A user authentication token manager.\n */\n/**\n * Class representing Twitter User Authentication.\n * Extends TwitterGuestAuth class.\n */\nexport class TwitterUserAuth extends TwitterGuestAuth {\n private userProfile: Profile | undefined;\n\n async isLoggedIn(): Promise<boolean> {\n const res = await requestApi<TwitterUserAuthVerifyCredentials>(\n \"https://api.twitter.com/1.1/account/verify_credentials.json\",\n this\n );\n if (!res.success) {\n return false;\n }\n\n const { value: verify } = res;\n this.userProfile = parseProfile(\n verify as LegacyUserRaw,\n (verify as unknown as { verified: boolean }).verified\n );\n return verify && !verify.errors?.length;\n }\n\n async me(): Promise<Profile | undefined> {\n if (this.userProfile) {\n return this.userProfile;\n }\n await this.isLoggedIn();\n return this.userProfile;\n }\n\n 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 await this.updateGuestToken();\n\n let next = await this.initLogin();\n while (\"subtask\" in next && next.subtask) {\n if (next.subtask.subtask_id === \"LoginJsInstrumentationSubtask\") {\n next = await this.handleJsInstrumentationSubtask(next);\n } else if (next.subtask.subtask_id === \"LoginEnterUserIdentifierSSO\") {\n next = await this.handleEnterUserIdentifierSSO(next, username);\n } else if (\n next.subtask.subtask_id === \"LoginEnterAlternateIdentifierSubtask\"\n ) {\n next = await this.handleEnterAlternateIdentifierSubtask(\n next,\n email as string\n );\n } else if (next.subtask.subtask_id === \"LoginEnterPassword\") {\n next = await this.handleEnterPassword(next, password);\n } else if (next.subtask.subtask_id === \"AccountDuplicationCheck\") {\n next = await this.handleAccountDuplicationCheck(next);\n } else if (next.subtask.subtask_id === \"LoginTwoFactorAuthChallenge\") {\n if (twoFactorSecret) {\n next = await this.handleTwoFactorAuthChallenge(next, twoFactorSecret);\n } else {\n throw new Error(\n \"Requested two factor authentication code but no secret provided\"\n );\n }\n } else if (next.subtask.subtask_id === \"LoginAcid\") {\n next = await this.handleAcid(next, email);\n } else if (next.subtask.subtask_id === \"LoginSuccessSubtask\") {\n next = await this.handleSuccessSubtask(next);\n } else {\n throw new Error(`Unknown subtask ${next.subtask.subtask_id}`);\n }\n }\n if (appKey && appSecret && accessToken && accessSecret) {\n this.loginWithV2(appKey, appSecret, accessToken, accessSecret);\n }\n if (\"err\" in next) {\n throw next.err;\n }\n }\n\n async logout(): Promise<void> {\n if (!this.isLoggedIn()) {\n return;\n }\n\n await requestApi<void>(\n \"https://api.twitter.com/1.1/account/logout.json\",\n this,\n \"POST\"\n );\n this.deleteToken();\n this.jar = new CookieJar();\n }\n\n async installCsrfToken(headers: Headers): Promise<void> {\n const cookies = await this.getCookies();\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n if (xCsrfToken) {\n headers.set(\"x-csrf-token\", xCsrfToken.value);\n }\n }\n\n async installTo(headers: Headers): Promise<void> {\n headers.set(\"authorization\", `Bearer ${this.bearerToken}`);\n headers.set(\"cookie\", await this.getCookieString());\n await this.installCsrfToken(headers);\n }\n\n private async initLogin() {\n // Reset certain session-related cookies because Twitter complains sometimes if we don't\n this.removeCookie(\"twitter_ads_id=\");\n this.removeCookie(\"ads_prefs=\");\n this.removeCookie(\"_twitter_sess=\");\n this.removeCookie(\"zipbox_forms_auth_token=\");\n this.removeCookie(\"lang=\");\n this.removeCookie(\"bouncer_reset_cookie=\");\n this.removeCookie(\"twid=\");\n this.removeCookie(\"twitter_ads_idb=\");\n this.removeCookie(\"email_uid=\");\n this.removeCookie(\"external_referer=\");\n this.removeCookie(\"ct0=\");\n this.removeCookie(\"aa_u=\");\n\n return await this.executeFlowTask({\n flow_name: \"login\",\n input_flow_data: {\n flow_context: {\n debug_overrides: {},\n start_location: {\n location: \"splash_screen\",\n },\n },\n },\n });\n }\n\n private async handleJsInstrumentationSubtask(prev: FlowTokenResultSuccess) {\n return await this.executeFlowTask({\n flow_token: prev.flowToken,\n subtask_inputs: [\n {\n subtask_id: \"LoginJsInstrumentationSubtask\",\n js_instrumentation: {\n response: \"{}\",\n link: \"next_link\",\n },\n },\n ],\n });\n }\n\n private async handleEnterAlternateIdentifierSubtask(\n prev: FlowTokenResultSuccess,\n email: string\n ) {\n return await this.executeFlowTask({\n flow_token: prev.flowToken,\n subtask_inputs: [\n {\n subtask_id: \"LoginEnterAlternateIdentifierSubtask\",\n enter_text: {\n text: email,\n link: \"next_link\",\n },\n },\n ],\n });\n }\n\n private async handleEnterUserIdentifierSSO(\n prev: FlowTokenResultSuccess,\n username: string\n ) {\n return await this.executeFlowTask({\n flow_token: prev.flowToken,\n subtask_inputs: [\n {\n subtask_id: \"LoginEnterUserIdentifierSSO\",\n settings_list: {\n setting_responses: [\n {\n key: \"user_identifier\",\n response_data: {\n text_data: { result: username },\n },\n },\n ],\n link: \"next_link\",\n },\n },\n ],\n });\n }\n\n private async handleEnterPassword(\n prev: FlowTokenResultSuccess,\n password: string\n ) {\n return await this.executeFlowTask({\n flow_token: prev.flowToken,\n subtask_inputs: [\n {\n subtask_id: \"LoginEnterPassword\",\n enter_password: {\n password,\n link: \"next_link\",\n },\n },\n ],\n });\n }\n\n private async handleAccountDuplicationCheck(prev: FlowTokenResultSuccess) {\n return await this.executeFlowTask({\n flow_token: prev.flowToken,\n subtask_inputs: [\n {\n subtask_id: \"AccountDuplicationCheck\",\n check_logged_in_account: {\n link: \"AccountDuplicationCheck_false\",\n },\n },\n ],\n });\n }\n\n private async handleTwoFactorAuthChallenge(\n prev: FlowTokenResultSuccess,\n secret: string\n ) {\n const totp = new OTPAuth.TOTP({ secret });\n let error;\n for (let attempts = 1; attempts < 4; attempts += 1) {\n try {\n return await this.executeFlowTask({\n flow_token: prev.flowToken,\n subtask_inputs: [\n {\n subtask_id: \"LoginTwoFactorAuthChallenge\",\n enter_text: {\n link: \"next_link\",\n text: totp.generate(),\n },\n },\n ],\n });\n } catch (err) {\n error = err;\n await new Promise((resolve) => setTimeout(resolve, 2000 * attempts));\n }\n }\n throw error;\n }\n\n private async handleAcid(\n prev: FlowTokenResultSuccess,\n email: string | undefined\n ) {\n return await this.executeFlowTask({\n flow_token: prev.flowToken,\n subtask_inputs: [\n {\n subtask_id: \"LoginAcid\",\n enter_text: {\n text: email,\n link: \"next_link\",\n },\n },\n ],\n });\n }\n\n private async handleSuccessSubtask(prev: FlowTokenResultSuccess) {\n return await this.executeFlowTask({\n flow_token: prev.flowToken,\n subtask_inputs: [],\n });\n }\n\n private async executeFlowTask(\n data: TwitterUserAuthFlowRequest\n ): Promise<FlowTokenResult> {\n const onboardingTaskUrl =\n \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n const token = this.guestToken;\n if (token == null) {\n throw new Error(\"Authentication token is null or undefined.\");\n }\n\n const headers = new Headers({\n authorization: `Bearer ${this.bearerToken}`,\n cookie: await this.getCookieString(),\n \"content-type\": \"application/json\",\n \"x-guest-token\": token,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n });\n \n // Apply browser fingerprinting\n const twitterHeaders = await getTwitterApiHeaders();\n for (const [key, value] of twitterHeaders.entries()) {\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n }\n \n await this.installCsrfToken(headers);\n\n const res = await this.fetch(onboardingTaskUrl, {\n credentials: \"include\",\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(data),\n });\n\n await updateCookieJar(this.jar, res.headers);\n\n if (!res.ok) {\n return { status: \"error\", err: new Error(await res.text()) };\n }\n\n const flow: TwitterUserAuthFlowResponse = await res.json();\n if (flow?.flow_token == null) {\n return { status: \"error\", err: new Error(\"flow_token not found.\") };\n }\n\n if (flow.errors?.length) {\n return {\n status: \"error\",\n err: new Error(\n `Authentication error (${flow.errors[0].code}): ${flow.errors[0].message}`\n ),\n };\n }\n\n if (typeof flow.flow_token !== \"string\") {\n return {\n status: \"error\",\n err: new Error(\"flow_token was not a string.\"),\n };\n }\n\n const subtask = flow.subtasks?.length ? flow.subtasks[0] : undefined;\n Check(TwitterUserAuthSubtask, subtask);\n\n if (subtask && subtask.subtask_id === \"DenyLoginSubtask\") {\n return {\n status: \"error\",\n err: new Error(\"Authentication error: DenyLoginSubtask\"),\n };\n }\n\n return {\n status: \"success\",\n subtask,\n flowToken: flow.flow_token,\n };\n }\n}\n","import stringify from \"json-stable-stringify\";\nimport { type RequestApiResult, requestApi } from \"./api\";\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\nexport async function getProfile(\n username: string,\n auth: TwitterAuth\n): Promise<RequestApiResult<Profile>> {\n const params = new URLSearchParams();\n params.set(\n \"variables\",\n stringify({\n screen_name: username,\n withSafetyModeUserFields: true,\n }) ?? \"\"\n );\n\n params.set(\n \"features\",\n stringify({\n hidden_profile_likes_enabled: false,\n hidden_profile_subscriptions_enabled: false, // Auth-restricted\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n subscriptions_verification_info_is_identity_verified_enabled: false,\n subscriptions_verification_info_verified_since_enabled: true,\n highlights_tweets_tab_ui_enabled: true,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n responsive_web_graphql_timeline_navigation_enabled: true,\n }) ?? \"\"\n );\n\n params.set(\n \"fieldToggles\",\n stringify({ withAuxiliaryUserLabels: false }) ?? \"\"\n );\n\n const res = await requestApi<UserRaw>(\n `https://twitter.com/i/api/graphql/G3KGOASz96M-Qu0nwmGXNg/UserByScreenName?${params.toString()}`,\n auth\n );\n if (!res.success) {\n return res as any;\n }\n\n const { value } = res;\n const { errors } = value;\n if (errors != null && errors.length > 0) {\n return {\n success: false,\n err: new Error(errors[0].message),\n };\n }\n\n if (!value.data || !value.data.user || !value.data.user.result) {\n return {\n success: false,\n err: new Error(\"User not found.\"),\n };\n }\n const { result: user } = value.data.user;\n const { legacy } = user;\n\n if (user.rest_id == null || user.rest_id.length === 0) {\n return {\n success: false,\n err: new Error(\"rest_id not found.\"),\n };\n }\n\n legacy.id_str = user.rest_id;\n\n if (legacy.screen_name == null || legacy.screen_name.length === 0) {\n return {\n success: false,\n err: new Error(`Either ${username} does not exist or is private.`),\n };\n }\n\n return {\n success: true,\n value: parseProfile(user.legacy, user.is_blue_verified),\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 const params = new URLSearchParams();\n params.set(\n \"variables\",\n stringify({\n userId: userId,\n withSafetyModeUserFields: true,\n }) ?? \"\"\n );\n\n params.set(\n \"features\",\n stringify({\n hidden_profile_subscriptions_enabled: true,\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n highlights_tweets_tab_ui_enabled: true,\n responsive_web_twitter_article_notes_tab_enabled: true,\n subscriptions_feature_can_gift_premium: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n responsive_web_graphql_timeline_navigation_enabled: true,\n }) ?? \"\"\n );\n\n const res = await requestApi<UserRaw>(\n `https://twitter.com/i/api/graphql/xf3jd90KKBCUxdlI_tNHZw/UserByRestId?${params.toString()}`,\n auth\n );\n\n if (!res.success) {\n return res as any;\n }\n\n const { value } = res;\n const { errors } = value;\n if (errors != null && errors.length > 0) {\n return {\n success: false,\n err: new Error(errors[0].message),\n };\n }\n\n if (!value.data || !value.data.user || !value.data.user.result) {\n return {\n success: false,\n err: new Error(\"User not found.\"),\n };\n }\n\n const { result: user } = value.data.user;\n const { legacy } = user;\n\n if (legacy.screen_name == null || legacy.screen_name.length === 0) {\n return {\n success: false,\n err: new Error(\n `Either user with ID ${userId} does not exist or is private.`\n ),\n };\n }\n\n return {\n success: true,\n value: legacy.screen_name,\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 { requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\n\n/**\n * Interface representing a Grok conversation object.\n * @interface\n * @property {Object} data - The data object containing information about the conversation.\n * @property {Object} data.create_grok_conversation - The object containing the created Grok conversation.\n * @property {string} data.create_grok_conversation.conversation_id - The ID of the created conversation.\n */\nexport interface GrokConversation {\n data: {\n create_grok_conversation: {\n conversation_id: string;\n };\n };\n}\n\n/**\n * Interface representing a Grok request.\n *\n * @property {GrokResponseMessage[]} responses - Array of GrokResponseMessage objects.\n * @property {string} systemPromptName - Name of the system prompt.\n * @property {string} grokModelOptionId - ID of the Grok model option.\n * @property {string} conversationId - ID of the conversation.\n * @property {boolean} returnSearchResults - Indicates if search results should be returned.\n * @property {boolean} returnCitations - Indicates if citations should be returned.\n * @property {Object} promptMetadata - Additional metadata for the prompt.\n * @property {string} promptMetadata.promptSource - Source of the prompt.\n * @property {string} promptMetadata.action - Action related to the prompt.\n * @property {number} imageGenerationCount - Number of image generations.\n * @property {Object} requestFeatures - Additional features requested for the request.\n * @property {boolean} requestFeatures.eagerTweets - Indicates if eager tweets are requested.\n * @property {boolean} requestFeatures.serverHistory - Indicates if server history is requested.\n */\n\nexport interface GrokRequest {\n responses: GrokResponseMessage[];\n systemPromptName: string;\n grokModelOptionId: string;\n conversationId: string;\n returnSearchResults: boolean;\n returnCitations: boolean;\n promptMetadata: {\n promptSource: string;\n action: string;\n };\n imageGenerationCount: number;\n requestFeatures: {\n eagerTweets: boolean;\n serverHistory: boolean;\n };\n}\n\n// Types for the user-facing API\n/**\n * Interface representing a GrokMessage object.\n * @interface\n * @property {string} role - The role of the message, can be either \"user\" or \"assistant\".\n * @property {string} content - The content of the message.\n */\nexport interface GrokMessage {\n role: \"user\" | \"assistant\";\n content: string;\n}\n\n/**\n * Interface for specifying options when using GrokChat.\n * @typedef {Object} GrokChatOptions\n * @property {GrokMessage[]} messages - Array of GrokMessage objects\n * @property {string} [conversationId] - Optional ID for the conversation. Will create new if not provided\n * @property {boolean} [returnSearchResults] - Flag to indicate whether to return search results\n * @property {boolean} [returnCitations] - Flag to indicate whether to return citations\n */\nexport interface GrokChatOptions {\n messages: GrokMessage[];\n conversationId?: string; // Optional - will create new if not provided\n returnSearchResults?: boolean;\n returnCitations?: boolean;\n}\n\n// Internal types for API requests\n/**\n * Interface for a Grok response message.\n * @property {string} message - The message content.\n * @property {1|2} sender - The sender of the message. 1 = user, 2 = assistant.\n * @property {string} [promptSource] - The source of the prompt (optional).\n * @property {any[]} [fileAttachments] - An array of file attachments (optional).\n */\nexport interface GrokResponseMessage {\n message: string;\n sender: 1 | 2; // 1 = user, 2 = assistant\n promptSource?: string;\n fileAttachments?: any[];\n}\n\n// Rate limit information\n/**\n * Interface representing a Grok rate limit response.\n * @typedef { Object } GrokRateLimit\n * @property { boolean } isRateLimited - Flag indicating if the rate limit is in effect.\n * @property { string } message - The message associated with the rate limit.\n * @property { Object } upsellInfo - Object containing additional information about the rate limit (optional).\n * @property { string } upsellInfo.usageLimit - The usage limit imposed by the rate limit.\n * @property { string } upsellInfo.quotaDuration - The duration of the quota for the rate limit.\n * @property { string } upsellInfo.title - The title related to the rate limit.\n * @property { string } upsellInfo.message - Additional message related to the rate limit.\n */\nexport interface GrokRateLimit {\n isRateLimited: boolean;\n message: string;\n upsellInfo?: {\n usageLimit: string;\n quotaDuration: string;\n title: string;\n message: string;\n };\n}\n\n/**\n * Interface for the response from the GrokChat API.\n * @typedef {object} GrokChatResponse\n * @property {string} conversationId - The ID of the conversation.\n * @property {string} message - The message content.\n * @property {Array<GrokMessage>} messages - An array of GrokMessage objects.\n * @property {Array<any>} [webResults] - Optional array of web results.\n * @property {object} [metadata] - Optional metadata object.\n * @property {object} [rateLimit] - Optional rate limit information.\n */\nexport interface GrokChatResponse {\n conversationId: string;\n message: string;\n messages: GrokMessage[];\n webResults?: any[];\n metadata?: any;\n rateLimit?: GrokRateLimit;\n}\n\n/**\n * Creates a new conversation with Grok.\n * @returns The ID of the newly created conversation\n * @internal\n */\n/**\n * Creates a Grok conversation using the provided Twitter authorization credentials.\n *\n * @param {TwitterAuth} auth - Twitter authorization credentials required to make the API request.\n * @returns {Promise<string>} A promise that resolves with the conversation ID of the newly created Grok conversation.\n */\nexport async function createGrokConversation(\n auth: TwitterAuth\n): Promise<string> {\n const res = await requestApi<GrokConversation>(\n \"https://x.com/i/api/graphql/6cmfJY3d7EPWuCSXWrkOFg/CreateGrokConversation\",\n auth,\n \"POST\"\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n return res.value.data.create_grok_conversation.conversation_id;\n}\n\n/**\n * Main method for interacting with Grok in a chat-like manner.\n */\nexport async function grokChat(\n options: GrokChatOptions,\n auth: TwitterAuth\n): Promise<GrokChatResponse> {\n let { conversationId, messages } = options;\n\n // Create new conversation if none provided\n if (!conversationId) {\n conversationId = await createGrokConversation(auth);\n }\n\n // Convert OpenAI-style messages to Grok's internal format\n const responses: GrokResponseMessage[] = messages.map((msg: GrokMessage) => ({\n message: msg.content,\n sender: msg.role === \"user\" ? 1 : 2,\n ...(msg.role === \"user\" && {\n promptSource: \"\",\n fileAttachments: [],\n }),\n }));\n\n const payload: GrokRequest = {\n responses,\n systemPromptName: \"\",\n grokModelOptionId: \"grok-2a\",\n conversationId,\n returnSearchResults: options.returnSearchResults ?? true,\n returnCitations: options.returnCitations ?? true,\n promptMetadata: {\n promptSource: \"NATURAL\",\n action: \"INPUT\",\n },\n imageGenerationCount: 4,\n requestFeatures: {\n eagerTweets: true,\n serverHistory: true,\n },\n };\n\n const res = await requestApi<{ text: string }>(\n \"https://api.x.com/2/grok/add_response.json\",\n auth,\n \"POST\",\n undefined,\n payload\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n // Parse response chunks - Grok may return either a single response or multiple chunks\n let chunks: any[];\n if (res.value.text) {\n // For streaming responses, split text into chunks and parse each JSON chunk\n chunks = res.value.text\n .split(\"\\n\")\n .filter(Boolean)\n .map((chunk: any) => JSON.parse(chunk));\n } else {\n // For single responses (like rate limiting), wrap in array\n chunks = [res.value];\n }\n\n // Check if we hit rate limits by examining first chunk\n const firstChunk = chunks[0];\n if (firstChunk.result?.responseType === \"limiter\") {\n return {\n conversationId,\n message: firstChunk.result.message,\n messages: [\n ...messages,\n { role: \"assistant\", content: firstChunk.result.message },\n ],\n rateLimit: {\n isRateLimited: true,\n message: firstChunk.result.message,\n upsellInfo: firstChunk.result.upsell\n ? {\n usageLimit: firstChunk.result.upsell.usageLimit,\n quotaDuration: `${firstChunk.result.upsell.quotaDurationCount} ${firstChunk.result.upsell.quotaDurationPeriod}`,\n title: firstChunk.result.upsell.title,\n message: firstChunk.result.upsell.message,\n }\n : undefined,\n },\n };\n }\n\n // Combine all message chunks into single response\n const fullMessage = chunks\n .filter((chunk: any) => chunk.result?.message)\n .map((chunk: any) => chunk.result.message)\n .join(\"\");\n\n // Return complete response with conversation history and metadata\n return {\n conversationId,\n message: fullMessage,\n messages: [...messages, { role: \"assistant\", content: fullMessage }],\n webResults: chunks.find((chunk: any) => chunk.result?.webResults)?.result\n .webResults,\n metadata: chunks[0],\n };\n}\n","import type { TwitterAuth } from \"./auth\";\nimport { getTwitterApiHeaders } from \"./browser-fingerprint\";\nimport { updateCookieJar } from \"./requests\";\n\n/**\n * Represents a direct message object.\n * @typedef {Object} DirectMessage\n * @property {string} id - The unique identifier of the direct message.\n * @property {string} text - The text content of the direct message.\n * @property {string} senderId - The unique identifier of the sender of the direct message.\n * @property {string} recipientId - The unique identifier of the recipient of the direct message.\n * @property {string} createdAt - The timestamp when the direct message was created.\n * @property {string[]} [mediaUrls] - An optional array of URLs for any media included in the direct message.\n * @property {string} [senderScreenName] - The screen name of the sender of the direct message.\n * @property {string} [recipientScreenName] - The screen name of the recipient of the direct message.\n */\n\nexport interface DirectMessage {\n id: string;\n text: string;\n senderId: string;\n recipientId: string;\n createdAt: string;\n mediaUrls?: string[];\n senderScreenName?: string;\n recipientScreenName?: string;\n}\n\n/**\n * Represents a direct message conversation.\n * @typedef {Object} DirectMessageConversation\n * @property {string} conversationId - The ID of the conversation.\n * @property {DirectMessage[]} messages - An array of DirectMessage objects representing the messages in the conversation.\n * @property {Object[]} participants - An array of participant objects with IDs and screen names.\n * @property {string} participants.id - The ID of the participant.\n * @property {string} participants.screenName - The screen name of the participant.\n */\nexport interface DirectMessageConversation {\n conversationId: string;\n messages: DirectMessage[];\n participants: {\n id: string;\n screenName: string;\n }[];\n}\n\n/**\n * Represents a direct message event object.\n * @typedef {Object} DirectMessageEvent\n * @property {string} id - The unique identifier of the direct message event.\n * @property {string} type - The type of the direct message event.\n * @property {Object} message_create - Object containing information about the message creation.\n * @property {string} message_create.sender_id - The sender's unique identifier.\n * @property {Object} message_create.target - Object containing information about the message target user.\n * @property {string} message_create.target.recipient_id - The recipient's unique identifier.\n * @property {Object} message_create.message_data - Object containing the message data.\n * @property {string} message_create.message_data.text - The text content of the message.\n * @property {string} message_create.message_data.created_at - The timestamp when the message was created.\n * @property {Object} [message_create.message_data.entities] - Object containing optional entities in the message data.\n * @property {Array<Object>} [message_create.message_data.entities.urls] - Array of URL objects in the message data.\n * @property {string} message_create.message_data.entities.urls.url - The URL in the message.\n * @property {string} message_create.message_data.entities.urls.expanded_url - The expanded URL of the link in the message.\n * @property {string} message_create.message_data.entities.urls.display_url - The display URL of the link in the message.\n * @property {Array<Object>} [message_create.message_data.entities.media] - Array of media objects in the message data.\n * @property {string} message_create.message_data.entities.media.url - The URL of the media in the message.\n * @property {string} message_create.message_data.entities.media.type - The type of media in the message.\n */\nexport interface DirectMessageEvent {\n id: string;\n type: string;\n message_create: {\n sender_id: string;\n target: {\n recipient_id: string;\n };\n message_data: {\n text: string;\n created_at: string;\n entities?: {\n urls?: Array<{\n url: string;\n expanded_url: string;\n display_url: string;\n }>;\n media?: Array<{\n url: string;\n type: string;\n }>;\n };\n };\n };\n}\n\n/**\n * Interface representing the response of direct messages.\n * @typedef {Object} DirectMessagesResponse\n * @property {DirectMessageConversation[]} conversations - Array of direct message conversations.\n * @property {TwitterUser[]} users - Array of Twitter users.\n * @property {string} [cursor] - Optional cursor for pagination.\n * @property {string} [lastSeenEventId] - Optional ID of the last seen event.\n * @property {string} [trustedLastSeenEventId] - Optional ID of the last seen trusted event.\n * @property {string} [untrustedLastSeenEventId] - Optional ID of the last seen untrusted event.\n * @property {Object} [inboxTimelines] - Optional object containing trusted and untrusted inbox timelines.\n * @property {Object} [inboxTimelines.trusted] - Object containing status and optional minimum entry ID for trusted inbox timeline.\n * @property {string} inboxTimelines.trusted.status - Status of the trusted inbox timeline.\n * @property {string} [inboxTimelines.trusted.minEntryId] - Optional minimum entry ID for the trusted inbox timeline.\n * @property {Object} [inboxTimelines.untrusted] - Object containing status and optional minimum entry ID for untrusted inbox timeline.\n * @property {string} inboxTimelines.untrusted.status - Status of the untrusted inbox timeline.\n * @property {string} [inboxTimelines.untrusted.minEntryId] - Optional minimum entry ID for the untrusted inbox timeline.\n * @property {string} userId - ID of the user.\n */\nexport interface DirectMessagesResponse {\n conversations: DirectMessageConversation[];\n users: TwitterUser[];\n cursor?: string;\n lastSeenEventId?: string;\n trustedLastSeenEventId?: string;\n untrustedLastSeenEventId?: string;\n inboxTimelines?: {\n trusted?: {\n status: string;\n minEntryId?: string;\n };\n untrusted?: {\n status: string;\n minEntryId?: string;\n };\n };\n userId: string;\n}\n\n/**\n * Interface representing a Twitter user.\n * @property {string} id - The unique identifier of the user.\n * @property {string} screenName - The user's screen name.\n * @property {string} name - The user's full name.\n * @property {string} profileImageUrl - The URL of the user's profile image.\n * @property {string} [description] - The user's profile description.\n * @property {boolean} [verified] - Whether the user is a verified account.\n * @property {boolean} [protected] - Whether the user has a protected account.\n * @property {number} [followersCount] - The number of followers the user has.\n * @property {number} [friendsCount] - The number of friends the user has.\n */\nexport interface TwitterUser {\n id: string;\n screenName: string;\n name: string;\n profileImageUrl: string;\n description?: string;\n verified?: boolean;\n protected?: boolean;\n followersCount?: number;\n friendsCount?: number;\n}\n\n/**\n * Interface representing the response of sending a direct message.\n * @typedef {Object} SendDirectMessageResponse\n * @property {Array<{message: {id: string, time: string, affects_sort: boolean, conversation_id: string, message_data: {id: string, time: string, recipient_id: string, sender_id: string, text: string}}}>} entries - Array of message entries.\n * @property {Object.<string, TwitterUser>} users - Record of Twitter users.\n */\nexport interface SendDirectMessageResponse {\n entries: {\n message: {\n id: string;\n time: string;\n affects_sort: boolean;\n conversation_id: string;\n message_data: {\n id: string;\n time: string;\n recipient_id: string;\n sender_id: string;\n text: string;\n };\n };\n }[];\n users: Record<string, TwitterUser>;\n}\n\n/**\n * Parses direct message conversations from the provided data.\n * @param {any} data - The data containing direct message conversations.\n * @param {string} userId - The user ID for which the conversations should be parsed.\n * @returns {DirectMessagesResponse} The parsed direct message conversations.\n */\nfunction parseDirectMessageConversations(\n data: any,\n userId: string\n): DirectMessagesResponse {\n try {\n const inboxState = data?.inbox_initial_state;\n const conversations = inboxState?.conversations || {};\n const entries = inboxState?.entries || [];\n const users = inboxState?.users || {};\n\n // Parse users first\n const parsedUsers: TwitterUser[] = Object.values(users).map(\n (user: any) => ({\n id: user.id_str,\n screenName: user.screen_name,\n name: user.name,\n profileImageUrl: user.profile_image_url_https,\n description: user.description,\n verified: user.verified,\n protected: user.protected,\n followersCount: user.followers_count,\n friendsCount: user.friends_count,\n })\n );\n\n // Group messages by conversation_id\n const messagesByConversation: Record<string, any[]> = {};\n entries.forEach((entry: any) => {\n if (entry.message) {\n const convId = entry.message.conversation_id;\n if (!messagesByConversation[convId]) {\n messagesByConversation[convId] = [];\n }\n messagesByConversation[convId].push(entry.message);\n }\n });\n\n // Convert to DirectMessageConversation array\n const parsedConversations = Object.entries(conversations).map(\n ([convId, conv]: [string, any]) => {\n const messages = messagesByConversation[convId] || [];\n\n // Sort messages by time in ascending order\n messages.sort((a, b) => Number(a.time) - Number(b.time));\n\n return {\n conversationId: convId,\n messages: parseDirectMessages(messages, users),\n participants: conv.participants.map((p: any) => ({\n id: p.user_id,\n screenName: users[p.user_id]?.screen_name || p.user_id,\n })),\n };\n }\n );\n\n return {\n conversations: parsedConversations,\n users: parsedUsers,\n cursor: inboxState?.cursor,\n lastSeenEventId: inboxState?.last_seen_event_id,\n trustedLastSeenEventId: inboxState?.trusted_last_seen_event_id,\n untrustedLastSeenEventId: inboxState?.untrusted_last_seen_event_id,\n inboxTimelines: {\n trusted: inboxState?.inbox_timelines?.trusted && {\n status: inboxState.inbox_timelines.trusted.status,\n minEntryId: inboxState.inbox_timelines.trusted.min_entry_id,\n },\n untrusted: inboxState?.inbox_timelines?.untrusted && {\n status: inboxState.inbox_timelines.untrusted.status,\n minEntryId: inboxState.inbox_timelines.untrusted.min_entry_id,\n },\n },\n userId,\n };\n } catch (error) {\n console.error(\"Error parsing DM conversations:\", error);\n return {\n conversations: [],\n users: [],\n userId,\n };\n }\n}\n\n/**\n * Parse direct messages and return an array of DirectMessage objects.\n *\n * @param {any[]} messages - Array of messages to parse\n * @param {any} users - Object containing user information\n * @returns {DirectMessage[]} Array of DirectMessage objects\n */\nfunction parseDirectMessages(messages: any[], users: any): DirectMessage[] {\n try {\n return messages.map((msg: any) => ({\n id: msg.message_data.id,\n text: msg.message_data.text,\n senderId: msg.message_data.sender_id,\n recipientId: msg.message_data.recipient_id,\n createdAt: msg.message_data.time,\n mediaUrls: extractMediaUrls(msg.message_data),\n senderScreenName: users[msg.message_data.sender_id]?.screen_name,\n recipientScreenName: users[msg.message_data.recipient_id]?.screen_name,\n }));\n } catch (error) {\n console.error(\"Error parsing DMs:\", error);\n return [];\n }\n}\n\n/**\n * Extracts media URLs from message data.\n * @param {any} messageData - The message data containing entities with URLs and media.\n * @returns {string[] | undefined} - An array of media URLs if found, otherwise undefined.\n */\nfunction extractMediaUrls(messageData: any): string[] | undefined {\n const urls: string[] = [];\n\n // Extract URLs from entities if they exist\n if (messageData.entities?.urls) {\n messageData.entities.urls.forEach((url: any) => {\n urls.push(url.expanded_url);\n });\n }\n\n // Extract media URLs if they exist\n if (messageData.entities?.media) {\n messageData.entities.media.forEach((media: any) => {\n urls.push(media.media_url_https || media.media_url);\n });\n }\n\n return urls.length > 0 ? urls : undefined;\n}\n\n/**\n * Retrieves a list of direct message conversations for a specific user.\n *\n * @param {string} userId - The ID of the user for whom to fetch direct message conversations.\n * @param {TwitterAuth} auth - The TwitterAuth object containing authentication information.\n * @param {string} [cursor] - Optional parameter for fetching paginated results.\n * @returns {Promise<DirectMessagesResponse>} A Promise that resolves to the response containing direct message conversations.\n * @throws {Error} If authentication is not available to fetch direct messages or if the response is not successful.\n */\nexport async function getDirectMessageConversations(\n userId: string,\n auth: TwitterAuth,\n cursor?: string\n): Promise<DirectMessagesResponse> {\n if (!auth.isLoggedIn()) {\n throw new Error(\"Authentication required to fetch direct messages\");\n }\n\n const url =\n \"https://twitter.com/i/api/graphql/7s3kOODhC5vgXlO0OlqYdA/DMInboxTimeline\";\n const messageListUrl = \"https://x.com/i/api/1.1/dm/inbox_initial_state.json\";\n\n const params = new URLSearchParams();\n\n if (cursor) {\n params.append(\"cursor\", cursor);\n }\n\n const finalUrl = `${messageListUrl}${params.toString() ? `?${params.toString()}` : \"\"}`;\n const cookies = await auth.cookieJar().getCookies(url);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n \n const twitterHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(url),\n \"content-type\": \"application/json\",\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n ...Object.fromEntries(twitterHeaders.entries()),\n });\n\n const response = await fetch(finalUrl, {\n method: \"GET\",\n headers,\n });\n\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n // parse the response\n const data = await response.json();\n return parseDirectMessageConversations(data, userId);\n}\n\n/**\n * Sends a direct message on Twitter.\n *\n * @param {TwitterAuth} auth - The Twitter authentication object.\n * @param {string} conversation_id - The ID of the conversation to send the message to.\n * @param {string} text - The text of the message to send.\n * @returns {Promise<SendDirectMessageResponse>} A Promise that resolves with the response of sending the direct message.\n * @throws {Error} If authentication is required to send direct messages and the user is not logged in.\n */\nexport async function sendDirectMessage(\n auth: TwitterAuth,\n conversation_id: string,\n text: string\n): Promise<SendDirectMessageResponse> {\n if (!auth.isLoggedIn()) {\n throw new Error(\"Authentication required to send direct messages\");\n }\n\n const url =\n \"https://twitter.com/i/api/graphql/7s3kOODhC5vgXlO0OlqYdA/DMInboxTimeline\";\n const messageDmUrl = \"https://x.com/i/api/1.1/dm/new2.json\";\n\n const cookies = await auth.cookieJar().getCookies(url);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const twitterHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(url),\n \"content-type\": \"application/json\",\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n ...Object.fromEntries(twitterHeaders.entries()),\n });\n\n const payload = {\n conversation_id: `${conversation_id}`,\n recipient_ids: false,\n text: text,\n cards_platform: \"Web-12\",\n include_cards: 1,\n include_quote_count: true,\n dm_users: false,\n };\n\n const response = await fetch(messageDmUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify(payload),\n });\n\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n return await response.json();\n}\n","import { Headers } from \"headers-polyfill\";\nimport stringify from \"json-stable-stringify\";\nimport { addApiFeatures, bearerToken, requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport { type Profile, getEntityIdByScreenName } from \"./profile\";\nimport { getUserTimeline } from \"./timeline-async\";\nimport {\n type RelationshipTimeline,\n parseRelationshipTimeline,\n} from \"./timeline-relationship\";\nimport type { QueryProfilesResponse } from \"./timeline-v1\";\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 function getFollowing(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth\n): AsyncGenerator<Profile, void> {\n return getUserTimeline(userId, maxProfiles, (q, mt, c) => {\n return fetchProfileFollowing(q, mt, auth, c);\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 function getFollowers(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth\n): AsyncGenerator<Profile, void> {\n return getUserTimeline(userId, maxProfiles, (q, mt, c) => {\n return fetchProfileFollowers(q, mt, auth, c);\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 const timeline = await getFollowingTimeline(\n userId,\n maxProfiles,\n auth,\n cursor\n );\n\n return parseRelationshipTimeline(timeline);\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 const timeline = await getFollowersTimeline(\n userId,\n maxProfiles,\n auth,\n cursor\n );\n\n return parseRelationshipTimeline(timeline);\n}\n\n/**\n * Asynchronously fetches the timeline of accounts that a user is following.\n *\n * @param {string} userId - The ID of the user whose following timeline is to be retrieved.\n * @param {number} maxItems - The maximum number of items to fetch (limited to 50).\n * @param {TwitterAuth} auth - The authentication information for making the API request.\n * @param {string} [cursor] - Optional cursor to paginate the results.\n * @returns {Promise<RelationshipTimeline>} A Promise that resolves to the RelationshipTimeline object representing the following timeline.\n * @throws {Error} If the client is not logged-in for profile following.\n */\nasync function getFollowingTimeline(\n userId: string,\n maxItems: number,\n auth: TwitterAuth,\n cursor?: string\n): Promise<RelationshipTimeline> {\n if (!auth.isLoggedIn()) {\n throw new Error(\"Client is not logged-in for profile following.\");\n }\n\n if (maxItems > 50) {\n maxItems = 50;\n }\n\n const variables: Record<string, any> = {\n userId,\n count: maxItems,\n includePromotedContent: false,\n };\n\n const features = addApiFeatures({\n responsive_web_twitter_article_tweet_consumption_enabled: false,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_media_download_video_enabled: false,\n });\n\n if (cursor != null && cursor !== \"\") {\n variables.cursor = cursor;\n }\n\n const params = new URLSearchParams();\n params.set(\"features\", stringify(features) ?? \"\");\n params.set(\"variables\", stringify(variables) ?? \"\");\n\n const res = await requestApi<RelationshipTimeline>(\n `https://twitter.com/i/api/graphql/iSicc7LrzWGBgDPL0tM_TQ/Following?${params.toString()}`,\n auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n return res.value;\n}\n\n/**\n * Retrieves the followers timeline for a specific user.\n * @param userId The ID of the user whose followers timeline will be retrieved.\n * @param maxItems The maximum number of items to retrieve (up to 50).\n * @param auth The Twitter authentication credentials.\n * @param cursor (Optional) The cursor for pagination.\n * @returns A Promise that resolves with the RelationshipTimeline object.\n * @throws Error if the client is not logged in or if the API request fails.\n */\nasync function getFollowersTimeline(\n userId: string,\n maxItems: number,\n auth: TwitterAuth,\n cursor?: string\n): Promise<RelationshipTimeline> {\n if (!auth.isLoggedIn()) {\n throw new Error(\"Client is not logged-in for profile followers.\");\n }\n\n if (maxItems > 50) {\n maxItems = 50;\n }\n\n const variables: Record<string, any> = {\n userId,\n count: maxItems,\n includePromotedContent: false,\n };\n\n const features = addApiFeatures({\n responsive_web_twitter_article_tweet_consumption_enabled: false,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_media_download_video_enabled: false,\n });\n\n if (cursor != null && cursor !== \"\") {\n variables.cursor = cursor;\n }\n\n const params = new URLSearchParams();\n params.set(\"features\", stringify(features) ?? \"\");\n params.set(\"variables\", stringify(variables) ?? \"\");\n\n const res = await requestApi<RelationshipTimeline>(\n `https://twitter.com/i/api/graphql/rRXFSG5vR6drKr5M37YOTw/Followers?${params.toString()}`,\n auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n return res.value;\n}\n\n/**\n * Makes a request to follow a user on Twitter.\n *\n * @param {string} username - The username of the user to follow.\n * @param {TwitterAuth} auth - Twitter authentication object.\n * @returns {Promise<Response>} - A Promise that resolves with the response data.\n * @throws {Error} - If the user is not logged in, or if an error occurs during the follow process.\n */\nexport async function followUser(\n username: string,\n auth: TwitterAuth\n): Promise<Response> {\n // Check if the user is logged in\n if (!(await auth.isLoggedIn())) {\n throw new Error(\"Must be logged in to follow users\");\n }\n // Get user ID from username\n const userIdResult = await getEntityIdByScreenName(username, auth);\n\n if (!userIdResult.success) {\n throw new Error(\n `Failed to get user ID: ${(userIdResult as any).err.message}`\n );\n }\n\n const userId = userIdResult.value;\n\n // Prepare the request body\n const requestBody = {\n include_profile_interstitial_type: \"1\",\n skip_status: \"true\",\n user_id: userId,\n };\n\n // Prepare the headers\n const headers = new Headers({\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n Referer: `https://twitter.com/${username}`,\n \"X-Twitter-Active-User\": \"yes\",\n \"X-Twitter-Auth-Type\": \"OAuth2Session\",\n \"X-Twitter-Client-Language\": \"en\",\n Authorization: `Bearer ${bearerToken}`,\n });\n\n // Install auth headers\n await auth.installTo(\n headers,\n \"https://api.twitter.com/1.1/friendships/create.json\"\n );\n\n // Make the follow request using auth.fetch\n const res = await auth.fetch(\n \"https://api.twitter.com/1.1/friendships/create.json\",\n {\n method: \"POST\",\n headers,\n body: new URLSearchParams(requestBody).toString(),\n credentials: \"include\",\n }\n );\n\n if (!res.ok) {\n throw new Error(`Failed to follow user: ${res.statusText}`);\n }\n\n const data = await res.json();\n\n return new Response(JSON.stringify(data), {\n status: 200,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n });\n}\n","import type { Profile } from \"./profile\";\nimport type { Tweet } from \"./tweets\";\n\n/**\n * Interface representing the response when fetching profiles.\n * @typedef {Object} FetchProfilesResponse\n * @property {Profile[]} profiles - An array of profiles.\n * @property {string} [next] - Optional: A string representing the next page to fetch.\n */\nexport interface FetchProfilesResponse {\n profiles: Profile[];\n next?: string;\n}\n\n/**\n * Function type for fetching profiles.\n *\n * @param {string} query - The search query for profiles.\n * @param {number} maxProfiles - The maximum number of profiles to retrieve.\n * @param {string | undefined} cursor - The cursor for fetching the next set of profiles.\n * @returns {Promise<FetchProfilesResponse>} - A promise that resolves to a FetchProfilesResponse object.\n */\nexport type FetchProfiles = (\n query: string,\n maxProfiles: number,\n cursor: string | undefined\n) => Promise<FetchProfilesResponse>;\n\n/**\n * Interface representing the response from a fetch tweets API request.\n * @typedef {Object} FetchTweetsResponse\n * @property {Tweet[]} tweets - An array of Tweet objects.\n * @property {string} [next] - Optional: a string representing the next page token.\n */\nexport interface FetchTweetsResponse {\n tweets: Tweet[];\n next?: string;\n}\n\n/**\n * Function to fetch tweets based on a query and maximum number of tweets.\n * @param {string} query - The search query for tweets.\n * @param {number} maxTweets - The maximum number of tweets to fetch.\n * @param {string | undefined} cursor - The cursor for pagination, if any.\n * @returns {Promise<FetchTweetsResponse>} A promise that resolves to the response containing fetched tweets.\n */\nexport type FetchTweets = (\n query: string,\n maxTweets: number,\n cursor: string | undefined\n) => Promise<FetchTweetsResponse>;\n\n/**\n * Asynchronously generates user profiles from a timeline based on the specified query and maximum number of profiles to fetch.\n * @param {string} query - The query string to search for profiles.\n * @param {number} maxProfiles - The maximum number of profiles to return.\n * @param {FetchProfiles} fetchFunc - The function to fetch profiles based on the query, maxProfiles, and cursor.\n * @returns {AsyncGenerator<Profile, void>} An asynchronous generator that yields profiles from the timeline.\n */\nexport async function* getUserTimeline(\n query: string,\n maxProfiles: number,\n fetchFunc: FetchProfiles\n): AsyncGenerator<Profile, void> {\n let nProfiles = 0;\n let cursor: string | undefined = undefined;\n let consecutiveEmptyBatches = 0;\n while (nProfiles < maxProfiles) {\n const batch: FetchProfilesResponse = await fetchFunc(\n query,\n maxProfiles,\n cursor\n );\n\n const { profiles, next } = batch;\n cursor = next;\n\n if (profiles.length === 0) {\n consecutiveEmptyBatches++;\n if (consecutiveEmptyBatches > 5) break;\n } else consecutiveEmptyBatches = 0;\n\n for (const profile of profiles) {\n if (nProfiles < maxProfiles) yield profile;\n else break;\n nProfiles++;\n }\n\n if (!next) break;\n }\n}\n\n/**\n * Async generator function that fetches and yields tweets from a timeline based on\n * the provided query and maximum number of tweets to retrieve.\n * @param {string} query - The search query for retrieving tweets.\n * @param {number} maxTweets - The maximum number of tweets to retrieve.\n * @param {FetchTweets} fetchFunc - The function to fetch tweets based on the query, maxTweets, and cursor.\n * @returns {AsyncGenerator<Tweet, void>} An async generator that yields retrieved tweets.\n */\nexport async function* getTweetTimeline(\n query: string,\n maxTweets: number,\n fetchFunc: FetchTweets\n): AsyncGenerator<Tweet, void> {\n let nTweets = 0;\n let cursor: string | undefined = undefined;\n while (nTweets < maxTweets) {\n const batch: FetchTweetsResponse = await fetchFunc(\n query,\n maxTweets,\n cursor\n );\n\n const { tweets, next } = batch;\n\n if (tweets.length === 0) {\n break;\n }\n\n for (const tweet of tweets) {\n if (nTweets < maxTweets) {\n cursor = next;\n yield tweet;\n } else {\n break;\n }\n\n nTweets++;\n }\n }\n}\n","import { type Profile, parseProfile } from \"./profile\";\nimport type { QueryProfilesResponse } from \"./timeline-v1\";\nimport type { TimelineUserResultRaw } from \"./timeline-v2\";\n\n/**\n * Interface for raw content of a relationship entry item.\n * @typedef { Object } RelationshipEntryItemContentRaw\n * @property { string } [itemType] - The type of item.\n * @property { string } [userDisplayType] - The display type for the user.\n * @property { Object } [user_results] - The results of the user.\n * @property { Object } [user_results.result] - The raw data of the timeline user result.\n */\nexport interface RelationshipEntryItemContentRaw {\n itemType?: string;\n userDisplayType?: string;\n user_results?: {\n result?: TimelineUserResultRaw;\n };\n}\n\n/**\n * Interface representing a raw relationship entry.\n * @interface\n * @property {string} entryId - The unique identifier for the entry.\n * @property {string} sortIndex - The sorting index for the entry.\n * @property {Object} [content] - Additional content for the entry.\n * @property {string} [content.cursorType] - The type of cursor.\n * @property {string} [content.entryType] - The type of entry.\n * @property {string} [content.__typename] - The typename of the content.\n * @property {string} [content.value] - The value of the content.\n * @property {RelationshipEntryItemContentRaw} [content.itemContent] - The raw item content for the entry.\n */\n\nexport interface RelationshipEntryRaw {\n entryId: string;\n sortIndex: string;\n content?: {\n cursorType?: string;\n entryType?: string;\n __typename?: string;\n value?: string;\n itemContent?: RelationshipEntryItemContentRaw;\n };\n}\n\n/**\n * Interface representing a relationship timeline.\n * @property {object} data - Optional property containing user result timeline instructions.\n * @property {object} data.user - Optional property containing user information.\n * @property {object} data.user.result - Optional property containing result information.\n * @property {object} data.user.result.timeline - Optional property containing timeline instructions.\n * @property {object} data.user.result.timeline.timeline - Optional property containing timeline instructions.\n * @property {object[]} data.user.result.timeline.timeline.instructions - Optional array of relationship entries.\n * @property {object} data.user.result.timeline.timeline.instructions.entry - Optional relationship entry object.\n * @property {object[]} data.user.result.timeline.timeline.instructions.type - Optional string representing type of timeline instructions.\n */\nexport interface RelationshipTimeline {\n data?: {\n user?: {\n result?: {\n timeline?: {\n timeline?: {\n instructions?: {\n entries?: RelationshipEntryRaw[];\n entry?: RelationshipEntryRaw;\n type?: string;\n }[];\n };\n };\n };\n };\n };\n}\n\n/**\n * Parses the given RelationshipTimeline data to extract profiles and cursors.\n * @param timeline The RelationshipTimeline data to parse.\n * @returns The QueryProfilesResponse object containing profiles, next cursor, and previous cursor.\n */\nexport function parseRelationshipTimeline(\n timeline: RelationshipTimeline\n): QueryProfilesResponse {\n let bottomCursor: string | undefined;\n let topCursor: string | undefined;\n const profiles: Profile[] = [];\n const instructions =\n timeline.data?.user?.result?.timeline?.timeline?.instructions ?? [];\n\n for (const instruction of instructions) {\n if (\n instruction.type === \"TimelineAddEntries\" ||\n instruction.type === \"TimelineReplaceEntry\"\n ) {\n if (instruction.entry?.content?.cursorType === \"Bottom\") {\n bottomCursor = instruction.entry.content.value;\n continue;\n }\n\n if (instruction.entry?.content?.cursorType === \"Top\") {\n topCursor = instruction.entry.content.value;\n continue;\n }\n\n const entries = instruction.entries ?? [];\n for (const entry of entries) {\n const itemContent = entry.content?.itemContent;\n if (itemContent?.userDisplayType === \"User\") {\n const userResultRaw = itemContent.user_results?.result;\n\n if (userResultRaw?.legacy) {\n const profile = parseProfile(\n userResultRaw.legacy,\n userResultRaw.is_blue_verified\n );\n\n if (!profile.userId) {\n profile.userId = userResultRaw.rest_id;\n }\n\n profiles.push(profile);\n }\n } else if (entry.content?.cursorType === \"Bottom\") {\n bottomCursor = entry.content.value;\n } else if (entry.content?.cursorType === \"Top\") {\n topCursor = entry.content.value;\n }\n }\n }\n }\n\n return { profiles, next: bottomCursor, previous: topCursor };\n}\n","import stringify from \"json-stable-stringify\";\nimport { addApiFeatures, requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport type { Profile } from \"./profile\";\nimport { getTweetTimeline, getUserTimeline } from \"./timeline-async\";\nimport {\n type SearchTimeline,\n parseSearchTimelineTweets,\n parseSearchTimelineUsers,\n} from \"./timeline-search\";\nimport type { QueryProfilesResponse, QueryTweetsResponse } from \"./timeline-v1\";\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\nexport function searchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n auth: TwitterAuth\n): AsyncGenerator<Tweet, void> {\n return getTweetTimeline(query, maxTweets, (q, mt, c) => {\n return fetchSearchTweets(q, mt, searchMode, auth, c);\n });\n}\n\nexport function searchProfiles(\n query: string,\n maxProfiles: number,\n auth: TwitterAuth\n): AsyncGenerator<Profile, void> {\n return getUserTimeline(query, maxProfiles, (q, mt, c) => {\n return fetchSearchProfiles(q, mt, auth, c);\n });\n}\n\nexport async function fetchSearchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n auth: TwitterAuth,\n cursor?: string\n): Promise<QueryTweetsResponse> {\n const timeline = await getSearchTimeline(\n query,\n maxTweets,\n searchMode,\n auth,\n cursor\n );\n\n return parseSearchTimelineTweets(timeline);\n}\n\nexport async function fetchSearchProfiles(\n query: string,\n maxProfiles: number,\n auth: TwitterAuth,\n cursor?: string\n): Promise<QueryProfilesResponse> {\n const timeline = await getSearchTimeline(\n query,\n maxProfiles,\n SearchMode.Users,\n auth,\n cursor\n );\n\n return parseSearchTimelineUsers(timeline);\n}\n\nasync function getSearchTimeline(\n query: string,\n maxItems: number,\n searchMode: SearchMode,\n auth: TwitterAuth,\n cursor?: string\n): Promise<SearchTimeline> {\n if (!auth.isLoggedIn()) {\n throw new Error(\"Client is not logged-in for search.\");\n }\n\n if (maxItems > 50) {\n maxItems = 50;\n }\n\n const variables: Record<string, any> = {\n rawQuery: query,\n count: maxItems,\n querySource: \"typed_query\",\n product: \"Top\",\n };\n\n const features = addApiFeatures({\n longform_notetweets_inline_media_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n responsive_web_media_download_video_enabled: false,\n responsive_web_twitter_article_tweet_consumption_enabled: false,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n interactive_text_enabled: false,\n responsive_web_text_conversations_enabled: false,\n vibe_api_enabled: false,\n });\n\n const fieldToggles: Record<string, any> = {\n withArticleRichContentState: false,\n };\n\n if (cursor != null && cursor !== \"\") {\n variables.cursor = cursor;\n }\n\n switch (searchMode) {\n case SearchMode.Latest:\n variables.product = \"Latest\";\n break;\n case SearchMode.Photos:\n variables.product = \"Photos\";\n break;\n case SearchMode.Videos:\n variables.product = \"Videos\";\n break;\n case SearchMode.Users:\n variables.product = \"People\";\n break;\n default:\n break;\n }\n\n const params = new URLSearchParams();\n params.set(\"features\", stringify(features) ?? \"\");\n params.set(\"fieldToggles\", stringify(fieldToggles) ?? \"\");\n params.set(\"variables\", stringify(variables) ?? \"\");\n\n const res = await requestApi<SearchTimeline>(\n `https://api.twitter.com/graphql/gkjsKepM6gl_HmFWoWKfgg/SearchTimeline?${params.toString()}`,\n auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n return res.value;\n}\n\n/**\n * Fetches one page of tweets that quote a given tweet ID.\n * This function does not handle pagination.\n * All comments must remain in English.\n *\n * @param quotedTweetId The tweet ID you want quotes of.\n * @param maxTweets Maximum number of tweets to return in one page.\n * @param auth The TwitterAuth object.\n * @param cursor Optional pagination cursor for fetching further pages.\n * @returns A promise that resolves to a QueryTweetsResponse containing tweets and the next cursor.\n */\nexport async function fetchQuotedTweetsPage(\n quotedTweetId: string,\n maxTweets: number,\n auth: TwitterAuth,\n cursor?: string\n): Promise<QueryTweetsResponse> {\n if (maxTweets > 50) {\n maxTweets = 50;\n }\n\n // Build the rawQuery and variables\n const variables: Record<string, any> = {\n rawQuery: `quoted_tweet_id:${quotedTweetId}`,\n count: maxTweets,\n querySource: \"tdqt\",\n product: \"Top\",\n };\n\n if (cursor && cursor !== \"\") {\n variables.cursor = cursor;\n }\n\n const features = addApiFeatures({\n profile_label_improvements_pcf_label_in_post_enabled: true,\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n premium_content_api_read_enabled: false,\n communities_web_enable_tweet_community_results_fetch: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n responsive_web_grok_analyze_button_fetch_trends_enabled: false,\n responsive_web_grok_analyze_post_followups_enabled: true,\n responsive_web_jetfuel_frame: false,\n responsive_web_grok_share_attachment_enabled: true,\n articles_preview_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n rweb_video_timestamps_enabled: true,\n longform_notetweets_rich_text_read_enabled: true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_grok_image_annotation_enabled: false,\n responsive_web_enhance_cards_enabled: false,\n });\n\n const fieldToggles: Record<string, any> = {\n withArticleRichContentState: false,\n };\n\n const params = new URLSearchParams();\n params.set(\"features\", stringify(features) ?? \"\");\n params.set(\"fieldToggles\", stringify(fieldToggles) ?? \"\");\n params.set(\"variables\", stringify(variables) ?? \"\");\n\n const url = `https://x.com/i/api/graphql/1BP5aKg8NvTNvRCyyCyq8g/SearchTimeline?${params.toString()}`;\n\n // Perform the request\n const res = await requestApi(url, auth);\n if (!res.success) {\n throw (res as any).err;\n }\n\n // Force cast for TypeScript\n const timeline = res.value as any;\n // Use parseSearchTimelineTweets to convert timeline data\n return parseSearchTimelineTweets(timeline);\n}\n\n/**\n * Creates an async generator, yielding pages of quotes for a given tweet ID.\n * It prevents infinite loop by checking if the next cursor hasn't changed.\n */\nexport async function* searchQuotedTweets(\n quotedTweetId: string,\n maxTweets: number,\n auth: TwitterAuth\n): AsyncGenerator<QueryTweetsResponse> {\n let cursor: string | undefined;\n\n while (true) {\n const response = await fetchQuotedTweetsPage(\n quotedTweetId,\n maxTweets,\n auth,\n cursor\n );\n yield response;\n\n // Prevent infinite loop if the API keeps returning the same cursor\n if (!response.next || response.next === cursor) {\n break;\n }\n\n // Update cursor for the next iteration\n cursor = response.next;\n }\n}\n","/**\n * Defines a type that ensures a specified property in an object is\n * not nullable or undefined.\n * @template T - The type of the object.\n * @template K - The keyof type representing the keys of the object.\n * @param {T} T - The object type.\n * @param {K} K - The key type of the object.\n * @returns {Object} - Returns a new type that includes all properties of the\n * original object with the specified key set to be non-nullable.\n */\nexport type NonNullableField<T, K extends keyof T> = {\n [P in K]-?: T[P];\n} & T;\n\n/**\n * Checks if the specified field is defined in the object.\n *\n * @template T - The type of the object\n * @template K - The key of the field\n * @param {K} key - The key of the field to check\n * @returns {(value: T) => value is NonNullableField<T, K>} A function that checks if the field is defined\n */\nexport function isFieldDefined<T, K extends keyof T>(key: K) {\n return (value: T): value is NonNullableField<T, K> => isDefined(value[key]);\n}\n\n/**\n * Check if a value is defined (not null or undefined).\n * @template T\n * @param {T | null | undefined} value - The value to check.\n * @return {value is T} Returns true if the value is defined, false otherwise.\n */\nexport function isDefined<T>(value: T | null | undefined): value is T {\n return value != null;\n}\n","import type { LegacyTweetRaw, TimelineMediaExtendedRaw } from \"./timeline-v1\";\nimport type { Photo, Video } from \"./tweets\";\nimport { type NonNullableField, isFieldDefined } from \"./type-util\";\n\nconst reHashtag = /\\B(\\#\\S+\\b)/g;\nconst reCashtag = /\\B(\\$\\S+\\b)/g;\nconst reTwitterUrl = /https:(\\/\\/t\\.co\\/([A-Za-z0-9]|[A-Za-z]){10})/g;\nconst reUsername = /\\B(\\@\\S{1,15}\\b)/g;\n\n/**\n * Parses the media groups from the provided array of TimelineMediaExtendedRaw objects\n * to extract photos and videos along with the sensitive content information.\n *\n * @param {TimelineMediaExtendedRaw[]} media - The array of TimelineMediaExtendedRaw objects to parse\n * @returns {{ sensitiveContent?: boolean, photos: Photo[], videos: Video[] }} - An object containing\n * the sensitive content boolean flag, an array of photos, and an array of videos\n */\nexport function parseMediaGroups(media: TimelineMediaExtendedRaw[]): {\n sensitiveContent?: boolean;\n photos: Photo[];\n videos: Video[];\n} {\n const photos: Photo[] = [];\n const videos: Video[] = [];\n let sensitiveContent: boolean | undefined = undefined;\n\n for (const m of media\n .filter(isFieldDefined(\"id_str\"))\n .filter(isFieldDefined(\"media_url_https\"))) {\n if (m.type === \"photo\") {\n photos.push({\n id: m.id_str,\n url: m.media_url_https,\n alt_text: m.ext_alt_text,\n });\n } else if (m.type === \"video\") {\n videos.push(parseVideo(m));\n }\n\n const sensitive = m.ext_sensitive_media_warning;\n if (sensitive != null) {\n sensitiveContent =\n sensitive.adult_content ||\n sensitive.graphic_violence ||\n sensitive.other;\n }\n }\n\n return { sensitiveContent, photos, videos };\n}\n\n/**\n * Parses the video information from the given raw media object.\n *\n * @param {NonNullableField<TimelineMediaExtendedRaw, \"id_str\" | \"media_url_https\">} m The raw media object containing the video information.\n * @returns {Video} The parsed video object with id, preview, and URL.\n */\nfunction parseVideo(\n m: NonNullableField<TimelineMediaExtendedRaw, \"id_str\" | \"media_url_https\">\n): Video {\n const video: Video = {\n id: m.id_str,\n preview: m.media_url_https,\n };\n\n let maxBitrate = 0;\n const variants = m.video_info?.variants ?? [];\n for (const variant of variants) {\n const bitrate = variant.bitrate;\n if (bitrate != null && bitrate > maxBitrate && variant.url != null) {\n let variantUrl = variant.url;\n const stringStart = 0;\n const tagSuffixIdx = variantUrl.indexOf(\"?tag=10\");\n if (tagSuffixIdx !== -1) {\n variantUrl = variantUrl.substring(stringStart, tagSuffixIdx + 1);\n }\n\n video.url = variantUrl;\n maxBitrate = bitrate;\n }\n }\n\n return video;\n}\n\n/**\n * Reconstructs the tweet HTML by parsing the tweet text and adding links to hashtags, cashtags, usernames,\n * and converting Twitter URLs. Also adds images and videos to the HTML.\n *\n * @param {LegacyTweetRaw} tweet The raw tweet object containing the full text of the tweet.\n * @param {Photo[]} photos Array of photo objects associated with the tweet.\n * @param {Video[]} videos Array of video objects associated with the tweet.\n * @returns {string} The reconstructed HTML for the tweet.\n */\nexport function reconstructTweetHtml(\n tweet: LegacyTweetRaw,\n photos: Photo[],\n videos: Video[]\n): string {\n const media: string[] = [];\n\n // HTML parsing with regex :)\n let html = tweet.full_text ?? \"\";\n\n html = html.replace(reHashtag, linkHashtagHtml);\n html = html.replace(reCashtag, linkCashtagHtml);\n html = html.replace(reUsername, linkUsernameHtml);\n html = html.replace(reTwitterUrl, unwrapTcoUrlHtml(tweet, media));\n\n for (const { url } of photos) {\n if (media.indexOf(url) !== -1) {\n continue;\n }\n\n html += `<br><img src=\"${url}\"/>`;\n }\n\n for (const { preview: url } of videos) {\n if (media.indexOf(url) !== -1) {\n continue;\n }\n\n html += `<br><img src=\"${url}\"/>`;\n }\n\n html = html.replace(/\\n/g, \"<br>\");\n\n return html;\n}\n\n/**\n * Generates an HTML link for a hashtag by removing the '#' symbol\n * and creating a Twitter hashtag link.\n *\n * @param hashtag - The hashtag to generate the link for\n * @returns The HTML link for the specified hashtag\n */\nfunction linkHashtagHtml(hashtag: string) {\n return `<a href=\"https://twitter.com/hashtag/${hashtag.replace(\"#\", \"\")}\">${hashtag}</a>`;\n}\n\n/**\n * Generates HTML anchor link for a cashtag.\n * @param {string} cashtag - The cashtag to link.\n * @returns {string} The HTML anchor link for the cashtag.\n */\nfunction linkCashtagHtml(cashtag: string) {\n return `<a href=\"https://twitter.com/search?q=%24${cashtag.replace(\"$\", \"\")}\">${cashtag}</a>`;\n}\n\n/**\n * Generates HTML for linking a Twitter username.\n *\n * @param {string} username - The Twitter username to generate link for.\n * @returns {string} - The HTML string for the linked username.\n */\nfunction linkUsernameHtml(username: string) {\n return `<a href=\"https://twitter.com/${username.replace(\"@\", \"\")}\">${username}</a>`;\n}\n\n/**\n * Unwraps the t.co URL in a tweet HTML based on the provided tweet object and founded media URLs.\n * @param {LegacyTweetRaw} tweet - The tweet object containing URLs and media entities.\n * @param {string[]} foundedMedia - An array to store the founded media URLs.\n * @returns {function(string): string} - A function that takes a t.co URL and returns the corresponding HTML representation.\n */\nfunction unwrapTcoUrlHtml(tweet: LegacyTweetRaw, foundedMedia: string[]) {\n return (tco: string) => {\n for (const entity of tweet.entities?.urls ?? []) {\n if (tco === entity.url && entity.expanded_url != null) {\n return `<a href=\"${entity.expanded_url}\">${tco}</a>`;\n }\n }\n\n for (const entity of tweet.extended_entities?.media ?? []) {\n if (tco === entity.url && entity.media_url_https != null) {\n foundedMedia.push(entity.media_url_https);\n return `<br><a href=\"${tco}\"><img src=\"${entity.media_url_https}\"/></a>`;\n }\n }\n\n return tco;\n };\n}\n","import type { LegacyUserRaw } from \"./profile\";\nimport { parseMediaGroups, reconstructTweetHtml } from \"./timeline-tweet-util\";\nimport type {\n LegacyTweetRaw,\n ParseTweetResult,\n QueryTweetsResponse,\n SearchResultRaw,\n TimelineResultRaw,\n} from \"./timeline-v1\";\nimport type { Tweet } from \"./tweets\";\nimport { isFieldDefined } from \"./type-util\";\n\n/**\n * Interface representing raw data for a user result in a timeline.\n * @property {string} [rest_id] - The REST ID of the user.\n * @property {LegacyUserRaw} [legacy] - The legacy user data.\n * @property {boolean} [is_blue_verified] - Indicates if the user is blue verified.\n */\nexport interface TimelineUserResultRaw {\n rest_id?: string;\n legacy?: LegacyUserRaw;\n is_blue_verified?: boolean;\n}\n\n/**\n * Interface representing the raw content of a timeline entry item.\n * @typedef {Object} TimelineEntryItemContentRaw\n * @property {string} [itemType] - The type of the item.\n * @property {string} [tweetDisplayType] - The display type of the tweet.\n * @property {Object} [tweetResult] - The result of the tweet.\n * @property {Object} [tweet_results] - The results of the tweet.\n * @property {string} [userDisplayType] - The display type of the user.\n * @property {Object} [user_results] - The results of the user.\n */\n\nexport interface TimelineEntryItemContentRaw {\n itemType?: string;\n tweetDisplayType?: string;\n tweetResult?: {\n result?: TimelineResultRaw;\n };\n tweet_results?: {\n result?: TimelineResultRaw;\n };\n userDisplayType?: string;\n user_results?: {\n result?: TimelineUserResultRaw;\n };\n}\n\n/**\n * Interface representing a raw Timeline Entry.\n * @typedef { Object } TimelineEntryRaw\n * @property { string } entryId - The unique identifier of the entry.\n * @property { Object } [content] - The content of the entry.\n * @property { string } [content.cursorType] - The cursor type of the content.\n * @property { string } [content.value] - The value of the content.\n * @property {Object[]} [content.items] - An array of items within the content.\n * @property { string } [content.items.entryId] - The unique identifier of an item.\n * @property { Object } [content.items.item] - The item within the content.\n * @property { Object } [content.items.item.content] - The content of the item.\n * @property { Object } [content.items.item.itemContent] - The item content of the item.\n */\nexport interface TimelineEntryRaw {\n entryId: string;\n content?: {\n cursorType?: string;\n value?: string;\n items?: {\n entryId?: string;\n item?: {\n content?: TimelineEntryItemContentRaw;\n itemContent?: SearchEntryItemContentRaw;\n };\n }[];\n itemContent?: TimelineEntryItemContentRaw;\n };\n}\n\n/**\n * Interface representing the raw content of a search entry item.\n * @interface\n * @property {string} [tweetDisplayType] - The display type of the tweet.\n * @property {Object} [tweet_results] - The results of the tweet search.\n * @property {Object} [tweet_results.result] - The raw search result of the tweet.\n * @property {string} [userDisplayType] - The display type of the user.\n * @property {Object} [user_results] - The results of the user search.\n * @property {Object} [user_results.result] - The raw search result of the user timeline.\n */\nexport interface SearchEntryItemContentRaw {\n tweetDisplayType?: string;\n tweet_results?: {\n result?: SearchResultRaw;\n };\n userDisplayType?: string;\n user_results?: {\n result?: TimelineUserResultRaw;\n };\n}\n\n/**\n * Interface representing a raw search entry.\n * @typedef { Object } SearchEntryRaw\n * @property { string } entryId - The unique identifier of the entry.\n * @property { string } sortIndex - The sorting index of the entry.\n * @property { Object } [content] - The content details of the entry.\n * @property { string } [content.cursorType] - The type of cursor associated with the entry content.\n * @property { string } [content.entryType] - The type of entry.\n * @property { string } [content.__typename] - The typename of the content.\n * @property { string } [content.value] - The value associated with the entry content.\n * @property {Array<Object>} [content.items] - An array of items associated with the entry.\n * @property { Object } [content.items.item] - An item object associated with the entry.\n * @property { Object } [content.items.item.content] - The content details of the item associated with the entry.\n * @property { Object } [content.itemContent] - The content details of the item associated with the entry.\n */\nexport interface SearchEntryRaw {\n entryId: string;\n sortIndex: string;\n content?: {\n cursorType?: string;\n entryType?: string;\n __typename?: string;\n value?: string;\n items?: {\n item?: {\n content?: SearchEntryItemContentRaw;\n };\n }[];\n itemContent?: SearchEntryItemContentRaw;\n };\n}\n\n/**\n * Interface representing a timeline instruction.\n * @typedef {Object} TimelineInstruction\n * @property {TimelineEntryRaw[]} [entries] - An array of timeline entry raw objects.\n * @property {TimelineEntryRaw} [entry] - A single timeline entry raw object.\n * @property {string} [type] - The type of the timeline instruction.\n */\nexport interface TimelineInstruction {\n entries?: TimelineEntryRaw[];\n entry?: TimelineEntryRaw;\n type?: string;\n}\n\n/**\n * Interface representing version 2 of a timeline object.\n * @typedef {Object} TimelineV2\n * @property {Object} data - Data object containing user information.\n * @property {Object} data.user - User object containing result information.\n * @property {Object} data.user.result - Result object containing timeline_v2 information.\n * @property {Object} data.user.result.timeline_v2 - Timeline_v2 object containing timeline information.\n * @property {Object} data.user.result.timeline_v2.timeline - Timeline object containing instructions.\n * @property {Array<TimelineInstruction>} data.user.result.timeline_v2.timeline.instructions - Array of timeline instructions.\n */\nexport interface TimelineV2 {\n data?: {\n user?: {\n result?: {\n timeline_v2?: {\n timeline?: {\n instructions?: TimelineInstruction[];\n };\n };\n };\n };\n };\n}\n\n/**\n * Represents a threaded conversation with optional data.\n * @interface\n * @property {Object} data - Optional data for the conversation.\n * @property {Object} data.threaded_conversation_with_injections_v2 - Optional object containing instructions.\n * @property {TimelineInstruction[]} data.threaded_conversation_with_injections_v2.instructions - Array of timeline instructions.\n */\nexport interface ThreadedConversation {\n data?: {\n threaded_conversation_with_injections_v2?: {\n instructions?: TimelineInstruction[];\n };\n };\n}\n\n/**\n * Parses a legacy tweet object and returns a ParseTweetResult.\n * @param {LegacyUserRaw} [user] - The legacy user object.\n * @param {LegacyTweetRaw} [tweet] - The legacy tweet object.\n * @returns {ParseTweetResult} The result of parsing the legacy tweet.\n */\nexport function parseLegacyTweet(\n user?: LegacyUserRaw,\n tweet?: LegacyTweetRaw\n): ParseTweetResult {\n if (tweet == null) {\n return {\n success: false,\n err: new Error(\"Tweet was not found in the timeline object.\"),\n };\n }\n\n if (user == null) {\n return {\n success: false,\n err: new Error(\"User was not found in the timeline object.\"),\n };\n }\n\n if (!tweet.id_str) {\n if (!tweet.conversation_id_str) {\n return {\n success: false,\n err: new Error(\"Tweet ID was not found in object.\"),\n };\n }\n\n tweet.id_str = tweet.conversation_id_str;\n }\n\n const hashtags = tweet.entities?.hashtags ?? [];\n const mentions = tweet.entities?.user_mentions ?? [];\n const media = tweet.extended_entities?.media ?? [];\n const pinnedTweets = new Set<string | undefined>(\n user.pinned_tweet_ids_str ?? []\n );\n const urls = tweet.entities?.urls ?? [];\n const { photos, videos, sensitiveContent } = parseMediaGroups(media);\n\n const tw: Tweet = {\n bookmarkCount: tweet.bookmark_count,\n conversationId: tweet.conversation_id_str,\n id: tweet.id_str,\n hashtags: hashtags\n .filter(isFieldDefined(\"text\"))\n .map((hashtag) => hashtag.text),\n likes: tweet.favorite_count,\n mentions: mentions.filter(isFieldDefined(\"id_str\")).map((mention) => ({\n id: mention.id_str,\n username: mention.screen_name,\n name: mention.name,\n })),\n name: user.name,\n permanentUrl: `https://twitter.com/${user.screen_name}/status/${tweet.id_str}`,\n photos,\n replies: tweet.reply_count,\n retweets: tweet.retweet_count,\n text: tweet.full_text,\n thread: [],\n urls: urls\n .filter(isFieldDefined(\"expanded_url\"))\n .map((url) => url.expanded_url),\n userId: tweet.user_id_str,\n username: user.screen_name,\n videos,\n isQuoted: false,\n isReply: false,\n isRetweet: false,\n isPin: false,\n sensitiveContent: false,\n };\n\n if (tweet.created_at) {\n tw.timeParsed = new Date(Date.parse(tweet.created_at));\n tw.timestamp = Math.floor(tw.timeParsed.valueOf() / 1000);\n }\n\n if (tweet.place?.id) {\n tw.place = tweet.place;\n }\n\n const quotedStatusIdStr = tweet.quoted_status_id_str;\n const inReplyToStatusIdStr = tweet.in_reply_to_status_id_str;\n const retweetedStatusIdStr = tweet.retweeted_status_id_str;\n const retweetedStatusResult = tweet.retweeted_status_result?.result;\n\n if (quotedStatusIdStr) {\n tw.isQuoted = true;\n tw.quotedStatusId = quotedStatusIdStr;\n }\n\n if (inReplyToStatusIdStr) {\n tw.isReply = true;\n tw.inReplyToStatusId = inReplyToStatusIdStr;\n }\n\n if (retweetedStatusIdStr || retweetedStatusResult) {\n tw.isRetweet = true;\n tw.retweetedStatusId = retweetedStatusIdStr;\n\n if (retweetedStatusResult) {\n const parsedResult = parseLegacyTweet(\n retweetedStatusResult?.core?.user_results?.result?.legacy,\n retweetedStatusResult?.legacy\n );\n\n if (parsedResult.success) {\n tw.retweetedStatus = parsedResult.tweet;\n }\n }\n }\n\n const views = Number.parseInt(tweet.ext_views?.count ?? \"\");\n if (!Number.isNaN(views)) {\n tw.views = views;\n }\n\n if (pinnedTweets.has(tweet.id_str)) {\n // TODO: Update tests so this can be assigned at the tweet declaration\n tw.isPin = true;\n }\n\n if (sensitiveContent) {\n // TODO: Update tests so this can be assigned at the tweet declaration\n tw.sensitiveContent = true;\n }\n\n tw.html = reconstructTweetHtml(tweet, tw.photos, tw.videos);\n\n return { success: true, tweet: tw };\n}\n\n/**\n * Parses a raw timeline result object into a ParseTweetResult object.\n *\n * @param {TimelineResultRaw} result - The raw timeline result object to parse.\n * @returns {ParseTweetResult} The parsed tweet result object.\n */\nfunction parseResult(result?: TimelineResultRaw): ParseTweetResult {\n const noteTweetResultText =\n result?.note_tweet?.note_tweet_results?.result?.text;\n\n if (result?.legacy && noteTweetResultText) {\n result.legacy.full_text = noteTweetResultText;\n }\n\n const tweetResult = parseLegacyTweet(\n result?.core?.user_results?.result?.legacy,\n result?.legacy\n );\n if (!tweetResult.success) {\n return tweetResult;\n }\n\n if (!tweetResult.tweet.views && result?.views?.count) {\n const views = Number.parseInt(result.views.count);\n if (!Number.isNaN(views)) {\n tweetResult.tweet.views = views;\n }\n }\n\n const quotedResult = result?.quoted_status_result?.result;\n if (quotedResult) {\n if (quotedResult.legacy && quotedResult.rest_id) {\n quotedResult.legacy.id_str = quotedResult.rest_id;\n }\n\n const quotedTweetResult = parseResult(quotedResult);\n if (quotedTweetResult.success) {\n tweetResult.tweet.quotedStatus = quotedTweetResult.tweet;\n }\n }\n\n return tweetResult;\n}\n\nconst expectedEntryTypes = [\"tweet\", \"profile-conversation\"];\n\n/**\n * Parses the timeline tweets from a TimelineV2 object and returns the QueryTweetsResponse.\n * @param {TimelineV2} timeline The timeline object containing the tweet data.\n * @returns {QueryTweetsResponse} The parsed tweets along with the next and previous cursors.\n */\nexport function parseTimelineTweetsV2(\n timeline: TimelineV2\n): QueryTweetsResponse {\n let bottomCursor: string | undefined;\n let topCursor: string | undefined;\n const tweets: Tweet[] = [];\n const instructions =\n timeline.data?.user?.result?.timeline_v2?.timeline?.instructions ?? [];\n for (const instruction of instructions) {\n const entries = instruction.entries ?? [];\n\n for (const entry of entries) {\n const entryContent = entry.content;\n if (!entryContent) continue;\n\n // Handle pagination\n if (entryContent.cursorType === \"Bottom\") {\n bottomCursor = entryContent.value;\n continue;\n }\n if (entryContent.cursorType === \"Top\") {\n topCursor = entryContent.value;\n continue;\n }\n\n const idStr = entry.entryId;\n if (\n !expectedEntryTypes.some((entryType) => idStr.startsWith(entryType))\n ) {\n continue;\n }\n\n if (entryContent.itemContent) {\n // Typically TimelineTimelineTweet entries\n parseAndPush(tweets, entryContent.itemContent, idStr);\n } else if (entryContent.items) {\n // Typically TimelineTimelineModule entries\n for (const item of entryContent.items) {\n if (item.item?.itemContent) {\n parseAndPush(tweets, item.item.itemContent, idStr);\n }\n }\n }\n }\n }\n\n return { tweets, next: bottomCursor, previous: topCursor };\n}\n\n/**\n * Parses the raw content of a timeline entry item to extract the tweet data.\n * @param {TimelineEntryItemContentRaw} content - The raw content of the timeline entry item\n * @param {string} entryId - The entry ID of the timeline entry\n * @param {boolean} [isConversation=false] - Indicates if the timeline entry is part of a conversation\n * @returns {Tweet | null} The parsed tweet data or null if the parsing was unsuccessful\n */\nexport function parseTimelineEntryItemContentRaw(\n content: TimelineEntryItemContentRaw,\n entryId: string,\n isConversation = false\n) {\n let result = content.tweet_results?.result ?? content.tweetResult?.result;\n if (\n result?.__typename === \"Tweet\" ||\n (result?.__typename === \"TweetWithVisibilityResults\" && result?.tweet)\n ) {\n if (result?.__typename === \"TweetWithVisibilityResults\")\n result = result.tweet;\n\n if (result?.legacy) {\n result.legacy.id_str =\n result.rest_id ??\n entryId.replace(\"conversation-\", \"\").replace(\"tweet-\", \"\");\n }\n\n const tweetResult = parseResult(result);\n if (tweetResult.success) {\n if (isConversation) {\n if (content?.tweetDisplayType === \"SelfThread\") {\n tweetResult.tweet.isSelfThread = true;\n }\n }\n\n return tweetResult.tweet;\n }\n }\n\n return null;\n}\n\n/**\n * Parses the given content and pushes the resulting Tweet object to the specified array.\n *\n * @param {Tweet[]} tweets - The array to push the parsed Tweet object to.\n * @param {TimelineEntryItemContentRaw} content - The raw content to parse.\n * @param {string} entryId - The ID of the timeline entry.\n * @param {boolean} [isConversation=false] - Indicates if the tweet is part of a conversation.\n */\nexport function parseAndPush(\n tweets: Tweet[],\n content: TimelineEntryItemContentRaw,\n entryId: string,\n isConversation = false\n) {\n const tweet = parseTimelineEntryItemContentRaw(\n content,\n entryId,\n isConversation\n );\n\n if (tweet) {\n tweets.push(tweet);\n }\n}\n\n/**\n * Parses a threaded conversation object and returns an array of Tweets.\n * @param conversation The threaded conversation object to parse\n * @returns An array of Tweet objects parsed from the conversation\n */\nexport function parseThreadedConversation(\n conversation: ThreadedConversation\n): Tweet[] {\n const tweets: Tweet[] = [];\n const instructions =\n conversation.data?.threaded_conversation_with_injections_v2?.instructions ??\n [];\n\n for (const instruction of instructions) {\n const entries = instruction.entries ?? [];\n for (const entry of entries) {\n const entryContent = entry.content?.itemContent;\n if (entryContent) {\n parseAndPush(tweets, entryContent, entry.entryId, true);\n }\n\n for (const item of entry.content?.items ?? []) {\n const itemContent = item.item?.itemContent;\n if (itemContent) {\n parseAndPush(tweets, itemContent, entry.entryId, true);\n }\n }\n }\n }\n\n for (const tweet of tweets) {\n if (tweet.inReplyToStatusId) {\n for (const parentTweet of tweets) {\n if (parentTweet.id === tweet.inReplyToStatusId) {\n tweet.inReplyToStatus = parentTweet;\n break;\n }\n }\n }\n\n if (tweet.isSelfThread && tweet.conversationId === tweet.id) {\n for (const childTweet of tweets) {\n if (childTweet.isSelfThread && childTweet.id !== tweet.id) {\n tweet.thread.push(childTweet);\n }\n }\n\n if (tweet.thread.length === 0) {\n tweet.isSelfThread = false;\n }\n }\n }\n\n return tweets;\n}\n\n/**\n * Interface representing a timeline article.\n * @typedef {Object} TimelineArticle\n * @property {string} id - The unique identifier for the article.\n * @property {string} articleId - The identifier for the article.\n * @property {string} title - The title of the article.\n * @property {string} previewText - The preview text of the article.\n * @property {string} [coverMediaUrl] - The URL of the cover media for the article. (Optional)\n * @property {string} text - The main text content of the article.\n */\nexport interface TimelineArticle {\n id: string;\n articleId: string;\n title: string;\n previewText: string;\n coverMediaUrl?: string;\n text: string;\n}\n\n/**\n * Parses a ThreadedConversation object to extract TimelineArticle objects.\n *\n * @param {ThreadedConversation} conversation - The ThreadedConversation object to parse.\n * @returns {TimelineArticle[]} The extracted TimelineArticle objects.\n */\nexport function parseArticle(\n conversation: ThreadedConversation\n): TimelineArticle[] {\n const articles: TimelineArticle[] = [];\n for (const instruction of conversation.data\n ?.threaded_conversation_with_injections_v2?.instructions ?? []) {\n for (const entry of instruction.entries ?? []) {\n const id = entry.content?.itemContent?.tweet_results?.result?.rest_id;\n const article =\n entry.content?.itemContent?.tweet_results?.result?.article\n ?.article_results?.result;\n if (!id || !article) continue;\n const text =\n article.content_state?.blocks\n ?.map((block) => block.text)\n .join(\"\\n\\n\") ?? \"\";\n articles.push({\n id,\n articleId: article.rest_id || \"\",\n coverMediaUrl: article.cover_media?.media_info?.original_img_url,\n previewText: article.preview_text || \"\",\n text,\n title: article.title || \"\",\n });\n }\n }\n return articles;\n}\n","import { type Profile, parseProfile } from \"./profile\";\nimport type { QueryProfilesResponse, QueryTweetsResponse } from \"./timeline-v1\";\nimport { type SearchEntryRaw, parseLegacyTweet } from \"./timeline-v2\";\nimport type { Tweet } from \"./tweets\";\n\n/**\n * Represents a search timeline object.\n * * @typedef { Object } SearchTimeline\n * @property { Object } [data] - Optional data object containing search information.\n * @property { Object } [data.search_by_raw_query] - Optional object containing search timeline information.\n * @property { Object } [data.search_by_raw_query.search_timeline] - Optional object containing search timeline details.\n * @property { Object } [data.search_by_raw_query.search_timeline.timeline] - Optional object containing timeline instructions.\n * @property {Array<Object>} [data.search_by_raw_query.search_timeline.timeline.instructions] - Optional array of search entry instructions.\n * @property {Array<SearchEntryRaw>} [data.search_by_raw_query.search_timeline.timeline.instructions.entries] - Optional array of raw search entries.\n * @property { SearchEntryRaw } [data.search_by_raw_query.search_timeline.timeline.instructions.entry] - Optional raw search entry.\n * @property { string } [data.search_by_raw_query.search_timeline.timeline.instructions.type] - Optional type of search instructions.\n */\nexport interface SearchTimeline {\n data?: {\n search_by_raw_query?: {\n search_timeline?: {\n timeline?: {\n instructions?: {\n entries?: SearchEntryRaw[];\n entry?: SearchEntryRaw;\n type?: string;\n }[];\n };\n };\n };\n };\n}\n\n/**\n * Parses the search timeline tweets from the provided SearchTimeline object.\n *\n * @param {SearchTimeline} timeline The SearchTimeline object containing the data to be parsed.\n * @returns {QueryTweetsResponse} An object containing an array of parsed Tweet objects, as well as the next and previous cursors for pagination.\n */\nexport function parseSearchTimelineTweets(\n timeline: SearchTimeline\n): QueryTweetsResponse {\n let bottomCursor: string | undefined;\n let topCursor: string | undefined;\n const tweets: Tweet[] = [];\n const instructions =\n timeline.data?.search_by_raw_query?.search_timeline?.timeline\n ?.instructions ?? [];\n for (const instruction of instructions) {\n if (\n instruction.type === \"TimelineAddEntries\" ||\n instruction.type === \"TimelineReplaceEntry\"\n ) {\n if (instruction.entry?.content?.cursorType === \"Bottom\") {\n bottomCursor = instruction.entry.content.value;\n continue;\n }\n if (instruction.entry?.content?.cursorType === \"Top\") {\n topCursor = instruction.entry.content.value;\n continue;\n }\n\n const entries = instruction.entries ?? [];\n for (const entry of entries) {\n const itemContent = entry.content?.itemContent;\n if (itemContent?.tweetDisplayType === \"Tweet\") {\n const tweetResultRaw = itemContent.tweet_results?.result;\n const tweetResult = parseLegacyTweet(\n tweetResultRaw?.core?.user_results?.result?.legacy,\n tweetResultRaw?.legacy\n );\n\n if (tweetResult.success) {\n if (!tweetResult.tweet.views && tweetResultRaw?.views?.count) {\n const views = Number.parseInt(tweetResultRaw.views.count);\n if (!Number.isNaN(views)) {\n tweetResult.tweet.views = views;\n }\n }\n\n tweets.push(tweetResult.tweet);\n }\n } else if (entry.content?.cursorType === \"Bottom\") {\n bottomCursor = entry.content.value;\n } else if (entry.content?.cursorType === \"Top\") {\n topCursor = entry.content.value;\n }\n }\n }\n }\n\n return { tweets, next: bottomCursor, previous: topCursor };\n}\n\n/**\n * Parses the search timeline users from the provided SearchTimeline.\n * @param {SearchTimeline} timeline The search timeline to parse users from.\n * @returns {QueryProfilesResponse} An object containing the parsed profiles along with next and previous cursors.\n */\nexport function parseSearchTimelineUsers(\n timeline: SearchTimeline\n): QueryProfilesResponse {\n let bottomCursor: string | undefined;\n let topCursor: string | undefined;\n const profiles: Profile[] = [];\n const instructions =\n timeline.data?.search_by_raw_query?.search_timeline?.timeline\n ?.instructions ?? [];\n\n for (const instruction of instructions) {\n if (\n instruction.type === \"TimelineAddEntries\" ||\n instruction.type === \"TimelineReplaceEntry\"\n ) {\n if (instruction.entry?.content?.cursorType === \"Bottom\") {\n bottomCursor = instruction.entry.content.value;\n continue;\n }\n if (instruction.entry?.content?.cursorType === \"Top\") {\n topCursor = instruction.entry.content.value;\n continue;\n }\n\n const entries = instruction.entries ?? [];\n for (const entry of entries) {\n const itemContent = entry.content?.itemContent;\n if (itemContent?.userDisplayType === \"User\") {\n const userResultRaw = itemContent.user_results?.result;\n\n if (userResultRaw?.legacy) {\n const profile = parseProfile(\n userResultRaw.legacy,\n userResultRaw.is_blue_verified\n );\n\n if (!profile.userId) {\n profile.userId = userResultRaw.rest_id;\n }\n\n profiles.push(profile);\n }\n } else if (entry.content?.cursorType === \"Bottom\") {\n bottomCursor = entry.content.value;\n } else if (entry.content?.cursorType === \"Top\") {\n topCursor = entry.content.value;\n }\n }\n }\n }\n\n return { profiles, next: bottomCursor, previous: topCursor };\n}\n","import type { TwitterAuth } from \"./auth\";\nimport { getTwitterApiHeaders } from \"./browser-fingerprint\";\nimport { updateCookieJar } from \"./requests\";\nimport type {\n AudioSpace,\n AudioSpaceByIdResponse,\n AudioSpaceByIdVariables,\n AuthenticatePeriscopeResponse,\n BrowseSpaceTopicsResponse,\n Community,\n CommunitySelectQueryResponse,\n LiveVideoStreamStatus,\n LoginTwitterTokenResponse,\n Subtopic,\n} from \"./types/spaces\";\n\n/**\n * Generates a random string that mimics a UUID v4.\n */\n// TODO: install and replace with uuidv4\n/**\n * Generates a random UUID (Universally Unique Identifier) in the form of \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".\n * @returns {string} A randomly generated UUID.\n */\nfunction generateRandomId(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === \"x\" ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\n/**\n * Fetches details of an Audio Space by its ID.\n * @param variables The variables required for the GraphQL query.\n * @param auth The authentication object.\n * @returns The details of the Audio Space.\n */\nexport async function fetchAudioSpaceById(\n variables: AudioSpaceByIdVariables,\n auth: TwitterAuth\n): Promise<AudioSpace> {\n const queryId = \"Tvv_cNXCbtTcgdy1vWYPMw\"; // Specific to the AudioSpaceById GraphQL query\n const operationName = \"AudioSpaceById\";\n\n // URL encode the variables and features\n const variablesEncoded = encodeURIComponent(JSON.stringify(variables));\n const features = {\n spaces_2022_h2_spaces_communities: true,\n spaces_2022_h2_clipping: true,\n creator_subscriptions_tweet_preview_api_enabled: true,\n profile_label_improvements_pcf_label_in_post_enabled: false,\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n premium_content_api_read_enabled: false,\n communities_web_enable_tweet_community_results_fetch: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n responsive_web_grok_analyze_button_fetch_trends_enabled: true,\n articles_preview_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n rweb_video_timestamps_enabled: true,\n longform_notetweets_rich_text_read_enabled: true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n };\n const featuresEncoded = encodeURIComponent(JSON.stringify(features));\n\n const url = `https://x.com/i/api/graphql/${queryId}/${operationName}?variables=${variablesEncoded}&features=${featuresEncoded}`;\n\n const onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n // Retrieve necessary cookies and tokens\n const cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const twitterHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n Accept: \"*/*\",\n Authorization: `Bearer ${(auth as any).bearerToken}`,\n \"Content-Type\": \"application/json\",\n Cookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n ...Object.fromEntries(twitterHeaders.entries()),\n });\n\n const response = await auth.fetch(url, {\n headers,\n method: \"GET\",\n });\n\n // Update the cookie jar with any new cookies from the response\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // Check for errors in the response\n if (!response.ok) {\n throw new Error(`Failed to fetch Audio Space: ${await response.text()}`);\n }\n\n const data: AudioSpaceByIdResponse = await response.json();\n\n if (data.errors && data.errors.length > 0) {\n throw new Error(`API Errors: ${JSON.stringify(data.errors)}`);\n }\n\n return data.data.audioSpace;\n}\n\n/**\n * Fetches available space topics from Twitter.\n * @param auth The authentication object.\n * @returns An array of space topics.\n */\nexport async function fetchBrowseSpaceTopics(\n auth: TwitterAuth\n): Promise<Subtopic[]> {\n const queryId = \"TYpVV9QioZfViHqEqRZxJA\";\n const operationName = \"BrowseSpaceTopics\";\n\n const variables = {};\n const features = {};\n\n const variablesEncoded = encodeURIComponent(JSON.stringify(variables));\n const featuresEncoded = encodeURIComponent(JSON.stringify(features));\n\n const url = `https://x.com/i/api/graphql/${queryId}/${operationName}?variables=${variablesEncoded}&features=${featuresEncoded}`;\n\n const onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n // Retrieve necessary cookies and tokens\n const cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const twitterHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n Accept: \"*/*\",\n Authorization: `Bearer ${(auth as any).bearerToken}`,\n \"Content-Type\": \"application/json\",\n Cookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n ...Object.fromEntries(twitterHeaders.entries()),\n });\n\n const response = await auth.fetch(url, {\n headers,\n method: \"GET\",\n });\n\n // Update the cookie jar with any new cookies from the response\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // Check for errors in the response\n if (!response.ok) {\n throw new Error(`Failed to fetch Space Topics: ${await response.text()}`);\n }\n\n const data: BrowseSpaceTopicsResponse = await response.json();\n\n if (data.errors && data.errors.length > 0) {\n throw new Error(`API Errors: ${JSON.stringify(data.errors)}`);\n }\n\n // Flatten the subtopics from all categories into a single array\n return data.data.browse_space_topics.categories.flatMap(\n (category) => category.subtopics\n );\n}\n\n/**\n * Fetches available communities from Twitter.\n * @param auth The authentication object.\n * @returns An array of communities.\n */\nexport async function fetchCommunitySelectQuery(\n auth: TwitterAuth\n): Promise<Community[]> {\n const queryId = \"Lue1DfmoW2cc0225t_8z1w\"; // Specific to the CommunitySelectQuery GraphQL query\n const operationName = \"CommunitySelectQuery\";\n\n const variables = {};\n const features = {};\n\n const variablesEncoded = encodeURIComponent(JSON.stringify(variables));\n const featuresEncoded = encodeURIComponent(JSON.stringify(features));\n\n const url = `https://x.com/i/api/graphql/${queryId}/${operationName}?variables=${variablesEncoded}&features=${featuresEncoded}`;\n\n const onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n // Retrieve necessary cookies and tokens\n const cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const twitterHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n Accept: \"*/*\",\n Authorization: `Bearer ${(auth as any).bearerToken}`,\n \"Content-Type\": \"application/json\",\n Cookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n ...Object.fromEntries(twitterHeaders.entries()),\n });\n\n const response = await auth.fetch(url, {\n headers,\n method: \"GET\",\n });\n\n // Update the cookie jar with any new cookies from the response\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // Check for errors in the response\n if (!response.ok) {\n throw new Error(\n `Failed to fetch Community Select Query: ${await response.text()}`\n );\n }\n\n const data: CommunitySelectQueryResponse = await response.json();\n\n if (data.errors && data.errors.length > 0) {\n throw new Error(`API Errors: ${JSON.stringify(data.errors)}`);\n }\n\n // Return the space_hostable_communities array, which may be empty\n return data.data.space_hostable_communities;\n}\n\n/**\n * Fetches the status of an Audio Space stream by its media key.\n * @param mediaKey The media key of the Audio Space.\n * @param auth The authentication object.\n * @returns The status of the Audio Space stream.\n */\nexport async function fetchLiveVideoStreamStatus(\n mediaKey: string,\n auth: TwitterAuth\n): Promise<LiveVideoStreamStatus> {\n const baseUrl = `https://x.com/i/api/1.1/live_video_stream/status/${mediaKey}`;\n const queryParams = new URLSearchParams({\n client: \"web\",\n use_syndication_guest_id: \"false\",\n cookie_set_host: \"x.com\",\n });\n\n const url = `${baseUrl}?${queryParams.toString()}`;\n\n const onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n // Retrieve necessary cookies and tokens\n const cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const twitterHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n Accept: \"*/*\",\n Authorization: `Bearer ${(auth as any).bearerToken}`,\n \"Content-Type\": \"application/json\",\n Cookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n ...Object.fromEntries(twitterHeaders.entries()),\n });\n\n try {\n const response = await auth.fetch(url, {\n method: \"GET\",\n headers: headers,\n });\n\n // Update the cookie jar with any new cookies from the response\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // Check for errors in the response\n if (!response.ok) {\n throw new Error(\n `Failed to fetch live video stream status: ${await response.text()}`\n );\n }\n\n return await response.json();\n } catch (error) {\n console.error(\n `Error fetching live video stream status for mediaKey ${mediaKey}:`,\n error\n );\n throw error;\n }\n}\n\n/**\n * Authenticates Periscope to obtain a token.\n * @param auth The authentication object.\n * @returns The Periscope authentication token.\n */\nexport async function fetchAuthenticatePeriscope(\n auth: TwitterAuth\n): Promise<string> {\n const queryId = \"r7VUmxbfqNkx7uwjgONSNw\";\n const operationName = \"AuthenticatePeriscope\";\n\n const variables = {};\n const features = {};\n\n const variablesEncoded = encodeURIComponent(JSON.stringify(variables));\n const featuresEncoded = encodeURIComponent(JSON.stringify(features));\n\n const url = `https://x.com/i/api/graphql/${queryId}/${operationName}?variables=${variablesEncoded}&features=${featuresEncoded}`;\n\n const onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n const cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n if (!xCsrfToken) {\n throw new Error(\"CSRF Token (ct0) not found in cookies.\");\n }\n\n const clientTransactionId = generateRandomId();\n\n const twitterHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n Accept: \"*/*\",\n Authorization: `Bearer ${(auth as any).bearerToken}`,\n \"Content-Type\": \"application/json\",\n Cookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Session\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken.value,\n \"x-client-transaction-id\": clientTransactionId,\n \"sec-ch-ua-platform\": '\"Windows\"',\n \"sec-ch-ua\":\n '\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"',\n \"x-twitter-client-language\": \"en\",\n \"sec-ch-ua-mobile\": \"?0\",\n Referer: \"https://x.com/i/spaces/start\",\n ...Object.fromEntries(twitterHeaders.entries()),\n });\n\n try {\n const response = await auth.fetch(url, {\n method: \"GET\",\n headers: headers,\n });\n\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Error ${response.status}: ${errorText}`);\n }\n\n const data: AuthenticatePeriscopeResponse = await response.json();\n\n if (data.errors && data.errors.length > 0) {\n throw new Error(`API Errors: ${JSON.stringify(data.errors)}`);\n }\n\n if (!data.data.authenticate_periscope) {\n throw new Error(\"Periscope authentication failed, no data returned.\");\n }\n\n return data.data.authenticate_periscope;\n } catch (error) {\n console.error(\"Error during Periscope authentication:\", error);\n throw error;\n }\n}\n\n/**\n * Logs in to Twitter via Proxsee using the Periscope JWT to obtain a login cookie.\n * @param jwt The JWT obtained via AuthenticatePeriscope.\n * @param auth The authentication object.\n * @returns The response containing the cookie and user information.\n */\nexport async function fetchLoginTwitterToken(\n jwt: unknown,\n auth: TwitterAuth\n): Promise<LoginTwitterTokenResponse> {\n const url = \"https://proxsee.pscp.tv/api/v2/loginTwitterToken\";\n\n const idempotenceKey = generateRandomId();\n\n const payload = {\n jwt: jwt,\n vendor_id: \"m5-proxsee-login-a2011357b73e\",\n create_user: true,\n };\n\n const twitterHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n \"Content-Type\": \"application/json\",\n Referer: \"https://x.com/\",\n \"sec-ch-ua\":\n '\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"',\n \"sec-ch-ua-platform\": '\"Windows\"',\n \"sec-ch-ua-mobile\": \"?0\",\n \"X-Periscope-User-Agent\": \"Twitter/m5\",\n \"X-Idempotence\": idempotenceKey,\n \"X-Attempt\": \"1\",\n ...Object.fromEntries(twitterHeaders.entries()),\n });\n\n try {\n const response = await auth.fetch(url, {\n method: \"POST\",\n headers: headers,\n body: JSON.stringify(payload),\n });\n\n // Update the cookie jar with any new cookies from the response\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // Check if the response is successful\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Error ${response.status}: ${errorText}`);\n }\n\n const data: LoginTwitterTokenResponse = await response.json();\n\n if (!data.cookie || !data.user) {\n throw new Error(\"Twitter authentication failed, missing data.\");\n }\n\n return data;\n } catch (error) {\n console.error(\"Error logging into Twitter via Proxsee:\", error);\n throw error;\n }\n}\n","import { type RequestApiResult, requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport { ApiError } from \"./errors\";\nimport type { TimelineInstruction } from \"./timeline-v2\";\n\n/**\n * Interface for the response data of the latest timeline for the home page.\n * @property {object} data - The response data object.\n * @property {object} data.home - The home object within the response data.\n * @property {array} data.home.home_timeline_urt - The array of timeline instructions for the home page.\n */\nexport interface HomeLatestTimelineResponse {\n data?: {\n home: {\n home_timeline_urt: {\n instructions: TimelineInstruction[];\n };\n };\n };\n}\n\n/**\n * Fetches the following timeline from Twitter API.\n *\n * @param {number} count - The number of tweets to fetch\n * @param {string[]} seenTweetIds - Array of IDs of tweets that have been seen\n * @param {TwitterAuth} auth - The authentication credentials\n * @returns {Promise<any[]>} - Array of tweets in the following timeline\n */\nexport async function fetchFollowingTimeline(\n count: number,\n seenTweetIds: string[],\n auth: TwitterAuth\n): Promise<any[]> {\n const variables = {\n count,\n includePromotedContent: true,\n latestControlAvailable: true,\n requestContext: \"launch\",\n seenTweetIds,\n };\n\n const features = {\n profile_label_improvements_pcf_label_in_post_enabled: true,\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n communities_web_enable_tweet_community_results_fetch: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n articles_preview_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n rweb_video_timestamps_enabled: true,\n longform_notetweets_rich_text_read_enabled: true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n };\n\n const res = (await requestApi<HomeLatestTimelineResponse>(\n `https://x.com/i/api/graphql/K0X1xbCZUjttdK8RazKAlw/HomeLatestTimeline?variables=${encodeURIComponent(\n JSON.stringify(variables)\n )}&features=${encodeURIComponent(JSON.stringify(features))}`,\n auth,\n \"GET\"\n )) as RequestApiResult<HomeLatestTimelineResponse>;\n\n if (!res.success) {\n if ((res as any).err instanceof ApiError) {\n console.error(\"Error details:\", (res as any).err.data);\n }\n throw (res as any).err;\n }\n\n const home = res.value?.data?.home.home_timeline_urt?.instructions;\n\n if (!home) {\n return [];\n }\n\n const entries: any[] = [];\n\n for (const instruction of home) {\n if (instruction.type === \"TimelineAddEntries\") {\n for (const entry of instruction.entries ?? []) {\n entries.push(entry);\n }\n }\n }\n // get the itemContnent from each entry\n const tweets = entries\n .map((entry) => entry.content.itemContent?.tweet_results?.result)\n .filter((tweet) => tweet !== undefined);\n\n return tweets;\n}\n","import { requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport { ApiError } from \"./errors\";\nimport type { TimelineInstruction } from \"./timeline-v2\";\n\n/**\n * Interface representing the response object for the home timeline API endpoint.\n * @property {object} data - The data object containing the response data.\n * @property {object} data.home - The home object containing the home timeline data.\n * @property {object} data.home.home_timeline_urt - The object containing the timeline instructions.\n * @property {TimelineInstruction[]} data.home.home_timeline_urt.instructions - An array of timeline instructions.\n */\nexport interface HomeTimelineResponse {\n data?: {\n home: {\n home_timeline_urt: {\n instructions: TimelineInstruction[];\n };\n };\n };\n}\n\n/**\n * Fetches the home timeline for a Twitter user.\n *\n * @param {number} count - The number of tweets to fetch.\n * @param {string[]} seenTweetIds - An array of ids of tweets that the user has already seen.\n * @param {TwitterAuth} auth - The authentication credentials for the Twitter API.\n * @returns {Promise<any[]>} - A promise that resolves to an array of tweets from the home timeline.\n */\nexport async function fetchHomeTimeline(\n count: number,\n seenTweetIds: string[],\n auth: TwitterAuth\n): Promise<any[]> {\n const variables = {\n count,\n includePromotedContent: true,\n latestControlAvailable: true,\n requestContext: \"launch\",\n withCommunity: true,\n seenTweetIds,\n };\n\n const features = {\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n communities_web_enable_tweet_community_results_fetch: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n articles_preview_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n rweb_video_timestamps_enabled: true,\n longform_notetweets_rich_text_read_enabled: true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n };\n\n const res = await requestApi<HomeTimelineResponse>(\n `https://x.com/i/api/graphql/HJFjzBgCs16TqxewQOeLNg/HomeTimeline?variables=${encodeURIComponent(\n JSON.stringify(variables)\n )}&features=${encodeURIComponent(JSON.stringify(features))}`,\n auth,\n \"GET\"\n );\n\n if (!res.success) {\n if ((res as any).err instanceof ApiError) {\n console.error(\"Error details:\", (res as any).err.data);\n }\n throw (res as any).err;\n }\n\n const home = res.value?.data?.home.home_timeline_urt?.instructions;\n\n if (!home) {\n return [];\n }\n\n const entries: any[] = [];\n\n for (const instruction of home) {\n if (instruction.type === \"TimelineAddEntries\") {\n for (const entry of instruction.entries ?? []) {\n entries.push(entry);\n }\n }\n }\n // get the itemContnent from each entry\n const tweets = entries\n .map((entry) => entry.content.itemContent?.tweet_results?.result)\n .filter((tweet) => tweet !== undefined);\n\n return tweets;\n}\n","import { addApiParams, requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport type { TimelineV1 } from \"./timeline-v1\";\n\n/**\n * Retrieves the current trends from the Twitter API.\n *\n * @param {TwitterAuth} auth - The authentication credentials for accessing the Twitter API.\n * @returns {Promise<string[]>} An array of strings representing the current trends.\n * @throws {Error} If no trend entries are found in the response.\n */\nexport async function getTrends(auth: TwitterAuth): Promise<string[]> {\n const params = new URLSearchParams();\n addApiParams(params, false);\n\n params.set(\"count\", \"20\");\n params.set(\"candidate_source\", \"trends\");\n params.set(\"include_page_configuration\", \"false\");\n params.set(\"entity_tokens\", \"false\");\n\n const res = await requestApi<TimelineV1>(\n `https://api.twitter.com/2/guide.json?${params.toString()}`,\n auth\n );\n if (!res.success) {\n throw (res as any).err;\n }\n\n const instructions = res.value.timeline?.instructions ?? [];\n if (instructions.length < 2) {\n throw new Error(\"No trend entries found.\");\n }\n\n // Some of this is silly, but for now we're assuming we know nothing about the\n // data, and that anything can be missing. Go has non-nilable strings and empty\n // slices are nil, so it largely doesn't need to worry about this.\n const entries = instructions[1].addEntries?.entries ?? [];\n if (entries.length < 2) {\n throw new Error(\"No trend entries found.\");\n }\n\n const items = entries[1].content?.timelineModule?.items ?? [];\n const trends: string[] = [];\n for (const item of items) {\n const trend =\n item.item?.clientEventInfo?.details?.guideDetails?.transparentGuideDetails\n ?.trendMetadata?.trendName;\n if (trend != null) {\n trends.push(trend);\n }\n }\n\n return trends;\n}\n","import stringify from \"json-stable-stringify\";\n\n/**\n * Examples of requests to API endpoints. These are parsed at runtime and used\n * as templates for requests to a particular endpoint. Please ensure these do\n * not contain any information that you do not want published to NPM.\n */\n/**\n * Object containing various endpoint URLs for Twitter API.\n *\n * @type {Object}\n */\nconst endpoints = {\n // TODO: Migrate other endpoint URLs here\n UserTweets:\n \"https://twitter.com/i/api/graphql/V7H0Ap3_Hh2FyS75OCDO3Q/UserTweets?variables=%7B%22userId%22%3A%224020276615%22%2C%22count%22%3A20%2C%22includePromotedContent%22%3Atrue%2C%22withQuickPromoteEligibilityTweetFields%22%3Atrue%2C%22withVoice%22%3Atrue%2C%22withV2Timeline%22%3Atrue%7D&features=%7B%22rweb_tipjar_consumption_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22articles_preview_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22creator_subscriptions_quote_tweet_preview_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22rweb_video_timestamps_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticlePlainText%22%3Afalse%7D\",\n UserTweetsAndReplies:\n \"https://twitter.com/i/api/graphql/E4wA5vo2sjVyvpliUffSCw/UserTweetsAndReplies?variables=%7B%22userId%22%3A%224020276615%22%2C%22count%22%3A40%2C%22cursor%22%3A%22DAABCgABGPWl-F-ATiIKAAIY9YfiF1rRAggAAwAAAAEAAA%22%2C%22includePromotedContent%22%3Atrue%2C%22withCommunity%22%3Atrue%2C%22withVoice%22%3Atrue%2C%22withV2Timeline%22%3Atrue%7D&features=%7B%22rweb_tipjar_consumption_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22articles_preview_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22creator_subscriptions_quote_tweet_preview_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22rweb_video_timestamps_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticlePlainText%22%3Afalse%7D\",\n UserLikedTweets:\n \"https://twitter.com/i/api/graphql/eSSNbhECHHWWALkkQq-YTA/Likes?variables=%7B%22userId%22%3A%222244196397%22%2C%22count%22%3A20%2C%22includePromotedContent%22%3Afalse%2C%22withClientEventToken%22%3Afalse%2C%22withBirdwatchNotes%22%3Afalse%2C%22withVoice%22%3Atrue%2C%22withV2Timeline%22%3Atrue%7D&features=%7B%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22rweb_video_timestamps_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D\",\n TweetDetail:\n \"https://twitter.com/i/api/graphql/xOhkmRac04YFZmOzU9PJHg/TweetDetail?variables=%7B%22focalTweetId%22%3A%221237110546383724547%22%2C%22with_rux_injections%22%3Afalse%2C%22includePromotedContent%22%3Atrue%2C%22withCommunity%22%3Atrue%2C%22withQuickPromoteEligibilityTweetFields%22%3Atrue%2C%22withBirdwatchNotes%22%3Atrue%2C%22withVoice%22%3Atrue%2C%22withV2Timeline%22%3Atrue%7D&features=%7B%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Afalse%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_media_download_video_enabled%22%3Afalse%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticleRichContentState%22%3Afalse%7D\",\n TweetDetailArticle:\n \"https://twitter.com/i/api/graphql/GtcBtFhtQymrpxAs5MALVA/TweetDetail?variables=%7B%22focalTweetId%22%3A%221765884209527394325%22%2C%22with_rux_injections%22%3Atrue%2C%22rankingMode%22%3A%22Relevance%22%2C%22includePromotedContent%22%3Atrue%2C%22withCommunity%22%3Atrue%2C%22withQuickPromoteEligibilityTweetFields%22%3Atrue%2C%22withBirdwatchNotes%22%3Atrue%2C%22withVoice%22%3Atrue%7D&features=%7B%22profile_label_improvements_pcf_label_in_post_enabled%22%3Afalse%2C%22rweb_tipjar_consumption_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22premium_content_api_read_enabled%22%3Afalse%2C%22communities_web_enable_tweet_community_results_fetch%22%3Atrue%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22responsive_web_grok_analyze_button_fetch_trends_enabled%22%3Atrue%2C%22responsive_web_grok_analyze_post_followups_enabled%22%3Afalse%2C%22responsive_web_grok_share_attachment_enabled%22%3Atrue%2C%22articles_preview_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Atrue%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22creator_subscriptions_quote_tweet_preview_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22rweb_video_timestamps_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D&fieldToggles=%7B%22withArticleRichContentState%22%3Atrue%2C%22withArticlePlainText%22%3Afalse%2C%22withGrokAnalyze%22%3Afalse%2C%22withDisallowedReplyControls%22%3Afalse%7D\",\n TweetResultByRestId:\n \"https://twitter.com/i/api/graphql/DJS3BdhUhcaEpZ7B7irJDg/TweetResultByRestId?variables=%7B%22tweetId%22%3A%221237110546383724547%22%2C%22withCommunity%22%3Afalse%2C%22includePromotedContent%22%3Afalse%2C%22withVoice%22%3Afalse%7D&features=%7B%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Afalse%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22responsive_web_media_download_video_enabled%22%3Afalse%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D\",\n ListTweets:\n \"https://twitter.com/i/api/graphql/whF0_KH1fCkdLLoyNPMoEw/ListLatestTweetsTimeline?variables=%7B%22listId%22%3A%221736495155002106192%22%2C%22count%22%3A20%7D&features=%7B%22responsive_web_graphql_exclude_directive_enabled%22%3Atrue%2C%22verified_phone_label_enabled%22%3Afalse%2C%22creator_subscriptions_tweet_preview_api_enabled%22%3Atrue%2C%22responsive_web_graphql_timeline_navigation_enabled%22%3Atrue%2C%22responsive_web_graphql_skip_user_profile_image_extensions_enabled%22%3Afalse%2C%22c9s_tweet_anatomy_moderator_badge_enabled%22%3Atrue%2C%22tweetypie_unmention_optimization_enabled%22%3Atrue%2C%22responsive_web_edit_tweet_api_enabled%22%3Atrue%2C%22graphql_is_translatable_rweb_tweet_is_translatable_enabled%22%3Atrue%2C%22view_counts_everywhere_api_enabled%22%3Atrue%2C%22longform_notetweets_consumption_enabled%22%3Atrue%2C%22responsive_web_twitter_article_tweet_consumption_enabled%22%3Afalse%2C%22tweet_awards_web_tipping_enabled%22%3Afalse%2C%22freedom_of_speech_not_reach_fetch_enabled%22%3Atrue%2C%22standardized_nudges_misinfo%22%3Atrue%2C%22tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled%22%3Atrue%2C%22rweb_video_timestamps_enabled%22%3Atrue%2C%22longform_notetweets_rich_text_read_enabled%22%3Atrue%2C%22longform_notetweets_inline_media_enabled%22%3Atrue%2C%22responsive_web_media_download_video_enabled%22%3Afalse%2C%22responsive_web_enhance_cards_enabled%22%3Afalse%7D\",\n} as const;\n\nexport interface EndpointFieldInfo {\n /**\n * Request variables, used for providing arguments such as user IDs or result counts.\n */\n variables: Record<string, unknown>;\n\n /**\n * Request features, used for encoding feature flags into the request. These may either be\n * boolean values or numerically-encoded booleans (1 or 0). It is possible this may change\n * to include other representations of booleans as Twitter's backend evolves.\n */\n features: Record<string, unknown>;\n\n /**\n * Request field toggles, used for limiting how returned fields are represented. This is\n * rarely used.\n */\n fieldToggles: Record<string, unknown>;\n}\n\ntype SomePartial<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;\n\ntype EndpointVersion = string;\ntype EndpointName = string;\ntype EncodedVariables = string;\ntype EncodedFeatures = string;\ntype EncodedFieldToggles = string;\n\n// TODO: Set up field-level Intellisense for the QraphQL parameters in these?\ntype EndpointFields<EndpointUrl> =\n EndpointUrl extends `https://twitter.com/i/api/graphql/${EndpointVersion}/${EndpointName}?variables=${EncodedVariables}&features=${EncodedFeatures}&fieldToggles=${EncodedFieldToggles}`\n ? EndpointFieldInfo\n : EndpointUrl extends `https://twitter.com/i/api/graphql/${EndpointVersion}/${EndpointName}?variables=${EncodedVariables}&features=${EncodedFeatures}`\n ? SomePartial<EndpointFieldInfo, \"fieldToggles\">\n : EndpointUrl extends `https://twitter.com/i/api/graphql/${EndpointVersion}/${EndpointName}?variables=${EncodedVariables}`\n ? SomePartial<EndpointFieldInfo, \"features\" | \"fieldToggles\">\n : Partial<EndpointFieldInfo>;\n\nexport type ApiRequestInfo<EndpointUrl> = EndpointFields<EndpointUrl> & {\n /**\n * The URL, without any GraphQL query parameters.\n */\n url: string;\n\n /**\n * Converts the request back into a URL to be sent to the Twitter API.\n */\n toRequestUrl(): string;\n};\n\n/** Wrapper class for API request information. */\nclass ApiRequest<EndpointUrl> {\n url: string;\n variables?: Record<string, unknown> | undefined;\n features?: Record<string, unknown> | undefined;\n fieldToggles?: Record<string, unknown> | undefined;\n\n constructor(info: Omit<ApiRequestInfo<EndpointUrl>, \"toRequestUrl\">) {\n this.url = info.url;\n this.variables = info.variables;\n this.features = info.features;\n this.fieldToggles = info.fieldToggles;\n }\n\n toRequestUrl(): string {\n const params = new URLSearchParams();\n\n // Only include query parameters with values\n if (this.variables) {\n // Stringify with the query keys in sorted order like the Go package\n params.set(\"variables\", stringify(this.variables) ?? \"\");\n }\n\n if (this.features) {\n params.set(\"features\", stringify(this.features) ?? \"\");\n }\n\n if (this.fieldToggles) {\n params.set(\"fieldToggles\", stringify(this.fieldToggles) ?? \"\");\n }\n\n return `${this.url}?${params.toString()}`;\n }\n}\n\n/**\n * Parses information from a Twitter API endpoint using an example request\n * URL against that endpoint. This can be used to extract GraphQL parameters\n * in order to easily reuse and/or override them later.\n * @param example An example of the endpoint to analyze.\n * @returns The parsed endpoint information.\n */\nfunction parseEndpointExample<\n Endpoints,\n Endpoint extends string & keyof Endpoints,\n>(example: Endpoint): ApiRequestInfo<Endpoints[Endpoint]> {\n const { protocol, host, pathname, searchParams: query } = new URL(example);\n\n const base = `${protocol}//${host}${pathname}`;\n const variables = query.get(\"variables\");\n const features = query.get(\"features\");\n const fieldToggles = query.get(\"fieldToggles\");\n\n return new ApiRequest<Endpoints[Endpoint]>({\n url: base,\n variables: variables ? JSON.parse(variables) : undefined,\n features: features ? JSON.parse(features) : undefined,\n fieldToggles: fieldToggles ? JSON.parse(fieldToggles) : undefined,\n } as Omit<\n ApiRequestInfo<Endpoints[Endpoint]>,\n \"toRequestUrl\"\n >) as ApiRequestInfo<Endpoints[Endpoint]>;\n}\n\ntype ApiRequestFactory<Endpoints> = {\n [Endpoint in keyof Endpoints as `create${string & Endpoint}Request`]: () => ApiRequestInfo<\n Endpoints[Endpoint]\n >;\n};\n\nfunction createApiRequestFactory<Endpoints extends Record<string, string>>(\n endpoints: Endpoints\n): ApiRequestFactory<Endpoints> {\n type UntypedApiRequestFactory = ApiRequestFactory<Record<string, string>>;\n\n return Object.entries(endpoints)\n .map<UntypedApiRequestFactory>(([endpointName, endpointExample]) => {\n // Create a partial factory for only one endpoint\n return {\n [`create${endpointName}Request`]: () => {\n // Create a new instance on each invocation so that we can safely\n // mutate requests before sending them off\n return parseEndpointExample<Endpoints, any>(endpointExample);\n },\n };\n })\n .reduce((agg, next) => {\n // Merge all of our factories into one that includes every endpoint\n return Object.assign(agg, next);\n }) as ApiRequestFactory<Endpoints>;\n}\n\nexport const apiRequestFactory = createApiRequestFactory(endpoints);\n","import type { QueryTweetsResponse } from \"./timeline-v1\";\nimport { type TimelineEntryRaw, parseAndPush } from \"./timeline-v2\";\nimport type { Tweet } from \"./tweets\";\n\n/**\n * Interface representing a list timeline with optional data.\n *\n * @property {Object} data - Optional object containing list timeline data.\n * @property {Object} data.list - Optional object containing list information.\n * @property {Object} data.list.tweets_timeline - Optional object containing tweets timeline information.\n * @property {Object} data.list.tweets_timeline.timeline - Optional object containing timeline instructions.\n * @property {Object[]} data.list.tweets_timeline.timeline.instructions - Optional array of timeline instructions.\n * @property {Object[]} data.list.tweets_timeline.timeline.instructions.entries - Optional array of timeline entry objects.\n * @property {Object} data.list.tweets_timeline.timeline.instructions.entry - Optional single timeline entry object.\n * @property {string} data.list.tweets_timeline.timeline.instructions.type - Optional string indicating the type of timeline entry.\n */\n\nexport interface ListTimeline {\n data?: {\n list?: {\n tweets_timeline?: {\n timeline?: {\n instructions?: {\n entries?: TimelineEntryRaw[];\n entry?: TimelineEntryRaw;\n type?: string;\n }[];\n };\n };\n };\n };\n}\n\n/**\n * Parses the list timeline tweets from the provided ListTimeline object.\n *\n * @param {ListTimeline} timeline The ListTimeline object to parse tweets from.\n * @returns {QueryTweetsResponse} An object containing the parsed tweets, next cursor, and previous cursor.\n */\nexport function parseListTimelineTweets(\n timeline: ListTimeline\n): QueryTweetsResponse {\n let bottomCursor: string | undefined;\n let topCursor: string | undefined;\n const tweets: Tweet[] = [];\n const instructions =\n timeline.data?.list?.tweets_timeline?.timeline?.instructions ?? [];\n for (const instruction of instructions) {\n const entries = instruction.entries ?? [];\n\n for (const entry of entries) {\n const entryContent = entry.content;\n if (!entryContent) continue;\n\n if (entryContent.cursorType === \"Bottom\") {\n bottomCursor = entryContent.value;\n continue;\n }\n if (entryContent.cursorType === \"Top\") {\n topCursor = entryContent.value;\n continue;\n }\n\n const idStr = entry.entryId;\n if (\n !idStr.startsWith(\"tweet\") &&\n !idStr.startsWith(\"list-conversation\")\n ) {\n continue;\n }\n\n if (entryContent.itemContent) {\n parseAndPush(tweets, entryContent.itemContent, idStr);\n } else if (entryContent.items) {\n for (const contentItem of entryContent.items) {\n if (contentItem.item?.itemContent && contentItem.entryId) {\n parseAndPush(\n tweets,\n contentItem.item.itemContent,\n contentItem.entryId.split(\"tweet-\")[1]\n );\n }\n }\n }\n }\n }\n\n return { tweets, next: bottomCursor, previous: topCursor };\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 { addApiFeatures, requestApi } from \"./api\";\nimport { apiRequestFactory } from \"./api-data\";\nimport type { TwitterAuth } from \"./auth\";\nimport { getTwitterApiHeaders } from \"./browser-fingerprint\";\nimport { getEntityIdByScreenName } from \"./profile\";\nimport { updateCookieJar } from \"./requests\";\nimport { getTweetTimeline } from \"./timeline-async\";\nimport { type ListTimeline, parseListTimelineTweets } from \"./timeline-list\";\nimport type { QueryTweetsResponse } from \"./timeline-v1\";\nimport {\n type ThreadedConversation,\n type TimelineArticle,\n type TimelineEntryItemContentRaw,\n type TimelineV2,\n parseArticle,\n parseThreadedConversation,\n parseTimelineEntryItemContentRaw,\n parseTimelineTweetsV2,\n} from \"./timeline-v2\";\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 const features = addApiFeatures({\n interactive_text_enabled: true,\n longform_notetweets_inline_media_enabled: false,\n responsive_web_text_conversations_enabled: false,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n false,\n vibe_api_enabled: false,\n});\n\nexport async function fetchTweets(\n userId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth\n): Promise<QueryTweetsResponse> {\n if (maxTweets > 200) {\n maxTweets = 200;\n }\n\n const userTweetsRequest = apiRequestFactory.createUserTweetsRequest();\n userTweetsRequest.variables.userId = userId;\n userTweetsRequest.variables.count = maxTweets;\n userTweetsRequest.variables.includePromotedContent = false; // true on the website\n\n if (cursor != null && cursor !== \"\") {\n userTweetsRequest.variables.cursor = cursor;\n }\n\n const res = await requestApi<TimelineV2>(\n userTweetsRequest.toRequestUrl(),\n auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n return parseTimelineTweetsV2(res.value);\n}\n\nexport async function fetchTweetsAndReplies(\n userId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth\n): Promise<QueryTweetsResponse> {\n if (maxTweets > 40) {\n maxTweets = 40;\n }\n\n const userTweetsRequest =\n apiRequestFactory.createUserTweetsAndRepliesRequest();\n userTweetsRequest.variables.userId = userId;\n userTweetsRequest.variables.count = maxTweets;\n userTweetsRequest.variables.includePromotedContent = false; // true on the website\n\n if (cursor != null && cursor !== \"\") {\n userTweetsRequest.variables.cursor = cursor;\n }\n\n const res = await requestApi<TimelineV2>(\n userTweetsRequest.toRequestUrl(),\n auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n return parseTimelineTweetsV2(res.value);\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 defaultTweetData?: Tweet | null\n): Tweet {\n let parsedTweet: Tweet;\n if (defaultTweetData != null) {\n parsedTweet = defaultTweetData;\n }\n parsedTweet = {\n id: tweetV2.id,\n text: tweetV2.text ?? defaultTweetData?.text ?? \"\",\n hashtags:\n tweetV2.entities?.hashtags?.map((tag) => tag.tag) ??\n defaultTweetData?.hashtags ??\n [],\n mentions:\n tweetV2.entities?.mentions?.map((mention) => ({\n id: mention.id,\n username: mention.username,\n })) ??\n defaultTweetData?.mentions ??\n [],\n urls:\n tweetV2.entities?.urls?.map((url) => url.url) ??\n defaultTweetData?.urls ??\n [],\n likes: tweetV2.public_metrics?.like_count ?? defaultTweetData?.likes ?? 0,\n retweets:\n tweetV2.public_metrics?.retweet_count ?? defaultTweetData?.retweets ?? 0,\n replies:\n tweetV2.public_metrics?.reply_count ?? defaultTweetData?.replies ?? 0,\n views:\n tweetV2.public_metrics?.impression_count ?? defaultTweetData?.views ?? 0,\n userId: tweetV2.author_id ?? defaultTweetData?.userId,\n conversationId: tweetV2.conversation_id ?? defaultTweetData?.conversationId,\n photos: defaultTweetData?.photos ?? [],\n videos: defaultTweetData?.videos ?? [],\n poll: defaultTweetData?.poll ?? null,\n username: defaultTweetData?.username ?? \"\",\n name: defaultTweetData?.name ?? \"\",\n place: defaultTweetData?.place,\n thread: defaultTweetData?.thread ?? [],\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 ? poll.end_datetime\n : defaultTweetData?.poll?.end_datetime\n ? defaultTweetData?.poll?.end_datetime\n : undefined,\n options: poll.options.map((option) => ({\n position: option.position,\n label: option.label,\n votes: option.votes,\n })),\n voting_status:\n poll.voting_status ?? defaultTweetData?.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 ?? defaultTweetData?.username ?? \"\";\n parsedTweet.name = user.name ?? defaultTweetData?.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 ?? defaultTweetData?.place?.full_name ?? \"\",\n country: place.country ?? defaultTweetData?.place?.country ?? \"\",\n country_code:\n place.country_code ?? defaultTweetData?.place?.country_code ?? \"\",\n name: place.name ?? defaultTweetData?.place?.name ?? \"\",\n place_type: place.place_type ?? defaultTweetData?.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 onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n const cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n //@ ts-expect-error - This is a private API.\n const twitterHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n \"content-type\": \"application/json\",\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-twitter-client-language\": \"en\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n ...Object.fromEntries(twitterHeaders.entries()),\n });\n\n const variables: Record<string, any> = {\n tweet_text: text,\n dark_request: false,\n media: {\n media_entities: [],\n possibly_sensitive: false,\n },\n semantic_annotation_ids: [],\n };\n\n if (hideLinkPreview) {\n variables.card_uri = \"tombstone://card\";\n }\n\n if (mediaData && mediaData.length > 0) {\n const mediaIds = await Promise.all(\n mediaData.map(({ data, mediaType }) => uploadMedia(data, auth, mediaType))\n );\n\n variables.media.media_entities = mediaIds.map((id) => ({\n media_id: id,\n tagged_users: [],\n }));\n }\n\n if (tweetId) {\n variables.reply = { in_reply_to_tweet_id: tweetId };\n }\n\n const response = await fetch(\n \"https://twitter.com/i/api/graphql/a1p9RWpkYKBjWv_I3WzS-A/CreateTweet\",\n {\n headers,\n body: JSON.stringify({\n variables,\n features: {\n interactive_text_enabled: true,\n longform_notetweets_inline_media_enabled: false,\n responsive_web_text_conversations_enabled: false,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n false,\n vibe_api_enabled: false,\n rweb_lists_timeline_redesign_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled:\n false,\n tweetypie_unmention_optimization_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n longform_notetweets_rich_text_read_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n subscriptions_verification_info_enabled: true,\n subscriptions_verification_info_reason_enabled: true,\n subscriptions_verification_info_verified_since_enabled: true,\n super_follow_badge_privacy_enabled: false,\n super_follow_exclusive_tweet_notifications_enabled: false,\n super_follow_tweet_api_enabled: false,\n super_follow_user_api_enabled: false,\n android_graphql_skip_api_media_color_palette: false,\n creator_subscriptions_subscription_count_enabled: false,\n blue_business_profile_image_shape_enabled: false,\n unified_cards_ad_metadata_container_dynamic_card_content_query_enabled:\n false,\n rweb_video_timestamps_enabled: false,\n c9s_tweet_anatomy_moderator_badge_enabled: false,\n responsive_web_twitter_article_tweet_consumption_enabled: false,\n },\n fieldToggles: {},\n }),\n method: \"POST\",\n }\n );\n\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // check for errors\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n return response;\n}\n\nexport async function createCreateNoteTweetRequest(\n text: string,\n auth: TwitterAuth,\n tweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[]\n) {\n const onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n const cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const baseHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n ...Object.fromEntries(baseHeaders.entries()),\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n \"content-type\": \"application/json\",\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-twitter-client-language\": \"en\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n });\n\n const variables: Record<string, any> = {\n tweet_text: text,\n dark_request: false,\n media: {\n media_entities: [],\n possibly_sensitive: false,\n },\n semantic_annotation_ids: [],\n };\n\n if (mediaData && mediaData.length > 0) {\n const mediaIds = await Promise.all(\n mediaData.map(({ data, mediaType }) => uploadMedia(data, auth, mediaType))\n );\n\n variables.media.media_entities = mediaIds.map((id) => ({\n media_id: id,\n tagged_users: [],\n }));\n }\n\n if (tweetId) {\n variables.reply = { in_reply_to_tweet_id: tweetId };\n }\n\n const response = await fetch(\n \"https://twitter.com/i/api/graphql/0aWhJJmFlxkxv9TAUJPanA/CreateNoteTweet\",\n {\n headers,\n body: JSON.stringify({\n variables,\n features: {\n interactive_text_enabled: true,\n longform_notetweets_inline_media_enabled: false,\n responsive_web_text_conversations_enabled: false,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n false,\n vibe_api_enabled: false,\n rweb_lists_timeline_redesign_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled:\n false,\n tweetypie_unmention_optimization_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n longform_notetweets_creation_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n longform_notetweets_rich_text_read_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n subscriptions_verification_info_enabled: true,\n subscriptions_verification_info_reason_enabled: true,\n subscriptions_verification_info_verified_since_enabled: true,\n super_follow_badge_privacy_enabled: false,\n super_follow_exclusive_tweet_notifications_enabled: false,\n super_follow_tweet_api_enabled: false,\n super_follow_user_api_enabled: false,\n android_graphql_skip_api_media_color_palette: false,\n creator_subscriptions_subscription_count_enabled: false,\n blue_business_profile_image_shape_enabled: false,\n unified_cards_ad_metadata_container_dynamic_card_content_query_enabled:\n false,\n rweb_video_timestamps_enabled: false,\n c9s_tweet_anatomy_moderator_badge_enabled: false,\n responsive_web_twitter_article_tweet_consumption_enabled: false,\n\n communities_web_enable_tweet_community_results_fetch: false,\n articles_preview_enabled: false,\n rweb_tipjar_consumption_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n },\n fieldToggles: {},\n }),\n method: \"POST\",\n }\n );\n\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // Check for errors and log the error response\n if (!response.ok) {\n const errorText = await response.text();\n console.error(\"Error response:\", errorText);\n throw new Error(`Failed to create long tweet: ${errorText}`);\n }\n\n // Parse and return the response\n const data = await response.json();\n return data;\n}\n\nexport async function fetchListTweets(\n listId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth\n): Promise<QueryTweetsResponse> {\n if (maxTweets > 200) {\n maxTweets = 200;\n }\n\n const listTweetsRequest = apiRequestFactory.createListTweetsRequest();\n listTweetsRequest.variables.listId = listId;\n listTweetsRequest.variables.count = maxTweets;\n\n if (cursor != null && cursor !== \"\") {\n listTweetsRequest.variables.cursor = cursor;\n }\n\n const res = await requestApi<ListTimeline>(\n listTweetsRequest.toRequestUrl(),\n auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n return parseListTimelineTweets(res.value);\n}\n\nexport async function deleteTweet(tweetId: string, auth: TwitterAuth) {\n const onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n // Retrieve necessary cookies and tokens\n const cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const baseHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n ...Object.fromEntries(baseHeaders.entries()),\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n \"content-type\": \"application/json\",\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n });\n\n // Construct variables for the GraphQL request\n const variables: Record<string, any> = {\n tweet_id: tweetId,\n dark_request: false,\n };\n\n // Send the GraphQL request to delete a tweet\n const response = await fetch(\n \"https://twitter.com/i/api/graphql/VaenaVgh5q5ih7kvyVjgtg/DeleteTweet\",\n {\n headers,\n body: JSON.stringify({\n variables,\n queryId: \"VaenaVgh5q5ih7kvyVjgtg\",\n }),\n method: \"POST\",\n }\n );\n\n // Update the cookie jar with any new cookies from the response\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // Check for errors in the response\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n return response;\n}\n\nexport function getTweets(\n user: string,\n maxTweets: number,\n auth: TwitterAuth\n): AsyncGenerator<Tweet, void> {\n return getTweetTimeline(user, maxTweets, async (q, mt, c) => {\n const userIdRes = await getEntityIdByScreenName(q, auth);\n\n if (!userIdRes.success) {\n throw (userIdRes as any).err;\n }\n\n const { value: userId } = userIdRes;\n\n return fetchTweets(userId, mt, c, auth);\n });\n}\n\nexport function getTweetsByUserId(\n userId: string,\n maxTweets: number,\n auth: TwitterAuth\n): AsyncGenerator<Tweet, void> {\n return getTweetTimeline(userId, maxTweets, (q, mt, c) => {\n return fetchTweets(q, mt, c, auth);\n });\n}\n\nexport function getTweetsAndReplies(\n user: string,\n maxTweets: number,\n auth: TwitterAuth\n): AsyncGenerator<Tweet, void> {\n return getTweetTimeline(user, maxTweets, async (q, mt, c) => {\n const userIdRes = await getEntityIdByScreenName(q, auth);\n\n if (!userIdRes.success) {\n throw (userIdRes as any).err;\n }\n\n const { value: userId } = userIdRes;\n\n return fetchTweetsAndReplies(userId, mt, c, auth);\n });\n}\n\nexport function getTweetsAndRepliesByUserId(\n userId: string,\n maxTweets: number,\n auth: TwitterAuth\n): AsyncGenerator<Tweet, void> {\n return getTweetTimeline(userId, maxTweets, (q, mt, c) => {\n return fetchTweetsAndReplies(q, mt, c, auth);\n });\n}\n\nexport async function fetchLikedTweets(\n userId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth\n): Promise<QueryTweetsResponse> {\n if (!auth.isLoggedIn()) {\n throw new Error(\"Client is not logged-in for fetching liked tweets.\");\n }\n\n if (maxTweets > 200) {\n maxTweets = 200;\n }\n\n const userTweetsRequest = apiRequestFactory.createUserLikedTweetsRequest();\n userTweetsRequest.variables.userId = userId;\n userTweetsRequest.variables.count = maxTweets;\n userTweetsRequest.variables.includePromotedContent = false; // true on the website\n\n if (cursor != null && cursor !== \"\") {\n userTweetsRequest.variables.cursor = cursor;\n }\n\n const res = await requestApi<TimelineV2>(\n userTweetsRequest.toRequestUrl(),\n auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n return parseTimelineTweetsV2(res.value);\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\nexport interface TweetResultByRestId {\n data?: TimelineEntryItemContentRaw;\n}\n\nexport async function getTweet(\n id: string,\n auth: TwitterAuth\n): Promise<Tweet | null> {\n const tweetDetailRequest = apiRequestFactory.createTweetDetailRequest();\n tweetDetailRequest.variables.focalTweetId = id;\n\n const res = await requestApi<ThreadedConversation>(\n tweetDetailRequest.toRequestUrl(),\n auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n if (!res.value) {\n return null;\n }\n\n const tweets = parseThreadedConversation(res.value);\n return tweets.find((tweet) => tweet.id === id) ?? null;\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 const defaultTweetData = await getTweet(tweetData.data.id, auth);\n // Extract primary tweet data\n const parsedTweet = parseTweetV2ToV1(\n tweetData.data,\n tweetData?.includes,\n defaultTweetData\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(async (tweet) => await getTweetV2(tweet.id, auth, options))\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 const tweetResultByRestIdRequest =\n apiRequestFactory.createTweetResultByRestIdRequest();\n tweetResultByRestIdRequest.variables.tweetId = id;\n\n const res = await requestApi<TweetResultByRestId>(\n tweetResultByRestIdRequest.toRequestUrl(),\n auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n if (!res.value.data) {\n return null;\n }\n\n return parseTimelineEntryItemContentRaw(res.value.data, id);\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 const uploadUrl = \"https://upload.twitter.com/1.1/media/upload.json\";\n\n // Get authentication headers\n const cookies = await auth.cookieJar().getCookies(uploadUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n const headers = new Headers({\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(uploadUrl),\n \"x-csrf-token\": xCsrfToken?.value as string,\n });\n\n // Detect if media is a video based on mediaType\n const isVideo = mediaType.startsWith(\"video/\");\n\n if (isVideo) {\n // Handle video upload using chunked media upload\n const mediaId = await uploadVideoInChunks(mediaData, mediaType);\n return mediaId;\n }\n // Handle image upload\n const form = new FormData();\n form.append(\"media\", new Blob([mediaData]));\n\n const response = await fetch(uploadUrl, {\n method: \"POST\",\n headers,\n body: form,\n });\n\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n const data: MediaUploadResponse = await response.json();\n return data.media_id_string;\n\n // Function to upload video in chunks\n async function uploadVideoInChunks(\n mediaData: Buffer,\n mediaType: string\n ): Promise<string> {\n // Initialize upload\n const initParams = new URLSearchParams();\n initParams.append(\"command\", \"INIT\");\n initParams.append(\"media_type\", mediaType);\n initParams.append(\"total_bytes\", mediaData.length.toString());\n\n const initResponse = await fetch(uploadUrl, {\n method: \"POST\",\n headers,\n body: initParams,\n });\n\n if (!initResponse.ok) {\n throw new Error(await initResponse.text());\n }\n\n const initData = await initResponse.json();\n const mediaId = initData.media_id_string;\n\n // Append upload in chunks\n const segmentSize = 5 * 1024 * 1024; // 5 MB per chunk\n let segmentIndex = 0;\n for (let offset = 0; offset < mediaData.length; offset += segmentSize) {\n const chunk = mediaData.slice(offset, offset + segmentSize);\n\n const appendForm = new FormData();\n appendForm.append(\"command\", \"APPEND\");\n appendForm.append(\"media_id\", mediaId);\n appendForm.append(\"segment_index\", segmentIndex.toString());\n appendForm.append(\"media\", new Blob([chunk]));\n\n const appendResponse = await fetch(uploadUrl, {\n method: \"POST\",\n headers,\n body: appendForm,\n });\n\n if (!appendResponse.ok) {\n throw new Error(await appendResponse.text());\n }\n\n segmentIndex++;\n }\n\n // Finalize upload\n const finalizeParams = new URLSearchParams();\n finalizeParams.append(\"command\", \"FINALIZE\");\n finalizeParams.append(\"media_id\", mediaId);\n\n const finalizeResponse = await fetch(uploadUrl, {\n method: \"POST\",\n headers,\n body: finalizeParams,\n });\n\n if (!finalizeResponse.ok) {\n throw new Error(await finalizeResponse.text());\n }\n\n const finalizeData = await finalizeResponse.json();\n\n // Check processing status for videos\n if (finalizeData.processing_info) {\n await checkUploadStatus(mediaId);\n }\n\n return mediaId;\n }\n\n // Function to check upload status\n async function checkUploadStatus(mediaId: string): Promise<void> {\n let processing = true;\n while (processing) {\n await new Promise((resolve) => setTimeout(resolve, 5000)); // Wait 5 seconds\n\n const statusParams = new URLSearchParams();\n statusParams.append(\"command\", \"STATUS\");\n statusParams.append(\"media_id\", mediaId);\n\n const statusResponse = await fetch(\n `${uploadUrl}?${statusParams.toString()}`,\n {\n method: \"GET\",\n headers,\n }\n );\n\n if (!statusResponse.ok) {\n throw new Error(await statusResponse.text());\n }\n\n const statusData = await statusResponse.json();\n const state = statusData.processing_info.state;\n\n if (state === \"succeeded\") {\n processing = false;\n } else if (state === \"failed\") {\n throw new Error(\"Video processing failed\");\n }\n }\n }\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 onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n // Retrieve necessary cookies and tokens\n const cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const baseHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n ...Object.fromEntries(baseHeaders.entries()),\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n \"content-type\": \"application/json\",\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n });\n\n // Construct variables for the GraphQL request\n const variables: Record<string, any> = {\n tweet_text: text,\n dark_request: false,\n attachment_url: `https://twitter.com/twitter/status/${quotedTweetId}`,\n media: {\n media_entities: [],\n possibly_sensitive: false,\n },\n semantic_annotation_ids: [],\n };\n\n // Handle media uploads if any media data is provided\n if (mediaData && mediaData.length > 0) {\n const mediaIds = await Promise.all(\n mediaData.map(({ data, mediaType }) => uploadMedia(data, auth, mediaType))\n );\n\n variables.media.media_entities = mediaIds.map((id) => ({\n media_id: id,\n tagged_users: [],\n }));\n }\n\n // Send the GraphQL request to create a quote tweet\n const response = await fetch(\n \"https://twitter.com/i/api/graphql/a1p9RWpkYKBjWv_I3WzS-A/CreateTweet\",\n {\n headers,\n body: JSON.stringify({\n variables,\n features: {\n interactive_text_enabled: true,\n longform_notetweets_inline_media_enabled: false,\n responsive_web_text_conversations_enabled: false,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n false,\n vibe_api_enabled: false,\n rweb_lists_timeline_redesign_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled:\n false,\n tweetypie_unmention_optimization_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n longform_notetweets_rich_text_read_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n subscriptions_verification_info_enabled: true,\n subscriptions_verification_info_reason_enabled: true,\n subscriptions_verification_info_verified_since_enabled: true,\n super_follow_badge_privacy_enabled: false,\n super_follow_exclusive_tweet_notifications_enabled: false,\n super_follow_tweet_api_enabled: false,\n super_follow_user_api_enabled: false,\n android_graphql_skip_api_media_color_palette: false,\n creator_subscriptions_subscription_count_enabled: false,\n blue_business_profile_image_shape_enabled: false,\n unified_cards_ad_metadata_container_dynamic_card_content_query_enabled:\n false,\n rweb_video_timestamps_enabled: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: false,\n },\n fieldToggles: {},\n }),\n method: \"POST\",\n }\n );\n\n // Update the cookie jar with any new cookies from the response\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // Check for errors in the response\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n return response;\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 // Prepare the GraphQL endpoint and payload\n const likeTweetUrl =\n \"https://twitter.com/i/api/graphql/lI07N6Otwv1PhnEgXILM7A/FavoriteTweet\";\n\n // Retrieve necessary cookies and tokens\n const cookies = await auth.cookieJar().getCookies(likeTweetUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const headers = new Headers({\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(likeTweetUrl),\n \"content-type\": \"application/json\",\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n });\n\n const payload = {\n variables: {\n tweet_id: tweetId,\n },\n };\n\n // Send the POST request to like the tweet\n const response = await fetch(likeTweetUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify(payload),\n });\n\n // Update the cookie jar with any new cookies from the response\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // Check for errors in the response\n if (!response.ok) {\n throw new Error(await response.text());\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 // Prepare the GraphQL endpoint and payload\n const retweetUrl =\n \"https://twitter.com/i/api/graphql/ojPdsZsimiJrUGLR1sjUtA/CreateRetweet\";\n\n // Retrieve necessary cookies and tokens\n const cookies = await auth.cookieJar().getCookies(retweetUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const headers = new Headers({\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(retweetUrl),\n \"content-type\": \"application/json\",\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n });\n\n const payload = {\n variables: {\n tweet_id: tweetId,\n dark_request: false,\n },\n };\n\n // Send the POST request to retweet the tweet\n const response = await fetch(retweetUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify(payload),\n });\n\n // Update the cookie jar with any new cookies from the response\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // Check for errors in the response\n if (!response.ok) {\n throw new Error(await response.text());\n }\n}\n\nexport async function createCreateLongTweetRequest(\n text: string,\n auth: TwitterAuth,\n tweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[]\n) {\n // URL for the long tweet endpoint\n const url =\n \"https://x.com/i/api/graphql/YNXM2DGuE2Sff6a2JD3Ztw/CreateNoteTweet\";\n const onboardingTaskUrl = \"https://api.twitter.com/1.1/onboarding/task.json\";\n\n const cookies = await auth.cookieJar().getCookies(onboardingTaskUrl);\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n //@ ts-expect-error - This is a private API.\n const baseHeaders = await getTwitterApiHeaders();\n const headers = new Headers({\n ...Object.fromEntries(baseHeaders.entries()),\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(onboardingTaskUrl),\n \"content-type\": \"application/json\",\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-twitter-client-language\": \"en\",\n \"x-csrf-token\": xCsrfToken?.value as string,\n });\n\n const variables: Record<string, any> = {\n tweet_text: text,\n dark_request: false,\n media: {\n media_entities: [],\n possibly_sensitive: false,\n },\n semantic_annotation_ids: [],\n };\n\n if (mediaData && mediaData.length > 0) {\n const mediaIds = await Promise.all(\n mediaData.map(({ data, mediaType }) => uploadMedia(data, auth, mediaType))\n );\n\n variables.media.media_entities = mediaIds.map((id) => ({\n media_id: id,\n tagged_users: [],\n }));\n }\n\n if (tweetId) {\n variables.reply = { in_reply_to_tweet_id: tweetId };\n }\n\n const features = {\n premium_content_api_read_enabled: false,\n communities_web_enable_tweet_community_results_fetch: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n responsive_web_grok_analyze_button_fetch_trends_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n longform_notetweets_rich_text_read_enabled: true,\n longform_notetweets_inline_media_enabled: true,\n profile_label_improvements_pcf_label_in_post_enabled: false,\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n articles_preview_enabled: true,\n rweb_video_timestamps_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n };\n\n const response = await fetch(url, {\n headers,\n body: JSON.stringify({\n variables,\n features,\n queryId: \"YNXM2DGuE2Sff6a2JD3Ztw\",\n }),\n method: \"POST\",\n });\n\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n // check for errors\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n return response;\n}\n\nexport async function getArticle(\n id: string,\n auth: TwitterAuth\n): Promise<TimelineArticle | null> {\n const tweetDetailRequest =\n apiRequestFactory.createTweetDetailArticleRequest();\n tweetDetailRequest.variables.focalTweetId = id;\n\n const res = await requestApi<ThreadedConversation>(\n tweetDetailRequest.toRequestUrl(),\n auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n if (!res.value) {\n return null;\n }\n\n const articles = parseArticle(res.value);\n return articles.find((article) => article.id === id) ?? null;\n}\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 const baseUrl =\n \"https://twitter.com/i/api/graphql/VSnHXwLGADxxtetlPnO7xg/Retweeters\";\n\n // Build query parameters\n const variables = {\n tweetId,\n count,\n cursor,\n includePromotedContent: true,\n };\n const features = {\n profile_label_improvements_pcf_label_in_post_enabled: true,\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n premium_content_api_read_enabled: false,\n communities_web_enable_tweet_community_results_fetch: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n responsive_web_grok_analyze_button_fetch_trends_enabled: false,\n responsive_web_grok_analyze_post_followups_enabled: true,\n responsive_web_jetfuel_frame: false,\n responsive_web_grok_share_attachment_enabled: true,\n articles_preview_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n rweb_video_timestamps_enabled: true,\n longform_notetweets_rich_text_read_enabled: true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_grok_image_annotation_enabled: false,\n responsive_web_enhance_cards_enabled: false,\n };\n\n // Prepare URL with query params\n const url = new URL(baseUrl);\n url.searchParams.set(\"variables\", JSON.stringify(variables));\n url.searchParams.set(\"features\", JSON.stringify(features));\n\n // Retrieve necessary cookies and tokens\n const cookies = await auth.cookieJar().getCookies(url.toString());\n const xCsrfToken = cookies.find((cookie) => cookie.key === \"ct0\");\n\n const headers = new Headers({\n authorization: `Bearer ${(auth as any).bearerToken}`,\n cookie: await auth.cookieJar().getCookieString(url.toString()),\n \"content-type\": \"application/json\",\n \"x-guest-token\": (auth as any).guestToken,\n \"x-twitter-auth-type\": \"OAuth2Client\",\n \"x-twitter-active-user\": \"yes\",\n \"x-csrf-token\": xCsrfToken?.value || \"\",\n });\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers,\n });\n\n // Update cookies if needed\n await updateCookieJar(auth.cookieJar(), response.headers);\n\n if (!response.ok) {\n throw new Error(await response.text());\n }\n\n const json = await response.json();\n const instructions =\n json?.data?.retweeters_timeline?.timeline?.instructions || [];\n\n const retweeters: Retweeter[] = [];\n let bottomCursor: string | undefined;\n let topCursor: string | undefined;\n\n // Parse the retweeters from instructions\n for (const instruction of instructions) {\n if (instruction.type === \"TimelineAddEntries\") {\n for (const entry of instruction.entries) {\n // If this entry is a user entry\n if (entry.content?.itemContent?.user_results?.result) {\n const user = entry.content.itemContent.user_results.result;\n const description = user.legacy?.name ?? \"\";\n\n retweeters.push({\n rest_id: user.rest_id,\n screen_name: user.legacy?.screen_name ?? \"\",\n name: user.legacy?.name ?? \"\",\n description,\n });\n }\n\n // Capture the bottom cursor\n if (\n entry.content?.entryType === \"TimelineTimelineCursor\" &&\n entry.content?.cursorType === \"Bottom\"\n ) {\n bottomCursor = entry.content.value;\n }\n\n // Capture the top cursor\n if (\n entry.content?.entryType === \"TimelineTimelineCursor\" &&\n entry.content?.cursorType === \"Top\"\n ) {\n topCursor = entry.content.value;\n }\n }\n }\n }\n\n return { retweeters, bottomCursor, topCursor };\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 { Cookie } from \"tough-cookie\";\nimport type {\n TTweetv2Expansion,\n TTweetv2MediaField,\n TTweetv2PlaceField,\n TTweetv2PollField,\n TTweetv2TweetField,\n TTweetv2UserField,\n} from \"twitter-api-v2\";\nimport {\n type FetchTransformOptions,\n type RequestApiResult,\n bearerToken,\n requestApi,\n} from \"./api\";\nimport {\n type TwitterAuth,\n type TwitterAuthOptions,\n TwitterGuestAuth,\n} from \"./auth\";\nimport { TwitterUserAuth } from \"./auth-user\";\nimport {\n type GrokChatOptions,\n type GrokChatResponse,\n createGrokConversation,\n grokChat,\n} from \"./grok\";\nimport {\n type DirectMessagesResponse,\n type SendDirectMessageResponse,\n getDirectMessageConversations,\n sendDirectMessage,\n} from \"./messages\";\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 fetchQuotedTweetsPage,\n fetchSearchProfiles,\n fetchSearchTweets,\n searchProfiles,\n searchTweets,\n} from \"./search\";\nimport {\n fetchAudioSpaceById,\n fetchAuthenticatePeriscope,\n fetchBrowseSpaceTopics,\n fetchCommunitySelectQuery,\n fetchLiveVideoStreamStatus,\n fetchLoginTwitterToken,\n} from \"./spaces\";\nimport { fetchFollowingTimeline } from \"./timeline-following\";\nimport { fetchHomeTimeline } from \"./timeline-home\";\nimport type { QueryProfilesResponse, QueryTweetsResponse } from \"./timeline-v1\";\nimport {\n type TimelineArticle,\n type TimelineV2,\n parseTimelineTweetsV2,\n} from \"./timeline-v2\";\nimport { getTrends } from \"./trends\";\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 getArticle,\n getLatestTweet,\n getTweet,\n getTweetAnonymous,\n getTweetV2,\n getTweetWhere,\n getTweets,\n getTweetsAndReplies,\n getTweetsAndRepliesByUserId,\n getTweetsByUserId,\n getTweetsV2,\n getTweetsWhere,\n likeTweet,\n retweet,\n} from \"./tweets\";\nimport type {\n AudioSpace,\n Community,\n LiveVideoStreamStatus,\n LoginTwitterTokenResponse,\n Subtopic,\n} from \"./types/spaces\";\n\nconst twUrl = \"https://twitter.com\";\nconst UserTweetsUrl =\n \"https://twitter.com/i/api/graphql/E3opETHurmVJflFsUBVuUQ/UserTweets\";\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 undocumented API.\n * - Reusing Client objects is recommended to minimize the time spent authenticating unnecessarily.\n */\nexport class Client {\n private auth!: TwitterAuth;\n private authTrends!: TwitterAuth;\n private token: string;\n\n /**\n * Creates a new Client object.\n * - Clients maintain their own guest tokens for Twitter's internal API.\n * - Reusing Client objects is recommended to minimize the time spent authenticating unnecessarily.\n */\n constructor(private readonly options?: Partial<ClientOptions>) {\n this.token = bearerToken;\n this.useGuestAuth();\n }\n\n /**\n * Initializes auth properties using a guest token.\n * Used when creating a new instance of this class, and when logging out.\n * @internal\n */\n private useGuestAuth() {\n this.auth = new TwitterGuestAuth(this.token, this.getAuthOptions());\n this.authTrends = new TwitterGuestAuth(this.token, this.getAuthOptions());\n }\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 fetchSearchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n cursor?: string\n ): Promise<QueryTweetsResponse> {\n return fetchSearchTweets(query, maxTweets, searchMode, this.auth, cursor);\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 fetchSearchProfiles(\n query: string,\n maxProfiles: number,\n cursor?: string\n ): Promise<QueryProfilesResponse> {\n return fetchSearchProfiles(query, maxProfiles, this.auth, cursor);\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. (for you feed)\n * @param count The number of tweets to fetch.\n * @param seenTweetIds An array of tweet IDs that have already been seen.\n * @returns A promise that resolves to the home timeline response.\n */\n public async fetchHomeTimeline(\n count: number,\n seenTweetIds: string[]\n ): Promise<any[]> {\n return await fetchHomeTimeline(count, seenTweetIds, this.auth);\n }\n\n /**\n * Fetches the home timeline for the current user. (following feed)\n * @param count The number of tweets to fetch.\n * @param seenTweetIds An array of tweet IDs that have already been seen.\n * @returns A promise that resolves to the home timeline response.\n */\n public async fetchFollowingTimeline(\n count: number,\n seenTweetIds: string[]\n ): Promise<any[]> {\n return await fetchFollowingTimeline(count, seenTweetIds, this.auth);\n }\n\n async getUserTweets(\n userId: string,\n maxTweets = 200,\n cursor?: string\n ): Promise<{ tweets: Tweet[]; next?: string }> {\n if (maxTweets > 200) {\n maxTweets = 200;\n }\n\n const variables: Record<string, any> = {\n userId,\n count: maxTweets,\n includePromotedContent: true,\n withQuickPromoteEligibilityTweetFields: true,\n withVoice: true,\n withV2Timeline: true,\n };\n\n if (cursor) {\n variables.cursor = cursor;\n }\n\n const features = {\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n communities_web_enable_tweet_community_results_fetch: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n articles_preview_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n rweb_video_timestamps_enabled: true,\n longform_notetweets_rich_text_read_enabled: true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n };\n\n const fieldToggles = {\n withArticlePlainText: false,\n };\n\n const res = await requestApi<TimelineV2>(\n `${UserTweetsUrl}?variables=${encodeURIComponent(\n JSON.stringify(variables)\n )}&features=${encodeURIComponent(JSON.stringify(features))}&fieldToggles=${encodeURIComponent(\n JSON.stringify(fieldToggles)\n )}`,\n this.auth\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n const timelineV2 = parseTimelineTweetsV2(res.value);\n return {\n tweets: timelineV2.tweets,\n next: timelineV2.next,\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 return getTrends(this.authTrends);\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 if (this.auth instanceof TwitterUserAuth) {\n return getTweet(id, this.auth);\n }\n return getTweetAnonymous(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 * Returns if the client has a guest token. The token may not be valid.\n * @returns `true` if the client has a guest token; otherwise `false`.\n */\n public hasGuestToken(): boolean {\n return this.auth.hasToken() || this.authTrends.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 (\n (await this.auth.isLoggedIn()) && (await this.authTrends.isLoggedIn())\n );\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 as a real Twitter account. This enables running\n * searches.\n * @param username The username of the Twitter account to login with.\n * @param password The password of the Twitter account to login with.\n * @param email The email to log in with, if you have email confirmation enabled.\n * @param twoFactorSecret The secret to generate two factor authentication tokens with, if you have two factor authentication enabled.\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 // Swap in a real authorizer for all requests\n const userAuth = new TwitterUserAuth(this.token, this.getAuthOptions());\n await userAuth.login(\n username,\n password,\n email,\n twoFactorSecret,\n appKey,\n appSecret,\n accessToken,\n accessSecret\n );\n this.auth = userAuth;\n this.authTrends = userAuth;\n }\n\n /**\n * Log out of Twitter.\n */\n public async logout(): Promise<void> {\n await this.auth.logout();\n await this.authTrends.logout();\n\n // Swap in guest authorizers for all requests\n this.useGuestAuth();\n }\n\n /**\n * Retrieves all cookies for the current session.\n * @returns All cookies for the current session.\n */\n public async getCookies(): Promise<Cookie[]> {\n return await this.authTrends\n .cookieJar()\n .getCookies(\n typeof document !== \"undefined\" ? document.location.toString() : twUrl\n );\n }\n\n /**\n * Set cookies for the current session.\n * @param cookies The cookies to set for the current session.\n */\n public async setCookies(cookies: (string | Cookie)[]): Promise<void> {\n const userAuth = new TwitterUserAuth(this.token, this.getAuthOptions());\n for (const cookie of cookies) {\n await userAuth.cookieJar().setCookie(cookie, twUrl);\n }\n\n this.auth = userAuth;\n this.authTrends = userAuth;\n }\n\n /**\n * Clear all cookies for the current session.\n */\n public async clearCookies(): Promise<void> {\n await this.auth.cookieJar().removeAllCookies();\n await this.authTrends.cookieJar().removeAllCookies();\n }\n\n /**\n * Sets the optional cookie to be used in requests.\n * @param _cookie The cookie to be used in requests.\n * @deprecated This function no longer represents any part of Twitter's auth flow.\n * @returns This client instance.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n public withCookie(_cookie: string): Client {\n console.warn(\n \"Warning: Client#withCookie is deprecated and will be removed in a later version. Use Client#login or Client#setCookies instead.\"\n );\n return this;\n }\n\n /**\n * Sets the optional CSRF token to be used in requests.\n * @param _token The CSRF token to be used in requests.\n * @deprecated This function no longer represents any part of Twitter's auth flow.\n * @returns This client instance.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n public withXCsrfToken(_token: string): Client {\n console.warn(\n \"Warning: Client#withXCsrfToken is deprecated and will be removed in a later version.\"\n );\n return this;\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<Response> {\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 * @param count Number of conversations to fetch (default: 50)\n * @param cursor Pagination cursor for fetching more conversations\n * @returns Array of DM conversations and other details\n */\n public async getDirectMessageConversations(\n userId: string,\n cursor?: string\n ): Promise<DirectMessagesResponse> {\n return await getDirectMessageConversations(userId, this.auth, cursor);\n }\n\n /**\n * Sends a direct message to a user.\n * @param conversationId The ID of the conversation to send the message to.\n * @param text The text of the message to send.\n * @returns The response from the Twitter API.\n */\n public async sendDirectMessage(\n conversationId: string,\n text: string\n ): Promise<SendDirectMessageResponse> {\n return await sendDirectMessage(this.auth, conversationId, text);\n }\n\n private getAuthOptions(): Partial<TwitterAuthOptions> {\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 * Retrieves the details of an Audio Space by its ID.\n * @param id The ID of the Audio Space.\n * @returns The details of the Audio Space.\n */\n public async getAudioSpaceById(id: string): Promise<AudioSpace> {\n const variables = {\n id,\n isMetatagsQuery: false,\n withReplays: true,\n withListeners: true,\n };\n\n return await fetchAudioSpaceById(variables, this.auth);\n }\n\n /**\n * Retrieves available space topics.\n * @returns An array of space topics.\n */\n public async browseSpaceTopics(): Promise<Subtopic[]> {\n return await fetchBrowseSpaceTopics(this.auth);\n }\n\n /**\n * Retrieves available communities.\n * @returns An array of communities.\n */\n public async communitySelectQuery(): Promise<Community[]> {\n return await fetchCommunitySelectQuery(this.auth);\n }\n\n /**\n * Retrieves the status of an Audio Space stream by its media key.\n * @param mediaKey The media key of the Audio Space.\n * @returns The status of the Audio Space stream.\n */\n public async getAudioSpaceStreamStatus(\n mediaKey: string\n ): Promise<LiveVideoStreamStatus> {\n return await fetchLiveVideoStreamStatus(mediaKey, this.auth);\n }\n\n /**\n * Retrieves the status of an Audio Space by its ID.\n * This method internally fetches the Audio Space to obtain the media key,\n * then retrieves the stream status using the media key.\n * @param audioSpaceId The ID of the Audio Space.\n * @returns The status of the Audio Space stream.\n */\n public async getAudioSpaceStatus(\n audioSpaceId: string\n ): Promise<LiveVideoStreamStatus> {\n const audioSpace = await this.getAudioSpaceById(audioSpaceId);\n\n const mediaKey = audioSpace.metadata.media_key;\n if (!mediaKey) {\n throw new Error(\"Media Key not found in Audio Space metadata.\");\n }\n\n return await this.getAudioSpaceStreamStatus(mediaKey);\n }\n\n /**\n * Authenticates Periscope to obtain a token.\n * @returns The Periscope authentication token.\n */\n public async authenticatePeriscope(): Promise<string> {\n return await fetchAuthenticatePeriscope(this.auth);\n }\n\n /**\n * Logs in to Twitter via Proxsee using the Periscope JWT.\n * @param jwt The JWT obtained from AuthenticatePeriscope.\n * @returns The response containing the cookie and user information.\n */\n public async loginTwitterToken(\n jwt: string\n ): Promise<LoginTwitterTokenResponse> {\n return await fetchLoginTwitterToken(jwt, this.auth);\n }\n\n /**\n * Orchestrates the flow: get token -> login -> return Periscope cookie\n */\n public async getPeriscopeCookie(): Promise<string> {\n const periscopeToken = await this.authenticatePeriscope();\n\n const loginResponse = await this.loginTwitterToken(periscopeToken);\n\n return loginResponse.cookie;\n }\n\n /**\n * Fetches a article (long form tweet) by its ID.\n * @param id The ID of the article to fetch. In the format of (http://x.com/i/article/id)\n * @returns The {@link TimelineArticle} object, or `null` if it couldn't be fetched.\n */\n public getArticle(id: string): Promise<TimelineArticle | null> {\n return getArticle(id, this.auth);\n }\n\n /**\n * Creates a new conversation with Grok.\n * @returns A promise that resolves to the conversation ID string.\n */\n public async createGrokConversation(): Promise<string> {\n return await createGrokConversation(this.auth);\n }\n\n /**\n * Interact with Grok in a chat-like manner.\n * @param options The options for the Grok chat interaction.\n * @param {GrokMessage[]} options.messages - Array of messages in the conversation.\n * @param {string} [options.conversationId] - Optional ID of an existing conversation.\n * @param {boolean} [options.returnSearchResults] - Whether to return search results.\n * @param {boolean} [options.returnCitations] - Whether to return citations.\n * @returns A promise that resolves to the Grok chat response.\n */\n public async grokChat(options: GrokChatOptions): Promise<GrokChatResponse> {\n return await grokChat(options, this.auth);\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 tweets quoting a given tweet ID by chaining requests\n * until no more pages are available.\n * @param quotedTweetId The tweet ID to find quotes of.\n * @param maxTweetsPerPage Max tweets per page (default 20).\n * @returns An array of all Tweet objects referencing the given tweet.\n */\n public async getAllQuotedTweets(\n quotedTweetId: string,\n maxTweetsPerPage = 20\n ): Promise<Tweet[]> {\n const allQuotes: Tweet[] = [];\n let cursor: string | undefined;\n let prevCursor: string | undefined;\n\n while (true) {\n const page = await fetchQuotedTweetsPage(\n quotedTweetId,\n maxTweetsPerPage,\n this.auth,\n cursor\n );\n\n // If there's no new tweets, stop\n if (!page.tweets || page.tweets.length === 0) {\n break;\n }\n\n allQuotes.push(...page.tweets);\n\n // If next is missing or same => stop\n if (!page.next || page.next === cursor || page.next === prevCursor) {\n break;\n }\n\n // Move cursors\n prevCursor = cursor;\n cursor = page.next;\n }\n\n return allQuotes;\n }\n}\n","// src/core/Space.ts\n\nimport { EventEmitter } from 'node:events';\nimport type { Client } from '../../client';\nimport { Logger } from '../logger';\nimport type {\n AudioDataWithUser,\n BroadcastCreated,\n Plugin,\n PluginRegistration,\n SpaceConfig,\n SpeakerInfo,\n} from '../types';\nimport {\n authorizeToken,\n createBroadcast,\n getRegion,\n getTurnServers,\n muteSpeaker,\n publishBroadcast,\n setupCommonChatEvents,\n unmuteSpeaker,\n} from '../utils';\nimport { ChatClient } from './ChatClient';\nimport { JanusClient } from './JanusClient';\n\n/**\n * Manages the creation of a new Space (broadcast host):\n * 1) Creates the broadcast on Periscope\n * 2) Sets up Janus WebRTC for audio\n * 3) Optionally creates a ChatClient for interactive mode\n * 4) Allows managing (approve/remove) speakers, pushing audio, etc.\n */\n/**\n * Represents a space that can be used for communication and collaboration.\n * Extends the EventEmitter class and contains properties for debugging, logging, Janus client, chat client, authentication token,\n * and broadcast information.\n */\nexport class Space extends EventEmitter {\n private readonly debug: boolean;\n private readonly logger: Logger;\n\n private janusClient?: JanusClient;\n private chatClient?: ChatClient;\n\n private authToken?: string;\n private broadcastInfo?: BroadcastCreated;\n private isInitialized = false;\n\n private plugins = new Set<PluginRegistration>();\n private speakers = new Map<string, SpeakerInfo>();\n\n constructor(\n private readonly client: Client,\n options?: { debug?: boolean }\n ) {\n super();\n this.debug = options?.debug ?? false;\n this.logger = new Logger(this.debug);\n }\n\n /**\n * Registers a plugin and calls its onAttach(...).\n * init(...) will be invoked once initialization is complete.\n */\n public use(plugin: Plugin, config?: Record<string, any>) {\n const registration: PluginRegistration = { plugin, config };\n this.plugins.add(registration);\n\n this.logger.debug('[Space] Plugin added =>', plugin.constructor.name);\n plugin.onAttach?.({ space: this, pluginConfig: config });\n\n // If we've already initialized this Space, immediately call plugin.init(...)\n if (this.isInitialized && plugin.init) {\n plugin.init({ space: this, pluginConfig: config });\n // If Janus is also up, call onJanusReady\n if (this.janusClient) {\n plugin.onJanusReady?.(this.janusClient);\n }\n }\n\n return this;\n }\n\n /**\n * Main entry point to create and initialize the Space broadcast.\n */\n public async initialize(config: SpaceConfig) {\n this.logger.debug('[Space] Initializing...');\n\n // 1) Obtain the Periscope cookie + region\n const cookie = await this.client.getPeriscopeCookie();\n const region = await getRegion();\n this.logger.debug('[Space] Got region =>', region);\n\n // 2) Create a broadcast\n this.logger.debug('[Space] Creating broadcast...');\n const broadcast = await createBroadcast({\n description: config.description,\n languages: config.languages,\n cookie,\n region,\n record: config.record,\n });\n this.broadcastInfo = broadcast;\n\n // 3) Authorize to get an auth token\n this.logger.debug('[Space] Authorizing token...');\n this.authToken = await authorizeToken(cookie);\n\n // 4) Gather TURN servers\n this.logger.debug('[Space] Getting turn servers...');\n const turnServers = await getTurnServers(cookie);\n\n // 5) Create and initialize Janus for hosting\n this.janusClient = new JanusClient({\n webrtcUrl: broadcast.webrtc_gw_url,\n roomId: broadcast.room_id,\n credential: broadcast.credential,\n userId: broadcast.broadcast.user_id,\n streamName: broadcast.stream_name,\n turnServers,\n logger: this.logger,\n });\n await this.janusClient.initialize();\n\n // Forward PCM from Janus to plugin.onAudioData\n this.janusClient.on('audioDataFromSpeaker', (data: AudioDataWithUser) => {\n this.logger.debug('[Space] Received PCM from speaker =>', data.userId);\n this.handleAudioData(data);\n });\n\n // Update speaker info once we subscribe\n this.janusClient.on('subscribedSpeaker', ({ userId, feedId }) => {\n const speaker = this.speakers.get(userId);\n if (!speaker) {\n this.logger.debug('[Space] subscribedSpeaker => no speaker found', userId);\n return;\n }\n speaker.janusParticipantId = feedId;\n this.logger.debug(`[Space] updated speaker => userId=${userId}, feedId=${feedId}`);\n });\n\n // 6) Publish the broadcast so it's live\n this.logger.debug('[Space] Publishing broadcast...');\n await publishBroadcast({\n title: config.title || '',\n broadcast,\n cookie,\n janusSessionId: this.janusClient.getSessionId(),\n janusHandleId: this.janusClient.getHandleId(),\n janusPublisherId: this.janusClient.getPublisherId(),\n });\n\n // 7) If interactive => set up ChatClient\n if (config.mode === 'INTERACTIVE') {\n this.logger.debug('[Space] Connecting chat...');\n this.chatClient = new ChatClient({\n spaceId: broadcast.room_id,\n accessToken: broadcast.access_token,\n endpoint: broadcast.endpoint,\n logger: this.logger,\n });\n await this.chatClient.connect();\n this.setupChatEvents();\n }\n\n this.logger.info('[Space] Initialized =>', broadcast.share_url.replace('broadcasts', 'spaces'));\n this.isInitialized = true;\n\n // Call plugin.init(...) and onJanusReady(...) for all plugins now that we're set\n for (const { plugin, config: pluginConfig } of this.plugins) {\n plugin.init?.({ space: this, pluginConfig });\n plugin.onJanusReady?.(this.janusClient);\n }\n\n this.logger.debug('[Space] All plugins initialized');\n return broadcast;\n }\n\n /**\n * Send an emoji reaction via chat, if interactive.\n */\n public reactWithEmoji(emoji: string) {\n if (!this.chatClient) return;\n this.chatClient.reactWithEmoji(emoji);\n }\n\n /**\n * Internal method to wire up chat events if interactive.\n */\n private setupChatEvents() {\n if (!this.chatClient) return;\n setupCommonChatEvents(this.chatClient, this.logger, this);\n }\n\n /**\n * Approves a speaker request on Twitter side, then calls Janus to subscribe their audio.\n */\n public async approveSpeaker(userId: string, sessionUUID: string) {\n if (!this.isInitialized || !this.broadcastInfo) {\n throw new Error('[Space] Not initialized or missing broadcastInfo');\n }\n if (!this.authToken) {\n throw new Error('[Space] No auth token available');\n }\n\n // Store in our local speaker map\n this.speakers.set(userId, { userId, sessionUUID });\n\n // 1) Call Twitter's /request/approve\n await this.callApproveEndpoint(this.broadcastInfo, this.authToken, userId, sessionUUID);\n\n // 2) Subscribe to their audio in Janus\n await this.janusClient?.subscribeSpeaker(userId);\n }\n\n /**\n * Approve request => calls /api/v1/audiospace/request/approve\n */\n private async callApproveEndpoint(\n broadcast: BroadcastCreated,\n authorizationToken: string,\n userId: string,\n sessionUUID: string\n ): Promise<void> {\n const endpoint = 'https://guest.pscp.tv/api/v1/audiospace/request/approve';\n const headers = {\n 'Content-Type': 'application/json',\n Referer: 'https://x.com/',\n Authorization: authorizationToken,\n };\n const body = {\n ntpForBroadcasterFrame: '2208988800024000300',\n ntpForLiveFrame: '2208988800024000300',\n chat_token: broadcast.access_token,\n session_uuid: sessionUUID,\n };\n\n this.logger.debug('[Space] Approving speaker =>', endpoint, body);\n\n const resp = await fetch(endpoint, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n if (!resp.ok) {\n const error = await resp.text();\n throw new Error(`[Space] Failed to approve speaker => ${resp.status}: ${error}`);\n }\n\n this.logger.info('[Space] Speaker approved =>', userId);\n }\n\n /**\n * Removes a speaker from the Twitter side, then unsubscribes in Janus if needed.\n */\n public async removeSpeaker(userId: string) {\n if (!this.isInitialized || !this.broadcastInfo) {\n throw new Error('[Space] Not initialized or missing broadcastInfo');\n }\n if (!this.authToken) {\n throw new Error('[Space] No auth token');\n }\n if (!this.janusClient) {\n throw new Error('[Space] No Janus client');\n }\n\n // Find this speaker in local map\n const speaker = this.speakers.get(userId);\n if (!speaker) {\n throw new Error(`[Space] removeSpeaker => no speaker found for userId=${userId}`);\n }\n\n const { sessionUUID, janusParticipantId } = speaker;\n this.logger.debug('[Space] removeSpeaker =>', sessionUUID, janusParticipantId, speaker);\n\n if (!sessionUUID || janusParticipantId === undefined) {\n throw new Error(\n `[Space] removeSpeaker => missing sessionUUID or feedId for userId=${userId}`\n );\n }\n\n // 1) Eject on Twitter side\n const janusHandleId = this.janusClient.getHandleId();\n const janusSessionId = this.janusClient.getSessionId();\n if (!janusHandleId || !janusSessionId) {\n throw new Error(`[Space] removeSpeaker => missing Janus handle/session for userId=${userId}`);\n }\n\n await this.callRemoveEndpoint(\n this.broadcastInfo,\n this.authToken,\n sessionUUID,\n janusParticipantId,\n this.broadcastInfo.room_id,\n janusHandleId,\n janusSessionId\n );\n\n // 2) Remove from local map\n this.speakers.delete(userId);\n this.logger.info(`[Space] removeSpeaker => removed userId=${userId}`);\n }\n\n /**\n * Twitter's /api/v1/audiospace/stream/eject call\n */\n private async callRemoveEndpoint(\n broadcast: BroadcastCreated,\n authorizationToken: string,\n sessionUUID: string,\n janusParticipantId: number,\n janusRoomId: string,\n webrtcHandleId: number,\n webrtcSessionId: number\n ): Promise<void> {\n const endpoint = 'https://guest.pscp.tv/api/v1/audiospace/stream/eject';\n const headers = {\n 'Content-Type': 'application/json',\n Referer: 'https://x.com/',\n Authorization: authorizationToken,\n };\n const body = {\n ntpForBroadcasterFrame: '2208988800024000300',\n ntpForLiveFrame: '2208988800024000300',\n session_uuid: sessionUUID,\n chat_token: broadcast.access_token,\n janus_room_id: janusRoomId,\n janus_participant_id: janusParticipantId,\n webrtc_handle_id: webrtcHandleId,\n webrtc_session_id: webrtcSessionId,\n };\n\n this.logger.debug('[Space] Removing speaker =>', endpoint, body);\n\n const resp = await fetch(endpoint, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n if (!resp.ok) {\n const error = await resp.text();\n throw new Error(`[Space] Failed to remove speaker => ${resp.status}: ${error}`);\n }\n\n this.logger.debug('[Space] Speaker removed => sessionUUID=', sessionUUID);\n }\n\n /**\n * Push PCM audio frames if you're the host. Usually you'd do this if you're capturing\n * microphone input from the host side.\n */\n public pushAudio(samples: Int16Array, sampleRate: number) {\n this.janusClient?.pushLocalAudio(samples, sampleRate);\n }\n\n /**\n * Handler for PCM from other speakers, forwarded to plugin.onAudioData\n */\n private handleAudioData(data: AudioDataWithUser) {\n for (const { plugin } of this.plugins) {\n plugin.onAudioData?.(data);\n }\n }\n\n /**\n * Gracefully shut down this Space: destroy the Janus room, end the broadcast, etc.\n */\n public async finalizeSpace(): Promise<void> {\n this.logger.info('[Space] finalizeSpace => stopping broadcast gracefully');\n\n const tasks: Array<Promise<any>> = [];\n\n if (this.janusClient) {\n tasks.push(\n this.janusClient.destroyRoom().catch((err) => {\n this.logger.error('[Space] destroyRoom error =>', err);\n })\n );\n }\n\n if (this.broadcastInfo) {\n tasks.push(\n this.endAudiospace({\n broadcastId: this.broadcastInfo.room_id,\n chatToken: this.broadcastInfo.access_token,\n }).catch((err) => {\n this.logger.error('[Space] endAudiospace error =>', err);\n })\n );\n }\n\n if (this.janusClient) {\n tasks.push(\n this.janusClient.leaveRoom().catch((err) => {\n this.logger.error('[Space] leaveRoom error =>', err);\n })\n );\n }\n\n await Promise.all(tasks);\n this.logger.info('[Space] finalizeSpace => done.');\n }\n\n /**\n * Calls /api/v1/audiospace/admin/endAudiospace on Twitter side.\n */\n private async endAudiospace(params: { broadcastId: string; chatToken: string }): Promise<void> {\n const url = 'https://guest.pscp.tv/api/v1/audiospace/admin/endAudiospace';\n const headers = {\n 'Content-Type': 'application/json',\n Referer: 'https://x.com/',\n Authorization: this.authToken || '',\n };\n const body = {\n broadcast_id: params.broadcastId,\n chat_token: params.chatToken,\n };\n\n this.logger.debug('[Space] endAudiospace =>', body);\n\n const resp = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n if (!resp.ok) {\n const errText = await resp.text();\n throw new Error(`[Space] endAudiospace => ${resp.status} ${errText}`);\n }\n\n const json = await resp.json();\n this.logger.debug('[Space] endAudiospace => success =>', json);\n }\n\n /**\n * Retrieves an array of known speakers in this Space (by userId and sessionUUID).\n */\n public getSpeakers(): SpeakerInfo[] {\n return Array.from(this.speakers.values());\n }\n\n /**\n * Mute the host (yourself). For the host, session_uuid = '' (empty).\n */\n public async muteHost() {\n if (!this.authToken) {\n throw new Error('[Space] No auth token available');\n }\n if (!this.broadcastInfo) {\n throw new Error('[Space] No broadcastInfo');\n }\n\n await muteSpeaker({\n broadcastId: this.broadcastInfo.room_id,\n sessionUUID: '', // host => empty\n chatToken: this.broadcastInfo.access_token,\n authToken: this.authToken,\n });\n this.logger.info('[Space] Host muted successfully.');\n }\n\n /**\n * Unmute the host (yourself).\n */\n public async unmuteHost() {\n if (!this.authToken) {\n throw new Error('[Space] No auth token');\n }\n if (!this.broadcastInfo) {\n throw new Error('[Space] No broadcastInfo');\n }\n\n await unmuteSpeaker({\n broadcastId: this.broadcastInfo.room_id,\n sessionUUID: '',\n chatToken: this.broadcastInfo.access_token,\n authToken: this.authToken,\n });\n this.logger.info('[Space] Host unmuted successfully.');\n }\n\n /**\n * Mute a specific speaker. We'll retrieve sessionUUID from our local map.\n */\n public async muteSpeaker(userId: string) {\n if (!this.authToken) {\n throw new Error('[Space] No auth token available');\n }\n if (!this.broadcastInfo) {\n throw new Error('[Space] No broadcastInfo');\n }\n\n const speaker = this.speakers.get(userId);\n if (!speaker) {\n throw new Error(`[Space] Speaker not found for userId=${userId}`);\n }\n\n await muteSpeaker({\n broadcastId: this.broadcastInfo.room_id,\n sessionUUID: speaker.sessionUUID,\n chatToken: this.broadcastInfo.access_token,\n authToken: this.authToken,\n });\n this.logger.info(`[Space] Muted speaker => userId=${userId}`);\n }\n\n /**\n * Unmute a specific speaker. We'll retrieve sessionUUID from local map.\n */\n public async unmuteSpeaker(userId: string) {\n if (!this.authToken) {\n throw new Error('[Space] No auth token available');\n }\n if (!this.broadcastInfo) {\n throw new Error('[Space] No broadcastInfo');\n }\n\n const speaker = this.speakers.get(userId);\n if (!speaker) {\n throw new Error(`[Space] Speaker not found for userId=${userId}`);\n }\n\n await unmuteSpeaker({\n broadcastId: this.broadcastInfo.room_id,\n sessionUUID: speaker.sessionUUID,\n chatToken: this.broadcastInfo.access_token,\n authToken: this.authToken,\n });\n this.logger.info(`[Space] Unmuted speaker => userId=${userId}`);\n }\n\n /**\n * Stop the broadcast entirely, performing finalizeSpace() plus plugin cleanup.\n */\n public async stop() {\n this.logger.info('[Space] Stopping...');\n\n await this.finalizeSpace().catch((err) => {\n this.logger.error('[Space] finalizeBroadcast error =>', err);\n });\n\n // Disconnect chat if present\n if (this.chatClient) {\n await this.chatClient.disconnect();\n this.chatClient = undefined;\n }\n\n // Stop Janus if running\n if (this.janusClient) {\n await this.janusClient.stop();\n this.janusClient = undefined;\n }\n\n // Cleanup all plugins\n for (const { plugin } of this.plugins) {\n plugin.cleanup?.();\n }\n this.plugins.clear();\n\n this.isInitialized = false;\n }\n}\n","// src/logger.ts\n\n/**\n * Represents a Logger class for logging information, debug messages, warnings, and errors.\n */\nexport class Logger {\n private readonly debugEnabled: boolean;\n\n /**\n * Constructor for initializing a new instance of the class.\n *\n * @param {boolean} debugEnabled - Specifies whether debug mode is enabled or not.\n */\n constructor(debugEnabled: boolean) {\n this.debugEnabled = debugEnabled;\n }\n\n /**\n * Logs an info message with optional additional arguments.\n *\n * @param {string} msg - The info message to log.\n * @param {...any} args - Additional arguments to include in the log message.\n */\n info(msg: string, ...args: any[]) {\n console.log(msg, ...args);\n }\n\n /**\n * Logs a debug message if debug mode is enabled.\n *\n * @param {string} msg - The debug message to be logged.\n * @param {...any} args - Additional arguments to be passed to the console.log function.\n */\n debug(msg: string, ...args: any[]) {\n if (this.debugEnabled) {\n console.log(msg, ...args);\n }\n }\n\n /**\n * Logs a warning message to the console.\n *\n * @param {string} msg The warning message to be logged.\n * @param {...any} args Additional arguments to be logged along with the message.\n */\n warn(msg: string, ...args: any[]) {\n console.warn('[WARN]', msg, ...args);\n }\n\n /**\n * Logs an error message to the console.\n *\n * @param {string} msg - The error message to be logged.\n * @param {...any} args - Additional arguments to be logged along with the error message.\n */\n error(msg: string, ...args: any[]) {\n console.error(msg, ...args);\n }\n\n /**\n * Check if debug mode is enabled.\n * @returns {boolean} True if debug mode is enabled, false otherwise.\n */\n isDebugEnabled(): boolean {\n return this.debugEnabled;\n }\n}\n","// src/utils.ts\n\nimport type { EventEmitter } from 'node:events';\nimport { Headers } from 'headers-polyfill';\nimport type { ChatClient } from './core/ChatClient';\nimport type { Logger } from './logger';\nimport type { BroadcastCreated, TurnServersInfo } from './types';\n\n/**\n * Authorizes a token for guest access, using the provided Periscope cookie.\n * Returns an authorization token (bearer/JWT-like).\n */\n/**\n * Authorizes a token for a specified cookie.\n *\n * @param {string} cookie - The cookie to use for authorization.\n * @returns {Promise<string>} The authorized token.\n * @throws {Error} If the request fails or if the authorization_token is missing in the response.\n */\nexport async function authorizeToken(cookie: string): Promise<string> {\n const headers = new Headers({\n 'X-Periscope-User-Agent': 'Twitter/m5',\n 'Content-Type': 'application/json',\n 'X-Idempotence': Date.now().toString(),\n Referer: 'https://x.com/',\n 'X-Attempt': '1',\n });\n\n const resp = await fetch('https://proxsee.pscp.tv/api/v2/authorizeToken', {\n method: 'POST',\n headers,\n body: JSON.stringify({\n service: 'guest',\n cookie: cookie,\n }),\n });\n\n if (!resp.ok) {\n throw new Error(`authorizeToken => request failed with status ${resp.status}`);\n }\n\n const data = (await resp.json()) as { authorization_token: string };\n if (!data.authorization_token) {\n throw new Error('authorizeToken => Missing authorization_token in response');\n }\n\n return data.authorization_token;\n}\n\n/**\n * Publishes a newly created broadcast (Space) to make it live/visible.\n * Generally invoked after creating the broadcast and initializing Janus.\n */\nexport async function publishBroadcast(params: {\n title: string;\n broadcast: BroadcastCreated;\n cookie: string;\n janusSessionId?: number;\n janusHandleId?: number;\n janusPublisherId?: number;\n}): Promise<void> {\n const headers = new Headers({\n 'X-Periscope-User-Agent': 'Twitter/m5',\n 'Content-Type': 'application/json',\n Referer: 'https://x.com/',\n 'X-Idempotence': Date.now().toString(),\n 'X-Attempt': '1',\n });\n\n await fetch('https://proxsee.pscp.tv/api/v2/publishBroadcast', {\n method: 'POST',\n headers,\n body: JSON.stringify({\n accept_guests: true,\n broadcast_id: params.broadcast.room_id,\n webrtc_handle_id: params.janusHandleId,\n webrtc_session_id: params.janusSessionId,\n janus_publisher_id: params.janusPublisherId,\n janus_room_id: params.broadcast.room_id,\n cookie: params.cookie,\n status: params.title,\n conversation_controls: 0,\n }),\n });\n}\n\n/**\n * Retrieves TURN server credentials and URIs from Periscope.\n */\nexport async function getTurnServers(cookie: string): Promise<TurnServersInfo> {\n const headers = new Headers({\n 'X-Periscope-User-Agent': 'Twitter/m5',\n 'Content-Type': 'application/json',\n Referer: 'https://x.com/',\n 'X-Idempotence': Date.now().toString(),\n 'X-Attempt': '1',\n });\n\n const resp = await fetch('https://proxsee.pscp.tv/api/v2/turnServers', {\n method: 'POST',\n headers,\n body: JSON.stringify({ cookie }),\n });\n if (!resp.ok) {\n throw new Error(`getTurnServers => request failed with status ${resp.status}`);\n }\n return resp.json();\n}\n\n/**\n * Obtains the region from signer.pscp.tv, typically used when creating a broadcast.\n */\nexport async function getRegion(): Promise<string> {\n const resp = await fetch('https://signer.pscp.tv/region', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Referer: 'https://x.com',\n },\n body: JSON.stringify({}),\n });\n if (!resp.ok) {\n throw new Error(`getRegion => request failed with status ${resp.status}`);\n }\n const data = (await resp.json()) as { region: string };\n return data.region;\n}\n\n/**\n * Creates a new broadcast on Periscope/Twitter.\n * Used by the host to create the underlying audio-room structure.\n */\nexport async function createBroadcast(params: {\n description?: string;\n languages?: string[];\n cookie: string;\n region: string;\n record: boolean;\n}): Promise<BroadcastCreated> {\n const headers = new Headers({\n 'X-Periscope-User-Agent': 'Twitter/m5',\n 'Content-Type': 'application/json',\n 'X-Idempotence': Date.now().toString(),\n Referer: 'https://x.com/',\n 'X-Attempt': '1',\n });\n\n const resp = await fetch('https://proxsee.pscp.tv/api/v2/createBroadcast', {\n method: 'POST',\n headers,\n body: JSON.stringify({\n app_component: 'audio-room',\n content_type: 'visual_audio',\n cookie: params.cookie,\n conversation_controls: 0,\n description: params.description || '',\n height: 1080,\n is_360: false,\n is_space_available_for_replay: params.record,\n is_webrtc: true,\n languages: params.languages ?? [],\n region: params.region,\n width: 1920,\n }),\n });\n\n if (!resp.ok) {\n const text = await resp.text();\n throw new Error(`createBroadcast => request failed with status ${resp.status} ${text}`);\n }\n\n const data = await resp.json();\n return data as BroadcastCreated;\n}\n\n/**\n * Acquires chat access info (token, endpoint, etc.) from Periscope.\n * Needed to connect via WebSocket to the chat server.\n */\nexport async function accessChat(chatToken: string, cookie: string): Promise<any> {\n const url = 'https://proxsee.pscp.tv/api/v2/accessChat';\n const headers = new Headers({\n 'Content-Type': 'application/json',\n 'X-Periscope-User-Agent': 'Twitter/m5',\n });\n\n const body = {\n chat_token: chatToken,\n cookie,\n };\n\n const resp = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n if (!resp.ok) {\n throw new Error(`accessChat => request failed with status ${resp.status}`);\n }\n return resp.json();\n}\n\n/**\n * Registers this client as a viewer (POST /startWatching), returning a watch session token.\n */\nexport async function startWatching(lifecycleToken: string, cookie: string): Promise<string> {\n const url = 'https://proxsee.pscp.tv/api/v2/startWatching';\n const headers = new Headers({\n 'Content-Type': 'application/json',\n 'X-Periscope-User-Agent': 'Twitter/m5',\n });\n\n const body = {\n auto_play: false,\n life_cycle_token: lifecycleToken,\n cookie,\n };\n\n const resp = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n if (!resp.ok) {\n throw new Error(`startWatching => request failed with status ${resp.status}`);\n }\n const json = await resp.json();\n // Typically returns { session: \"...someToken...\" }\n return json.session;\n}\n\n/**\n * Deregisters this client from viewing the broadcast (POST /stopWatching).\n */\nexport async function stopWatching(session: string, cookie: string): Promise<void> {\n const url = 'https://proxsee.pscp.tv/api/v2/stopWatching';\n const headers = new Headers({\n 'Content-Type': 'application/json',\n 'X-Periscope-User-Agent': 'Twitter/m5',\n });\n\n const body = { session, cookie };\n const resp = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n if (!resp.ok) {\n throw new Error(`stopWatching => request failed with status ${resp.status}`);\n }\n}\n\n/**\n * Optional step: join an existing AudioSpace (POST /audiospace/join).\n * This might be required before you can request speaker.\n */\nexport async function joinAudioSpace(params: {\n broadcastId: string;\n chatToken: string;\n authToken: string;\n joinAsAdmin?: boolean;\n shouldAutoJoin?: boolean;\n}): Promise<any> {\n const url = 'https://guest.pscp.tv/api/v1/audiospace/join';\n\n const body = {\n ntpForBroadcasterFrame: '2208988800031000000',\n ntpForLiveFrame: '2208988800031000000',\n broadcast_id: params.broadcastId,\n join_as_admin: params.joinAsAdmin ?? false,\n should_auto_join: params.shouldAutoJoin ?? false,\n chat_token: params.chatToken,\n };\n\n const headers = new Headers({\n 'Content-Type': 'application/json',\n Authorization: params.authToken,\n });\n\n const resp = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n\n if (!resp.ok) {\n throw new Error(`joinAudioSpace => request failed with status ${resp.status}`);\n }\n // Typically returns { can_auto_join: boolean } etc.\n return resp.json();\n}\n\n/**\n * Submits a speaker request (POST /audiospace/request/submit),\n * returning the session UUID you need for negotiation.\n */\nexport async function submitSpeakerRequest(params: {\n broadcastId: string;\n chatToken: string;\n authToken: string;\n}): Promise<{ session_uuid: string }> {\n const url = 'https://guest.pscp.tv/api/v1/audiospace/request/submit';\n const headers = new Headers({\n 'Content-Type': 'application/json',\n Authorization: params.authToken,\n });\n\n const body = {\n ntpForBroadcasterFrame: '2208988800030000000',\n ntpForLiveFrame: '2208988800030000000',\n broadcast_id: params.broadcastId,\n chat_token: params.chatToken,\n };\n\n const resp = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n if (!resp.ok) {\n throw new Error(`submitSpeakerRequest => request failed with status ${resp.status}`);\n }\n return resp.json();\n}\n\n/**\n * Cancels a previously submitted speaker request (POST /audiospace/request/cancel).\n * Only valid if a request/submit was made first with a sessionUUID.\n */\nexport async function cancelSpeakerRequest(params: {\n broadcastId: string;\n sessionUUID: string;\n chatToken: string;\n authToken: string;\n}): Promise<void> {\n const url = 'https://guest.pscp.tv/api/v1/audiospace/request/cancel';\n const headers = new Headers({\n 'Content-Type': 'application/json',\n Authorization: params.authToken,\n });\n\n const body = {\n ntpForBroadcasterFrame: '2208988800002000000',\n ntpForLiveFrame: '2208988800002000000',\n broadcast_id: params.broadcastId,\n session_uuid: params.sessionUUID,\n chat_token: params.chatToken,\n };\n\n const resp = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n if (!resp.ok) {\n throw new Error(`cancelSpeakerRequest => request failed with status ${resp.status}`);\n }\n // Typically returns { \"success\": true }\n return resp.json();\n}\n\n/**\n * Negotiates a guest streaming session (POST /audiospace/stream/negotiate),\n * returning a Janus JWT and gateway URL for WebRTC.\n */\nexport async function negotiateGuestStream(params: {\n broadcastId: string;\n sessionUUID: string;\n authToken: string;\n cookie: string;\n}): Promise<{ janus_jwt: string; webrtc_gw_url: string }> {\n const url = 'https://guest.pscp.tv/api/v1/audiospace/stream/negotiate';\n const headers = new Headers({\n 'Content-Type': 'application/json',\n Authorization: params.authToken,\n });\n\n const body = {\n session_uuid: params.sessionUUID,\n };\n\n const resp = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n if (!resp.ok) {\n throw new Error(`negotiateGuestStream => request failed with status ${resp.status}`);\n }\n return resp.json();\n}\n\n/**\n * Mutes a speaker (POST /audiospace/muteSpeaker).\n * If called by the host, sessionUUID is \"\".\n * If called by a speaker, pass your own sessionUUID.\n */\nexport async function muteSpeaker(params: {\n broadcastId: string;\n sessionUUID?: string;\n chatToken: string;\n authToken: string;\n}): Promise<void> {\n const url = 'https://guest.pscp.tv/api/v1/audiospace/muteSpeaker';\n\n const body = {\n ntpForBroadcasterFrame: 2208988800031000000,\n ntpForLiveFrame: 2208988800031000000,\n session_uuid: params.sessionUUID ?? '',\n broadcast_id: params.broadcastId,\n chat_token: params.chatToken,\n };\n\n const headers = new Headers({\n 'Content-Type': 'application/json',\n Authorization: params.authToken,\n });\n\n const resp = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n if (!resp.ok) {\n const text = await resp.text();\n throw new Error(`muteSpeaker => ${resp.status} ${text}`);\n }\n}\n\n/**\n * Unmutes a speaker (POST /audiospace/unmuteSpeaker).\n * If called by the host, sessionUUID is \"\".\n * If called by a speaker, pass your own sessionUUID.\n */\nexport async function unmuteSpeaker(params: {\n broadcastId: string;\n sessionUUID?: string;\n chatToken: string;\n authToken: string;\n}): Promise<void> {\n const url = 'https://guest.pscp.tv/api/v1/audiospace/unmuteSpeaker';\n\n const body = {\n ntpForBroadcasterFrame: 2208988800031000000,\n ntpForLiveFrame: 2208988800031000000,\n session_uuid: params.sessionUUID ?? '',\n broadcast_id: params.broadcastId,\n chat_token: params.chatToken,\n };\n\n const headers = new Headers({\n 'Content-Type': 'application/json',\n Authorization: params.authToken,\n });\n\n const resp = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n if (!resp.ok) {\n const text = await resp.text();\n throw new Error(`unmuteSpeaker => ${resp.status} ${text}`);\n }\n}\n\n/**\n * Common chat events helper. Attaches listeners to a ChatClient, then re-emits them\n * through a given EventEmitter (e.g. Space or SpaceParticipant).\n */\nexport function setupCommonChatEvents(\n chatClient: ChatClient,\n logger: Logger,\n emitter: EventEmitter\n): void {\n // Occupancy updates\n chatClient.on('occupancyUpdate', (upd) => {\n logger.debug('[ChatEvents] occupancyUpdate =>', upd);\n emitter.emit('occupancyUpdate', upd);\n });\n\n // Reaction events\n chatClient.on('guestReaction', (reaction) => {\n logger.debug('[ChatEvents] guestReaction =>', reaction);\n emitter.emit('guestReaction', reaction);\n });\n\n // Mute state changes\n chatClient.on('muteStateChanged', (evt) => {\n logger.debug('[ChatEvents] muteStateChanged =>', evt);\n emitter.emit('muteStateChanged', evt);\n });\n\n // Speaker requests\n chatClient.on('speakerRequest', (req) => {\n logger.debug('[ChatEvents] speakerRequest =>', req);\n emitter.emit('speakerRequest', req);\n });\n\n // Additional event example: new speaker accepted\n chatClient.on('newSpeakerAccepted', (info) => {\n logger.debug('[ChatEvents] newSpeakerAccepted =>', info);\n emitter.emit('newSpeakerAccepted', info);\n });\n\n chatClient.on('newSpeakerRemoved', (info) => {\n logger.debug('[ChatEvents] newSpeakerRemoved =>', info);\n emitter.emit('newSpeakerRemoved', info);\n });\n}\n","// src/core/ChatClient.ts\n\nimport { EventEmitter } from 'node:events';\nimport WebSocket from 'ws';\nimport type { Logger } from '../logger';\nimport type { OccupancyUpdate, SpeakerRequest } from '../types';\nimport { getTwitterWebHeaders } from '../../browser-fingerprint';\n\n/**\n * Configuration object for ChatClient.\n */\n/**\n * @typedef {Object} ChatClientConfig\n * @property {string} spaceId - The space ID (e.g., \"1vOGwAbcdE...\") for this audio space.\n * @property {string} accessToken - The access token obtained from accessChat or the live_video_stream/status.\n * @property {string} endpoint - The endpoint host for the chat server (e.g., \"https://prod-chatman-ancillary-eu-central-1.pscp.tv\").\n * @property {Logger} logger - An instance of Logger for debug/info logs.\n */\ninterface ChatClientConfig {\n /**\n * The space ID (e.g., \"1vOGwAbcdE...\") for this audio space.\n */\n spaceId: string;\n\n /**\n * The access token obtained from accessChat or the live_video_stream/status.\n */\n accessToken: string;\n\n /**\n * The endpoint host for the chat server (e.g., \"https://prod-chatman-ancillary-eu-central-1.pscp.tv\").\n */\n endpoint: string;\n\n /**\n * An instance of Logger for debug/info logs.\n */\n logger: Logger;\n}\n\n/**\n * ChatClient handles the WebSocket connection to the Twitter/Periscope chat API.\n * It emits events such as \"speakerRequest\", \"occupancyUpdate\", \"muteStateChanged\", etc.\n */\nexport class ChatClient extends EventEmitter {\n private ws?: WebSocket;\n private connected = false;\n\n private readonly logger: Logger;\n private readonly spaceId: string;\n private readonly accessToken: string;\n private endpoint: string;\n\n constructor(config: ChatClientConfig) {\n super();\n this.spaceId = config.spaceId;\n this.accessToken = config.accessToken;\n this.endpoint = config.endpoint;\n this.logger = config.logger;\n }\n\n /**\n * Establishes a WebSocket connection to the chat endpoint and sets up event handlers.\n */\n public async connect(): Promise<void> {\n const wsUrl = `${this.endpoint}/chatapi/v1/chatnow`.replace('https://', 'wss://');\n this.logger.info('[ChatClient] Connecting =>', wsUrl);\n\n const headers = await getTwitterWebHeaders();\n this.ws = new WebSocket(wsUrl, {\n headers: {\n Origin: 'https://x.com',\n 'User-Agent': headers['User-Agent'],\n },\n });\n\n await this.setupHandlers();\n }\n\n /**\n * Internal method to set up WebSocket event listeners (open, message, close, error).\n */\n private setupHandlers(): Promise<void> {\n if (!this.ws) {\n throw new Error('[ChatClient] No WebSocket instance available');\n }\n\n return new Promise((resolve, reject) => {\n this.ws?.on('open', () => {\n this.logger.info('[ChatClient] Connected');\n this.connected = true;\n this.sendAuthAndJoin();\n resolve();\n });\n\n this.ws?.on('message', (data: { toString: () => string }) => {\n this.handleMessage(data.toString());\n });\n\n this.ws?.on('close', () => {\n this.logger.info('[ChatClient] Closed');\n this.connected = false;\n this.emit('disconnected');\n });\n\n this.ws?.on('error', (err) => {\n this.logger.error('[ChatClient] Error =>', err);\n reject(err);\n });\n });\n }\n\n /**\n * Sends two WebSocket messages to authenticate and join the specified space.\n */\n private sendAuthAndJoin(): void {\n if (!this.ws) return;\n\n // 1) Send authentication (access token)\n this.ws.send(\n JSON.stringify({\n payload: JSON.stringify({ access_token: this.accessToken }),\n kind: 3,\n })\n );\n\n // 2) Send a \"join\" message specifying the room (space ID)\n this.ws.send(\n JSON.stringify({\n payload: JSON.stringify({\n body: JSON.stringify({ room: this.spaceId }),\n kind: 1,\n }),\n kind: 2,\n })\n );\n }\n\n /**\n * Sends an emoji reaction to the chat server.\n * @param emoji - The emoji string, e.g. '🔥', '🙏', etc.\n */\n public reactWithEmoji(emoji: string): void {\n if (!this.ws || !this.connected) {\n this.logger.warn('[ChatClient] Not connected or WebSocket missing; ignoring reactWithEmoji.');\n return;\n }\n\n const payload = JSON.stringify({\n body: JSON.stringify({ body: emoji, type: 2, v: 2 }),\n kind: 1,\n /*\n // The 'sender' field is not required, it's not even verified by the server\n // Instead of passing attributes down here it's easier to ignore it\n sender: {\n user_id: null,\n twitter_id: null,\n username: null,\n display_name: null,\n },\n */\n payload: JSON.stringify({\n room: this.spaceId,\n body: JSON.stringify({ body: emoji, type: 2, v: 2 }),\n }),\n type: 2,\n });\n\n this.ws.send(payload);\n }\n\n /**\n * Handles inbound WebSocket messages, parsing JSON payloads\n * and emitting relevant events (speakerRequest, occupancyUpdate, etc.).\n */\n private handleMessage(raw: string): void {\n let msg: any;\n try {\n msg = JSON.parse(raw);\n } catch {\n return; // Invalid JSON, ignoring\n }\n if (!msg.payload) return;\n\n const payload = safeJson(msg.payload);\n if (!payload?.body) return;\n\n const body = safeJson(payload.body);\n\n // 1) Speaker request => \"guestBroadcastingEvent=1\"\n if (body.guestBroadcastingEvent === 1) {\n const req: SpeakerRequest = {\n userId: body.guestRemoteID,\n username: body.guestUsername,\n displayName: payload.sender?.display_name || body.guestUsername,\n sessionUUID: body.sessionUUID,\n };\n this.emit('speakerRequest', req);\n }\n\n // 2) Occupancy update => body.occupancy\n if (typeof body.occupancy === 'number') {\n const update: OccupancyUpdate = {\n occupancy: body.occupancy,\n totalParticipants: body.total_participants || 0,\n };\n this.emit('occupancyUpdate', update);\n }\n\n // 3) Mute/unmute => \"guestBroadcastingEvent=16\" (mute) or \"17\" (unmute)\n if (body.guestBroadcastingEvent === 16) {\n this.emit('muteStateChanged', {\n userId: body.guestRemoteID,\n muted: true,\n });\n }\n if (body.guestBroadcastingEvent === 17) {\n this.emit('muteStateChanged', {\n userId: body.guestRemoteID,\n muted: false,\n });\n }\n\n // 4) \"guestBroadcastingEvent=12\" => host accepted a speaker\n if (body.guestBroadcastingEvent === 12) {\n this.emit('newSpeakerAccepted', {\n userId: body.guestRemoteID,\n username: body.guestUsername,\n sessionUUID: body.sessionUUID,\n });\n }\n\n // 5) \"guestBroadcastingEvent=10\" => host removed a speaker\n if (body.guestBroadcastingEvent === 10) {\n this.emit('newSpeakerRemoved', {\n userId: body.guestRemoteID,\n username: body.guestUsername,\n sessionUUID: body.sessionUUID,\n });\n }\n\n // 6) Reaction => body.type=2\n if (body?.type === 2) {\n this.logger.debug('[ChatClient] Emitting guestReaction =>', body);\n this.emit('guestReaction', {\n displayName: body.displayName,\n emoji: body.body,\n });\n }\n }\n\n /**\n * Closes the WebSocket connection if open, and resets internal state.\n */\n public async disconnect(): Promise<void> {\n if (this.ws) {\n this.logger.info('[ChatClient] Disconnecting...');\n this.ws.close();\n this.ws = undefined;\n this.connected = false;\n }\n }\n}\n\n/**\n * Helper function to safely parse JSON without throwing.\n */\nfunction safeJson(text: string): any {\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n","// src/core/JanusClient.ts\n\nimport { EventEmitter } from 'node:events';\nimport wrtc from '@roamhq/wrtc';\nconst { RTCPeerConnection, MediaStream } = wrtc;\nimport type { Logger } from '../logger';\nimport type { AudioDataWithUser, TurnServersInfo } from '../types';\nimport { JanusAudioSink, JanusAudioSource } from './JanusAudio';\n\n/**\n * Interface representing the configuration settings for the Janus gateway.\n * @typedef {Object} JanusConfig\n * @property {string} webrtcUrl - The base URL for the Janus gateway.\n * @property {string} roomId - The unique room ID.\n * @property {string} credential - The token/credential used to authorize requests to Janus.\n * @property {string} userId - The user identifier (host or speaker).\n * @property {string} streamName - The name of the stream.\n * @property {TurnServersInfo} turnServers - ICE/TURN server information returned by Twitter's /turnServers endpoint.\n * @property {Logger} logger - Logger instance for consistent debug/info/error logs.\n */\ninterface JanusConfig {\n /**\n * The base URL for the Janus gateway (e.g. \"https://gw-prod-hydra-eu-west-3.pscp.tv/s=prod:XX/v1/gateway\")\n */\n webrtcUrl: string;\n\n /**\n * The unique room ID (e.g., the broadcast or space ID)\n */\n roomId: string;\n\n /**\n * The token/credential used to authorize requests to Janus (often a signed JWT).\n */\n credential: string;\n\n /**\n * The user identifier (host or speaker). Used as 'display' in the Janus plugin.\n */\n userId: string;\n\n /**\n * The name of the stream (often the same as roomId for convenience).\n */\n streamName: string;\n\n /**\n * ICE / TURN server information returned by Twitter's /turnServers endpoint.\n */\n turnServers: TurnServersInfo;\n\n /**\n * Logger instance for consistent debug/info/error logs.\n */\n logger: Logger;\n}\n\n/**\n * Manages the Janus session for a Twitter AudioSpace:\n * - Creates a Janus session and plugin handle\n * - Joins the Janus videoroom as publisher/subscriber\n * - Subscribes to other speakers\n * - Sends local PCM frames as Opus\n * - Polls for Janus events\n *\n * It can be used by both the host (who creates a room) or a guest speaker (who joins an existing room).\n */\nexport class JanusClient extends EventEmitter {\n private logger: Logger;\n\n private sessionId?: number;\n private handleId?: number;\n private publisherId?: number;\n\n private pc?: RTCPeerConnection;\n private localAudioSource?: JanusAudioSource;\n\n private pollActive = false;\n\n // Tracks promises waiting for specific Janus events\n private eventWaiters: Array<{\n predicate: (evt: any) => boolean;\n resolve: (value: any) => void;\n reject: (error: Error) => void;\n }> = [];\n\n // Tracks subscriber handle+pc for each userId we subscribe to\n private subscribers = new Map<\n string,\n {\n handleId: number;\n pc: RTCPeerConnection;\n }\n >();\n\n constructor(private readonly config: JanusConfig) {\n super();\n this.logger = config.logger;\n }\n\n /**\n * Initializes this JanusClient for the host scenario:\n * 1) createSession()\n * 2) attachPlugin()\n * 3) createRoom()\n * 4) joinRoom()\n * 5) configure local PeerConnection (send audio, etc.)\n */\n public async initialize(): Promise<void> {\n this.logger.debug('[JanusClient] initialize() called');\n\n this.sessionId = await this.createSession();\n this.handleId = await this.attachPlugin();\n\n // Start polling for Janus events\n this.pollActive = true;\n this.startPolling();\n\n // Create a new Janus room (only for the host scenario)\n await this.createRoom();\n\n // Join that room as publisher\n this.publisherId = await this.joinRoom();\n\n // Set up our RTCPeerConnection for local audio\n this.pc = new RTCPeerConnection({\n iceServers: [\n {\n urls: this.config.turnServers.uris,\n username: this.config.turnServers.username,\n credential: this.config.turnServers.password,\n },\n ],\n });\n this.setupPeerEvents();\n\n // Add local audio track\n this.enableLocalAudio();\n\n // Create an offer and configure the publisher in Janus\n await this.configurePublisher();\n\n this.logger.info('[JanusClient] Initialization complete');\n }\n\n /**\n * Initializes this JanusClient for a guest speaker scenario:\n * 1) createSession()\n * 2) attachPlugin()\n * 3) join existing room as publisher (no createRoom call)\n * 4) configure local PeerConnection\n * 5) subscribe to any existing publishers\n */\n public async initializeGuestSpeaker(sessionUUID: string): Promise<void> {\n this.logger.debug('[JanusClient] initializeGuestSpeaker() called');\n\n // 1) Create a new Janus session\n this.sessionId = await this.createSession();\n this.handleId = await this.attachPlugin();\n\n // Start polling\n this.pollActive = true;\n this.startPolling();\n\n // 2) Join the existing room as a publisher (no createRoom)\n const evtPromise = this.waitForJanusEvent(\n (e) =>\n e.janus === 'event' &&\n e.plugindata?.plugin === 'janus.plugin.videoroom' &&\n e.plugindata?.data?.videoroom === 'joined',\n 10000,\n 'Guest Speaker joined event'\n );\n\n const body = {\n request: 'join',\n room: this.config.roomId,\n ptype: 'publisher',\n display: this.config.userId,\n periscope_user_id: this.config.userId,\n };\n await this.sendJanusMessage(this.handleId, body);\n\n // Wait for the joined event\n const evt = await evtPromise;\n const data = evt.plugindata?.data;\n this.publisherId = data.id; // Our own publisherId\n this.logger.debug('[JanusClient] guest joined => publisherId=', this.publisherId);\n\n // If there are existing publishers, we can subscribe to them\n const publishers = data.publishers || [];\n this.logger.debug('[JanusClient] existing publishers =>', publishers);\n\n // 3) Create RTCPeerConnection for sending local audio\n this.pc = new RTCPeerConnection({\n iceServers: [\n {\n urls: this.config.turnServers.uris,\n username: this.config.turnServers.username,\n credential: this.config.turnServers.password,\n },\n ],\n });\n this.setupPeerEvents();\n this.enableLocalAudio();\n\n // 4) configurePublisher => generate offer, wait for answer\n await this.configurePublisher(sessionUUID);\n\n // 5) Subscribe to each existing publisher\n await Promise.all(publishers.map((pub: any) => this.subscribeSpeaker(pub.display, pub.id)));\n\n this.logger.info('[JanusClient] Guest speaker negotiation complete');\n }\n\n /**\n * Subscribes to a speaker's audio feed by userId and/or feedId.\n * If feedId=0, we wait for a \"publishers\" event to discover feedId.\n */\n public async subscribeSpeaker(userId: string, feedId = 0): Promise<void> {\n this.logger.debug('[JanusClient] subscribeSpeaker => userId=', userId);\n\n // 1) Attach a separate plugin handle for subscriber\n const subscriberHandleId = await this.attachPlugin();\n this.logger.debug('[JanusClient] subscriber handle =>', subscriberHandleId);\n\n // If feedId was not provided, wait for an event listing publishers\n if (feedId === 0) {\n const publishersEvt = await this.waitForJanusEvent(\n (e) =>\n e.janus === 'event' &&\n e.plugindata?.plugin === 'janus.plugin.videoroom' &&\n e.plugindata?.data?.videoroom === 'event' &&\n Array.isArray(e.plugindata?.data?.publishers) &&\n e.plugindata?.data?.publishers.length > 0,\n 8000,\n 'discover feed_id from \"publishers\"'\n );\n\n const list = publishersEvt.plugindata.data.publishers as any[];\n const pub = list.find((p) => p.display === userId || p.periscope_user_id === userId);\n if (!pub) {\n throw new Error(\n `[JanusClient] subscribeSpeaker => No publisher found for userId=${userId}`\n );\n }\n feedId = pub.id;\n this.logger.debug('[JanusClient] found feedId =>', feedId);\n }\n\n // Notify listeners that we've discovered a feed\n this.emit('subscribedSpeaker', { userId, feedId });\n\n // 2) Join the room as a \"subscriber\"\n const joinBody = {\n request: 'join',\n room: this.config.roomId,\n periscope_user_id: this.config.userId,\n ptype: 'subscriber',\n streams: [\n {\n feed: feedId,\n mid: '0',\n send: true, // indicates we might send audio?\n },\n ],\n };\n await this.sendJanusMessage(subscriberHandleId, joinBody);\n\n // 3) Wait for \"attached\" + jsep.offer\n const attachedEvt = await this.waitForJanusEvent(\n (e) =>\n e.janus === 'event' &&\n e.sender === subscriberHandleId &&\n e.plugindata?.plugin === 'janus.plugin.videoroom' &&\n e.plugindata?.data?.videoroom === 'attached' &&\n e.jsep?.type === 'offer',\n 8000,\n 'subscriber attached + offer'\n );\n this.logger.debug('[JanusClient] subscriber => \"attached\" with offer');\n\n // 4) Create a new RTCPeerConnection for receiving audio from this feed\n const offer = attachedEvt.jsep;\n const subPc = new RTCPeerConnection({\n iceServers: [\n {\n urls: this.config.turnServers.uris,\n username: this.config.turnServers.username,\n credential: this.config.turnServers.password,\n },\n ],\n });\n\n subPc.ontrack = (evt) => {\n this.logger.debug(\n '[JanusClient] subscriber track => kind=%s, readyState=%s, muted=%s',\n evt.track.kind,\n evt.track.readyState,\n evt.track.muted\n );\n // Attach a JanusAudioSink to capture PCM\n const sink = new JanusAudioSink(evt.track, { logger: this.logger });\n\n // For each audio frame, forward it to 'audioDataFromSpeaker'\n sink.on('audioData', (frame) => {\n if (this.logger.isDebugEnabled()) {\n let maxVal = 0;\n for (let i = 0; i < frame.samples.length; i++) {\n const val = Math.abs(frame.samples[i]);\n if (val > maxVal) maxVal = val;\n }\n this.logger.debug(`[AudioSink] userId=${userId}, maxAmplitude=${maxVal}`);\n }\n\n this.emit('audioDataFromSpeaker', {\n userId,\n bitsPerSample: frame.bitsPerSample,\n sampleRate: frame.sampleRate,\n numberOfFrames: frame.numberOfFrames,\n channelCount: frame.channelCount,\n samples: frame.samples,\n } as AudioDataWithUser);\n });\n };\n\n // 5) Answer the subscription offer\n await subPc.setRemoteDescription(offer);\n const answer = await subPc.createAnswer();\n await subPc.setLocalDescription(answer);\n\n // 6) Send \"start\" request to begin receiving\n await this.sendJanusMessage(\n subscriberHandleId,\n {\n request: 'start',\n room: this.config.roomId,\n periscope_user_id: this.config.userId,\n },\n answer\n );\n\n this.logger.debug('[JanusClient] subscriber => done (user=', userId, ')');\n\n // Track this subscription handle+pc by userId\n this.subscribers.set(userId, { handleId: subscriberHandleId, pc: subPc });\n }\n\n /**\n * Pushes local PCM frames to Janus. If the localAudioSource isn't active, it enables it.\n */\n public pushLocalAudio(samples: Int16Array, sampleRate: number, channels = 1) {\n if (!this.localAudioSource) {\n this.logger.warn('[JanusClient] No localAudioSource => enabling now...');\n this.enableLocalAudio();\n }\n this.localAudioSource?.pushPcmData(samples, sampleRate, channels);\n }\n\n /**\n * Ensures a local audio track is added to the RTCPeerConnection for publishing.\n */\n public enableLocalAudio(): void {\n if (!this.pc) {\n this.logger.warn('[JanusClient] enableLocalAudio => No RTCPeerConnection');\n return;\n }\n if (this.localAudioSource) {\n this.logger.debug('[JanusClient] localAudioSource already active');\n return;\n }\n // Create a JanusAudioSource that feeds PCM frames\n this.localAudioSource = new JanusAudioSource({ logger: this.logger });\n const track = this.localAudioSource.getTrack();\n const localStream = new MediaStream();\n localStream.addTrack(track);\n this.pc.addTrack(track, localStream);\n }\n\n /**\n * Stops the Janus client: ends polling, closes the RTCPeerConnection, etc.\n * Does not destroy or leave the room automatically; call destroyRoom() or leaveRoom() if needed.\n */\n public async stop(): Promise<void> {\n this.logger.info('[JanusClient] Stopping...');\n this.pollActive = false;\n if (this.pc) {\n this.pc.close();\n this.pc = undefined;\n }\n }\n\n /**\n * Returns the current Janus sessionId, if any.\n */\n public getSessionId(): number | undefined {\n return this.sessionId;\n }\n\n /**\n * Returns the Janus handleId for the publisher, if any.\n */\n public getHandleId(): number | undefined {\n return this.handleId;\n }\n\n /**\n * Returns the Janus publisherId (internal participant ID), if any.\n */\n public getPublisherId(): number | undefined {\n return this.publisherId;\n }\n\n /**\n * Creates a new Janus session via POST /janus (with \"janus\":\"create\").\n */\n private async createSession(): Promise<number> {\n const transaction = this.randomTid();\n const resp = await fetch(this.config.webrtcUrl, {\n method: 'POST',\n headers: {\n Authorization: this.config.credential,\n 'Content-Type': 'application/json',\n Referer: 'https://x.com',\n },\n body: JSON.stringify({\n janus: 'create',\n transaction,\n }),\n });\n if (!resp.ok) {\n throw new Error('[JanusClient] createSession failed');\n }\n const json = await resp.json();\n if (json.janus !== 'success') {\n throw new Error('[JanusClient] createSession invalid response');\n }\n return json.data.id;\n }\n\n /**\n * Attaches to the videoroom plugin via /janus/{sessionId} (with \"janus\":\"attach\").\n */\n private async attachPlugin(): Promise<number> {\n if (!this.sessionId) {\n throw new Error('[JanusClient] attachPlugin => no sessionId');\n }\n const transaction = this.randomTid();\n const resp = await fetch(`${this.config.webrtcUrl}/${this.sessionId}`, {\n method: 'POST',\n headers: {\n Authorization: this.config.credential,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n janus: 'attach',\n plugin: 'janus.plugin.videoroom',\n transaction,\n }),\n });\n if (!resp.ok) {\n throw new Error('[JanusClient] attachPlugin failed');\n }\n const json = await resp.json();\n if (json.janus !== 'success') {\n throw new Error('[JanusClient] attachPlugin invalid response');\n }\n return json.data.id;\n }\n\n /**\n * Creates a Janus room for the host scenario.\n * For a guest, this step is skipped (the room already exists).\n */\n private async createRoom(): Promise<void> {\n if (!this.sessionId || !this.handleId) {\n throw new Error('[JanusClient] createRoom => No session/handle');\n }\n const transaction = this.randomTid();\n const body = {\n request: 'create',\n room: this.config.roomId,\n periscope_user_id: this.config.userId,\n audiocodec: 'opus',\n videocodec: 'h264',\n transport_wide_cc_ext: true,\n app_component: 'audio-room',\n h264_profile: '42e01f',\n dummy_publisher: false,\n };\n const resp = await fetch(`${this.config.webrtcUrl}/${this.sessionId}/${this.handleId}`, {\n method: 'POST',\n headers: {\n Authorization: this.config.credential,\n 'Content-Type': 'application/json',\n Referer: 'https://x.com',\n },\n body: JSON.stringify({\n janus: 'message',\n transaction,\n body,\n }),\n });\n if (!resp.ok) {\n throw new Error(`[JanusClient] createRoom failed => ${resp.status}`);\n }\n const json = await resp.json();\n this.logger.debug('[JanusClient] createRoom =>', JSON.stringify(json));\n\n if (json.janus === 'error') {\n throw new Error(`[JanusClient] createRoom error => ${json.error?.reason || 'Unknown'}`);\n }\n if (json.plugindata?.data?.videoroom !== 'created') {\n throw new Error(`[JanusClient] unexpected createRoom response => ${JSON.stringify(json)}`);\n }\n this.logger.debug(`[JanusClient] Room '${this.config.roomId}' created successfully`);\n }\n\n /**\n * Joins the created room as a publisher, for the host scenario.\n */\n private async joinRoom(): Promise<number> {\n if (!this.sessionId || !this.handleId) {\n throw new Error('[JanusClient] no session/handle for joinRoom()');\n }\n\n this.logger.debug('[JanusClient] joinRoom => start');\n\n // Wait for the 'joined' event from videoroom\n const evtPromise = this.waitForJanusEvent(\n (e) =>\n e.janus === 'event' &&\n e.plugindata?.plugin === 'janus.plugin.videoroom' &&\n e.plugindata?.data?.videoroom === 'joined',\n 12000,\n 'Host Joined Event'\n );\n\n const body = {\n request: 'join',\n room: this.config.roomId,\n ptype: 'publisher',\n display: this.config.userId,\n periscope_user_id: this.config.userId,\n };\n await this.sendJanusMessage(this.handleId, body);\n\n const evt = await evtPromise;\n const publisherId = evt.plugindata.data.id;\n this.logger.debug('[JanusClient] joined room => publisherId=', publisherId);\n return publisherId;\n }\n\n /**\n * Creates an SDP offer and sends \"configure\" to Janus with it.\n * Used by both host and guest after attach + join.\n */\n private async configurePublisher(sessionUUID = ''): Promise<void> {\n if (!this.pc || !this.sessionId || !this.handleId) {\n return;\n }\n\n this.logger.debug('[JanusClient] createOffer...');\n const offer = await this.pc.createOffer({\n offerToReceiveAudio: true,\n offerToReceiveVideo: false,\n });\n await this.pc.setLocalDescription(offer);\n\n this.logger.debug('[JanusClient] sending configure with JSEP...');\n await this.sendJanusMessage(\n this.handleId,\n {\n request: 'configure',\n room: this.config.roomId,\n periscope_user_id: this.config.userId,\n session_uuid: sessionUUID,\n stream_name: this.config.streamName,\n vidman_token: this.config.credential,\n },\n offer\n );\n this.logger.debug('[JanusClient] waiting for answer...');\n }\n\n /**\n * Sends a \"janus\":\"message\" to the Janus handle, optionally with jsep.\n */\n private async sendJanusMessage(handleId: number, body: any, jsep?: any): Promise<void> {\n if (!this.sessionId) {\n throw new Error('[JanusClient] No session for sendJanusMessage');\n }\n const transaction = this.randomTid();\n const resp = await fetch(`${this.config.webrtcUrl}/${this.sessionId}/${handleId}`, {\n method: 'POST',\n headers: {\n Authorization: this.config.credential,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n janus: 'message',\n transaction,\n body,\n jsep,\n }),\n });\n if (!resp.ok) {\n throw new Error(`[JanusClient] sendJanusMessage failed => status=${resp.status}`);\n }\n }\n\n /**\n * Starts polling /janus/{sessionId}?maxev=1 for events. We parse keepalives, answers, etc.\n */\n private startPolling(): void {\n this.logger.debug('[JanusClient] Starting polling...');\n const doPoll = async () => {\n if (!this.pollActive || !this.sessionId) {\n this.logger.debug('[JanusClient] Polling stopped');\n return;\n }\n try {\n const url = `${this.config.webrtcUrl}/${this.sessionId}?maxev=1&_=${Date.now()}`;\n const resp = await fetch(url, {\n headers: { Authorization: this.config.credential },\n });\n if (resp.ok) {\n const event = await resp.json();\n this.handleJanusEvent(event);\n } else {\n this.logger.warn('[JanusClient] poll error =>', resp.status);\n }\n } catch (err) {\n this.logger.error('[JanusClient] poll exception =>', err);\n }\n setTimeout(doPoll, 500);\n };\n doPoll();\n }\n\n /**\n * Processes each Janus event received from the poll cycle.\n */\n private handleJanusEvent(evt: any): void {\n if (!evt.janus) {\n return;\n }\n if (evt.janus === 'keepalive') {\n this.logger.debug('[JanusClient] keepalive received');\n return;\n }\n if (evt.janus === 'webrtcup') {\n this.logger.debug('[JanusClient] webrtcup => sender=', evt.sender);\n }\n // If there's a JSEP answer, set it on our RTCPeerConnection\n if (evt.jsep && evt.jsep.type === 'answer') {\n this.onReceivedAnswer(evt.jsep);\n }\n // If there's a publisherId in the data, store it\n if (evt.plugindata?.data?.id) {\n this.publisherId = evt.plugindata.data.id;\n }\n // If there's an error, emit an 'error' event\n if (evt.error) {\n this.logger.error('[JanusClient] Janus error =>', evt.error.reason);\n this.emit('error', new Error(evt.error.reason));\n }\n\n // Resolve any waiting eventWaiters whose predicate matches\n for (let i = 0; i < this.eventWaiters.length; i++) {\n const waiter = this.eventWaiters[i];\n if (waiter.predicate(evt)) {\n this.eventWaiters.splice(i, 1);\n waiter.resolve(evt);\n break;\n }\n }\n }\n\n /**\n * Called whenever we get an SDP \"answer\" from Janus. Sets the remote description on our PC.\n */\n private async onReceivedAnswer(answer: any): Promise<void> {\n if (!this.pc) {\n return;\n }\n this.logger.debug('[JanusClient] got answer => setRemoteDescription');\n await this.pc.setRemoteDescription(answer);\n }\n\n /**\n * Sets up events on our main RTCPeerConnection for ICE changes, track additions, etc.\n */\n private setupPeerEvents(): void {\n if (!this.pc) {\n return;\n }\n this.pc.addEventListener('iceconnectionstatechange', () => {\n this.logger.debug('[JanusClient] ICE state =>', this.pc?.iceConnectionState);\n if (this.pc?.iceConnectionState === 'failed') {\n this.emit('error', new Error('[JanusClient] ICE connection failed'));\n }\n });\n this.pc.addEventListener('track', (evt) => {\n this.logger.debug('[JanusClient] ontrack => kind=', evt.track.kind);\n });\n }\n\n /**\n * Generates a random transaction ID for Janus requests.\n */\n private randomTid(): string {\n return Math.random().toString(36).slice(2, 10);\n }\n\n /**\n * Waits for a specific Janus event (e.g., \"joined\", \"attached\", etc.)\n * that matches a given predicate. Times out after timeoutMs if not received.\n */\n private async waitForJanusEvent(\n predicate: (evt: any) => boolean,\n timeoutMs = 5000,\n description = 'some event'\n ): Promise<any> {\n return new Promise((resolve, reject) => {\n const waiter = { predicate, resolve, reject };\n this.eventWaiters.push(waiter);\n\n setTimeout(() => {\n const idx = this.eventWaiters.indexOf(waiter);\n if (idx !== -1) {\n this.eventWaiters.splice(idx, 1);\n this.logger.warn(\n `[JanusClient] waitForJanusEvent => timed out waiting for: ${description}`\n );\n reject(\n new Error(\n `[JanusClient] waitForJanusEvent (expecting \"${description}\") timed out after ${timeoutMs}ms`\n )\n );\n }\n }, timeoutMs);\n });\n }\n\n /**\n * Destroys the Janus room (host only). Does not close local PC or stop polling.\n */\n public async destroyRoom(): Promise<void> {\n if (!this.sessionId || !this.handleId) {\n this.logger.warn('[JanusClient] destroyRoom => no session/handle');\n return;\n }\n if (!this.config.roomId || !this.config.userId) {\n this.logger.warn('[JanusClient] destroyRoom => no roomId/userId');\n return;\n }\n\n const transaction = this.randomTid();\n const body = {\n request: 'destroy',\n room: this.config.roomId,\n periscope_user_id: this.config.userId,\n };\n this.logger.info('[JanusClient] destroying room =>', body);\n\n const resp = await fetch(`${this.config.webrtcUrl}/${this.sessionId}/${this.handleId}`, {\n method: 'POST',\n headers: {\n Authorization: this.config.credential,\n 'Content-Type': 'application/json',\n Referer: 'https://x.com',\n },\n body: JSON.stringify({\n janus: 'message',\n transaction,\n body,\n }),\n });\n if (!resp.ok) {\n throw new Error(`[JanusClient] destroyRoom failed => ${resp.status}`);\n }\n const json = await resp.json();\n this.logger.debug('[JanusClient] destroyRoom =>', JSON.stringify(json));\n }\n\n /**\n * Leaves the Janus room if we've joined. Does not close the local PC or stop polling.\n */\n public async leaveRoom(): Promise<void> {\n if (!this.sessionId || !this.handleId) {\n this.logger.warn('[JanusClient] leaveRoom => no session/handle');\n return;\n }\n const transaction = this.randomTid();\n const body = {\n request: 'leave',\n room: this.config.roomId,\n periscope_user_id: this.config.userId,\n };\n this.logger.info('[JanusClient] leaving room =>', body);\n\n const resp = await fetch(`${this.config.webrtcUrl}/${this.sessionId}/${this.handleId}`, {\n method: 'POST',\n headers: {\n Authorization: this.config.credential,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n janus: 'message',\n transaction,\n body,\n }),\n });\n if (!resp.ok) {\n throw new Error(`[JanusClient] leaveRoom => error code ${resp.status}`);\n }\n const json = await resp.json();\n this.logger.debug('[JanusClient] leaveRoom =>', JSON.stringify(json));\n }\n}\n","// src/core/JanusAudio.ts\n\nimport { EventEmitter } from 'node:events';\nimport wrtc from '@roamhq/wrtc';\nconst { nonstandard } = wrtc;\nconst { RTCAudioSource, RTCAudioSink } = nonstandard;\nimport type { Logger } from '../logger';\n\n/**\n * Configuration options for the JanusAudioSource.\n */\n/**\n * Optional logger instance for debug/info/warn logs.\n */\ninterface AudioSourceOptions {\n /**\n * Optional logger instance for debug/info/warn logs.\n */\n logger?: Logger;\n}\n\n/**\n * Configuration options for the JanusAudioSink.\n */\ninterface AudioSinkOptions {\n /**\n * Optional logger instance for debug/info/warn logs.\n */\n logger?: Logger;\n}\n\n/**\n * JanusAudioSource wraps a RTCAudioSource, allowing you to push\n * raw PCM frames (Int16Array) into the WebRTC pipeline.\n */\nexport class JanusAudioSource extends EventEmitter {\n private source: any;\n private readonly track: MediaStreamTrack;\n private logger?: Logger;\n\n constructor(options?: AudioSourceOptions) {\n super();\n this.logger = options?.logger;\n this.source = new RTCAudioSource();\n this.track = this.source.createTrack();\n }\n\n /**\n * Returns the MediaStreamTrack associated with this audio source.\n */\n public getTrack(): MediaStreamTrack {\n return this.track;\n }\n\n /**\n * Pushes PCM data into the RTCAudioSource. Typically 16-bit, single- or multi-channel frames.\n * @param samples - The Int16Array audio samples.\n * @param sampleRate - The sampling rate (e.g., 48000).\n * @param channels - Number of channels (e.g., 1 for mono).\n */\n public pushPcmData(samples: Int16Array, sampleRate: number, channels = 1): void {\n if (this.logger?.isDebugEnabled()) {\n this.logger?.debug(\n `[JanusAudioSource] pushPcmData => sampleRate=${sampleRate}, channels=${channels}, frames=${samples.length}`\n );\n }\n\n // Feed data into the RTCAudioSource\n this.source.onData({\n samples,\n sampleRate,\n bitsPerSample: 16,\n channelCount: channels,\n numberOfFrames: samples.length / channels,\n });\n }\n}\n\n/**\n * JanusAudioSink wraps a RTCAudioSink, providing an event emitter\n * that forwards raw PCM frames (Int16Array) to listeners.\n */\nexport class JanusAudioSink extends EventEmitter {\n private sink: any;\n private active = true;\n private logger?: Logger;\n\n constructor(track: MediaStreamTrack, options?: AudioSinkOptions) {\n super();\n this.logger = options?.logger;\n\n if (track.kind !== 'audio') {\n throw new Error('[JanusAudioSink] Provided track is not an audio track');\n }\n\n // Create RTCAudioSink to listen for PCM frames\n this.sink = new RTCAudioSink(track);\n\n // Register callback for PCM frames\n this.sink.ondata = (frame: {\n samples: Int16Array;\n sampleRate: number;\n bitsPerSample: number;\n channelCount: number;\n }) => {\n if (!this.active) return;\n\n if (this.logger?.isDebugEnabled()) {\n this.logger?.debug(\n `[JanusAudioSink] ondata => sampleRate=${frame.sampleRate}, bitsPerSample=${frame.bitsPerSample}, channelCount=${frame.channelCount}, frames=${frame.samples.length}`\n );\n }\n\n // Emit 'audioData' event with the raw PCM frame\n this.emit('audioData', frame);\n };\n }\n\n /**\n * Stops receiving audio data. Once called, no further 'audioData' events will be emitted.\n */\n public stop(): void {\n this.active = false;\n if (this.logger?.isDebugEnabled()) {\n this.logger?.debug('[JanusAudioSink] stop called => stopping the sink');\n }\n this.sink?.stop();\n }\n}\n","// src/core/SpaceParticipant.ts\n\nimport { EventEmitter } from 'node:events';\nimport type { Client } from '../../client';\nimport { Logger } from '../logger';\nimport type { AudioDataWithUser, Plugin, PluginRegistration, TurnServersInfo } from '../types';\nimport {\n accessChat,\n authorizeToken,\n cancelSpeakerRequest,\n getTurnServers,\n muteSpeaker,\n negotiateGuestStream,\n setupCommonChatEvents,\n startWatching,\n stopWatching,\n submitSpeakerRequest,\n unmuteSpeaker,\n} from '../utils';\nimport { ChatClient } from './ChatClient';\nimport { JanusClient } from './JanusClient';\n\n/**\n * Interface representing the configuration options for a space participant.\n * @typedef {object} SpaceParticipantConfig\n * @property {string} spaceId - The unique identifier for the space.\n * @property {boolean} [debug] - Optional flag for enabling debug mode.\n */\ninterface SpaceParticipantConfig {\n spaceId: string;\n debug?: boolean;\n}\n\n/**\n * Manages joining an existing Space in listener mode,\n * and optionally becoming a speaker via WebRTC (Janus).\n */\n/**\n * Class representing a participant in a space.\n * @extends EventEmitter\n */\nexport class SpaceParticipant extends EventEmitter {\n private readonly spaceId: string;\n private readonly debug: boolean;\n private readonly logger: Logger;\n\n // Basic auth/cookie data\n private cookie?: string;\n private authToken?: string;\n\n // Chat\n private chatJwtToken?: string;\n private chatToken?: string;\n private chatClient?: ChatClient;\n\n // Watch session\n private lifecycleToken?: string;\n private watchSession?: string;\n\n // HLS stream\n private hlsUrl?: string;\n\n // Speaker request + Janus\n private sessionUUID?: string;\n private janusJwt?: string;\n private webrtcGwUrl?: string;\n private janusClient?: JanusClient;\n\n // Plugin management\n private plugins = new Set<PluginRegistration>();\n\n constructor(\n private readonly client: Client,\n config: SpaceParticipantConfig\n ) {\n super();\n this.spaceId = config.spaceId;\n this.debug = config.debug ?? false;\n this.logger = new Logger(this.debug);\n }\n\n /**\n * Adds a plugin and calls its onAttach immediately.\n * init() or onJanusReady() will be invoked later at the appropriate time.\n */\n public use(plugin: Plugin, config?: Record<string, any>) {\n const registration: PluginRegistration = { plugin, config };\n this.plugins.add(registration);\n\n this.logger.debug('[SpaceParticipant] Plugin added =>', plugin.constructor.name);\n\n // Call the plugin's onAttach if it exists\n plugin.onAttach?.({ space: this, pluginConfig: config });\n\n if (plugin.init) {\n plugin.init({ space: this, pluginConfig: config });\n }\n\n return this;\n }\n\n /**\n * Joins the Space as a listener: obtains HLS, chat token, etc.\n */\n public async joinAsListener(): Promise<void> {\n this.logger.info('[SpaceParticipant] Joining space as listener =>', this.spaceId);\n\n // 1) Get cookie and authorize\n this.cookie = await this.client.getPeriscopeCookie();\n this.authToken = await authorizeToken(this.cookie);\n\n // 2) Retrieve the space metadata for mediaKey\n const spaceMeta = await this.client.getAudioSpaceById(this.spaceId);\n const mediaKey = spaceMeta?.metadata?.media_key;\n if (!mediaKey) {\n throw new Error('[SpaceParticipant] No mediaKey found in metadata');\n }\n this.logger.debug('[SpaceParticipant] mediaKey =>', mediaKey);\n\n // 3) Query live_video_stream/status for HLS URL and chat token\n const status = await this.client.getAudioSpaceStreamStatus(mediaKey);\n this.hlsUrl = status?.source?.location;\n this.chatJwtToken = status?.chatToken;\n this.lifecycleToken = status?.lifecycleToken;\n this.logger.debug('[SpaceParticipant] HLS =>', this.hlsUrl);\n\n // 4) Access the chat\n if (!this.chatJwtToken) {\n throw new Error('[SpaceParticipant] No chatToken found');\n }\n const chatInfo = await accessChat(this.chatJwtToken, this.cookie!);\n this.chatToken = chatInfo.access_token;\n\n // 5) Create and connect the ChatClient\n this.chatClient = new ChatClient({\n spaceId: chatInfo.room_id,\n accessToken: chatInfo.access_token,\n endpoint: chatInfo.endpoint,\n logger: this.logger,\n });\n await this.chatClient.connect();\n this.setupChatEvents();\n\n // 6) startWatching (to appear as a viewer)\n this.watchSession = await startWatching(this.lifecycleToken!, this.cookie!);\n\n this.logger.info('[SpaceParticipant] Joined as listener.');\n }\n\n /**\n * Returns the HLS URL if you want to consume the stream as a listener.\n */\n public getHlsUrl(): string | undefined {\n return this.hlsUrl;\n }\n\n /**\n * Submits a speaker request using /audiospace/request/submit.\n * Returns the sessionUUID used to track approval.\n */\n public async requestSpeaker(): Promise<{ sessionUUID: string }> {\n if (!this.chatJwtToken) {\n throw new Error('[SpaceParticipant] Must join as listener first (no chat token).');\n }\n if (!this.authToken) {\n throw new Error('[SpaceParticipant] No auth token available.');\n }\n if (!this.chatToken) {\n throw new Error('[SpaceParticipant] No chat token available.');\n }\n\n this.logger.info('[SpaceParticipant] Submitting speaker request...');\n\n const { session_uuid } = await submitSpeakerRequest({\n broadcastId: this.spaceId,\n chatToken: this.chatToken,\n authToken: this.authToken,\n });\n this.sessionUUID = session_uuid;\n\n this.logger.info('[SpaceParticipant] Speaker request submitted =>', session_uuid);\n return { sessionUUID: session_uuid };\n }\n\n /**\n * Cancels a previously submitted speaker request using /audiospace/request/cancel.\n * This requires a valid sessionUUID from requestSpeaker() first.\n */\n public async cancelSpeakerRequest(): Promise<void> {\n if (!this.sessionUUID) {\n throw new Error(\n '[SpaceParticipant] No sessionUUID; cannot cancel a speaker request that was never submitted.'\n );\n }\n if (!this.authToken) {\n throw new Error('[SpaceParticipant] No auth token available.');\n }\n if (!this.chatToken) {\n throw new Error('[SpaceParticipant] No chat token available.');\n }\n\n await cancelSpeakerRequest({\n broadcastId: this.spaceId,\n sessionUUID: this.sessionUUID,\n chatToken: this.chatToken,\n authToken: this.authToken,\n });\n\n this.logger.info('[SpaceParticipant] Speaker request canceled =>', this.sessionUUID);\n this.sessionUUID = undefined;\n }\n\n /**\n * Once the host approves our speaker request, we perform Janus negotiation\n * to become a speaker.\n */\n public async becomeSpeaker(): Promise<void> {\n if (!this.sessionUUID) {\n throw new Error('[SpaceParticipant] No sessionUUID (did you call requestSpeaker()?).');\n }\n this.logger.info('[SpaceParticipant] Negotiating speaker role via Janus...');\n\n // 1) Retrieve TURN servers\n const turnServers: TurnServersInfo = await getTurnServers(this.cookie!);\n this.logger.debug('[SpaceParticipant] turnServers =>', turnServers);\n\n // 2) Negotiate with /audiospace/stream/negotiate\n const nego = await negotiateGuestStream({\n broadcastId: this.spaceId,\n sessionUUID: this.sessionUUID,\n authToken: this.authToken!,\n cookie: this.cookie!,\n });\n this.janusJwt = nego.janus_jwt;\n this.webrtcGwUrl = nego.webrtc_gw_url;\n this.logger.debug('[SpaceParticipant] webrtcGwUrl =>', this.webrtcGwUrl);\n\n // 3) Create JanusClient\n this.janusClient = new JanusClient({\n webrtcUrl: this.webrtcGwUrl!,\n roomId: this.spaceId,\n credential: this.janusJwt!,\n userId: turnServers.username.split(':')[1],\n streamName: this.spaceId,\n turnServers,\n logger: this.logger,\n });\n\n // 4) Initialize the guest speaker session in Janus\n await this.janusClient.initializeGuestSpeaker(this.sessionUUID);\n\n this.janusClient.on('audioDataFromSpeaker', (data: AudioDataWithUser) => {\n this.logger.debug('[SpaceParticipant] Received speaker audio =>', data.userId);\n this.handleAudioData(data);\n });\n\n this.logger.info('[SpaceParticipant] Now speaker on the Space =>', this.spaceId);\n\n // For plugins that need direct Janus references, call onJanusReady\n for (const { plugin } of this.plugins) {\n plugin.onJanusReady?.(this.janusClient);\n }\n }\n\n /**\n * Removes self from the speaker role and transitions back to a listener.\n */\n public async removeFromSpeaker(): Promise<void> {\n if (!this.sessionUUID) {\n throw new Error('[SpaceParticipant] No sessionUUID; cannot remove from speaker role.');\n }\n if (!this.authToken || !this.chatToken) {\n throw new Error('[SpaceParticipant] Missing authToken or chatToken.');\n }\n\n this.logger.info('[SpaceParticipant] Removing from speaker role...');\n\n // Stop the Janus session\n if (this.janusClient) {\n await this.janusClient.stop();\n this.janusClient = undefined;\n }\n\n this.logger.info('[SpaceParticipant] Successfully removed from speaker role.');\n }\n\n /**\n * Leaves the Space gracefully:\n * - Stop Janus if we were a speaker\n * - Stop watching as a viewer\n * - Disconnect chat\n */\n public async leaveSpace(): Promise<void> {\n this.logger.info('[SpaceParticipant] Leaving space...');\n\n // If speaker, stop Janus\n if (this.janusClient) {\n await this.janusClient.stop();\n this.janusClient = undefined;\n }\n\n // Stop watching\n if (this.watchSession && this.cookie) {\n await stopWatching(this.watchSession, this.cookie);\n }\n\n // Disconnect chat\n if (this.chatClient) {\n await this.chatClient.disconnect();\n this.chatClient = undefined;\n }\n\n this.logger.info('[SpaceParticipant] Left space =>', this.spaceId);\n }\n\n /**\n * Pushes PCM audio frames if we're speaker; otherwise logs a warning.\n */\n public pushAudio(samples: Int16Array, sampleRate: number) {\n if (!this.janusClient) {\n this.logger.warn('[SpaceParticipant] Not a speaker yet; ignoring pushAudio.');\n return;\n }\n this.janusClient.pushLocalAudio(samples, sampleRate);\n }\n\n /**\n * Internal handler for incoming PCM frames from Janus, forwarded to plugin.onAudioData if present.\n */\n private handleAudioData(data: AudioDataWithUser) {\n for (const { plugin } of this.plugins) {\n plugin.onAudioData?.(data);\n }\n }\n\n /**\n * Sets up chat events: \"occupancyUpdate\", \"newSpeakerAccepted\", etc.\n */\n private setupChatEvents() {\n if (!this.chatClient) return;\n setupCommonChatEvents(this.chatClient, this.logger, this);\n\n this.chatClient.on('newSpeakerAccepted', ({ userId }) => {\n this.logger.debug('[SpaceParticipant] newSpeakerAccepted =>', userId);\n\n // If we haven't created Janus yet, skip\n if (!this.janusClient) {\n this.logger.warn('[SpaceParticipant] No janusClient yet; ignoring new speaker...');\n return;\n }\n // If this is our own handle, skip\n if (userId === this.janusClient.getHandleId()) {\n return;\n }\n\n // Subscribe to this new speaker's audio\n this.janusClient.subscribeSpeaker(userId).catch((err) => {\n this.logger.error('[SpaceParticipant] subscribeSpeaker error =>', err);\n });\n });\n }\n\n /**\n * Mute self if we are speaker: calls /audiospace/muteSpeaker with our sessionUUID.\n */\n public async muteSelf(): Promise<void> {\n if (!this.authToken || !this.chatToken) {\n throw new Error('[SpaceParticipant] Missing authToken or chatToken.');\n }\n if (!this.sessionUUID) {\n throw new Error('[SpaceParticipant] No sessionUUID; are you a speaker?');\n }\n\n await muteSpeaker({\n broadcastId: this.spaceId,\n sessionUUID: this.sessionUUID,\n chatToken: this.chatToken,\n authToken: this.authToken,\n });\n this.logger.info('[SpaceParticipant] Successfully muted self.');\n }\n\n /**\n * Unmute self if we are speaker: calls /audiospace/unmuteSpeaker with our sessionUUID.\n */\n public async unmuteSelf(): Promise<void> {\n if (!this.authToken || !this.chatToken) {\n throw new Error('[SpaceParticipant] Missing authToken or chatToken.');\n }\n if (!this.sessionUUID) {\n throw new Error('[SpaceParticipant] No sessionUUID; are you a speaker?');\n }\n\n await unmuteSpeaker({\n broadcastId: this.spaceId,\n sessionUUID: this.sessionUUID,\n chatToken: this.chatToken,\n authToken: this.authToken,\n });\n this.logger.info('[SpaceParticipant] Successfully unmuted self.');\n }\n}\n","// src/plugins/SttTtsPlugin.ts\n\nimport { spawn } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport type { JanusClient } from '../core/JanusClient';\nimport type { Space } from '../core/Space';\nimport type { SpaceParticipant } from '../core/SpaceParticipant';\nimport { Logger } from '../logger';\nimport type { AudioDataWithUser, Plugin } from '../types';\nimport { logger } from '@elizaos/core';\n\n/**\n * Interface for configuring a plugin\n * @typedef {Object} PluginConfig\n * @property {string} [openAiApiKey] - API key for OpenAI used for STT & ChatGPT\n * @property {string} [elevenLabsApiKey] - API key for ElevenLabs used for TTS\n * @property {string} [sttLanguage] - Language code for speech-to-text (e.g., \"en\" for English)\n * @property {string} [gptModel] - Model for ChatGPT (e.g., \"gpt-3.5-turbo\" or \"gpt-4\")\n * @property {number} [silenceThreshold] - Amplitude threshold for ignoring silence\n * @property {string} [voiceId] - Specifies which ElevenLabs voice to use\n * @property {string} [elevenLabsModel] - Model for ElevenLabs (e.g., \"eleven_monolingual_v1\")\n * @property {string} [systemPrompt] - Default prompt for the AI assistant\n * @property {Array<{ role: \"system\" | \"user\" | \"assistant\"; content: string; }>} [chatContext] - Array of objects representing chat context\n * @property {boolean} [debug] - Flag to enable debug mode\n */\ninterface PluginConfig {\n openAiApiKey?: string; // for STT & ChatGPT\n elevenLabsApiKey?: string; // for TTS\n sttLanguage?: string; // e.g., \"en\" for Whisper\n gptModel?: string; // e.g., \"gpt-3.5-turbo\" or \"gpt-4\"\n silenceThreshold?: number; // amplitude threshold for ignoring silence\n voiceId?: string; // specify which ElevenLabs voice to use\n elevenLabsModel?: string; // e.g., \"eleven_monolingual_v1\"\n systemPrompt?: string; // e.g., \"You are a helpful AI assistant\"\n chatContext?: Array<{\n role: 'system' | 'user' | 'assistant';\n content: string;\n }>;\n debug?: boolean;\n}\n\n/**\n * SttTtsPlugin\n * ------------\n * Provides an end-to-end flow of:\n * - Speech-to-Text (OpenAI Whisper)\n * - ChatGPT conversation\n * - Text-to-Speech (ElevenLabs)\n * - Streams TTS audio frames back to Janus\n *\n * Lifecycle:\n * - onAttach(...) => minimal references\n * - init(...) => space or participant has joined in basic mode\n * - onJanusReady(...) => we have a JanusClient\n * - onAudioData(...) => receiving PCM frames from speakers\n * - cleanup(...) => release resources, stop timers, etc.\n */\n/**\n * Represents a plugin for speech-to-text and text-to-speech functionality.\n * @implements Plugin\n * @property {Space | SpaceParticipant} spaceOrParticipant - Reference to the space/participant using the plugin.\n * @property {JanusClient} janus - Reference to the Janus client for real-time communication.\n * @property {Logger} logger - Optional logger retrieved from the space or participant.\n */\nexport class SttTtsPlugin implements Plugin {\n // References to the space/participant and the Janus client\n private spaceOrParticipant?: Space | SpaceParticipant;\n private janus?: JanusClient;\n\n // Optional logger retrieved from the space or participant\n private logger?: Logger;\n\n // Credentials & config\n private openAiApiKey?: string;\n private elevenLabsApiKey?: string;\n private sttLanguage = 'en';\n private gptModel = 'gpt-3.5-turbo';\n private voiceId = '21m00Tcm4TlvDq8ikWAM';\n private elevenLabsModel = 'eleven_monolingual_v1';\n private systemPrompt = 'You are a helpful AI assistant.';\n private silenceThreshold = 50;\n\n /**\n * chatContext accumulates the conversation for GPT:\n * - system: persona instructions\n * - user/assistant: running conversation\n */\n private chatContext: Array<{\n role: 'system' | 'user' | 'assistant';\n content: string;\n }> = [];\n\n /**\n * Maps each userId => array of Int16Array PCM chunks\n * Only accumulates data if the speaker is unmuted\n */\n private pcmBuffers = new Map<string, Int16Array[]>();\n\n /**\n * Tracks which speakers are currently unmuted:\n * userId => true/false\n */\n private speakerUnmuted = new Map<string, boolean>();\n\n /**\n * TTS queue for sequential playback\n */\n private ttsQueue: string[] = [];\n private isSpeaking = false;\n\n /**\n * Called immediately after `.use(plugin)`.\n * Usually used for storing references or minimal setup.\n */\n onAttach(params: { space: Space | SpaceParticipant; pluginConfig?: Record<string, any> }): void {\n // Store a reference to the space or participant\n this.spaceOrParticipant = params.space;\n\n const debugEnabled = params.pluginConfig?.debug ?? false;\n this.logger = new Logger(debugEnabled);\n\n logger.debug('[SttTtsPlugin] onAttach => plugin attached');\n }\n\n /**\n * Called after the space/participant has joined in basic mode (listener + chat).\n * This is where we can finalize setup that doesn't require Janus or speaker mode.\n */\n init(params: { space: Space | SpaceParticipant; pluginConfig?: Record<string, any> }): void {\n const config = params.pluginConfig as PluginConfig;\n\n this.logger?.debug('[SttTtsPlugin] init => finalizing basic setup');\n\n // Overwrite the local reference with a strong typed one\n this.spaceOrParticipant = params.space;\n\n // If space/participant has a Janus client already, we can store it,\n // but typically we rely on \"onJanusReady\" for that.\n this.janus = (this.spaceOrParticipant as any).janusClient;\n\n // Merge plugin configuration\n this.openAiApiKey = config?.openAiApiKey;\n this.elevenLabsApiKey = config?.elevenLabsApiKey;\n if (config?.sttLanguage) this.sttLanguage = config.sttLanguage;\n if (config?.gptModel) this.gptModel = config.gptModel;\n if (typeof config?.silenceThreshold === 'number') {\n this.silenceThreshold = config.silenceThreshold;\n }\n if (config?.voiceId) this.voiceId = config.voiceId;\n if (config?.elevenLabsModel) this.elevenLabsModel = config.elevenLabsModel;\n if (config?.systemPrompt) this.systemPrompt = config.systemPrompt;\n if (config?.chatContext) {\n this.chatContext = config.chatContext;\n }\n\n this.logger?.debug('[SttTtsPlugin] Merged config =>', config);\n\n // Example: watch for \"muteStateChanged\" events from the space or participant\n this.spaceOrParticipant.on('muteStateChanged', (evt: { userId: string; muted: boolean }) => {\n this.logger?.debug('[SttTtsPlugin] muteStateChanged =>', evt);\n if (evt.muted) {\n // If the user just muted, flush STT\n this.handleMute(evt.userId).catch((err) => {\n this.logger?.error('[SttTtsPlugin] handleMute error =>', err);\n });\n } else {\n // Mark user as unmuted\n this.speakerUnmuted.set(evt.userId, true);\n if (!this.pcmBuffers.has(evt.userId)) {\n this.pcmBuffers.set(evt.userId, []);\n }\n }\n });\n }\n\n /**\n * Called if/when the plugin needs direct access to a JanusClient.\n * For example, once the participant becomes a speaker or if a host\n * has finished setting up Janus.\n */\n onJanusReady(janusClient: JanusClient): void {\n this.logger?.debug('[SttTtsPlugin] onJanusReady => JanusClient is now available');\n this.janus = janusClient;\n }\n\n /**\n * onAudioData: triggered for every incoming PCM frame from a speaker.\n * We'll accumulate them if that speaker is currently unmuted.\n */\n onAudioData(data: AudioDataWithUser): void {\n const { userId, samples } = data;\n if (!this.speakerUnmuted.get(userId)) return;\n\n // Basic amplitude check\n let maxVal = 0;\n for (let i = 0; i < samples.length; i++) {\n const val = Math.abs(samples[i]);\n if (val > maxVal) maxVal = val;\n }\n if (maxVal < this.silenceThreshold) return;\n\n // Accumulate frames\n const chunks = this.pcmBuffers.get(userId) ?? [];\n chunks.push(samples);\n this.pcmBuffers.set(userId, chunks);\n }\n\n /**\n * handleMute: called when a speaker goes from unmuted to muted.\n * We'll flush their collected PCM => STT => GPT => TTS => push to Janus\n */\n private async handleMute(userId: string): Promise<void> {\n this.speakerUnmuted.set(userId, false);\n\n const chunks = this.pcmBuffers.get(userId) || [];\n this.pcmBuffers.set(userId, []); // reset\n\n if (!chunks.length) {\n this.logger?.debug('[SttTtsPlugin] No audio data => userId=', userId);\n return;\n }\n\n this.logger?.info(\n `[SttTtsPlugin] Flushing STT buffer => userId=${userId}, chunkCount=${chunks.length}`\n );\n\n // Merge into one Int16Array\n const totalLen = chunks.reduce((acc, c) => acc + c.length, 0);\n const merged = new Int16Array(totalLen);\n let offset = 0;\n for (const c of chunks) {\n merged.set(c, offset);\n offset += c.length;\n }\n\n // Convert to WAV\n const wavPath = await this.convertPcmToWav(merged, 48000);\n this.logger?.debug('[SttTtsPlugin] WAV created =>', wavPath);\n\n // Whisper STT\n const sttText = await this.transcribeWithOpenAI(wavPath, this.sttLanguage);\n fs.unlinkSync(wavPath); // remove temp\n\n if (!sttText.trim()) {\n this.logger?.debug('[SttTtsPlugin] No speech recognized => userId=', userId);\n return;\n }\n this.logger?.info(`[SttTtsPlugin] STT => userId=${userId}, text=\"${sttText}\"`);\n\n // GPT response\n const replyText = await this.askChatGPT(sttText);\n this.logger?.info(`[SttTtsPlugin] GPT => userId=${userId}, reply=\"${replyText}\"`);\n\n // Send TTS\n await this.speakText(replyText);\n }\n\n /**\n * speakText: Public method to enqueue a text message for TTS output\n */\n public async speakText(text: string): Promise<void> {\n this.ttsQueue.push(text);\n\n if (!this.isSpeaking) {\n this.isSpeaking = true;\n this.processTtsQueue().catch((err) => {\n this.logger?.error('[SttTtsPlugin] processTtsQueue error =>', err);\n });\n }\n }\n\n /**\n * processTtsQueue: Drains the TTS queue in order, sending frames to Janus\n */\n private async processTtsQueue(): Promise<void> {\n while (this.ttsQueue.length > 0) {\n const text = this.ttsQueue.shift();\n if (!text) continue;\n try {\n const mp3Buf = await this.elevenLabsTts(text);\n const pcm = await this.convertMp3ToPcm(mp3Buf, 48000);\n await this.streamToJanus(pcm, 48000);\n } catch (err) {\n this.logger?.error('[SttTtsPlugin] TTS streaming error =>', err);\n }\n }\n this.isSpeaking = false;\n }\n\n /**\n * convertPcmToWav: Creates a temporary WAV file from raw PCM samples\n */\n private convertPcmToWav(samples: Int16Array, sampleRate: number): Promise<string> {\n return new Promise((resolve, reject) => {\n const tmpPath = path.resolve('/tmp', `stt-${Date.now()}.wav`);\n const ff = spawn('ffmpeg', [\n '-f',\n 's16le',\n '-ar',\n sampleRate.toString(),\n '-ac',\n '1',\n '-i',\n 'pipe:0',\n '-y',\n tmpPath,\n ]);\n\n ff.stdin.write(Buffer.from(samples.buffer));\n ff.stdin.end();\n\n ff.on('close', (code) => {\n if (code === 0) {\n resolve(tmpPath);\n } else {\n reject(new Error(`ffmpeg pcm->wav error code=${code}`));\n }\n });\n });\n }\n\n /**\n * transcribeWithOpenAI: sends the WAV file to OpenAI Whisper\n */\n private async transcribeWithOpenAI(wavPath: string, language: string): Promise<string> {\n if (!this.openAiApiKey) {\n throw new Error('[SttTtsPlugin] No OpenAI API key');\n }\n\n this.logger?.info('[SttTtsPlugin] Transcribing =>', wavPath);\n const fileBuffer = fs.readFileSync(wavPath);\n this.logger?.debug('[SttTtsPlugin] WAV size =>', fileBuffer.length);\n\n const blob = new Blob([fileBuffer], { type: 'audio/wav' });\n const formData = new FormData();\n formData.append('file', blob, path.basename(wavPath));\n formData.append('model', 'whisper-1');\n formData.append('language', language);\n formData.append('temperature', '0');\n\n const resp = await fetch('https://api.openai.com/v1/audio/transcriptions', {\n method: 'POST',\n headers: { Authorization: `Bearer ${this.openAiApiKey}` },\n body: formData,\n });\n\n if (!resp.ok) {\n const errText = await resp.text();\n this.logger?.error('[SttTtsPlugin] OpenAI STT error =>', errText);\n throw new Error(`OpenAI STT => ${resp.status} ${errText}`);\n }\n\n const data = (await resp.json()) as { text: string };\n return data.text.trim();\n }\n\n /**\n * askChatGPT: sends user text to GPT, returns the assistant reply\n */\n private async askChatGPT(userText: string): Promise<string> {\n if (!this.openAiApiKey) {\n throw new Error('[SttTtsPlugin] No OpenAI API key (GPT) provided');\n }\n\n const messages = [\n { role: 'system', content: this.systemPrompt },\n ...this.chatContext,\n { role: 'user', content: userText },\n ];\n\n const resp = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${this.openAiApiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({ model: this.gptModel, messages }),\n });\n\n if (!resp.ok) {\n const errText = await resp.text();\n throw new Error(`[SttTtsPlugin] ChatGPT error => ${resp.status} ${errText}`);\n }\n\n const json = await resp.json();\n const reply = json.choices?.[0]?.message?.content || '';\n // Keep conversation context\n this.chatContext.push({ role: 'user', content: userText });\n this.chatContext.push({ role: 'assistant', content: reply });\n return reply.trim();\n }\n\n /**\n * elevenLabsTts: fetches MP3 audio from ElevenLabs for a given text\n */\n private async elevenLabsTts(text: string): Promise<Buffer> {\n if (!this.elevenLabsApiKey) {\n throw new Error('[SttTtsPlugin] No ElevenLabs API key');\n }\n\n const url = `https://api.elevenlabs.io/v1/text-to-speech/${this.voiceId}`;\n const resp = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'xi-api-key': this.elevenLabsApiKey,\n },\n body: JSON.stringify({\n text,\n model_id: this.elevenLabsModel,\n voice_settings: { stability: 0.4, similarity_boost: 0.8 },\n }),\n });\n\n if (!resp.ok) {\n const errText = await resp.text();\n throw new Error(`[SttTtsPlugin] ElevenLabs error => ${resp.status} ${errText}`);\n }\n\n const arrayBuffer = await resp.arrayBuffer();\n return Buffer.from(arrayBuffer);\n }\n\n /**\n * convertMp3ToPcm: uses ffmpeg to convert an MP3 buffer to raw PCM\n */\n private convertMp3ToPcm(mp3Buf: Buffer, outRate: number): Promise<Int16Array> {\n return new Promise((resolve, reject) => {\n const ff = spawn('ffmpeg', [\n '-i',\n 'pipe:0',\n '-f',\n 's16le',\n '-ar',\n outRate.toString(),\n '-ac',\n '1',\n 'pipe:1',\n ]);\n\n let raw = Buffer.alloc(0);\n\n ff.stdout.on('data', (chunk: Buffer) => {\n raw = Buffer.concat([raw, chunk]);\n });\n ff.stderr.on('data', () => {\n // ignoring ffmpeg stderr\n });\n ff.on('close', (code) => {\n if (code !== 0) {\n reject(new Error(`ffmpeg mp3->pcm error code=${code}`));\n return;\n }\n const samples = new Int16Array(raw.buffer, raw.byteOffset, raw.byteLength / 2);\n resolve(samples);\n });\n\n ff.stdin.write(mp3Buf);\n ff.stdin.end();\n });\n }\n\n /**\n * streamToJanus: push PCM frames to Janus in small increments (~10ms).\n */\n private async streamToJanus(samples: Int16Array, sampleRate: number): Promise<void> {\n if (!this.janus) {\n this.logger?.warn('[SttTtsPlugin] No JanusClient available, cannot send TTS audio');\n return;\n }\n\n const frameSize = Math.floor(sampleRate * 0.01); // 10ms => e.g. 480 @ 48kHz\n\n for (let offset = 0; offset + frameSize <= samples.length; offset += frameSize) {\n const frame = new Int16Array(frameSize);\n frame.set(samples.subarray(offset, offset + frameSize));\n this.janus.pushLocalAudio(frame, sampleRate, 1);\n await new Promise((r) => setTimeout(r, 10));\n }\n }\n\n /**\n * setSystemPrompt: update the GPT system prompt at runtime\n */\n public setSystemPrompt(prompt: string): void {\n this.systemPrompt = prompt;\n this.logger?.info('[SttTtsPlugin] setSystemPrompt =>', prompt);\n }\n\n /**\n * setGptModel: switch GPT model (e.g. \"gpt-4\")\n */\n public setGptModel(model: string): void {\n this.gptModel = model;\n this.logger?.info('[SttTtsPlugin] setGptModel =>', model);\n }\n\n /**\n * addMessage: manually add a system/user/assistant message to the chat context\n */\n public addMessage(role: 'system' | 'user' | 'assistant', content: string): void {\n this.chatContext.push({ role, content });\n this.logger?.debug(`[SttTtsPlugin] addMessage => role=${role}, content=\"${content}\"`);\n }\n\n /**\n * clearChatContext: resets the GPT conversation\n */\n public clearChatContext(): void {\n this.chatContext = [];\n this.logger?.debug('[SttTtsPlugin] clearChatContext => done');\n }\n\n /**\n * cleanup: release resources when the space/participant is stopping or plugin removed\n */\n cleanup(): void {\n this.logger?.info('[SttTtsPlugin] cleanup => releasing resources');\n\n this.pcmBuffers.clear();\n this.speakerUnmuted.clear();\n this.ttsQueue = [];\n this.isSpeaking = false;\n }\n}\n","import * as fs from 'node:fs';\nimport type { Space } from '../core/Space';\nimport type { SpaceParticipant } from '../core/SpaceParticipant';\nimport { Logger } from '../logger';\nimport type { AudioDataWithUser, Plugin } from '../types';\n\n/**\n * Configuration options for the RecordToDiskPlugin.\n *\n * @typedef {Object} RecordToDiskPluginConfig\n * @property {string} [filePath] - The file path where records will be stored.\n * @property {boolean} [debug] - Whether to enable verbose logs.\n */\ninterface RecordToDiskPluginConfig {\n filePath?: string;\n debug?: boolean; // whether to enable verbose logs\n}\n\n/**\n * RecordToDiskPlugin\n * ------------------\n * A simple plugin that writes all incoming PCM frames to a local .raw file.\n *\n * Lifecycle:\n * - onAttach(...) => minimal references, logger config\n * - init(...) => finalize file path, open stream\n * - onAudioData(...) => append PCM frames to the file\n * - cleanup(...) => close file stream\n */\n/**\n * Class representing a plugin for recording audio data to disk.\n * @implements {Plugin}\n */\nexport class RecordToDiskPlugin implements Plugin {\n private filePath = '/tmp/speaker_audio.raw';\n private outStream?: fs.WriteStream;\n private logger?: Logger;\n\n /**\n * Called immediately after .use(plugin).\n * We create a logger based on pluginConfig.debug and store the file path if provided.\n */\n onAttach(params: { space: Space | SpaceParticipant; pluginConfig?: Record<string, any> }): void {\n const debugEnabled = params.pluginConfig?.debug ?? false;\n this.logger = new Logger(debugEnabled);\n\n this.logger.info('[RecordToDiskPlugin] onAttach => plugin attached');\n\n if (params.pluginConfig?.filePath) {\n this.filePath = params.pluginConfig.filePath;\n }\n this.logger.debug('[RecordToDiskPlugin] Using filePath =>', this.filePath);\n }\n\n /**\n * Called after the space/participant has joined in basic mode.\n * We open the WriteStream to our file path here.\n */\n init(params: { space: Space | SpaceParticipant; pluginConfig?: Record<string, any> }): void {\n // If filePath was re-defined in pluginConfig, re-check:\n if (params.pluginConfig?.filePath) {\n this.filePath = params.pluginConfig.filePath;\n }\n\n this.logger?.info('[RecordToDiskPlugin] init => opening output stream');\n this.outStream = fs.createWriteStream(this.filePath, { flags: 'w' });\n }\n\n /**\n * Called whenever PCM audio frames arrive from a speaker.\n * We write them to the file as raw 16-bit PCM.\n */\n onAudioData(data: AudioDataWithUser): void {\n if (!this.outStream) {\n this.logger?.warn('[RecordToDiskPlugin] No outStream yet; ignoring data');\n return;\n }\n const buf = Buffer.from(data.samples.buffer);\n this.outStream.write(buf);\n this.logger?.debug(\n `[RecordToDiskPlugin] Wrote ${buf.byteLength} bytes from userId=${data.userId} to disk`\n );\n }\n\n /**\n * Called when the plugin is cleaned up (e.g. space/participant stop).\n * We close our file stream.\n */\n cleanup(): void {\n this.logger?.info('[RecordToDiskPlugin] cleanup => closing output stream');\n if (this.outStream) {\n this.outStream.end();\n this.outStream = undefined;\n }\n }\n}\n","import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process';\nimport { Logger } from '../logger';\nimport type { AudioDataWithUser, Plugin } from '../types';\n\n/**\n * MonitorAudioPlugin\n * ------------------\n * A simple plugin that spawns an `ffplay` process to play raw PCM audio in real time.\n * It reads frames from `onAudioData()` and writes them to ffplay via stdin.\n *\n * Usage:\n * const plugin = new MonitorAudioPlugin(48000, /* debug= *\\/ true);\n * space.use(plugin);\n */\n/**\n * MonitorAudioPlugin class that implements Plugin interface.\n *\n * @param {number} sampleRate The expected PCM sample rate (e.g. 16000 or 48000).\n * @param {boolean} debug If true, enables debug logging via Logger.\n *\n * @method onAudioData Called whenever PCM frames arrive (from a speaker).\n * @param {AudioDataWithUser} data The audio data received.\n *\n * @method cleanup Cleanup function called when the plugin is removed or when the space/participant stops.\n */\nexport class MonitorAudioPlugin implements Plugin {\n private ffplay?: ChildProcessWithoutNullStreams;\n private logger: Logger;\n\n /**\n * @param sampleRate The expected PCM sample rate (e.g. 16000 or 48000).\n * @param debug If true, enables debug logging via Logger.\n */\n constructor(\n private readonly sampleRate = 48000,\n debug = false\n ) {\n this.logger = new Logger(debug);\n\n // Spawn ffplay to read raw PCM (s16le) on stdin\n this.ffplay = spawn('ffplay', [\n '-f',\n 's16le',\n '-ar',\n this.sampleRate.toString(),\n '-ac',\n '1', // mono\n '-nodisp',\n '-loglevel',\n 'quiet',\n '-i',\n 'pipe:0',\n ]);\n\n this.ffplay.on('error', (err) => {\n this.logger.error('[MonitorAudioPlugin] ffplay error =>', err);\n });\n\n this.ffplay.on('close', (code) => {\n this.logger.info('[MonitorAudioPlugin] ffplay closed => code=', code);\n this.ffplay = undefined;\n });\n\n this.logger.info(\n `[MonitorAudioPlugin] Started ffplay for real-time monitoring (sampleRate=${this.sampleRate})`\n );\n }\n\n /**\n * Called whenever PCM frames arrive (from a speaker).\n * Writes frames to ffplay's stdin to play them in real time.\n */\n onAudioData(data: AudioDataWithUser): void {\n // Log debug info\n this.logger.debug(\n `[MonitorAudioPlugin] onAudioData => userId=${data.userId}, samples=${data.samples.length}, sampleRate=${data.sampleRate}`\n );\n\n if (!this.ffplay?.stdin.writable) {\n return;\n }\n\n // In this plugin, we assume data.sampleRate matches our expected sampleRate.\n // Convert the Int16Array to a Buffer, then write to ffplay stdin.\n const pcmBuffer = Buffer.from(data.samples.buffer);\n this.ffplay.stdin.write(pcmBuffer);\n }\n\n /**\n * Cleanup is called when the plugin is removed or when the space/participant stops.\n * Ends the ffplay process and closes its stdin pipe.\n */\n cleanup(): void {\n this.logger.info('[MonitorAudioPlugin] Cleanup => stopping ffplay');\n if (this.ffplay) {\n this.ffplay.stdin.end();\n this.ffplay.kill();\n this.ffplay = undefined;\n }\n }\n}\n","import type { Space } from '../core/Space';\nimport { Logger } from '../logger';\nimport type { AudioDataWithUser, Plugin } from '../types';\n\n/**\n * IdleMonitorPlugin\n * -----------------\n * Monitors silence in both remote speaker audio and local (pushed) audio.\n * If no audio is detected for a specified duration, it emits an 'idleTimeout' event on the space.\n */\n/**\n * Class representing an Idle Monitor Plugin.\n * * @implements { Plugin }\n */\nexport class IdleMonitorPlugin implements Plugin {\n private space?: Space;\n private logger?: Logger;\n\n private lastSpeakerAudioMs = Date.now();\n private lastLocalAudioMs = Date.now();\n private checkInterval?: NodeJS.Timeout;\n\n /**\n * @param idleTimeoutMs The duration (in ms) of total silence before triggering idle. (Default: 60s)\n * @param checkEveryMs How frequently (in ms) to check for silence. (Default: 10s)\n */\n constructor(\n private idleTimeoutMs = 60_000,\n private checkEveryMs = 10_000\n ) {}\n\n /**\n * Called immediately after .use(plugin).\n * Allows for minimal setup, including obtaining a debug logger if desired.\n */\n onAttach(params: { space: Space; pluginConfig?: Record<string, any> }): void {\n this.space = params.space;\n const debug = params.pluginConfig?.debug ?? false;\n this.logger = new Logger(debug);\n\n this.logger.info('[IdleMonitorPlugin] onAttach => plugin attached');\n }\n\n /**\n * Called once the space has fully initialized (basic mode).\n * We set up idle checks and override pushAudio to detect local audio activity.\n */\n init(params: { space: Space; pluginConfig?: Record<string, any> }): void {\n this.space = params.space;\n this.logger?.info('[IdleMonitorPlugin] init => setting up idle checks');\n\n // Update lastSpeakerAudioMs on incoming speaker audio\n // (Here we're hooking into an event triggered by Space for each speaker's PCM data.)\n this.space.on('audioDataFromSpeaker', (_data: AudioDataWithUser) => {\n this.lastSpeakerAudioMs = Date.now();\n });\n\n // Patch space.pushAudio to track local audio\n const originalPushAudio = this.space.pushAudio.bind(this.space);\n this.space.pushAudio = (samples, sampleRate) => {\n this.lastLocalAudioMs = Date.now();\n originalPushAudio(samples, sampleRate);\n };\n\n // Periodically check for silence\n this.checkInterval = setInterval(() => this.checkIdle(), this.checkEveryMs) as any;\n }\n\n /**\n * Checks if we've exceeded idleTimeoutMs with no audio activity.\n * If so, emits an 'idleTimeout' event on the space with { idleMs } info.\n */\n private checkIdle() {\n const now = Date.now();\n const lastAudio = Math.max(this.lastSpeakerAudioMs, this.lastLocalAudioMs);\n const idleMs = now - lastAudio;\n\n if (idleMs >= this.idleTimeoutMs) {\n this.logger?.warn(`[IdleMonitorPlugin] idleTimeout => no audio for ${idleMs}ms`);\n this.space?.emit('idleTimeout', { idleMs });\n }\n }\n\n /**\n * Returns how many milliseconds have passed since any audio was detected (local or speaker).\n */\n public getIdleTimeMs(): number {\n const now = Date.now();\n const lastAudio = Math.max(this.lastSpeakerAudioMs, this.lastLocalAudioMs);\n return now - lastAudio;\n }\n\n /**\n * Cleans up resources (interval) when the plugin is removed or space stops.\n */\n cleanup(): void {\n this.logger?.info('[IdleMonitorPlugin] cleanup => stopping idle checks');\n if (this.checkInterval) {\n clearInterval(this.checkInterval);\n this.checkInterval = undefined;\n }\n }\n}\n","import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process';\nimport type { Space } from '../core/Space';\nimport { Logger } from '../logger';\nimport type { OccupancyUpdate, Plugin } from '../types';\n\n/**\n * HlsRecordPlugin\n * ---------------\n * Records the final Twitter Spaces HLS mix to a local .ts file using ffmpeg.\n *\n * Workflow:\n * - Wait for occupancy > 0 (i.e., at least one listener).\n * - Attempt to retrieve the HLS URL from Twitter (via client).\n * - If valid (HTTP 200), spawn ffmpeg to record the stream.\n * - If HLS not ready yet (HTTP 404), wait for next occupancy event.\n *\n * Lifecycle:\n * - onAttach(...) => minimal references, logger setup\n * - init(...) => fully runs once the Space is created (broadcastInfo ready)\n * - cleanup() => stop ffmpeg if running\n */\n/**\n * HlsRecordPlugin class for recording HLS stream from Twitter Space.\n *\n * @param {string} [outputPath] - Optional output path for recording.\n *\n * @property {Logger} [logger] - Logger instance for logging.\n * @property {ChildProcessWithoutNullStreams} [recordingProcess] - Child process for recording.\n * @property {boolean} isRecording - Flag indicating if recording is in progress.\n * @property {string} [outputPath] - Output path for recording.\n * @property {string} [mediaKey] - Media key for the broadcast.\n * @property {Space} [space] - Twitter Space instance where recording is happening.\n *\n * @method constructor - HlsRecordPlugin constructor.\n * @method onAttach - Method called after attaching the plugin to store references and create a Logger.\n * @method init - Method called after Space has fully initialized to prepare for recording.\n * @method handleOccupancyUpdate - Private method to handle occupancy updates and start recording if necessary.\n * @method waitForHlsReady - Private method to check if HLS URL is ready for recording.\n * @method startRecording - Private method to spawn ffmpeg for recording HLS stream.\n * @method cleanup - Method called when the plugin is being cleaned up, to stop the recording process.\n */\n\nexport class HlsRecordPlugin implements Plugin {\n private logger?: Logger;\n private recordingProcess?: ChildProcessWithoutNullStreams;\n private isRecording = false;\n\n private outputPath?: string;\n private mediaKey?: string;\n private space?: Space;\n\n /**\n * You can optionally provide an outputPath in the constructor.\n * Alternatively, it can be set via pluginConfig in onAttach/init.\n */\n constructor(outputPath?: string) {\n this.outputPath = outputPath;\n }\n\n /**\n * Called immediately after .use(plugin). We store references here\n * (e.g., the space) and create a Logger based on pluginConfig.debug.\n */\n onAttach(params: { space: Space; pluginConfig?: Record<string, any> }): void {\n this.space = params.space;\n\n const debug = params.pluginConfig?.debug ?? false;\n this.logger = new Logger(debug);\n\n this.logger.info('[HlsRecordPlugin] onAttach => plugin attached');\n\n // If outputPath was not passed in constructor, check pluginConfig\n if (params.pluginConfig?.outputPath) {\n this.outputPath = params.pluginConfig.outputPath;\n }\n }\n\n /**\n * Called once the Space has fully initialized (broadcastInfo is ready).\n * We retrieve the media_key from the broadcast, subscribe to occupancy,\n * and prepare for recording if occupancy > 0.\n */\n async init(params: { space: Space; pluginConfig?: Record<string, any> }) {\n // Merge plugin config again (in case it was not set in onAttach).\n if (params.pluginConfig?.outputPath) {\n this.outputPath = params.pluginConfig.outputPath;\n }\n\n // Use the same logger from onAttach\n const broadcastInfo = (this.space as any)?.broadcastInfo;\n if (!broadcastInfo || !broadcastInfo.broadcast?.media_key) {\n this.logger?.warn('[HlsRecordPlugin] No media_key found in broadcastInfo');\n return;\n }\n this.mediaKey = broadcastInfo.broadcast.media_key;\n\n // If no custom output path was provided, use a default\n const roomId = broadcastInfo.room_id || 'unknown_room';\n if (!this.outputPath) {\n this.outputPath = `/tmp/record_${roomId}.ts`;\n }\n\n this.logger?.info(\n `[HlsRecordPlugin] init => ready to record. Output path=\"${this.outputPath}\"`\n );\n\n // Listen for occupancy updates\n this.space?.on('occupancyUpdate', (update: OccupancyUpdate) => {\n this.handleOccupancyUpdate(update).catch((err) => {\n this.logger?.error('[HlsRecordPlugin] handleOccupancyUpdate =>', err);\n });\n });\n }\n\n /**\n * If occupancy > 0 and we're not recording yet, attempt to fetch the HLS URL\n * from Twitter. If it's ready, spawn ffmpeg to record.\n */\n private async handleOccupancyUpdate(update: OccupancyUpdate) {\n if (!this.space || !this.mediaKey) return;\n if (this.isRecording) return;\n if (update.occupancy <= 0) {\n this.logger?.debug('[HlsRecordPlugin] occupancy=0 => ignoring');\n return;\n }\n\n this.logger?.debug(\n `[HlsRecordPlugin] occupancy=${update.occupancy} => trying to fetch HLS URL...`\n );\n\n const client = (this.space as any).client;\n if (!client) {\n this.logger?.warn('[HlsRecordPlugin] No client found on space');\n return;\n }\n\n try {\n const status = await client.getAudioSpaceStreamStatus(this.mediaKey);\n if (!status?.source?.location) {\n this.logger?.debug('[HlsRecordPlugin] occupancy>0 but no HLS URL => wait next update');\n return;\n }\n\n const hlsUrl = status.source.location;\n const isReady = await this.waitForHlsReady(hlsUrl, 1);\n if (!isReady) {\n this.logger?.debug('[HlsRecordPlugin] HLS URL 404 => waiting next occupancy update...');\n return;\n }\n await this.startRecording(hlsUrl);\n } catch (err) {\n this.logger?.error('[HlsRecordPlugin] handleOccupancyUpdate =>', err);\n }\n }\n\n /**\n * HEAD request to see if the HLS URL is returning 200 OK.\n * maxRetries=1 => only try once here; rely on occupancy re-calls otherwise.\n */\n private async waitForHlsReady(hlsUrl: string, maxRetries: number): Promise<boolean> {\n let attempt = 0;\n while (attempt < maxRetries) {\n try {\n const resp = await fetch(hlsUrl, { method: 'HEAD' });\n if (resp.ok) {\n this.logger?.debug(`[HlsRecordPlugin] HLS is ready (attempt #${attempt + 1})`);\n return true;\n }\n this.logger?.debug(`[HlsRecordPlugin] HLS status=${resp.status}, retrying...`);\n } catch (error) {\n this.logger?.debug('[HlsRecordPlugin] HLS fetch error =>', (error as Error).message);\n }\n attempt++;\n await new Promise((r) => setTimeout(r, 2000));\n }\n return false;\n }\n\n /**\n * Spawns ffmpeg to record the HLS stream at the given URL.\n */\n private async startRecording(hlsUrl: string): Promise<void> {\n if (this.isRecording) {\n this.logger?.debug('[HlsRecordPlugin] Already recording, skipping...');\n return;\n }\n this.isRecording = true;\n\n if (!this.outputPath) {\n this.logger?.warn('[HlsRecordPlugin] No output path set, using /tmp/space_record.ts');\n this.outputPath = '/tmp/space_record';\n }\n\n this.logger?.info('[HlsRecordPlugin] Starting HLS recording =>', hlsUrl);\n\n this.recordingProcess = spawn('ffmpeg', ['-y', '-i', hlsUrl, '-c', 'copy', this.outputPath]);\n\n // Capture stderr for errors or debug info\n this.recordingProcess.stderr.on('data', (chunk) => {\n const msg = chunk.toString();\n if (msg.toLowerCase().includes('error')) {\n this.logger?.error('[HlsRecordPlugin][ffmpeg error] =>', msg.trim());\n } else {\n this.logger?.debug('[HlsRecordPlugin][ffmpeg]', msg.trim());\n }\n });\n\n this.recordingProcess.on('close', (code) => {\n this.isRecording = false;\n this.logger?.info('[HlsRecordPlugin] Recording process closed => code=', code);\n });\n\n this.recordingProcess.on('error', (err) => {\n this.logger?.error('[HlsRecordPlugin] Recording process failed =>', err);\n });\n }\n\n /**\n * Called when the plugin is cleaned up (e.g. space.stop()).\n * Kills ffmpeg if still running.\n */\n cleanup(): void {\n if (this.isRecording && this.recordingProcess) {\n this.logger?.info('[HlsRecordPlugin] Stopping HLS recording...');\n this.recordingProcess.kill();\n this.recordingProcess = undefined;\n this.isRecording = false;\n }\n }\n}\n","// src/plugins/SttTtsPlugin.ts\n\nimport { spawn } from \"node:child_process\";\nimport type { Readable } from \"node:stream\";\nimport {\n ChannelType,\n type Content,\n EventType,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n ModelType,\n type Plugin,\n createUniqueUuid,\n logger,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base\";\nimport type { AudioDataWithUser, JanusClient, Space } from \"./client\";\ntype Timer = NodeJS.Timeout;\n\n/**\n * Interface for defining configuration options for a plugin.\n * @typedef {Object} PluginConfig\n * @property {IAgentRuntime} runtime - The runtime environment for the plugin.\n * @property {ClientBase} client - The client to interact with.\n * @property {string} spaceId - The ID of the space the plugin is associated with.\n */\ninterface PluginConfig {\n runtime: IAgentRuntime;\n client: ClientBase;\n spaceId: string;\n}\n\nconst VOLUME_WINDOW_SIZE = 100;\nconst SPEAKING_THRESHOLD = 0.05;\nconst SILENCE_DETECTION_THRESHOLD_MS = 1000; // 1-second silence threshold\n\n/**\n * MVP plugin for speech-to-text (OpenAI) + conversation + TTS (ElevenLabs)\n * Approach:\n * - Collect each speaker's unmuted PCM in a memory buffer (only if above silence threshold)\n * - On speaker mute -> flush STT -> GPT -> TTS -> push to Janus\n */\n/**\n * Class representing a plugin for Speech-to-text (OpenAI) + conversation + TTS (ElevenLabs).\n * @class\n */\n\nexport class SttTtsPlugin implements Plugin {\n name = \"SttTtsPlugin\";\n description = \"Speech-to-text (OpenAI) + conversation + TTS (ElevenLabs)\";\n private runtime: IAgentRuntime;\n private spaceId: string;\n\n private space?: Space;\n private janus?: JanusClient;\n\n /**\n * userId => arrayOfChunks (PCM Int16)\n */\n private pcmBuffers = new Map<string, Int16Array[]>();\n\n // TTS queue for sequentially speaking\n private ttsQueue: string[] = [];\n private isSpeaking = false;\n private isProcessingAudio = false;\n private userSpeakingTimer: Timer | null = null;\n private volumeBuffers: Map<string, number[]>;\n private ttsAbortController: AbortController | null = null;\n\n onAttach(_space: Space) {\n logger.log(\"[SttTtsPlugin] onAttach => space was attached\");\n }\n\n async init(params): Promise<void> {\n logger.log(\n \"[SttTtsPlugin] init => Space fully ready. Subscribing to events.\"\n );\n\n this.space = params.space;\n this.janus = (this.space as any)?.janusClient as JanusClient | undefined;\n\n const config = params.pluginConfig as PluginConfig;\n this.runtime = config?.runtime;\n this.spaceId = config?.spaceId;\n\n this.volumeBuffers = new Map<string, number[]>();\n }\n\n /**\n * Called whenever we receive PCM from a speaker\n */\n onAudioData(data: AudioDataWithUser): void {\n if (this.isProcessingAudio) {\n return;\n }\n /**\n * For ignoring near-silence frames (if amplitude < threshold)\n */\n const silenceThreshold = 50;\n let maxVal = 0;\n for (let i = 0; i < data.samples.length; i++) {\n const val = Math.abs(data.samples[i]);\n if (val > maxVal) maxVal = val;\n }\n if (maxVal < silenceThreshold) {\n return;\n }\n\n if (this.userSpeakingTimer) {\n clearTimeout(this.userSpeakingTimer);\n }\n\n let arr = this.pcmBuffers.get(data.userId);\n if (!arr) {\n arr = [];\n this.pcmBuffers.set(data.userId, arr);\n }\n arr.push(data.samples);\n\n if (!this.isSpeaking) {\n this.userSpeakingTimer = setTimeout(() => {\n logger.log(\n \"[SttTtsPlugin] start processing audio for user =>\",\n data.userId\n );\n this.userSpeakingTimer = null;\n this.processAudio(data.userId).catch((err) =>\n logger.error(\"[SttTtsPlugin] handleSilence error =>\", err)\n );\n }, SILENCE_DETECTION_THRESHOLD_MS);\n } else {\n // check interruption\n let volumeBuffer = this.volumeBuffers.get(data.userId);\n if (!volumeBuffer) {\n volumeBuffer = [];\n this.volumeBuffers.set(data.userId, volumeBuffer);\n }\n const samples = new Int16Array(\n data.samples.buffer,\n data.samples.byteOffset,\n data.samples.length / 2\n );\n const maxAmplitude = Math.max(...samples.map(Math.abs)) / 32768;\n volumeBuffer.push(maxAmplitude);\n\n if (volumeBuffer.length > VOLUME_WINDOW_SIZE) {\n volumeBuffer.shift();\n }\n const avgVolume =\n volumeBuffer.reduce((sum, v) => sum + v, 0) / VOLUME_WINDOW_SIZE;\n\n if (avgVolume > SPEAKING_THRESHOLD) {\n volumeBuffer.length = 0;\n if (this.ttsAbortController) {\n this.ttsAbortController.abort();\n this.isSpeaking = false;\n logger.log(\"[SttTtsPlugin] TTS playback interrupted\");\n }\n }\n }\n }\n\n // /src/sttTtsPlugin.ts\n private async convertPcmToWavInMemory(\n pcmData: Int16Array,\n sampleRate: number\n ): Promise<ArrayBuffer> {\n // number of channels\n const numChannels = 1;\n // byte rate = (sampleRate * numChannels * bitsPerSample/8)\n const byteRate = sampleRate * numChannels * 2;\n const blockAlign = numChannels * 2;\n // data chunk size = pcmData.length * (bitsPerSample/8)\n const dataSize = pcmData.length * 2;\n\n // WAV header is 44 bytes\n const buffer = new ArrayBuffer(44 + dataSize);\n const view = new DataView(buffer);\n\n // RIFF chunk descriptor\n this.writeString(view, 0, \"RIFF\");\n view.setUint32(4, 36 + dataSize, true); // file size - 8\n this.writeString(view, 8, \"WAVE\");\n\n // fmt sub-chunk\n this.writeString(view, 12, \"fmt \");\n view.setUint32(16, 16, true); // Subchunk1Size (16 for PCM)\n view.setUint16(20, 1, true); // AudioFormat (1 = PCM)\n view.setUint16(22, numChannels, true); // NumChannels\n view.setUint32(24, sampleRate, true); // SampleRate\n view.setUint32(28, byteRate, true); // ByteRate\n view.setUint16(32, blockAlign, true); // BlockAlign\n view.setUint16(34, 16, true); // BitsPerSample (16)\n\n // data sub-chunk\n this.writeString(view, 36, \"data\");\n view.setUint32(40, dataSize, true);\n\n // Write PCM samples\n let offset = 44;\n for (let i = 0; i < pcmData.length; i++, offset += 2) {\n view.setInt16(offset, pcmData[i], true);\n }\n\n return buffer;\n }\n\n private writeString(view: DataView, offset: number, text: string) {\n for (let i = 0; i < text.length; i++) {\n view.setUint8(offset + i, text.charCodeAt(i));\n }\n }\n\n /**\n * On speaker silence => flush STT => GPT => TTS => push to Janus\n */\n private async processAudio(userId: string): Promise<void> {\n if (this.isProcessingAudio) {\n return;\n }\n this.isProcessingAudio = true;\n try {\n logger.log(\"[SttTtsPlugin] Starting audio processing for user:\", userId);\n const chunks = this.pcmBuffers.get(userId) || [];\n this.pcmBuffers.clear();\n\n if (!chunks.length) {\n logger.warn(\"[SttTtsPlugin] No audio chunks for user =>\", userId);\n return;\n }\n logger.log(\n `[SttTtsPlugin] Flushing STT buffer for user=${userId}, chunks=${chunks.length}`\n );\n\n const totalLen = chunks.reduce((acc, c) => acc + c.length, 0);\n const merged = new Int16Array(totalLen);\n let offset = 0;\n for (const c of chunks) {\n merged.set(c, offset);\n offset += c.length;\n }\n\n // Convert PCM to WAV for STT\n const wavBuffer = await this.convertPcmToWavInMemory(merged, 48000);\n\n // Whisper STT\n const sttText = await this.runtime.useModel(\n ModelType.TRANSCRIPTION,\n wavBuffer\n );\n\n logger.log(`[SttTtsPlugin] Transcription result: \"${sttText}\"`);\n\n if (!sttText || !sttText.trim()) {\n logger.warn(\"[SttTtsPlugin] No speech recognized for user =>\", userId);\n return;\n }\n logger.log(`[SttTtsPlugin] STT => user=${userId}, text=\"${sttText}\"`);\n\n // Get response\n await this.handleUserMessage(sttText, userId);\n } catch (error) {\n logger.error(\"[SttTtsPlugin] processAudio error =>\", error);\n } finally {\n this.isProcessingAudio = false;\n }\n }\n\n /**\n * Public method to queue a TTS request\n */\n public async speakText(text: string): Promise<void> {\n this.ttsQueue.push(text);\n if (!this.isSpeaking) {\n this.isSpeaking = true;\n this.processTtsQueue().catch((err) => {\n logger.error(\"[SttTtsPlugin] processTtsQueue error =>\", err);\n });\n }\n }\n\n /**\n * Process TTS requests one by one\n */\n private async processTtsQueue(): Promise<void> {\n while (this.ttsQueue.length > 0) {\n const text = this.ttsQueue.shift();\n if (!text) continue;\n\n this.ttsAbortController = new AbortController();\n const { signal } = this.ttsAbortController;\n\n try {\n const responseStream = await this.runtime.useModel(\n ModelType.TEXT_TO_SPEECH,\n text\n );\n if (!responseStream) {\n logger.error(\"[SttTtsPlugin] TTS responseStream is null\");\n continue;\n }\n\n logger.log(\"[SttTtsPlugin] Received ElevenLabs TTS stream\");\n\n // Convert the Readable Stream to PCM and stream to Janus\n await this.streamTtsStreamToJanus(responseStream, 48000, signal);\n\n if (signal.aborted) {\n logger.log(\"[SttTtsPlugin] TTS interrupted after streaming\");\n return;\n }\n } catch (err) {\n logger.error(\"[SttTtsPlugin] TTS streaming error =>\", err);\n } finally {\n // Clean up the AbortController\n this.ttsAbortController = null;\n }\n }\n this.isSpeaking = false;\n }\n\n /**\n * Handle User Message\n */\n private async handleUserMessage(\n userText: string,\n userId: string // This is the raw Twitter user ID like 'tw-1865462035586142208'\n ): Promise<string> {\n if (!userText || userText.trim() === \"\") {\n return null;\n }\n\n // Extract the numeric ID part\n const numericId = userId.replace(\"tw-\", \"\");\n const roomId = createUniqueUuid(\n this.runtime,\n `twitter_generate_room-${this.spaceId}`\n );\n\n // Create consistent UUID for the user\n const userUuid = createUniqueUuid(this.runtime, numericId);\n\n const entity = await this.runtime.getEntityById(userUuid);\n if (!entity) {\n await this.runtime.createEntity({\n id: userUuid,\n names: [userId],\n agentId: this.runtime.agentId,\n });\n }\n\n // Ensure room exists and user is in it\n await this.runtime.ensureConnection({\n entityId: userUuid,\n roomId: roomId,\n name: \"Twitter Space\",\n source: \"twitter\",\n type: ChannelType.VOICE_GROUP,\n channelId: null,\n serverId: this.spaceId,\n worldId: createUniqueUuid(this.runtime, this.spaceId),\n });\n\n const memory = {\n id: createUniqueUuid(\n this.runtime,\n `${roomId}-voice-message-${Date.now()}`\n ),\n agentId: this.runtime.agentId,\n content: {\n text: userText,\n source: \"twitter\",\n },\n userId: userUuid,\n roomId,\n createdAt: Date.now(),\n };\n\n const callback: HandlerCallback = async (\n content: Content,\n _files: any[] = []\n ) => {\n try {\n const responseMemory: Memory = {\n id: createUniqueUuid(\n this.runtime,\n `${memory.id}-voice-response-${Date.now()}`\n ),\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n content: {\n ...content,\n user: this.runtime.character.name,\n inReplyTo: memory.id,\n isVoiceMessage: true,\n },\n roomId,\n createdAt: Date.now(),\n };\n\n if (responseMemory.content.text?.trim()) {\n await this.runtime.createMemory(responseMemory, \"messages\");\n this.isProcessingAudio = false;\n this.volumeBuffers.clear();\n await this.speakText(content.text);\n }\n\n return [responseMemory];\n } catch (error) {\n console.error(\"Error in voice message callback:\", error);\n return [];\n }\n };\n\n // Emit voice-specific events\n this.runtime.emitEvent(EventType.VOICE_MESSAGE_RECEIVED, {\n runtime: this.runtime,\n message: memory,\n callback,\n });\n }\n\n /**\n * Convert MP3 => PCM via ffmpeg\n */\n private convertMp3ToPcm(\n mp3Buf: Buffer,\n outRate: number\n ): Promise<Int16Array> {\n return new Promise((resolve, reject) => {\n const ff = spawn(\"ffmpeg\", [\n \"-i\",\n \"pipe:0\",\n \"-f\",\n \"s16le\",\n \"-ar\",\n outRate.toString(),\n \"-ac\",\n \"1\",\n \"pipe:1\",\n ]);\n let raw = Buffer.alloc(0);\n\n ff.stdout.on(\"data\", (chunk: Buffer) => {\n raw = Buffer.concat([raw, chunk]);\n });\n ff.stderr.on(\"data\", () => {\n // ignoring ffmpeg logs\n });\n ff.on(\"close\", (code) => {\n if (code !== 0) {\n reject(new Error(`ffmpeg error code=${code}`));\n return;\n }\n const samples = new Int16Array(\n raw.buffer,\n raw.byteOffset,\n raw.byteLength / 2\n );\n resolve(samples);\n });\n\n ff.stdin.write(mp3Buf);\n ff.stdin.end();\n });\n }\n\n /**\n * Push PCM back to Janus in small frames\n * We'll do 10ms @48k => 960 samples per frame\n */\n private async streamToJanus(\n samples: Int16Array,\n sampleRate: number\n ): Promise<void> {\n // TODO: Check if better than 480 fixed\n const FRAME_SIZE = Math.floor(sampleRate * 0.01); // 10ms frames => 480 @48kHz\n\n for (\n let offset = 0;\n offset + FRAME_SIZE <= samples.length;\n offset += FRAME_SIZE\n ) {\n if (this.ttsAbortController?.signal.aborted) {\n logger.log(\"[SttTtsPlugin] streamToJanus interrupted\");\n return;\n }\n const frame = new Int16Array(FRAME_SIZE);\n frame.set(samples.subarray(offset, offset + FRAME_SIZE));\n this.janus?.pushLocalAudio(frame, sampleRate, 1);\n\n // Short pause so we don't overload\n await new Promise((r) => setTimeout(r, 10));\n }\n }\n\n private async streamTtsStreamToJanus(\n stream: Readable,\n sampleRate: number,\n signal: AbortSignal\n ): Promise<void> {\n const chunks: Buffer[] = [];\n\n return new Promise((resolve, reject) => {\n stream.on(\"data\", (chunk: Buffer) => {\n if (signal.aborted) {\n logger.log(\"[SttTtsPlugin] Stream aborted, stopping playback\");\n stream.destroy();\n reject(new Error(\"TTS streaming aborted\"));\n return;\n }\n chunks.push(chunk);\n });\n\n stream.on(\"end\", async () => {\n if (signal.aborted) {\n logger.log(\"[SttTtsPlugin] Stream ended but was aborted\");\n return reject(new Error(\"TTS streaming aborted\"));\n }\n\n const mp3Buffer = Buffer.concat(chunks);\n\n try {\n // Convert MP3 to PCM\n const pcmSamples = await this.convertMp3ToPcm(mp3Buffer, sampleRate);\n\n // Stream PCM to Janus\n await this.streamToJanus(pcmSamples, sampleRate);\n resolve();\n } catch (error) {\n reject(error);\n }\n });\n\n stream.on(\"error\", (error) => {\n logger.error(\"[SttTtsPlugin] Error in TTS stream\", error);\n reject(error);\n });\n });\n }\n\n cleanup(): void {\n logger.log(\"[SttTtsPlugin] cleanup => releasing resources\");\n this.pcmBuffers.clear();\n this.userSpeakingTimer = null;\n this.ttsQueue = [];\n this.isSpeaking = false;\n this.volumeBuffers.clear();\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Media, State } from \"@elizaos/core\";\nimport {\n type Content,\n type IAgentRuntime,\n type Memory,\n ModelType,\n type UUID,\n composePrompt,\n createUniqueUuid,\n logger,\n truncateToCompleteSentence,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base\";\nimport type { Tweet } from \"./client\";\nimport type { SttTtsPlugin } from \"./sttTtsSpaces\";\nimport type { ActionResponse, MediaData } from \"./types\";\nimport { TWEET_CHAR_LIMIT } 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 const noteTweetResult = await client.requestQueue.add(\n async () =>\n await client.twitterClient.sendNoteTweet(content, tweetId, mediaData)\n );\n\n if (noteTweetResult.errors && noteTweetResult.errors.length > 0) {\n // Note Tweet failed due to authorization. Falling back to standard Tweet.\n const truncateContent = truncateToCompleteSentence(\n content,\n TWEET_CHAR_LIMIT - 1\n );\n return await sendStandardTweet(client, truncateContent, tweetId);\n }\n return noteTweetResult.data.notetweet_create.tweet_results.result;\n}\n\n/**\n * Asynchronously sends a standard tweet using the provided Twitter client.\n *\n * @param {ClientBase} client - The client used to make the request.\n * @param {string} content - The content of the tweet.\n * @param {string} [tweetId] - Optional tweet ID to reply to.\n * @param {MediaData[]} [mediaData] - Optional array of media data to attach to the tweet.\n * @returns {Promise<string>} The result of sending the tweet.\n */\nexport async function sendStandardTweet(\n client: ClientBase,\n content: string,\n tweetId?: string,\n mediaData?: MediaData[]\n) {\n const standardTweetResult = await client.requestQueue.add(\n async () =>\n await client.twitterClient.sendTweet(content, tweetId, mediaData)\n );\n const body = await standardTweetResult.json();\n if (!body?.data?.create_tweet?.tweet_results?.result) {\n logger.error(\"Error sending tweet; Bad response:\", body);\n return;\n }\n return body.data.create_tweet.tweet_results.result;\n}\n\nexport async function sendTweet(\n client: ClientBase,\n text: string,\n mediaData: MediaData[] = [],\n tweetToReplyTo?: string\n): Promise<any> {\n if (text.length > TWEET_CHAR_LIMIT - 1) {\n return await handleNoteTweet(client, text, tweetToReplyTo, mediaData);\n } else {\n return await sendStandardTweet(client, text, tweetToReplyTo, mediaData);\n }\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 isLongTweet = content.text.length > TWEET_CHAR_LIMIT - 1;\n\n const tweetChunks = splitTweetContent(content.text, TWEET_CHAR_LIMIT - 1);\n const sentTweets: Tweet[] = [];\n let previousTweetId = inReplyTo;\n\n for (const chunk of tweetChunks) {\n let mediaData = null;\n\n if (content.attachments && content.attachments.length > 0) {\n mediaData = await fetchMediaData(content.attachments);\n }\n\n const cleanChunk = deduplicateMentions(chunk.trim());\n\n const result = await client.requestQueue.add(async () =>\n isLongTweet\n ? client.twitterClient.sendLongTweet(\n cleanChunk,\n previousTweetId,\n mediaData\n )\n : client.twitterClient.sendTweet(cleanChunk, previousTweetId, mediaData)\n );\n\n const body = await result.json();\n const tweetResult = isLongTweet\n ? body?.data?.notetweet_create?.tweet_results?.result\n : body?.data?.create_tweet?.tweet_results?.result;\n\n // if we have a response\n if (tweetResult) {\n // Parse the response\n const finalTweet: Tweet = {\n id: tweetResult.rest_id,\n text: tweetResult.legacy.full_text,\n conversationId: tweetResult.legacy.conversation_id_str,\n timestamp: new Date(tweetResult.legacy.created_at).getTime() / 1000,\n userId: tweetResult.legacy.user_id_str,\n inReplyToStatusId: tweetResult.legacy.in_reply_to_status_id_str,\n permanentUrl: `https://twitter.com/${twitterUsername}/status/${tweetResult.rest_id}`,\n hashtags: [],\n mentions: [],\n photos: [],\n thread: [],\n urls: [],\n videos: [],\n };\n sentTweets.push(finalTweet);\n previousTweetId = finalTweet.id;\n } else {\n logger.error(\"Error sending tweet chunk:\", {\n chunk,\n response: body,\n });\n }\n\n // Wait a bit between tweets to avoid rate limiting issues\n await wait(1000, 2000);\n }\n\n const memories: Memory[] = sentTweets.map((tweet) => ({\n id: createUniqueUuid(client.runtime, tweet.id),\n agentId: client.runtime.agentId,\n entityId: client.runtime.agentId,\n content: {\n tweetId: tweet.id,\n text: tweet.text,\n source: \"twitter\",\n url: tweet.permanentUrl,\n imageUrls: tweet.photos.map((p) => p.url) || [],\n inReplyTo: tweet.inReplyToStatusId\n ? createUniqueUuid(client.runtime, tweet.inReplyToStatusId)\n : undefined,\n },\n roomId,\n createdAt: tweet.timestamp * 1000,\n }));\n\n return memories;\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/**\n * Generate short filler text via GPT\n */\n/**\n * Generates a short filler message for a Twitter Space based on the specified filler type.\n *\n * @param {IAgentRuntime} runtime - The agent runtime instance to use for generating the filler.\n * @param {string} fillerType - The type of filler message to generate.\n * @returns {Promise<string>} The generated filler message as a string.\n */\nexport async function generateFiller(\n runtime: IAgentRuntime,\n fillerType: string\n): Promise<string> {\n const prompt = composePrompt({\n state: {\n values: {\n fillerType,\n },\n } as any as State,\n template: `\n# INSTRUCTIONS:\nYou are generating a short filler message for a Twitter Space. The filler type is \"{{fillerType}}\".\nKeep it brief, friendly, and relevant. No more than two sentences.\nOnly return the text, no additional formatting.\n\n---\n`,\n });\n const output = await runtime.useModel(ModelType.TEXT_SMALL, {\n prompt,\n });\n return output.trim();\n}\n\n/**\n * Speak a filler message if STT/TTS plugin is available. Sleep a bit after TTS to avoid cutoff.\n */\nexport async function speakFiller(\n runtime: IAgentRuntime,\n sttTtsPlugin: SttTtsPlugin | undefined,\n fillerType: string,\n sleepAfterMs = 3000\n): Promise<void> {\n if (!sttTtsPlugin) return;\n const text = await generateFiller(runtime, fillerType);\n if (!text) return;\n\n logger.log(`[Space] Filler (${fillerType}) => ${text}`);\n await sttTtsPlugin.speakText(text);\n\n if (sleepAfterMs > 0) {\n await new Promise((res) => setTimeout(res, sleepAfterMs));\n }\n}\n\n/**\n * Generate topic suggestions via GPT if no topics are configured\n */\nexport async function generateTopicsIfEmpty(\n runtime: IAgentRuntime\n): Promise<string[]> {\n const prompt = composePrompt({\n state: {} as any,\n template: `\n# INSTRUCTIONS:\nPlease generate 5 short topic ideas for a Twitter Space about technology or random interesting subjects.\nReturn them as a comma-separated list, no additional formatting or numbering.\n\nExample:\n\"AI Advances, Futuristic Gadgets, Space Exploration, Quantum Computing, Digital Ethics\"\n---\n`,\n });\n const response = await runtime.useModel(ModelType.TEXT_SMALL, {\n prompt,\n });\n const topics = response\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n return topics.length ? topics : [\"Random Tech Chat\", \"AI Thoughts\"];\n}\n\nexport async function isAgentInSpace(\n client: ClientBase,\n spaceId: string\n): Promise<boolean> {\n const space = await client.twitterClient.getAudioSpaceById(spaceId);\n const agentName = client.state.TWITTER_USERNAME;\n\n return (\n space.participants.listeners.some(\n (participant) => participant.twitter_screen_name === agentName\n ) ||\n space.participants.speakers.some(\n (participant) => participant.twitter_screen_name === agentName\n )\n );\n}\n","export const TWITTER_SERVICE_NAME = \"twitter\";\nexport const TWEET_CHAR_LIMIT = 280;\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\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 } catch (error) {\n console.error(\"Error processing request:\", error);\n this.queue.unshift(request);\n await this.exponentialBackoff(this.queue.length);\n }\n await this.randomDelay();\n }\n\n this.processing = false;\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 console.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 parseTweet(raw: any, depth = 0, maxDepth = 3): Tweet {\n // If we've reached maxDepth, don't parse nested quotes/retweets further\n const canRecurse = depth < maxDepth;\n\n const quotedStatus =\n raw.quoted_status_result?.result && canRecurse\n ? this.parseTweet(raw.quoted_status_result.result, depth + 1, maxDepth)\n : undefined;\n\n const retweetedStatus =\n raw.retweeted_status_result?.result && canRecurse\n ? this.parseTweet(\n raw.retweeted_status_result.result,\n depth + 1,\n maxDepth\n )\n : undefined;\n\n const t: Tweet = {\n bookmarkCount:\n raw.bookmarkCount ?? raw.legacy?.bookmark_count ?? undefined,\n conversationId: raw.conversationId ?? raw.legacy?.conversation_id_str,\n hashtags: raw.hashtags ?? raw.legacy?.entities?.hashtags ?? [],\n html: raw.html,\n id: raw.id ?? raw.rest_id ?? raw.legacy.id_str ?? raw.id_str ?? undefined,\n inReplyToStatus: raw.inReplyToStatus,\n inReplyToStatusId:\n raw.inReplyToStatusId ??\n raw.legacy?.in_reply_to_status_id_str ??\n undefined,\n isQuoted: raw.legacy?.is_quote_status === true,\n isPin: raw.isPin,\n isReply: raw.isReply,\n isRetweet: raw.legacy?.retweeted === true,\n isSelfThread: raw.isSelfThread,\n language: raw.legacy?.lang,\n likes: raw.legacy?.favorite_count ?? 0,\n name:\n raw.name ??\n raw?.user_results?.result?.legacy?.name ??\n raw.core?.user_results?.result?.legacy?.name,\n mentions: raw.mentions ?? raw.legacy?.entities?.user_mentions ?? [],\n permanentUrl:\n raw.permanentUrl ??\n (raw.core?.user_results?.result?.legacy?.screen_name && raw.rest_id\n ? `https://x.com/${raw.core?.user_results?.result?.legacy?.screen_name}/status/${raw.rest_id}`\n : undefined),\n photos:\n raw.photos ??\n (raw.legacy?.entities?.media\n ?.filter((media: any) => media.type === \"photo\")\n .map((media: any) => ({\n id: media.id_str || media.rest_id || media.legacy.id_str,\n url: media.media_url_https,\n alt_text: media.alt_text,\n })) ||\n []),\n place: raw.place,\n poll: raw.poll ?? null,\n quotedStatus,\n quotedStatusId:\n raw.quotedStatusId ?? raw.legacy?.quoted_status_id_str ?? undefined,\n quotes: raw.legacy?.quote_count ?? 0,\n replies: raw.legacy?.reply_count ?? 0,\n retweets: raw.legacy?.retweet_count ?? 0,\n retweetedStatus,\n retweetedStatusId: raw.legacy?.retweeted_status_id_str ?? undefined,\n text: raw.text ?? raw.legacy?.full_text ?? undefined,\n thread: raw.thread || [],\n timeParsed: raw.timeParsed\n ? new Date(raw.timeParsed)\n : raw.legacy?.created_at\n ? new Date(raw.legacy?.created_at)\n : undefined,\n timestamp:\n raw.timestamp ??\n (raw.legacy?.created_at\n ? new Date(raw.legacy.created_at).getTime() / 1000\n : undefined),\n urls: raw.urls ?? raw.legacy?.entities?.urls ?? [],\n userId: raw.userId ?? raw.legacy?.user_id_str ?? undefined,\n username:\n raw.username ??\n raw.core?.user_results?.result?.legacy?.screen_name ??\n undefined,\n videos:\n raw.videos ??\n raw.legacy?.entities?.media?.filter(\n (media: any) => media.type === \"video\"\n ) ??\n [],\n views: raw.views?.count ? Number(raw.views.count) : 0,\n sensitiveContent: raw.sensitiveContent,\n };\n\n return t;\n }\n\n state: any;\n\n constructor(runtime: IAgentRuntime, state: any) {\n this.runtime = runtime;\n this.state = state;\n const username =\n state?.TWITTER_USERNAME ||\n (this.runtime.getSetting(\"TWITTER_USERNAME\") as string);\n if (ClientBase._twitterClients[username]) {\n this.twitterClient = ClientBase._twitterClients[username];\n } else {\n this.twitterClient = new Client();\n ClientBase._twitterClients[username] = this.twitterClient;\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 username =\n this.state?.TWITTER_USERNAME ||\n this.runtime.getSetting(\"TWITTER_USERNAME\");\n const password =\n this.state?.TWITTER_PASSWORD ||\n this.runtime.getSetting(\"TWITTER_PASSWORD\");\n const email =\n this.state?.TWITTER_EMAIL || this.runtime.getSetting(\"TWITTER_EMAIL\");\n const twitter2faSecret =\n this.state?.TWITTER_2FA_SECRET ||\n this.runtime.getSetting(\"TWITTER_2FA_SECRET\");\n\n // Validate required credentials\n if (!username || !password || !email) {\n const missing = [];\n if (!username) missing.push(\"TWITTER_USERNAME\");\n if (!password) missing.push(\"TWITTER_PASSWORD\");\n if (!email) missing.push(\"TWITTER_EMAIL\");\n throw new Error(\n `Missing required Twitter 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 const authToken =\n this.state?.TWITTER_COOKIES_AUTH_TOKEN ||\n this.runtime.getSetting(\"TWITTER_COOKIES_AUTH_TOKEN\");\n const ct0 =\n this.state?.TWITTER_COOKIES_CT0 ||\n this.runtime.getSetting(\"TWITTER_COOKIES_CT0\");\n const guestId =\n this.state?.TWITTER_COOKIES_GUEST_ID ||\n this.runtime.getSetting(\"TWITTER_COOKIES_GUEST_ID\");\n\n const createTwitterCookies = (\n authToken: string,\n ct0: string,\n guestId: string\n ) =>\n authToken && ct0 && guestId\n ? [\n { key: \"auth_token\", value: authToken, domain: \".twitter.com\" },\n { key: \"ct0\", value: ct0, domain: \".twitter.com\" },\n { key: \"guest_id\", value: guestId, domain: \".twitter.com\" },\n ]\n : null;\n\n const cachedCookies =\n (await this.getCachedCookies(username)) ||\n createTwitterCookies(authToken, ct0, guestId);\n\n if (cachedCookies) {\n logger.info(\"Using cached cookies\");\n await this.setCookiesFromArray(cachedCookies);\n }\n\n logger.log(\"Waiting for Twitter login\");\n if (await this.twitterClient.isLoggedIn()) {\n // cookies are valid, no login required\n logger.info(\"Successfully logged in.\");\n break;\n }\n await this.twitterClient.login(\n username,\n password,\n email,\n twitter2faSecret\n );\n if (await this.twitterClient.isLoggedIn()) {\n // fresh login, store new cookies\n logger.info(\"Successfully logged in.\");\n logger.info(\"Caching cookies\");\n await this.cacheCookies(\n username,\n await this.twitterClient.getCookies()\n );\n break;\n }\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n logger.error(\n `Login 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 login failed after ${maxRetries} attempts. Last error: ${lastError?.message}`\n );\n }\n\n // Initialize Twitter profile\n this.profile = await this.fetchProfile(username);\n\n if (this.profile) {\n logger.log(\"Twitter user ID:\", this.profile.id);\n logger.log(\"Twitter loaded:\", JSON.stringify(this.profile, null, 10));\n\n const agentId = this.runtime.agentId;\n\n const entity = await this.runtime.getEntityById(agentId);\n if (entity?.metadata?.twitter?.userName !== this.profile.username) {\n logger.log(\n \"Updating Agents known X/twitter handle\",\n this.profile.username,\n \"was\",\n entity?.metadata?.twitter\n );\n const names = [this.profile.screenName, this.profile.username];\n await this.runtime.updateEntity({\n id: agentId,\n names: [...new Set([...(entity.names || []), ...names])].filter(\n Boolean\n ),\n metadata: {\n ...entity.metadata,\n twitter: {\n // we should stomp this, we don't want to carry dev data over to public\n // but you should just clear the db when you do that\n ...entity.metadata?.twitter,\n name: this.profile.screenName,\n userName: this.profile.username,\n },\n },\n agentId,\n });\n }\n\n // Store profile info for use in responses\n this.profile = {\n id: this.profile.id,\n username: this.profile.username, // this is the at\n screenName: this.profile.screenName, // this is the human readable name of the at\n bio: this.profile.bio,\n nicknames: this.profile.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 // Use parseTweet on each tweet\n return homeTimeline.tweets.map((t) => this.parseTweet(t));\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 const processedTimeline = homeTimeline\n .filter((t) => t.__typename !== \"TweetWithVisibilityResults\") // what's this about?\n .map((tweet) => this.parseTweet(tweet));\n\n //logger.debug(\"process homeTimeline\", processedTimeline);\n return processedTimeline;\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 const username = this.runtime.getSetting(\"TWITTER_USERNAME\");\n\n // Get the most recent 20 mentions and interactions\n const mentionsAndInteractions = await this.fetchSearchTweets(\n `@${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 setCookiesFromArray(cookiesArray: any[]) {\n const cookieStrings = cookiesArray.map(\n (cookie) =>\n `${cookie.key}=${cookie.value}; Domain=${cookie.domain}; Path=${cookie.path}; ${\n cookie.secure ? \"Secure\" : \"\"\n }; ${cookie.httpOnly ? \"HttpOnly\" : \"\"}; SameSite=${cookie.sameSite || \"Lax\"}`\n );\n await this.twitterClient.setCookies(cookieStrings);\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 getCachedCookies(username: string) {\n const cached = await this.runtime.getCache<any[]>(\n `twitter/${username}/cookies`\n );\n\n if (!cached) {\n return undefined;\n }\n\n return cached;\n }\n\n async cacheCookies(username: string, cookies: any[]) {\n await this.runtime.setCache<any[]>(`twitter/${username}/cookies`, cookies);\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 console.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 {\n ChannelType,\n type Content,\n ContentType,\n EventType,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type MessagePayload,\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 } 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// Add conversion functions\nconst convertToCoreTweet = (tweet: ClientTweet): CoreTweet => ({\n id: tweet.id,\n text: tweet.text,\n conversationId: tweet.conversationId,\n timestamp: tweet.timestamp,\n userId: tweet.userId,\n username: tweet.username,\n name: tweet.name,\n inReplyToStatusId: tweet.inReplyToStatusId,\n permanentUrl: tweet.permanentUrl,\n photos: tweet.photos,\n hashtags: tweet.hashtags,\n mentions: tweet.mentions.map((mention) => mention.username),\n urls: tweet.urls,\n videos: tweet.videos,\n thread: tweet.thread,\n});\n\nconst convertToCoreTweets = (tweets: ClientTweet[]): CoreTweet[] =>\n tweets.map(convertToCoreTweet);\n\n/**\n * Class representing a client for interacting with Twitter.\n */\nexport class TwitterInteractionClient {\n client: ClientBase;\n runtime: IAgentRuntime;\n private isDryRun: boolean;\n private state: any;\n /**\n * Constructor for setting up a new instance with the provided client, runtime, and state.\n * @param {ClientBase} client - The client being used for communication.\n * @param {IAgentRuntime} runtime - The runtime environment for the agent.\n * @param {any} state - The initial state of the agent.\n */\n constructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n this.client = client;\n this.runtime = runtime;\n this.state = state;\n this.isDryRun =\n this.state?.TWITTER_DRY_RUN ||\n (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 an interval based on the 'TWITTER_POLL_INTERVAL' setting, or defaults to 2 minutes if not set.\n */\n async start() {\n const handleTwitterInteractionsLoop = () => {\n // Defaults to 2 minutes\n const interactionInterval =\n (this.state?.TWITTER_POLL_INTERVAL ||\n (this.runtime.getSetting(\n \"TWITTER_POLL_INTERVAL\"\n ) as unknown as number) ||\n 120) * 1000;\n\n this.handleTwitterInteractions();\n setTimeout(handleTwitterInteractionsLoop, interactionInterval);\n };\n handleTwitterInteractionsLoop();\n }\n\n /**\n * Asynchronously handles Twitter interactions by checking for mentions, processing tweets, and updating the last checked tweet ID.\n */\n async handleTwitterInteractions() {\n logger.log(\"Checking Twitter interactions\");\n\n const twitterUsername = this.client.profile?.username;\n try {\n // Check for mentions\n const cursorKey = `twitter/${twitterUsername}/mention_cursor`;\n const cachedCursor: String =\n 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, \"\"); // used to be null, but DB doesn't allow it\n }\n\n await this.processMentionTweets(mentionCandidates);\n\n // 2. Format mentions into interactions\n // TODO: EventType.REACTION_RECEIVED are not fully handled yet, re-enable once properly processed\n // const interactionCandidates = mentionCandidates\n // .map((tweet) => this.client.formatTweetToInteraction?.(tweet))\n // .filter((i) => i?.targetTweet?.conversationId);\n\n // for (const interaction of interactionCandidates) {\n // try {\n // await this.handleInteraction(interaction);\n // } catch (error) {\n // logger.erro(`Failed to process interaction ${interaction.id}`)\n // }\n // }\n\n // For follower changes:\n // const processFollowerChange = async (\n // change: { type: string; userId: string },\n // profileId: string | undefined\n // ) => {\n // if (change?.type && change?.userId && profileId) {\n // const followerMemory = this.createMemoryObject(\n // change.type,\n // `${change.type}-${change.userId}`,\n // change.userId,\n // profileId\n // );\n\n // await this.runtime.createMemory(followerMemory, 'follower-changes');\n // }\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 * 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 // for each tweet candidate, handle the tweet\n for (const tweet of uniqueTweetCandidates) {\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(this.runtime, tweet.conversationId);\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(memory => \n memory.content?.inReplyTo === tweetId || \n (memory.content?.source === \"twitter\" && \n memory.agentId === this.runtime.agentId &&\n memory.content?.inReplyTo === tweetId)\n );\n\n if (hasExistingReply) {\n logger.log(`Already replied to tweet ${tweet.id} (found existing reply), skipping`);\n continue;\n }\n logger.log(\"New Tweet found\", tweet.permanentUrl);\n\n const entityId = createUniqueUuid(\n this.runtime,\n tweet.userId === this.client.profile.id\n ? this.runtime.agentId\n : tweet.userId\n );\n\n // Create standardized world and room IDs\n const worldId = createUniqueUuid(this.runtime, tweet.userId);\n const roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: tweet.username,\n worldName: `${tweet.name}'s Twitter`,\n name: tweet.name,\n source: \"twitter\",\n type: ChannelType.GROUP,\n channelId: tweet.conversationId,\n serverId: tweet.userId,\n worldId: 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 // Create standardized message memory\n const memory: Memory = {\n id: tweetId,\n agentId: this.runtime.agentId,\n content: {\n text: tweet.text,\n url: tweet.permanentUrl,\n attachments:\n tweet.photos?.map((photo, index) => ({\n id: photo.id,\n url: photo.url,\n contentType: ContentType.IMAGE, // TODO: check if we can read this.\n })) || [],\n inReplyTo: tweet.inReplyToStatusId\n ? createUniqueUuid(this.runtime, tweet.inReplyToStatusId)\n : undefined,\n source: \"twitter\",\n channelType: ChannelType.GROUP,\n tweet,\n },\n entityId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n };\n await this.runtime.createMemory(memory, \"messages\");\n\n // Emit mention received events\n // TODO: Handle MENTION_RECEIVED event correctly before enabling again\n // if (tweet.text.includes(`@${twitterUsername}`)) {\n // const messagePayload: MessagePayload = {\n // runtime: this.runtime,\n // message: {\n // ...memory,\n // source: 'twitter',\n // } as TwitterMemory,\n // source: 'twitter',\n // callback: async (response) => {\n // logger.info('Received message response:', response);\n // return [];\n // },\n // };\n\n // // Emit platform-specific MENTION_RECEIVED event\n // const mentionPayload: TwitterMentionReceivedPayload = {\n // runtime: this.runtime,\n // message: {\n // ...memory,\n // source: 'twitter',\n // } as TwitterMemory,\n // tweet: convertToCoreTweet(tweet),\n // user: {\n // id: tweet.userId,\n // username: tweet.username,\n // name: tweet.name,\n // },\n // source: 'twitter',\n // callback: async (response) => {\n // logger.info('Received mention response:', response);\n // return [];\n // },\n // };\n\n // this.runtime.emitEvent(TwitterEventTypes.MENTION_RECEIVED, mentionPayload);\n // }\n\n // Handle thread events\n if (tweet.thread.length > 1) {\n const threadPayload = {\n runtime: this.runtime,\n tweets: convertToCoreTweets(tweet.thread),\n user: {\n id: tweet.userId,\n username: tweet.username,\n name: tweet.name,\n },\n source: \"twitter\",\n };\n\n if (tweet.thread[tweet.thread.length - 1].id === tweet.id) {\n // This is a new tweet in an existing thread\n this.runtime.emitEvent(TwitterEventTypes.THREAD_UPDATED, {\n ...threadPayload,\n newTweet: convertToCoreTweet(tweet),\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(\n this.runtime,\n interaction.targetTweet.userId\n ),\n roomId: createUniqueUuid(\n this.runtime,\n interaction.targetTweet.conversationId\n ),\n agentId: this.runtime.agentId,\n };\n\n // Create base event payload\n const basePayload = {\n runtime: this.runtime,\n user: {\n id: interaction.userId,\n username: interaction.username,\n name: interaction.name,\n },\n source: \"twitter\" as const,\n };\n\n // Emit platform-specific event\n switch (interaction.type) {\n case \"like\": {\n const likePayload: TwitterLikeReceivedPayload = {\n ...basePayload,\n tweet: interaction.targetTweet as unknown as CoreTweet,\n };\n // Emit platform-specific event\n this.runtime.emitEvent(TwitterEventTypes.LIKE_RECEIVED, likePayload);\n\n // Emit generic REACTION_RECEIVED event\n this.runtime.emitEvent(EventType.REACTION_RECEIVED, {\n ...basePayload,\n reaction: {\n type: \"like\",\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n },\n message: reactionMessage,\n callback: async () => {\n return [];\n },\n } as MessagePayload);\n break;\n }\n\n case \"retweet\": {\n const retweetPayload: TwitterRetweetReceivedPayload = {\n ...basePayload,\n tweet: interaction.targetTweet as unknown as CoreTweet,\n retweetId: interaction.retweetId,\n };\n // Emit platform-specific event\n this.runtime.emitEvent(\n TwitterEventTypes.RETWEET_RECEIVED,\n retweetPayload\n );\n\n // Emit generic REACTION_RECEIVED event\n this.runtime.emitEvent(EventType.REACTION_RECEIVED, {\n ...basePayload,\n reaction: {\n type: \"retweet\",\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n },\n message: reactionMessage,\n callback: async () => {\n return [];\n },\n } as MessagePayload);\n break;\n }\n\n case \"quote\": {\n const quotePayload: TwitterQuoteReceivedPayload = {\n ...basePayload,\n message: reactionMessage,\n quotedTweet: interaction.targetTweet as unknown as CoreTweet,\n quoteTweet: (interaction.quoteTweet ||\n interaction.targetTweet) as unknown as CoreTweet,\n callback: async () => [],\n reaction: {\n type: \"quote\",\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n },\n };\n // Emit platform-specific event\n this.runtime.emitEvent(\n TwitterEventTypes.QUOTE_RECEIVED,\n quotePayload\n );\n\n // Emit generic REACTION_RECEIVED event\n this.runtime.emitEvent(EventType.REACTION_RECEIVED, {\n ...basePayload,\n reaction: {\n type: \"quote\",\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n },\n message: reactionMessage,\n callback: async () => {\n return [];\n },\n } as MessagePayload);\n break;\n }\n }\n }\n }\n\n /**\n * Handles a tweet by processing its content, formatting it, generating image descriptions,\n * saving the tweet if it doesn't already exist, determining if a response should be sent,\n * composing a response prompt, generating a response based on the prompt, handling the response\n * tweet, and saving information about the response.\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.rest_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 // Save the response to memory\n await this.runtime.createMemory(responseMemory, \"messages\");\n\n return [responseMemory];\n } catch (error) {\n logger.error(\"Error replying to tweet:\", error);\n return [];\n }\n };\n\n // Emit standardized event for handling the message\n this.runtime.emitEvent(EventType.MESSAGE_RECEIVED, {\n runtime: this.runtime,\n message,\n callback,\n source: \"twitter\",\n } as MessagePayload);\n\n return { text: \"\", actions: [\"RESPOND\"] };\n }\n\n /**\n * Build a conversation thread based on a given tweet.\n *\n * @param {Tweet} tweet - The tweet to start the thread from.\n * @param {number} [maxReplies=10] - The maximum number of replies to include in the thread.\n * @returns {Promise<Tweet[]>} The conversation thread as an array of tweets.\n */\n async buildConversationThread(\n tweet: ClientTweet,\n maxReplies = 10\n ): Promise<ClientTweet[]> {\n const thread: ClientTweet[] = [];\n const visited: Set<string> = new Set();\n\n async function processThread(currentTweet: ClientTweet, depth = 0) {\n logger.log(\"Processing tweet:\", {\n id: currentTweet.id,\n inReplyToStatusId: currentTweet.inReplyToStatusId,\n depth: depth,\n });\n\n if (!currentTweet) {\n logger.log(\"No current tweet found for thread building\");\n return;\n }\n\n if (depth >= maxReplies) {\n logger.log(\"Reached maximum reply depth\", depth);\n return;\n }\n\n // Handle memory storage\n const memory = await this.runtime.getMemoryById(\n createUniqueUuid(this.runtime, currentTweet.id)\n );\n if (!memory) {\n const roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n const entityId = createUniqueUuid(this.runtime, currentTweet.userId);\n\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: currentTweet.username,\n name: currentTweet.name,\n source: \"twitter\",\n type: ChannelType.GROUP,\n worldId: createUniqueUuid(this.runtime, currentTweet.userId),\n worldName: `${currentTweet.name}'s Twitter`,\n });\n\n this.runtime.createMemory(\n {\n id: createUniqueUuid(this.runtime, currentTweet.id),\n agentId: this.runtime.agentId,\n content: {\n text: currentTweet.text,\n source: \"twitter\",\n url: currentTweet.permanentUrl,\n imageUrls: currentTweet.photos?.map((photo) => photo.url) || [],\n inReplyTo: currentTweet.inReplyToStatusId\n ? createUniqueUuid(this.runtime, currentTweet.inReplyToStatusId)\n : undefined,\n },\n createdAt: currentTweet.timestamp * 1000,\n roomId,\n entityId:\n currentTweet.userId === this.twitterUserId\n ? this.runtime.agentId\n : createUniqueUuid(this.runtime, currentTweet.userId),\n },\n \"messages\"\n );\n }\n\n if (visited.has(currentTweet.id)) {\n logger.log(\"Already visited tweet:\", currentTweet.id);\n return;\n }\n\n visited.add(currentTweet.id);\n thread.unshift(currentTweet);\n\n if (currentTweet.inReplyToStatusId) {\n logger.log(\"Fetching parent tweet:\", currentTweet.inReplyToStatusId);\n try {\n const parentTweet = await this.twitterClient.getTweet(\n currentTweet.inReplyToStatusId\n );\n\n if (parentTweet) {\n logger.log(\"Found parent tweet:\", {\n id: parentTweet.id,\n text: parentTweet.text?.slice(0, 50),\n });\n await processThread(parentTweet, depth + 1);\n } else {\n logger.log(\n \"No parent tweet found for:\",\n currentTweet.inReplyToStatusId\n );\n }\n } catch (error) {\n logger.log(\"Error fetching parent tweet:\", {\n tweetId: currentTweet.inReplyToStatusId,\n error,\n });\n }\n } else {\n logger.log(\"Reached end of reply chain at:\", currentTweet.id);\n }\n }\n\n // Need to bind this prompt for the inner function\n await processThread.bind(this)(tweet, 0);\n\n return thread;\n }\n\n private createMemoryObject(\n type: string,\n id: string,\n userId: string,\n roomId: 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, roomId),\n content: {\n type,\n source: \"twitter\",\n },\n createdAt: Date.now(),\n };\n }\n}\n","import { type IAgentRuntime, parseBooleanFromText } from \"@elizaos/core\";\nimport { ZodError, z } from \"zod\";\n\n/**\n * This schema defines all required/optional environment settings,\n * including new fields like TWITTER_SPACES_ENABLE.\n */\n/**\n * Schema definition for Twitter environment variables\n */\nexport const twitterEnvSchema = z.object({\n TWITTER_DRY_RUN: z.boolean(),\n TWITTER_USERNAME: z.string().min(1, \"X/Twitter username is required\"),\n TWITTER_PASSWORD: z.string().min(1, \"X/Twitter password is required\"),\n TWITTER_EMAIL: z.string().email(\"Valid X/Twitter email is required\"),\n TWITTER_2FA_SECRET: z.string().default(undefined),\n TWITTER_RETRY_LIMIT: z.number().int(),\n TWITTER_POLL_INTERVAL: z.number().int(),\n TWITTER_TARGET_USERS: z.string().default(\"\"),\n TWITTER_ENABLE_POST_GENERATION: z.boolean(),\n TWITTER_POST_INTERVAL_MIN: z.number().int(),\n TWITTER_POST_INTERVAL_MAX: z.number().int(),\n TWITTER_POST_IMMEDIATELY: z.boolean(),\n TWITTER_SPACES_ENABLE: z.boolean().default(false),\n});\n\nexport type TwitterConfig = z.infer<typeof twitterEnvSchema>;\n\n/**\n * Helper to parse a comma-separated list of Twitter usernames\n * (already present in your code).\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 based on TWITTER_TARGET_USERS\n * Supports wildcard \"*\" to target all users\n */\nexport function shouldTargetUser(\n username: string,\n targetUsersConfig: string\n): boolean {\n if (!targetUsersConfig?.trim()) {\n return true; // If no target users specified, interact with everyone\n }\n\n const targetUsers = parseTargetUsers(targetUsersConfig);\n\n // If wildcard is specified, target everyone\n if (targetUsers.includes(\"*\")) {\n return true;\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\nfunction safeParseInt(\n value: string | undefined | null,\n defaultValue: number\n): number {\n if (!value) return defaultValue;\n const parsed = Number.parseInt(value, 10);\n return Number.isNaN(parsed) ? defaultValue : Math.max(1, parsed);\n}\n\n/**\n * Validates or constructs a TwitterConfig object using zod,\n * taking values from the IAgentRuntime or process.env as needed.\n */\n// This also is organized to serve as a point of documentation for the client\n// most of the inputs from the framework (env/character)\n\n// we also do a lot of typing/prompt here\n// so we can do it once and only once per character\nexport async function validateTwitterConfig(\n runtime: IAgentRuntime,\n config: Partial<TwitterConfig> = {}\n): Promise<TwitterConfig> {\n try {\n const twitterConfig = {\n TWITTER_DRY_RUN:\n parseBooleanFromText(\n runtime.getSetting(\"TWITTER_DRY_RUN\") || process.env.TWITTER_DRY_RUN\n ) ?? false,\n\n TWITTER_USERNAME:\n runtime.getSetting(\"TWITTER_USERNAME\") || process.env.TWITTER_USERNAME,\n\n TWITTER_PASSWORD:\n runtime.getSetting(\"TWITTER_PASSWORD\") || process.env.TWITTER_PASSWORD,\n\n TWITTER_EMAIL:\n runtime.getSetting(\"TWITTER_EMAIL\") || process.env.TWITTER_EMAIL,\n\n TWITTER_2FA_SECRET:\n runtime.getSetting(\"TWITTER_2FA_SECRET\") ||\n process.env.TWITTER_2FA_SECRET ||\n \"\",\n\n // int\n TWITTER_RETRY_LIMIT: safeParseInt(\n runtime.getSetting(\"TWITTER_RETRY_LIMIT\") ||\n process.env.TWITTER_RETRY_LIMIT,\n 5\n ),\n\n // int in seconds\n TWITTER_POLL_INTERVAL: safeParseInt(\n runtime.getSetting(\"TWITTER_POLL_INTERVAL\") ||\n process.env.TWITTER_POLL_INTERVAL,\n 120 // 2m\n ),\n\n // string - comma-separated list of target users\n TWITTER_TARGET_USERS:\n runtime.getSetting(\"TWITTER_TARGET_USERS\") ||\n process.env.TWITTER_TARGET_USERS ||\n \"\",\n\n // bool\n TWITTER_ENABLE_POST_GENERATION:\n parseBooleanFromText(\n runtime.getSetting(\"TWITTER_ENABLE_POST_GENERATION\") ||\n process.env.TWITTER_ENABLE_POST_GENERATION\n ) ?? true,\n\n // int in minutes\n TWITTER_POST_INTERVAL_MIN: safeParseInt(\n runtime.getSetting(\"TWITTER_POST_INTERVAL_MIN\") ||\n process.env.TWITTER_POST_INTERVAL_MIN,\n 90 // 1.5 hours\n ),\n\n // int in minutes\n TWITTER_POST_INTERVAL_MAX: safeParseInt(\n runtime.getSetting(\"TWITTER_POST_INTERVAL_MAX\") ||\n process.env.TWITTER_POST_INTERVAL_MAX,\n 180 // 3 hours\n ),\n\n // bool\n TWITTER_POST_IMMEDIATELY:\n parseBooleanFromText(\n runtime.getSetting(\"TWITTER_POST_IMMEDIATELY\") ||\n process.env.TWITTER_POST_IMMEDIATELY\n ) ?? false,\n\n TWITTER_SPACES_ENABLE:\n parseBooleanFromText(\n runtime.getSetting(\"TWITTER_SPACES_ENABLE\") ||\n process.env.TWITTER_SPACES_ENABLE\n ) ?? false,\n ...config,\n };\n\n return twitterEnvSchema.parse(twitterConfig);\n } catch (error) {\n if (error instanceof ZodError) {\n const errorMessages = error.errors\n .map((err) => `${err.path.join(\".\")}: ${err.message}`)\n .join(\"\\n\");\n throw new Error(\n `X/Twitter configuration validation failed:\\n${errorMessages}`\n );\n }\n throw error;\n }\n}\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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.){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 {\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\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 this.twitterUsername =\n state?.TWITTER_USERNAME ||\n (this.runtime.getSetting(\"TWITTER_USERNAME\") as string);\n this.isDryRun =\n this.state?.TWITTER_DRY_RUN ||\n (this.runtime.getSetting(\"TWITTER_DRY_RUN\") as unknown as boolean);\n\n // Log configuration on initialization\n logger.log(\"Twitter Client Configuration:\");\n logger.log(`- Username: ${this.twitterUsername}`);\n logger.log(`- Dry Run Mode: ${this.isDryRun ? \"Enabled\" : \"Disabled\"}`);\n\n logger.log(\n `- Post Interval: ${this.state?.TWITTER_POST_INTERVAL_MIN || this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MIN\") || 90}-${this.state?.TWITTER_POST_INTERVAL_MAX || this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MAX\") || 180} minutes`\n );\n logger.log(\n `- Post Immediately: ${\n this.state?.TWITTER_POST_IMMEDIATELY ||\n this.runtime.getSetting(\"TWITTER_POST_IMMEDIATELY\")\n ? \"enabled\"\n : \"disabled\"\n }`\n );\n\n if (this.isDryRun) {\n logger.log(\n \"Twitter client initialized in dry run mode - no actual tweets should be posted\"\n );\n }\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\n const generateNewTweetLoop = async () => {\n const minPostMinutes =\n this.state?.TWITTER_POST_INTERVAL_MIN ||\n this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MIN\") ||\n 90;\n const maxPostMinutes =\n this.state?.TWITTER_POST_INTERVAL_MAX ||\n this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MAX\") ||\n 180;\n const randomMinutes =\n Math.floor(Math.random() * (maxPostMinutes - minPostMinutes + 1)) +\n minPostMinutes;\n const interval = randomMinutes * 60 * 1000;\n\n await this.generateNewTweet();\n setTimeout(generateNewTweetLoop, interval);\n };\n\n // Start the loop after a 1 minute delay to allow other services to initialize\n setTimeout(generateNewTweetLoop, 60 * 1000);\n if (\n this.state?.TWITTER_POST_IMMEDIATELY ||\n this.runtime.getSetting(\"TWITTER_POST_IMMEDIATELY\")\n ) {\n // await 1 second\n await new Promise((resolve) => setTimeout(resolve, 1000));\n await this.generateNewTweet();\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 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 // 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 // Create a callback for handling the actual posting\n const callback: HandlerCallback = async (content: Content) => {\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 // 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 =\n (result as any).rest_id ||\n (result as any).id_str ||\n (result as any).legacy?.id_str;\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 posting tweet:\", error, content);\n return [];\n }\n };\n\n // Emit event to handle the post generation using standard handlers\n this.runtime.emitEvent(\n [EventType.POST_GENERATED, TwitterEventTypes.POST_GENERATED],\n {\n runtime: this.runtime,\n callback,\n worldId,\n userId,\n roomId,\n source: \"twitter\",\n }\n );\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 if (!result) {\n logger.error(\"Error sending tweet; Bad response:\");\n return null;\n }\n\n return result;\n } catch (error) {\n logger.error(\"Error posting to Twitter:\", error);\n throw error;\n }\n }\n\n async stop() {\n // Implement stop functionality if needed\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\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 this.timelineType =\n this.state?.TWITTER_TIMELINE_MODE ||\n this.runtime.getSetting(\"TWITTER_TIMELINE_MODE\");\n }\n\n async start() {\n const handleTwitterTimelineLoop = () => {\n // Defaults to 2 minutes\n const interactionInterval =\n (this.state?.TWITTER_TIMELINE_POLL_INTERVAL ||\n (this.runtime.getSetting(\n \"TWITTER_TIMELINE_POLL_INTERVAL\"\n ) as unknown as number) ||\n 120) * 1000;\n\n this.handleTimeline();\n setTimeout(handleTwitterTimelineLoop, interactionInterval);\n };\n handleTwitterTimelineLoop();\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 return homeTimeline\n .map((tweet) => ({\n id: tweet.rest_id,\n name: tweet.core?.user_results?.result?.legacy?.name,\n username: tweet.core?.user_results?.result?.legacy?.screen_name,\n text: tweet.legacy?.full_text,\n inReplyToStatusId: tweet.legacy?.in_reply_to_status_id_str,\n timestamp: new Date(tweet.legacy?.created_at).getTime() / 1000,\n userId: tweet.legacy?.user_id_str,\n conversationId: tweet.legacy?.conversation_id_str,\n permanentUrl: `https://twitter.com/${tweet.core?.user_results?.result?.legacy?.screen_name}/status/${tweet.rest_id}`,\n hashtags: tweet.legacy?.entities?.hashtags || [],\n mentions: tweet.legacy?.entities?.user_mentions || [],\n photos:\n tweet.legacy?.entities?.media\n ?.filter((media) => media.type === \"photo\")\n .map((media) => ({\n id: media.id_str,\n url: media.media_url_https, // Store media_url_https as url\n alt_text: media.alt_text,\n })) || [],\n thread: tweet.thread || [],\n urls: tweet.legacy?.entities?.urls || [],\n videos:\n tweet.legacy?.entities?.media?.filter(\n (media) => media.type === \"video\"\n ) || [],\n }))\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 console.log(\"Start Hanldeling Twitter Timeline\");\n\n const tweets = await this.getTimeline(20);\n const maxActionsPerCycle = 20;\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 console.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\n if (!actionResponse) {\n logger.log(`No valid actions generated for tweet ${tweet.id}`);\n continue;\n }\n\n const { actions } = parseActionResponseFromText(actionResponse.trim());\n\n tweetDecisions.push({\n tweet: tweet,\n actionResponse: actions,\n tweetState: state,\n roomId: roomId,\n });\n } catch (error) {\n logger.error(`Error processing tweet ${tweet.id}:`, error);\n continue;\n }\n }\n const rankByActionRelevance = (arr) => {\n return arr.sort((a, b) => {\n // Count the number of true values in the actionResponse object\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 this.processTimelineActions(prioritizedTweets);\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 for (const decision of tweetDecisions) {\n const { actionResponse, tweetState, roomId, tweet } = decision;\n const entityId = createUniqueUuid(this.runtime, tweet.userId);\n const worldId = createUniqueUuid(this.runtime, tweet.userId);\n\n await this.ensureTweetWorldContext(tweet, roomId, worldId, entityId);\n\n try {\n const message = this.formMessage(this.runtime, tweet);\n\n await Promise.all([\n this.runtime.addEmbeddingToMemory(message),\n this.runtime.createMemory(message, \"messages\"),\n ]);\n\n // Execute actions\n if (actionResponse.like) {\n this.handleLikeAction(tweet);\n }\n\n if (actionResponse.retweet) {\n this.handleRetweetAction(tweet);\n }\n\n if (actionResponse.quote) {\n this.handleQuoteAction(tweet);\n }\n\n if (actionResponse.reply) {\n this.handleReplyAction(tweet);\n }\n } catch (error) {\n logger.error(`Error processing tweet ${tweet.id}:`, error);\n continue;\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.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 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 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 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 = await result.json();\n\n if (body?.data?.create_tweet?.tweet_results?.result) {\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 responseId = createUniqueUuid(this.runtime, body.rest_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 } 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 responding 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 const tweetResult = await sendTweet(\n this.client,\n responseObject.post,\n [],\n tweet.id\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.rest_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 } catch (error) {\n logger.error(\"Error in quote 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","// packages/plugin-twitter/src/tests/ClientBaseTestSuite.ts\n\nimport type { IAgentRuntime, TestSuite } from \"@elizaos/core\";\nimport { ClientBase } from \"./base\";\nimport type { TwitterConfig } from \"./environment\";\nimport { logger } from \"@elizaos/core\";\n\nexport class ClientBaseTestSuite implements TestSuite {\n name = \"twitter-client-base\";\n\n private mockRuntime: IAgentRuntime;\n private mockConfig: TwitterConfig;\n\n constructor() {\n this.mockRuntime = {\n env: {\n TWITTER_USERNAME: \"testuser\",\n TWITTER_DRY_RUN: \"true\",\n TWITTER_POST_INTERVAL_MIN: \"90\",\n TWITTER_POST_INTERVAL_MAX: \"180\",\n TWITTER_ENABLE_ACTION_PROCESSING: \"true\",\n TWITTER_POST_IMMEDIATELY: \"false\",\n },\n getEnv: (key: string) => this.mockRuntime.env[key] || null,\n getSetting: (key: string) => this.mockRuntime.env[key] || null,\n character: {\n style: {\n all: [\"Test style 1\", \"Test style 2\"],\n post: [\"Post style 1\", \"Post style 2\"],\n },\n },\n } as unknown as IAgentRuntime;\n\n this.mockConfig = {\n TWITTER_USERNAME: \"testuser\",\n TWITTER_DRY_RUN: true,\n TWITTER_SPACES_ENABLE: false,\n TWITTER_TARGET_USERS: [],\n TWITTER_PASSWORD: \"hashedpassword\",\n TWITTER_EMAIL: \"test@example.com\",\n TWITTER_2FA_SECRET: \"\",\n TWITTER_RETRY_LIMIT: 5,\n TWITTER_POLL_INTERVAL: 120,\n TWITTER_ENABLE_POST_GENERATION: true,\n TWITTER_POST_INTERVAL_MIN: 90,\n TWITTER_POST_INTERVAL_MAX: 180,\n TWITTER_POST_IMMEDIATELY: false,\n };\n }\n\n tests = [\n {\n name: \"Create instance with correct configuration\",\n fn: this.testInstanceCreation.bind(this),\n },\n {\n name: \"Initialize with correct post intervals\",\n fn: this.testPostIntervals.bind(this),\n },\n ];\n\n async testInstanceCreation() {\n const client = new ClientBase(this.mockRuntime, this.mockConfig);\n if (!client) throw new Error(\"ClientBase instance creation failed.\");\n\n if (this.mockRuntime.getSetting(\"TWITTER_USERNAME\") !== \"testuser\") {\n throw new Error(\"TWITTER_USERNAME setting mismatch.\");\n }\n\n if (client.state.TWITTER_USERNAME !== \"testuser\") {\n throw new Error(\"Client state TWITTER_USERNAME mismatch.\");\n }\n\n if (this.mockRuntime.getSetting(\"TWITTER_DRY_RUN\") !== \"true\") {\n throw new Error(\"TWITTER_DRY_RUN setting mismatch.\");\n }\n\n if (client.state.TWITTER_DRY_RUN !== true) {\n throw new Error(\"Client state TWITTER_DRY_RUN mismatch.\");\n }\n\n logger.success(\"ClientBase instance created with correct configuration.\");\n }\n\n async testPostIntervals() {\n const client = new ClientBase(this.mockRuntime, this.mockConfig);\n\n if (this.mockRuntime.getSetting(\"TWITTER_POST_INTERVAL_MIN\") !== \"90\") {\n throw new Error(\"TWITTER_POST_INTERVAL_MIN setting mismatch.\");\n }\n\n if (client.state.TWITTER_POST_INTERVAL_MIN !== 90) {\n throw new Error(\"Client state TWITTER_POST_INTERVAL_MIN mismatch.\");\n }\n\n if (this.mockRuntime.getSetting(\"TWITTER_POST_INTERVAL_MAX\") !== \"180\") {\n throw new Error(\"TWITTER_POST_INTERVAL_MAX setting mismatch.\");\n }\n\n if (client.state.TWITTER_POST_INTERVAL_MAX !== 180) {\n throw new Error(\"Client state TWITTER_POST_INTERVAL_MAX mismatch.\");\n }\n\n logger.success(\"ClientBase initialized with correct post intervals.\");\n }\n}\n"],"mappings":";;;;;AAAA;AAAA,EACE,eAAAA;AAAA,EAEA,aAAAC;AAAA,EAGA;AAAA,EAEA;AAAA,EAGA,oBAAAC;AAAA,EACA,UAAAC;AAAA,OACK;;;ACbP;AAAA,EAOE,UAAAC;AAAA,OACK;;;ACRP;AAAA,EAEE,aAAAC;AAAA,EACA,oBAAAC;AAAA,EACA,UAAAC;AAAA,OACK;;;ACLP,SAAS,WAAAC,gBAAe;;;ACIjB,IAAM,WAAN,MAAM,kBAAiB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ1B,YACG,UACA,MACT,SACA;AACA,UAAM,OAAO;AAJJ;AACA;AAAA,EAIX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,aAAa,aAAa,UAAoB;AAE5C,QAAI,OAAoC;AACxC,QAAI;AACF,aAAO,MAAM,SAAS,KAAK;AAAA,IAC7B,QAAQ;AACN,UAAI;AACF,eAAO,MAAM,SAAS,KAAK;AAAA,MAC7B,QAAQ;AAAA,MAAC;AAAA,IACX;AAEA,WAAO,IAAI,UAAS,UAAU,MAAM,oBAAoB,SAAS,MAAM,EAAE;AAAA,EAC3E;AACF;;;ACrBO,IAAM,kBAAkB,IAAK,MAAoC;AAAA,EACtE,mBAAkC;AAChC,WAAO,QAAQ,QAAQ;AAAA,EACzB;AACF,EAAG;;;AClBH,IAAM,gBAAyB,OAAO,YAAY;AAK3C,IAAM,WAAN,MAAM,UAAuC;AAAA;AAAA;AAAA;AAAA,EA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niqueUuid","logger","Headers","Headers","Headers","Headers","Headers","bearerToken","Headers","Headers","CookieJar","CookieJar","Headers","Headers","stringify","features","stringify","Headers","stringify","features","stringify","features","features","features","stringify","features","endpoints","user","place","data","mediaData","mediaType","features","features","EventEmitter","Headers","Headers","logger","EventEmitter","wrtc","EventEmitter","wrtc","EventEmitter","EventEmitter","EventEmitter","EventEmitter","fs","spawn","spawn","spawn","logger","SttTtsPlugin","fs","path","ModelType","createUniqueUuid","logger","logger","ModelType","logger","SttTtsPlugin","logger","createUniqueUuid","ModelType","logger","tweet","spaceJoined","ChannelType","createUniqueUuid","logger","authToken","ct0","guestId","logger","existingMemories","createUniqueUuid","existingMemoryIds","tweetsToSave","ChannelType","profile","ChannelType","EventType","createUniqueUuid","logger","util","objectUtil","path","errorUtil","path","errorMap","ctx","result","issues","elements","processed","result","r","ZodFirstPartyTypeKind","logger","createUniqueUuid","memory","ChannelType","EventType","ChannelType","EventType","createUniqueUuid","logger","logger","createUniqueUuid","ChannelType","EventType","ChannelType","createUniqueUuid","ModelType","logger","createUniqueUuid","ChannelType","ModelType","logger","logger","logger","createUniqueUuid","ChannelType","EventType"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/base.ts","../src/client/api.ts","../src/client/errors.ts","../src/client/auth.ts","../src/client/profile.ts","../src/client/relationships.ts","../src/client/timeline-async.ts","../src/client/timeline-relationship.ts","../src/client/search.ts","../src/client/timeline-following.ts","../src/client/timeline-home.ts","../src/client/type-util.ts","../src/client/timeline-tweet-util.ts","../src/client/timeline-v2.ts","../src/client/tweets.ts","../src/client/client.ts","../src/constants.ts","../src/interactions.ts","../src/utils.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/tests.ts"],"sourcesContent":["import {\n ChannelType,\n type Entity,\n EventType,\n type IAgentRuntime,\n type Plugin,\n Role,\n type Room,\n Service,\n type UUID,\n type World,\n createUniqueUuid,\n logger,\n} from \"@elizaos/core\";\nimport { ClientBase } from \"./base\";\nimport { TWITTER_SERVICE_NAME } from \"./constants\";\nimport type { TwitterConfig } from \"./environment\";\nimport { TwitterInteractionClient } from \"./interactions\";\nimport { TwitterPostClient } from \"./post\";\nimport { TwitterTimelineClient } from \"./timeline\";\nimport { ClientBaseTestSuite } from \"./tests\";\nimport { type ITwitterClient, TwitterEventTypes } from \"./types\";\n\nconsole.log(`Twitter plugin loaded with service name: ${TWITTER_SERVICE_NAME}`);\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 * - search: searching tweets / replying logic\n * - interaction: handling mentions, replies\n * - space: launching and managing Twitter Spaces (optional)\n */\n/**\n * TwitterClientInstance class that implements ITwitterClient interface.\n *\n * @class\n * @implements {ITwitterClient}\n */\n\nexport class TwitterClientInstance implements ITwitterClient {\n client: ClientBase;\n post: TwitterPostClient;\n interaction: TwitterInteractionClient;\n timeline?: TwitterTimelineClient;\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 - use TWITTER_POST_ENABLE instead\n if (runtime.getSetting(\"TWITTER_POST_ENABLE\") === \"true\") {\n this.post = new TwitterPostClient(this.client, runtime, state);\n }\n\n // Mentions and interactions - check for TWITTER_SEARCH_ENABLE\n if (runtime.getSetting(\"TWITTER_SEARCH_ENABLE\") !== \"false\") {\n this.interaction = new TwitterInteractionClient(\n this.client,\n runtime,\n state,\n );\n }\n\n // handle timeline - check if TWITTER_ENABLE_ACTION_PROCESSING is enabled\n if (runtime.getSetting(\"TWITTER_ENABLE_ACTION_PROCESSING\") === \"true\") {\n this.timeline = new TwitterTimelineClient(this.client, runtime, state);\n }\n\n this.service = TwitterService.getInstance();\n }\n}\n\nexport class TwitterService extends Service {\n static serviceType: string = TWITTER_SERVICE_NAME;\n capabilityDescription =\n \"The agent is able to send and receive messages on twitter\";\n private static instance: TwitterService;\n private clients: Map<string, TwitterClientInstance> = new Map();\n\n static getInstance(): TwitterService {\n if (!TwitterService.instance) {\n TwitterService.instance = new TwitterService();\n }\n return TwitterService.instance;\n }\n\n async createClient(\n runtime: IAgentRuntime,\n clientId: string,\n state: any,\n ): Promise<TwitterClientInstance> {\n try {\n // Check if client already exists\n const existingClient = this.getClient(clientId, runtime.agentId);\n if (existingClient) {\n logger.info(`Twitter client already exists for ${clientId}`);\n return existingClient;\n }\n\n // Create new client instance\n const client = new TwitterClientInstance(runtime, state);\n\n // Initialize the client\n await client.client.init();\n\n if (client.post) {\n client.post.start();\n }\n\n if (client.interaction) {\n client.interaction.start();\n }\n\n if (client.timeline) {\n client.timeline.start();\n }\n\n // Store the client instance\n this.clients.set(this.getClientKey(clientId, runtime.agentId), client);\n\n // Emit standardized WORLD_JOINED event once we have client profile\n await this.emitServerJoinedEvent(runtime, client);\n\n logger.info(`Created Twitter client for ${clientId}`);\n return client;\n } catch (error) {\n logger.error(`Failed to create Twitter client for ${clientId}:`, error);\n throw error;\n }\n }\n\n /**\n * Emits a standardized WORLD_JOINED event for Twitter\n * @param runtime The agent runtime\n * @param client The Twitter client instance\n */\n private async emitServerJoinedEvent(\n runtime: IAgentRuntime,\n client: TwitterClientInstance,\n ): Promise<void> {\n try {\n if (!client.client.profile) {\n logger.warn(\n \"Twitter profile not available yet, can't emit WORLD_JOINED event\",\n );\n return;\n }\n\n const profile = client.client.profile;\n const twitterId = profile.id;\n const username = profile.username;\n\n // Create the world ID based on the twitter user ID\n const worldId = createUniqueUuid(runtime, twitterId) as UUID;\n\n // For Twitter, we create a single world representing the user's Twitter account\n const world: World = {\n id: worldId,\n name: `${username}'s Twitter`,\n agentId: runtime.agentId,\n serverId: twitterId,\n metadata: {\n ownership: { ownerId: twitterId },\n roles: {\n [twitterId]: Role.OWNER,\n },\n twitter: {\n username: username,\n id: twitterId,\n },\n },\n };\n\n // We'll create a \"home timeline\" room\n const homeTimelineRoomId = createUniqueUuid(\n runtime,\n `${twitterId}-home`,\n ) as UUID;\n const homeTimelineRoom: Room = {\n id: homeTimelineRoomId,\n name: `${username}'s Timeline`,\n source: \"twitter\",\n type: ChannelType.FEED,\n channelId: `${twitterId}-home`,\n serverId: twitterId,\n worldId: worldId,\n };\n\n // Create a \"mentions\" room\n const mentionsRoomId = createUniqueUuid(\n runtime,\n `${twitterId}-mentions`,\n ) as UUID;\n const mentionsRoom: Room = {\n id: mentionsRoomId,\n name: `${username}'s Mentions`,\n source: \"twitter\",\n type: ChannelType.GROUP,\n channelId: `${twitterId}-mentions`,\n serverId: twitterId,\n worldId: worldId,\n };\n\n // Create an entity for the Twitter user\n const twitterUserId = createUniqueUuid(runtime, twitterId) as UUID;\n const twitterUser: Entity = {\n id: twitterUserId,\n names: [profile.screenName || username],\n agentId: runtime.agentId,\n metadata: {\n twitter: {\n id: twitterId,\n username: username,\n screenName: profile.screenName || username,\n name: profile.screenName || username,\n },\n },\n };\n\n // Emit the WORLD_JOINED event\n runtime.emitEvent(\n [TwitterEventTypes.WORLD_JOINED, EventType.WORLD_JOINED],\n {\n runtime: runtime,\n world: world,\n rooms: [homeTimelineRoom, mentionsRoom],\n entities: [twitterUser],\n source: \"twitter\",\n },\n );\n\n logger.info(`Emitted WORLD_JOINED event for Twitter account ${username}`);\n } catch (error) {\n logger.error(\"Failed to emit WORLD_JOINED event for Twitter:\", error);\n }\n }\n\n getClient(\n clientId: string,\n agentId: UUID,\n ): TwitterClientInstance | undefined {\n return this.clients.get(this.getClientKey(clientId, agentId));\n }\n\n async stopClient(clientId: string, agentId: UUID): Promise<void> {\n const key = this.getClientKey(clientId, agentId);\n const client = this.clients.get(key);\n if (client) {\n try {\n await client.service.stop();\n this.clients.delete(key);\n logger.info(`Stopped Twitter client for ${clientId}`);\n } catch (error) {\n logger.error(`Error stopping Twitter client for ${clientId}:`, error);\n }\n }\n }\n\n static async start(runtime: IAgentRuntime) {\n const twitterClientManager = TwitterService.getInstance();\n\n // Check for character-level Twitter credentials\n const twitterConfig: Partial<TwitterConfig> = {\n TWITTER_API_KEY:\n String(runtime.getSetting(\"TWITTER_API_KEY\") || \"\") ||\n String(runtime.character.settings?.TWITTER_API_KEY || \"\") ||\n String(runtime.character.secrets?.TWITTER_API_KEY || \"\"),\n TWITTER_API_SECRET_KEY:\n String(runtime.getSetting(\"TWITTER_API_SECRET_KEY\") || \"\") ||\n String(runtime.character.settings?.TWITTER_API_SECRET_KEY || \"\") ||\n String(runtime.character.secrets?.TWITTER_API_SECRET_KEY || \"\"),\n TWITTER_ACCESS_TOKEN:\n String(runtime.getSetting(\"TWITTER_ACCESS_TOKEN\") || \"\") ||\n String(runtime.character.settings?.TWITTER_ACCESS_TOKEN || \"\") ||\n String(runtime.character.secrets?.TWITTER_ACCESS_TOKEN || \"\"),\n TWITTER_ACCESS_TOKEN_SECRET:\n String(runtime.getSetting(\"TWITTER_ACCESS_TOKEN_SECRET\") || \"\") ||\n String(runtime.character.settings?.TWITTER_ACCESS_TOKEN_SECRET || \"\") ||\n String(runtime.character.secrets?.TWITTER_ACCESS_TOKEN_SECRET || \"\"),\n };\n\n // Filter out undefined values\n const config = Object.fromEntries(\n Object.entries(twitterConfig).filter(([_, v]) => v !== undefined && v !== \"\"),\n ) as TwitterConfig;\n\n // If we have enough settings to create a client, do so\n try {\n if (\n config.TWITTER_API_KEY &&\n config.TWITTER_API_SECRET_KEY &&\n config.TWITTER_ACCESS_TOKEN &&\n config.TWITTER_ACCESS_TOKEN_SECRET\n ) {\n logger.info(\"Creating default Twitter client from character settings\");\n await twitterClientManager.createClient(\n runtime,\n runtime.agentId,\n config,\n );\n }\n } catch (error) {\n logger.error(\"Failed to create default Twitter client:\", error);\n throw error;\n }\n\n return twitterClientManager;\n }\n\n async stop(): Promise<void> {\n await this.stopAllClients();\n }\n\n async stopAllClients(): Promise<void> {\n for (const [key, client] of this.clients.entries()) {\n try {\n await client.service.stop();\n this.clients.delete(key);\n } catch (error) {\n logger.error(`Error stopping Twitter client ${key}:`, error);\n }\n }\n }\n\n private getClientKey(clientId: string, agentId: UUID): string {\n return `${clientId}-${agentId}`;\n }\n}\n\nconst twitterPlugin: Plugin = {\n name: TWITTER_SERVICE_NAME,\n description: \"Twitter client with per-server instance management\",\n services: [TwitterService],\n actions: [],\n tests: [new ClientBaseTestSuite()],\n};\n\nexport default twitterPlugin;\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\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 } catch (error) {\n console.error(\"Error processing request:\", error);\n this.queue.unshift(request);\n await this.exponentialBackoff(this.queue.length);\n }\n await this.randomDelay();\n }\n\n this.processing = false;\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 console.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 parseTweet(raw: any, depth = 0, maxDepth = 3): Tweet {\n // If we've reached maxDepth, don't parse nested quotes/retweets further\n const canRecurse = depth < maxDepth;\n\n const quotedStatus =\n raw.quoted_status_result?.result && canRecurse\n ? this.parseTweet(raw.quoted_status_result.result, depth + 1, maxDepth)\n : undefined;\n\n const retweetedStatus =\n raw.retweeted_status_result?.result && canRecurse\n ? this.parseTweet(\n raw.retweeted_status_result.result,\n depth + 1,\n maxDepth,\n )\n : undefined;\n\n const t: Tweet = {\n bookmarkCount:\n raw.bookmarkCount ?? raw.legacy?.bookmark_count ?? undefined,\n conversationId: raw.conversationId ?? raw.legacy?.conversation_id_str,\n hashtags: raw.hashtags ?? raw.legacy?.entities?.hashtags ?? [],\n html: raw.html,\n id: raw.id ?? raw.rest_id ?? raw.legacy.id_str ?? raw.id_str ?? undefined,\n inReplyToStatus: raw.inReplyToStatus,\n inReplyToStatusId:\n raw.inReplyToStatusId ??\n raw.legacy?.in_reply_to_status_id_str ??\n undefined,\n isQuoted: raw.legacy?.is_quote_status === true,\n isPin: raw.isPin,\n isReply: raw.isReply,\n isRetweet: raw.legacy?.retweeted === true,\n isSelfThread: raw.isSelfThread,\n language: raw.legacy?.lang,\n likes: raw.legacy?.favorite_count ?? 0,\n name:\n raw.name ??\n raw?.user_results?.result?.legacy?.name ??\n raw.core?.user_results?.result?.legacy?.name,\n mentions: raw.mentions ?? raw.legacy?.entities?.user_mentions ?? [],\n permanentUrl:\n raw.permanentUrl ??\n (raw.core?.user_results?.result?.legacy?.screen_name && raw.rest_id\n ? `https://x.com/${raw.core?.user_results?.result?.legacy?.screen_name}/status/${raw.rest_id}`\n : undefined),\n photos:\n raw.photos ??\n (raw.legacy?.entities?.media\n ?.filter((media: any) => media.type === \"photo\")\n .map((media: any) => ({\n id: media.id_str || media.rest_id || media.legacy.id_str,\n url: media.media_url_https,\n alt_text: media.alt_text,\n })) ||\n []),\n place: raw.place,\n poll: raw.poll ?? null,\n quotedStatus,\n quotedStatusId:\n raw.quotedStatusId ?? raw.legacy?.quoted_status_id_str ?? undefined,\n quotes: raw.legacy?.quote_count ?? 0,\n replies: raw.legacy?.reply_count ?? 0,\n retweets: raw.legacy?.retweet_count ?? 0,\n retweetedStatus,\n retweetedStatusId: raw.legacy?.retweeted_status_id_str ?? undefined,\n text: raw.text ?? raw.legacy?.full_text ?? undefined,\n thread: raw.thread || [],\n timeParsed: raw.timeParsed\n ? new Date(raw.timeParsed)\n : raw.legacy?.created_at\n ? new Date(raw.legacy?.created_at)\n : undefined,\n timestamp:\n raw.timestamp ??\n (raw.legacy?.created_at\n ? new Date(raw.legacy.created_at).getTime() / 1000\n : undefined),\n urls: raw.urls ?? raw.legacy?.entities?.urls ?? [],\n userId: raw.userId ?? raw.legacy?.user_id_str ?? undefined,\n username:\n raw.username ??\n raw.core?.user_results?.result?.legacy?.screen_name ??\n undefined,\n videos:\n raw.videos ??\n raw.legacy?.entities?.media?.filter(\n (media: any) => media.type === \"video\",\n ) ??\n [],\n views: raw.views?.count ? Number(raw.views.count) : 0,\n sensitiveContent: raw.sensitiveContent,\n };\n\n return t;\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 // Use parseTweet on each tweet\n return homeTimeline.tweets.map((t) => this.parseTweet(t));\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 const processedTimeline = homeTimeline\n .filter((t) => t.__typename !== \"TweetWithVisibilityResults\") // what's this about?\n .map((tweet) => this.parseTweet(tweet));\n\n //logger.debug(\"process homeTimeline\", processedTimeline);\n return processedTimeline;\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 console.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 { Headers } from \"headers-polyfill\";\nimport type { TwitterAuth } from \"./auth\";\nimport { ApiError } from \"./errors\";\n\n// For some reason using Parameters<typeof fetch> reduces the request transform function to\n// `(url: string) => string` in tests.\n/**\n * Represents an array type for parameters used in the fetch function,\n * with the first element being input of type RequestInfo or URL,\n * and the second element being init of type RequestInit or optional if not provided.\n */\ntype FetchParameters = [input: RequestInfo | URL, init?: RequestInit];\n\n/**\n * @typedef {Object} FetchTransformOptions\n * @property {Function} request Transforms the request options before a request is made. This executes after all of the default\n * parameters have been configured, and is stateless. It is safe to return new request options\n * objects.\n * @param {FetchParameters} args The request options.\n * @returns {FetchParameters|Promise<FetchParameters>} The transformed request options.\n *\n * @property {Function} response Transforms the response after a request completes. This executes immediately after the request\n * completes, and is stateless. It is safe to return a new response object.\n * @param {Response} response The response object.\n * @returns {Response|Promise<Response>} The transformed response object.\n */\n\nexport interface FetchTransformOptions {\n /**\n * Transforms the request options before a request is made. This executes after all of the default\n * parameters have been configured, and is stateless. It is safe to return new request options\n * objects.\n * @param args The request options.\n * @returns The transformed request options.\n */\n request: (\n ...args: FetchParameters\n ) => FetchParameters | Promise<FetchParameters>;\n\n /**\n * Transforms the response after a request completes. This executes immediately after the request\n * completes, and is stateless. It is safe to return a new response object.\n * @param response The response object.\n * @returns The transformed response object.\n */\n response: (response: Response) => Response | Promise<Response>;\n}\n\nexport const bearerToken =\n \"AAAAAAAAAAAAAAAAAAAAAFQODgEAAAAAVHTp76lzh3rFzcHbmHVvQxYYpTw%3DckAlMINMjmCwxUcaXbAN4XqJVdgMJaHqNOFgPMK0zN1qLqLQCF\";\n\n/**\n * An API result container.\n */\nexport type RequestApiResult<T> =\n | { success: true; value: T }\n | { success: false; err: Error };\n\n/**\n * Used internally to send HTTP requests to the Twitter API.\n * @internal\n * @param url - The URL to send the request to.\n * @param auth - The instance of {@link TwitterAuth} that will be used to authorize this request.\n * @param method - The HTTP method used when sending this request.\n */\nexport async function requestApi<T>(\n url: string,\n auth: TwitterAuth,\n method: \"GET\" | \"POST\" = \"GET\",\n body?: any,\n): Promise<RequestApiResult<T>> {\n const headers = new Headers({\n \"Content-Type\": \"application/json\",\n });\n\n let res: Response;\n do {\n try {\n // Use global fetch instead of auth.fetch since TwitterAuth v2 doesn't have it\n res = await fetch(url, {\n method,\n headers: headers as any,\n credentials: \"include\",\n ...(body && { body: JSON.stringify(body) }),\n });\n } catch (err) {\n if (!(err instanceof Error)) {\n throw err;\n }\n return {\n success: false,\n err: new Error(\"Failed to perform request.\"),\n };\n }\n\n if (res.status === 429) {\n /*\n Known headers at this point:\n - x-rate-limit-limit: Maximum number of requests per time period?\n - x-rate-limit-reset: UNIX timestamp when the current rate limit will be reset.\n - x-rate-limit-remaining: Number of requests remaining in current time period?\n */\n const xRateLimitRemaining = res.headers.get(\"x-rate-limit-remaining\");\n const xRateLimitReset = res.headers.get(\"x-rate-limit-reset\");\n if (xRateLimitRemaining === \"0\" && xRateLimitReset) {\n const currentTime = new Date().valueOf() / 1000;\n const timeDeltaMs =\n 1000 * (Number.parseInt(xRateLimitReset) - currentTime);\n\n // I have seen this block for 800s (~13 *minutes*)\n await new Promise((resolve) => setTimeout(resolve, timeDeltaMs));\n }\n }\n } while (res.status === 429);\n\n if (!res.ok) {\n return {\n success: false,\n err: await ApiError.fromResponse(res),\n };\n }\n\n // Check if response is chunked\n const transferEncoding = res.headers.get(\"transfer-encoding\");\n if (transferEncoding === \"chunked\") {\n // Handle streaming response, if a reader is present\n const reader =\n typeof res.body?.getReader === \"function\" ? res.body.getReader() : null;\n if (!reader) {\n try {\n const text = await res.text();\n try {\n const value = JSON.parse(text);\n return { success: true, value };\n } catch (_e) {\n // Return if just a normal string\n return { success: true, value: { text } as any };\n }\n } catch (_e) {\n return {\n success: false,\n err: new Error(\"No readable stream available and cant parse\"),\n };\n }\n }\n\n let chunks: any = \"\";\n // Read all chunks before attempting to parse\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n // Convert chunk to text and append\n chunks += new TextDecoder().decode(value);\n }\n\n // Now try to parse the complete accumulated response\n try {\n const value = JSON.parse(chunks);\n return { success: true, value };\n } catch (_e) {\n // If we can't parse as JSON, return the raw text\n return { success: true, value: { text: chunks } as any };\n }\n }\n\n // Handle non-streaming responses as before\n const contentType = res.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n const value: T = await res.json();\n // Skip deleteToken since TwitterAuth v2 doesn't have it\n // if (res.headers.get(\"x-rate-limit-incoming\") === \"0\") {\n // auth.deleteToken();\n // }\n return { success: true, value };\n }\n\n return { success: true, value: {} as T };\n}\n\n/** @internal */\nexport function addApiFeatures(o: object) {\n return {\n ...o,\n rweb_lists_timeline_redesign_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n tweetypie_unmention_optimization_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n longform_notetweets_rich_text_read_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n subscriptions_verification_info_enabled: true,\n subscriptions_verification_info_reason_enabled: true,\n subscriptions_verification_info_verified_since_enabled: true,\n super_follow_badge_privacy_enabled: false,\n super_follow_exclusive_tweet_notifications_enabled: false,\n super_follow_tweet_api_enabled: false,\n super_follow_user_api_enabled: false,\n android_graphql_skip_api_media_color_palette: false,\n creator_subscriptions_subscription_count_enabled: false,\n blue_business_profile_image_shape_enabled: false,\n unified_cards_ad_metadata_container_dynamic_card_content_query_enabled:\n false,\n };\n}\n\nexport function addApiParams(\n params: URLSearchParams,\n includeTweetReplies: boolean,\n): URLSearchParams {\n params.set(\"include_profile_interstitial_type\", \"1\");\n params.set(\"include_blocking\", \"1\");\n params.set(\"include_blocked_by\", \"1\");\n params.set(\"include_followed_by\", \"1\");\n params.set(\"include_want_retweets\", \"1\");\n params.set(\"include_mute_edge\", \"1\");\n params.set(\"include_can_dm\", \"1\");\n params.set(\"include_can_media_tag\", \"1\");\n params.set(\"include_ext_has_nft_avatar\", \"1\");\n params.set(\"include_ext_is_blue_verified\", \"1\");\n params.set(\"include_ext_verified_type\", \"1\");\n params.set(\"skip_status\", \"1\");\n params.set(\"cards_platform\", \"Web-12\");\n params.set(\"include_cards\", \"1\");\n params.set(\"include_ext_alt_text\", \"true\");\n params.set(\"include_ext_limited_action_results\", \"false\");\n params.set(\"include_quote_count\", \"true\");\n params.set(\"include_reply_count\", \"1\");\n params.set(\"tweet_mode\", \"extended\");\n params.set(\"include_ext_collab_control\", \"true\");\n params.set(\"include_ext_views\", \"true\");\n params.set(\"include_entities\", \"true\");\n params.set(\"include_user_entities\", \"true\");\n params.set(\"include_ext_media_color\", \"true\");\n params.set(\"include_ext_media_availability\", \"true\");\n params.set(\"include_ext_sensitive_media_warning\", \"true\");\n params.set(\"include_ext_trusted_friends_metadata\", \"true\");\n params.set(\"send_error_codes\", \"true\");\n params.set(\"simple_quoted_tweet\", \"true\");\n params.set(\"include_tweet_replies\", `${includeTweetReplies}`);\n params.set(\n \"ext\",\n \"mediaStats,highlightedLabel,hasNftAvatar,voiceInfo,birdwatchPivot,enrichments,superFollowMetadata,unmentionInfo,editControl,collab_control,vibe\",\n );\n return params;\n}\n","/**\n * Class representing an API error.\n */\n\nexport class ApiError extends Error {\n /**\n * Constructor for creating a new instance of the class.\n *\n * @param response The response object.\n * @param data The data object.\n * @param message The message string.\n */\n private constructor(\n readonly response: Response,\n readonly data: any,\n message: string,\n ) {\n super(message);\n }\n\n /**\n * Creates an instance of ApiError based on a Response object.\n *\n * @param {Response} response The Response object to parse.\n * @returns {Promise<ApiError>} A new instance of ApiError with the parsed data and status.\n */\n static async fromResponse(response: Response) {\n // Try our best to parse the result, but don't bother if we can't\n let data: string | object | undefined = undefined;\n try {\n data = await response.json();\n } catch {\n try {\n data = await response.text();\n } catch {}\n }\n\n return new ApiError(response, data, `Response status: ${response.status}`);\n }\n}\n\n/**\n * Represents a position in a file with line and column information.\n * @interface Position\n * @property {number} line - The line number of the position.\n * @property {number} column - The column number of the position.\n */\ninterface Position {\n line: number;\n column: number;\n}\n\n/**\n * Interface representing trace information.\n * @property { string } trace_id - The ID of the trace.\n */\ninterface TraceInfo {\n trace_id: string;\n}\n\n/**\n * Interface representing additional information that can be included in Twitter API error objects.\n * @typedef { Object } TwitterApiErrorExtensions\n * @property { number } [code] - The error code associated with the error.\n * @property { string } [kind] - The kind of error that occurred.\n * @property { string } [name] - The name of the error.\n * @property { string } [source] - The source of the error.\n * @property { TraceInfo } [tracing] - Information about the tracing of the error.\n */\ninterface TwitterApiErrorExtensions {\n code?: number;\n kind?: string;\n name?: string;\n source?: string;\n tracing?: TraceInfo;\n}\n\n/**\n * Interface representing a raw Twitter API error object.\n * @interface\n * @extends {TwitterApiErrorExtensions}\n * @property {string} [message] The error message.\n * @property {Position[]} [locations] An array of positions.\n * @property {string[]} [path] An array representing the path of the error.\n * @property {TwitterApiErrorExtensions} [extensions] Additional error extensions.\n */\nexport interface TwitterApiErrorRaw extends TwitterApiErrorExtensions {\n message?: string;\n locations?: Position[];\n path?: string[];\n extensions?: TwitterApiErrorExtensions;\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, requestApi } from \"./api\";\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\nexport async function getProfile(\n username: string,\n auth: TwitterAuth,\n): Promise<RequestApiResult<Profile>> {\n const params = new URLSearchParams();\n params.set(\n \"variables\",\n stringify({\n screen_name: username,\n withSafetyModeUserFields: true,\n }) ?? \"\",\n );\n\n params.set(\n \"features\",\n stringify({\n hidden_profile_likes_enabled: false,\n hidden_profile_subscriptions_enabled: false, // Auth-restricted\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n subscriptions_verification_info_is_identity_verified_enabled: false,\n subscriptions_verification_info_verified_since_enabled: true,\n highlights_tweets_tab_ui_enabled: true,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n responsive_web_graphql_timeline_navigation_enabled: true,\n }) ?? \"\",\n );\n\n params.set(\n \"fieldToggles\",\n stringify({ withAuxiliaryUserLabels: false }) ?? \"\",\n );\n\n const res = await requestApi<UserRaw>(\n `https://twitter.com/i/api/graphql/G3KGOASz96M-Qu0nwmGXNg/UserByScreenName?${params.toString()}`,\n auth,\n );\n if (!res.success) {\n return res as any;\n }\n\n const { value } = res;\n const { errors } = value;\n if (errors != null && errors.length > 0) {\n return {\n success: false,\n err: new Error(errors[0].message),\n };\n }\n\n if (!value.data || !value.data.user || !value.data.user.result) {\n return {\n success: false,\n err: new Error(\"User not found.\"),\n };\n }\n const { result: user } = value.data.user;\n const { legacy } = user;\n\n if (user.rest_id == null || user.rest_id.length === 0) {\n return {\n success: false,\n err: new Error(\"rest_id not found.\"),\n };\n }\n\n legacy.id_str = user.rest_id;\n\n if (legacy.screen_name == null || legacy.screen_name.length === 0) {\n return {\n success: false,\n err: new Error(`Either ${username} does not exist or is private.`),\n };\n }\n\n return {\n success: true,\n value: parseProfile(user.legacy, user.is_blue_verified),\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 const params = new URLSearchParams();\n params.set(\n \"variables\",\n stringify({\n userId: userId,\n withSafetyModeUserFields: true,\n }) ?? \"\",\n );\n\n params.set(\n \"features\",\n stringify({\n hidden_profile_subscriptions_enabled: true,\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n highlights_tweets_tab_ui_enabled: true,\n responsive_web_twitter_article_notes_tab_enabled: true,\n subscriptions_feature_can_gift_premium: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n responsive_web_graphql_timeline_navigation_enabled: true,\n }) ?? \"\",\n );\n\n const res = await requestApi<UserRaw>(\n `https://twitter.com/i/api/graphql/xf3jd90KKBCUxdlI_tNHZw/UserByRestId?${params.toString()}`,\n auth,\n );\n\n if (!res.success) {\n return res as any;\n }\n\n const { value } = res;\n const { errors } = value;\n if (errors != null && errors.length > 0) {\n return {\n success: false,\n err: new Error(errors[0].message),\n };\n }\n\n if (!value.data || !value.data.user || !value.data.user.result) {\n return {\n success: false,\n err: new Error(\"User not found.\"),\n };\n }\n\n const { result: user } = value.data.user;\n const { legacy } = user;\n\n if (legacy.screen_name == null || legacy.screen_name.length === 0) {\n return {\n success: false,\n err: new Error(\n `Either user with ID ${userId} does not exist or is private.`,\n ),\n };\n }\n\n return {\n success: true,\n value: legacy.screen_name,\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 stringify from \"json-stable-stringify\";\nimport { addApiFeatures, bearerToken, requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport { type Profile, getEntityIdByScreenName } from \"./profile\";\nimport { getUserTimeline } from \"./timeline-async\";\nimport {\n type RelationshipTimeline,\n parseRelationshipTimeline,\n} from \"./timeline-relationship\";\nimport type { QueryProfilesResponse } from \"./timeline-v1\";\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 function getFollowing(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n return getUserTimeline(userId, maxProfiles, (q, mt, c) => {\n return fetchProfileFollowing(q, mt, auth, c);\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 function getFollowers(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n return getUserTimeline(userId, maxProfiles, (q, mt, c) => {\n return fetchProfileFollowers(q, mt, auth, c);\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 const timeline = await getFollowingTimeline(\n userId,\n maxProfiles,\n auth,\n cursor,\n );\n\n return parseRelationshipTimeline(timeline);\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 const timeline = await getFollowersTimeline(\n userId,\n maxProfiles,\n auth,\n cursor,\n );\n\n return parseRelationshipTimeline(timeline);\n}\n\n/**\n * Asynchronously fetches the timeline of accounts that a user is following.\n *\n * @param {string} userId - The ID of the user whose following timeline is to be retrieved.\n * @param {number} maxItems - The maximum number of items to fetch (limited to 50).\n * @param {TwitterAuth} auth - The authentication information for making the API request.\n * @param {string} [cursor] - Optional cursor to paginate the results.\n * @returns {Promise<RelationshipTimeline>} A Promise that resolves to the RelationshipTimeline object representing the following timeline.\n * @throws {Error} If the client is not logged-in for profile following.\n */\nasync function getFollowingTimeline(\n userId: string,\n maxItems: number,\n auth: TwitterAuth,\n cursor?: string,\n): Promise<RelationshipTimeline> {\n if (!auth.isLoggedIn()) {\n throw new Error(\"Client is not logged-in for profile following.\");\n }\n\n if (maxItems > 50) {\n maxItems = 50;\n }\n\n const variables: Record<string, any> = {\n userId,\n count: maxItems,\n includePromotedContent: false,\n };\n\n const features = addApiFeatures({\n responsive_web_twitter_article_tweet_consumption_enabled: false,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_media_download_video_enabled: false,\n });\n\n if (cursor != null && cursor !== \"\") {\n variables.cursor = cursor;\n }\n\n const params = new URLSearchParams();\n params.set(\"features\", stringify(features) ?? \"\");\n params.set(\"variables\", stringify(variables) ?? \"\");\n\n const res = await requestApi<RelationshipTimeline>(\n `https://twitter.com/i/api/graphql/iSicc7LrzWGBgDPL0tM_TQ/Following?${params.toString()}`,\n auth,\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n return res.value;\n}\n\n/**\n * Retrieves the followers timeline for a specific user.\n * @param userId The ID of the user whose followers timeline will be retrieved.\n * @param maxItems The maximum number of items to retrieve (up to 50).\n * @param auth The Twitter authentication credentials.\n * @param cursor (Optional) The cursor for pagination.\n * @returns A Promise that resolves with the RelationshipTimeline object.\n * @throws Error if the client is not logged in or if the API request fails.\n */\nasync function getFollowersTimeline(\n userId: string,\n maxItems: number,\n auth: TwitterAuth,\n cursor?: string,\n): Promise<RelationshipTimeline> {\n if (!auth.isLoggedIn()) {\n throw new Error(\"Client is not logged-in for profile followers.\");\n }\n\n if (maxItems > 50) {\n maxItems = 50;\n }\n\n const variables: Record<string, any> = {\n userId,\n count: maxItems,\n includePromotedContent: false,\n };\n\n const features = addApiFeatures({\n responsive_web_twitter_article_tweet_consumption_enabled: false,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_media_download_video_enabled: false,\n });\n\n if (cursor != null && cursor !== \"\") {\n variables.cursor = cursor;\n }\n\n const params = new URLSearchParams();\n params.set(\"features\", stringify(features) ?? \"\");\n params.set(\"variables\", stringify(variables) ?? \"\");\n\n const res = await requestApi<RelationshipTimeline>(\n `https://twitter.com/i/api/graphql/rRXFSG5vR6drKr5M37YOTw/Followers?${params.toString()}`,\n auth,\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n return res.value;\n}\n\n/**\n * Following users is not supported in the current Twitter API v2 implementation\n * This functionality requires additional OAuth scopes and endpoints not included in this client\n *\n * @deprecated This function is not implemented for Twitter API v2\n */\nexport async function followUser(\n username: string,\n auth: TwitterAuth,\n): Promise<Response> {\n console.warn(\n \"Follow user functionality is not supported in Twitter API v2 client\",\n );\n throw new Error(\n \"Follow user functionality not implemented for Twitter API v2\",\n );\n}\n","import type { Profile } from \"./profile\";\nimport type { Tweet } from \"./tweets\";\n\n/**\n * Interface representing the response when fetching profiles.\n * @typedef {Object} FetchProfilesResponse\n * @property {Profile[]} profiles - An array of profiles.\n * @property {string} [next] - Optional: A string representing the next page to fetch.\n */\nexport interface FetchProfilesResponse {\n profiles: Profile[];\n next?: string;\n}\n\n/**\n * Function type for fetching profiles.\n *\n * @param {string} query - The search query for profiles.\n * @param {number} maxProfiles - The maximum number of profiles to retrieve.\n * @param {string | undefined} cursor - The cursor for fetching the next set of profiles.\n * @returns {Promise<FetchProfilesResponse>} - A promise that resolves to a FetchProfilesResponse object.\n */\nexport type FetchProfiles = (\n query: string,\n maxProfiles: number,\n cursor: string | undefined,\n) => Promise<FetchProfilesResponse>;\n\n/**\n * Interface representing the response from a fetch tweets API request.\n * @typedef {Object} FetchTweetsResponse\n * @property {Tweet[]} tweets - An array of Tweet objects.\n * @property {string} [next] - Optional: a string representing the next page token.\n */\nexport interface FetchTweetsResponse {\n tweets: Tweet[];\n next?: string;\n}\n\n/**\n * Function to fetch tweets based on a query and maximum number of tweets.\n * @param {string} query - The search query for tweets.\n * @param {number} maxTweets - The maximum number of tweets to fetch.\n * @param {string | undefined} cursor - The cursor for pagination, if any.\n * @returns {Promise<FetchTweetsResponse>} A promise that resolves to the response containing fetched tweets.\n */\nexport type FetchTweets = (\n query: string,\n maxTweets: number,\n cursor: string | undefined,\n) => Promise<FetchTweetsResponse>;\n\n/**\n * Asynchronously generates user profiles from a timeline based on the specified query and maximum number of profiles to fetch.\n * @param {string} query - The query string to search for profiles.\n * @param {number} maxProfiles - The maximum number of profiles to return.\n * @param {FetchProfiles} fetchFunc - The function to fetch profiles based on the query, maxProfiles, and cursor.\n * @returns {AsyncGenerator<Profile, void>} An asynchronous generator that yields profiles from the timeline.\n */\nexport async function* getUserTimeline(\n query: string,\n maxProfiles: number,\n fetchFunc: FetchProfiles,\n): AsyncGenerator<Profile, void> {\n let nProfiles = 0;\n let cursor: string | undefined = undefined;\n let consecutiveEmptyBatches = 0;\n while (nProfiles < maxProfiles) {\n const batch: FetchProfilesResponse = await fetchFunc(\n query,\n maxProfiles,\n cursor,\n );\n\n const { profiles, next } = batch;\n cursor = next;\n\n if (profiles.length === 0) {\n consecutiveEmptyBatches++;\n if (consecutiveEmptyBatches > 5) break;\n } else consecutiveEmptyBatches = 0;\n\n for (const profile of profiles) {\n if (nProfiles < maxProfiles) yield profile;\n else break;\n nProfiles++;\n }\n\n if (!next) break;\n }\n}\n\n/**\n * Async generator function that fetches and yields tweets from a timeline based on\n * the provided query and maximum number of tweets to retrieve.\n * @param {string} query - The search query for retrieving tweets.\n * @param {number} maxTweets - The maximum number of tweets to retrieve.\n * @param {FetchTweets} fetchFunc - The function to fetch tweets based on the query, maxTweets, and cursor.\n * @returns {AsyncGenerator<Tweet, void>} An async generator that yields retrieved tweets.\n */\nexport async function* getTweetTimeline(\n query: string,\n maxTweets: number,\n fetchFunc: FetchTweets,\n): AsyncGenerator<Tweet, void> {\n let nTweets = 0;\n let cursor: string | undefined = undefined;\n while (nTweets < maxTweets) {\n const batch: FetchTweetsResponse = await fetchFunc(\n query,\n maxTweets,\n cursor,\n );\n\n const { tweets, next } = batch;\n\n if (tweets.length === 0) {\n break;\n }\n\n for (const tweet of tweets) {\n if (nTweets < maxTweets) {\n cursor = next;\n yield tweet;\n } else {\n break;\n }\n\n nTweets++;\n }\n }\n}\n","import { type Profile, parseProfile } from \"./profile\";\nimport type { QueryProfilesResponse } from \"./timeline-v1\";\nimport type { TimelineUserResultRaw } from \"./timeline-v2\";\n\n/**\n * Interface for raw content of a relationship entry item.\n * @typedef { Object } RelationshipEntryItemContentRaw\n * @property { string } [itemType] - The type of item.\n * @property { string } [userDisplayType] - The display type for the user.\n * @property { Object } [user_results] - The results of the user.\n * @property { Object } [user_results.result] - The raw data of the timeline user result.\n */\nexport interface RelationshipEntryItemContentRaw {\n itemType?: string;\n userDisplayType?: string;\n user_results?: {\n result?: TimelineUserResultRaw;\n };\n}\n\n/**\n * Interface representing a raw relationship entry.\n * @interface\n * @property {string} entryId - The unique identifier for the entry.\n * @property {string} sortIndex - The sorting index for the entry.\n * @property {Object} [content] - Additional content for the entry.\n * @property {string} [content.cursorType] - The type of cursor.\n * @property {string} [content.entryType] - The type of entry.\n * @property {string} [content.__typename] - The typename of the content.\n * @property {string} [content.value] - The value of the content.\n * @property {RelationshipEntryItemContentRaw} [content.itemContent] - The raw item content for the entry.\n */\n\nexport interface RelationshipEntryRaw {\n entryId: string;\n sortIndex: string;\n content?: {\n cursorType?: string;\n entryType?: string;\n __typename?: string;\n value?: string;\n itemContent?: RelationshipEntryItemContentRaw;\n };\n}\n\n/**\n * Interface representing a relationship timeline.\n * @property {object} data - Optional property containing user result timeline instructions.\n * @property {object} data.user - Optional property containing user information.\n * @property {object} data.user.result - Optional property containing result information.\n * @property {object} data.user.result.timeline - Optional property containing timeline instructions.\n * @property {object} data.user.result.timeline.timeline - Optional property containing timeline instructions.\n * @property {object[]} data.user.result.timeline.timeline.instructions - Optional array of relationship entries.\n * @property {object} data.user.result.timeline.timeline.instructions.entry - Optional relationship entry object.\n * @property {object[]} data.user.result.timeline.timeline.instructions.type - Optional string representing type of timeline instructions.\n */\nexport interface RelationshipTimeline {\n data?: {\n user?: {\n result?: {\n timeline?: {\n timeline?: {\n instructions?: {\n entries?: RelationshipEntryRaw[];\n entry?: RelationshipEntryRaw;\n type?: string;\n }[];\n };\n };\n };\n };\n };\n}\n\n/**\n * Parses the given RelationshipTimeline data to extract profiles and cursors.\n * @param timeline The RelationshipTimeline data to parse.\n * @returns The QueryProfilesResponse object containing profiles, next cursor, and previous cursor.\n */\nexport function parseRelationshipTimeline(\n timeline: RelationshipTimeline,\n): QueryProfilesResponse {\n let bottomCursor: string | undefined;\n let topCursor: string | undefined;\n const profiles: Profile[] = [];\n const instructions =\n timeline.data?.user?.result?.timeline?.timeline?.instructions ?? [];\n\n for (const instruction of instructions) {\n if (\n instruction.type === \"TimelineAddEntries\" ||\n instruction.type === \"TimelineReplaceEntry\"\n ) {\n if (instruction.entry?.content?.cursorType === \"Bottom\") {\n bottomCursor = instruction.entry.content.value;\n continue;\n }\n\n if (instruction.entry?.content?.cursorType === \"Top\") {\n topCursor = instruction.entry.content.value;\n continue;\n }\n\n const entries = instruction.entries ?? [];\n for (const entry of entries) {\n const itemContent = entry.content?.itemContent;\n if (itemContent?.userDisplayType === \"User\") {\n const userResultRaw = itemContent.user_results?.result;\n\n if (userResultRaw?.legacy) {\n const profile = parseProfile(\n userResultRaw.legacy,\n userResultRaw.is_blue_verified,\n );\n\n if (!profile.userId) {\n profile.userId = userResultRaw.rest_id;\n }\n\n profiles.push(profile);\n }\n } else if (entry.content?.cursorType === \"Bottom\") {\n bottomCursor = entry.content.value;\n } else if (entry.content?.cursorType === \"Top\") {\n topCursor = entry.content.value;\n }\n }\n }\n }\n\n return { profiles, next: bottomCursor, previous: topCursor };\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 RequestApiResult, requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport { ApiError } from \"./errors\";\nimport type { TimelineInstruction } from \"./timeline-v2\";\n\n/**\n * Interface for the response data of the latest timeline for the home page.\n * @property {object} data - The response data object.\n * @property {object} data.home - The home object within the response data.\n * @property {array} data.home.home_timeline_urt - The array of timeline instructions for the home page.\n */\nexport interface HomeLatestTimelineResponse {\n data?: {\n home: {\n home_timeline_urt: {\n instructions: TimelineInstruction[];\n };\n };\n };\n}\n\n/**\n * Fetches the following timeline from Twitter API.\n *\n * @param {number} count - The number of tweets to fetch\n * @param {string[]} seenTweetIds - Array of IDs of tweets that have been seen\n * @param {TwitterAuth} auth - The authentication credentials\n * @returns {Promise<any[]>} - Array of tweets in the following timeline\n */\nexport async function fetchFollowingTimeline(\n count: number,\n seenTweetIds: string[],\n auth: TwitterAuth,\n): Promise<any[]> {\n const variables = {\n count,\n includePromotedContent: true,\n latestControlAvailable: true,\n requestContext: \"launch\",\n seenTweetIds,\n };\n\n const features = {\n profile_label_improvements_pcf_label_in_post_enabled: true,\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n communities_web_enable_tweet_community_results_fetch: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n articles_preview_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n rweb_video_timestamps_enabled: true,\n longform_notetweets_rich_text_read_enabled: true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n };\n\n const res = (await requestApi<HomeLatestTimelineResponse>(\n `https://x.com/i/api/graphql/K0X1xbCZUjttdK8RazKAlw/HomeLatestTimeline?variables=${encodeURIComponent(\n JSON.stringify(variables),\n )}&features=${encodeURIComponent(JSON.stringify(features))}`,\n auth,\n \"GET\",\n )) as RequestApiResult<HomeLatestTimelineResponse>;\n\n if (!res.success) {\n if ((res as any).err instanceof ApiError) {\n console.error(\"Error details:\", (res as any).err.data);\n }\n throw (res as any).err;\n }\n\n const home = res.value?.data?.home.home_timeline_urt?.instructions;\n\n if (!home) {\n return [];\n }\n\n const entries: any[] = [];\n\n for (const instruction of home) {\n if (instruction.type === \"TimelineAddEntries\") {\n for (const entry of instruction.entries ?? []) {\n entries.push(entry);\n }\n }\n }\n // get the itemContnent from each entry\n const tweets = entries\n .map((entry) => entry.content.itemContent?.tweet_results?.result)\n .filter((tweet) => tweet !== undefined);\n\n return tweets;\n}\n","import { requestApi } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport { ApiError } from \"./errors\";\nimport type { TimelineInstruction } from \"./timeline-v2\";\n\n/**\n * Interface representing the response object for the home timeline API endpoint.\n * @property {object} data - The data object containing the response data.\n * @property {object} data.home - The home object containing the home timeline data.\n * @property {object} data.home.home_timeline_urt - The object containing the timeline instructions.\n * @property {TimelineInstruction[]} data.home.home_timeline_urt.instructions - An array of timeline instructions.\n */\nexport interface HomeTimelineResponse {\n data?: {\n home: {\n home_timeline_urt: {\n instructions: TimelineInstruction[];\n };\n };\n };\n}\n\n/**\n * Fetches the home timeline for a Twitter user.\n *\n * @param {number} count - The number of tweets to fetch.\n * @param {string[]} seenTweetIds - An array of ids of tweets that the user has already seen.\n * @param {TwitterAuth} auth - The authentication credentials for the Twitter API.\n * @returns {Promise<any[]>} - A promise that resolves to an array of tweets from the home timeline.\n */\nexport async function fetchHomeTimeline(\n count: number,\n seenTweetIds: string[],\n auth: TwitterAuth,\n): Promise<any[]> {\n const variables = {\n count,\n includePromotedContent: true,\n latestControlAvailable: true,\n requestContext: \"launch\",\n withCommunity: true,\n seenTweetIds,\n };\n\n const features = {\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n communities_web_enable_tweet_community_results_fetch: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n articles_preview_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n rweb_video_timestamps_enabled: true,\n longform_notetweets_rich_text_read_enabled: true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n };\n\n const res = await requestApi<HomeTimelineResponse>(\n `https://x.com/i/api/graphql/HJFjzBgCs16TqxewQOeLNg/HomeTimeline?variables=${encodeURIComponent(\n JSON.stringify(variables),\n )}&features=${encodeURIComponent(JSON.stringify(features))}`,\n auth,\n \"GET\",\n );\n\n if (!res.success) {\n if ((res as any).err instanceof ApiError) {\n console.error(\"Error details:\", (res as any).err.data);\n }\n throw (res as any).err;\n }\n\n const home = res.value?.data?.home.home_timeline_urt?.instructions;\n\n if (!home) {\n return [];\n }\n\n const entries: any[] = [];\n\n for (const instruction of home) {\n if (instruction.type === \"TimelineAddEntries\") {\n for (const entry of instruction.entries ?? []) {\n entries.push(entry);\n }\n }\n }\n // get the itemContnent from each entry\n const tweets = entries\n .map((entry) => entry.content.itemContent?.tweet_results?.result)\n .filter((tweet) => tweet !== undefined);\n\n return tweets;\n}\n","/**\n * Defines a type that ensures a specified property in an object is\n * not nullable or undefined.\n * @template T - The type of the object.\n * @template K - The keyof type representing the keys of the object.\n * @param {T} T - The object type.\n * @param {K} K - The key type of the object.\n * @returns {Object} - Returns a new type that includes all properties of the\n * original object with the specified key set to be non-nullable.\n */\nexport type NonNullableField<T, K extends keyof T> = {\n [P in K]-?: T[P];\n} & T;\n\n/**\n * Checks if the specified field is defined in the object.\n *\n * @template T - The type of the object\n * @template K - The key of the field\n * @param {K} key - The key of the field to check\n * @returns {(value: T) => value is NonNullableField<T, K>} A function that checks if the field is defined\n */\nexport function isFieldDefined<T, K extends keyof T>(key: K) {\n return (value: T): value is NonNullableField<T, K> => isDefined(value[key]);\n}\n\n/**\n * Check if a value is defined (not null or undefined).\n * @template T\n * @param {T | null | undefined} value - The value to check.\n * @return {value is T} Returns true if the value is defined, false otherwise.\n */\nexport function isDefined<T>(value: T | null | undefined): value is T {\n return value != null;\n}\n","import type { LegacyTweetRaw, TimelineMediaExtendedRaw } from \"./timeline-v1\";\nimport type { Photo, Video } from \"./tweets\";\nimport { type NonNullableField, isFieldDefined } from \"./type-util\";\n\nconst reHashtag = /\\B(\\#\\S+\\b)/g;\nconst reCashtag = /\\B(\\$\\S+\\b)/g;\nconst reTwitterUrl = /https:(\\/\\/t\\.co\\/([A-Za-z0-9]|[A-Za-z]){10})/g;\nconst reUsername = /\\B(\\@\\S{1,15}\\b)/g;\n\n/**\n * Parses the media groups from the provided array of TimelineMediaExtendedRaw objects\n * to extract photos and videos along with the sensitive content information.\n *\n * @param {TimelineMediaExtendedRaw[]} media - The array of TimelineMediaExtendedRaw objects to parse\n * @returns {{ sensitiveContent?: boolean, photos: Photo[], videos: Video[] }} - An object containing\n * the sensitive content boolean flag, an array of photos, and an array of videos\n */\nexport function parseMediaGroups(media: TimelineMediaExtendedRaw[]): {\n sensitiveContent?: boolean;\n photos: Photo[];\n videos: Video[];\n} {\n const photos: Photo[] = [];\n const videos: Video[] = [];\n let sensitiveContent: boolean | undefined = undefined;\n\n for (const m of media\n .filter(isFieldDefined(\"id_str\"))\n .filter(isFieldDefined(\"media_url_https\"))) {\n if (m.type === \"photo\") {\n photos.push({\n id: m.id_str,\n url: m.media_url_https,\n alt_text: m.ext_alt_text,\n });\n } else if (m.type === \"video\") {\n videos.push(parseVideo(m));\n }\n\n const sensitive = m.ext_sensitive_media_warning;\n if (sensitive != null) {\n sensitiveContent =\n sensitive.adult_content ||\n sensitive.graphic_violence ||\n sensitive.other;\n }\n }\n\n return { sensitiveContent, photos, videos };\n}\n\n/**\n * Parses the video information from the given raw media object.\n *\n * @param {NonNullableField<TimelineMediaExtendedRaw, \"id_str\" | \"media_url_https\">} m The raw media object containing the video information.\n * @returns {Video} The parsed video object with id, preview, and URL.\n */\nfunction parseVideo(\n m: NonNullableField<TimelineMediaExtendedRaw, \"id_str\" | \"media_url_https\">,\n): Video {\n const video: Video = {\n id: m.id_str,\n preview: m.media_url_https,\n };\n\n let maxBitrate = 0;\n const variants = m.video_info?.variants ?? [];\n for (const variant of variants) {\n const bitrate = variant.bitrate;\n if (bitrate != null && bitrate > maxBitrate && variant.url != null) {\n let variantUrl = variant.url;\n const stringStart = 0;\n const tagSuffixIdx = variantUrl.indexOf(\"?tag=10\");\n if (tagSuffixIdx !== -1) {\n variantUrl = variantUrl.substring(stringStart, tagSuffixIdx + 1);\n }\n\n video.url = variantUrl;\n maxBitrate = bitrate;\n }\n }\n\n return video;\n}\n\n/**\n * Reconstructs the tweet HTML by parsing the tweet text and adding links to hashtags, cashtags, usernames,\n * and converting Twitter URLs. Also adds images and videos to the HTML.\n *\n * @param {LegacyTweetRaw} tweet The raw tweet object containing the full text of the tweet.\n * @param {Photo[]} photos Array of photo objects associated with the tweet.\n * @param {Video[]} videos Array of video objects associated with the tweet.\n * @returns {string} The reconstructed HTML for the tweet.\n */\nexport function reconstructTweetHtml(\n tweet: LegacyTweetRaw,\n photos: Photo[],\n videos: Video[],\n): string {\n const media: string[] = [];\n\n // HTML parsing with regex :)\n let html = tweet.full_text ?? \"\";\n\n html = html.replace(reHashtag, linkHashtagHtml);\n html = html.replace(reCashtag, linkCashtagHtml);\n html = html.replace(reUsername, linkUsernameHtml);\n html = html.replace(reTwitterUrl, unwrapTcoUrlHtml(tweet, media));\n\n for (const { url } of photos) {\n if (media.indexOf(url) !== -1) {\n continue;\n }\n\n html += `<br><img src=\"${url}\"/>`;\n }\n\n for (const { preview: url } of videos) {\n if (media.indexOf(url) !== -1) {\n continue;\n }\n\n html += `<br><img src=\"${url}\"/>`;\n }\n\n html = html.replace(/\\n/g, \"<br>\");\n\n return html;\n}\n\n/**\n * Generates an HTML link for a hashtag by removing the '#' symbol\n * and creating a Twitter hashtag link.\n *\n * @param hashtag - The hashtag to generate the link for\n * @returns The HTML link for the specified hashtag\n */\nfunction linkHashtagHtml(hashtag: string) {\n return `<a href=\"https://twitter.com/hashtag/${hashtag.replace(\"#\", \"\")}\">${hashtag}</a>`;\n}\n\n/**\n * Generates HTML anchor link for a cashtag.\n * @param {string} cashtag - The cashtag to link.\n * @returns {string} The HTML anchor link for the cashtag.\n */\nfunction linkCashtagHtml(cashtag: string) {\n return `<a href=\"https://twitter.com/search?q=%24${cashtag.replace(\"$\", \"\")}\">${cashtag}</a>`;\n}\n\n/**\n * Generates HTML for linking a Twitter username.\n *\n * @param {string} username - The Twitter username to generate link for.\n * @returns {string} - The HTML string for the linked username.\n */\nfunction linkUsernameHtml(username: string) {\n return `<a href=\"https://twitter.com/${username.replace(\"@\", \"\")}\">${username}</a>`;\n}\n\n/**\n * Unwraps the t.co URL in a tweet HTML based on the provided tweet object and founded media URLs.\n * @param {LegacyTweetRaw} tweet - The tweet object containing URLs and media entities.\n * @param {string[]} foundedMedia - An array to store the founded media URLs.\n * @returns {function(string): string} - A function that takes a t.co URL and returns the corresponding HTML representation.\n */\nfunction unwrapTcoUrlHtml(tweet: LegacyTweetRaw, foundedMedia: string[]) {\n return (tco: string) => {\n for (const entity of tweet.entities?.urls ?? []) {\n if (tco === entity.url && entity.expanded_url != null) {\n return `<a href=\"${entity.expanded_url}\">${tco}</a>`;\n }\n }\n\n for (const entity of tweet.extended_entities?.media ?? []) {\n if (tco === entity.url && entity.media_url_https != null) {\n foundedMedia.push(entity.media_url_https);\n return `<br><a href=\"${tco}\"><img src=\"${entity.media_url_https}\"/></a>`;\n }\n }\n\n return tco;\n };\n}\n","import type { LegacyUserRaw } from \"./profile\";\nimport { parseMediaGroups, reconstructTweetHtml } from \"./timeline-tweet-util\";\nimport type {\n LegacyTweetRaw,\n ParseTweetResult,\n QueryTweetsResponse,\n SearchResultRaw,\n TimelineResultRaw,\n} from \"./timeline-v1\";\nimport type { Tweet } from \"./tweets\";\nimport { isFieldDefined } from \"./type-util\";\n\n/**\n * Interface representing raw data for a user result in a timeline.\n * @property {string} [rest_id] - The REST ID of the user.\n * @property {LegacyUserRaw} [legacy] - The legacy user data.\n * @property {boolean} [is_blue_verified] - Indicates if the user is blue verified.\n */\nexport interface TimelineUserResultRaw {\n rest_id?: string;\n legacy?: LegacyUserRaw;\n is_blue_verified?: boolean;\n}\n\n/**\n * Interface representing the raw content of a timeline entry item.\n * @typedef {Object} TimelineEntryItemContentRaw\n * @property {string} [itemType] - The type of the item.\n * @property {string} [tweetDisplayType] - The display type of the tweet.\n * @property {Object} [tweetResult] - The result of the tweet.\n * @property {Object} [tweet_results] - The results of the tweet.\n * @property {string} [userDisplayType] - The display type of the user.\n * @property {Object} [user_results] - The results of the user.\n */\n\nexport interface TimelineEntryItemContentRaw {\n itemType?: string;\n tweetDisplayType?: string;\n tweetResult?: {\n result?: TimelineResultRaw;\n };\n tweet_results?: {\n result?: TimelineResultRaw;\n };\n userDisplayType?: string;\n user_results?: {\n result?: TimelineUserResultRaw;\n };\n}\n\n/**\n * Interface representing a raw Timeline Entry.\n * @typedef { Object } TimelineEntryRaw\n * @property { string } entryId - The unique identifier of the entry.\n * @property { Object } [content] - The content of the entry.\n * @property { string } [content.cursorType] - The cursor type of the content.\n * @property { string } [content.value] - The value of the content.\n * @property {Object[]} [content.items] - An array of items within the content.\n * @property { string } [content.items.entryId] - The unique identifier of an item.\n * @property { Object } [content.items.item] - The item within the content.\n * @property { Object } [content.items.item.content] - The content of the item.\n * @property { Object } [content.items.item.itemContent] - The item content of the item.\n */\nexport interface TimelineEntryRaw {\n entryId: string;\n content?: {\n cursorType?: string;\n value?: string;\n items?: {\n entryId?: string;\n item?: {\n content?: TimelineEntryItemContentRaw;\n itemContent?: SearchEntryItemContentRaw;\n };\n }[];\n itemContent?: TimelineEntryItemContentRaw;\n };\n}\n\n/**\n * Interface representing the raw content of a search entry item.\n * @interface\n * @property {string} [tweetDisplayType] - The display type of the tweet.\n * @property {Object} [tweet_results] - The results of the tweet search.\n * @property {Object} [tweet_results.result] - The raw search result of the tweet.\n * @property {string} [userDisplayType] - The display type of the user.\n * @property {Object} [user_results] - The results of the user search.\n * @property {Object} [user_results.result] - The raw search result of the user timeline.\n */\nexport interface SearchEntryItemContentRaw {\n tweetDisplayType?: string;\n tweet_results?: {\n result?: SearchResultRaw;\n };\n userDisplayType?: string;\n user_results?: {\n result?: TimelineUserResultRaw;\n };\n}\n\n/**\n * Interface representing a raw search entry.\n * @typedef { Object } SearchEntryRaw\n * @property { string } entryId - The unique identifier of the entry.\n * @property { string } sortIndex - The sorting index of the entry.\n * @property { Object } [content] - The content details of the entry.\n * @property { string } [content.cursorType] - The type of cursor associated with the entry content.\n * @property { string } [content.entryType] - The type of entry.\n * @property { string } [content.__typename] - The typename of the content.\n * @property { string } [content.value] - The value associated with the entry content.\n * @property {Array<Object>} [content.items] - An array of items associated with the entry.\n * @property { Object } [content.items.item] - An item object associated with the entry.\n * @property { Object } [content.items.item.content] - The content details of the item associated with the entry.\n * @property { Object } [content.itemContent] - The content details of the item associated with the entry.\n */\nexport interface SearchEntryRaw {\n entryId: string;\n sortIndex: string;\n content?: {\n cursorType?: string;\n entryType?: string;\n __typename?: string;\n value?: string;\n items?: {\n item?: {\n content?: SearchEntryItemContentRaw;\n };\n }[];\n itemContent?: SearchEntryItemContentRaw;\n };\n}\n\n/**\n * Interface representing a timeline instruction.\n * @typedef {Object} TimelineInstruction\n * @property {TimelineEntryRaw[]} [entries] - An array of timeline entry raw objects.\n * @property {TimelineEntryRaw} [entry] - A single timeline entry raw object.\n * @property {string} [type] - The type of the timeline instruction.\n */\nexport interface TimelineInstruction {\n entries?: TimelineEntryRaw[];\n entry?: TimelineEntryRaw;\n type?: string;\n}\n\n/**\n * Interface representing version 2 of a timeline object.\n * @typedef {Object} TimelineV2\n * @property {Object} data - Data object containing user information.\n * @property {Object} data.user - User object containing result information.\n * @property {Object} data.user.result - Result object containing timeline_v2 information.\n * @property {Object} data.user.result.timeline_v2 - Timeline_v2 object containing timeline information.\n * @property {Object} data.user.result.timeline_v2.timeline - Timeline object containing instructions.\n * @property {Array<TimelineInstruction>} data.user.result.timeline_v2.timeline.instructions - Array of timeline instructions.\n */\nexport interface TimelineV2 {\n data?: {\n user?: {\n result?: {\n timeline_v2?: {\n timeline?: {\n instructions?: TimelineInstruction[];\n };\n };\n };\n };\n };\n}\n\n/**\n * Represents a threaded conversation with optional data.\n * @interface\n * @property {Object} data - Optional data for the conversation.\n * @property {Object} data.threaded_conversation_with_injections_v2 - Optional object containing instructions.\n * @property {TimelineInstruction[]} data.threaded_conversation_with_injections_v2.instructions - Array of timeline instructions.\n */\nexport interface ThreadedConversation {\n data?: {\n threaded_conversation_with_injections_v2?: {\n instructions?: TimelineInstruction[];\n };\n };\n}\n\n/**\n * Parses a legacy tweet object and returns a ParseTweetResult.\n * @param {LegacyUserRaw} [user] - The legacy user object.\n * @param {LegacyTweetRaw} [tweet] - The legacy tweet object.\n * @returns {ParseTweetResult} The result of parsing the legacy tweet.\n */\nexport function parseLegacyTweet(\n user?: LegacyUserRaw,\n tweet?: LegacyTweetRaw,\n): ParseTweetResult {\n if (tweet == null) {\n return {\n success: false,\n err: new Error(\"Tweet was not found in the timeline object.\"),\n };\n }\n\n if (user == null) {\n return {\n success: false,\n err: new Error(\"User was not found in the timeline object.\"),\n };\n }\n\n if (!tweet.id_str) {\n if (!tweet.conversation_id_str) {\n return {\n success: false,\n err: new Error(\"Tweet ID was not found in object.\"),\n };\n }\n\n tweet.id_str = tweet.conversation_id_str;\n }\n\n const hashtags = tweet.entities?.hashtags ?? [];\n const mentions = tweet.entities?.user_mentions ?? [];\n const media = tweet.extended_entities?.media ?? [];\n const pinnedTweets = new Set<string | undefined>(\n user.pinned_tweet_ids_str ?? [],\n );\n const urls = tweet.entities?.urls ?? [];\n const { photos, videos, sensitiveContent } = parseMediaGroups(media);\n\n const tw: Tweet = {\n bookmarkCount: tweet.bookmark_count,\n conversationId: tweet.conversation_id_str,\n id: tweet.id_str,\n hashtags: hashtags\n .filter(isFieldDefined(\"text\"))\n .map((hashtag) => hashtag.text),\n likes: tweet.favorite_count,\n mentions: mentions.filter(isFieldDefined(\"id_str\")).map((mention) => ({\n id: mention.id_str,\n username: mention.screen_name,\n name: mention.name,\n })),\n name: user.name,\n permanentUrl: `https://twitter.com/${user.screen_name}/status/${tweet.id_str}`,\n photos,\n replies: tweet.reply_count,\n retweets: tweet.retweet_count,\n text: tweet.full_text,\n thread: [],\n urls: urls\n .filter(isFieldDefined(\"expanded_url\"))\n .map((url) => url.expanded_url),\n userId: tweet.user_id_str,\n username: user.screen_name,\n videos,\n isQuoted: false,\n isReply: false,\n isRetweet: false,\n isPin: false,\n sensitiveContent: false,\n };\n\n if (tweet.created_at) {\n tw.timeParsed = new Date(Date.parse(tweet.created_at));\n tw.timestamp = Math.floor(tw.timeParsed.valueOf() / 1000);\n }\n\n if (tweet.place?.id) {\n tw.place = tweet.place;\n }\n\n const quotedStatusIdStr = tweet.quoted_status_id_str;\n const inReplyToStatusIdStr = tweet.in_reply_to_status_id_str;\n const retweetedStatusIdStr = tweet.retweeted_status_id_str;\n const retweetedStatusResult = tweet.retweeted_status_result?.result;\n\n if (quotedStatusIdStr) {\n tw.isQuoted = true;\n tw.quotedStatusId = quotedStatusIdStr;\n }\n\n if (inReplyToStatusIdStr) {\n tw.isReply = true;\n tw.inReplyToStatusId = inReplyToStatusIdStr;\n }\n\n if (retweetedStatusIdStr || retweetedStatusResult) {\n tw.isRetweet = true;\n tw.retweetedStatusId = retweetedStatusIdStr;\n\n if (retweetedStatusResult) {\n const parsedResult = parseLegacyTweet(\n retweetedStatusResult?.core?.user_results?.result?.legacy,\n retweetedStatusResult?.legacy,\n );\n\n if (parsedResult.success) {\n tw.retweetedStatus = parsedResult.tweet;\n }\n }\n }\n\n const views = Number.parseInt(tweet.ext_views?.count ?? \"\");\n if (!Number.isNaN(views)) {\n tw.views = views;\n }\n\n if (pinnedTweets.has(tweet.id_str)) {\n // TODO: Update tests so this can be assigned at the tweet declaration\n tw.isPin = true;\n }\n\n if (sensitiveContent) {\n // TODO: Update tests so this can be assigned at the tweet declaration\n tw.sensitiveContent = true;\n }\n\n tw.html = reconstructTweetHtml(tweet, tw.photos, tw.videos);\n\n return { success: true, tweet: tw };\n}\n\n/**\n * Parses a raw timeline result object into a ParseTweetResult object.\n *\n * @param {TimelineResultRaw} result - The raw timeline result object to parse.\n * @returns {ParseTweetResult} The parsed tweet result object.\n */\nfunction parseResult(result?: TimelineResultRaw): ParseTweetResult {\n const noteTweetResultText =\n result?.note_tweet?.note_tweet_results?.result?.text;\n\n if (result?.legacy && noteTweetResultText) {\n result.legacy.full_text = noteTweetResultText;\n }\n\n const tweetResult = parseLegacyTweet(\n result?.core?.user_results?.result?.legacy,\n result?.legacy,\n );\n if (!tweetResult.success) {\n return tweetResult;\n }\n\n if (!tweetResult.tweet.views && result?.views?.count) {\n const views = Number.parseInt(result.views.count);\n if (!Number.isNaN(views)) {\n tweetResult.tweet.views = views;\n }\n }\n\n const quotedResult = result?.quoted_status_result?.result;\n if (quotedResult) {\n if (quotedResult.legacy && quotedResult.rest_id) {\n quotedResult.legacy.id_str = quotedResult.rest_id;\n }\n\n const quotedTweetResult = parseResult(quotedResult);\n if (quotedTweetResult.success) {\n tweetResult.tweet.quotedStatus = quotedTweetResult.tweet;\n }\n }\n\n return tweetResult;\n}\n\nconst expectedEntryTypes = [\"tweet\", \"profile-conversation\"];\n\n/**\n * Parses the timeline tweets from a TimelineV2 object and returns the QueryTweetsResponse.\n * @param {TimelineV2} timeline The timeline object containing the tweet data.\n * @returns {QueryTweetsResponse} The parsed tweets along with the next and previous cursors.\n */\nexport function parseTimelineTweetsV2(\n timeline: TimelineV2,\n): QueryTweetsResponse {\n let bottomCursor: string | undefined;\n let topCursor: string | undefined;\n const tweets: Tweet[] = [];\n const instructions =\n timeline.data?.user?.result?.timeline_v2?.timeline?.instructions ?? [];\n for (const instruction of instructions) {\n const entries = instruction.entries ?? [];\n\n for (const entry of entries) {\n const entryContent = entry.content;\n if (!entryContent) continue;\n\n // Handle pagination\n if (entryContent.cursorType === \"Bottom\") {\n bottomCursor = entryContent.value;\n continue;\n }\n if (entryContent.cursorType === \"Top\") {\n topCursor = entryContent.value;\n continue;\n }\n\n const idStr = entry.entryId;\n if (\n !expectedEntryTypes.some((entryType) => idStr.startsWith(entryType))\n ) {\n continue;\n }\n\n if (entryContent.itemContent) {\n // Typically TimelineTimelineTweet entries\n parseAndPush(tweets, entryContent.itemContent, idStr);\n } else if (entryContent.items) {\n // Typically TimelineTimelineModule entries\n for (const item of entryContent.items) {\n if (item.item?.itemContent) {\n parseAndPush(tweets, item.item.itemContent, idStr);\n }\n }\n }\n }\n }\n\n return { tweets, next: bottomCursor, previous: topCursor };\n}\n\n/**\n * Parses the raw content of a timeline entry item to extract the tweet data.\n * @param {TimelineEntryItemContentRaw} content - The raw content of the timeline entry item\n * @param {string} entryId - The entry ID of the timeline entry\n * @param {boolean} [isConversation=false] - Indicates if the timeline entry is part of a conversation\n * @returns {Tweet | null} The parsed tweet data or null if the parsing was unsuccessful\n */\nexport function parseTimelineEntryItemContentRaw(\n content: TimelineEntryItemContentRaw,\n entryId: string,\n isConversation = false,\n) {\n let result = content.tweet_results?.result ?? content.tweetResult?.result;\n if (\n result?.__typename === \"Tweet\" ||\n (result?.__typename === \"TweetWithVisibilityResults\" && result?.tweet)\n ) {\n if (result?.__typename === \"TweetWithVisibilityResults\")\n result = result.tweet;\n\n if (result?.legacy) {\n result.legacy.id_str =\n result.rest_id ??\n entryId.replace(\"conversation-\", \"\").replace(\"tweet-\", \"\");\n }\n\n const tweetResult = parseResult(result);\n if (tweetResult.success) {\n if (isConversation) {\n if (content?.tweetDisplayType === \"SelfThread\") {\n tweetResult.tweet.isSelfThread = true;\n }\n }\n\n return tweetResult.tweet;\n }\n }\n\n return null;\n}\n\n/**\n * Parses the given content and pushes the resulting Tweet object to the specified array.\n *\n * @param {Tweet[]} tweets - The array to push the parsed Tweet object to.\n * @param {TimelineEntryItemContentRaw} content - The raw content to parse.\n * @param {string} entryId - The ID of the timeline entry.\n * @param {boolean} [isConversation=false] - Indicates if the tweet is part of a conversation.\n */\nexport function parseAndPush(\n tweets: Tweet[],\n content: TimelineEntryItemContentRaw,\n entryId: string,\n isConversation = false,\n) {\n const tweet = parseTimelineEntryItemContentRaw(\n content,\n entryId,\n isConversation,\n );\n\n if (tweet) {\n tweets.push(tweet);\n }\n}\n\n/**\n * Parses a threaded conversation object and returns an array of Tweets.\n * @param conversation The threaded conversation object to parse\n * @returns An array of Tweet objects parsed from the conversation\n */\nexport function parseThreadedConversation(\n conversation: ThreadedConversation,\n): Tweet[] {\n const tweets: Tweet[] = [];\n const instructions =\n conversation.data?.threaded_conversation_with_injections_v2?.instructions ??\n [];\n\n for (const instruction of instructions) {\n const entries = instruction.entries ?? [];\n for (const entry of entries) {\n const entryContent = entry.content?.itemContent;\n if (entryContent) {\n parseAndPush(tweets, entryContent, entry.entryId, true);\n }\n\n for (const item of entry.content?.items ?? []) {\n const itemContent = item.item?.itemContent;\n if (itemContent) {\n parseAndPush(tweets, itemContent, entry.entryId, true);\n }\n }\n }\n }\n\n for (const tweet of tweets) {\n if (tweet.inReplyToStatusId) {\n for (const parentTweet of tweets) {\n if (parentTweet.id === tweet.inReplyToStatusId) {\n tweet.inReplyToStatus = parentTweet;\n break;\n }\n }\n }\n\n if (tweet.isSelfThread && tweet.conversationId === tweet.id) {\n for (const childTweet of tweets) {\n if (childTweet.isSelfThread && childTweet.id !== tweet.id) {\n tweet.thread.push(childTweet);\n }\n }\n\n if (tweet.thread.length === 0) {\n tweet.isSelfThread = false;\n }\n }\n }\n\n return tweets;\n}\n\n/**\n * Interface representing a timeline article.\n * @typedef {Object} TimelineArticle\n * @property {string} id - The unique identifier for the article.\n * @property {string} articleId - The identifier for the article.\n * @property {string} title - The title of the article.\n * @property {string} previewText - The preview text of the article.\n * @property {string} [coverMediaUrl] - The URL of the cover media for the article. (Optional)\n * @property {string} text - The main text content of the article.\n */\nexport interface TimelineArticle {\n id: string;\n articleId: string;\n title: string;\n previewText: string;\n coverMediaUrl?: string;\n text: string;\n}\n\n/**\n * Parses a ThreadedConversation object to extract TimelineArticle objects.\n *\n * @param {ThreadedConversation} conversation - The ThreadedConversation object to parse.\n * @returns {TimelineArticle[]} The extracted TimelineArticle objects.\n */\nexport function parseArticle(\n conversation: ThreadedConversation,\n): TimelineArticle[] {\n const articles: TimelineArticle[] = [];\n for (const instruction of conversation.data\n ?.threaded_conversation_with_injections_v2?.instructions ?? []) {\n for (const entry of instruction.entries ?? []) {\n const id = entry.content?.itemContent?.tweet_results?.result?.rest_id;\n const article =\n entry.content?.itemContent?.tweet_results?.result?.article\n ?.article_results?.result;\n if (!id || !article) continue;\n const text =\n article.content_state?.blocks\n ?.map((block) => block.text)\n .join(\"\\n\\n\") ?? \"\";\n articles.push({\n id,\n articleId: article.rest_id || \"\",\n coverMediaUrl: article.cover_media?.media_info?.original_img_url,\n previewText: article.preview_text || \"\",\n text,\n title: article.title || \"\",\n });\n }\n }\n return articles;\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 { addApiFeatures } from \"./api\";\nimport type { TwitterAuth } from \"./auth\";\nimport { getEntityIdByScreenName } from \"./profile\";\nimport { getTweetTimeline } from \"./timeline-async\";\nimport type { QueryTweetsResponse } from \"./timeline-v1\";\nimport {\n type TimelineArticle,\n type TimelineEntryItemContentRaw,\n} from \"./timeline-v2\";\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 const features = addApiFeatures({\n interactive_text_enabled: true,\n longform_notetweets_inline_media_enabled: false,\n responsive_web_text_conversations_enabled: false,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n false,\n vibe_api_enabled: false,\n});\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}`);\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}`);\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 defaultTweetData?: Tweet | null,\n): Tweet {\n let parsedTweet: Tweet;\n if (defaultTweetData != null) {\n parsedTweet = defaultTweetData;\n }\n parsedTweet = {\n id: tweetV2.id,\n text: tweetV2.text ?? defaultTweetData?.text ?? \"\",\n hashtags:\n tweetV2.entities?.hashtags?.map((tag) => tag.tag) ??\n defaultTweetData?.hashtags ??\n [],\n mentions:\n tweetV2.entities?.mentions?.map((mention) => ({\n id: mention.id,\n username: mention.username,\n })) ??\n defaultTweetData?.mentions ??\n [],\n urls:\n tweetV2.entities?.urls?.map((url) => url.url) ??\n defaultTweetData?.urls ??\n [],\n likes: tweetV2.public_metrics?.like_count ?? defaultTweetData?.likes ?? 0,\n retweets:\n tweetV2.public_metrics?.retweet_count ?? defaultTweetData?.retweets ?? 0,\n replies:\n tweetV2.public_metrics?.reply_count ?? defaultTweetData?.replies ?? 0,\n views:\n tweetV2.public_metrics?.impression_count ?? defaultTweetData?.views ?? 0,\n userId: tweetV2.author_id ?? defaultTweetData?.userId,\n conversationId: tweetV2.conversation_id ?? defaultTweetData?.conversationId,\n photos: defaultTweetData?.photos ?? [],\n videos: defaultTweetData?.videos ?? [],\n poll: defaultTweetData?.poll ?? null,\n username: defaultTweetData?.username ?? \"\",\n name: defaultTweetData?.name ?? \"\",\n place: defaultTweetData?.place,\n thread: defaultTweetData?.thread ?? [],\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 ? poll.end_datetime\n : defaultTweetData?.poll?.end_datetime\n ? defaultTweetData?.poll?.end_datetime\n : undefined,\n options: poll.options.map((option) => ({\n position: option.position,\n label: option.label,\n votes: option.votes,\n })),\n voting_status:\n poll.voting_status ?? defaultTweetData?.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 ?? defaultTweetData?.username ?? \"\";\n parsedTweet.name = user.name ?? defaultTweetData?.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 ?? defaultTweetData?.place?.full_name ?? \"\",\n country: place.country ?? defaultTweetData?.place?.country ?? \"\",\n country_code:\n place.country_code ?? defaultTweetData?.place?.country_code ?? \"\",\n name: place.name ?? defaultTweetData?.place?.name ?? \"\",\n place_type: place.place_type ?? defaultTweetData?.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}`);\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 function getTweets(\n user: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n return getTweetTimeline(user, maxTweets, async (q, mt, c) => {\n const userIdRes = await getEntityIdByScreenName(q, auth);\n\n if (!userIdRes.success) {\n throw (userIdRes as any).err;\n }\n\n const { value: userId } = userIdRes;\n\n return fetchTweets(userId, mt, c, auth);\n });\n}\n\nexport function getTweetsByUserId(\n userId: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n return getTweetTimeline(userId, maxTweets, (q, mt, c) => {\n return fetchTweets(q, mt, c, auth);\n });\n}\n\nexport function getTweetsAndReplies(\n user: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n return getTweetTimeline(user, maxTweets, async (q, mt, c) => {\n const userIdRes = await getEntityIdByScreenName(q, auth);\n\n if (!userIdRes.success) {\n throw (userIdRes as any).err;\n }\n\n const { value: userId } = userIdRes;\n\n return fetchTweetsAndReplies(userId, mt, c, auth);\n });\n}\n\nexport function getTweetsAndRepliesByUserId(\n userId: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n return getTweetTimeline(userId, maxTweets, (q, mt, c) => {\n return fetchTweetsAndReplies(q, mt, c, auth);\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\nexport interface TweetResultByRestId {\n data?: TimelineEntryItemContentRaw;\n}\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 const defaultTweetData = await getTweet(tweetData.data.id, auth);\n // Extract primary tweet data\n const parsedTweet = parseTweetV2ToV1(\n tweetData.data,\n tweetData?.includes,\n defaultTweetData,\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\nexport async function getArticle(\n id: string,\n auth: TwitterAuth,\n): Promise<TimelineArticle | null> {\n // Twitter API v2 doesn't have a separate article endpoint\n // Articles are part of regular tweets\n const tweet = await getTweet(id, auth);\n\n if (!tweet) {\n return null;\n }\n\n // Return a minimal article representation with all required fields\n return {\n id: tweet.id || id,\n articleId: id,\n title: \"\",\n previewText: tweet.text?.substring(0, 100) || \"\",\n text: tweet.text || \"\",\n };\n}\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 RequestApiResult,\n requestApi,\n} from \"./api\";\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 fetchSearchProfiles,\n fetchSearchTweets,\n searchProfiles,\n searchTweets,\n searchQuotedTweets,\n} from \"./search\";\nimport { fetchFollowingTimeline } from \"./timeline-following\";\nimport { fetchHomeTimeline } from \"./timeline-home\";\nimport type { QueryProfilesResponse, QueryTweetsResponse } from \"./timeline-v1\";\nimport {\n type TimelineArticle,\n type TimelineV2,\n parseTimelineTweetsV2,\n} from \"./timeline-v2\";\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 getArticle,\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} from \"./tweets\";\n\nconst twUrl = \"https://twitter.com\";\nconst UserTweetsUrl =\n \"https://twitter.com/i/api/graphql/E3opETHurmVJflFsUBVuUQ/UserTweets\";\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 fetchSearchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n cursor?: string,\n ): Promise<QueryTweetsResponse> {\n return fetchSearchTweets(query, maxTweets, searchMode, this.auth, cursor);\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 fetchSearchProfiles(\n query: string,\n maxProfiles: number,\n cursor?: string,\n ): Promise<QueryProfilesResponse> {\n return fetchSearchProfiles(query, maxProfiles, this.auth, cursor);\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. (for you feed)\n * @param count The number of tweets to fetch.\n * @param seenTweetIds An array of tweet IDs that have already been seen.\n * @returns A promise that resolves to the home timeline response.\n */\n public async fetchHomeTimeline(\n count: number,\n seenTweetIds: string[],\n ): Promise<any[]> {\n return await fetchHomeTimeline(count, seenTweetIds, this.auth);\n }\n\n /**\n * Fetches the home timeline for the current user. (following feed)\n * @param count The number of tweets to fetch.\n * @param seenTweetIds An array of tweet IDs that have already been seen.\n * @returns A promise that resolves to the home timeline response.\n */\n public async fetchFollowingTimeline(\n count: number,\n seenTweetIds: string[],\n ): Promise<any[]> {\n return await fetchFollowingTimeline(count, seenTweetIds, this.auth);\n }\n\n async getUserTweets(\n userId: string,\n maxTweets = 200,\n cursor?: string,\n ): Promise<{ tweets: Tweet[]; next?: string }> {\n if (maxTweets > 200) {\n maxTweets = 200;\n }\n\n const variables: Record<string, any> = {\n userId,\n count: maxTweets,\n includePromotedContent: true,\n withQuickPromoteEligibilityTweetFields: true,\n withVoice: true,\n withV2Timeline: true,\n };\n\n if (cursor) {\n variables.cursor = cursor;\n }\n\n const features = {\n rweb_tipjar_consumption_enabled: true,\n responsive_web_graphql_exclude_directive_enabled: true,\n verified_phone_label_enabled: false,\n creator_subscriptions_tweet_preview_api_enabled: true,\n responsive_web_graphql_timeline_navigation_enabled: true,\n responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,\n communities_web_enable_tweet_community_results_fetch: true,\n c9s_tweet_anatomy_moderator_badge_enabled: true,\n articles_preview_enabled: true,\n responsive_web_edit_tweet_api_enabled: true,\n graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,\n view_counts_everywhere_api_enabled: true,\n longform_notetweets_consumption_enabled: true,\n responsive_web_twitter_article_tweet_consumption_enabled: true,\n tweet_awards_web_tipping_enabled: false,\n creator_subscriptions_quote_tweet_preview_enabled: false,\n freedom_of_speech_not_reach_fetch_enabled: true,\n standardized_nudges_misinfo: true,\n tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled:\n true,\n rweb_video_timestamps_enabled: true,\n longform_notetweets_rich_text_read_enabled: true,\n longform_notetweets_inline_media_enabled: true,\n responsive_web_enhance_cards_enabled: false,\n };\n\n const fieldToggles = {\n withArticlePlainText: false,\n };\n\n const res = await requestApi<TimelineV2>(\n `${UserTweetsUrl}?variables=${encodeURIComponent(\n JSON.stringify(variables),\n )}&features=${encodeURIComponent(JSON.stringify(features))}&fieldToggles=${encodeURIComponent(\n JSON.stringify(fieldToggles),\n )}`,\n this.auth,\n );\n\n if (!res.success) {\n throw (res as any).err;\n }\n\n const timelineV2 = parseTimelineTweetsV2(res.value);\n return {\n tweets: timelineV2.tweets,\n next: timelineV2.next,\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 * Sets the optional cookie to be used in requests.\n * @param _cookie The cookie to be used in requests.\n * @deprecated This function no longer represents any part of Twitter's auth flow.\n * @returns This client instance.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n public withCookie(_cookie: string): Client {\n console.warn(\n \"Warning: Client#withCookie is deprecated and will be removed in a later version. Use Client#login or Client#setCookies instead.\",\n );\n return this;\n }\n\n /**\n * Sets the optional CSRF token to be used in requests.\n * @param _token The CSRF token to be used in requests.\n * @deprecated This function no longer represents any part of Twitter's auth flow.\n * @returns This client instance.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n public withXCsrfToken(_token: string): Client {\n console.warn(\n \"Warning: Client#withXCsrfToken is deprecated and will be removed in a later version.\",\n );\n return this;\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 * Fetches a article (long form tweet) by its ID.\n * @param id The ID of the article to fetch. In the format of (http://x.com/i/article/id)\n * @returns The {@link TimelineArticle} object, or `null` if it couldn't be fetched.\n */\n public getArticle(id: string): Promise<TimelineArticle | null> {\n return getArticle(id, this.auth);\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","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 {\n ChannelType,\n type Content,\n ContentType,\n EventType,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type MessagePayload,\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 } 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// Add conversion functions\nconst convertToCoreTweet = (tweet: ClientTweet): CoreTweet => ({\n id: tweet.id,\n text: tweet.text,\n conversationId: tweet.conversationId,\n timestamp: tweet.timestamp,\n userId: tweet.userId,\n username: tweet.username,\n name: tweet.name,\n inReplyToStatusId: tweet.inReplyToStatusId,\n permanentUrl: tweet.permanentUrl,\n photos: tweet.photos,\n hashtags: tweet.hashtags,\n mentions: tweet.mentions.map((mention) => mention.username),\n urls: tweet.urls,\n videos: tweet.videos,\n thread: tweet.thread,\n});\n\nconst convertToCoreTweets = (tweets: ClientTweet[]): CoreTweet[] =>\n tweets.map(convertToCoreTweet);\n\n/**\n * Class representing a client for interacting with Twitter.\n */\nexport class TwitterInteractionClient {\n client: ClientBase;\n runtime: IAgentRuntime;\n private isDryRun: boolean;\n private state: any;\n /**\n * Constructor for setting up a new instance with the provided client, runtime, and state.\n * @param {ClientBase} client - The client being used for communication.\n * @param {IAgentRuntime} runtime - The runtime environment for the agent.\n * @param {any} state - The initial state of the agent.\n */\n constructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n this.client = client;\n this.runtime = runtime;\n this.state = state;\n this.isDryRun =\n this.state?.TWITTER_DRY_RUN ||\n (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 an interval based on the 'TWITTER_POLL_INTERVAL' setting, or defaults to 2 minutes if not set.\n */\n async start() {\n const handleTwitterInteractionsLoop = () => {\n // Defaults to 2 minutes\n const interactionInterval =\n (this.state?.TWITTER_POLL_INTERVAL ||\n (this.runtime.getSetting(\n \"TWITTER_POLL_INTERVAL\",\n ) as unknown as number) ||\n 120) * 1000;\n\n this.handleTwitterInteractions();\n setTimeout(handleTwitterInteractionsLoop, interactionInterval);\n };\n handleTwitterInteractionsLoop();\n }\n\n /**\n * Asynchronously handles Twitter interactions by checking for mentions, processing tweets, and updating the last checked tweet ID.\n */\n async handleTwitterInteractions() {\n logger.log(\"Checking Twitter interactions\");\n\n const twitterUsername = this.client.profile?.username;\n try {\n // Check for mentions\n const cursorKey = `twitter/${twitterUsername}/mention_cursor`;\n const cachedCursor: String =\n 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, \"\"); // used to be null, but DB doesn't allow it\n }\n\n await this.processMentionTweets(mentionCandidates);\n\n // 2. Format mentions into interactions\n // TODO: EventType.REACTION_RECEIVED are not fully handled yet, re-enable once properly processed\n // const interactionCandidates = mentionCandidates\n // .map((tweet) => this.client.formatTweetToInteraction?.(tweet))\n // .filter((i) => i?.targetTweet?.conversationId);\n\n // for (const interaction of interactionCandidates) {\n // try {\n // await this.handleInteraction(interaction);\n // } catch (error) {\n // logger.erro(`Failed to process interaction ${interaction.id}`)\n // }\n // }\n\n // For follower changes:\n // const processFollowerChange = async (\n // change: { type: string; userId: string },\n // profileId: string | undefined\n // ) => {\n // if (change?.type && change?.userId && profileId) {\n // const followerMemory = this.createMemoryObject(\n // change.type,\n // `${change.type}-${change.userId}`,\n // change.userId,\n // profileId\n // );\n\n // await this.runtime.createMemory(followerMemory, 'follower-changes');\n // }\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 * 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 // for each tweet candidate, handle the tweet\n for (const tweet of uniqueTweetCandidates) {\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?.source === \"twitter\" &&\n memory.agentId === this.runtime.agentId &&\n memory.content?.inReplyTo === tweetId),\n );\n\n if (hasExistingReply) {\n logger.log(\n `Already replied to tweet ${tweet.id} (found existing reply), skipping`,\n );\n continue;\n }\n logger.log(\"New Tweet found\", tweet.permanentUrl);\n\n const entityId = createUniqueUuid(\n this.runtime,\n tweet.userId === this.client.profile.id\n ? this.runtime.agentId\n : tweet.userId,\n );\n\n // Create standardized world and room IDs\n const worldId = createUniqueUuid(this.runtime, tweet.userId);\n const roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: tweet.username,\n worldName: `${tweet.name}'s Twitter`,\n name: tweet.name,\n source: \"twitter\",\n type: ChannelType.GROUP,\n channelId: tweet.conversationId,\n serverId: tweet.userId,\n worldId: 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 // Create standardized message memory\n const memory: Memory = {\n id: tweetId,\n agentId: this.runtime.agentId,\n content: {\n text: tweet.text,\n url: tweet.permanentUrl,\n attachments:\n tweet.photos?.map((photo, index) => ({\n id: photo.id,\n url: photo.url,\n contentType: ContentType.IMAGE, // TODO: check if we can read this.\n })) || [],\n inReplyTo: tweet.inReplyToStatusId\n ? createUniqueUuid(this.runtime, tweet.inReplyToStatusId)\n : undefined,\n source: \"twitter\",\n channelType: ChannelType.GROUP,\n tweet,\n },\n entityId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n };\n await this.runtime.createMemory(memory, \"messages\");\n\n // Emit mention received events\n // TODO: Handle MENTION_RECEIVED event correctly before enabling again\n // if (tweet.text.includes(`@${twitterUsername}`)) {\n // const messagePayload: MessagePayload = {\n // runtime: this.runtime,\n // message: {\n // ...memory,\n // source: 'twitter',\n // } as TwitterMemory,\n // source: 'twitter',\n // callback: async (response) => {\n // logger.info('Received message response:', response);\n // return [];\n // },\n // };\n\n // // Emit platform-specific MENTION_RECEIVED event\n // const mentionPayload: TwitterMentionReceivedPayload = {\n // runtime: this.runtime,\n // message: {\n // ...memory,\n // source: 'twitter',\n // } as TwitterMemory,\n // tweet: convertToCoreTweet(tweet),\n // user: {\n // id: tweet.userId,\n // username: tweet.username,\n // name: tweet.name,\n // },\n // source: 'twitter',\n // callback: async (response) => {\n // logger.info('Received mention response:', response);\n // return [];\n // },\n // };\n\n // this.runtime.emitEvent(TwitterEventTypes.MENTION_RECEIVED, mentionPayload);\n // }\n\n // Handle thread events\n if (tweet.thread.length > 1) {\n const threadPayload = {\n runtime: this.runtime,\n tweets: convertToCoreTweets(tweet.thread),\n user: {\n id: tweet.userId,\n username: tweet.username,\n name: tweet.name,\n },\n source: \"twitter\",\n };\n\n if (tweet.thread[tweet.thread.length - 1].id === tweet.id) {\n // This is a new tweet in an existing thread\n this.runtime.emitEvent(TwitterEventTypes.THREAD_UPDATED, {\n ...threadPayload,\n newTweet: convertToCoreTweet(tweet),\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(\n this.runtime,\n interaction.targetTweet.userId,\n ),\n roomId: createUniqueUuid(\n this.runtime,\n interaction.targetTweet.conversationId,\n ),\n agentId: this.runtime.agentId,\n };\n\n // Create base event payload\n const basePayload = {\n runtime: this.runtime,\n user: {\n id: interaction.userId,\n username: interaction.username,\n name: interaction.name,\n },\n source: \"twitter\" as const,\n };\n\n // Emit platform-specific event\n switch (interaction.type) {\n case \"like\": {\n const likePayload: TwitterLikeReceivedPayload = {\n ...basePayload,\n tweet: interaction.targetTweet as unknown as CoreTweet,\n };\n // Emit platform-specific event\n this.runtime.emitEvent(TwitterEventTypes.LIKE_RECEIVED, likePayload);\n\n // Emit generic REACTION_RECEIVED event\n this.runtime.emitEvent(EventType.REACTION_RECEIVED, {\n ...basePayload,\n reaction: {\n type: \"like\",\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n },\n message: reactionMessage,\n callback: async () => {\n return [];\n },\n } as MessagePayload);\n break;\n }\n\n case \"retweet\": {\n const retweetPayload: TwitterRetweetReceivedPayload = {\n ...basePayload,\n tweet: interaction.targetTweet as unknown as CoreTweet,\n retweetId: interaction.retweetId,\n };\n // Emit platform-specific event\n this.runtime.emitEvent(\n TwitterEventTypes.RETWEET_RECEIVED,\n retweetPayload,\n );\n\n // Emit generic REACTION_RECEIVED event\n this.runtime.emitEvent(EventType.REACTION_RECEIVED, {\n ...basePayload,\n reaction: {\n type: \"retweet\",\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n },\n message: reactionMessage,\n callback: async () => {\n return [];\n },\n } as MessagePayload);\n break;\n }\n\n case \"quote\": {\n const quotePayload: TwitterQuoteReceivedPayload = {\n ...basePayload,\n message: reactionMessage,\n quotedTweet: interaction.targetTweet as unknown as CoreTweet,\n quoteTweet: (interaction.quoteTweet ||\n interaction.targetTweet) as unknown as CoreTweet,\n callback: async () => [],\n reaction: {\n type: \"quote\",\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n },\n };\n // Emit platform-specific event\n this.runtime.emitEvent(\n TwitterEventTypes.QUOTE_RECEIVED,\n quotePayload,\n );\n\n // Emit generic REACTION_RECEIVED event\n this.runtime.emitEvent(EventType.REACTION_RECEIVED, {\n ...basePayload,\n reaction: {\n type: \"quote\",\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n },\n message: reactionMessage,\n callback: async () => {\n return [];\n },\n } as MessagePayload);\n break;\n }\n }\n }\n }\n\n /**\n * Handles a tweet by processing its content, formatting it, generating image descriptions,\n * saving the tweet if it doesn't already exist, determining if a response should be sent,\n * composing a response prompt, generating a response based on the prompt, handling the response\n * tweet, and saving information about the response.\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.rest_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 // Save the response to memory\n await this.runtime.createMemory(responseMemory, \"messages\");\n\n return [responseMemory];\n } catch (error) {\n logger.error(\"Error replying to tweet:\", error);\n return [];\n }\n };\n\n // Emit standardized event for handling the message\n this.runtime.emitEvent(EventType.MESSAGE_RECEIVED, {\n runtime: this.runtime,\n message,\n callback,\n source: \"twitter\",\n } as MessagePayload);\n\n return { text: \"\", actions: [\"RESPOND\"] };\n }\n\n /**\n * Build a conversation thread based on a given tweet.\n *\n * @param {Tweet} tweet - The tweet to start the thread from.\n * @param {number} [maxReplies=10] - The maximum number of replies to include in the thread.\n * @returns {Promise<Tweet[]>} The conversation thread as an array of tweets.\n */\n async buildConversationThread(\n tweet: ClientTweet,\n maxReplies = 10,\n ): Promise<ClientTweet[]> {\n const thread: ClientTweet[] = [];\n const visited: Set<string> = new Set();\n\n async function processThread(currentTweet: ClientTweet, depth = 0) {\n logger.log(\"Processing tweet:\", {\n id: currentTweet.id,\n inReplyToStatusId: currentTweet.inReplyToStatusId,\n depth: depth,\n });\n\n if (!currentTweet) {\n logger.log(\"No current tweet found for thread building\");\n return;\n }\n\n if (depth >= maxReplies) {\n logger.log(\"Reached maximum reply depth\", depth);\n return;\n }\n\n // Handle memory storage\n const memory = await this.runtime.getMemoryById(\n createUniqueUuid(this.runtime, currentTweet.id),\n );\n if (!memory) {\n const roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n const entityId = createUniqueUuid(this.runtime, currentTweet.userId);\n\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: currentTweet.username,\n name: currentTweet.name,\n source: \"twitter\",\n type: ChannelType.GROUP,\n worldId: createUniqueUuid(this.runtime, currentTweet.userId),\n worldName: `${currentTweet.name}'s Twitter`,\n });\n\n this.runtime.createMemory(\n {\n id: createUniqueUuid(this.runtime, currentTweet.id),\n agentId: this.runtime.agentId,\n content: {\n text: currentTweet.text,\n source: \"twitter\",\n url: currentTweet.permanentUrl,\n imageUrls: currentTweet.photos?.map((photo) => photo.url) || [],\n inReplyTo: currentTweet.inReplyToStatusId\n ? createUniqueUuid(this.runtime, currentTweet.inReplyToStatusId)\n : undefined,\n },\n createdAt: currentTweet.timestamp * 1000,\n roomId,\n entityId:\n currentTweet.userId === this.twitterUserId\n ? this.runtime.agentId\n : createUniqueUuid(this.runtime, currentTweet.userId),\n },\n \"messages\",\n );\n }\n\n if (visited.has(currentTweet.id)) {\n logger.log(\"Already visited tweet:\", currentTweet.id);\n return;\n }\n\n visited.add(currentTweet.id);\n thread.unshift(currentTweet);\n\n if (currentTweet.inReplyToStatusId) {\n logger.log(\"Fetching parent tweet:\", currentTweet.inReplyToStatusId);\n try {\n const parentTweet = await this.twitterClient.getTweet(\n currentTweet.inReplyToStatusId,\n );\n\n if (parentTweet) {\n logger.log(\"Found parent tweet:\", {\n id: parentTweet.id,\n text: parentTweet.text?.slice(0, 50),\n });\n await processThread(parentTweet, depth + 1);\n } else {\n logger.log(\n \"No parent tweet found for:\",\n currentTweet.inReplyToStatusId,\n );\n }\n } catch (error) {\n logger.log(\"Error fetching parent tweet:\", {\n tweetId: currentTweet.inReplyToStatusId,\n error,\n });\n }\n } else {\n logger.log(\"Reached end of reply chain at:\", currentTweet.id);\n }\n }\n\n // Need to bind this prompt for the inner function\n await processThread.bind(this)(tweet, 0);\n\n return thread;\n }\n\n private createMemoryObject(\n type: string,\n id: string,\n userId: string,\n roomId: 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, roomId),\n content: {\n type,\n source: \"twitter\",\n },\n createdAt: Date.now(),\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","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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{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 * This schema defines all required/optional environment settings.\n */\n/**\n * Schema definition for Twitter environment variables\n */\nexport const twitterEnvSchema = z.object({\n TWITTER_API_KEY: z.string().optional(),\n TWITTER_API_SECRET_KEY: z.string().optional(),\n TWITTER_ACCESS_TOKEN: z.string().optional(),\n TWITTER_ACCESS_TOKEN_SECRET: z.string().optional(),\n TWITTER_TARGET_USERS: z.string().default(\"\"),\n TWITTER_RETRY_LIMIT: z.string().default(\"5\"),\n TWITTER_POLL_INTERVAL: z.string().default(\"120\"),\n TWITTER_SEARCH_ENABLE: z.string().default(\"true\"),\n TWITTER_DRY_RUN: z.string().default(\"false\"),\n TWITTER_POST_ENABLE: z.string().default(\"false\"),\n TWITTER_POST_INTERVAL_MIN: z.string().default(\"90\"),\n TWITTER_POST_INTERVAL_MAX: z.string().default(\"180\"),\n TWITTER_POST_IMMEDIATELY: z.string().default(\"false\"),\n TWITTER_INTERACTION_INTERVAL_MIN: z.string().default(\"15\"),\n TWITTER_INTERACTION_INTERVAL_MAX: z.string().default(\"30\"),\n TWITTER_TIMELINE_ALGORITHM: z\n .enum([\"latest\", \"weighted\"])\n .default(\"weighted\"),\n TWITTER_TIMELINE_USER_BASED_WEIGHT: z.string().default(\"3\"),\n TWITTER_TIMELINE_TIME_BASED_WEIGHT: z.string().default(\"2\"),\n TWITTER_TIMELINE_RELEVANCE_WEIGHT: z.string().default(\"5\"),\n TWITTER_MAX_TWEET_LENGTH: z.string().default(\"4000\"),\n TWITTER_MAX_INTERACTIONS_PER_RUN: z.string().default(\"10\"),\n TWITTER_DM_ONLY: z.string().default(\"false\"),\n TWITTER_ENABLE_ACTION_PROCESSING: z.string().default(\"false\"),\n TWITTER_ACTION_INTERVAL: z.string().default(\"240\"),\n TWITTER_AUTO_RESPOND_MENTIONS: z.string().default(\"true\"),\n TWITTER_AUTO_RESPOND_REPLIES: z.string().default(\"true\"),\n TWITTER_POST_INTERVAL_VARIANCE: z.string().default(\"0.2\"),\n TWITTER_INTERACTION_INTERVAL_VARIANCE: z.string().default(\"0.3\"),\n});\n\nexport type TwitterConfig = z.infer<typeof twitterEnvSchema>;\n\n/**\n * Helper to parse a comma-separated list of Twitter usernames\n * (already present in your code).\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 based on TWITTER_TARGET_USERS\n * Supports wildcard \"*\" to target all users\n */\nexport function shouldTargetUser(\n username: string,\n targetUsersConfig: string,\n): boolean {\n if (!targetUsersConfig?.trim()) {\n return true; // If no target users specified, interact with everyone\n }\n\n const targetUsers = parseTargetUsers(targetUsersConfig);\n\n // If wildcard is specified, target everyone\n if (targetUsers.includes(\"*\")) {\n return true;\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\nfunction safeParseInt(\n value: string | undefined | null,\n defaultValue: number,\n): number {\n if (!value) return defaultValue;\n const parsed = Number.parseInt(value, 10);\n return Number.isNaN(parsed) ? defaultValue : Math.max(1, parsed);\n}\n\n/**\n * Validates or constructs a TwitterConfig object using zod,\n * taking values from the IAgentRuntime or process.env as needed.\n */\n// This also is organized to serve as a point of documentation for the client\n// most of the inputs from the framework (env/character)\n\n// we also do a lot of typing/prompt here\n// so we can do it once and only once per character\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 targetUsersStr = getConfig(\"TWITTER_TARGET_USERS\");\n const targetUsers = parseTargetUsers(targetUsersStr) || [];\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:\n getConfig(\"TWITTER_ACCESS_TOKEN_SECRET\") || \"\",\n TWITTER_TARGET_USERS: targetUsersStr || \"\",\n TWITTER_RETRY_LIMIT: String(\n safeParseInt(getConfig(\"TWITTER_RETRY_LIMIT\"), 5),\n ),\n TWITTER_POLL_INTERVAL: String(\n safeParseInt(getConfig(\"TWITTER_POLL_INTERVAL\"), 120),\n ),\n TWITTER_SEARCH_ENABLE: String(\n getConfig(\"TWITTER_SEARCH_ENABLE\") !== undefined\n ? getConfig(\"TWITTER_SEARCH_ENABLE\")?.toLowerCase() === \"true\"\n : true, // Default to true when not set\n ),\n TWITTER_DRY_RUN: String(\n getConfig(\"TWITTER_DRY_RUN\")?.toLowerCase() === \"true\",\n ),\n TWITTER_POST_ENABLE: String(\n getConfig(\"TWITTER_POST_ENABLE\")?.toLowerCase() === \"true\",\n ),\n TWITTER_POST_INTERVAL_MIN: String(\n safeParseInt(getConfig(\"TWITTER_POST_INTERVAL_MIN\"), 90),\n ),\n TWITTER_POST_INTERVAL_MAX: String(\n safeParseInt(getConfig(\"TWITTER_POST_INTERVAL_MAX\"), 180),\n ),\n TWITTER_POST_IMMEDIATELY: String(\n getConfig(\"TWITTER_POST_IMMEDIATELY\")?.toLowerCase() === \"true\",\n ),\n TWITTER_INTERACTION_INTERVAL_MIN: String(\n safeParseInt(getConfig(\"TWITTER_INTERACTION_INTERVAL_MIN\"), 15),\n ),\n TWITTER_INTERACTION_INTERVAL_MAX: String(\n safeParseInt(getConfig(\"TWITTER_INTERACTION_INTERVAL_MAX\"), 30),\n ),\n TWITTER_TIMELINE_ALGORITHM: (getConfig(\"TWITTER_TIMELINE_ALGORITHM\") ===\n \"latest\"\n ? \"latest\"\n : \"weighted\") as \"latest\" | \"weighted\",\n TWITTER_TIMELINE_USER_BASED_WEIGHT: String(\n safeParseInt(getConfig(\"TWITTER_TIMELINE_USER_BASED_WEIGHT\"), 3),\n ),\n TWITTER_TIMELINE_TIME_BASED_WEIGHT: String(\n safeParseInt(getConfig(\"TWITTER_TIMELINE_TIME_BASED_WEIGHT\"), 2),\n ),\n TWITTER_TIMELINE_RELEVANCE_WEIGHT: String(\n safeParseInt(getConfig(\"TWITTER_TIMELINE_RELEVANCE_WEIGHT\"), 5),\n ),\n TWITTER_MAX_TWEET_LENGTH: String(\n safeParseInt(getConfig(\"TWITTER_MAX_TWEET_LENGTH\"), 4000),\n ),\n TWITTER_MAX_INTERACTIONS_PER_RUN: String(\n safeParseInt(getConfig(\"TWITTER_MAX_INTERACTIONS_PER_RUN\"), 10),\n ),\n TWITTER_DM_ONLY: String(\n getConfig(\"TWITTER_DM_ONLY\")?.toLowerCase() === \"true\",\n ),\n TWITTER_ENABLE_ACTION_PROCESSING: String(\n getConfig(\"TWITTER_ENABLE_ACTION_PROCESSING\")?.toLowerCase() === \"true\",\n ),\n TWITTER_ACTION_INTERVAL: String(\n safeParseInt(getConfig(\"TWITTER_ACTION_INTERVAL\"), 240),\n ),\n TWITTER_AUTO_RESPOND_MENTIONS: String(\n getConfig(\"TWITTER_AUTO_RESPOND_MENTIONS\")?.toLowerCase() === \"true\",\n ),\n TWITTER_AUTO_RESPOND_REPLIES: String(\n getConfig(\"TWITTER_AUTO_RESPOND_REPLIES\")?.toLowerCase() === \"true\",\n ),\n TWITTER_POST_INTERVAL_VARIANCE: String(\n Number(getConfig(\"TWITTER_POST_INTERVAL_VARIANCE\") || \"0.2\"),\n ),\n TWITTER_INTERACTION_INTERVAL_VARIANCE: String(\n Number(getConfig(\"TWITTER_INTERACTION_INTERVAL_VARIANCE\") || \"0.3\"),\n ),\n };\n\n // Only require API keys, not username/password\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 const errorMessage =\n error instanceof z.ZodError\n ? error.errors.map((e) => e.message).join(\", \")\n : error instanceof Error\n ? error.message\n : \"Unknown error\";\n throw new Error(`Twitter configuration validation failed: ${errorMessage}`);\n }\n}\n\n/**\n * Load configuration from file\n * @param configPath - Path to the configuration file (optional)\n * @returns 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 * 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 // Required API credentials\n if (getConfig(\"TWITTER_API_KEY\")) {\n config.TWITTER_API_KEY = getConfig(\"TWITTER_API_KEY\");\n }\n if (getConfig(\"TWITTER_API_SECRET_KEY\")) {\n config.TWITTER_API_SECRET_KEY = getConfig(\"TWITTER_API_SECRET_KEY\");\n }\n if (getConfig(\"TWITTER_ACCESS_TOKEN\")) {\n config.TWITTER_ACCESS_TOKEN = getConfig(\"TWITTER_ACCESS_TOKEN\");\n }\n if (getConfig(\"TWITTER_ACCESS_TOKEN_SECRET\")) {\n config.TWITTER_ACCESS_TOKEN_SECRET = getConfig(\n \"TWITTER_ACCESS_TOKEN_SECRET\",\n );\n }\n\n // Optional settings\n if (getConfig(\"TWITTER_TARGET_USERS\")) {\n config.TWITTER_TARGET_USERS = getConfig(\"TWITTER_TARGET_USERS\");\n }\n if (getConfig(\"TWITTER_RETRY_LIMIT\")) {\n config.TWITTER_RETRY_LIMIT = getConfig(\"TWITTER_RETRY_LIMIT\");\n }\n if (getConfig(\"TWITTER_POLL_INTERVAL\")) {\n config.TWITTER_POLL_INTERVAL = getConfig(\"TWITTER_POLL_INTERVAL\");\n }\n if (getConfig(\"TWITTER_SEARCH_ENABLE\")) {\n config.TWITTER_SEARCH_ENABLE = getConfig(\"TWITTER_SEARCH_ENABLE\");\n }\n if (getConfig(\"TWITTER_DRY_RUN\")) {\n config.TWITTER_DRY_RUN = getConfig(\"TWITTER_DRY_RUN\");\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_TARGET_USERS: getConfig(\"TWITTER_TARGET_USERS\") || \"\",\n TWITTER_RETRY_LIMIT: getConfig(\"TWITTER_RETRY_LIMIT\") || \"5\",\n TWITTER_POLL_INTERVAL: getConfig(\"TWITTER_POLL_INTERVAL\") || \"120\",\n TWITTER_SEARCH_ENABLE: getConfig(\"TWITTER_SEARCH_ENABLE\") || \"true\",\n TWITTER_DRY_RUN: getConfig(\"TWITTER_DRY_RUN\") || \"false\",\n TWITTER_POST_ENABLE: getConfig(\"TWITTER_POST_ENABLE\") || \"false\",\n TWITTER_POST_INTERVAL_MIN: getConfig(\"TWITTER_POST_INTERVAL_MIN\") || \"90\",\n TWITTER_POST_INTERVAL_MAX: getConfig(\"TWITTER_POST_INTERVAL_MAX\") || \"180\",\n TWITTER_POST_IMMEDIATELY: getConfig(\"TWITTER_POST_IMMEDIATELY\") || \"false\",\n TWITTER_INTERACTION_INTERVAL_MIN:\n getConfig(\"TWITTER_INTERACTION_INTERVAL_MIN\") || \"15\",\n TWITTER_INTERACTION_INTERVAL_MAX:\n getConfig(\"TWITTER_INTERACTION_INTERVAL_MAX\") || \"30\",\n TWITTER_TIMELINE_ALGORITHM: (getConfig(\"TWITTER_TIMELINE_ALGORITHM\") ===\n \"latest\"\n ? \"latest\"\n : \"weighted\") as \"latest\" | \"weighted\",\n TWITTER_TIMELINE_USER_BASED_WEIGHT:\n getConfig(\"TWITTER_TIMELINE_USER_BASED_WEIGHT\") || \"3\",\n TWITTER_TIMELINE_TIME_BASED_WEIGHT:\n getConfig(\"TWITTER_TIMELINE_TIME_BASED_WEIGHT\") || \"2\",\n TWITTER_TIMELINE_RELEVANCE_WEIGHT:\n getConfig(\"TWITTER_TIMELINE_RELEVANCE_WEIGHT\") || \"5\",\n TWITTER_MAX_TWEET_LENGTH: getConfig(\"TWITTER_MAX_TWEET_LENGTH\") || \"4000\",\n TWITTER_MAX_INTERACTIONS_PER_RUN:\n getConfig(\"TWITTER_MAX_INTERACTIONS_PER_RUN\") || \"10\",\n TWITTER_DM_ONLY: getConfig(\"TWITTER_DM_ONLY\") || \"false\",\n TWITTER_ENABLE_ACTION_PROCESSING:\n getConfig(\"TWITTER_ENABLE_ACTION_PROCESSING\") || \"false\",\n TWITTER_ACTION_INTERVAL: getConfig(\"TWITTER_ACTION_INTERVAL\") || \"240\",\n TWITTER_AUTO_RESPOND_MENTIONS:\n getConfig(\"TWITTER_AUTO_RESPOND_MENTIONS\") || \"true\",\n TWITTER_AUTO_RESPOND_REPLIES:\n getConfig(\"TWITTER_AUTO_RESPOND_REPLIES\") || \"true\",\n TWITTER_POST_INTERVAL_VARIANCE:\n getConfig(\"TWITTER_POST_INTERVAL_VARIANCE\") || \"0.2\",\n TWITTER_INTERACTION_INTERVAL_VARIANCE:\n getConfig(\"TWITTER_INTERACTION_INTERVAL_VARIANCE\") || \"0.3\",\n };\n}\n\n/**\n * Load configuration from file\n * @param configPath - Path to configuration file\n * @returns Partial<TwitterConfig>\n */\nfunction loadConfigFromFile(configPath?: string): Partial<TwitterConfig> {\n // This is a placeholder for file-based configuration\n // Implementation would depend on your specific needs\n return {};\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\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 this.isDryRun =\n this.state?.TWITTER_DRY_RUN ||\n (this.runtime.getSetting(\"TWITTER_DRY_RUN\") as unknown as boolean);\n\n // Log configuration on initialization\n logger.log(\"Twitter Client Configuration:\");\n logger.log(`- Dry Run Mode: ${this.isDryRun ? \"Enabled\" : \"Disabled\"}`);\n\n logger.log(\n `- Post Interval: ${this.state?.TWITTER_POST_INTERVAL_MIN || this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MIN\") || 90}-${this.state?.TWITTER_POST_INTERVAL_MAX || this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MAX\") || 180} minutes`,\n );\n logger.log(\n `- Post Immediately: ${\n this.state?.TWITTER_POST_IMMEDIATELY ||\n this.runtime.getSetting(\"TWITTER_POST_IMMEDIATELY\")\n ? \"enabled\"\n : \"disabled\"\n }`,\n );\n\n if (this.isDryRun) {\n logger.log(\n \"Twitter client initialized in dry run mode - no actual tweets should be posted\",\n );\n }\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\n const generateNewTweetLoop = async () => {\n const minPostMinutes =\n this.state?.TWITTER_POST_INTERVAL_MIN ||\n this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MIN\") ||\n 90;\n const maxPostMinutes =\n this.state?.TWITTER_POST_INTERVAL_MAX ||\n this.runtime.getSetting(\"TWITTER_POST_INTERVAL_MAX\") ||\n 180;\n const randomMinutes =\n Math.floor(Math.random() * (maxPostMinutes - minPostMinutes + 1)) +\n minPostMinutes;\n const interval = randomMinutes * 60 * 1000;\n\n await this.generateNewTweet();\n setTimeout(generateNewTweetLoop, interval);\n };\n\n // Start the loop after a 1 minute delay to allow other services to initialize\n setTimeout(generateNewTweetLoop, 60 * 1000);\n if (\n this.state?.TWITTER_POST_IMMEDIATELY ||\n this.runtime.getSetting(\"TWITTER_POST_IMMEDIATELY\")\n ) {\n // await 1 second\n await new Promise((resolve) => setTimeout(resolve, 1000));\n await this.generateNewTweet();\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 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 // 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 // Create a callback for handling the actual posting\n const callback: HandlerCallback = async (content: Content) => {\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 // 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 =\n (result as any).rest_id ||\n (result as any).id_str ||\n (result as any).legacy?.id_str;\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 posting tweet:\", error, content);\n return [];\n }\n };\n\n // Emit event to handle the post generation using standard handlers\n this.runtime.emitEvent(\n [EventType.POST_GENERATED, TwitterEventTypes.POST_GENERATED],\n {\n runtime: this.runtime,\n callback,\n worldId,\n userId,\n roomId,\n source: \"twitter\",\n },\n );\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 if (!result) {\n logger.error(\"Error sending tweet; Bad response:\");\n return null;\n }\n\n return result;\n } catch (error) {\n logger.error(\"Error posting to Twitter:\", error);\n throw error;\n }\n }\n\n async stop() {\n // Implement stop functionality if needed\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\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 this.timelineType =\n this.state?.TWITTER_TIMELINE_MODE ||\n this.runtime.getSetting(\"TWITTER_TIMELINE_MODE\");\n }\n\n async start() {\n const handleTwitterTimelineLoop = () => {\n // Defaults to 2 minutes\n const interactionInterval =\n (this.state?.TWITTER_TIMELINE_POLL_INTERVAL ||\n (this.runtime.getSetting(\n \"TWITTER_TIMELINE_POLL_INTERVAL\",\n ) as unknown as number) ||\n 120) * 1000;\n\n this.handleTimeline();\n setTimeout(handleTwitterTimelineLoop, interactionInterval);\n };\n handleTwitterTimelineLoop();\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 return homeTimeline\n .map((tweet) => ({\n id: tweet.rest_id,\n name: tweet.core?.user_results?.result?.legacy?.name,\n username: tweet.core?.user_results?.result?.legacy?.screen_name,\n text: tweet.legacy?.full_text,\n inReplyToStatusId: tweet.legacy?.in_reply_to_status_id_str,\n timestamp: new Date(tweet.legacy?.created_at).getTime() / 1000,\n userId: tweet.legacy?.user_id_str,\n conversationId: tweet.legacy?.conversation_id_str,\n permanentUrl: `https://twitter.com/${tweet.core?.user_results?.result?.legacy?.screen_name}/status/${tweet.rest_id}`,\n hashtags: tweet.legacy?.entities?.hashtags || [],\n mentions: tweet.legacy?.entities?.user_mentions || [],\n photos:\n tweet.legacy?.entities?.media\n ?.filter((media) => media.type === \"photo\")\n .map((media) => ({\n id: media.id_str,\n url: media.media_url_https, // Store media_url_https as url\n alt_text: media.alt_text,\n })) || [],\n thread: tweet.thread || [],\n urls: tweet.legacy?.entities?.urls || [],\n videos:\n tweet.legacy?.entities?.media?.filter(\n (media) => media.type === \"video\",\n ) || [],\n }))\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 console.log(\"Start Hanldeling Twitter Timeline\");\n\n const tweets = await this.getTimeline(20);\n const maxActionsPerCycle = 20;\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 console.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\n if (!actionResponse) {\n logger.log(`No valid actions generated for tweet ${tweet.id}`);\n continue;\n }\n\n const { actions } = parseActionResponseFromText(actionResponse.trim());\n\n tweetDecisions.push({\n tweet: tweet,\n actionResponse: actions,\n tweetState: state,\n roomId: roomId,\n });\n } catch (error) {\n logger.error(`Error processing tweet ${tweet.id}:`, error);\n continue;\n }\n }\n const rankByActionRelevance = (arr) => {\n return arr.sort((a, b) => {\n // Count the number of true values in the actionResponse object\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 this.processTimelineActions(prioritizedTweets);\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 for (const decision of tweetDecisions) {\n const { actionResponse, tweetState, roomId, tweet } = decision;\n const entityId = createUniqueUuid(this.runtime, tweet.userId);\n const worldId = createUniqueUuid(this.runtime, tweet.userId);\n\n await this.ensureTweetWorldContext(tweet, roomId, worldId, entityId);\n\n try {\n const message = this.formMessage(this.runtime, tweet);\n\n await Promise.all([\n this.runtime.addEmbeddingToMemory(message),\n this.runtime.createMemory(message, \"messages\"),\n ]);\n\n // Execute actions\n if (actionResponse.like) {\n this.handleLikeAction(tweet);\n }\n\n if (actionResponse.retweet) {\n this.handleRetweetAction(tweet);\n }\n\n if (actionResponse.quote) {\n this.handleQuoteAction(tweet);\n }\n\n if (actionResponse.reply) {\n this.handleReplyAction(tweet);\n }\n } catch (error) {\n logger.error(`Error processing tweet ${tweet.id}:`, error);\n continue;\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.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 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 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 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?.rest_id || 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 responding 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 const tweetResult = await sendTweet(\n this.client,\n responseObject.post,\n [],\n tweet.id,\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.rest_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 } catch (error) {\n logger.error(\"Error in quote 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","// packages/plugin-twitter/src/tests/ClientBaseTestSuite.ts\n\nimport type { TestSuite } from \"@elizaos/core\";\nimport type { IAgentRuntime } from \"@elizaos/core\";\nimport type { TwitterConfig } from \"./environment\";\nimport { ClientBase } from \"./base\";\n\n/**\n * Test suite for Twitter client base functionality\n */\nexport class ClientBaseTestSuite implements TestSuite {\n name = \"twitter-client-base\";\n\n private mockRuntime: IAgentRuntime;\n private mockConfig: TwitterConfig;\n\n constructor() {\n // Create a mock runtime for tests\n this.mockRuntime = {\n agentId: \"test-agent-id\" as any,\n getSetting: (key: string) => {\n return this.mockConfig[key];\n },\n character: {},\n getCache: async () => null,\n setCache: async () => {},\n getMemoriesByRoomIds: async () => [],\n ensureWorldExists: async () => {},\n ensureConnection: async () => {},\n createMemory: async () => {},\n getEntityById: async () => null,\n updateEntity: async () => {},\n } as any;\n\n // Create test config with only API v2 credentials\n this.mockConfig = {\n TWITTER_API_KEY: \"test-api-key\",\n TWITTER_API_SECRET_KEY: \"test-api-secret\",\n TWITTER_ACCESS_TOKEN: \"test-access-token\",\n TWITTER_ACCESS_TOKEN_SECRET: \"test-access-secret\",\n TWITTER_TARGET_USERS: \"\",\n TWITTER_RETRY_LIMIT: \"5\",\n TWITTER_POLL_INTERVAL: \"120\",\n TWITTER_SEARCH_ENABLE: \"true\",\n TWITTER_DRY_RUN: \"false\",\n TWITTER_POST_ENABLE: \"false\",\n TWITTER_POST_INTERVAL_MIN: \"90\",\n TWITTER_POST_INTERVAL_MAX: \"180\",\n TWITTER_POST_IMMEDIATELY: \"false\",\n TWITTER_INTERACTION_INTERVAL_MIN: \"15\",\n TWITTER_INTERACTION_INTERVAL_MAX: \"30\",\n TWITTER_TIMELINE_ALGORITHM: \"weighted\",\n TWITTER_TIMELINE_USER_BASED_WEIGHT: \"3\",\n TWITTER_TIMELINE_TIME_BASED_WEIGHT: \"2\",\n TWITTER_TIMELINE_RELEVANCE_WEIGHT: \"5\",\n TWITTER_MAX_TWEET_LENGTH: \"4000\",\n TWITTER_MAX_INTERACTIONS_PER_RUN: \"10\",\n TWITTER_DM_ONLY: \"false\",\n TWITTER_ENABLE_ACTION_PROCESSING: \"false\",\n TWITTER_ACTION_INTERVAL: \"240\",\n TWITTER_AUTO_RESPOND_MENTIONS: \"true\",\n TWITTER_AUTO_RESPOND_REPLIES: \"true\",\n TWITTER_POST_INTERVAL_VARIANCE: \"0.2\",\n TWITTER_INTERACTION_INTERVAL_VARIANCE: \"0.3\",\n };\n }\n\n tests = [\n {\n name: \"Create instance with correct configuration\",\n fn: async () => {\n const state = {\n TWITTER_API_KEY: this.mockConfig.TWITTER_API_KEY,\n TWITTER_API_SECRET_KEY: this.mockConfig.TWITTER_API_SECRET_KEY,\n TWITTER_ACCESS_TOKEN: this.mockConfig.TWITTER_ACCESS_TOKEN,\n TWITTER_ACCESS_TOKEN_SECRET:\n this.mockConfig.TWITTER_ACCESS_TOKEN_SECRET,\n };\n const client = new ClientBase(this.mockRuntime, state);\n\n // Verify API credentials are passed to state\n if (client.state.TWITTER_API_KEY !== this.mockConfig.TWITTER_API_KEY) {\n throw new Error(\"Client state TWITTER_API_KEY mismatch.\");\n }\n if (\n client.state.TWITTER_API_SECRET_KEY !==\n this.mockConfig.TWITTER_API_SECRET_KEY\n ) {\n throw new Error(\"Client state TWITTER_API_SECRET_KEY mismatch.\");\n }\n if (\n client.state.TWITTER_ACCESS_TOKEN !==\n this.mockConfig.TWITTER_ACCESS_TOKEN\n ) {\n throw new Error(\"Client state TWITTER_ACCESS_TOKEN mismatch.\");\n }\n if (\n client.state.TWITTER_ACCESS_TOKEN_SECRET !==\n this.mockConfig.TWITTER_ACCESS_TOKEN_SECRET\n ) {\n throw new Error(\"Client state TWITTER_ACCESS_TOKEN_SECRET mismatch.\");\n }\n },\n },\n {\n name: \"Initialize with correct post intervals\",\n fn: async () => {\n const state = {\n TWITTER_API_KEY: this.mockConfig.TWITTER_API_KEY,\n TWITTER_API_SECRET_KEY: this.mockConfig.TWITTER_API_SECRET_KEY,\n TWITTER_ACCESS_TOKEN: this.mockConfig.TWITTER_ACCESS_TOKEN,\n TWITTER_ACCESS_TOKEN_SECRET:\n this.mockConfig.TWITTER_ACCESS_TOKEN_SECRET,\n TWITTER_POST_INTERVAL_MIN: this.mockConfig.TWITTER_POST_INTERVAL_MIN,\n TWITTER_POST_INTERVAL_MAX: this.mockConfig.TWITTER_POST_INTERVAL_MAX,\n };\n const client = new ClientBase(this.mockRuntime, state);\n\n // Verify post intervals are set correctly\n if (client.state.TWITTER_POST_INTERVAL_MIN !== \"90\") {\n throw new Error(\"Client state TWITTER_POST_INTERVAL_MIN mismatch.\");\n }\n if (client.state.TWITTER_POST_INTERVAL_MAX !== \"180\") {\n throw new Error(\"Client state TWITTER_POST_INTERVAL_MAX mismatch.\");\n }\n },\n },\n ];\n}\n"],"mappings":";;;;;;;AAAA;AAAA,EACE,eAAAA;AAAA,EAEA,aAAAC;AAAA,EAGA;AAAA,EAEA;AAAA,EAGA,oBAAAC;AAAA,EACA,UAAAC;AAAA,OACK;;;ACbP;AAAA,EACE;AAAA,EAMA;AAAA,EACA;AAAA,OACK;;;ACTP,SAAS,eAAe;;;ACIjB,IAAM,WAAN,MAAM,kBAAiB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ1B,YACG,UACA,MACT,SACA;AACA,UAAM,OAAO;AAJJ;AACA;AAAA,EAIX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,aAAa,aAAa,UAAoB;AAE5C,QAAI,OAAoC;AACxC,QAAI;AACF,aAAO,MAAM,SAAS,KAAK;AAAA,IAC7B,Q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ACF;AA/Pa,gBACJ,cAAsB;AADxB,IAAM,iBAAN;AAiQP,IAAM,gBAAwB;AAAA,EAC5B,MAAM;AAAA,EACN,aAAa;AAAA,EACb,UAAU,CAAC,cAAc;AAAA,EACzB,SAAS,CAAC;AAAA,EACV,OAAO,CAAC,IAAI,oBAAoB,CAAC;AACnC;AAEA,IAAO,gBAAQ;","names":["ChannelType","EventType","createUniqueUuid","logger","stringify","features","stringify","features","features","user","place","features","existingMemories","existingMemoryIds","tweetsToSave","profile","ChannelType","createUniqueUuid","logger","createUniqueUuid","logger","logger","util","objectUtil","path","errorUtil","path","errorMap","ctx","result","issues","elements","processed","result","r","ZodFirstPartyTypeKind","logger","createUniqueUuid","memory","ChannelType","ChannelType","EventType","createUniqueUuid","logger","logger","createUniqueUuid","ChannelType","EventType","ChannelType","createUniqueUuid","logger","createUniqueUuid","ChannelType","logger","logger","createUniqueUuid","ChannelType","EventType"]}