vibebusiness 1.2.86 → 1.2.87
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/.next/standalone/.next/BUILD_ID +1 -1
- package/.next/standalone/.next/app-build-manifest.json +29 -29
- package/.next/standalone/.next/app-path-routes-manifest.json +1 -1
- package/.next/standalone/.next/build-manifest.json +2 -2
- package/.next/standalone/.next/prerender-manifest.json +1 -1
- package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/_not-found.html +1 -1
- package/.next/standalone/.next/server/app/_not-found.rsc +1 -1
- package/.next/standalone/.next/server/app/api/analyze/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/config/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/epics/[id]/ideas/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/epics/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/epics/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/goals/[id]/kpis/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/goals/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/goals/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/hypotheses/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/hypotheses/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/ideas/[id]/card/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/ideas/[id]/comments/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/ideas/[id]/implement/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/ideas/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/ideas/[id]/transition/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/ideas/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/implementations/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/kpis/refresh/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/social/[id]/publish/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/social/[id]/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/api/social/route.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/goals/[id]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/goals/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/goals/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/hypotheses/[id]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/hypotheses/page.js +1 -1
- package/.next/standalone/.next/server/app/hypotheses/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/hypotheses/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/ideas/[id]/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/ideas/[id]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/page.js +1 -1
- package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/roadmap/[id]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/roadmap/investors/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/roadmap/investors/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/roadmap/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/roadmap/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/roadmap/public/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/roadmap/public/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/sessions/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/sessions/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/settings.html +1 -1
- package/.next/standalone/.next/server/app/settings.rsc +1 -1
- package/.next/standalone/.next/server/app/social/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/social.html +1 -1
- package/.next/standalone/.next/server/app/social.rsc +1 -1
- package/.next/standalone/.next/server/app/updates/[id]/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/updates/[id]/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/updates/new/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app/updates/new.html +1 -1
- package/.next/standalone/.next/server/app/updates/new.rsc +1 -1
- package/.next/standalone/.next/server/app/updates/page.js.nft.json +1 -1
- package/.next/standalone/.next/server/app/updates/page_client-reference-manifest.js +1 -1
- package/.next/standalone/.next/server/app-paths-manifest.json +17 -17
- package/.next/standalone/.next/server/chunks/7151.js +10 -10
- package/.next/standalone/.next/server/pages/404.html +1 -1
- package/.next/standalone/.next/server/pages/500.html +1 -1
- package/.next/standalone/.next/server/server-reference-manifest.json +1 -1
- package/.next/standalone/data/business-context.json +1 -1
- package/.next/standalone/data/goals.json +1 -1
- package/.next/standalone/data/ideas.json +25 -8
- package/.next/standalone/data/implementations.json +40 -2
- package/.next/standalone/data/reports/visuals/idea-3f4595f7-card.png +0 -0
- package/.next/standalone/data/reports/visuals/idea-4rxt3mkj-card.png +0 -0
- package/.next/standalone/data/reports/visuals/idea-6631456b-card.png +0 -0
- package/.next/standalone/data/reports/visuals/idea-boot-001-card.png +0 -0
- package/.next/standalone/data/reports/visuals/idea-fb3eba74-card.png +0 -0
- package/.next/standalone/data/reports/visuals/idea-prqf3lob-card.png +0 -0
- package/.next/standalone/package.json +1 -1
- package/dist/scripts/heartbeat.js +118 -6
- package/dist/scripts/scan.js +3 -0
- package/dist/scripts/social-routine.js +3 -0
- package/package.json +1 -1
- /package/.next/static/{fBNMzUSuIGwJGs9aNW81h → kgtR3Ls8MG4aQqwp3I0UE}/_buildManifest.js +0 -0
- /package/.next/static/{fBNMzUSuIGwJGs9aNW81h → kgtR3Ls8MG4aQqwp3I0UE}/_ssgManifest.js +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
exports.id=7151,exports.ids=[7151],exports.modules={1401:e=>{function t(e){var t=Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=1401,e.exports=t},5883:(e,t,s)=>{"use strict";s.r(t),s.d(t,{ApiPartialResponseError:()=>f,ApiRequestError:()=>_,ApiResponseError:()=>w,DmEventsV1Paginator:()=>p,EApiV1ErrorCode:()=>x,EApiV2ErrorCode:()=>S,EDirectMessageEventTypeV1:()=>b,ETwitterApiError:()=>k,ETwitterStreamEvent:()=>T,EUploadMimeType:()=>v,FriendshipsIncomingV1Paginator:()=>eg,FriendshipsOutgoingV1Paginator:()=>e_,HomeTimelineV1Paginator:()=>er,ListMembersV1Paginator:()=>ek,ListMembershipsV1Paginator:()=>ew,ListOwnershipsV1Paginator:()=>ey,ListSubscribersV1Paginator:()=>ex,ListSubscriptionsV1Paginator:()=>ev,ListTimelineV1Paginator:()=>en,MentionTimelineV1Paginator:()=>ei,MuteUserIdsV1Paginator:()=>eu,MuteUserListV1Paginator:()=>el,PreviousableTwitterPaginator:()=>d,QuotedTweetsTimelineV2Paginator:()=>eU,TweetBookmarksTimelineV2Paginator:()=>eW,TweetHomeTimelineV2Paginator:()=>eB,TweetLikingUsersV2Paginator:()=>e2,TweetRetweetersUsersV2Paginator:()=>e8,TweetSearchAllV2Paginator:()=>eM,TweetSearchRecentV2Paginator:()=>eF,TweetStream:()=>H,TweetUserMentionTimelineV2Paginator:()=>eV,TweetUserTimelineV2Paginator:()=>eH,TweetV2ListTweetsPaginator:()=>eJ,TweetV2UserLikedTweetsPaginator:()=>eY,TwitterApi:()=>t_,TwitterApiPluginResponseOverride:()=>y,TwitterApiReadOnly:()=>tl,TwitterApiReadWrite:()=>tu,TwitterApiV2Settings:()=>D,TwitterApiv1:()=>eL,TwitterApiv2:()=>to,TwitterApiv2Labs:()=>tn,TwitterPaginator:()=>u,TwitterV2IncludesHelper:()=>eO,UserBlockingUsersV2Paginator:()=>eG,UserFavoritesV1Paginator:()=>eo,UserFollowerIdsV1Paginator:()=>ec,UserFollowerListV1Paginator:()=>ed,UserFollowersIdsV1Paginator:()=>ep,UserFollowersV2Paginator:()=>eQ,UserFollowingV2Paginator:()=>eZ,UserFriendListV1Paginator:()=>eh,UserListFollowedV2Paginator:()=>e7,UserListFollowersV2Paginator:()=>e1,UserListMembersV2Paginator:()=>e0,UserListMembershipsV2Paginator:()=>e3,UserMutingUsersV2Paginator:()=>eX,UserOwnedListsV2Paginator:()=>e5,UserSearchV1Paginator:()=>em,UserTimelineV1Paginator:()=>ea,WelcomeDmV1Paginator:()=>m,default:()=>tf});let r="https://api.x.com/2/",i="https://api.x.com/labs/2/",a="https://api.x.com/1.1/",n="https://upload.x.com/1.1/",o="https://ads-api.x.com/12/",l="https://ads-api-sandbox.twitter.com/12/";class u{constructor({realData:e,rateLimit:t,instance:s,queryParams:r,sharedParams:i}){this._maxResultsWhenFetchLast=100,this._realData=e,this._rateLimit=t,this._instance=s,this._queryParams=r,this._sharedParams=i}get _isRateLimitOk(){return!!(!this._rateLimit||1e3*this._rateLimit.reset<Date.now())||this._rateLimit.remaining>0}makeRequest(e){return this._instance.get(this.getEndpoint(),e,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(e,t){return new this.constructor({realData:e.data,rateLimit:e.rateLimit,instance:this._instance,queryParams:t,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(e){return{...e?{max_results:e}:{},...this._queryParams}}async next(e){let t=this.getNextQueryParams(e),s=await this.makeRequest(t);return this.makeNewInstanceFromResult(s,t)}async fetchNext(e){let t=this.getNextQueryParams(e),s=await this.makeRequest(t);return await this.refreshInstanceFromResult(s,!0),this}async fetchLast(e=1/0){let t=this.getNextQueryParams(this._maxResultsWhenFetchLast),s=0;for(;s<e&&this._isRateLimitOk;){let e=await this.makeRequest(t);if(await this.refreshInstanceFromResult(e,!0),s+=this.getPageLengthFromRequest(e),this.isFetchLastOver(e))break;t=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var e;return{...null!==(e=this._rateLimit)&&void 0!==e?e:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async *[Symbol.asyncIterator](){yield*this.getItemArray();let e=this,t=this.canFetchNextPage(this._realData);for(;t&&this._isRateLimitOk&&e.getItemArray().length>0;){let s=await e.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:s._realData,headers:{},rateLimit:s._rateLimit},!0),t=this.canFetchNextPage(s._realData);let r=s.getItemArray();yield*r,e=s}}async *fetchAndIterate(){for(let e of this.getItemArray())yield[e,this];let e=this,t=this.canFetchNextPage(this._realData);for(;t&&this._isRateLimitOk&&e.getItemArray().length>0;){let s=await e.next(this._maxResultsWhenFetchLast);for(let e of(this.refreshInstanceFromResult({data:s._realData,headers:{},rateLimit:s._rateLimit},!0),t=this.canFetchNextPage(s._realData),s.getItemArray()))yield[e,s];this._rateLimit=s._rateLimit,e=s}}}class d extends u{async previous(e){let t=this.getPreviousQueryParams(e),s=await this.makeRequest(t);return this.makeNewInstanceFromResult(s,t)}async fetchPrevious(e){let t=this.getPreviousQueryParams(e),s=await this.makeRequest(t);return await this.refreshInstanceFromResult(s,!1),this}}let c=u;class h extends c{getNextQueryParams(e){var t;return{...this._queryParams,cursor:null!==(t=this._realData.next_cursor_str)&&void 0!==t?t:this._realData.next_cursor,...e?{count:e}:{}}}isFetchLastOver(e){return!this.canFetchNextPage(e.data)}canFetchNextPage(e){return!this.isNextCursorInvalid(e.next_cursor)||!this.isNextCursorInvalid(e.next_cursor_str)}isNextCursorInvalid(e){return void 0===e||0===e||-1===e||"0"===e||"-1"===e}}class p extends h{constructor(){super(...arguments),this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.events.push(...s.events),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class m extends h{constructor(){super(...arguments),this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.welcome_messages.push(...s.welcome_messages),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}(function(e){e.Jpeg="image/jpeg",e.Mp4="video/mp4",e.Mov="video/quicktime",e.Gif="image/gif",e.Png="image/png",e.Srt="text/plain",e.Webp="image/webp"})(v||(v={})),function(e){e.Create="message_create",e.WelcomeCreate="welcome_message"}(b||(b={})),function(e){e.Request="request",e.PartialResponse="partial-response",e.Response="response"}(k||(k={}));class g extends Error{constructor(){super(...arguments),this.error=!0}}class _ extends g{constructor(e,t){super(e),this.type=k.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class f extends g{constructor(e,t){super(e),this.type=k.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t})}get request(){return this._options.request}get response(){return this._options.response}get responseError(){return this._options.responseError}get rawContent(){return this._options.rawContent}toJSON(){return{type:this.type,error:this.responseError}}}class w extends g{constructor(e,t){if(super(e),this.type=k.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t}),this.code=t.code,this.headers=t.headers,this.rateLimit=t.rateLimit,t.data&&"object"==typeof t.data&&"error"in t.data&&!t.data.errors){let e={...t.data};e.errors=[{code:x.InternalError,message:e.error}],this.data=e}else this.data=t.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...e){let t=this.errors;if(!(null==t?void 0:t.length))return!1;if("code"in t[0])return t.some(t=>e.includes(t.code));let s=this.data;return e.includes(s.type)}get errors(){var e;return null===(e=this.data)||void 0===e?void 0:e.errors}get rateLimitError(){return 420===this.code||429===this.code}get isAuthError(){return 401===this.code||this.hasErrorCode(x.AuthTimestampInvalid,x.AuthenticationFail,x.BadAuthenticationData,x.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}(function(e){e[e.InvalidCoordinates=3]="InvalidCoordinates",e[e.NoLocationFound=13]="NoLocationFound",e[e.AuthenticationFail=32]="AuthenticationFail",e[e.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",e[e.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",e[e.AuthTimestampInvalid=135]="AuthTimestampInvalid",e[e.BadAuthenticationData=215]="BadAuthenticationData",e[e.NoUserMatch=17]="NoUserMatch",e[e.UserNotFound=50]="UserNotFound",e[e.ResourceNotFound=34]="ResourceNotFound",e[e.TweetNotFound=144]="TweetNotFound",e[e.TweetNotVisible=179]="TweetNotVisible",e[e.NotAllowedResource=220]="NotAllowedResource",e[e.MediaIdNotFound=325]="MediaIdNotFound",e[e.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",e[e.TweetViolatedRules=422]="TweetViolatedRules",e[e.TargetUserSuspended=63]="TargetUserSuspended",e[e.YouAreSuspended=64]="YouAreSuspended",e[e.AccountUpdateFailed=120]="AccountUpdateFailed",e[e.NoSelfSpamReport=36]="NoSelfSpamReport",e[e.NoSelfMute=271]="NoSelfMute",e[e.AccountLocked=326]="AccountLocked",e[e.RateLimitExceeded=88]="RateLimitExceeded",e[e.NoDMRightForApp=93]="NoDMRightForApp",e[e.OverCapacity=130]="OverCapacity",e[e.InternalError=131]="InternalError",e[e.TooManyFollowings=161]="TooManyFollowings",e[e.TweetLimitExceeded=185]="TweetLimitExceeded",e[e.DuplicatedTweet=187]="DuplicatedTweet",e[e.TooManySpamReports=205]="TooManySpamReports",e[e.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",e[e.NoWriteRightForApp=261]="NoWriteRightForApp",e[e.TweetActionsDisabled=425]="TweetActionsDisabled",e[e.TweetRepliesRestricted=433]="TweetRepliesRestricted",e[e.NamedParameterMissing=38]="NamedParameterMissing",e[e.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",e[e.TweetTextTooLong=186]="TweetTextTooLong",e[e.MissingUrlParameter=195]="MissingUrlParameter",e[e.NoMultipleGifs=323]="NoMultipleGifs",e[e.InvalidMediaIds=324]="InvalidMediaIds",e[e.InvalidUrl=407]="InvalidUrl",e[e.TooManyTweetAttachments=386]="TooManyTweetAttachments",e[e.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",e[e.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",e[e.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",e[e.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",e[e.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",e[e.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",e[e.UnableToSendDM=151]="UnableToSendDM",e[e.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",e[e.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",e[e.DMTextTooLong=354]="DMTextTooLong",e[e.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",e[e.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",e[e.SuspendedApplication=416]="SuspendedApplication",e[e.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(x||(x={})),function(e){e.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",e.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",e.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",e.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",e.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",e.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",e.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",e.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",e.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",e.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",e.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",e.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",e.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"}(S||(S={})),function(e){e.Connected="connected",e.ConnectError="connect error",e.ConnectionError="connection error",e.ConnectionClosed="connection closed",e.ConnectionLost="connection lost",e.ReconnectAttempt="reconnect attempt",e.Reconnected="reconnected",e.ReconnectError="reconnect error",e.ReconnectLimitExceeded="reconnect limit exceeded",e.DataKeepAlive="data keep-alive",e.Data="data event content",e.DataError="data twitter error",e.TweetParseError="data tweet parse error",e.Error="stream error"}(T||(T={}));class y{constructor(e){this.value=e}}var v,b,k,x,S,T,R,E=s(2048);let D={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function A(e){let t={value:void 0,promise:e().then(e=>(t.value=e,e))};return t}function P(e){return Array.isArray(e)?e:[e]}function I(e){return"object"==typeof e&&"errors"in e&&!("data"in e)}function L(e){return!!Array.isArray(e)&&e.length>1||e.toString().includes(",")}let $=new Set;function O(e){if("undefined"==typeof console||!console.warn||!D.deprecationWarnings)return;let t=`${e.instance}-${e.method}-${e.problem}`;$.has(t)||(console.warn(`[twitter-api-v2] Deprecation warning: In ${e.instance}.${e.method}() call, ${e.problem}.
|
|
2
|
-
${e.resolution}.`),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),$.add(t))}var q=s(7702),j=s(8791),C=s(1568);class N{constructor(e){this.requestData=e,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let e=this.requestData.url;return e.hostname+e.pathname}isCompressionDisabled(){return!this.requestData.compression||"identity"===this.requestData.compression}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(e){return D.debug&&D.logger.log("Request error:",e),new _("Request failed.",{request:this.req,error:e})}createPartialResponseError(e,t){let s=this.res,r=`Request failed with partial response with HTTP code ${s.statusCode}`;return t?r+=" (connection abruptly closed)":r+=" (parse error)",new f(r,{request:this.req,response:this.res,responseError:e,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(e){return e.map(({code:e,message:t})=>`${t} (Twitter code ${e})`).join(", ")}formatV2Error(e){return`${e.title}: ${e.detail} (see ${e.type})`}createResponseError({res:e,data:t,rateLimit:s,code:r}){var i;D.debug&&(D.logger.log(`Request failed with code ${r}, data:`,t),D.logger.log("Response headers:",e.headers));let a=`Request failed with code ${r}`;if(null===(i=null==t?void 0:t.errors)||void 0===i?void 0:i.length){let e=t.errors;"object"==typeof e[0]&&"code"in e[0]?a+=" - "+this.formatV1Errors(e):a+=" - "+this.formatV2Error(t)}return new w(a,{code:r,data:t,headers:e.headers,request:this.req,response:e,rateLimit:s})}getResponseDataStream(e){if(this.isCompressionDisabled())return e;let t=(e.headers["content-encoding"]||"identity").trim().toLowerCase();if("br"===t){let t=C.createBrotliDecompress({flush:C.constants.BROTLI_OPERATION_FLUSH,finishFlush:C.constants.BROTLI_OPERATION_FLUSH});return e.pipe(t),t}if("gzip"===t){let t=C.createGunzip({flush:C.constants.Z_SYNC_FLUSH,finishFlush:C.constants.Z_SYNC_FLUSH});return e.pipe(t),t}if("deflate"===t){let t=C.createInflate({flush:C.constants.Z_SYNC_FLUSH,finishFlush:C.constants.Z_SYNC_FLUSH});return e.pipe(t),t}return e}detectResponseType(e){var t,s;return(null===(t=e.headers["content-type"])||void 0===t?void 0:t.includes("application/json"))||(null===(s=e.headers["content-type"])||void 0===s?void 0:s.includes("application/problem+json"))?"json":this.isFormEncodedEndpoint()?"url":"text"}getParsedResponse(e){let t=this.responseData,s=this.requestData.forceParseMode||this.detectResponseType(e);if("buffer"===s)return Buffer.concat(t);if("text"===s)return Buffer.concat(t).toString();if("json"===s){let e=Buffer.concat(t).toString();return e.length?JSON.parse(e):void 0}{if("url"!==s)return;let e=Buffer.concat(t).toString(),r={};for(let[t,s]of new URLSearchParams(e))r[t]=s;return r}}getRateLimitFromResponse(e){let t;return e.headers["x-rate-limit-limit"]&&(t={limit:Number(e.headers["x-rate-limit-limit"]),remaining:Number(e.headers["x-rate-limit-remaining"]),reset:Number(e.headers["x-rate-limit-reset"])},e.headers["x-app-limit-24hour-limit"]&&(t.day={limit:Number(e.headers["x-app-limit-24hour-limit"]),remaining:Number(e.headers["x-app-limit-24hour-remaining"]),reset:Number(e.headers["x-app-limit-24hour-reset"])}),e.headers["x-user-limit-24hour-limit"]&&(t.userDay={limit:Number(e.headers["x-user-limit-24hour-limit"]),remaining:Number(e.headers["x-user-limit-24hour-remaining"]),reset:Number(e.headers["x-user-limit-24hour-reset"])}),this.requestData.rateLimitSaver&&this.requestData.rateLimitSaver(t)),t}onSocketEventHandler(e,t,s){let r=this.onSocketCloseHandler.bind(this,e);s.on("close",r),t.on("complete",()=>s.off("close",r))}onSocketCloseHandler(e){if(this.req.removeAllListeners("timeout"),!this.res&&!this.requestErrorHandled)return e(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(e,t){var s,r;null===(r=(s=this.requestData).requestEventDebugHandler)||void 0===r||r.call(s,"request-error",{requestError:t}),this.requestErrorHandled=!0,e(this.createRequestError(t))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(e,t,s){this.res=s;let r=this.getResponseDataStream(s);r.on("data",e=>this.responseData.push(e)),r.on("end",this.onResponseEndHandler.bind(this,e,t)),r.on("close",this.onResponseCloseHandler.bind(this,e,t)),this.requestData.requestEventDebugHandler&&(this.requestData.requestEventDebugHandler("response",{res:s}),s.on("aborted",e=>this.requestData.requestEventDebugHandler("response-aborted",{error:e})),s.on("error",e=>this.requestData.requestEventDebugHandler("response-error",{error:e})),s.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),s.on("end",()=>this.requestData.requestEventDebugHandler("response-end")))}onResponseEndHandler(e,t){let s;let r=this.getRateLimitFromResponse(this.res);try{s=this.getParsedResponse(this.res)}catch(e){t(this.createPartialResponseError(e,!1));return}let i=this.res.statusCode;if(i>=400){t(this.createResponseError({data:s,res:this.res,rateLimit:r,code:i}));return}D.debug&&(D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),D.logger.log("Response body:",s)),e({data:s,headers:this.res.headers,rateLimit:r})}onResponseCloseHandler(e,t){let s=this.res;if(s.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(e,t)}catch(e){return t(this.createPartialResponseError(e,!0))}if(!s.complete)return t(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(e,t,s){if(s.statusCode<400){D.debug&&D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${s.statusCode} (starting stream)`);let t=this.getResponseDataStream(s);e({req:this.req,res:t,originalResponse:s,requestData:this.requestData})}else this.classicResponseHandler(()=>void 0,t,s)}debugRequest(){let e=this.requestData.url;D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),e.search&&D.logger.log("Request parameters:",[...e.searchParams.entries()].map(([e,t])=>`${e}: ${t}`)),this.requestData.body&&D.logger.log("Request body:",this.requestData.body)}buildRequest(){var e;let t=this.requestData.url,s=t.username?`${t.username}:${t.password}`:void 0,r=null!==(e=this.requestData.options.headers)&&void 0!==e?e:{};!0===this.requestData.compression||"brotli"===this.requestData.compression?r["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1":"gzip"===this.requestData.compression?r["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1":"deflate"===this.requestData.compression&&(r["accept-encoding"]="deflate;q=1, *;q=0.1"),D.debug&&this.debugRequest(),this.req=(0,j.request)({...this.requestData.options,host:t.hostname,port:t.port||void 0,path:t.pathname+t.search,protocol:t.protocol,auth:s,headers:r})}registerRequestEventDebugHandlers(e){e.on("close",()=>this.requestData.requestEventDebugHandler("close")),e.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),e.on("socket",e=>{this.requestData.requestEventDebugHandler("socket",{socket:e}),e.on("error",t=>this.requestData.requestEventDebugHandler("socket-error",{socket:e,error:t})),e.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:e})),e.on("close",t=>this.requestData.requestEventDebugHandler("socket-close",{socket:e,withError:t})),e.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:e})),e.on("lookup",(...t)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:e,data:t})),e.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:e}))})}makeRequest(){return this.buildRequest(),new Promise((e,t)=>{let s=e=>{r.emit("complete"),t(e)},r=new q.EventEmitter,i=this.req;i.on("error",this.requestErrorHandler.bind(this,s)),i.on("socket",this.onSocketEventHandler.bind(this,s,r)),i.on("response",this.classicResponseHandler.bind(this,t=>{r.emit("complete"),e(t)},s)),this.requestData.options.timeout&&i.on("timeout",this.timeoutErrorHandler.bind(this)),this.requestData.requestEventDebugHandler&&this.registerRequestEventDebugHandlers(i),this.requestData.body&&i.write(this.requestData.body),i.end()})}async makeRequestAsStream(){let{req:e,res:t,requestData:s,originalResponse:r}=await this.makeRequestAndResolveWhenReady();return new V(s,{req:e,res:t,originalResponse:r})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((e,t)=>{let s=this.req;s.on("error",this.requestErrorHandler.bind(this,t)),s.on("response",this.streamResponseHandler.bind(this,e,t)),this.requestData.body&&s.write(this.requestData.body),s.end()})}}class F extends q.EventEmitter{constructor(e){super(),this.stream=e,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),e.on(T.Data,this.onStreamData),e.on(T.ConnectionError,this.onStreamError),e.on(T.TweetParseError,this.onStreamError),e.on(T.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let e=this.stack;return this.stack=[],e}destroy(){this.removeAllListeners(),this.stream.off(T.Data,this.onStreamData),this.stream.off(T.ConnectionError,this.onStreamError),this.stream.off(T.TweetParseError,this.onStreamError),this.stream.off(T.ConnectionClosed,this.onStreamError)}emitEvent(e,t){this.emit("event",{type:e,payload:t})}onStreamError(e){this.emitEvent("error",e)}onStreamData(e){this.stack.push(e),this.emitEvent("data",e)}}class M extends q.EventEmitter{constructor(){super(...arguments),this.currentMessage=""}push(e){this.currentMessage+=e;let t=(e=this.currentMessage).length,s=0,r=0;for(;r<t;){if("\r\n"===e.slice(r,r+2)){let t=e.slice(s,r);if(s=r+=2,!t.length)continue;try{let e=JSON.parse(t);if(e){this.emit(R.ParsedData,e);continue}}catch(e){this.emit(R.ParseError,e)}}r++}this.currentMessage=e.slice(s,t)}reset(){this.currentMessage=""}}!function(e){e.ParsedData="parsed data",e.ParseError="parse error"}(R||(R={}));let U=[5,15,30,60,90,120,180,300,600,900],B=e=>e>U.length?901e3:1e3*U[e-1];class H extends q.EventEmitter{constructor(e,t){super(),this.requestData=e,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=12e4,this.nextRetryTimeout=B,this.parser=new M,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),t&&(this.req=t.req,this.res=t.res,this.originalResponse=t.originalResponse,this.initEventsFromRequest())}on(e,t){return super.on(e,t)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let e=e=>{this.emit(T.ConnectionError,e),this.emit(T.Error,{type:T.ConnectionError,error:e,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",e),this.res.on("error",e),this.res.on("close",()=>e(Error("Connection closed by Twitter."))),this.res.on("data",e=>{if(this.resetKeepAliveTimeout(),"\r\n"===e.toString())return this.emit(T.DataKeepAlive);this.parser.push(e.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let e=this.requestData.payloadIsError;this.parser.on(R.ParsedData,t=>{e&&e(t)?(this.emit(T.DataError,t),this.emit(T.Error,{type:T.DataError,error:t,message:"Twitter sent a payload that is detected as an error payload."})):this.emit(T.Data,t)}),this.parser.on(R.ParseError,e=>{this.emit(T.TweetParseError,e),this.emit(T.Error,{type:T.TweetParseError,error:e,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0&&(this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs))}onKeepAliveTimeout(){this.emit(T.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){this.keepAliveTimeout&&(clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0)}unbindRetryTimeout(){this.retryTimeout&&(clearTimeout(this.retryTimeout),this.retryTimeout=void 0)}closeWithoutEmit(){this.unbindTimeouts(),this.res&&(this.res.removeAllListeners(),this.res.destroy()),this.req&&(this.req.removeAllListeners(),this.req.destroy())}close(){this.emit(T.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let e=new N(this.requestData),t=await e.makeRequestAsStream();for(let e of this.eventNames())for(let s of this.listeners(e))t.on(e,s);return t}async connect(e={}){void 0!==e.autoReconnect&&(this.autoReconnect=e.autoReconnect),void 0!==e.autoReconnectRetries&&(this.autoReconnectRetries="unlimited"===e.autoReconnectRetries?1/0:e.autoReconnectRetries),void 0!==e.keepAliveTimeout&&(this.keepAliveTimeoutMs="disable"===e.keepAliveTimeout?1/0:e.keepAliveTimeout),void 0!==e.nextRetryTimeout&&(this.nextRetryTimeout=e.nextRetryTimeout),this.unbindTimeouts();try{await this.reconnect()}catch(e){if(this.emit(T.ConnectError,0),this.emit(T.Error,{type:T.ConnectError,error:e,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,e);else throw e}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let e=!0;this.req&&(e=!1,this.closeWithoutEmit());let{req:t,res:s,originalResponse:r}=await new N(this.requestData).makeRequestAndResolveWhenReady();this.req=t,this.res=s,this.originalResponse=r,this.emit(e?T.Connected:T.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(e=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(T.ConnectionClosed);return}if(e>=this.autoReconnectRetries){this.emit(T.ReconnectLimitExceeded),this.emit(T.ConnectionClosed);return}try{this.emit(T.ReconnectAttempt,e),await this.reconnect()}catch(t){this.emit(T.ReconnectError,e),this.emit(T.Error,{type:T.ReconnectError,error:t,message:`Reconnect error - ${e+1} attempts made yet.`}),this.makeAutoReconnectRetry(e,t)}}makeAutoReconnectRetry(e,t){let s=this.nextRetryTimeout(e+1,t);this.retryTimeout=setTimeout(()=>{this.onConnectionError(e+1)},s)}async *[Symbol.asyncIterator](){let e=new F(this);try{for(;;){if(!this.req||this.req.aborted)throw Error("Connection closed");e.hasStack()&&(yield*e.popStack());let{type:t,payload:s}=await e.nextEvent();if("error"===t)throw s}}finally{e.destroy()}}}let V=H;async function W(e,t,s,r){let i;return(r instanceof _||r instanceof f?i=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,error:r}):r instanceof w&&(i=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,error:r})),i&&i instanceof y)?i.value:Promise.reject(r)}var K=s(4770);class Y{constructor(e){this.nonceLength=32,this.consumerKeys=e.consumerKeys}static percentEncode(e){return encodeURIComponent(e).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(e,t){return K.createHmac("sha1",t).update(e).digest("base64")}authorize(e,t={}){let s={oauth_consumer_key:this.consumerKeys.key,oauth_nonce:this.getNonce(),oauth_signature_method:"HMAC-SHA1",oauth_timestamp:this.getTimestamp(),oauth_version:"1.0"};return void 0!==t.key&&(s.oauth_token=t.key),e.data||(e.data={}),s.oauth_signature=this.getSignature(e,t.secret,s),s}toHeader(e){let t=z(e),s="OAuth ";for(let e of t)0===e.key.indexOf("oauth_")&&(s+=Y.percentEncode(e.key)+'="'+Y.percentEncode(e.value)+'",');return{Authorization:s.slice(0,s.length-1)}}getNonce(){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let s=0;s<this.nonceLength;s++)t+=e[Math.trunc(Math.random()*e.length)];return t}getTimestamp(){return Math.trunc(new Date().getTime()/1e3)}getSignature(e,t,s){return this.hash(this.getBaseString(e,s),this.getSigningKey(t))}getSigningKey(e){return Y.percentEncode(this.consumerKeys.secret)+"&"+Y.percentEncode(e||"")}getBaseString(e,t){return e.method.toUpperCase()+"&"+Y.percentEncode(this.getBaseUrl(e.url))+"&"+Y.percentEncode(this.getParameterString(e,t))}getParameterString(e,t){let s=z(function(e){let t={};for(let s in e){let r=e[s];r=r&&Array.isArray(r)?r.map(e=>Y.percentEncode(e)):Y.percentEncode(r),t[Y.percentEncode(s)]=r}return t}(J(t,J(e.data,function(e){let t=e.split("?");return 1===t.length?{}:function(e){let t=e.split("&"),s={};for(let e of t){let[t,r=""]=e.split("=");s[t]?(Array.isArray(s[t])||(s[t]=[s[t]]),s[t].push(decodeURIComponent(r))):s[t]=decodeURIComponent(r)}return s}(t[1])}(e.url))))),r="";for(let{key:e,value:t}of s)if(t&&Array.isArray(t)){t.sort();let s="";t.forEach((r,i)=>{s+=e+"="+r,i<t.length&&(s+="&")}),r+=s}else r+=e+"="+t+"&";return r.slice(0,r.length-1)}getBaseUrl(e){return e.split("?")[0]}}function J(e,t){return{...e||{},...t||{}}}function z(e){return Object.keys(e).sort().map(t=>({key:t,value:e[t]}))}class G{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...e){let t=e.map(e=>e instanceof Buffer?e:Buffer.from(e));this._chunks.push(...t)}append(e,t,s){let r=t instanceof Buffer?t:t.toString(),i=this.getMultipartHeader(e,r,s);this.bodyAppend(i,r,G.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((e,t)=>e+t.length,this.getMultipartFooter().length)}getBuffer(){let e=[...this._chunks,this.getMultipartFooter()],t=Buffer.alloc(this.getLength()),s=0;for(let r of e)for(let e=0;e<r.length;s++,e++)t[s]=r[e];return t}getBoundary(){return this._boundary||this.generateBoundary(),this._boundary}generateBoundary(){let e="--------------------------";for(let t=0;t<24;t++)e+=Math.floor(10*Math.random()).toString(16);this._boundary=e}getMultipartHeader(e,t,s){s||(s=t instanceof Buffer?G.DEFAULT_CONTENT_TYPE:"");let r="";for(let[t,i]of Object.entries({"Content-Disposition":["form-data",`name="${e}"`],"Content-Type":s}))i.length&&(r+=t+": "+P(i).join("; ")+G.LINE_BREAK);return"--"+this.getBoundary()+G.LINE_BREAK+r+G.LINE_BREAK}getMultipartFooter(){return this._footerChunk?this._footerChunk:this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+G.LINE_BREAK)}}G.LINE_BREAK="\r\n",G.DEFAULT_CONTENT_TYPE="application/octet-stream";class X{static formatQueryToString(e){let t={};for(let s in e)"string"==typeof e[s]?t[s]=e[s]:void 0!==e[s]&&(t[s]=String(e[s]));return t}static autoDetectBodyType(e){if(e.pathname.startsWith("/2/")||e.pathname.startsWith("/labs/2/"))return e.password.startsWith("/2/oauth2")?"url":"json";if("upload.x.com"===e.hostname)return"/1.1/media/upload.json"===e.pathname?"form-data":"json";let t=e.pathname.split("/1.1/",2)[1];return this.JSON_1_1_ENDPOINTS.has(t)?"json":"url"}static addQueryParamsToUrl(e,t){let s=Object.entries(t);if(s.length){let t="";for(let[e,r]of s)t+=(t.length?"&":"?")+`${Y.percentEncode(e)}=${Y.percentEncode(r)}`;e.search=t}}static constructBodyParams(e,t,s){if(e instanceof Buffer)return e;if("json"===s)return t["content-type"]||(t["content-type"]="application/json;charset=UTF-8"),JSON.stringify(e);if("url"===s)return(t["content-type"]||(t["content-type"]="application/x-www-form-urlencoded;charset=UTF-8"),Object.keys(e).length)?new URLSearchParams(e).toString().replace(/\*/g,"%2A"):"";if("raw"===s)throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");{let s=new G;for(let t in e)s.append(t,e[t]);if(!t["content-type"]){let e=s.getHeaders();t["content-type"]=e["content-type"]}return s.getBuffer()}}static setBodyLengthHeader(e,t){var s;e.headers=null!==(s=e.headers)&&void 0!==s?s:{},"string"==typeof t?e.headers["content-length"]=Buffer.byteLength(t):e.headers["content-length"]=t.length}static isOAuthSerializable(e){return!(e instanceof Buffer)}static mergeQueryAndBodyForOAuth(e,t){let s={};for(let t in e)s[t]=e[t];if(this.isOAuthSerializable(t))for(let e in t){let r=t[e];this.isOAuthSerializable(r)&&(s[e]="object"==typeof r&&null!==r&&"toString"in r?r.toString():r)}return s}static moveUrlQueryParamsIntoObject(e,t){for(let[s,r]of e.searchParams)t[s]=r;return e.search="",e}static applyRequestParametersToUrl(e,t){return e.pathname=e.pathname.replace(/:([A-Z_-]+)/ig,(e,s)=>void 0!==t[s]?String(t[s]):e),e}}X.JSON_1_1_ENDPOINTS=new Set(["direct_messages/events/new.json","direct_messages/welcome_messages/new.json","direct_messages/welcome_messages/rules/new.json","media/metadata/create.json","collections/entries/curate.json"]);class Q{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(e){return this.escapeBase64Url(K.createHash("sha256").update(e).digest("base64"))}static getAuthHeader(e,t){let s=encodeURIComponent(e)+":"+encodeURIComponent(t);return Buffer.from(s).toString("base64")}static generateRandomString(e){let t="",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let r=0;r<e;r++)t+=s[Math.floor(Math.random()*s.length)];return t}static escapeBase64Url(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class Z{constructor(e){this.rateLimits={},this.clientSettings={},e&&(this.clientSettings=e)}getRateLimits(){return this.rateLimits}saveRateLimit(e,t){this.rateLimits[e]=t}async send(e){var t,s,r,i,a;if(null===(t=this.clientSettings.plugins)||void 0===t?void 0:t.length){let t=await this.applyPreRequestConfigHooks(e);if(t)return t}let n=this.getHttpRequestArgs(e),o={method:n.method,headers:n.headers,timeout:e.timeout,agent:this.clientSettings.httpAgent},l=!1!==e.enableRateLimitSave;n.body&&X.setBodyLengthHeader(o,n.body),(null===(s=this.clientSettings.plugins)||void 0===s?void 0:s.length)&&await this.applyPreRequestHooks(e,n,o);let u=new N({url:n.url,options:o,body:n.body,rateLimitSaver:l?this.saveRateLimit.bind(this,n.rawUrl):void 0,requestEventDebugHandler:e.requestEventDebugHandler,compression:null===(i=null!==(r=e.compression)&&void 0!==r?r:this.clientSettings.compression)||void 0===i||i,forceParseMode:e.forceParseMode}).makeRequest();(function(e){var t;if(!(null===(t=e.clientSettings.plugins)||void 0===t?void 0:t.length))return!1;for(let t of e.clientSettings.plugins)if(t.onRequestError||t.onResponseError)return!0;return!1})(this)&&(u=this.applyResponseErrorHooks(e,n,o,u));let d=await u;if(null===(a=this.clientSettings.plugins)||void 0===a?void 0:a.length){let t=await this.applyPostRequestHooks(e,n,o,d);if(t)return t.value}return d}sendStream(e){var t,s;this.clientSettings.plugins&&this.applyPreStreamRequestConfigHooks(e);let r=this.getHttpRequestArgs(e),i={method:r.method,headers:r.headers,agent:this.clientSettings.httpAgent},a=!1!==e.enableRateLimitSave,n=!1!==e.autoConnect;r.body&&X.setBodyLengthHeader(i,r.body);let o=new V({url:r.url,options:i,body:r.body,rateLimitSaver:a?this.saveRateLimit.bind(this,r.rawUrl):void 0,payloadIsError:e.payloadIsError,compression:null===(s=null!==(t=e.compression)&&void 0!==t?t:this.clientSettings.compression)||void 0===s||s});return n?o.connect():o}initializeToken(e){if("string"==typeof e)this.bearerToken=e;else if("object"==typeof e&&"appKey"in e)this.consumerToken=e.appKey,this.consumerSecret=e.appSecret,e.accessToken&&e.accessSecret&&(this.accessToken=e.accessToken,this.accessSecret=e.accessSecret),this._oauth=this.buildOAuth();else if("object"==typeof e&&"username"in e){let t=encodeURIComponent(e.username)+":"+encodeURIComponent(e.password);this.basicToken=Buffer.from(t).toString("base64")}else"object"==typeof e&&"clientId"in e&&(this.clientId=e.clientId,this.clientSecret=e.clientSecret)}getActiveTokens(){return this.bearerToken?{type:"oauth2",bearerToken:this.bearerToken}:this.basicToken?{type:"basic",token:this.basicToken}:this.consumerSecret&&this._oauth?{type:"oauth-1.0a",appKey:this.consumerToken,appSecret:this.consumerSecret,accessToken:this.accessToken,accessSecret:this.accessSecret}:this.clientId?{type:"oauth2-user",clientId:this.clientId}:{type:"none"}}buildOAuth(){if(!this.consumerSecret||!this.consumerToken)throw Error("Invalid consumer tokens");return new Y({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(this.accessSecret&&this.accessToken)return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var e;return null!==(e=this.clientSettings.plugins)&&void 0!==e?e:[]}hasPlugins(){var e;return!!(null===(e=this.clientSettings.plugins)||void 0===e?void 0:e.length)}async applyPluginMethod(e,t){var s;let r;for(let i of this.getPlugins()){let a=await (null===(s=i[e])||void 0===s?void 0:s.call(i,t));a&&a instanceof y&&(r=a)}return r}writeAuthHeaders({headers:e,bodyInSignature:t,url:s,method:r,query:i,body:a}){if(e={...e},this.bearerToken)e.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)e.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)e.Authorization="Basic "+Q.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let n=t?X.mergeQueryAndBodyForOAuth(i,a):i,o=this._oauth.authorize({url:s.toString(),method:r,data:n},this.getOAuthAccessTokens());e={...e,...this._oauth.toHeader(o)}}return e}getUrlObjectFromUrlString(e){return e.startsWith("http")||(e="https://"+e),new URL(e)}getHttpRequestArgs({url:e,method:t,query:s={},body:r={},headers:i,forceBodyMode:a,enableAuth:n,params:o}){let l;t=t.toUpperCase(),(i=null!=i?i:{})["x-user-agent"]||(i["x-user-agent"]="Node.twitter-api-v2");let u=this.getUrlObjectFromUrlString(e),d=u.origin+u.pathname;o&&X.applyRequestParametersToUrl(u,o);let c=X.formatQueryToString(s);X.moveUrlQueryParamsIntoObject(u,c),r instanceof Buffer||function(e){for(let t of Object.keys(e))void 0===e[t]&&delete e[t]}(r);let h=null!=a?a:X.autoDetectBodyType(u);if(!1!==n){let e=Z.BODY_METHODS.has(t)&&"url"===h;i=this.writeAuthHeaders({headers:i,bodyInSignature:e,method:t,query:c,url:u,body:r})}return Z.BODY_METHODS.has(t)&&(l=X.constructBodyParams(r,i,h)||void 0),X.addQueryParamsToUrl(u,c),{rawUrl:d,url:u,method:t,headers:i,body:l}}async applyPreRequestConfigHooks(e){var t;let s=this.getUrlObjectFromUrlString(e.url);for(let r of this.getPlugins()){let i=await (null===(t=r.onBeforeRequestConfig)||void 0===t?void 0:t.call(r,{client:this,url:s,params:e}));if(i)return i}}applyPreStreamRequestConfigHooks(e){var t;let s=this.getUrlObjectFromUrlString(e.url);for(let r of this.getPlugins())null===(t=r.onBeforeStreamRequestConfig)||void 0===t||t.call(r,{client:this,url:s,params:e})}async applyPreRequestHooks(e,t,s){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s})}async applyPostRequestHooks(e,t,s,r){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,response:r})}applyResponseErrorHooks(e,t,s,r){return r.catch(W.bind(this,e,t,s))}}Z.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class ee{constructor(e,t={}){this._currentUser=null,this._currentUserV2=null,e instanceof ee?this._requestMaker=e._requestMaker:(this._requestMaker=new Z(t),this._requestMaker.initializeToken(e))}setPrefix(e){this._prefix=e}cloneWithPrefix(e){let t=this.constructor(this);return t.setPrefix(e),t}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(e){return this.getPlugins().find(t=>t instanceof e)}hasHitRateLimit(e){var t;return!this.isRateLimitStatusObsolete(e)&&(null===(t=this.getLastRateLimitStatus(e))||void 0===t?void 0:t.remaining)===0}isRateLimitStatusObsolete(e){let t=this.getLastRateLimitStatus(e);return void 0===t||1e3*t.reset<Date.now()}getLastRateLimitStatus(e){let t=e.match(/^https?:\/\//)?e:this._prefix+e;return this._requestMaker.getRateLimits()[t]}getCurrentUserObject(e=!1){return!e&&this._currentUser?this._currentUser.value?Promise.resolve(this._currentUser.value):this._currentUser.promise:(this._currentUser=A(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:a})),this._currentUser.promise)}getCurrentUserV2Object(e=!1){return!e&&this._currentUserV2?this._currentUserV2.value?Promise.resolve(this._currentUserV2.value):this._currentUserV2.promise:(this._currentUserV2=A(()=>this.get("users/me",void 0,{prefix:r})),this._currentUserV2.promise)}async get(e,t={},{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"GET",query:t,...i});return s?a:a.data}async delete(e,t={},{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"DELETE",query:t,...i});return s?a:a.data}async post(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"POST",body:t,...i});return s?a:a.data}async put(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"PUT",body:t,...i});return s?a:a.data}async patch(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"PATCH",body:t,...i});return s?a:a.data}getStream(e,t,{prefix:s=this._prefix,...r}={}){return this._requestMaker.sendStream({url:s?s+e:e,method:"GET",query:t,...r})}postStream(e,t,{prefix:s=this._prefix,...r}={}){return this._requestMaker.sendStream({url:s?s+e:e,method:"POST",body:t,...r})}}class et extends ee{constructor(e){if(!(e instanceof ee))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(e)}}class es extends c{constructor(){super(...arguments),this.hasFinishedFetch=!1}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.push(...s),this.hasFinishedFetch=0===s.length)}getNextQueryParams(e){let t=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(e),max_id:(t-BigInt(1)).toString()}}getPageLengthFromRequest(e){return e.data.length}isFetchLastOver(e){return!e.data.length}canFetchNextPage(e){return e.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class er extends es{constructor(){super(...arguments),this._endpoint="statuses/home_timeline.json"}}class ei extends es{constructor(){super(...arguments),this._endpoint="statuses/mentions_timeline.json"}}class ea extends es{constructor(){super(...arguments),this._endpoint="statuses/user_timeline.json"}}class en extends es{constructor(){super(...arguments),this._endpoint="lists/statuses.json"}}class eo extends es{constructor(){super(...arguments),this._endpoint="favorites/list.json"}}class el extends h{constructor(){super(...arguments),this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class eu extends h{constructor(){super(...arguments),this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class ed extends h{constructor(){super(...arguments),this._endpoint="followers/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ec extends h{constructor(){super(...arguments),this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class eh extends h{constructor(){super(...arguments),this._endpoint="friends/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ep extends h{constructor(){super(...arguments),this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class em extends c{constructor(){super(...arguments),this._endpoint="users/search.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&this._realData.push(...s)}getNextQueryParams(e){var t;let s=Number(null!==(t=this._queryParams.page)&&void 0!==t?t:"1");return{...this._queryParams,page:s+1,...e?{count:e}:{}}}getPageLengthFromRequest(e){return e.data.length}isFetchLastOver(e){return!e.data.length}canFetchNextPage(e){return e.length>0}getItemArray(){return this.users}get users(){return this._realData}}class eg extends h{constructor(){super(...arguments),this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class e_ extends eg{constructor(){super(...arguments),this._endpoint="friendships/outgoing.json"}}class ef extends h{refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.lists.push(...s.lists),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class ew extends ef{constructor(){super(...arguments),this._endpoint="lists/memberships.json"}}class ey extends ef{constructor(){super(...arguments),this._endpoint="lists/ownerships.json"}}class ev extends ef{constructor(){super(...arguments),this._endpoint="lists/subscriptions.json"}}class eb extends h{refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ek extends eb{constructor(){super(...arguments),this._endpoint="lists/members.json"}}class ex extends eb{constructor(){super(...arguments),this._endpoint="lists/subscribers.json"}}class eS extends et{constructor(){super(...arguments),this._prefix=a}singleTweet(e,t={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:e,...t})}tweets(e,t={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:e,...t})}oembedTweet(e,t={}){return this.get("oembed",{url:`https://x.com/i/statuses/${e}`,...t},{prefix:"https://publish.x.com/"})}async homeTimeline(e={}){let t={tweet_mode:"extended",...e},s=await this.get("statuses/home_timeline.json",t,{fullResponse:!0});return new er({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async mentionTimeline(e={}){let t={tweet_mode:"extended",...e},s=await this.get("statuses/mentions_timeline.json",t,{fullResponse:!0});return new ei({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userTimeline(e,t={}){let s={tweet_mode:"extended",user_id:e,...t},r=await this.get("statuses/user_timeline.json",s,{fullResponse:!0});return new ea({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async userTimelineByUsername(e,t={}){let s={tweet_mode:"extended",screen_name:e,...t},r=await this.get("statuses/user_timeline.json",s,{fullResponse:!0});return new ea({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async favoriteTimeline(e,t={}){let s={tweet_mode:"extended",user_id:e,...t},r=await this.get("favorites/list.json",s,{fullResponse:!0});return new eo({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async favoriteTimelineByUsername(e,t={}){let s={tweet_mode:"extended",screen_name:e,...t},r=await this.get("favorites/list.json",s,{fullResponse:!0});return new eo({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}user(e){return this.get("users/show.json",{tweet_mode:"extended",...e})}users(e){return this.get("users/lookup.json",{tweet_mode:"extended",...e})}verifyCredentials(e={}){return this.get("account/verify_credentials.json",e)}async listMutedUsers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("mutes/users/list.json",t,{fullResponse:!0});return new el({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listMutedUserIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("mutes/users/ids.json",t,{fullResponse:!0});return new eu({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFriendList(e={}){let t={...e},s=await this.get("friends/list.json",t,{fullResponse:!0});return new eh({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowerList(e={}){let t={...e},s=await this.get("followers/list.json",t,{fullResponse:!0});return new ed({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowerIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("followers/ids.json",t,{fullResponse:!0});return new ec({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowingIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("friends/ids.json",t,{fullResponse:!0});return new ep({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async searchUsers(e,t={}){let s={q:e,tweet_mode:"extended",page:1,...t},r=await this.get("users/search.json",s,{fullResponse:!0});return new em({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}friendship(e){return this.get("friendships/show.json",e)}friendships(e){return this.get("friendships/lookup.json",e)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(e={}){let t={stringify_ids:!0,...e},s=await this.get("friendships/incoming.json",t,{fullResponse:!0});return new eg({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async friendshipsOutgoing(e={}){let t={stringify_ids:!0,...e},s=await this.get("friendships/outgoing.json",t,{fullResponse:!0});return new e_({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(e){return this.get("users/profile_banner.json",e)}list(e){return this.get("lists/show.json",{tweet_mode:"extended",...e})}lists(e={}){return this.get("lists/list.json",{tweet_mode:"extended",...e})}async listMembers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/members.json",t,{fullResponse:!0});return new ek({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}listGetMember(e){return this.get("lists/members/show.json",{tweet_mode:"extended",...e})}async listMemberships(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/memberships.json",t,{fullResponse:!0});return new ew({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listOwnerships(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/ownerships.json",t,{fullResponse:!0});return new ey({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listStatuses(e){let t={tweet_mode:"extended",...e},s=await this.get("lists/statuses.json",t,{fullResponse:!0});return new en({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listSubscribers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/subscribers.json",t,{fullResponse:!0});return new ex({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}listGetSubscriber(e){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...e})}async listSubscriptions(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/subscriptions.json",t,{fullResponse:!0});return new ev({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}mediaInfo(e){return this.get("media/upload.json",{command:"STATUS",media_id:e},{prefix:n})}filterStream({autoConnect:e,...t}={}){let s={};for(let[e,r]of Object.entries(t))"follow"===e||"track"===e?s[e]=r.toString():"locations"===e?s.locations=P(r).map(e=>`${e.lng},${e.lat}`).join(","):s[e]=r;return this.stream.postStream("statuses/filter.json",s,{autoConnect:e})}sampleStream({autoConnect:e,...t}={}){return this.stream.getStream("statuses/sample.json",t,{autoConnect:e})}get stream(){let e=new e$(this);return e.setPrefix("https://stream.x.com/1.1/"),e}trendsByPlace(e,t={}){return this.get("trends/place.json",{id:e,...t})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(e,t){return this.get("trends/closest.json",{lat:e,long:t})}geoPlace(e){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:e}})}geoSearch(e){return this.get("geo/search.json",e)}geoReverseGeoCode(e){return this.get("geo/reverse_geocode.json",e)}rateLimitStatuses(...e){return this.get("application/rate_limit_status.json",{resources:e})}supportedLanguages(){return this.get("help/languages.json")}}async function eT(e){let t=await eR(e);return"number"==typeof t?new Promise((e,s)=>{E.readFile(t,(t,r)=>{if(t)return s(t);e(r)})}):t instanceof Buffer?t:t.readFile()}function eR(e){if("string"==typeof e)return E.promises.open(e,"r");if("number"==typeof e||"object"==typeof e&&!(e instanceof Buffer)||e instanceof Buffer)return e;throw Error("Given file is not valid, please check its type.")}async function eE(e){return"number"==typeof e?(await new Promise((t,s)=>{E.fstat(e,(e,r)=>{e&&s(e),t(r)})})).size:e instanceof Buffer?e.length:(await e.stat()).size}function eD(e){return new Promise(t=>setTimeout(t,1e3*e))}async function eA(e,t,s=0,r){let i;if(e instanceof Buffer){let r=e.slice(s,s+t);return[r,r.length]}if(!r)throw Error("Well, we will need a buffer to store file content.");return i="number"==typeof e?await new Promise((i,a)=>{E.read(e,r,0,t,s,(e,t)=>{e&&a(e),i(t)})}):(await e.read(r,0,t,s)).bytesRead,[r,i]}let eP="media/upload.json";class eI extends eS{constructor(){super(...arguments),this._prefix=a}get readOnly(){return this}tweet(e,t={}){let s={status:e,tweet_mode:"extended",...t};return this.post("statuses/update.json",s)}async quote(e,t,s={}){return this.tweet(e,{...s,attachment_url:"https://x.com/i/statuses/"+t})}async tweetThread(e){let t=[];for(let s of e){let e=t.length?t[t.length-1]:null,r={..."string"==typeof s?{status:s}:s},i=e?e.id_str:r.in_reply_to_status_id,a=r.status;i?t.push(await this.reply(a,i,r)):t.push(await this.tweet(a,r))}return t}reply(e,t,s={}){return this.tweet(e,{auto_populate_reply_metadata:!0,in_reply_to_status_id:t,...s})}deleteTweet(e){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:e}})}reportUserAsSpam(e){return this.post("users/report_spam.json",{tweet_mode:"extended",...e})}updateFriendship(e){return this.post("friendships/update.json",e)}createFriendship(e){return this.post("friendships/create.json",e)}destroyFriendship(e){return this.post("friendships/destroy.json",e)}updateAccountSettings(e){return this.post("account/settings.json",e)}updateAccountProfile(e){return this.post("account/update_profile.json",e)}async updateAccountProfileBanner(e,t={}){let s={banner:await eT(e),...t};return this.post("account/update_profile_banner.json",s,{forceBodyMode:"form-data"})}async updateAccountProfileImage(e,t={}){let s={tweet_mode:"extended",image:await eT(e),...t};return this.post("account/update_profile_image.json",s,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(e){return this.post("lists/create.json",{tweet_mode:"extended",...e})}updateList(e){return this.post("lists/update.json",{tweet_mode:"extended",...e})}removeList(e){return this.post("lists/destroy.json",{tweet_mode:"extended",...e})}addListMembers(e){let t=e.user_id&&L(e.user_id)||e.screen_name&&L(e.screen_name);return this.post(t?"lists/members/create_all.json":"lists/members/create.json",e)}removeListMembers(e){let t=e.user_id&&L(e.user_id)||e.screen_name&&L(e.screen_name);return this.post(t?"lists/members/destroy_all.json":"lists/members/destroy.json",e)}subscribeToList(e){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...e})}unsubscribeOfList(e){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...e})}createMediaMetadata(e,t){return this.post("media/metadata/create.json",{media_id:e,...t},{prefix:n,forceBodyMode:"json"})}createMediaSubtitles(e,t){return this.post("media/subtitles/create.json",{media_id:e,media_category:"TweetVideo",subtitle_info:{subtitles:t}},{prefix:n,forceBodyMode:"json"})}deleteMediaSubtitles(e,...t){return this.post("media/subtitles/delete.json",{media_id:e,media_category:"TweetVideo",subtitle_info:{subtitles:t.map(e=>({language_code:e}))}},{prefix:n,forceBodyMode:"json"})}async uploadMedia(e,t={},s=!1){var r;let i=null!==(r=t.chunkLength)&&void 0!==r?r:1048576,{fileHandle:a,mediaCategory:o,fileSize:l,mimeType:u}=await this.getUploadMediaRequirements(e,t);try{let e=await this.post(eP,{command:"INIT",total_bytes:l,media_type:u,media_category:o,additional_owners:t.additionalOwners,shared:!!t.shared||void 0},{prefix:n});await this.mediaChunkedUpload(a,i,e.media_id_string,t.maxConcurrentUploads);let r=await this.post(eP,{command:"FINALIZE",media_id:e.media_id_string},{prefix:n});if(r.processing_info&&"succeeded"!==r.processing_info.state&&await this.awaitForMediaProcessingCompletion(r),s)return r;return r.media_id_string}finally{"number"==typeof e?E.close(e,()=>{}):"object"!=typeof a||a instanceof Buffer||a.close()}}async awaitForMediaProcessingCompletion(e){for(var t;;){let{processing_info:s}=e=await this.mediaInfo(e.media_id_string);if(!s||"succeeded"===s.state)return;if(null===(t=s.error)||void 0===t?void 0:t.code){let{name:e,message:t}=s.error;throw Error(`Failed to process media: ${e} - ${t}.`)}if("failed"===s.state)throw Error("Failed to process the media.");s.check_after_secs?await eD(s.check_after_secs):await eD(5)}}async getUploadMediaRequirements(e,{mimeType:t,type:s,target:r,longVideo:i}={}){let a;try{let o;a=await eR(e);let l=function(e,t,s){if("string"==typeof s)return s;if("string"==typeof e&&!t)return e.endsWith(".jpeg")||e.endsWith(".jpg")?v.Jpeg:e.endsWith(".png")?v.Png:e.endsWith(".webp")?v.Webp:e.endsWith(".gif")?v.Gif:e.endsWith(".mpeg4")||e.endsWith(".mp4")?v.Mp4:e.endsWith(".mov")||e.endsWith(".mov")?v.Mov:e.endsWith(".srt")?v.Srt:(O({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"options.mimeType is missing and filename couldn't help to resolve MIME type, so it will fallback to image/jpeg",resolution:"If you except to give filenames without extensions, please specify explicitlty the MIME type using options.mimeType"}),v.Jpeg);if("string"==typeof t)return(O({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"you're using options.type",resolution:"Remove options.type argument and migrate to options.mimeType which takes the real MIME type. If you're using type=longmp4, add options.longVideo alongside of mimeType=EUploadMimeType.Mp4"}),"gif"===t)?v.Gif:"jpg"===t?v.Jpeg:"png"===t?v.Png:"webp"===t?v.Webp:"srt"===t?v.Srt:"mp4"===t||"longmp4"===t?v.Mp4:"mov"===t?v.Mov:t;throw Error("You must specify type if file is a file handle or Buffer.")}(e,s,t);if(l!==v.Mp4||(t||s||"dm"===r)&&!i){var n;n=null!=r?r:"tweet",o=l===v.Mp4||l===v.Mov?"tweet"===n?"TweetVideo":"DmVideo":l===v.Gif?"tweet"===n?"TweetGif":"DmGif":l===v.Srt?"Subtitles":"tweet"===n?"TweetImage":"DmImage"}else o="amplify_video";return{fileHandle:a,mediaCategory:o,fileSize:await eE(a),mimeType:l}}catch(t){throw"number"==typeof e?E.close(e,()=>{}):"object"!=typeof a||a instanceof Buffer||a.close(),t}}async mediaChunkedUpload(e,t,s,r=3){let i,a,o=0;if(r<1)throw RangeError("Bad maxConcurrentUploads parameter.");let l=e instanceof Buffer?void 0:Buffer.alloc(t),u=0;[i,a]=await eA(e,t,u,l),u+=a;let d=new Set;for(;a;){let c=i.slice(0,a);if(c.length){let e=this.post(eP,{command:"APPEND",media_id:s,segment_index:o,media:c},{prefix:n});d.add(e),e.then(()=>{d.delete(e)}),o++}d.size>=r&&await Promise.race(d),[i,a]=await eA(e,t,u,l),u+=a}await Promise.all([...d])}}class eL extends eI{constructor(){super(...arguments),this._prefix=a}get readWrite(){return this}sendDm({recipient_id:e,custom_profile_id:t,...s}){let r={event:{type:b.Create,[b.Create]:{target:{recipient_id:e},message_data:s}}};return t&&(r.event[b.Create].custom_profile_id=t),this.post("direct_messages/events/new.json",r,{forceBodyMode:"json"})}getDmEvent(e){return this.get("direct_messages/events/show.json",{id:e})}deleteDm(e){return this.delete("direct_messages/events/destroy.json",{id:e})}async listDmEvents(e={}){let t={...e},s=await this.get("direct_messages/events/list.json",t,{fullResponse:!0});return new p({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}newWelcomeDm(e,t){let s={[b.WelcomeCreate]:{name:e,message_data:t}};return this.post("direct_messages/welcome_messages/new.json",s,{forceBodyMode:"json"})}getWelcomeDm(e){return this.get("direct_messages/welcome_messages/show.json",{id:e})}deleteWelcomeDm(e){return this.delete("direct_messages/welcome_messages/destroy.json",{id:e})}updateWelcomeDm(e,t){return this.put("direct_messages/welcome_messages/update.json",{message_data:t},{forceBodyMode:"json",query:{id:e}})}async listWelcomeDms(e={}){let t={...e},s=await this.get("direct_messages/welcome_messages/list.json",t,{fullResponse:!0});return new m({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}newWelcomeDmRule(e){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:e}},{forceBodyMode:"json"})}getWelcomeDmRule(e){return this.get("direct_messages/welcome_messages/rules/show.json",{id:e})}deleteWelcomeDmRule(e){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:e})}async listWelcomeDmRules(e={}){let t={...e};return this.get("direct_messages/welcome_messages/rules/list.json",t)}async setWelcomeDm(e,t=!0){var s;let r=await this.listWelcomeDmRules();if(null===(s=r.welcome_message_rules)||void 0===s?void 0:s.length)for(let e of r.welcome_message_rules)await this.deleteWelcomeDmRule(e.id),t&&await this.deleteWelcomeDm(e.welcome_message_id);return this.newWelcomeDmRule(e)}markDmAsRead(e,t){return this.post("direct_messages/mark_read.json",{last_read_event_id:e,recipient_id:t},{forceBodyMode:"url"})}indicateDmTyping(e){return this.post("direct_messages/indicate_typing.json",{recipient_id:e},{forceBodyMode:"url"})}async downloadDmImage(e){if("string"!=typeof e){let t=e[b.Create].message_data.attachment;if(!t)throw Error("The given direct message doesn't contain any attachment");e=t.media.media_url_https}let t=await this.get(e,void 0,{forceParseMode:"buffer",prefix:""});if(!t.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return t}}let e$=eL;class eO{constructor(e){this.result=e}get tweets(){return eO.tweets(this.result)}static tweets(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.tweets)&&void 0!==s?s:[]}tweetById(e){return eO.tweetById(this.result,e)}static tweetById(e,t){return this.tweets(e).find(e=>e.id===t)}retweet(e){return eO.retweet(this.result,e)}static retweet(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"retweeted"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}quote(e){return eO.quote(this.result,e)}static quote(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"quoted"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}repliedTo(e){return eO.repliedTo(this.result,e)}static repliedTo(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"replied_to"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}author(e){return eO.author(this.result,e)}static author(e,t){let s=t.author_id;return s?this.users(e).find(e=>e.id===s):void 0}repliedToAuthor(e){return eO.repliedToAuthor(this.result,e)}static repliedToAuthor(e,t){let s=t.in_reply_to_user_id;return s?this.users(e).find(e=>e.id===s):void 0}get users(){return eO.users(this.result)}static users(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.users)&&void 0!==s?s:[]}userById(e){return eO.userById(this.result,e)}static userById(e,t){return this.users(e).find(e=>e.id===t)}pinnedTweet(e){return eO.pinnedTweet(this.result,e)}static pinnedTweet(e,t){return t.pinned_tweet_id?this.tweets(e).find(e=>e.id===t.pinned_tweet_id):void 0}get media(){return eO.media(this.result)}static media(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.media)&&void 0!==s?s:[]}medias(e){return eO.medias(this.result,e)}static medias(e,t){var s,r;let i=null!==(r=null===(s=t.attachments)||void 0===s?void 0:s.media_keys)&&void 0!==r?r:[];return this.media(e).filter(e=>i.includes(e.media_key))}get polls(){return eO.polls(this.result)}static polls(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.polls)&&void 0!==s?s:[]}poll(e){return eO.poll(this.result,e)}static poll(e,t){var s,r;let i=null!==(r=null===(s=t.attachments)||void 0===s?void 0:s.poll_ids)&&void 0!==r?r:[];if(i.length){let t=i[0];return this.polls(e).find(e=>e.id===t)}}get places(){return eO.places(this.result)}static places(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.places)&&void 0!==s?s:[]}place(e){return eO.place(this.result,e)}static place(e,t){var s;let r=null===(s=t.geo)||void 0===s?void 0:s.place_id;return r?this.places(e).find(e=>e.id===r):void 0}listOwner(e){return eO.listOwner(this.result,e)}static listOwner(e,t){let s=t.owner_id;return s?this.users(e).find(e=>e.id===s):void 0}spaceCreator(e){return eO.spaceCreator(this.result,e)}static spaceCreator(e,t){let s=t.creator_id;return s?this.users(e).find(e=>e.id===s):void 0}spaceHosts(e){return eO.spaceHosts(this.result,e)}static spaceHosts(e,t){var s;let r=null!==(s=t.host_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}spaceSpeakers(e){return eO.spaceSpeakers(this.result,e)}static spaceSpeakers(e,t){var s;let r=null!==(s=t.speaker_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}spaceInvitedUsers(e){return eO.spaceInvitedUsers(this.result,e)}static spaceInvitedUsers(e,t){var s;let r=null!==(s=t.invited_user_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}}class eq extends d{updateIncludes(e){if(e.errors&&(this._realData.errors||(this._realData.errors=[]),this._realData.errors=[...this._realData.errors,...e.errors]),!e.includes)return;this._realData.includes||(this._realData.includes={});let t=this._realData.includes;for(let[s,r]of Object.entries(e.includes))t[s]||(t[s]=[]),t[s]=[...t[s],...r]}assertUsable(){if(this.unusable)throw Error("Unable to use this paginator to fetch more data, as it does not contain any metadata. Check .errors property for more details.")}get meta(){return this._realData.meta}get includes(){var e;return(null===(e=this._realData)||void 0===e?void 0:e.includes)?this._includesInstance?this._includesInstance:this._includesInstance=new eO(this._realData):new eO(this._realData)}get errors(){var e;return null!==(e=this._realData.errors)&&void 0!==e?e:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class ej extends eq{refreshInstanceFromResult(e,t){var s;let r=e.data,i=null!==(s=r.data)&&void 0!==s?s:[];this._rateLimit=e.rateLimit,this._realData.data||(this._realData.data=[]),t?(this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.next_token=r.meta.next_token,this._realData.data.push(...i)):(this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.previous_token=r.meta.previous_token,this._realData.data.unshift(...i)),this.updateIncludes(r)}getNextQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(e){var t,s;return null!==(s=null===(t=e.data.data)||void 0===t?void 0:t.length)&&void 0!==s?s:0}isFetchLastOver(e){var t;return!(null===(t=e.data.data)||void 0===t?void 0:t.length)||!this.canFetchNextPage(e.data)}canFetchNextPage(e){var t;return!!(null===(t=e.meta)||void 0===t?void 0:t.next_token)}}class eC extends eq{refreshInstanceFromResult(e,t){var s;let r=e.data,i=null!==(s=r.data)&&void 0!==s?s:[];this._rateLimit=e.rateLimit,this._realData.data||(this._realData.data=[]),t?(this._realData.meta.oldest_id=r.meta.oldest_id,this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.next_token=r.meta.next_token,this._realData.data.push(...i)):(this._realData.meta.newest_id=r.meta.newest_id,this._realData.meta.result_count+=r.meta.result_count,this._realData.data.unshift(...i)),this.updateIncludes(r)}getNextQueryParams(e){this.assertUsable();let t={...this.injectQueryParams(e)};return this._realData.meta.next_token?t.next_token=this._realData.meta.next_token:(t.start_time&&(t.since_id=this.dateStringToSnowflakeId(t.start_time),delete t.start_time),t.end_time&&delete t.end_time,t.until_id=this._realData.meta.oldest_id),t}getPreviousQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(e){var t,s;return null!==(s=null===(t=e.data.data)||void 0===t?void 0:t.length)&&void 0!==s?s:0}isFetchLastOver(e){var t;return!(null===(t=e.data.data)||void 0===t?void 0:t.length)||!this.canFetchNextPage(e.data)}canFetchNextPage(e){return!!e.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(e){let t=BigInt("1288834974657"),s=new Date(e);if(isNaN(s.valueOf()))throw Error("Unable to convert start_time/end_time to a valid date. A ISO 8601 DateTime is excepted, please check your input.");return(BigInt(s.valueOf())-t<<BigInt("22")).toString()}get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eN extends ej{refreshInstanceFromResult(e,t){super.refreshInstanceFromResult(e,t);let s=e.data;t?this._realData.meta.oldest_id=s.meta.oldest_id:this._realData.meta.newest_id=s.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eF extends eC{constructor(){super(...arguments),this._endpoint="tweets/search/recent"}}class eM extends eC{constructor(){super(...arguments),this._endpoint="tweets/search/all"}}class eU extends eN{constructor(){super(...arguments),this._endpoint="tweets/:id/quote_tweets"}}class eB extends eN{constructor(){super(...arguments),this._endpoint="users/:id/timelines/reverse_chronological"}}class eH extends eN{constructor(){super(...arguments),this._endpoint="users/:id/tweets"}}class eV extends eN{constructor(){super(...arguments),this._endpoint="users/:id/mentions"}}class eW extends eN{constructor(){super(...arguments),this._endpoint="users/:id/bookmarks"}}class eK extends ej{get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class eY extends eK{constructor(){super(...arguments),this._endpoint="users/:id/liked_tweets"}}class eJ extends eK{constructor(){super(...arguments),this._endpoint="lists/:id/tweets"}}class ez extends ej{getItemArray(){return this.users}get users(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eG extends ez{constructor(){super(...arguments),this._endpoint="users/:id/blocking"}}class eX extends ez{constructor(){super(...arguments),this._endpoint="users/:id/muting"}}class eQ extends ez{constructor(){super(...arguments),this._endpoint="users/:id/followers"}}class eZ extends ez{constructor(){super(...arguments),this._endpoint="users/:id/following"}}class e0 extends ez{constructor(){super(...arguments),this._endpoint="lists/:id/members"}}class e1 extends ez{constructor(){super(...arguments),this._endpoint="lists/:id/followers"}}class e2 extends ez{constructor(){super(...arguments),this._endpoint="tweets/:id/liking_users"}}class e8 extends ez{constructor(){super(...arguments),this._endpoint="tweets/:id/retweeted_by"}}class e4 extends ej{getItemArray(){return this.lists}get lists(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class e5 extends e4{constructor(){super(...arguments),this._endpoint="users/:id/owned_lists"}}class e3 extends e4{constructor(){super(...arguments),this._endpoint="users/:id/list_memberships"}}class e7 extends e4{constructor(){super(...arguments),this._endpoint="users/:id/followed_lists"}}class e6 extends et{constructor(){super(...arguments),this._prefix=i}}class e9 extends ej{getItemArray(){return this.events}get events(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class te extends e9{constructor(){super(...arguments),this._endpoint="dm_events"}}class tt extends e9{constructor(){super(...arguments),this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class ts extends e9{constructor(){super(...arguments),this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class tr extends et{constructor(){super(...arguments),this._prefix=r}get labs(){return this._labs?this._labs:this._labs=new e6(this)}async search(e,t={}){let s="string"==typeof e?{...t,query:e}:{...e},r=await this.get("tweets/search/recent",s,{fullResponse:!0});return new eF({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async searchAll(e,t={}){let s={...t,query:e},r=await this.get("tweets/search/all",s,{fullResponse:!0});return new eM({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}singleTweet(e,t={}){return this.get("tweets/:id",t,{params:{id:e}})}tweets(e,t={}){return this.get("tweets",{ids:e,...t})}tweetCountRecent(e,t={}){return this.get("tweets/counts/recent",{query:e,...t})}tweetCountAll(e,t={}){return this.get("tweets/counts/all",{query:e,...t})}async tweetRetweetedBy(e,t={}){let{asPaginator:s,...r}=t,i=await this.get("tweets/:id/retweeted_by",r,{fullResponse:!0,params:{id:e}});return s?new e8({realData:i.data,rateLimit:i.rateLimit,instance:this,queryParams:r,sharedParams:{id:e}}):i.data}async tweetLikedBy(e,t={}){let{asPaginator:s,...r}=t,i=await this.get("tweets/:id/liking_users",r,{fullResponse:!0,params:{id:e}});return s?new e2({realData:i.data,rateLimit:i.rateLimit,instance:this,queryParams:r,sharedParams:{id:e}}):i.data}async homeTimeline(e={}){let t=await this.getCurrentUserV2Object(),s=await this.get("users/:id/timelines/reverse_chronological",e,{fullResponse:!0,params:{id:t.data.id}});return new eB({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:e,sharedParams:{id:t.data.id}})}async userTimeline(e,t={}){let s=await this.get("users/:id/tweets",t,{fullResponse:!0,params:{id:e}});return new eH({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async userMentionTimeline(e,t={}){let s=await this.get("users/:id/mentions",t,{fullResponse:!0,params:{id:e}});return new eV({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async quotes(e,t={}){let s=await this.get("tweets/:id/quote_tweets",t,{fullResponse:!0,params:{id:e}});return new eU({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async bookmarks(e={}){let t=await this.getCurrentUserV2Object(),s=await this.get("users/:id/bookmarks",e,{fullResponse:!0,params:{id:t.data.id}});return new eW({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:e,sharedParams:{id:t.data.id}})}me(e={}){return this.get("users/me",e)}user(e,t={}){return this.get("users/:id",t,{params:{id:e}})}users(e,t={}){let s=Array.isArray(e)?e.join(","):e;return this.get("users",{...t,ids:s})}userByUsername(e,t={}){return this.get("users/by/username/:username",t,{params:{username:e}})}usersByUsernames(e,t={}){return e=Array.isArray(e)?e.join(","):e,this.get("users/by",{...t,usernames:e})}async followers(e,t={}){let{asPaginator:s,...r}=t,i={id:e};if(!s)return this.get("users/:id/followers",r,{params:i});let a=await this.get("users/:id/followers",r,{fullResponse:!0,params:i});return new eQ({realData:a.data,rateLimit:a.rateLimit,instance:this,queryParams:r,sharedParams:i})}async following(e,t={}){let{asPaginator:s,...r}=t,i={id:e};if(!s)return this.get("users/:id/following",r,{params:i});let a=await this.get("users/:id/following",r,{fullResponse:!0,params:i});return new eZ({realData:a.data,rateLimit:a.rateLimit,instance:this,queryParams:r,sharedParams:i})}async userLikedTweets(e,t={}){let s={id:e},r=await this.get("users/:id/liked_tweets",t,{fullResponse:!0,params:s});return new eY({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async userBlockingUsers(e,t={}){let s={id:e},r=await this.get("users/:id/blocking",t,{fullResponse:!0,params:s});return new eG({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async userMutingUsers(e,t={}){let s={id:e},r=await this.get("users/:id/muting",t,{fullResponse:!0,params:s});return new eX({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}list(e,t={}){return this.get("lists/:id",t,{params:{id:e}})}async listsOwned(e,t={}){let s={id:e},r=await this.get("users/:id/owned_lists",t,{fullResponse:!0,params:s});return new e5({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listMemberships(e,t={}){let s={id:e},r=await this.get("users/:id/list_memberships",t,{fullResponse:!0,params:s});return new e3({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listFollowed(e,t={}){let s={id:e},r=await this.get("users/:id/followed_lists",t,{fullResponse:!0,params:s});return new e7({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listTweets(e,t={}){let s={id:e},r=await this.get("lists/:id/tweets",t,{fullResponse:!0,params:s});return new eJ({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listMembers(e,t={}){let s={id:e},r=await this.get("lists/:id/members",t,{fullResponse:!0,params:s});return new e0({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listFollowers(e,t={}){let s={id:e},r=await this.get("lists/:id/followers",t,{fullResponse:!0,params:s});return new e1({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listDmEvents(e={}){let t=await this.get("dm_events",e,{fullResponse:!0});return new te({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...e}})}async listDmEventsWithParticipant(e,t={}){let s={participant_id:e},r=await this.get("dm_conversations/with/:participant_id/dm_events",t,{fullResponse:!0,params:s});return new tt({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listDmEventsOfConversation(e,t={}){let s={dm_conversation_id:e},r=await this.get("dm_conversations/:dm_conversation_id/dm_events",t,{fullResponse:!0,params:s});return new ts({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}space(e,t={}){return this.get("spaces/:id",t,{params:{id:e}})}spaces(e,t={}){return this.get("spaces",{ids:e,...t})}spacesByCreators(e,t={}){return this.get("spaces/by/creator_ids",{user_ids:e,...t})}searchSpaces(e){return this.get("spaces/search",e)}spaceBuyers(e,t={}){return this.get("spaces/:id/buyers",t,{params:{id:e}})}spaceTweets(e,t={}){return this.get("spaces/:id/tweets",t,{params:{id:e}})}searchStream({autoConnect:e,...t}={}){return this.getStream("tweets/search/stream",t,{payloadIsError:I,autoConnect:e})}streamRules(e={}){return this.get("tweets/search/stream/rules",e)}updateStreamRules(e,t={}){return this.post("tweets/search/stream/rules",e,{query:t})}sampleStream({autoConnect:e,...t}={}){return this.getStream("tweets/sample/stream",t,{payloadIsError:I,autoConnect:e})}sample10Stream({autoConnect:e,...t}={}){return this.getStream("tweets/sample10/stream",t,{payloadIsError:I,autoConnect:e})}complianceJobs(e){return this.get("compliance/jobs",e)}complianceJob(e){return this.get("compliance/jobs/:id",void 0,{params:{id:e}})}async sendComplianceJob(e){let t=await this.post("compliance/jobs",{type:e.type,name:e.name}),s=e.ids instanceof Buffer?e.ids:Buffer.from(e.ids.join("\n"));return await this.put(t.data.upload_url,s,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),t}async complianceJobResult(e){let t=e;for(;"complete"!==t.status;){if("expired"===t.status||"failed"===t.status)throw Error("Job failed to be completed.");await new Promise(e=>setTimeout(e,3500)),t=(await this.complianceJob(e.id)).data}return(await this.get(e.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split("\n").filter(e=>e).map(e=>JSON.parse(e))}async usage(e={}){return this.get("usage/tweets",e)}community(e,t={}){return this.get("communities/:id",t,{params:{id:e}})}searchCommunities(e,t={}){return this.get("communities/search",{query:e,...t})}}class ti extends e6{constructor(){super(...arguments),this._prefix=i}get readOnly(){return this}}class ta extends tr{constructor(){super(...arguments),this._prefix=r}get readOnly(){return this}get labs(){return this._labs?this._labs:this._labs=new ti(this)}hideReply(e,t){return this.put("tweets/:id/hidden",{hidden:t},{params:{id:e}})}like(e,t){return this.post("users/:id/likes",{tweet_id:t},{params:{id:e}})}unlike(e,t){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:e,tweet_id:t}})}retweet(e,t){return this.post("users/:id/retweets",{tweet_id:t},{params:{id:e}})}unretweet(e,t){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:e,tweet_id:t}})}tweet(e,t={}){return t="object"==typeof e?e:{text:e,...t},this.post("tweets",t)}async uploadMedia(e,t,s=1048576){let r=t.media_category;!t.media_category&&(t.media_type.includes("gif")?r="tweet_gif":t.media_type.includes("image")?r="tweet_image":t.media_type.includes("video")&&(r="tweet_video"));let i={additional_owners:t.additional_owners,media_type:t.media_type,total_bytes:e.length,media_category:r},a=(await this.post("media/upload/initialize",i)).data.id,n=Math.ceil(e.length/s),o=new Uint8Array(e);for(let t=0;t<n;t++){let r=t*s,i=Math.min(r+s,e.length),n=o.slice(r,i),l={segment_index:t,media:Buffer.from(n)};await this.post(`media/upload/${a}/append`,l,{forceBodyMode:"form-data"})}return(await this.post(`media/upload/${a}/finalize`)).data.processing_info&&await this.waitForMediaProcessing(a),a}async waitForMediaProcessing(e){var t;let s=(await this.get("media/upload",{command:"STATUS",media_id:e})).data.processing_info;if(s)switch(s.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${null===(t=s.error)||void 0===t?void 0:t.message}`);case"pending":case"in_progress":{let t=null==s?void 0:s.check_after_secs;t&&t>0&&(await new Promise(e=>setTimeout(e,1e3*t)),await this.waitForMediaProcessing(e))}}}createMediaMetadata(e,t){return this.post("media/metadata",{id:e,metadata:t})}reply(e,t,s={}){var r;let i={in_reply_to_tweet_id:t,...null!==(r=s.reply)&&void 0!==r?r:{}};return this.post("tweets",{text:e,...s,reply:i})}quote(e,t,s={}){return this.tweet(e,{...s,quote_tweet_id:t})}async tweetThread(e){var t,s;let r=[];for(let i of e){let e=r.length?r[r.length-1]:null,a={..."string"==typeof i?{text:i}:i},n=e?e.data.id:null===(t=a.reply)||void 0===t?void 0:t.in_reply_to_tweet_id,o=null!==(s=a.text)&&void 0!==s?s:"";n?r.push(await this.reply(o,n,a)):r.push(await this.tweet(o,a))}return r}deleteTweet(e){return this.delete("tweets/:id",void 0,{params:{id:e}})}async bookmark(e){let t=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:e},{params:{id:t.data.id}})}async deleteBookmark(e){let t=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:t.data.id,tweet_id:e}})}follow(e,t){return this.post("users/:id/following",{target_user_id:t},{params:{id:e}})}unfollow(e,t){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}block(e,t){return this.post("users/:id/blocking",{target_user_id:t},{params:{id:e}})}unblock(e,t){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}mute(e,t){return this.post("users/:id/muting",{target_user_id:t},{params:{id:e}})}unmute(e,t){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}createList(e){return this.post("lists",e)}updateList(e,t={}){return this.put("lists/:id",t,{params:{id:e}})}removeList(e){return this.delete("lists/:id",void 0,{params:{id:e}})}addListMember(e,t){return this.post("lists/:id/members",{user_id:t},{params:{id:e}})}removeListMember(e,t){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:e,user_id:t}})}subscribeToList(e,t){return this.post("users/:id/followed_lists",{list_id:t},{params:{id:e}})}unsubscribeOfList(e,t){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:e,list_id:t}})}pinList(e,t){return this.post("users/:id/pinned_lists",{list_id:t},{params:{id:e}})}unpinList(e,t){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:e,list_id:t}})}sendDmInConversation(e,t){return this.post("dm_conversations/:dm_conversation_id/messages",t,{params:{dm_conversation_id:e}})}sendDmToParticipant(e,t){return this.post("dm_conversations/with/:participant_id/messages",t,{params:{participant_id:e}})}createDmConversation(e){return this.post("dm_conversations",e)}}class tn extends ti{constructor(){super(...arguments),this._prefix=i}get readWrite(){return this}}class to extends ta{constructor(){super(...arguments),this._prefix=r}get readWrite(){return this}get labs(){return this._labs?this._labs:this._labs=new tn(this)}}class tl extends ee{get v1(){return this._v1?this._v1:this._v1=new eS(this)}get v2(){return this._v2?this._v2:this._v2=new tr(this)}async currentUser(e=!1){return await this.getCurrentUserObject(e)}async currentUserV2(e=!1){return await this.getCurrentUserV2Object(e)}search(e,t){return this.v2.search(e,t)}async generateAuthLink(e="oob",{authAccessType:t,linkMode:s="authenticate",forceLogin:r,screenName:i}={}){let a=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:e,x_auth_access_type:t}),n=`https://api.x.com/oauth/${s}?oauth_token=${encodeURIComponent(a.oauth_token)}`;return void 0!==r&&(n+=`&force_login=${encodeURIComponent(r)}`),void 0!==i&&(n+=`&screen_name=${encodeURIComponent(i)}`),this._requestMaker.hasPlugins()&&this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:n,oauthResult:a}),{url:n,...a}}async login(e){let t=this.getActiveTokens();if("oauth-1.0a"!==t.type)throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let s=await this.post("https://api.x.com/oauth/access_token",{oauth_token:t.accessToken,oauth_verifier:e}),r=new this.constructor({appKey:t.appKey,appSecret:t.appSecret,accessToken:s.oauth_token,accessSecret:s.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:s.oauth_token,accessSecret:s.oauth_token_secret,userId:s.user_id,screenName:s.screen_name,client:r}}async appLogin(){let e=this.getActiveTokens();if("oauth-1.0a"!==e.type)throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let t=new this.constructor({username:e.appKey,password:e.appSecret},this._requestMaker.clientSettings),s=await t.post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor(s.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(e,t={}){var s,r;if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. You can find your client ID in Twitter Developer Portal. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let i=null!==(s=t.state)&&void 0!==s?s:Q.generateRandomString(32),a=Q.getCodeVerifier(),n=Q.getCodeChallengeFromVerifier(a),o=null!==(r=t.scope)&&void 0!==r?r:"",l=Array.isArray(o)?o.join(" "):o,u=new URL("https://x.com/i/oauth2/authorize"),d={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:e,state:i,code_challenge:n,code_challenge_method:"s256",scope:l};X.addQueryParamsToUrl(u,d);let c={url:u.toString(),state:i,codeVerifier:a,codeChallenge:n};return this._requestMaker.hasPlugins()&&this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:c,redirectUri:e}),c}async loginWithOAuth2({code:e,codeVerifier:t,redirectUri:s}){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let r=await this.post("https://api.x.com/2/oauth2/token",{code:e,code_verifier:t,redirect_uri:s,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(r)}async refreshOAuth2Token(e){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let t=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:e,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(t)}async revokeOAuth2Token(e,t="access_token"){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");return await this.post("https://api.x.com/2/oauth2/revoke",{client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret,token:e,token_type_hint:t})}parseOAuth2AccessTokenResult(e){let t=new this.constructor(e.access_token,this._requestMaker.clientSettings),s=e.scope.split(" ").filter(e=>e);return{client:t,expiresIn:e.expires_in,accessToken:e.access_token,scope:s,refreshToken:e.refresh_token}}}class tu extends tl{get v1(){return this._v1?this._v1:this._v1=new eI(this)}get v2(){return this._v2?this._v2:this._v2=new ta(this)}get readOnly(){return this}}class td extends et{constructor(){super(...arguments),this._prefix=o}}class tc extends td{constructor(){super(...arguments),this._prefix=o}get readOnly(){return this}}class th extends et{constructor(){super(...arguments),this._prefix=l}}class tp extends th{constructor(){super(...arguments),this._prefix=l}get readOnly(){return this}}class tm extends tp{constructor(){super(...arguments),this._prefix=l}get readWrite(){return this}}class tg extends tc{constructor(){super(...arguments),this._prefix=o}get readWrite(){return this}get sandbox(){return this._sandbox?this._sandbox:this._sandbox=new tm(this)}}class t_ extends tu{get v1(){return this._v1?this._v1:this._v1=new e$(this)}get v2(){return this._v2?this._v2:this._v2=new to(this)}get readWrite(){return this}get ads(){return this._ads?this._ads:this._ads=new tg(this)}static getErrors(e){var t;return"object"==typeof e&&"data"in e&&null!==(t=e.data.errors)&&void 0!==t?t:[]}static getProfileImageInSize(e,t){let s=e.split("/").pop(),r=e;for(let t of["normal","bigger","mini"])if(s.includes(`_${t}`)){r=e.replace(`_${t}`,"");break}if("original"===t)return r;let i=r.lastIndexOf(".");if(-1===i)return r+"_"+t;{let e=r.slice(i+1);return r.slice(0,i)+"_"+t+"."+e}}}let tf=t_},7786:(e,t,s)=>{"use strict";s.d(t,{ET:()=>d,QN:()=>n,Ug:()=>u,b0:()=>a,pF:()=>o,wE:()=>l});var r=s(5315),i=s(2048);let a=function(){let e=process.cwd();if(i.existsSync(r.join(e,"data","config.json")))return e;try{for(let t of i.readdirSync(e,{withFileTypes:!0}))if(t.isDirectory()){let s=r.join(e,t.name,"data","config.json");if(i.existsSync(s))return r.join(e,t.name)}}catch{}let t=e;for(let e=0;e<5;e++){let e=r.dirname(t);if(e===t)break;if(i.existsSync(r.join(e,"data","config.json")))return e;t=e}return e}(),n=r.join(a,"data");r.join(a,"STATUS.md"),r.join(a,"TODO.md"),r.join(a,"MEMORY.md");let o=r.join(n,"ideas.json"),l=r.join(n,"goals.json");r.join(n,"sessions.json"),r.join(n,"config.json"),r.join(n,"business-context.json"),r.join(n,"hypotheses.json"),r.join(n,"implementations.json"),r.join(n,"roadmap.json"),r.join(n,"competitors.json");let u=r.join(n,"positioning.json");r.join(n,"pages.json"),r.join(n,"payments.json"),r.join(n,"posthog.json");let d=r.join(n,"social.json"),c=r.join(__dirname,"..","..","templates");r.join(c,"commands")},7530:(e,t,s)=>{"use strict";s.d(t,{$O:()=>l,Fb:()=>u,cq:()=>c,gJ:()=>d});var r=s(2048),i=s(7786);let a="#buildinpublic";function n(e,t=280){return e.length<=t?e:e.slice(0,t-3).trimEnd()+"..."}function o(e,t){try{if(!r.existsSync(e))return t;return JSON.parse(r.readFileSync(e,"utf-8"))}catch{return t}}function l(e){if(!e){let t=o(i.pF,{ideas:[]}).ideas.filter(e=>"shipped"===e.stage).sort((e,t)=>(t.implementation?.completed_at||t.updated_at).localeCompare(e.implementation?.completed_at||e.updated_at));if(0===t.length)return null;e=t[0]}return n(`Just shipped: ${e.title}. ${e.summary} ${a}`)}function u(e,t,s){if(e&&null!=t&&null!=s)return n(`Hit ${t} ${e}! ${s>0?Math.round(t/s*100):100}% to goal ${a}`);for(let e of o(i.wE,{goals:[]}).goals)for(let t of e.kpis)if(null!=t.current_value&&null!=t.target_value&&t.current_value>=t.target_value){let e=Math.round(t.current_value/t.target_value*100);return n(`Hit ${t.current_value} ${t.name}! ${e}% to goal ${a}`)}return null}function d(e){if(!e){let t=o(i.pF,{ideas:[]}),s=new Date(Date.now()-6048e5).toISOString(),r=t.ideas.filter(e=>"shipped"===e.stage&&(e.implementation?.completed_at||e.updated_at)>s);if(0===r.length)return null;e={ideasShipped:r.length,kpisMoved:0,topShip:r[0]?.title}}let t=["Weekly recap:"];return t.push(`${e.ideasShipped} feature${1!==e.ideasShipped?"s":""} shipped`),e.kpisMoved>0&&t.push(`${e.kpisMoved} KPI${1!==e.kpisMoved?"s":""} moved`),e.topShip&&t.push(`Top: ${e.topShip}`),n(`${t.join(". ")}. ${a}`)}function c(e){if(!e&&(e=o(i.Ug,null),!e?.current))return null;let t=e.current.tagline,s=e.current.value_proposition,r=s.split(/[.!]/).filter(Boolean)[0]?.trim();return r?n(`${t} — ${r}. ${a}`):n(`${t} ${a}`)}},7151:(e,t,s)=>{"use strict";s.r(t),s.d(t,{executeSocialTask:()=>K,gatherKickstartContext:()=>J,isSocialTask:()=>W,readSocialFreshness:()=>Y});var r=s(2048),i=s(5315),a=s(9576),n=s(7786);function o(){let e=function(e){let t=i.join(e,".env");if(!r.existsSync(t))return{};let s=r.readFileSync(t,"utf-8"),a={};for(let e of s.split("\n")){let t=e.trim();if(!t||t.startsWith("#"))continue;let s=t.indexOf("=");if(-1===s)continue;let r=t.slice(0,s).trim(),i=t.slice(s+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),a[r]=i}return a}(n.b0),t=e.X_API_KEY||process.env.X_API_KEY,s=e.X_API_SECRET||process.env.X_API_SECRET,a=e.X_ACCESS_TOKEN||process.env.X_ACCESS_TOKEN,o=e.X_ACCESS_SECRET||process.env.X_ACCESS_SECRET;return t&&s&&a&&o?{apiKey:t,apiSecret:s,accessToken:a,accessSecret:o}:null}function l(e){let t;try{let e=s(1401).resolve("twitter-api-v2",{paths:[n.b0]}),r=s(1401)(e);t=r.TwitterApi||r.default?.TwitterApi||r.default}catch{try{let e=s(5883);t=e.TwitterApi||e.default?.TwitterApi||e.default}catch{throw Error("twitter-api-v2 is not installed. Run: npm install twitter-api-v2")}}if("function"!=typeof t)throw Error("Could not find TwitterApi constructor in twitter-api-v2");return new t({appKey:e.apiKey,appSecret:e.apiSecret,accessToken:e.accessToken,accessSecret:e.accessSecret})}async function u(e){try{let t=await e.v2.me({"user.fields":["public_metrics"]}),s=t?.data;if(!s?.username)return{valid:!1,username:null,followersCount:null};return{valid:!0,username:`@${s.username}`,followersCount:s.public_metrics?.followers_count??null}}catch{return{valid:!1,username:null,followersCount:null}}}async function d(e,t){if(t.length>280)throw Error(`Tweet exceeds 280 characters (${t.length})`);let s=await e.v2.tweet(t),r=s?.data?.id;if(!r)throw Error("Tweet posted but no ID returned");return{id:r,url:`https://x.com/i/status/${r}`}}async function c(e,t){if(!s(2048).existsSync(t))throw Error(`Media file not found: ${t}`);let r=await e.v1.uploadMedia(t);if(!r)throw Error("Media uploaded but no media_id returned");return String(r)}async function h(e,t,s){if(t.length>280)throw Error(`Tweet exceeds 280 characters (${t.length})`);if(0===s.length)throw Error("No media IDs provided");if(s.length>4)throw Error("X allows max 4 media attachments per tweet");let r=await e.v2.tweet(t,{media:{media_ids:s}}),i=r?.data?.id;if(!i)throw Error("Tweet posted but no ID returned");return{id:i,url:`https://x.com/i/status/${i}`}}async function p(e,t){try{let s=await e.v2.singleTweet(t,{"tweet.fields":["public_metrics","non_public_metrics","organic_metrics"]}),r=s?.data;if(!r)return null;let i=r.public_metrics??{},a=r.non_public_metrics??{},n=r.organic_metrics??{},o=a.impression_count??n.impression_count??0,l=(i.like_count??0)+(i.retweet_count??0)+(i.reply_count??0)+(i.bookmark_count??0)+(a.url_link_clicks??0)+(a.user_profile_clicks??0);return{tweet_id:t,impressions:o,likes:i.like_count??0,retweets:i.retweet_count??0,replies:i.reply_count??0,bookmarks:i.bookmark_count??0,profile_clicks:a.user_profile_clicks??0,engagements:l,engagement_rate:o>0?l/o:0,fetched_at:new Date().toISOString()}}catch(e){return console.error(`Failed to fetch metrics for tweet ${t}:`,e),null}}async function m(e,t){let s=[];for(let r of t){let t=await p(e,r);t&&s.push(t)}return s}async function g(e,t,s){if(t.length>280)throw Error(`Reply exceeds 280 characters (${t.length})`);let r=await e.v2.tweet(t,{reply:{in_reply_to_tweet_id:s}}),i=r?.data?.id;if(!i)throw Error("Reply posted but no ID returned");return{id:i,url:`https://x.com/i/status/${i}`}}async function _(e,t,s=10){let r=await e.v2.search(t,{max_results:Math.min(s,100),"tweet.fields":["public_metrics","created_at","author_id"],"user.fields":["username","name","public_metrics"],expansions:["author_id"]}),i=r?.data?.data??[],a=r?.data?.includes?.users??r?.includes?.users??[],n=new Map;for(let e of a)n.set(e.id,{username:e.username,name:e.name,followers:e.public_metrics?.followers_count??0});let o=[];for(let e of i){let t=n.get(e.author_id),s=e.public_metrics??{};o.push({id:e.id,text:e.text,author_id:e.author_id,author_username:t?.username??"unknown",author_name:t?.name??"Unknown",author_followers:t?.followers??0,like_count:s.like_count??0,retweet_count:s.retweet_count??0,reply_count:s.reply_count??0,bookmark_count:s.bookmark_count??0,created_at:e.created_at??"",url:`https://x.com/${t?.username??"i"}/status/${e.id}`})}return o}async function f(e,t,s){if(0===t.length)throw Error("Thread must have at least one tweet");if(t.length>25)throw Error("Thread cannot exceed 25 tweets");for(let e=0;e<t.length;e++)if(t[e].length>280)throw Error(`Tweet ${e+1} exceeds 280 characters (${t[e].length})`);let r=[];for(let i=0;i<t.length;i++){let a=t[i],n=s?.[i],o={};i>0&&(o.reply={in_reply_to_tweet_id:r[i-1].id}),n&&(o.media={media_ids:[n]});let l=await e.v2.tweet(a,o),u=l?.data?.id;if(!u)throw Error(`Thread tweet ${i+1} posted but no ID returned`);r.push({id:u,url:`https://x.com/i/status/${u}`})}return r}var w=s(7530),y=s(1282);let v=i.join(process.env.HOME||"",".vibebusiness"),b=i.join(v,"credentials.json"),k=i.join(process.env.HOME||"",".ai-analyst"),x=i.join(k,"provider.json");async function S(e){let t=Date.now(),s=process.env.ANTHROPIC_API_KEY;if(!s)return{output:"",provider:"anthropic-api",durationMs:0,error:"ANTHROPIC_API_KEY not set"};try{let r=e.model||"claude-sonnet-4-6",i=e.prompt;e.jsonSchema?i+=`
|
|
1
|
+
exports.id=7151,exports.ids=[7151],exports.modules={1401:e=>{function t(e){var t=Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}t.keys=()=>[],t.resolve=t,t.id=1401,e.exports=t},5883:(e,t,s)=>{"use strict";s.r(t),s.d(t,{ApiPartialResponseError:()=>f,ApiRequestError:()=>_,ApiResponseError:()=>w,DmEventsV1Paginator:()=>p,EApiV1ErrorCode:()=>x,EApiV2ErrorCode:()=>S,EDirectMessageEventTypeV1:()=>b,ETwitterApiError:()=>k,ETwitterStreamEvent:()=>T,EUploadMimeType:()=>v,FriendshipsIncomingV1Paginator:()=>eg,FriendshipsOutgoingV1Paginator:()=>e_,HomeTimelineV1Paginator:()=>er,ListMembersV1Paginator:()=>ek,ListMembershipsV1Paginator:()=>ew,ListOwnershipsV1Paginator:()=>ey,ListSubscribersV1Paginator:()=>ex,ListSubscriptionsV1Paginator:()=>ev,ListTimelineV1Paginator:()=>en,MentionTimelineV1Paginator:()=>ei,MuteUserIdsV1Paginator:()=>eu,MuteUserListV1Paginator:()=>el,PreviousableTwitterPaginator:()=>d,QuotedTweetsTimelineV2Paginator:()=>eU,TweetBookmarksTimelineV2Paginator:()=>eW,TweetHomeTimelineV2Paginator:()=>eB,TweetLikingUsersV2Paginator:()=>e2,TweetRetweetersUsersV2Paginator:()=>e8,TweetSearchAllV2Paginator:()=>eM,TweetSearchRecentV2Paginator:()=>eF,TweetStream:()=>H,TweetUserMentionTimelineV2Paginator:()=>eV,TweetUserTimelineV2Paginator:()=>eH,TweetV2ListTweetsPaginator:()=>eJ,TweetV2UserLikedTweetsPaginator:()=>eY,TwitterApi:()=>t_,TwitterApiPluginResponseOverride:()=>y,TwitterApiReadOnly:()=>tl,TwitterApiReadWrite:()=>tu,TwitterApiV2Settings:()=>D,TwitterApiv1:()=>eL,TwitterApiv2:()=>to,TwitterApiv2Labs:()=>tn,TwitterPaginator:()=>u,TwitterV2IncludesHelper:()=>eO,UserBlockingUsersV2Paginator:()=>eG,UserFavoritesV1Paginator:()=>eo,UserFollowerIdsV1Paginator:()=>ec,UserFollowerListV1Paginator:()=>ed,UserFollowersIdsV1Paginator:()=>ep,UserFollowersV2Paginator:()=>eQ,UserFollowingV2Paginator:()=>eZ,UserFriendListV1Paginator:()=>eh,UserListFollowedV2Paginator:()=>e7,UserListFollowersV2Paginator:()=>e1,UserListMembersV2Paginator:()=>e0,UserListMembershipsV2Paginator:()=>e3,UserMutingUsersV2Paginator:()=>eX,UserOwnedListsV2Paginator:()=>e5,UserSearchV1Paginator:()=>em,UserTimelineV1Paginator:()=>ea,WelcomeDmV1Paginator:()=>m,default:()=>tf});let r="https://api.x.com/2/",i="https://api.x.com/labs/2/",a="https://api.x.com/1.1/",n="https://upload.x.com/1.1/",o="https://ads-api.x.com/12/",l="https://ads-api-sandbox.twitter.com/12/";class u{constructor({realData:e,rateLimit:t,instance:s,queryParams:r,sharedParams:i}){this._maxResultsWhenFetchLast=100,this._realData=e,this._rateLimit=t,this._instance=s,this._queryParams=r,this._sharedParams=i}get _isRateLimitOk(){return!!(!this._rateLimit||1e3*this._rateLimit.reset<Date.now())||this._rateLimit.remaining>0}makeRequest(e){return this._instance.get(this.getEndpoint(),e,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(e,t){return new this.constructor({realData:e.data,rateLimit:e.rateLimit,instance:this._instance,queryParams:t,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(e){return{...e?{max_results:e}:{},...this._queryParams}}async next(e){let t=this.getNextQueryParams(e),s=await this.makeRequest(t);return this.makeNewInstanceFromResult(s,t)}async fetchNext(e){let t=this.getNextQueryParams(e),s=await this.makeRequest(t);return await this.refreshInstanceFromResult(s,!0),this}async fetchLast(e=1/0){let t=this.getNextQueryParams(this._maxResultsWhenFetchLast),s=0;for(;s<e&&this._isRateLimitOk;){let e=await this.makeRequest(t);if(await this.refreshInstanceFromResult(e,!0),s+=this.getPageLengthFromRequest(e),this.isFetchLastOver(e))break;t=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var e;return{...null!==(e=this._rateLimit)&&void 0!==e?e:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async *[Symbol.asyncIterator](){yield*this.getItemArray();let e=this,t=this.canFetchNextPage(this._realData);for(;t&&this._isRateLimitOk&&e.getItemArray().length>0;){let s=await e.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:s._realData,headers:{},rateLimit:s._rateLimit},!0),t=this.canFetchNextPage(s._realData);let r=s.getItemArray();yield*r,e=s}}async *fetchAndIterate(){for(let e of this.getItemArray())yield[e,this];let e=this,t=this.canFetchNextPage(this._realData);for(;t&&this._isRateLimitOk&&e.getItemArray().length>0;){let s=await e.next(this._maxResultsWhenFetchLast);for(let e of(this.refreshInstanceFromResult({data:s._realData,headers:{},rateLimit:s._rateLimit},!0),t=this.canFetchNextPage(s._realData),s.getItemArray()))yield[e,s];this._rateLimit=s._rateLimit,e=s}}}class d extends u{async previous(e){let t=this.getPreviousQueryParams(e),s=await this.makeRequest(t);return this.makeNewInstanceFromResult(s,t)}async fetchPrevious(e){let t=this.getPreviousQueryParams(e),s=await this.makeRequest(t);return await this.refreshInstanceFromResult(s,!1),this}}let c=u;class h extends c{getNextQueryParams(e){var t;return{...this._queryParams,cursor:null!==(t=this._realData.next_cursor_str)&&void 0!==t?t:this._realData.next_cursor,...e?{count:e}:{}}}isFetchLastOver(e){return!this.canFetchNextPage(e.data)}canFetchNextPage(e){return!this.isNextCursorInvalid(e.next_cursor)||!this.isNextCursorInvalid(e.next_cursor_str)}isNextCursorInvalid(e){return void 0===e||0===e||-1===e||"0"===e||"-1"===e}}class p extends h{constructor(){super(...arguments),this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.events.push(...s.events),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class m extends h{constructor(){super(...arguments),this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.welcome_messages.push(...s.welcome_messages),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}(function(e){e.Jpeg="image/jpeg",e.Mp4="video/mp4",e.Mov="video/quicktime",e.Gif="image/gif",e.Png="image/png",e.Srt="text/plain",e.Webp="image/webp"})(v||(v={})),function(e){e.Create="message_create",e.WelcomeCreate="welcome_message"}(b||(b={})),function(e){e.Request="request",e.PartialResponse="partial-response",e.Response="response"}(k||(k={}));class g extends Error{constructor(){super(...arguments),this.error=!0}}class _ extends g{constructor(e,t){super(e),this.type=k.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class f extends g{constructor(e,t){super(e),this.type=k.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t})}get request(){return this._options.request}get response(){return this._options.response}get responseError(){return this._options.responseError}get rawContent(){return this._options.rawContent}toJSON(){return{type:this.type,error:this.responseError}}}class w extends g{constructor(e,t){if(super(e),this.type=k.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:t}),this.code=t.code,this.headers=t.headers,this.rateLimit=t.rateLimit,t.data&&"object"==typeof t.data&&"error"in t.data&&!t.data.errors){let e={...t.data};e.errors=[{code:x.InternalError,message:e.error}],this.data=e}else this.data=t.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...e){let t=this.errors;if(!(null==t?void 0:t.length))return!1;if("code"in t[0])return t.some(t=>e.includes(t.code));let s=this.data;return e.includes(s.type)}get errors(){var e;return null===(e=this.data)||void 0===e?void 0:e.errors}get rateLimitError(){return 420===this.code||429===this.code}get isAuthError(){return 401===this.code||this.hasErrorCode(x.AuthTimestampInvalid,x.AuthenticationFail,x.BadAuthenticationData,x.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}(function(e){e[e.InvalidCoordinates=3]="InvalidCoordinates",e[e.NoLocationFound=13]="NoLocationFound",e[e.AuthenticationFail=32]="AuthenticationFail",e[e.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",e[e.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",e[e.AuthTimestampInvalid=135]="AuthTimestampInvalid",e[e.BadAuthenticationData=215]="BadAuthenticationData",e[e.NoUserMatch=17]="NoUserMatch",e[e.UserNotFound=50]="UserNotFound",e[e.ResourceNotFound=34]="ResourceNotFound",e[e.TweetNotFound=144]="TweetNotFound",e[e.TweetNotVisible=179]="TweetNotVisible",e[e.NotAllowedResource=220]="NotAllowedResource",e[e.MediaIdNotFound=325]="MediaIdNotFound",e[e.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",e[e.TweetViolatedRules=422]="TweetViolatedRules",e[e.TargetUserSuspended=63]="TargetUserSuspended",e[e.YouAreSuspended=64]="YouAreSuspended",e[e.AccountUpdateFailed=120]="AccountUpdateFailed",e[e.NoSelfSpamReport=36]="NoSelfSpamReport",e[e.NoSelfMute=271]="NoSelfMute",e[e.AccountLocked=326]="AccountLocked",e[e.RateLimitExceeded=88]="RateLimitExceeded",e[e.NoDMRightForApp=93]="NoDMRightForApp",e[e.OverCapacity=130]="OverCapacity",e[e.InternalError=131]="InternalError",e[e.TooManyFollowings=161]="TooManyFollowings",e[e.TweetLimitExceeded=185]="TweetLimitExceeded",e[e.DuplicatedTweet=187]="DuplicatedTweet",e[e.TooManySpamReports=205]="TooManySpamReports",e[e.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",e[e.NoWriteRightForApp=261]="NoWriteRightForApp",e[e.TweetActionsDisabled=425]="TweetActionsDisabled",e[e.TweetRepliesRestricted=433]="TweetRepliesRestricted",e[e.NamedParameterMissing=38]="NamedParameterMissing",e[e.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",e[e.TweetTextTooLong=186]="TweetTextTooLong",e[e.MissingUrlParameter=195]="MissingUrlParameter",e[e.NoMultipleGifs=323]="NoMultipleGifs",e[e.InvalidMediaIds=324]="InvalidMediaIds",e[e.InvalidUrl=407]="InvalidUrl",e[e.TooManyTweetAttachments=386]="TooManyTweetAttachments",e[e.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",e[e.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",e[e.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",e[e.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",e[e.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",e[e.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",e[e.UnableToSendDM=151]="UnableToSendDM",e[e.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",e[e.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",e[e.DMTextTooLong=354]="DMTextTooLong",e[e.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",e[e.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",e[e.SuspendedApplication=416]="SuspendedApplication",e[e.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(x||(x={})),function(e){e.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",e.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",e.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",e.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",e.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",e.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",e.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",e.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",e.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",e.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",e.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",e.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",e.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"}(S||(S={})),function(e){e.Connected="connected",e.ConnectError="connect error",e.ConnectionError="connection error",e.ConnectionClosed="connection closed",e.ConnectionLost="connection lost",e.ReconnectAttempt="reconnect attempt",e.Reconnected="reconnected",e.ReconnectError="reconnect error",e.ReconnectLimitExceeded="reconnect limit exceeded",e.DataKeepAlive="data keep-alive",e.Data="data event content",e.DataError="data twitter error",e.TweetParseError="data tweet parse error",e.Error="stream error"}(T||(T={}));class y{constructor(e){this.value=e}}var v,b,k,x,S,T,R,E=s(2048);let D={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function P(e){let t={value:void 0,promise:e().then(e=>(t.value=e,e))};return t}function A(e){return Array.isArray(e)?e:[e]}function I(e){return"object"==typeof e&&"errors"in e&&!("data"in e)}function L(e){return!!Array.isArray(e)&&e.length>1||e.toString().includes(",")}let $=new Set;function O(e){if("undefined"==typeof console||!console.warn||!D.deprecationWarnings)return;let t=`${e.instance}-${e.method}-${e.problem}`;$.has(t)||(console.warn(`[twitter-api-v2] Deprecation warning: In ${e.instance}.${e.method}() call, ${e.problem}.
|
|
2
|
+
${e.resolution}.`),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),$.add(t))}var q=s(7702),j=s(8791),C=s(1568);class N{constructor(e){this.requestData=e,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let e=this.requestData.url;return e.hostname+e.pathname}isCompressionDisabled(){return!this.requestData.compression||"identity"===this.requestData.compression}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(e){return D.debug&&D.logger.log("Request error:",e),new _("Request failed.",{request:this.req,error:e})}createPartialResponseError(e,t){let s=this.res,r=`Request failed with partial response with HTTP code ${s.statusCode}`;return t?r+=" (connection abruptly closed)":r+=" (parse error)",new f(r,{request:this.req,response:this.res,responseError:e,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(e){return e.map(({code:e,message:t})=>`${t} (Twitter code ${e})`).join(", ")}formatV2Error(e){return`${e.title}: ${e.detail} (see ${e.type})`}createResponseError({res:e,data:t,rateLimit:s,code:r}){var i;D.debug&&(D.logger.log(`Request failed with code ${r}, data:`,t),D.logger.log("Response headers:",e.headers));let a=`Request failed with code ${r}`;if(null===(i=null==t?void 0:t.errors)||void 0===i?void 0:i.length){let e=t.errors;"object"==typeof e[0]&&"code"in e[0]?a+=" - "+this.formatV1Errors(e):a+=" - "+this.formatV2Error(t)}return new w(a,{code:r,data:t,headers:e.headers,request:this.req,response:e,rateLimit:s})}getResponseDataStream(e){if(this.isCompressionDisabled())return e;let t=(e.headers["content-encoding"]||"identity").trim().toLowerCase();if("br"===t){let t=C.createBrotliDecompress({flush:C.constants.BROTLI_OPERATION_FLUSH,finishFlush:C.constants.BROTLI_OPERATION_FLUSH});return e.pipe(t),t}if("gzip"===t){let t=C.createGunzip({flush:C.constants.Z_SYNC_FLUSH,finishFlush:C.constants.Z_SYNC_FLUSH});return e.pipe(t),t}if("deflate"===t){let t=C.createInflate({flush:C.constants.Z_SYNC_FLUSH,finishFlush:C.constants.Z_SYNC_FLUSH});return e.pipe(t),t}return e}detectResponseType(e){var t,s;return(null===(t=e.headers["content-type"])||void 0===t?void 0:t.includes("application/json"))||(null===(s=e.headers["content-type"])||void 0===s?void 0:s.includes("application/problem+json"))?"json":this.isFormEncodedEndpoint()?"url":"text"}getParsedResponse(e){let t=this.responseData,s=this.requestData.forceParseMode||this.detectResponseType(e);if("buffer"===s)return Buffer.concat(t);if("text"===s)return Buffer.concat(t).toString();if("json"===s){let e=Buffer.concat(t).toString();return e.length?JSON.parse(e):void 0}{if("url"!==s)return;let e=Buffer.concat(t).toString(),r={};for(let[t,s]of new URLSearchParams(e))r[t]=s;return r}}getRateLimitFromResponse(e){let t;return e.headers["x-rate-limit-limit"]&&(t={limit:Number(e.headers["x-rate-limit-limit"]),remaining:Number(e.headers["x-rate-limit-remaining"]),reset:Number(e.headers["x-rate-limit-reset"])},e.headers["x-app-limit-24hour-limit"]&&(t.day={limit:Number(e.headers["x-app-limit-24hour-limit"]),remaining:Number(e.headers["x-app-limit-24hour-remaining"]),reset:Number(e.headers["x-app-limit-24hour-reset"])}),e.headers["x-user-limit-24hour-limit"]&&(t.userDay={limit:Number(e.headers["x-user-limit-24hour-limit"]),remaining:Number(e.headers["x-user-limit-24hour-remaining"]),reset:Number(e.headers["x-user-limit-24hour-reset"])}),this.requestData.rateLimitSaver&&this.requestData.rateLimitSaver(t)),t}onSocketEventHandler(e,t,s){let r=this.onSocketCloseHandler.bind(this,e);s.on("close",r),t.on("complete",()=>s.off("close",r))}onSocketCloseHandler(e){if(this.req.removeAllListeners("timeout"),!this.res&&!this.requestErrorHandled)return e(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(e,t){var s,r;null===(r=(s=this.requestData).requestEventDebugHandler)||void 0===r||r.call(s,"request-error",{requestError:t}),this.requestErrorHandled=!0,e(this.createRequestError(t))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(e,t,s){this.res=s;let r=this.getResponseDataStream(s);r.on("data",e=>this.responseData.push(e)),r.on("end",this.onResponseEndHandler.bind(this,e,t)),r.on("close",this.onResponseCloseHandler.bind(this,e,t)),this.requestData.requestEventDebugHandler&&(this.requestData.requestEventDebugHandler("response",{res:s}),s.on("aborted",e=>this.requestData.requestEventDebugHandler("response-aborted",{error:e})),s.on("error",e=>this.requestData.requestEventDebugHandler("response-error",{error:e})),s.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),s.on("end",()=>this.requestData.requestEventDebugHandler("response-end")))}onResponseEndHandler(e,t){let s;let r=this.getRateLimitFromResponse(this.res);try{s=this.getParsedResponse(this.res)}catch(e){t(this.createPartialResponseError(e,!1));return}let i=this.res.statusCode;if(i>=400){t(this.createResponseError({data:s,res:this.res,rateLimit:r,code:i}));return}D.debug&&(D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),D.logger.log("Response body:",s)),e({data:s,headers:this.res.headers,rateLimit:r})}onResponseCloseHandler(e,t){let s=this.res;if(s.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(e,t)}catch(e){return t(this.createPartialResponseError(e,!0))}if(!s.complete)return t(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(e,t,s){if(s.statusCode<400){D.debug&&D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${s.statusCode} (starting stream)`);let t=this.getResponseDataStream(s);e({req:this.req,res:t,originalResponse:s,requestData:this.requestData})}else this.classicResponseHandler(()=>void 0,t,s)}debugRequest(){let e=this.requestData.url;D.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),e.search&&D.logger.log("Request parameters:",[...e.searchParams.entries()].map(([e,t])=>`${e}: ${t}`)),this.requestData.body&&D.logger.log("Request body:",this.requestData.body)}buildRequest(){var e;let t=this.requestData.url,s=t.username?`${t.username}:${t.password}`:void 0,r=null!==(e=this.requestData.options.headers)&&void 0!==e?e:{};!0===this.requestData.compression||"brotli"===this.requestData.compression?r["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1":"gzip"===this.requestData.compression?r["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1":"deflate"===this.requestData.compression&&(r["accept-encoding"]="deflate;q=1, *;q=0.1"),D.debug&&this.debugRequest(),this.req=(0,j.request)({...this.requestData.options,host:t.hostname,port:t.port||void 0,path:t.pathname+t.search,protocol:t.protocol,auth:s,headers:r})}registerRequestEventDebugHandlers(e){e.on("close",()=>this.requestData.requestEventDebugHandler("close")),e.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),e.on("socket",e=>{this.requestData.requestEventDebugHandler("socket",{socket:e}),e.on("error",t=>this.requestData.requestEventDebugHandler("socket-error",{socket:e,error:t})),e.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:e})),e.on("close",t=>this.requestData.requestEventDebugHandler("socket-close",{socket:e,withError:t})),e.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:e})),e.on("lookup",(...t)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:e,data:t})),e.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:e}))})}makeRequest(){return this.buildRequest(),new Promise((e,t)=>{let s=e=>{r.emit("complete"),t(e)},r=new q.EventEmitter,i=this.req;i.on("error",this.requestErrorHandler.bind(this,s)),i.on("socket",this.onSocketEventHandler.bind(this,s,r)),i.on("response",this.classicResponseHandler.bind(this,t=>{r.emit("complete"),e(t)},s)),this.requestData.options.timeout&&i.on("timeout",this.timeoutErrorHandler.bind(this)),this.requestData.requestEventDebugHandler&&this.registerRequestEventDebugHandlers(i),this.requestData.body&&i.write(this.requestData.body),i.end()})}async makeRequestAsStream(){let{req:e,res:t,requestData:s,originalResponse:r}=await this.makeRequestAndResolveWhenReady();return new V(s,{req:e,res:t,originalResponse:r})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((e,t)=>{let s=this.req;s.on("error",this.requestErrorHandler.bind(this,t)),s.on("response",this.streamResponseHandler.bind(this,e,t)),this.requestData.body&&s.write(this.requestData.body),s.end()})}}class F extends q.EventEmitter{constructor(e){super(),this.stream=e,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),e.on(T.Data,this.onStreamData),e.on(T.ConnectionError,this.onStreamError),e.on(T.TweetParseError,this.onStreamError),e.on(T.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let e=this.stack;return this.stack=[],e}destroy(){this.removeAllListeners(),this.stream.off(T.Data,this.onStreamData),this.stream.off(T.ConnectionError,this.onStreamError),this.stream.off(T.TweetParseError,this.onStreamError),this.stream.off(T.ConnectionClosed,this.onStreamError)}emitEvent(e,t){this.emit("event",{type:e,payload:t})}onStreamError(e){this.emitEvent("error",e)}onStreamData(e){this.stack.push(e),this.emitEvent("data",e)}}class M extends q.EventEmitter{constructor(){super(...arguments),this.currentMessage=""}push(e){this.currentMessage+=e;let t=(e=this.currentMessage).length,s=0,r=0;for(;r<t;){if("\r\n"===e.slice(r,r+2)){let t=e.slice(s,r);if(s=r+=2,!t.length)continue;try{let e=JSON.parse(t);if(e){this.emit(R.ParsedData,e);continue}}catch(e){this.emit(R.ParseError,e)}}r++}this.currentMessage=e.slice(s,t)}reset(){this.currentMessage=""}}!function(e){e.ParsedData="parsed data",e.ParseError="parse error"}(R||(R={}));let U=[5,15,30,60,90,120,180,300,600,900],B=e=>e>U.length?901e3:1e3*U[e-1];class H extends q.EventEmitter{constructor(e,t){super(),this.requestData=e,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=12e4,this.nextRetryTimeout=B,this.parser=new M,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),t&&(this.req=t.req,this.res=t.res,this.originalResponse=t.originalResponse,this.initEventsFromRequest())}on(e,t){return super.on(e,t)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let e=e=>{this.emit(T.ConnectionError,e),this.emit(T.Error,{type:T.ConnectionError,error:e,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",e),this.res.on("error",e),this.res.on("close",()=>e(Error("Connection closed by Twitter."))),this.res.on("data",e=>{if(this.resetKeepAliveTimeout(),"\r\n"===e.toString())return this.emit(T.DataKeepAlive);this.parser.push(e.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let e=this.requestData.payloadIsError;this.parser.on(R.ParsedData,t=>{e&&e(t)?(this.emit(T.DataError,t),this.emit(T.Error,{type:T.DataError,error:t,message:"Twitter sent a payload that is detected as an error payload."})):this.emit(T.Data,t)}),this.parser.on(R.ParseError,e=>{this.emit(T.TweetParseError,e),this.emit(T.Error,{type:T.TweetParseError,error:e,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0&&(this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs))}onKeepAliveTimeout(){this.emit(T.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){this.keepAliveTimeout&&(clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0)}unbindRetryTimeout(){this.retryTimeout&&(clearTimeout(this.retryTimeout),this.retryTimeout=void 0)}closeWithoutEmit(){this.unbindTimeouts(),this.res&&(this.res.removeAllListeners(),this.res.destroy()),this.req&&(this.req.removeAllListeners(),this.req.destroy())}close(){this.emit(T.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let e=new N(this.requestData),t=await e.makeRequestAsStream();for(let e of this.eventNames())for(let s of this.listeners(e))t.on(e,s);return t}async connect(e={}){void 0!==e.autoReconnect&&(this.autoReconnect=e.autoReconnect),void 0!==e.autoReconnectRetries&&(this.autoReconnectRetries="unlimited"===e.autoReconnectRetries?1/0:e.autoReconnectRetries),void 0!==e.keepAliveTimeout&&(this.keepAliveTimeoutMs="disable"===e.keepAliveTimeout?1/0:e.keepAliveTimeout),void 0!==e.nextRetryTimeout&&(this.nextRetryTimeout=e.nextRetryTimeout),this.unbindTimeouts();try{await this.reconnect()}catch(e){if(this.emit(T.ConnectError,0),this.emit(T.Error,{type:T.ConnectError,error:e,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,e);else throw e}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let e=!0;this.req&&(e=!1,this.closeWithoutEmit());let{req:t,res:s,originalResponse:r}=await new N(this.requestData).makeRequestAndResolveWhenReady();this.req=t,this.res=s,this.originalResponse=r,this.emit(e?T.Connected:T.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(e=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(T.ConnectionClosed);return}if(e>=this.autoReconnectRetries){this.emit(T.ReconnectLimitExceeded),this.emit(T.ConnectionClosed);return}try{this.emit(T.ReconnectAttempt,e),await this.reconnect()}catch(t){this.emit(T.ReconnectError,e),this.emit(T.Error,{type:T.ReconnectError,error:t,message:`Reconnect error - ${e+1} attempts made yet.`}),this.makeAutoReconnectRetry(e,t)}}makeAutoReconnectRetry(e,t){let s=this.nextRetryTimeout(e+1,t);this.retryTimeout=setTimeout(()=>{this.onConnectionError(e+1)},s)}async *[Symbol.asyncIterator](){let e=new F(this);try{for(;;){if(!this.req||this.req.aborted)throw Error("Connection closed");e.hasStack()&&(yield*e.popStack());let{type:t,payload:s}=await e.nextEvent();if("error"===t)throw s}}finally{e.destroy()}}}let V=H;async function W(e,t,s,r){let i;return(r instanceof _||r instanceof f?i=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,error:r}):r instanceof w&&(i=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,error:r})),i&&i instanceof y)?i.value:Promise.reject(r)}var K=s(4770);class Y{constructor(e){this.nonceLength=32,this.consumerKeys=e.consumerKeys}static percentEncode(e){return encodeURIComponent(e).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(e,t){return K.createHmac("sha1",t).update(e).digest("base64")}authorize(e,t={}){let s={oauth_consumer_key:this.consumerKeys.key,oauth_nonce:this.getNonce(),oauth_signature_method:"HMAC-SHA1",oauth_timestamp:this.getTimestamp(),oauth_version:"1.0"};return void 0!==t.key&&(s.oauth_token=t.key),e.data||(e.data={}),s.oauth_signature=this.getSignature(e,t.secret,s),s}toHeader(e){let t=z(e),s="OAuth ";for(let e of t)0===e.key.indexOf("oauth_")&&(s+=Y.percentEncode(e.key)+'="'+Y.percentEncode(e.value)+'",');return{Authorization:s.slice(0,s.length-1)}}getNonce(){let e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",t="";for(let s=0;s<this.nonceLength;s++)t+=e[Math.trunc(Math.random()*e.length)];return t}getTimestamp(){return Math.trunc(new Date().getTime()/1e3)}getSignature(e,t,s){return this.hash(this.getBaseString(e,s),this.getSigningKey(t))}getSigningKey(e){return Y.percentEncode(this.consumerKeys.secret)+"&"+Y.percentEncode(e||"")}getBaseString(e,t){return e.method.toUpperCase()+"&"+Y.percentEncode(this.getBaseUrl(e.url))+"&"+Y.percentEncode(this.getParameterString(e,t))}getParameterString(e,t){let s=z(function(e){let t={};for(let s in e){let r=e[s];r=r&&Array.isArray(r)?r.map(e=>Y.percentEncode(e)):Y.percentEncode(r),t[Y.percentEncode(s)]=r}return t}(J(t,J(e.data,function(e){let t=e.split("?");return 1===t.length?{}:function(e){let t=e.split("&"),s={};for(let e of t){let[t,r=""]=e.split("=");s[t]?(Array.isArray(s[t])||(s[t]=[s[t]]),s[t].push(decodeURIComponent(r))):s[t]=decodeURIComponent(r)}return s}(t[1])}(e.url))))),r="";for(let{key:e,value:t}of s)if(t&&Array.isArray(t)){t.sort();let s="";t.forEach((r,i)=>{s+=e+"="+r,i<t.length&&(s+="&")}),r+=s}else r+=e+"="+t+"&";return r.slice(0,r.length-1)}getBaseUrl(e){return e.split("?")[0]}}function J(e,t){return{...e||{},...t||{}}}function z(e){return Object.keys(e).sort().map(t=>({key:t,value:e[t]}))}class G{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...e){let t=e.map(e=>e instanceof Buffer?e:Buffer.from(e));this._chunks.push(...t)}append(e,t,s){let r=t instanceof Buffer?t:t.toString(),i=this.getMultipartHeader(e,r,s);this.bodyAppend(i,r,G.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((e,t)=>e+t.length,this.getMultipartFooter().length)}getBuffer(){let e=[...this._chunks,this.getMultipartFooter()],t=Buffer.alloc(this.getLength()),s=0;for(let r of e)for(let e=0;e<r.length;s++,e++)t[s]=r[e];return t}getBoundary(){return this._boundary||this.generateBoundary(),this._boundary}generateBoundary(){let e="--------------------------";for(let t=0;t<24;t++)e+=Math.floor(10*Math.random()).toString(16);this._boundary=e}getMultipartHeader(e,t,s){s||(s=t instanceof Buffer?G.DEFAULT_CONTENT_TYPE:"");let r="";for(let[t,i]of Object.entries({"Content-Disposition":["form-data",`name="${e}"`],"Content-Type":s}))i.length&&(r+=t+": "+A(i).join("; ")+G.LINE_BREAK);return"--"+this.getBoundary()+G.LINE_BREAK+r+G.LINE_BREAK}getMultipartFooter(){return this._footerChunk?this._footerChunk:this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+G.LINE_BREAK)}}G.LINE_BREAK="\r\n",G.DEFAULT_CONTENT_TYPE="application/octet-stream";class X{static formatQueryToString(e){let t={};for(let s in e)"string"==typeof e[s]?t[s]=e[s]:void 0!==e[s]&&(t[s]=String(e[s]));return t}static autoDetectBodyType(e){if(e.pathname.startsWith("/2/")||e.pathname.startsWith("/labs/2/"))return e.password.startsWith("/2/oauth2")?"url":"json";if("upload.x.com"===e.hostname)return"/1.1/media/upload.json"===e.pathname?"form-data":"json";let t=e.pathname.split("/1.1/",2)[1];return this.JSON_1_1_ENDPOINTS.has(t)?"json":"url"}static addQueryParamsToUrl(e,t){let s=Object.entries(t);if(s.length){let t="";for(let[e,r]of s)t+=(t.length?"&":"?")+`${Y.percentEncode(e)}=${Y.percentEncode(r)}`;e.search=t}}static constructBodyParams(e,t,s){if(e instanceof Buffer)return e;if("json"===s)return t["content-type"]||(t["content-type"]="application/json;charset=UTF-8"),JSON.stringify(e);if("url"===s)return(t["content-type"]||(t["content-type"]="application/x-www-form-urlencoded;charset=UTF-8"),Object.keys(e).length)?new URLSearchParams(e).toString().replace(/\*/g,"%2A"):"";if("raw"===s)throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");{let s=new G;for(let t in e)s.append(t,e[t]);if(!t["content-type"]){let e=s.getHeaders();t["content-type"]=e["content-type"]}return s.getBuffer()}}static setBodyLengthHeader(e,t){var s;e.headers=null!==(s=e.headers)&&void 0!==s?s:{},"string"==typeof t?e.headers["content-length"]=Buffer.byteLength(t):e.headers["content-length"]=t.length}static isOAuthSerializable(e){return!(e instanceof Buffer)}static mergeQueryAndBodyForOAuth(e,t){let s={};for(let t in e)s[t]=e[t];if(this.isOAuthSerializable(t))for(let e in t){let r=t[e];this.isOAuthSerializable(r)&&(s[e]="object"==typeof r&&null!==r&&"toString"in r?r.toString():r)}return s}static moveUrlQueryParamsIntoObject(e,t){for(let[s,r]of e.searchParams)t[s]=r;return e.search="",e}static applyRequestParametersToUrl(e,t){return e.pathname=e.pathname.replace(/:([A-Z_-]+)/ig,(e,s)=>void 0!==t[s]?String(t[s]):e),e}}X.JSON_1_1_ENDPOINTS=new Set(["direct_messages/events/new.json","direct_messages/welcome_messages/new.json","direct_messages/welcome_messages/rules/new.json","media/metadata/create.json","collections/entries/curate.json"]);class Q{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(e){return this.escapeBase64Url(K.createHash("sha256").update(e).digest("base64"))}static getAuthHeader(e,t){let s=encodeURIComponent(e)+":"+encodeURIComponent(t);return Buffer.from(s).toString("base64")}static generateRandomString(e){let t="",s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let r=0;r<e;r++)t+=s[Math.floor(Math.random()*s.length)];return t}static escapeBase64Url(e){return e.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class Z{constructor(e){this.rateLimits={},this.clientSettings={},e&&(this.clientSettings=e)}getRateLimits(){return this.rateLimits}saveRateLimit(e,t){this.rateLimits[e]=t}async send(e){var t,s,r,i,a;if(null===(t=this.clientSettings.plugins)||void 0===t?void 0:t.length){let t=await this.applyPreRequestConfigHooks(e);if(t)return t}let n=this.getHttpRequestArgs(e),o={method:n.method,headers:n.headers,timeout:e.timeout,agent:this.clientSettings.httpAgent},l=!1!==e.enableRateLimitSave;n.body&&X.setBodyLengthHeader(o,n.body),(null===(s=this.clientSettings.plugins)||void 0===s?void 0:s.length)&&await this.applyPreRequestHooks(e,n,o);let u=new N({url:n.url,options:o,body:n.body,rateLimitSaver:l?this.saveRateLimit.bind(this,n.rawUrl):void 0,requestEventDebugHandler:e.requestEventDebugHandler,compression:null===(i=null!==(r=e.compression)&&void 0!==r?r:this.clientSettings.compression)||void 0===i||i,forceParseMode:e.forceParseMode}).makeRequest();(function(e){var t;if(!(null===(t=e.clientSettings.plugins)||void 0===t?void 0:t.length))return!1;for(let t of e.clientSettings.plugins)if(t.onRequestError||t.onResponseError)return!0;return!1})(this)&&(u=this.applyResponseErrorHooks(e,n,o,u));let d=await u;if(null===(a=this.clientSettings.plugins)||void 0===a?void 0:a.length){let t=await this.applyPostRequestHooks(e,n,o,d);if(t)return t.value}return d}sendStream(e){var t,s;this.clientSettings.plugins&&this.applyPreStreamRequestConfigHooks(e);let r=this.getHttpRequestArgs(e),i={method:r.method,headers:r.headers,agent:this.clientSettings.httpAgent},a=!1!==e.enableRateLimitSave,n=!1!==e.autoConnect;r.body&&X.setBodyLengthHeader(i,r.body);let o=new V({url:r.url,options:i,body:r.body,rateLimitSaver:a?this.saveRateLimit.bind(this,r.rawUrl):void 0,payloadIsError:e.payloadIsError,compression:null===(s=null!==(t=e.compression)&&void 0!==t?t:this.clientSettings.compression)||void 0===s||s});return n?o.connect():o}initializeToken(e){if("string"==typeof e)this.bearerToken=e;else if("object"==typeof e&&"appKey"in e)this.consumerToken=e.appKey,this.consumerSecret=e.appSecret,e.accessToken&&e.accessSecret&&(this.accessToken=e.accessToken,this.accessSecret=e.accessSecret),this._oauth=this.buildOAuth();else if("object"==typeof e&&"username"in e){let t=encodeURIComponent(e.username)+":"+encodeURIComponent(e.password);this.basicToken=Buffer.from(t).toString("base64")}else"object"==typeof e&&"clientId"in e&&(this.clientId=e.clientId,this.clientSecret=e.clientSecret)}getActiveTokens(){return this.bearerToken?{type:"oauth2",bearerToken:this.bearerToken}:this.basicToken?{type:"basic",token:this.basicToken}:this.consumerSecret&&this._oauth?{type:"oauth-1.0a",appKey:this.consumerToken,appSecret:this.consumerSecret,accessToken:this.accessToken,accessSecret:this.accessSecret}:this.clientId?{type:"oauth2-user",clientId:this.clientId}:{type:"none"}}buildOAuth(){if(!this.consumerSecret||!this.consumerToken)throw Error("Invalid consumer tokens");return new Y({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(this.accessSecret&&this.accessToken)return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var e;return null!==(e=this.clientSettings.plugins)&&void 0!==e?e:[]}hasPlugins(){var e;return!!(null===(e=this.clientSettings.plugins)||void 0===e?void 0:e.length)}async applyPluginMethod(e,t){var s;let r;for(let i of this.getPlugins()){let a=await (null===(s=i[e])||void 0===s?void 0:s.call(i,t));a&&a instanceof y&&(r=a)}return r}writeAuthHeaders({headers:e,bodyInSignature:t,url:s,method:r,query:i,body:a}){if(e={...e},this.bearerToken)e.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)e.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)e.Authorization="Basic "+Q.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let n=t?X.mergeQueryAndBodyForOAuth(i,a):i,o=this._oauth.authorize({url:s.toString(),method:r,data:n},this.getOAuthAccessTokens());e={...e,...this._oauth.toHeader(o)}}return e}getUrlObjectFromUrlString(e){return e.startsWith("http")||(e="https://"+e),new URL(e)}getHttpRequestArgs({url:e,method:t,query:s={},body:r={},headers:i,forceBodyMode:a,enableAuth:n,params:o}){let l;t=t.toUpperCase(),(i=null!=i?i:{})["x-user-agent"]||(i["x-user-agent"]="Node.twitter-api-v2");let u=this.getUrlObjectFromUrlString(e),d=u.origin+u.pathname;o&&X.applyRequestParametersToUrl(u,o);let c=X.formatQueryToString(s);X.moveUrlQueryParamsIntoObject(u,c),r instanceof Buffer||function(e){for(let t of Object.keys(e))void 0===e[t]&&delete e[t]}(r);let h=null!=a?a:X.autoDetectBodyType(u);if(!1!==n){let e=Z.BODY_METHODS.has(t)&&"url"===h;i=this.writeAuthHeaders({headers:i,bodyInSignature:e,method:t,query:c,url:u,body:r})}return Z.BODY_METHODS.has(t)&&(l=X.constructBodyParams(r,i,h)||void 0),X.addQueryParamsToUrl(u,c),{rawUrl:d,url:u,method:t,headers:i,body:l}}async applyPreRequestConfigHooks(e){var t;let s=this.getUrlObjectFromUrlString(e.url);for(let r of this.getPlugins()){let i=await (null===(t=r.onBeforeRequestConfig)||void 0===t?void 0:t.call(r,{client:this,url:s,params:e}));if(i)return i}}applyPreStreamRequestConfigHooks(e){var t;let s=this.getUrlObjectFromUrlString(e.url);for(let r of this.getPlugins())null===(t=r.onBeforeStreamRequestConfig)||void 0===t||t.call(r,{client:this,url:s,params:e})}async applyPreRequestHooks(e,t,s){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s})}async applyPostRequestHooks(e,t,s,r){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(e.url),params:e,computedParams:t,requestOptions:s,response:r})}applyResponseErrorHooks(e,t,s,r){return r.catch(W.bind(this,e,t,s))}}Z.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class ee{constructor(e,t={}){this._currentUser=null,this._currentUserV2=null,e instanceof ee?this._requestMaker=e._requestMaker:(this._requestMaker=new Z(t),this._requestMaker.initializeToken(e))}setPrefix(e){this._prefix=e}cloneWithPrefix(e){let t=this.constructor(this);return t.setPrefix(e),t}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(e){return this.getPlugins().find(t=>t instanceof e)}hasHitRateLimit(e){var t;return!this.isRateLimitStatusObsolete(e)&&(null===(t=this.getLastRateLimitStatus(e))||void 0===t?void 0:t.remaining)===0}isRateLimitStatusObsolete(e){let t=this.getLastRateLimitStatus(e);return void 0===t||1e3*t.reset<Date.now()}getLastRateLimitStatus(e){let t=e.match(/^https?:\/\//)?e:this._prefix+e;return this._requestMaker.getRateLimits()[t]}getCurrentUserObject(e=!1){return!e&&this._currentUser?this._currentUser.value?Promise.resolve(this._currentUser.value):this._currentUser.promise:(this._currentUser=P(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:a})),this._currentUser.promise)}getCurrentUserV2Object(e=!1){return!e&&this._currentUserV2?this._currentUserV2.value?Promise.resolve(this._currentUserV2.value):this._currentUserV2.promise:(this._currentUserV2=P(()=>this.get("users/me",void 0,{prefix:r})),this._currentUserV2.promise)}async get(e,t={},{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"GET",query:t,...i});return s?a:a.data}async delete(e,t={},{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"DELETE",query:t,...i});return s?a:a.data}async post(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"POST",body:t,...i});return s?a:a.data}async put(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"PUT",body:t,...i});return s?a:a.data}async patch(e,t,{fullResponse:s,prefix:r=this._prefix,...i}={}){r&&(e=r+e);let a=await this._requestMaker.send({url:e,method:"PATCH",body:t,...i});return s?a:a.data}getStream(e,t,{prefix:s=this._prefix,...r}={}){return this._requestMaker.sendStream({url:s?s+e:e,method:"GET",query:t,...r})}postStream(e,t,{prefix:s=this._prefix,...r}={}){return this._requestMaker.sendStream({url:s?s+e:e,method:"POST",body:t,...r})}}class et extends ee{constructor(e){if(!(e instanceof ee))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(e)}}class es extends c{constructor(){super(...arguments),this.hasFinishedFetch=!1}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.push(...s),this.hasFinishedFetch=0===s.length)}getNextQueryParams(e){let t=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(e),max_id:(t-BigInt(1)).toString()}}getPageLengthFromRequest(e){return e.data.length}isFetchLastOver(e){return!e.data.length}canFetchNextPage(e){return e.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class er extends es{constructor(){super(...arguments),this._endpoint="statuses/home_timeline.json"}}class ei extends es{constructor(){super(...arguments),this._endpoint="statuses/mentions_timeline.json"}}class ea extends es{constructor(){super(...arguments),this._endpoint="statuses/user_timeline.json"}}class en extends es{constructor(){super(...arguments),this._endpoint="lists/statuses.json"}}class eo extends es{constructor(){super(...arguments),this._endpoint="favorites/list.json"}}class el extends h{constructor(){super(...arguments),this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class eu extends h{constructor(){super(...arguments),this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class ed extends h{constructor(){super(...arguments),this._endpoint="followers/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ec extends h{constructor(){super(...arguments),this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class eh extends h{constructor(){super(...arguments),this._endpoint="friends/list.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ep extends h{constructor(){super(...arguments),this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class em extends c{constructor(){super(...arguments),this._endpoint="users/search.json"}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&this._realData.push(...s)}getNextQueryParams(e){var t;let s=Number(null!==(t=this._queryParams.page)&&void 0!==t?t:"1");return{...this._queryParams,page:s+1,...e?{count:e}:{}}}getPageLengthFromRequest(e){return e.data.length}isFetchLastOver(e){return!e.data.length}canFetchNextPage(e){return e.length>0}getItemArray(){return this.users}get users(){return this._realData}}class eg extends h{constructor(){super(...arguments),this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5e3}refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.ids.push(...s.ids),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class e_ extends eg{constructor(){super(...arguments),this._endpoint="friendships/outgoing.json"}}class ef extends h{refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.lists.push(...s.lists),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class ew extends ef{constructor(){super(...arguments),this._endpoint="lists/memberships.json"}}class ey extends ef{constructor(){super(...arguments),this._endpoint="lists/ownerships.json"}}class ev extends ef{constructor(){super(...arguments),this._endpoint="lists/subscriptions.json"}}class eb extends h{refreshInstanceFromResult(e,t){let s=e.data;this._rateLimit=e.rateLimit,t&&(this._realData.users.push(...s.users),this._realData.next_cursor=s.next_cursor)}getPageLengthFromRequest(e){return e.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class ek extends eb{constructor(){super(...arguments),this._endpoint="lists/members.json"}}class ex extends eb{constructor(){super(...arguments),this._endpoint="lists/subscribers.json"}}class eS extends et{constructor(){super(...arguments),this._prefix=a}singleTweet(e,t={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:e,...t})}tweets(e,t={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:e,...t})}oembedTweet(e,t={}){return this.get("oembed",{url:`https://x.com/i/statuses/${e}`,...t},{prefix:"https://publish.x.com/"})}async homeTimeline(e={}){let t={tweet_mode:"extended",...e},s=await this.get("statuses/home_timeline.json",t,{fullResponse:!0});return new er({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async mentionTimeline(e={}){let t={tweet_mode:"extended",...e},s=await this.get("statuses/mentions_timeline.json",t,{fullResponse:!0});return new ei({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userTimeline(e,t={}){let s={tweet_mode:"extended",user_id:e,...t},r=await this.get("statuses/user_timeline.json",s,{fullResponse:!0});return new ea({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async userTimelineByUsername(e,t={}){let s={tweet_mode:"extended",screen_name:e,...t},r=await this.get("statuses/user_timeline.json",s,{fullResponse:!0});return new ea({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async favoriteTimeline(e,t={}){let s={tweet_mode:"extended",user_id:e,...t},r=await this.get("favorites/list.json",s,{fullResponse:!0});return new eo({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async favoriteTimelineByUsername(e,t={}){let s={tweet_mode:"extended",screen_name:e,...t},r=await this.get("favorites/list.json",s,{fullResponse:!0});return new eo({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}user(e){return this.get("users/show.json",{tweet_mode:"extended",...e})}users(e){return this.get("users/lookup.json",{tweet_mode:"extended",...e})}verifyCredentials(e={}){return this.get("account/verify_credentials.json",e)}async listMutedUsers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("mutes/users/list.json",t,{fullResponse:!0});return new el({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listMutedUserIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("mutes/users/ids.json",t,{fullResponse:!0});return new eu({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFriendList(e={}){let t={...e},s=await this.get("friends/list.json",t,{fullResponse:!0});return new eh({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowerList(e={}){let t={...e},s=await this.get("followers/list.json",t,{fullResponse:!0});return new ed({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowerIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("followers/ids.json",t,{fullResponse:!0});return new ec({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async userFollowingIds(e={}){let t={stringify_ids:!0,...e},s=await this.get("friends/ids.json",t,{fullResponse:!0});return new ep({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async searchUsers(e,t={}){let s={q:e,tweet_mode:"extended",page:1,...t},r=await this.get("users/search.json",s,{fullResponse:!0});return new em({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}friendship(e){return this.get("friendships/show.json",e)}friendships(e){return this.get("friendships/lookup.json",e)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(e={}){let t={stringify_ids:!0,...e},s=await this.get("friendships/incoming.json",t,{fullResponse:!0});return new eg({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async friendshipsOutgoing(e={}){let t={stringify_ids:!0,...e},s=await this.get("friendships/outgoing.json",t,{fullResponse:!0});return new e_({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(e){return this.get("users/profile_banner.json",e)}list(e){return this.get("lists/show.json",{tweet_mode:"extended",...e})}lists(e={}){return this.get("lists/list.json",{tweet_mode:"extended",...e})}async listMembers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/members.json",t,{fullResponse:!0});return new ek({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}listGetMember(e){return this.get("lists/members/show.json",{tweet_mode:"extended",...e})}async listMemberships(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/memberships.json",t,{fullResponse:!0});return new ew({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listOwnerships(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/ownerships.json",t,{fullResponse:!0});return new ey({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listStatuses(e){let t={tweet_mode:"extended",...e},s=await this.get("lists/statuses.json",t,{fullResponse:!0});return new en({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}async listSubscribers(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/subscribers.json",t,{fullResponse:!0});return new ex({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}listGetSubscriber(e){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...e})}async listSubscriptions(e={}){let t={tweet_mode:"extended",...e},s=await this.get("lists/subscriptions.json",t,{fullResponse:!0});return new ev({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}mediaInfo(e){return this.get("media/upload.json",{command:"STATUS",media_id:e},{prefix:n})}filterStream({autoConnect:e,...t}={}){let s={};for(let[e,r]of Object.entries(t))"follow"===e||"track"===e?s[e]=r.toString():"locations"===e?s.locations=A(r).map(e=>`${e.lng},${e.lat}`).join(","):s[e]=r;return this.stream.postStream("statuses/filter.json",s,{autoConnect:e})}sampleStream({autoConnect:e,...t}={}){return this.stream.getStream("statuses/sample.json",t,{autoConnect:e})}get stream(){let e=new e$(this);return e.setPrefix("https://stream.x.com/1.1/"),e}trendsByPlace(e,t={}){return this.get("trends/place.json",{id:e,...t})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(e,t){return this.get("trends/closest.json",{lat:e,long:t})}geoPlace(e){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:e}})}geoSearch(e){return this.get("geo/search.json",e)}geoReverseGeoCode(e){return this.get("geo/reverse_geocode.json",e)}rateLimitStatuses(...e){return this.get("application/rate_limit_status.json",{resources:e})}supportedLanguages(){return this.get("help/languages.json")}}async function eT(e){let t=await eR(e);return"number"==typeof t?new Promise((e,s)=>{E.readFile(t,(t,r)=>{if(t)return s(t);e(r)})}):t instanceof Buffer?t:t.readFile()}function eR(e){if("string"==typeof e)return E.promises.open(e,"r");if("number"==typeof e||"object"==typeof e&&!(e instanceof Buffer)||e instanceof Buffer)return e;throw Error("Given file is not valid, please check its type.")}async function eE(e){return"number"==typeof e?(await new Promise((t,s)=>{E.fstat(e,(e,r)=>{e&&s(e),t(r)})})).size:e instanceof Buffer?e.length:(await e.stat()).size}function eD(e){return new Promise(t=>setTimeout(t,1e3*e))}async function eP(e,t,s=0,r){let i;if(e instanceof Buffer){let r=e.slice(s,s+t);return[r,r.length]}if(!r)throw Error("Well, we will need a buffer to store file content.");return i="number"==typeof e?await new Promise((i,a)=>{E.read(e,r,0,t,s,(e,t)=>{e&&a(e),i(t)})}):(await e.read(r,0,t,s)).bytesRead,[r,i]}let eA="media/upload.json";class eI extends eS{constructor(){super(...arguments),this._prefix=a}get readOnly(){return this}tweet(e,t={}){let s={status:e,tweet_mode:"extended",...t};return this.post("statuses/update.json",s)}async quote(e,t,s={}){return this.tweet(e,{...s,attachment_url:"https://x.com/i/statuses/"+t})}async tweetThread(e){let t=[];for(let s of e){let e=t.length?t[t.length-1]:null,r={..."string"==typeof s?{status:s}:s},i=e?e.id_str:r.in_reply_to_status_id,a=r.status;i?t.push(await this.reply(a,i,r)):t.push(await this.tweet(a,r))}return t}reply(e,t,s={}){return this.tweet(e,{auto_populate_reply_metadata:!0,in_reply_to_status_id:t,...s})}deleteTweet(e){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:e}})}reportUserAsSpam(e){return this.post("users/report_spam.json",{tweet_mode:"extended",...e})}updateFriendship(e){return this.post("friendships/update.json",e)}createFriendship(e){return this.post("friendships/create.json",e)}destroyFriendship(e){return this.post("friendships/destroy.json",e)}updateAccountSettings(e){return this.post("account/settings.json",e)}updateAccountProfile(e){return this.post("account/update_profile.json",e)}async updateAccountProfileBanner(e,t={}){let s={banner:await eT(e),...t};return this.post("account/update_profile_banner.json",s,{forceBodyMode:"form-data"})}async updateAccountProfileImage(e,t={}){let s={tweet_mode:"extended",image:await eT(e),...t};return this.post("account/update_profile_image.json",s,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(e){return this.post("lists/create.json",{tweet_mode:"extended",...e})}updateList(e){return this.post("lists/update.json",{tweet_mode:"extended",...e})}removeList(e){return this.post("lists/destroy.json",{tweet_mode:"extended",...e})}addListMembers(e){let t=e.user_id&&L(e.user_id)||e.screen_name&&L(e.screen_name);return this.post(t?"lists/members/create_all.json":"lists/members/create.json",e)}removeListMembers(e){let t=e.user_id&&L(e.user_id)||e.screen_name&&L(e.screen_name);return this.post(t?"lists/members/destroy_all.json":"lists/members/destroy.json",e)}subscribeToList(e){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...e})}unsubscribeOfList(e){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...e})}createMediaMetadata(e,t){return this.post("media/metadata/create.json",{media_id:e,...t},{prefix:n,forceBodyMode:"json"})}createMediaSubtitles(e,t){return this.post("media/subtitles/create.json",{media_id:e,media_category:"TweetVideo",subtitle_info:{subtitles:t}},{prefix:n,forceBodyMode:"json"})}deleteMediaSubtitles(e,...t){return this.post("media/subtitles/delete.json",{media_id:e,media_category:"TweetVideo",subtitle_info:{subtitles:t.map(e=>({language_code:e}))}},{prefix:n,forceBodyMode:"json"})}async uploadMedia(e,t={},s=!1){var r;let i=null!==(r=t.chunkLength)&&void 0!==r?r:1048576,{fileHandle:a,mediaCategory:o,fileSize:l,mimeType:u}=await this.getUploadMediaRequirements(e,t);try{let e=await this.post(eA,{command:"INIT",total_bytes:l,media_type:u,media_category:o,additional_owners:t.additionalOwners,shared:!!t.shared||void 0},{prefix:n});await this.mediaChunkedUpload(a,i,e.media_id_string,t.maxConcurrentUploads);let r=await this.post(eA,{command:"FINALIZE",media_id:e.media_id_string},{prefix:n});if(r.processing_info&&"succeeded"!==r.processing_info.state&&await this.awaitForMediaProcessingCompletion(r),s)return r;return r.media_id_string}finally{"number"==typeof e?E.close(e,()=>{}):"object"!=typeof a||a instanceof Buffer||a.close()}}async awaitForMediaProcessingCompletion(e){for(var t;;){let{processing_info:s}=e=await this.mediaInfo(e.media_id_string);if(!s||"succeeded"===s.state)return;if(null===(t=s.error)||void 0===t?void 0:t.code){let{name:e,message:t}=s.error;throw Error(`Failed to process media: ${e} - ${t}.`)}if("failed"===s.state)throw Error("Failed to process the media.");s.check_after_secs?await eD(s.check_after_secs):await eD(5)}}async getUploadMediaRequirements(e,{mimeType:t,type:s,target:r,longVideo:i}={}){let a;try{let o;a=await eR(e);let l=function(e,t,s){if("string"==typeof s)return s;if("string"==typeof e&&!t)return e.endsWith(".jpeg")||e.endsWith(".jpg")?v.Jpeg:e.endsWith(".png")?v.Png:e.endsWith(".webp")?v.Webp:e.endsWith(".gif")?v.Gif:e.endsWith(".mpeg4")||e.endsWith(".mp4")?v.Mp4:e.endsWith(".mov")||e.endsWith(".mov")?v.Mov:e.endsWith(".srt")?v.Srt:(O({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"options.mimeType is missing and filename couldn't help to resolve MIME type, so it will fallback to image/jpeg",resolution:"If you except to give filenames without extensions, please specify explicitlty the MIME type using options.mimeType"}),v.Jpeg);if("string"==typeof t)return(O({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"you're using options.type",resolution:"Remove options.type argument and migrate to options.mimeType which takes the real MIME type. If you're using type=longmp4, add options.longVideo alongside of mimeType=EUploadMimeType.Mp4"}),"gif"===t)?v.Gif:"jpg"===t?v.Jpeg:"png"===t?v.Png:"webp"===t?v.Webp:"srt"===t?v.Srt:"mp4"===t||"longmp4"===t?v.Mp4:"mov"===t?v.Mov:t;throw Error("You must specify type if file is a file handle or Buffer.")}(e,s,t);if(l!==v.Mp4||(t||s||"dm"===r)&&!i){var n;n=null!=r?r:"tweet",o=l===v.Mp4||l===v.Mov?"tweet"===n?"TweetVideo":"DmVideo":l===v.Gif?"tweet"===n?"TweetGif":"DmGif":l===v.Srt?"Subtitles":"tweet"===n?"TweetImage":"DmImage"}else o="amplify_video";return{fileHandle:a,mediaCategory:o,fileSize:await eE(a),mimeType:l}}catch(t){throw"number"==typeof e?E.close(e,()=>{}):"object"!=typeof a||a instanceof Buffer||a.close(),t}}async mediaChunkedUpload(e,t,s,r=3){let i,a,o=0;if(r<1)throw RangeError("Bad maxConcurrentUploads parameter.");let l=e instanceof Buffer?void 0:Buffer.alloc(t),u=0;[i,a]=await eP(e,t,u,l),u+=a;let d=new Set;for(;a;){let c=i.slice(0,a);if(c.length){let e=this.post(eA,{command:"APPEND",media_id:s,segment_index:o,media:c},{prefix:n});d.add(e),e.then(()=>{d.delete(e)}),o++}d.size>=r&&await Promise.race(d),[i,a]=await eP(e,t,u,l),u+=a}await Promise.all([...d])}}class eL extends eI{constructor(){super(...arguments),this._prefix=a}get readWrite(){return this}sendDm({recipient_id:e,custom_profile_id:t,...s}){let r={event:{type:b.Create,[b.Create]:{target:{recipient_id:e},message_data:s}}};return t&&(r.event[b.Create].custom_profile_id=t),this.post("direct_messages/events/new.json",r,{forceBodyMode:"json"})}getDmEvent(e){return this.get("direct_messages/events/show.json",{id:e})}deleteDm(e){return this.delete("direct_messages/events/destroy.json",{id:e})}async listDmEvents(e={}){let t={...e},s=await this.get("direct_messages/events/list.json",t,{fullResponse:!0});return new p({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}newWelcomeDm(e,t){let s={[b.WelcomeCreate]:{name:e,message_data:t}};return this.post("direct_messages/welcome_messages/new.json",s,{forceBodyMode:"json"})}getWelcomeDm(e){return this.get("direct_messages/welcome_messages/show.json",{id:e})}deleteWelcomeDm(e){return this.delete("direct_messages/welcome_messages/destroy.json",{id:e})}updateWelcomeDm(e,t){return this.put("direct_messages/welcome_messages/update.json",{message_data:t},{forceBodyMode:"json",query:{id:e}})}async listWelcomeDms(e={}){let t={...e},s=await this.get("direct_messages/welcome_messages/list.json",t,{fullResponse:!0});return new m({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t})}newWelcomeDmRule(e){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:e}},{forceBodyMode:"json"})}getWelcomeDmRule(e){return this.get("direct_messages/welcome_messages/rules/show.json",{id:e})}deleteWelcomeDmRule(e){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:e})}async listWelcomeDmRules(e={}){let t={...e};return this.get("direct_messages/welcome_messages/rules/list.json",t)}async setWelcomeDm(e,t=!0){var s;let r=await this.listWelcomeDmRules();if(null===(s=r.welcome_message_rules)||void 0===s?void 0:s.length)for(let e of r.welcome_message_rules)await this.deleteWelcomeDmRule(e.id),t&&await this.deleteWelcomeDm(e.welcome_message_id);return this.newWelcomeDmRule(e)}markDmAsRead(e,t){return this.post("direct_messages/mark_read.json",{last_read_event_id:e,recipient_id:t},{forceBodyMode:"url"})}indicateDmTyping(e){return this.post("direct_messages/indicate_typing.json",{recipient_id:e},{forceBodyMode:"url"})}async downloadDmImage(e){if("string"!=typeof e){let t=e[b.Create].message_data.attachment;if(!t)throw Error("The given direct message doesn't contain any attachment");e=t.media.media_url_https}let t=await this.get(e,void 0,{forceParseMode:"buffer",prefix:""});if(!t.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return t}}let e$=eL;class eO{constructor(e){this.result=e}get tweets(){return eO.tweets(this.result)}static tweets(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.tweets)&&void 0!==s?s:[]}tweetById(e){return eO.tweetById(this.result,e)}static tweetById(e,t){return this.tweets(e).find(e=>e.id===t)}retweet(e){return eO.retweet(this.result,e)}static retweet(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"retweeted"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}quote(e){return eO.quote(this.result,e)}static quote(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"quoted"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}repliedTo(e){return eO.repliedTo(this.result,e)}static repliedTo(e,t){var s;let r=(null!==(s=t.referenced_tweets)&&void 0!==s?s:[]).filter(e=>"replied_to"===e.type).map(e=>e.id);return this.tweets(e).find(e=>r.includes(e.id))}author(e){return eO.author(this.result,e)}static author(e,t){let s=t.author_id;return s?this.users(e).find(e=>e.id===s):void 0}repliedToAuthor(e){return eO.repliedToAuthor(this.result,e)}static repliedToAuthor(e,t){let s=t.in_reply_to_user_id;return s?this.users(e).find(e=>e.id===s):void 0}get users(){return eO.users(this.result)}static users(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.users)&&void 0!==s?s:[]}userById(e){return eO.userById(this.result,e)}static userById(e,t){return this.users(e).find(e=>e.id===t)}pinnedTweet(e){return eO.pinnedTweet(this.result,e)}static pinnedTweet(e,t){return t.pinned_tweet_id?this.tweets(e).find(e=>e.id===t.pinned_tweet_id):void 0}get media(){return eO.media(this.result)}static media(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.media)&&void 0!==s?s:[]}medias(e){return eO.medias(this.result,e)}static medias(e,t){var s,r;let i=null!==(r=null===(s=t.attachments)||void 0===s?void 0:s.media_keys)&&void 0!==r?r:[];return this.media(e).filter(e=>i.includes(e.media_key))}get polls(){return eO.polls(this.result)}static polls(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.polls)&&void 0!==s?s:[]}poll(e){return eO.poll(this.result,e)}static poll(e,t){var s,r;let i=null!==(r=null===(s=t.attachments)||void 0===s?void 0:s.poll_ids)&&void 0!==r?r:[];if(i.length){let t=i[0];return this.polls(e).find(e=>e.id===t)}}get places(){return eO.places(this.result)}static places(e){var t,s;return null!==(s=null===(t=e.includes)||void 0===t?void 0:t.places)&&void 0!==s?s:[]}place(e){return eO.place(this.result,e)}static place(e,t){var s;let r=null===(s=t.geo)||void 0===s?void 0:s.place_id;return r?this.places(e).find(e=>e.id===r):void 0}listOwner(e){return eO.listOwner(this.result,e)}static listOwner(e,t){let s=t.owner_id;return s?this.users(e).find(e=>e.id===s):void 0}spaceCreator(e){return eO.spaceCreator(this.result,e)}static spaceCreator(e,t){let s=t.creator_id;return s?this.users(e).find(e=>e.id===s):void 0}spaceHosts(e){return eO.spaceHosts(this.result,e)}static spaceHosts(e,t){var s;let r=null!==(s=t.host_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}spaceSpeakers(e){return eO.spaceSpeakers(this.result,e)}static spaceSpeakers(e,t){var s;let r=null!==(s=t.speaker_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}spaceInvitedUsers(e){return eO.spaceInvitedUsers(this.result,e)}static spaceInvitedUsers(e,t){var s;let r=null!==(s=t.invited_user_ids)&&void 0!==s?s:[];return this.users(e).filter(e=>r.includes(e.id))}}class eq extends d{updateIncludes(e){if(e.errors&&(this._realData.errors||(this._realData.errors=[]),this._realData.errors=[...this._realData.errors,...e.errors]),!e.includes)return;this._realData.includes||(this._realData.includes={});let t=this._realData.includes;for(let[s,r]of Object.entries(e.includes))t[s]||(t[s]=[]),t[s]=[...t[s],...r]}assertUsable(){if(this.unusable)throw Error("Unable to use this paginator to fetch more data, as it does not contain any metadata. Check .errors property for more details.")}get meta(){return this._realData.meta}get includes(){var e;return(null===(e=this._realData)||void 0===e?void 0:e.includes)?this._includesInstance?this._includesInstance:this._includesInstance=new eO(this._realData):new eO(this._realData)}get errors(){var e;return null!==(e=this._realData.errors)&&void 0!==e?e:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class ej extends eq{refreshInstanceFromResult(e,t){var s;let r=e.data,i=null!==(s=r.data)&&void 0!==s?s:[];this._rateLimit=e.rateLimit,this._realData.data||(this._realData.data=[]),t?(this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.next_token=r.meta.next_token,this._realData.data.push(...i)):(this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.previous_token=r.meta.previous_token,this._realData.data.unshift(...i)),this.updateIncludes(r)}getNextQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(e){var t,s;return null!==(s=null===(t=e.data.data)||void 0===t?void 0:t.length)&&void 0!==s?s:0}isFetchLastOver(e){var t;return!(null===(t=e.data.data)||void 0===t?void 0:t.length)||!this.canFetchNextPage(e.data)}canFetchNextPage(e){var t;return!!(null===(t=e.meta)||void 0===t?void 0:t.next_token)}}class eC extends eq{refreshInstanceFromResult(e,t){var s;let r=e.data,i=null!==(s=r.data)&&void 0!==s?s:[];this._rateLimit=e.rateLimit,this._realData.data||(this._realData.data=[]),t?(this._realData.meta.oldest_id=r.meta.oldest_id,this._realData.meta.result_count+=r.meta.result_count,this._realData.meta.next_token=r.meta.next_token,this._realData.data.push(...i)):(this._realData.meta.newest_id=r.meta.newest_id,this._realData.meta.result_count+=r.meta.result_count,this._realData.data.unshift(...i)),this.updateIncludes(r)}getNextQueryParams(e){this.assertUsable();let t={...this.injectQueryParams(e)};return this._realData.meta.next_token?t.next_token=this._realData.meta.next_token:(t.start_time&&(t.since_id=this.dateStringToSnowflakeId(t.start_time),delete t.start_time),t.end_time&&delete t.end_time,t.until_id=this._realData.meta.oldest_id),t}getPreviousQueryParams(e){return this.assertUsable(),{...this.injectQueryParams(e),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(e){var t,s;return null!==(s=null===(t=e.data.data)||void 0===t?void 0:t.length)&&void 0!==s?s:0}isFetchLastOver(e){var t;return!(null===(t=e.data.data)||void 0===t?void 0:t.length)||!this.canFetchNextPage(e.data)}canFetchNextPage(e){return!!e.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(e){let t=BigInt("1288834974657"),s=new Date(e);if(isNaN(s.valueOf()))throw Error("Unable to convert start_time/end_time to a valid date. A ISO 8601 DateTime is excepted, please check your input.");return(BigInt(s.valueOf())-t<<BigInt("22")).toString()}get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eN extends ej{refreshInstanceFromResult(e,t){super.refreshInstanceFromResult(e,t);let s=e.data;t?this._realData.meta.oldest_id=s.meta.oldest_id:this._realData.meta.newest_id=s.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eF extends eC{constructor(){super(...arguments),this._endpoint="tweets/search/recent"}}class eM extends eC{constructor(){super(...arguments),this._endpoint="tweets/search/all"}}class eU extends eN{constructor(){super(...arguments),this._endpoint="tweets/:id/quote_tweets"}}class eB extends eN{constructor(){super(...arguments),this._endpoint="users/:id/timelines/reverse_chronological"}}class eH extends eN{constructor(){super(...arguments),this._endpoint="users/:id/tweets"}}class eV extends eN{constructor(){super(...arguments),this._endpoint="users/:id/mentions"}}class eW extends eN{constructor(){super(...arguments),this._endpoint="users/:id/bookmarks"}}class eK extends ej{get tweets(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class eY extends eK{constructor(){super(...arguments),this._endpoint="users/:id/liked_tweets"}}class eJ extends eK{constructor(){super(...arguments),this._endpoint="lists/:id/tweets"}}class ez extends ej{getItemArray(){return this.users}get users(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class eG extends ez{constructor(){super(...arguments),this._endpoint="users/:id/blocking"}}class eX extends ez{constructor(){super(...arguments),this._endpoint="users/:id/muting"}}class eQ extends ez{constructor(){super(...arguments),this._endpoint="users/:id/followers"}}class eZ extends ez{constructor(){super(...arguments),this._endpoint="users/:id/following"}}class e0 extends ez{constructor(){super(...arguments),this._endpoint="lists/:id/members"}}class e1 extends ez{constructor(){super(...arguments),this._endpoint="lists/:id/followers"}}class e2 extends ez{constructor(){super(...arguments),this._endpoint="tweets/:id/liking_users"}}class e8 extends ez{constructor(){super(...arguments),this._endpoint="tweets/:id/retweeted_by"}}class e4 extends ej{getItemArray(){return this.lists}get lists(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class e5 extends e4{constructor(){super(...arguments),this._endpoint="users/:id/owned_lists"}}class e3 extends e4{constructor(){super(...arguments),this._endpoint="users/:id/list_memberships"}}class e7 extends e4{constructor(){super(...arguments),this._endpoint="users/:id/followed_lists"}}class e6 extends et{constructor(){super(...arguments),this._prefix=i}}class e9 extends ej{getItemArray(){return this.events}get events(){var e;return null!==(e=this._realData.data)&&void 0!==e?e:[]}get meta(){return super.meta}}class te extends e9{constructor(){super(...arguments),this._endpoint="dm_events"}}class tt extends e9{constructor(){super(...arguments),this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class ts extends e9{constructor(){super(...arguments),this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class tr extends et{constructor(){super(...arguments),this._prefix=r}get labs(){return this._labs?this._labs:this._labs=new e6(this)}async search(e,t={}){let s="string"==typeof e?{...t,query:e}:{...e},r=await this.get("tweets/search/recent",s,{fullResponse:!0});return new eF({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}async searchAll(e,t={}){let s={...t,query:e},r=await this.get("tweets/search/all",s,{fullResponse:!0});return new eM({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:s})}singleTweet(e,t={}){return this.get("tweets/:id",t,{params:{id:e}})}tweets(e,t={}){return this.get("tweets",{ids:e,...t})}tweetCountRecent(e,t={}){return this.get("tweets/counts/recent",{query:e,...t})}tweetCountAll(e,t={}){return this.get("tweets/counts/all",{query:e,...t})}async tweetRetweetedBy(e,t={}){let{asPaginator:s,...r}=t,i=await this.get("tweets/:id/retweeted_by",r,{fullResponse:!0,params:{id:e}});return s?new e8({realData:i.data,rateLimit:i.rateLimit,instance:this,queryParams:r,sharedParams:{id:e}}):i.data}async tweetLikedBy(e,t={}){let{asPaginator:s,...r}=t,i=await this.get("tweets/:id/liking_users",r,{fullResponse:!0,params:{id:e}});return s?new e2({realData:i.data,rateLimit:i.rateLimit,instance:this,queryParams:r,sharedParams:{id:e}}):i.data}async homeTimeline(e={}){let t=await this.getCurrentUserV2Object(),s=await this.get("users/:id/timelines/reverse_chronological",e,{fullResponse:!0,params:{id:t.data.id}});return new eB({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:e,sharedParams:{id:t.data.id}})}async userTimeline(e,t={}){let s=await this.get("users/:id/tweets",t,{fullResponse:!0,params:{id:e}});return new eH({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async userMentionTimeline(e,t={}){let s=await this.get("users/:id/mentions",t,{fullResponse:!0,params:{id:e}});return new eV({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async quotes(e,t={}){let s=await this.get("tweets/:id/quote_tweets",t,{fullResponse:!0,params:{id:e}});return new eU({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:t,sharedParams:{id:e}})}async bookmarks(e={}){let t=await this.getCurrentUserV2Object(),s=await this.get("users/:id/bookmarks",e,{fullResponse:!0,params:{id:t.data.id}});return new eW({realData:s.data,rateLimit:s.rateLimit,instance:this,queryParams:e,sharedParams:{id:t.data.id}})}me(e={}){return this.get("users/me",e)}user(e,t={}){return this.get("users/:id",t,{params:{id:e}})}users(e,t={}){let s=Array.isArray(e)?e.join(","):e;return this.get("users",{...t,ids:s})}userByUsername(e,t={}){return this.get("users/by/username/:username",t,{params:{username:e}})}usersByUsernames(e,t={}){return e=Array.isArray(e)?e.join(","):e,this.get("users/by",{...t,usernames:e})}async followers(e,t={}){let{asPaginator:s,...r}=t,i={id:e};if(!s)return this.get("users/:id/followers",r,{params:i});let a=await this.get("users/:id/followers",r,{fullResponse:!0,params:i});return new eQ({realData:a.data,rateLimit:a.rateLimit,instance:this,queryParams:r,sharedParams:i})}async following(e,t={}){let{asPaginator:s,...r}=t,i={id:e};if(!s)return this.get("users/:id/following",r,{params:i});let a=await this.get("users/:id/following",r,{fullResponse:!0,params:i});return new eZ({realData:a.data,rateLimit:a.rateLimit,instance:this,queryParams:r,sharedParams:i})}async userLikedTweets(e,t={}){let s={id:e},r=await this.get("users/:id/liked_tweets",t,{fullResponse:!0,params:s});return new eY({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async userBlockingUsers(e,t={}){let s={id:e},r=await this.get("users/:id/blocking",t,{fullResponse:!0,params:s});return new eG({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async userMutingUsers(e,t={}){let s={id:e},r=await this.get("users/:id/muting",t,{fullResponse:!0,params:s});return new eX({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}list(e,t={}){return this.get("lists/:id",t,{params:{id:e}})}async listsOwned(e,t={}){let s={id:e},r=await this.get("users/:id/owned_lists",t,{fullResponse:!0,params:s});return new e5({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listMemberships(e,t={}){let s={id:e},r=await this.get("users/:id/list_memberships",t,{fullResponse:!0,params:s});return new e3({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listFollowed(e,t={}){let s={id:e},r=await this.get("users/:id/followed_lists",t,{fullResponse:!0,params:s});return new e7({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listTweets(e,t={}){let s={id:e},r=await this.get("lists/:id/tweets",t,{fullResponse:!0,params:s});return new eJ({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listMembers(e,t={}){let s={id:e},r=await this.get("lists/:id/members",t,{fullResponse:!0,params:s});return new e0({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listFollowers(e,t={}){let s={id:e},r=await this.get("lists/:id/followers",t,{fullResponse:!0,params:s});return new e1({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listDmEvents(e={}){let t=await this.get("dm_events",e,{fullResponse:!0});return new te({realData:t.data,rateLimit:t.rateLimit,instance:this,queryParams:{...e}})}async listDmEventsWithParticipant(e,t={}){let s={participant_id:e},r=await this.get("dm_conversations/with/:participant_id/dm_events",t,{fullResponse:!0,params:s});return new tt({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}async listDmEventsOfConversation(e,t={}){let s={dm_conversation_id:e},r=await this.get("dm_conversations/:dm_conversation_id/dm_events",t,{fullResponse:!0,params:s});return new ts({realData:r.data,rateLimit:r.rateLimit,instance:this,queryParams:{...t},sharedParams:s})}space(e,t={}){return this.get("spaces/:id",t,{params:{id:e}})}spaces(e,t={}){return this.get("spaces",{ids:e,...t})}spacesByCreators(e,t={}){return this.get("spaces/by/creator_ids",{user_ids:e,...t})}searchSpaces(e){return this.get("spaces/search",e)}spaceBuyers(e,t={}){return this.get("spaces/:id/buyers",t,{params:{id:e}})}spaceTweets(e,t={}){return this.get("spaces/:id/tweets",t,{params:{id:e}})}searchStream({autoConnect:e,...t}={}){return this.getStream("tweets/search/stream",t,{payloadIsError:I,autoConnect:e})}streamRules(e={}){return this.get("tweets/search/stream/rules",e)}updateStreamRules(e,t={}){return this.post("tweets/search/stream/rules",e,{query:t})}sampleStream({autoConnect:e,...t}={}){return this.getStream("tweets/sample/stream",t,{payloadIsError:I,autoConnect:e})}sample10Stream({autoConnect:e,...t}={}){return this.getStream("tweets/sample10/stream",t,{payloadIsError:I,autoConnect:e})}complianceJobs(e){return this.get("compliance/jobs",e)}complianceJob(e){return this.get("compliance/jobs/:id",void 0,{params:{id:e}})}async sendComplianceJob(e){let t=await this.post("compliance/jobs",{type:e.type,name:e.name}),s=e.ids instanceof Buffer?e.ids:Buffer.from(e.ids.join("\n"));return await this.put(t.data.upload_url,s,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),t}async complianceJobResult(e){let t=e;for(;"complete"!==t.status;){if("expired"===t.status||"failed"===t.status)throw Error("Job failed to be completed.");await new Promise(e=>setTimeout(e,3500)),t=(await this.complianceJob(e.id)).data}return(await this.get(e.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split("\n").filter(e=>e).map(e=>JSON.parse(e))}async usage(e={}){return this.get("usage/tweets",e)}community(e,t={}){return this.get("communities/:id",t,{params:{id:e}})}searchCommunities(e,t={}){return this.get("communities/search",{query:e,...t})}}class ti extends e6{constructor(){super(...arguments),this._prefix=i}get readOnly(){return this}}class ta extends tr{constructor(){super(...arguments),this._prefix=r}get readOnly(){return this}get labs(){return this._labs?this._labs:this._labs=new ti(this)}hideReply(e,t){return this.put("tweets/:id/hidden",{hidden:t},{params:{id:e}})}like(e,t){return this.post("users/:id/likes",{tweet_id:t},{params:{id:e}})}unlike(e,t){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:e,tweet_id:t}})}retweet(e,t){return this.post("users/:id/retweets",{tweet_id:t},{params:{id:e}})}unretweet(e,t){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:e,tweet_id:t}})}tweet(e,t={}){return t="object"==typeof e?e:{text:e,...t},this.post("tweets",t)}async uploadMedia(e,t,s=1048576){let r=t.media_category;!t.media_category&&(t.media_type.includes("gif")?r="tweet_gif":t.media_type.includes("image")?r="tweet_image":t.media_type.includes("video")&&(r="tweet_video"));let i={additional_owners:t.additional_owners,media_type:t.media_type,total_bytes:e.length,media_category:r},a=(await this.post("media/upload/initialize",i)).data.id,n=Math.ceil(e.length/s),o=new Uint8Array(e);for(let t=0;t<n;t++){let r=t*s,i=Math.min(r+s,e.length),n=o.slice(r,i),l={segment_index:t,media:Buffer.from(n)};await this.post(`media/upload/${a}/append`,l,{forceBodyMode:"form-data"})}return(await this.post(`media/upload/${a}/finalize`)).data.processing_info&&await this.waitForMediaProcessing(a),a}async waitForMediaProcessing(e){var t;let s=(await this.get("media/upload",{command:"STATUS",media_id:e})).data.processing_info;if(s)switch(s.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${null===(t=s.error)||void 0===t?void 0:t.message}`);case"pending":case"in_progress":{let t=null==s?void 0:s.check_after_secs;t&&t>0&&(await new Promise(e=>setTimeout(e,1e3*t)),await this.waitForMediaProcessing(e))}}}createMediaMetadata(e,t){return this.post("media/metadata",{id:e,metadata:t})}reply(e,t,s={}){var r;let i={in_reply_to_tweet_id:t,...null!==(r=s.reply)&&void 0!==r?r:{}};return this.post("tweets",{text:e,...s,reply:i})}quote(e,t,s={}){return this.tweet(e,{...s,quote_tweet_id:t})}async tweetThread(e){var t,s;let r=[];for(let i of e){let e=r.length?r[r.length-1]:null,a={..."string"==typeof i?{text:i}:i},n=e?e.data.id:null===(t=a.reply)||void 0===t?void 0:t.in_reply_to_tweet_id,o=null!==(s=a.text)&&void 0!==s?s:"";n?r.push(await this.reply(o,n,a)):r.push(await this.tweet(o,a))}return r}deleteTweet(e){return this.delete("tweets/:id",void 0,{params:{id:e}})}async bookmark(e){let t=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:e},{params:{id:t.data.id}})}async deleteBookmark(e){let t=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:t.data.id,tweet_id:e}})}follow(e,t){return this.post("users/:id/following",{target_user_id:t},{params:{id:e}})}unfollow(e,t){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}block(e,t){return this.post("users/:id/blocking",{target_user_id:t},{params:{id:e}})}unblock(e,t){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}mute(e,t){return this.post("users/:id/muting",{target_user_id:t},{params:{id:e}})}unmute(e,t){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:e,target_user_id:t}})}createList(e){return this.post("lists",e)}updateList(e,t={}){return this.put("lists/:id",t,{params:{id:e}})}removeList(e){return this.delete("lists/:id",void 0,{params:{id:e}})}addListMember(e,t){return this.post("lists/:id/members",{user_id:t},{params:{id:e}})}removeListMember(e,t){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:e,user_id:t}})}subscribeToList(e,t){return this.post("users/:id/followed_lists",{list_id:t},{params:{id:e}})}unsubscribeOfList(e,t){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:e,list_id:t}})}pinList(e,t){return this.post("users/:id/pinned_lists",{list_id:t},{params:{id:e}})}unpinList(e,t){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:e,list_id:t}})}sendDmInConversation(e,t){return this.post("dm_conversations/:dm_conversation_id/messages",t,{params:{dm_conversation_id:e}})}sendDmToParticipant(e,t){return this.post("dm_conversations/with/:participant_id/messages",t,{params:{participant_id:e}})}createDmConversation(e){return this.post("dm_conversations",e)}}class tn extends ti{constructor(){super(...arguments),this._prefix=i}get readWrite(){return this}}class to extends ta{constructor(){super(...arguments),this._prefix=r}get readWrite(){return this}get labs(){return this._labs?this._labs:this._labs=new tn(this)}}class tl extends ee{get v1(){return this._v1?this._v1:this._v1=new eS(this)}get v2(){return this._v2?this._v2:this._v2=new tr(this)}async currentUser(e=!1){return await this.getCurrentUserObject(e)}async currentUserV2(e=!1){return await this.getCurrentUserV2Object(e)}search(e,t){return this.v2.search(e,t)}async generateAuthLink(e="oob",{authAccessType:t,linkMode:s="authenticate",forceLogin:r,screenName:i}={}){let a=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:e,x_auth_access_type:t}),n=`https://api.x.com/oauth/${s}?oauth_token=${encodeURIComponent(a.oauth_token)}`;return void 0!==r&&(n+=`&force_login=${encodeURIComponent(r)}`),void 0!==i&&(n+=`&screen_name=${encodeURIComponent(i)}`),this._requestMaker.hasPlugins()&&this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:n,oauthResult:a}),{url:n,...a}}async login(e){let t=this.getActiveTokens();if("oauth-1.0a"!==t.type)throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let s=await this.post("https://api.x.com/oauth/access_token",{oauth_token:t.accessToken,oauth_verifier:e}),r=new this.constructor({appKey:t.appKey,appSecret:t.appSecret,accessToken:s.oauth_token,accessSecret:s.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:s.oauth_token,accessSecret:s.oauth_token_secret,userId:s.user_id,screenName:s.screen_name,client:r}}async appLogin(){let e=this.getActiveTokens();if("oauth-1.0a"!==e.type)throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let t=new this.constructor({username:e.appKey,password:e.appSecret},this._requestMaker.clientSettings),s=await t.post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor(s.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(e,t={}){var s,r;if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. You can find your client ID in Twitter Developer Portal. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let i=null!==(s=t.state)&&void 0!==s?s:Q.generateRandomString(32),a=Q.getCodeVerifier(),n=Q.getCodeChallengeFromVerifier(a),o=null!==(r=t.scope)&&void 0!==r?r:"",l=Array.isArray(o)?o.join(" "):o,u=new URL("https://x.com/i/oauth2/authorize"),d={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:e,state:i,code_challenge:n,code_challenge_method:"s256",scope:l};X.addQueryParamsToUrl(u,d);let c={url:u.toString(),state:i,codeVerifier:a,codeChallenge:n};return this._requestMaker.hasPlugins()&&this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:c,redirectUri:e}),c}async loginWithOAuth2({code:e,codeVerifier:t,redirectUri:s}){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let r=await this.post("https://api.x.com/2/oauth2/token",{code:e,code_verifier:t,redirect_uri:s,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(r)}async refreshOAuth2Token(e){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let t=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:e,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(t)}async revokeOAuth2Token(e,t="access_token"){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");return await this.post("https://api.x.com/2/oauth2/revoke",{client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret,token:e,token_type_hint:t})}parseOAuth2AccessTokenResult(e){let t=new this.constructor(e.access_token,this._requestMaker.clientSettings),s=e.scope.split(" ").filter(e=>e);return{client:t,expiresIn:e.expires_in,accessToken:e.access_token,scope:s,refreshToken:e.refresh_token}}}class tu extends tl{get v1(){return this._v1?this._v1:this._v1=new eI(this)}get v2(){return this._v2?this._v2:this._v2=new ta(this)}get readOnly(){return this}}class td extends et{constructor(){super(...arguments),this._prefix=o}}class tc extends td{constructor(){super(...arguments),this._prefix=o}get readOnly(){return this}}class th extends et{constructor(){super(...arguments),this._prefix=l}}class tp extends th{constructor(){super(...arguments),this._prefix=l}get readOnly(){return this}}class tm extends tp{constructor(){super(...arguments),this._prefix=l}get readWrite(){return this}}class tg extends tc{constructor(){super(...arguments),this._prefix=o}get readWrite(){return this}get sandbox(){return this._sandbox?this._sandbox:this._sandbox=new tm(this)}}class t_ extends tu{get v1(){return this._v1?this._v1:this._v1=new e$(this)}get v2(){return this._v2?this._v2:this._v2=new to(this)}get readWrite(){return this}get ads(){return this._ads?this._ads:this._ads=new tg(this)}static getErrors(e){var t;return"object"==typeof e&&"data"in e&&null!==(t=e.data.errors)&&void 0!==t?t:[]}static getProfileImageInSize(e,t){let s=e.split("/").pop(),r=e;for(let t of["normal","bigger","mini"])if(s.includes(`_${t}`)){r=e.replace(`_${t}`,"");break}if("original"===t)return r;let i=r.lastIndexOf(".");if(-1===i)return r+"_"+t;{let e=r.slice(i+1);return r.slice(0,i)+"_"+t+"."+e}}}let tf=t_},7786:(e,t,s)=>{"use strict";s.d(t,{ET:()=>d,QN:()=>n,Ug:()=>u,b0:()=>a,pF:()=>o,wE:()=>l});var r=s(5315),i=s(2048);let a=function(){let e=process.cwd();if(i.existsSync(r.join(e,"data","config.json")))return e;try{for(let t of i.readdirSync(e,{withFileTypes:!0}))if(t.isDirectory()){let s=r.join(e,t.name,"data","config.json");if(i.existsSync(s))return r.join(e,t.name)}}catch{}let t=e;for(let e=0;e<5;e++){let e=r.dirname(t);if(e===t)break;if(i.existsSync(r.join(e,"data","config.json")))return e;t=e}return e}(),n=r.join(a,"data");r.join(a,"STATUS.md"),r.join(a,"TODO.md"),r.join(a,"MEMORY.md");let o=r.join(n,"ideas.json"),l=r.join(n,"goals.json");r.join(n,"sessions.json"),r.join(n,"config.json"),r.join(n,"business-context.json"),r.join(n,"hypotheses.json"),r.join(n,"implementations.json"),r.join(n,"roadmap.json"),r.join(n,"competitors.json");let u=r.join(n,"positioning.json");r.join(n,"pages.json"),r.join(n,"payments.json"),r.join(n,"posthog.json");let d=r.join(n,"social.json"),c=r.join(__dirname,"..","..","templates");r.join(c,"commands")},7530:(e,t,s)=>{"use strict";s.d(t,{$O:()=>l,Fb:()=>u,cq:()=>c,gJ:()=>d});var r=s(2048),i=s(7786);let a="#buildinpublic";function n(e,t=280){return e.length<=t?e:e.slice(0,t-3).trimEnd()+"..."}function o(e,t){try{if(!r.existsSync(e))return t;return JSON.parse(r.readFileSync(e,"utf-8"))}catch{return t}}function l(e){if(!e){let t=o(i.pF,{ideas:[]}).ideas.filter(e=>"shipped"===e.stage).sort((e,t)=>(t.implementation?.completed_at||t.updated_at).localeCompare(e.implementation?.completed_at||e.updated_at));if(0===t.length)return null;e=t[0]}return n(`Just shipped: ${e.title}. ${e.summary} ${a}`)}function u(e,t,s){if(e&&null!=t&&null!=s)return n(`Hit ${t} ${e}! ${s>0?Math.round(t/s*100):100}% to goal ${a}`);for(let e of o(i.wE,{goals:[]}).goals)for(let t of e.kpis)if(null!=t.current_value&&null!=t.target_value&&t.current_value>=t.target_value){let e=Math.round(t.current_value/t.target_value*100);return n(`Hit ${t.current_value} ${t.name}! ${e}% to goal ${a}`)}return null}function d(e){if(!e){let t=o(i.pF,{ideas:[]}),s=new Date(Date.now()-6048e5).toISOString(),r=t.ideas.filter(e=>"shipped"===e.stage&&(e.implementation?.completed_at||e.updated_at)>s);if(0===r.length)return null;e={ideasShipped:r.length,kpisMoved:0,topShip:r[0]?.title}}let t=["Weekly recap:"];return t.push(`${e.ideasShipped} feature${1!==e.ideasShipped?"s":""} shipped`),e.kpisMoved>0&&t.push(`${e.kpisMoved} KPI${1!==e.kpisMoved?"s":""} moved`),e.topShip&&t.push(`Top: ${e.topShip}`),n(`${t.join(". ")}. ${a}`)}function c(e){if(!e&&(e=o(i.Ug,null),!e?.current))return null;let t=e.current.tagline,s=e.current.value_proposition,r=s.split(/[.!]/).filter(Boolean)[0]?.trim();return r?n(`${t} — ${r}. ${a}`):n(`${t} ${a}`)}},7151:(e,t,s)=>{"use strict";s.r(t),s.d(t,{executeSocialTask:()=>K,gatherKickstartContext:()=>J,isSocialTask:()=>W,readSocialFreshness:()=>Y});var r=s(2048),i=s(5315),a=s(9576),n=s(7786);function o(){let e=function(e){let t=i.join(e,".env");if(!r.existsSync(t))return{};let s=r.readFileSync(t,"utf-8"),a={};for(let e of s.split("\n")){let t=e.trim();if(!t||t.startsWith("#"))continue;let s=t.indexOf("=");if(-1===s)continue;let r=t.slice(0,s).trim(),i=t.slice(s+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),a[r]=i}return a}(n.b0),t=e.X_API_KEY||process.env.X_API_KEY,s=e.X_API_SECRET||process.env.X_API_SECRET,a=e.X_ACCESS_TOKEN||process.env.X_ACCESS_TOKEN,o=e.X_ACCESS_SECRET||process.env.X_ACCESS_SECRET;return t&&s&&a&&o?{apiKey:t,apiSecret:s,accessToken:a,accessSecret:o}:null}function l(e){let t;try{let e=s(1401).resolve("twitter-api-v2",{paths:[n.b0]}),r=s(1401)(e);t=r.TwitterApi||r.default?.TwitterApi||r.default}catch{try{let e=s(5883);t=e.TwitterApi||e.default?.TwitterApi||e.default}catch{throw Error("twitter-api-v2 is not installed. Run: npm install twitter-api-v2")}}if("function"!=typeof t)throw Error("Could not find TwitterApi constructor in twitter-api-v2");return new t({appKey:e.apiKey,appSecret:e.apiSecret,accessToken:e.accessToken,accessSecret:e.accessSecret})}async function u(e){try{let t=await e.v2.me({"user.fields":["public_metrics"]}),s=t?.data;if(!s?.username)return{valid:!1,username:null,followersCount:null};return{valid:!0,username:`@${s.username}`,followersCount:s.public_metrics?.followers_count??null}}catch{return{valid:!1,username:null,followersCount:null}}}async function d(e,t){if(t.length>280)throw Error(`Tweet exceeds 280 characters (${t.length})`);let s=await e.v2.tweet(t),r=s?.data?.id;if(!r)throw Error("Tweet posted but no ID returned");return{id:r,url:`https://x.com/i/status/${r}`}}async function c(e,t){if(!s(2048).existsSync(t))throw Error(`Media file not found: ${t}`);let r=await e.v1.uploadMedia(t);if(!r)throw Error("Media uploaded but no media_id returned");return String(r)}async function h(e,t,s){if(t.length>280)throw Error(`Tweet exceeds 280 characters (${t.length})`);if(0===s.length)throw Error("No media IDs provided");if(s.length>4)throw Error("X allows max 4 media attachments per tweet");let r=await e.v2.tweet(t,{media:{media_ids:s}}),i=r?.data?.id;if(!i)throw Error("Tweet posted but no ID returned");return{id:i,url:`https://x.com/i/status/${i}`}}async function p(e,t){try{let s=await e.v2.singleTweet(t,{"tweet.fields":["public_metrics","non_public_metrics","organic_metrics"]}),r=s?.data;if(!r)return null;let i=r.public_metrics??{},a=r.non_public_metrics??{},n=r.organic_metrics??{},o=a.impression_count??n.impression_count??0,l=(i.like_count??0)+(i.retweet_count??0)+(i.reply_count??0)+(i.bookmark_count??0)+(a.url_link_clicks??0)+(a.user_profile_clicks??0);return{tweet_id:t,impressions:o,likes:i.like_count??0,retweets:i.retweet_count??0,replies:i.reply_count??0,bookmarks:i.bookmark_count??0,profile_clicks:a.user_profile_clicks??0,engagements:l,engagement_rate:o>0?l/o:0,fetched_at:new Date().toISOString()}}catch(e){return console.error(`Failed to fetch metrics for tweet ${t}:`,e),null}}async function m(e,t){let s=[];for(let r of t){let t=await p(e,r);t&&s.push(t)}return s}async function g(e,t,s){if(t.length>280)throw Error(`Reply exceeds 280 characters (${t.length})`);let r=await e.v2.tweet(t,{reply:{in_reply_to_tweet_id:s}}),i=r?.data?.id;if(!i)throw Error("Reply posted but no ID returned");return{id:i,url:`https://x.com/i/status/${i}`}}async function _(e,t,s=10){let r=await e.v2.search(t,{max_results:Math.min(s,100),"tweet.fields":["public_metrics","created_at","author_id"],"user.fields":["username","name","public_metrics"],expansions:["author_id"]}),i=r?.data?.data??[],a=r?.data?.includes?.users??r?.includes?.users??[],n=new Map;for(let e of a)n.set(e.id,{username:e.username,name:e.name,followers:e.public_metrics?.followers_count??0});let o=[];for(let e of i){let t=n.get(e.author_id),s=e.public_metrics??{};o.push({id:e.id,text:e.text,author_id:e.author_id,author_username:t?.username??"unknown",author_name:t?.name??"Unknown",author_followers:t?.followers??0,like_count:s.like_count??0,retweet_count:s.retweet_count??0,reply_count:s.reply_count??0,bookmark_count:s.bookmark_count??0,created_at:e.created_at??"",url:`https://x.com/${t?.username??"i"}/status/${e.id}`})}return o}async function f(e,t,s){if(0===t.length)throw Error("Thread must have at least one tweet");if(t.length>25)throw Error("Thread cannot exceed 25 tweets");for(let e=0;e<t.length;e++)if(t[e].length>280)throw Error(`Tweet ${e+1} exceeds 280 characters (${t[e].length})`);let r=[];for(let i=0;i<t.length;i++){let a=t[i],n=s?.[i],o={};i>0&&(o.reply={in_reply_to_tweet_id:r[i-1].id}),n&&(o.media={media_ids:[n]});let l=await e.v2.tweet(a,o),u=l?.data?.id;if(!u)throw Error(`Thread tweet ${i+1} posted but no ID returned`);r.push({id:u,url:`https://x.com/i/status/${u}`})}return r}var w=s(7530),y=s(1282);let v=i.join(process.env.HOME||"",".vibebusiness"),b=i.join(v,"credentials.json"),k=i.join(process.env.HOME||"",".ai-analyst"),x=i.join(k,"provider.json");async function S(e){let t=Date.now(),s=process.env.ANTHROPIC_API_KEY;if(!s)return{output:"",provider:"anthropic-api",durationMs:0,error:"ANTHROPIC_API_KEY not set"};try{let r=e.model||"claude-sonnet-4-6",i=e.prompt;e.jsonSchema?i+=`
|
|
3
3
|
|
|
4
4
|
IMPORTANT: Respond with valid JSON matching this schema:
|
|
5
5
|
${JSON.stringify(e.jsonSchema,null,2)}
|
|
6
6
|
|
|
7
|
-
Output ONLY the JSON object, no markdown code blocks or other text.`:e.expectJson&&(i+="\n\nIMPORTANT: Respond with valid JSON only. No markdown code blocks or other text.");let a=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":s,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:r,max_tokens:16384,messages:[{role:"user",content:i}]}),signal:AbortSignal.timeout(e.timeoutMs||3e5)});if(!a.ok){let e=await a.text();return{output:"",provider:"anthropic-api",durationMs:Date.now()-t,error:`Anthropic API error ${a.status}: ${e}`}}return{output:(await a.json()).content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),provider:"anthropic-api",durationMs:Date.now()-t}}catch(e){return{output:"",provider:"anthropic-api",durationMs:Date.now()-t,error:`Anthropic API call failed: ${e.message}`}}}async function T(e){let t=function(){try{if(r.existsSync(x))return JSON.parse(r.readFileSync(x,"utf-8"))}catch{}return null}(),s=function(e){let t=function(e){let t=e||"claude";try{let e=(0,y.execSync)(`${t} --version 2>/dev/null`,{timeout:1e4,encoding:"utf-8"}).trim();return{found:!0,path:t,version:e}}catch{for(let e of["/usr/local/bin/claude",i.join(process.env.HOME||"",".claude","bin","claude"),i.join(process.env.HOME||"",".local","bin","claude")])try{if(r.existsSync(e)){let t=(0,y.execSync)(`${e} --version 2>/dev/null`,{timeout:1e4,encoding:"utf-8"}).trim();return{found:!0,path:e,version:t}}}catch{continue}return{found:!1,path:t}}}(e?.claudePath);if(t.found)return{provider:"claude-cli",version:t.version,message:`Found Claude Code CLI${t.version?` (${t.version})`:""}. Using your Claude subscription for AI reasoning.`};let s=function(){if(process.env.ANTHROPIC_API_KEY)return{provider:"anthropic-api",key:process.env.ANTHROPIC_API_KEY,source:"env"};if(process.env.OPENAI_API_KEY)return{provider:"openai-api",key:process.env.OPENAI_API_KEY,source:"env"};if(process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY)return{provider:"google-api",key:process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,source:"env"};let e=function(){try{if(r.existsSync(b))return JSON.parse(r.readFileSync(b,"utf-8"))}catch{}return{}}();if(e.ANTHROPIC_API_KEY)return process.env.ANTHROPIC_API_KEY=e.ANTHROPIC_API_KEY,{provider:"anthropic-api",key:e.ANTHROPIC_API_KEY,source:"credentials"};if(e.OPENAI_API_KEY)return process.env.OPENAI_API_KEY=e.OPENAI_API_KEY,{provider:"openai-api",key:e.OPENAI_API_KEY,source:"credentials"};if(e.GOOGLE_API_KEY||e.GEMINI_API_KEY){let t=e.GOOGLE_API_KEY||e.GEMINI_API_KEY;return process.env.GOOGLE_API_KEY=t,{provider:"google-api",key:t,source:"credentials"}}return null}();return s?{provider:s.provider,message:`Using ${({"claude-cli":"Claude CLI","anthropic-api":"Anthropic API","openai-api":"OpenAI API","google-api":"Google AI API"})[s.provider]} key for AI reasoning.`}:{provider:"claude-cli",message:"No AI provider found. Install Claude Code CLI or set an API key (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)."}}(t||void 0);switch(s.provider){case"claude-cli":return function(e,t){let s=t||"claude",r=["--print"];e.model&&r.push("--model",e.model),e.jsonSchema&&r.push("--output-format","json","--json-schema",JSON.stringify(e.jsonSchema)),e.claudeFlags&&r.push(...e.claudeFlags);let i=!1!==e.useStdin&&e.prompt.length>1e4;i||r.push("-p",e.prompt);let a=Date.now(),n=e.timeoutMs||3e5;return new Promise(t=>{let o=(0,y.spawn)(s,r,{cwd:e.cwd||process.cwd(),env:process.env,stdio:i?["pipe","pipe","pipe"]:["ignore","pipe","pipe"]}),l="",u="";o.stdout?.on("data",e=>{l+=e.toString()}),o.stderr?.on("data",e=>{u+=e.toString()}),i&&o.stdin&&(o.stdin.write(e.prompt),o.stdin.end());let d=setTimeout(()=>{o.kill("SIGTERM"),t({output:l,provider:"claude-cli",durationMs:Date.now()-a,error:`Timeout after ${n}ms`})},n);o.on("close",e=>{clearTimeout(d),t({output:l.trim(),provider:"claude-cli",durationMs:Date.now()-a,error:0!==e?`Claude CLI exited with code ${e}: ${u}`:void 0})}),o.on("error",e=>{clearTimeout(d),t({output:"",provider:"claude-cli",durationMs:Date.now()-a,error:`Failed to spawn Claude CLI: ${e.message}`})})})}(e,t?.claudePath);case"anthropic-api":return S(e);case"openai-api":case"google-api":return{output:"",provider:s.provider,durationMs:0,error:`${s.provider} provider not yet implemented. Use Claude CLI or set ANTHROPIC_API_KEY.`};default:return{output:"",provider:"claude-cli",durationMs:0,error:s.message}}}function R(e,t){try{if(!r.existsSync(e))return t;return JSON.parse(r.readFileSync(e,"utf-8"))}catch{return t}}function E(e){if(!e||0===e.length)return"No historical data yet.";let t=[...e].sort((e,t)=>t.engagement_rate-e.engagement_rate),s=e.reduce((e,t)=>e+t.engagement_rate,0)/e.length,r=t[0];return`Average engagement rate: ${(100*s).toFixed(2)}%
|
|
7
|
+
Output ONLY the JSON object, no markdown code blocks or other text.`:e.expectJson&&(i+="\n\nIMPORTANT: Respond with valid JSON only. No markdown code blocks or other text.");let a=await fetch("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"Content-Type":"application/json","x-api-key":s,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:r,max_tokens:16384,messages:[{role:"user",content:i}]}),signal:AbortSignal.timeout(e.timeoutMs||3e5)});if(!a.ok){let e=await a.text();return{output:"",provider:"anthropic-api",durationMs:Date.now()-t,error:`Anthropic API error ${a.status}: ${e}`}}return{output:(await a.json()).content.filter(e=>"text"===e.type).map(e=>e.text).join("\n"),provider:"anthropic-api",durationMs:Date.now()-t}}catch(e){return{output:"",provider:"anthropic-api",durationMs:Date.now()-t,error:`Anthropic API call failed: ${e.message}`}}}async function T(e){let t=function(){try{if(r.existsSync(x))return JSON.parse(r.readFileSync(x,"utf-8"))}catch{}return null}(),s=function(e){let t=function(e){let t=e||"claude";try{let e=(0,y.execSync)(`${t} --version 2>/dev/null`,{timeout:1e4,encoding:"utf-8"}).trim();return{found:!0,path:t,version:e}}catch{for(let e of["/usr/local/bin/claude",i.join(process.env.HOME||"",".claude","bin","claude"),i.join(process.env.HOME||"",".local","bin","claude")])try{if(r.existsSync(e)){let t=(0,y.execSync)(`${e} --version 2>/dev/null`,{timeout:1e4,encoding:"utf-8"}).trim();return{found:!0,path:e,version:t}}}catch{continue}return{found:!1,path:t}}}(e?.claudePath);if(t.found)return{provider:"claude-cli",version:t.version,message:`Found Claude Code CLI${t.version?` (${t.version})`:""}. Using your Claude subscription for AI reasoning.`};let s=function(){if(process.env.ANTHROPIC_API_KEY)return{provider:"anthropic-api",key:process.env.ANTHROPIC_API_KEY,source:"env"};if(process.env.OPENAI_API_KEY)return{provider:"openai-api",key:process.env.OPENAI_API_KEY,source:"env"};if(process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY)return{provider:"google-api",key:process.env.GOOGLE_API_KEY||process.env.GEMINI_API_KEY,source:"env"};let e=function(){try{if(r.existsSync(b))return JSON.parse(r.readFileSync(b,"utf-8"))}catch{}return{}}();if(e.ANTHROPIC_API_KEY)return process.env.ANTHROPIC_API_KEY=e.ANTHROPIC_API_KEY,{provider:"anthropic-api",key:e.ANTHROPIC_API_KEY,source:"credentials"};if(e.OPENAI_API_KEY)return process.env.OPENAI_API_KEY=e.OPENAI_API_KEY,{provider:"openai-api",key:e.OPENAI_API_KEY,source:"credentials"};if(e.GOOGLE_API_KEY||e.GEMINI_API_KEY){let t=e.GOOGLE_API_KEY||e.GEMINI_API_KEY;return process.env.GOOGLE_API_KEY=t,{provider:"google-api",key:t,source:"credentials"}}return null}();return s?{provider:s.provider,message:`Using ${({"claude-cli":"Claude CLI","anthropic-api":"Anthropic API","openai-api":"OpenAI API","google-api":"Google AI API"})[s.provider]} key for AI reasoning.`}:{provider:"claude-cli",message:"No AI provider found. Install Claude Code CLI or set an API key (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)."}}(t||void 0);switch(s.provider){case"claude-cli":return function(e,t){let s=t||"claude",r=["--print"];e.model&&r.push("--model",e.model),e.jsonSchema&&r.push("--output-format","json","--json-schema",JSON.stringify(e.jsonSchema)),e.claudeFlags&&r.push(...e.claudeFlags);let i=!1!==e.useStdin&&e.prompt.length>1e4;i||r.push("-p",e.prompt);let a=Date.now(),n=e.timeoutMs||3e5;return new Promise(t=>{let o=(0,y.spawn)(s,r,{cwd:e.cwd||process.cwd(),env:process.env,stdio:i?["pipe","pipe","pipe"]:["ignore","pipe","pipe"]}),l="",u="";o.stdout?.on("data",e=>{l+=e.toString()}),o.stderr?.on("data",e=>{u+=e.toString()}),i&&o.stdin&&(o.stdin.on("error",e=>{if("EPIPE"!==e.code)throw e}),o.stdin.write(e.prompt),o.stdin.end());let d=setTimeout(()=>{o.kill("SIGTERM"),t({output:l,provider:"claude-cli",durationMs:Date.now()-a,error:`Timeout after ${n}ms`})},n);o.on("close",e=>{clearTimeout(d),t({output:l.trim(),provider:"claude-cli",durationMs:Date.now()-a,error:0!==e?`Claude CLI exited with code ${e}: ${u}`:void 0})}),o.on("error",e=>{clearTimeout(d),t({output:"",provider:"claude-cli",durationMs:Date.now()-a,error:`Failed to spawn Claude CLI: ${e.message}`})})})}(e,t?.claudePath);case"anthropic-api":return S(e);case"openai-api":case"google-api":return{output:"",provider:s.provider,durationMs:0,error:`${s.provider} provider not yet implemented. Use Claude CLI or set ANTHROPIC_API_KEY.`};default:return{output:"",provider:"claude-cli",durationMs:0,error:s.message}}}function R(e,t){try{if(!r.existsSync(e))return t;return JSON.parse(r.readFileSync(e,"utf-8"))}catch{return t}}function E(e){if(!e||0===e.length)return"No historical data yet.";let t=[...e].sort((e,t)=>t.engagement_rate-e.engagement_rate),s=e.reduce((e,t)=>e+t.engagement_rate,0)/e.length,r=t[0];return`Average engagement rate: ${(100*s).toFixed(2)}%
|
|
8
8
|
Best tweet: ${r.tweet_id} (${(100*r.engagement_rate).toFixed(2)}% rate, ${r.impressions} impressions, ${r.bookmarks} bookmarks)
|
|
9
9
|
Total tweets analyzed: ${e.length}`}let D=`
|
|
10
10
|
X/Twitter Algorithm Knowledge (use this to optimize content):
|
|
@@ -16,7 +16,7 @@ X/Twitter Algorithm Knowledge (use this to optimize content):
|
|
|
16
16
|
- 1-2 hashtags max. #buildinpublic is essential for our audience.
|
|
17
17
|
- Short paragraphs, line breaks between ideas for readability.
|
|
18
18
|
- Numbers and specific data points dramatically increase engagement.
|
|
19
|
-
`,
|
|
19
|
+
`,P=`
|
|
20
20
|
Proven Hook Patterns (rotate between these):
|
|
21
21
|
1. Stat-opening: "I analyzed 100 indie hackers..." / "After 30 days of..."
|
|
22
22
|
2. Contrarian take: "Hot take: [conventional wisdom] is wrong because..."
|
|
@@ -25,11 +25,11 @@ Proven Hook Patterns (rotate between these):
|
|
|
25
25
|
5. List tease: "5 things I learned building [product] this week:"
|
|
26
26
|
6. Before/after: "Before: [pain]. After: [result]. The difference? [insight]"
|
|
27
27
|
7. Bold claim: "[Product] just did something no other tool can do."
|
|
28
|
-
`;async function
|
|
28
|
+
`;async function A(e){let t=e.positioning??R(n.Ug,null),s=`You are a viral tweet copywriter for a developer-focused indie hacker audience.
|
|
29
29
|
|
|
30
30
|
${D}
|
|
31
31
|
|
|
32
|
-
${
|
|
32
|
+
${P}
|
|
33
33
|
|
|
34
34
|
PRODUCT CONTEXT:
|
|
35
35
|
- Product: ${t?.current?.tagline??"VibeBusiness"}
|
|
@@ -55,7 +55,7 @@ Respond in this exact JSON format (no markdown, no code blocks):
|
|
|
55
55
|
|
|
56
56
|
${D}
|
|
57
57
|
|
|
58
|
-
${
|
|
58
|
+
${P}
|
|
59
59
|
|
|
60
60
|
PRODUCT CONTEXT:
|
|
61
61
|
- Product: ${t?.current?.tagline??"VibeBusiness"}
|
|
@@ -110,7 +110,7 @@ Respond in this exact JSON format (no markdown, no code blocks):
|
|
|
110
110
|
|
|
111
111
|
${D}
|
|
112
112
|
|
|
113
|
-
${
|
|
113
|
+
${P}
|
|
114
114
|
|
|
115
115
|
PRODUCT CONTEXT:
|
|
116
116
|
- Product: ${t?.current?.tagline??"VibeBusiness"}
|
|
@@ -253,10 +253,10 @@ Respond in this exact JSON format (no markdown, no code blocks):
|
|
|
253
253
|
"top_performing": [
|
|
254
254
|
{ "tweet_id": "id", "highlight": "why this tweet worked well" }
|
|
255
255
|
]
|
|
256
|
-
}`,a=await T({prompt:i,model:"haiku"});try{let e=JSON.parse(C(a.output));return{summary:e.summary??"",best_hook_types:e.best_hook_types??[],best_posting_times:e.best_posting_times??[],thread_vs_single:e.thread_vs_single??"",recommendations:e.recommendations??[],top_performing:e.top_performing??[]}}catch{return{summary:"Could not analyze engagement data — AI response parsing failed.",best_hook_types:[],best_posting_times:[],thread_vs_single:"",recommendations:[],top_performing:[]}}}function C(e){let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t)return t[1].trim();let s=e.match(/\{[\s\S]*\}/);return s?s[0]:e.trim()}let N={last_updated:new Date().toISOString(),platform:"x",username:null,credentials_valid:!1,drafts:[],metrics:{followers_count:null,post_streak_days:0,total_posts:0,last_post_date:null}};function F(){if(!r.existsSync(n.ET))return{...N,metrics:{...N.metrics}};try{return JSON.parse(r.readFileSync(n.ET,"utf-8"))}catch{return{...N,metrics:{...N.metrics}}}}function M(e){e.last_updated=new Date().toISOString();let t=i.dirname(n.ET);r.existsSync(t)||r.mkdirSync(t,{recursive:!0}),r.writeFileSync(n.ET,JSON.stringify(e,null,2)+"\n")}function U(e){let t=e.drafts.filter(e=>"published"===e.status&&e.published_at).map(e=>e.published_at.split("T")[0]).sort().reverse();if(0===t.length)return 0;let s=Array.from(new Set(t)),r=new Date().toISOString().split("T")[0];if(s[0]!==r){let e=new Date(Date.now()-864e5).toISOString().split("T")[0];if(s[0]!==e)return 0}let i=1;for(let e=1;e<s.length;e++){let t=new Date(s[e-1]),r=new Date(s[e]);if(1===Math.round((t.getTime()-r.getTime())/864e5))i++;else break}return i}function B(e,t){return e.drafts.some(e=>e.source_ref===t&&("draft"===e.status||"published"===e.status))}function H(e,t,s,r,i=null){let n={id:`draft-${(0,a.Z)().slice(0,8)}`,text:t,source:s,source_ref:r,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,media_paths:i};return e.drafts.push(n),n}let V=["social-setup-x","social-plan-week","social-draft-ship-visual","social-draft-ship","social-draft-update","social-draft-milestone","social-draft-digest","social-draft-viral-","social-draft-thread-","social-publish-","social-boost-","social-find-replies","social-engagement-report","social-track-metrics","social-score-","social-check-status","social-kickstart"];function W(e){return V.some(t=>e.startsWith(t))}async function K(e,t,s){try{if("social-setup-x"===e)return await G();if("social-plan-week"===e)return await ei();if("social-draft-ship-visual"===e)return function(){let e=F(),t=(0,w.$O)();if(!t)return{success:!1,output:"No shipped ideas found to generate a tweet from."};let{ideas:s}=JSON.parse(r.readFileSync(i.join(i.dirname(n.ET),"ideas.json"),"utf-8")),a=s.filter(e=>"shipped"===e.stage).sort((e,t)=>t.updated_at.localeCompare(e.updated_at))[0];if(a&&B(e,a.id))return{success:!1,output:`Draft already exists for shipped idea ${a.id}`};let o=[];if(a){let e=i.join(n.QN,"reports","visuals",`${a.id}-card.png`);r.existsSync(e)&&o.push(e);let t=i.join(n.QN,"videos",`${a.id}-ship.mp4`);r.existsSync(t)&&(o.length=0,o.push(t))}if(0===o.length)return{success:!1,output:`No ship card or video found for idea ${a?.id||"unknown"}. Run generate-visual-{ideaId} first.`};let l=H(e,t,"ship",a?.id||null,o);return M(e),{success:!0,output:`Created ship draft with media: "${l.text}" (${l.id}) — ${o.length} file(s) attached`}}();if("social-draft-ship"===e)return await X();if("social-draft-update"===e)return await Q();if("social-draft-milestone"===e)return await Z();if("social-draft-digest"===e)return await ee();if(e.startsWith("social-draft-viral-")){let s=e.replace("social-draft-viral-","");return await es(s,t)}if(e.startsWith("social-draft-thread-")){let s=e.replace("social-draft-thread-","");return await er(s,t)}if(e.startsWith("social-publish-")){let t=e.replace("social-publish-","");return await et(t)}if(e.startsWith("social-boost-")){let t=e.replace("social-boost-","");return await ed(t)}if("social-kickstart"===e)return await z();if("social-find-replies"===e)return await eh();if("social-engagement-report"===e)return await ep();if("social-track-metrics"===e)return await en();if(e.startsWith("social-score-")){let t=e.replace("social-score-","");return await eo(t)}if("social-check-status"===e)return await eg();return{success:!1,output:`Unknown social task: ${e}`}}catch(t){let e=t instanceof Error?t.message:String(t);return{success:!1,output:`Social task failed: ${e}`}}}function Y(){let e=F(),t=e.drafts.filter(e=>"draft"===e.status).length,s=U(e),r=[];for(let t of e.drafts)t.engagement_history&&t.engagement_history.length>0&&r.push(t.engagement_history[t.engagement_history.length-1]);let i=null,a=null,n=null;if(r.length>0){i=r.reduce((e,t)=>e+t.engagement_rate,0)/r.length;let e=r.reduce((e,t)=>e.engagement_rate>t.engagement_rate?e:t);a=e.tweet_id,n=e.engagement_rate}let o=e.drafts.filter(e=>e.is_thread&&"published"===e.status).length,l=new Date().toISOString().split("T")[0],u=e.drafts.filter(e=>"draft"===e.status&&e.scheduled_date&&e.scheduled_date>=l).length,d=e.drafts.filter(e=>"draft"===e.status&&e.scheduled_date).map(e=>e.scheduled_date).sort(),c=d.length>0?d[0]:null,h=e.drafts.filter(e=>"draft"===e.status&&e.scheduled_date&&e.scheduled_date<l).length,p=e.drafts.filter(e=>"published"===e.status&&e.tweet_id&&!e.self_reply_id).map(e=>e.id),m=e.last_find_replies_at??null,g=e.last_engagement_report_at??null,_=e.kickstart_completed??!1;return{configured:e.credentials_valid,credentials_valid:e.credentials_valid,username:e.username,draft_count:t,post_streak_days:s,total_posts:e.metrics.total_posts,last_post_date:e.metrics.last_post_date,avg_engagement_rate:i,best_tweet_id:a,best_engagement_rate:n,thread_count:o,scheduled_draft_count:u,next_scheduled_date:c,overdue_scheduled_count:h,published_without_boost:p,last_find_replies_at:m,last_engagement_report_at:g,kickstart_completed:_}}function J(){let e="";try{if(r.existsSync(n.Ug)){let t=JSON.parse(r.readFileSync(n.Ug,"utf-8")),s=t.current?.tagline??"",i=t.current?.value_proposition??"",a=t.current?.target_audience?.primary,o="string"==typeof a?a:"object"==typeof a&&null!==a?a.description??"":"";e=[s,i,o].filter(Boolean).join(" | ")}}catch(t){let e=t instanceof Error?t.message:String(t);console.warn(`[social-kickstart] Could not read positioning.json: ${e}`)}let t="";try{if(r.existsSync(n.wE)){let{goals:e}=JSON.parse(r.readFileSync(n.wE,"utf-8")),s=e.find(e=>e.title?.toLowerCase().includes("build in public")||"acquisition"===e.category);s&&(t=`${s.title} — target: ${s.target_value} ${s.target_unit??""}`.trim())}}catch(t){let e=t instanceof Error?t.message:String(t);console.warn(`[social-kickstart] Could not read goals.json: ${e}`)}let s="",i=0,a=0;try{if(r.existsSync(n.pF)){let{ideas:e}=JSON.parse(r.readFileSync(n.pF,"utf-8"));i=e.length;let t=e.filter(e=>"shipped"===e.stage).sort((e,t)=>t.updated_at.localeCompare(e.updated_at));a=t.length;let o=t.slice(0,3).map(e=>e.title);o.length>0&&(s=`Last shipped: ${o.join(", ")}`)}}catch(t){let e=t instanceof Error?t.message:String(t);console.warn(`[social-kickstart] Could not read ideas.json: ${e}`)}return{positioningContext:e,goalsContext:t,ideasContext:s,followerCount:F().metrics.followers_count??335,totalIdeas:i,shippedIdeas:a}}async function z(){try{console.log("[social-kickstart] Starting kickstart — generating Day 0 thread + 6 daily tweets");let e=F();if(!0===e.kickstart_completed)return{success:!1,output:"Kickstart already completed."};if(e.metrics.total_posts>0)return{success:!1,output:"Account already has posts — kickstart is for cold-start only."};if(!e.credentials_valid)return{success:!1,output:"X credentials not configured. Run social-setup-x first."};let t=J(),s=null;try{r.existsSync(n.Ug)&&(s=JSON.parse(r.readFileSync(n.Ug,"utf-8")))}catch{}let i=["Product: VibeBusiness",t.positioningContext?`Positioning: ${t.positioningContext}`:"",`Followers: ${t.followerCount}`,`Total ideas generated: ${t.totalIdeas}`,`Shipped ideas: ${t.shippedIdeas}`,"Premise: autonomous AI product manager that dogfoods itself"].filter(Boolean).join(". "),o=await I({topic:"founding story",context:i,threadLength:7,positioning:s});if(!o.tweets||0===o.tweets.length)return{success:!1,output:"Kickstart failed: AI failed to generate founding thread."};console.log(`[social-kickstart] Generated Day 0 thread: ${o.tweets.length} tweets`);let l=[{topic:"ship",context:`First thing we shipped — describe the heartbeat system. ${t.positioningContext}`},{topic:"insight",context:`Key metric or learning from building VibeBusiness. Total ideas: ${t.totalIdeas}. Shipped: ${t.shippedIdeas}. Followers: ${t.followerCount}.`},{topic:"ship",context:`Technical decision — why we chose JSON storage over a database. ${t.positioningContext}`},{topic:"insight",context:`Failure or lesson learned building an AI product manager. ${t.ideasContext}`},{topic:"question",context:`Community question — ask indie hackers about their prioritization. ${t.positioningContext}`},{topic:"update",context:`Week 1 recap — what was accomplished. Shipped ${t.shippedIdeas} ideas. ${t.ideasContext}`}],u=[];for(let e of l){let t=await P({topic:e.topic,context:e.context,positioning:s});u.push(t.text)}let d=new Date().toISOString().split("T")[0],c=[],h={id:`draft-${(0,a.Z)().slice(0,8)}`,text:o.tweets[0],source:"thread",source_ref:"kickstart-day-0",status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,is_thread:!0,thread_tweets:o.tweets,scheduled_date:d};e.drafts.push(h),console.log(`[social-kickstart] Created draft: ${h.id} scheduled for ${d}`),c.push(` Day 0 (thread, ${o.tweets.length} tweets): ${h.id} — ${d}`);for(let t=1;t<=6;t++){let s=l[t-1],r="insight"===s.topic||"question"===s.topic?"insight":s.topic,i=new Date(Date.now()+864e5*t).toISOString().split("T")[0],n={id:`draft-${(0,a.Z)().slice(0,8)}`,text:u[t-1],source:r,source_ref:`kickstart-day-${t}`,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,scheduled_date:i};e.drafts.push(n),console.log(`[social-kickstart] Created draft: ${n.id} scheduled for ${i}`),c.push(` Day ${t}: ${n.id} — ${i}`)}return e.kickstart_completed=!0,e.kickstart_completed_at=new Date().toISOString(),M(e),console.log("[social-kickstart] Complete — 7 drafts created"),{success:!0,output:["Kickstart complete! 7 drafts created:",...c,"","Review and schedule at: vibebusiness start → /social"].join("\n")}}catch(t){let e=t instanceof Error?t.message:String(t);return console.error("[social-kickstart] Failed:",e),{success:!1,output:`Kickstart failed: ${e}`}}}async function G(){let e=o();if(!e)return{success:!1,output:'X API credentials not found. Add these to your .env file:\n X_API_KEY=your_consumer_api_key\n X_API_SECRET=your_consumer_api_secret\n X_ACCESS_TOKEN=your_access_token\n X_ACCESS_SECRET=your_access_token_secret\n\nGet these at https://developer.x.com/en/portal/dashboard\nCreate a project with "Read and Write" permissions.'};let t=l(e),s=await u(t),r=F();return(r.credentials_valid=s.valid,r.username=s.username,null!=s.followersCount&&(r.metrics.followers_count=s.followersCount),M(r),s.valid)?{success:!0,output:`Connected to X as ${s.username} (${s.followersCount??0} followers)`}:{success:!1,output:"X API credentials are invalid. Check your keys at https://developer.x.com"}}async function X(){let e,t,s;let i=F(),a=[];try{let{ideas:e}=JSON.parse(r.readFileSync(n.pF,"utf-8"));a=e}catch{return{success:!1,output:"Could not read ideas.json."}}let o=a.filter(e=>"shipped"===e.stage).sort((e,t)=>t.updated_at.localeCompare(e.updated_at))[0];if(!o)return{success:!1,output:"No shipped ideas found to generate a tweet from."};if(B(i,o.id))return{success:!1,output:`Draft already exists for shipped idea ${o.id}`};try{let a=function(e){let t=[`Title: ${e.title}`];if(e.context){let s=e.context.split(/[.!]/)[0]?.trim();s&&t.push(`Background: ${s}`)}if(e.rationale){let s=e.rationale.split(/[.!]/)[0]?.trim();s&&t.push(`Why it matters: ${s}`)}return e.summary&&t.push(`What was shipped: ${e.summary}`),e.success_metrics?.[0]&&t.push(`Success target: ${e.success_metrics[0]}`),e.category&&t.push(`Category: ${e.category}`),t.join("\n")}(o),l=null;try{r.existsSync(n.Ug)&&(l=JSON.parse(r.readFileSync(n.Ug,"utf-8")))}catch{}let u=em(i),d=await P({topic:"ship",context:a,positioning:l,pastPerformance:u});e=d.text,t=d.hook_type,s=d.estimated_engagement}catch{let t=(0,w.$O)();if(!t)return{success:!1,output:"No shipped ideas found to generate a tweet from."};e=t}let l=H(i,e,"ship",o.id);M(i);let u=[`Created ship draft: "${l.text}" (${l.id})`];return t&&u.push(`Hook type: ${t}`),s&&u.push(`Estimated engagement: ${s}`),{success:!0,output:u.join("\n")}}async function Q(){let e,t,s;let i=F();try{let a=null;try{r.existsSync(n.Ug)&&(a=JSON.parse(r.readFileSync(n.Ug,"utf-8")))}catch{}let o=[];if(a?.current?.tagline&&o.push(`Tagline: ${a.current.tagline}`),a?.current?.value_proposition){let e=a.current.value_proposition.split(/[.!]/)[0]?.trim();e&&o.push(`Value prop: ${e}`)}if(a?.copy_bank?.pain_points?.length){let e=a.copy_bank.pain_points.slice(0,2).map(e=>e.pain);o.push(`Pain points: ${e.join(", ")}`)}if(a?.current?.differentiators?.length&&o.push(`Differentiator: ${a.current.differentiators[0]}`),0===o.length)throw Error("No positioning context available");let l=o.join("\n"),u=em(i),d=await P({topic:"update",context:l,positioning:a,pastPerformance:u});e=d.text,t=d.hook_type,s=d.estimated_engagement}catch{let t=(0,w.cq)();if(!t)return{success:!1,output:"No positioning data found to generate update tweet."};e=t}let a=H(i,e,"update",null);M(i);let o=[`Created update draft: "${a.text}" (${a.id})`];return t&&o.push(`Hook type: ${t}`),s&&o.push(`Estimated engagement: ${s}`),{success:!0,output:o.join("\n")}}async function Z(){let e,t,s;let i=F();try{let a="";try{if(r.existsSync(n.wE)){let{goals:e}=JSON.parse(r.readFileSync(n.wE,"utf-8"));for(let t of e){for(let e of t.kpis)if(null!=e.current_value&&null!=e.target_value&&e.current_value/e.target_value>=.8){a=`KPI: ${e.name}
|
|
256
|
+
}`,a=await T({prompt:i,model:"haiku"});try{let e=JSON.parse(C(a.output));return{summary:e.summary??"",best_hook_types:e.best_hook_types??[],best_posting_times:e.best_posting_times??[],thread_vs_single:e.thread_vs_single??"",recommendations:e.recommendations??[],top_performing:e.top_performing??[]}}catch{return{summary:"Could not analyze engagement data — AI response parsing failed.",best_hook_types:[],best_posting_times:[],thread_vs_single:"",recommendations:[],top_performing:[]}}}function C(e){let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t)return t[1].trim();let s=e.match(/\{[\s\S]*\}/);return s?s[0]:e.trim()}let N={last_updated:new Date().toISOString(),platform:"x",username:null,credentials_valid:!1,drafts:[],metrics:{followers_count:null,post_streak_days:0,total_posts:0,last_post_date:null}};function F(){if(!r.existsSync(n.ET))return{...N,metrics:{...N.metrics}};try{return JSON.parse(r.readFileSync(n.ET,"utf-8"))}catch{return{...N,metrics:{...N.metrics}}}}function M(e){e.last_updated=new Date().toISOString();let t=i.dirname(n.ET);r.existsSync(t)||r.mkdirSync(t,{recursive:!0}),r.writeFileSync(n.ET,JSON.stringify(e,null,2)+"\n")}function U(e){let t=e.drafts.filter(e=>"published"===e.status&&e.published_at).map(e=>e.published_at.split("T")[0]).sort().reverse();if(0===t.length)return 0;let s=Array.from(new Set(t)),r=new Date().toISOString().split("T")[0];if(s[0]!==r){let e=new Date(Date.now()-864e5).toISOString().split("T")[0];if(s[0]!==e)return 0}let i=1;for(let e=1;e<s.length;e++){let t=new Date(s[e-1]),r=new Date(s[e]);if(1===Math.round((t.getTime()-r.getTime())/864e5))i++;else break}return i}function B(e,t){return e.drafts.some(e=>e.source_ref===t&&("draft"===e.status||"published"===e.status))}function H(e,t,s,r,i=null){let n={id:`draft-${(0,a.Z)().slice(0,8)}`,text:t,source:s,source_ref:r,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,media_paths:i};return e.drafts.push(n),n}let V=["social-setup-x","social-plan-week","social-draft-ship-visual","social-draft-ship","social-draft-update","social-draft-milestone","social-draft-digest","social-draft-viral-","social-draft-thread-","social-publish-","social-boost-","social-find-replies","social-engagement-report","social-track-metrics","social-score-","social-check-status","social-kickstart"];function W(e){return V.some(t=>e.startsWith(t))}async function K(e,t,s){try{if("social-setup-x"===e)return await G();if("social-plan-week"===e)return await ei();if("social-draft-ship-visual"===e)return function(){let e=F(),t=(0,w.$O)();if(!t)return{success:!1,output:"No shipped ideas found to generate a tweet from."};let{ideas:s}=JSON.parse(r.readFileSync(i.join(i.dirname(n.ET),"ideas.json"),"utf-8")),a=s.filter(e=>"shipped"===e.stage).sort((e,t)=>t.updated_at.localeCompare(e.updated_at))[0];if(a&&B(e,a.id))return{success:!1,output:`Draft already exists for shipped idea ${a.id}`};let o=[];if(a){let e=i.join(n.QN,"reports","visuals",`${a.id}-card.png`);r.existsSync(e)&&o.push(e);let t=i.join(n.QN,"videos",`${a.id}-ship.mp4`);r.existsSync(t)&&(o.length=0,o.push(t))}if(0===o.length)return{success:!1,output:`No ship card or video found for idea ${a?.id||"unknown"}. Run generate-visual-{ideaId} first.`};let l=H(e,t,"ship",a?.id||null,o);return M(e),{success:!0,output:`Created ship draft with media: "${l.text}" (${l.id}) — ${o.length} file(s) attached`}}();if("social-draft-ship"===e)return await X();if("social-draft-update"===e)return await Q();if("social-draft-milestone"===e)return await Z();if("social-draft-digest"===e)return await ee();if(e.startsWith("social-draft-viral-")){let s=e.replace("social-draft-viral-","");return await es(s,t)}if(e.startsWith("social-draft-thread-")){let s=e.replace("social-draft-thread-","");return await er(s,t)}if(e.startsWith("social-publish-")){let t=e.replace("social-publish-","");return await et(t)}if(e.startsWith("social-boost-")){let t=e.replace("social-boost-","");return await ed(t)}if("social-kickstart"===e)return await z();if("social-find-replies"===e)return await eh();if("social-engagement-report"===e)return await ep();if("social-track-metrics"===e)return await en();if(e.startsWith("social-score-")){let t=e.replace("social-score-","");return await eo(t)}if("social-check-status"===e)return await eg();return{success:!1,output:`Unknown social task: ${e}`}}catch(t){let e=t instanceof Error?t.message:String(t);return{success:!1,output:`Social task failed: ${e}`}}}function Y(){let e=F(),t=e.drafts.filter(e=>"draft"===e.status).length,s=U(e),r=[];for(let t of e.drafts)t.engagement_history&&t.engagement_history.length>0&&r.push(t.engagement_history[t.engagement_history.length-1]);let i=null,a=null,n=null;if(r.length>0){i=r.reduce((e,t)=>e+t.engagement_rate,0)/r.length;let e=r.reduce((e,t)=>e.engagement_rate>t.engagement_rate?e:t);a=e.tweet_id,n=e.engagement_rate}let o=e.drafts.filter(e=>e.is_thread&&"published"===e.status).length,l=new Date().toISOString().split("T")[0],u=e.drafts.filter(e=>"draft"===e.status&&e.scheduled_date&&e.scheduled_date>=l).length,d=e.drafts.filter(e=>"draft"===e.status&&e.scheduled_date).map(e=>e.scheduled_date).sort(),c=d.length>0?d[0]:null,h=e.drafts.filter(e=>"draft"===e.status&&e.scheduled_date&&e.scheduled_date<l).length,p=e.drafts.filter(e=>"published"===e.status&&e.tweet_id&&!e.self_reply_id).map(e=>e.id),m=e.last_find_replies_at??null,g=e.last_engagement_report_at??null,_=e.kickstart_completed??!1;return{configured:e.credentials_valid,credentials_valid:e.credentials_valid,username:e.username,draft_count:t,post_streak_days:s,total_posts:e.metrics.total_posts,last_post_date:e.metrics.last_post_date,avg_engagement_rate:i,best_tweet_id:a,best_engagement_rate:n,thread_count:o,scheduled_draft_count:u,next_scheduled_date:c,overdue_scheduled_count:h,published_without_boost:p,last_find_replies_at:m,last_engagement_report_at:g,kickstart_completed:_}}function J(){let e="";try{if(r.existsSync(n.Ug)){let t=JSON.parse(r.readFileSync(n.Ug,"utf-8")),s=t.current?.tagline??"",i=t.current?.value_proposition??"",a=t.current?.target_audience?.primary,o="string"==typeof a?a:"object"==typeof a&&null!==a?a.description??"":"";e=[s,i,o].filter(Boolean).join(" | ")}}catch(t){let e=t instanceof Error?t.message:String(t);console.warn(`[social-kickstart] Could not read positioning.json: ${e}`)}let t="";try{if(r.existsSync(n.wE)){let{goals:e}=JSON.parse(r.readFileSync(n.wE,"utf-8")),s=e.find(e=>e.title?.toLowerCase().includes("build in public")||"acquisition"===e.category);s&&(t=`${s.title} — target: ${s.target_value} ${s.target_unit??""}`.trim())}}catch(t){let e=t instanceof Error?t.message:String(t);console.warn(`[social-kickstart] Could not read goals.json: ${e}`)}let s="",i=0,a=0;try{if(r.existsSync(n.pF)){let{ideas:e}=JSON.parse(r.readFileSync(n.pF,"utf-8"));i=e.length;let t=e.filter(e=>"shipped"===e.stage).sort((e,t)=>t.updated_at.localeCompare(e.updated_at));a=t.length;let o=t.slice(0,3).map(e=>e.title);o.length>0&&(s=`Last shipped: ${o.join(", ")}`)}}catch(t){let e=t instanceof Error?t.message:String(t);console.warn(`[social-kickstart] Could not read ideas.json: ${e}`)}return{positioningContext:e,goalsContext:t,ideasContext:s,followerCount:F().metrics.followers_count??335,totalIdeas:i,shippedIdeas:a}}async function z(){try{console.log("[social-kickstart] Starting kickstart — generating Day 0 thread + 6 daily tweets");let e=F();if(!0===e.kickstart_completed)return{success:!1,output:"Kickstart already completed."};if(e.metrics.total_posts>0)return{success:!1,output:"Account already has posts — kickstart is for cold-start only."};if(!e.credentials_valid)return{success:!1,output:"X credentials not configured. Run social-setup-x first."};let t=J(),s=null;try{r.existsSync(n.Ug)&&(s=JSON.parse(r.readFileSync(n.Ug,"utf-8")))}catch{}let i=["Product: VibeBusiness",t.positioningContext?`Positioning: ${t.positioningContext}`:"",`Followers: ${t.followerCount}`,`Total ideas generated: ${t.totalIdeas}`,`Shipped ideas: ${t.shippedIdeas}`,"Premise: autonomous AI product manager that dogfoods itself"].filter(Boolean).join(". "),o=await I({topic:"founding story",context:i,threadLength:7,positioning:s});if(!o.tweets||0===o.tweets.length)return{success:!1,output:"Kickstart failed: AI failed to generate founding thread."};console.log(`[social-kickstart] Generated Day 0 thread: ${o.tweets.length} tweets`);let l=[{topic:"ship",context:`First thing we shipped — describe the heartbeat system. ${t.positioningContext}`},{topic:"insight",context:`Key metric or learning from building VibeBusiness. Total ideas: ${t.totalIdeas}. Shipped: ${t.shippedIdeas}. Followers: ${t.followerCount}.`},{topic:"ship",context:`Technical decision — why we chose JSON storage over a database. ${t.positioningContext}`},{topic:"insight",context:`Failure or lesson learned building an AI product manager. ${t.ideasContext}`},{topic:"question",context:`Community question — ask indie hackers about their prioritization. ${t.positioningContext}`},{topic:"update",context:`Week 1 recap — what was accomplished. Shipped ${t.shippedIdeas} ideas. ${t.ideasContext}`}],u=[];for(let e of l){let t=await A({topic:e.topic,context:e.context,positioning:s});u.push(t.text)}let d=new Date().toISOString().split("T")[0],c=[],h={id:`draft-${(0,a.Z)().slice(0,8)}`,text:o.tweets[0],source:"thread",source_ref:"kickstart-day-0",status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,is_thread:!0,thread_tweets:o.tweets,scheduled_date:d};e.drafts.push(h),console.log(`[social-kickstart] Created draft: ${h.id} scheduled for ${d}`),c.push(` Day 0 (thread, ${o.tweets.length} tweets): ${h.id} — ${d}`);for(let t=1;t<=6;t++){let s=l[t-1],r="insight"===s.topic||"question"===s.topic?"insight":s.topic,i=new Date(Date.now()+864e5*t).toISOString().split("T")[0],n={id:`draft-${(0,a.Z)().slice(0,8)}`,text:u[t-1],source:r,source_ref:`kickstart-day-${t}`,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,scheduled_date:i};e.drafts.push(n),console.log(`[social-kickstart] Created draft: ${n.id} scheduled for ${i}`),c.push(` Day ${t}: ${n.id} — ${i}`)}return e.kickstart_completed=!0,e.kickstart_completed_at=new Date().toISOString(),M(e),console.log("[social-kickstart] Complete — 7 drafts created"),{success:!0,output:["Kickstart complete! 7 drafts created:",...c,"","Review and schedule at: vibebusiness start → /social"].join("\n")}}catch(t){let e=t instanceof Error?t.message:String(t);return console.error("[social-kickstart] Failed:",e),{success:!1,output:`Kickstart failed: ${e}`}}}async function G(){let e=o();if(!e)return{success:!1,output:'X API credentials not found. Add these to your .env file:\n X_API_KEY=your_consumer_api_key\n X_API_SECRET=your_consumer_api_secret\n X_ACCESS_TOKEN=your_access_token\n X_ACCESS_SECRET=your_access_token_secret\n\nGet these at https://developer.x.com/en/portal/dashboard\nCreate a project with "Read and Write" permissions.'};let t=l(e),s=await u(t),r=F();return(r.credentials_valid=s.valid,r.username=s.username,null!=s.followersCount&&(r.metrics.followers_count=s.followersCount),M(r),s.valid)?{success:!0,output:`Connected to X as ${s.username} (${s.followersCount??0} followers)`}:{success:!1,output:"X API credentials are invalid. Check your keys at https://developer.x.com"}}async function X(){let e,t,s;let i=F(),a=[];try{let{ideas:e}=JSON.parse(r.readFileSync(n.pF,"utf-8"));a=e}catch{return{success:!1,output:"Could not read ideas.json."}}let o=a.filter(e=>"shipped"===e.stage).sort((e,t)=>t.updated_at.localeCompare(e.updated_at))[0];if(!o)return{success:!1,output:"No shipped ideas found to generate a tweet from."};if(B(i,o.id))return{success:!1,output:`Draft already exists for shipped idea ${o.id}`};try{let a=function(e){let t=[`Title: ${e.title}`];if(e.context){let s=e.context.split(/[.!]/)[0]?.trim();s&&t.push(`Background: ${s}`)}if(e.rationale){let s=e.rationale.split(/[.!]/)[0]?.trim();s&&t.push(`Why it matters: ${s}`)}return e.summary&&t.push(`What was shipped: ${e.summary}`),e.success_metrics?.[0]&&t.push(`Success target: ${e.success_metrics[0]}`),e.category&&t.push(`Category: ${e.category}`),t.join("\n")}(o),l=null;try{r.existsSync(n.Ug)&&(l=JSON.parse(r.readFileSync(n.Ug,"utf-8")))}catch{}let u=em(i),d=await A({topic:"ship",context:a,positioning:l,pastPerformance:u});e=d.text,t=d.hook_type,s=d.estimated_engagement}catch{let t=(0,w.$O)();if(!t)return{success:!1,output:"No shipped ideas found to generate a tweet from."};e=t}let l=H(i,e,"ship",o.id);M(i);let u=[`Created ship draft: "${l.text}" (${l.id})`];return t&&u.push(`Hook type: ${t}`),s&&u.push(`Estimated engagement: ${s}`),{success:!0,output:u.join("\n")}}async function Q(){let e,t,s;let i=F();try{let a=null;try{r.existsSync(n.Ug)&&(a=JSON.parse(r.readFileSync(n.Ug,"utf-8")))}catch{}let o=[];if(a?.current?.tagline&&o.push(`Tagline: ${a.current.tagline}`),a?.current?.value_proposition){let e=a.current.value_proposition.split(/[.!]/)[0]?.trim();e&&o.push(`Value prop: ${e}`)}if(a?.copy_bank?.pain_points?.length){let e=a.copy_bank.pain_points.slice(0,2).map(e=>e.pain);o.push(`Pain points: ${e.join(", ")}`)}if(a?.current?.differentiators?.length&&o.push(`Differentiator: ${a.current.differentiators[0]}`),0===o.length)throw Error("No positioning context available");let l=o.join("\n"),u=em(i),d=await A({topic:"update",context:l,positioning:a,pastPerformance:u});e=d.text,t=d.hook_type,s=d.estimated_engagement}catch{let t=(0,w.cq)();if(!t)return{success:!1,output:"No positioning data found to generate update tweet."};e=t}let a=H(i,e,"update",null);M(i);let o=[`Created update draft: "${a.text}" (${a.id})`];return t&&o.push(`Hook type: ${t}`),s&&o.push(`Estimated engagement: ${s}`),{success:!0,output:o.join("\n")}}async function Z(){let e,t,s;let i=F();try{let a="";try{if(r.existsSync(n.wE)){let{goals:e}=JSON.parse(r.readFileSync(n.wE,"utf-8"));for(let t of e){for(let e of t.kpis)if(null!=e.current_value&&null!=e.target_value&&e.current_value/e.target_value>=.8){a=`KPI: ${e.name}
|
|
257
257
|
Current: ${e.current_value} ${e.unit}
|
|
258
258
|
Target: ${e.target_value} ${e.unit}
|
|
259
|
-
Goal: ${t.title}`;break}if(a)break}}}catch{}if(!a)throw Error("No milestone KPI context available");let o=em(i),l=await
|
|
259
|
+
Goal: ${t.title}`;break}if(a)break}}}catch{}if(!a)throw Error("No milestone KPI context available");let o=em(i),l=await A({topic:"milestone",context:a,pastPerformance:o});e=l.text,t=l.hook_type,s=l.estimated_engagement}catch{let t=(0,w.Fb)();if(!t)return{success:!1,output:"No KPI milestones found to celebrate."};e=t}let a=H(i,e,"milestone",null);M(i);let o=[`Created milestone draft: "${a.text}" (${a.id})`];return t&&o.push(`Hook type: ${t}`),s&&o.push(`Estimated engagement: ${s}`),{success:!0,output:o.join("\n")}}async function ee(){let e,t,s;let i=F();try{let a=new Date(Date.now()-6048e5).toISOString(),o=[],l="";try{if(r.existsSync(n.pF)){let{ideas:e}=JSON.parse(r.readFileSync(n.pF,"utf-8"));o=e.filter(e=>"shipped"===e.stage&&e.updated_at>a).sort((e,t)=>t.updated_at.localeCompare(e.updated_at)).slice(0,5).map(e=>({title:e.title,category:e.category}))}}catch{}try{if(r.existsSync(n.wE)){let{goals:e}=JSON.parse(r.readFileSync(n.wE,"utf-8")),t=[];for(let s of e)for(let e of s.kpis)if(null!=e.current_value&&null!=e.target_value){let s=Math.round(e.current_value/e.target_value*100);t.push(`${e.name}: ${e.current_value}/${e.target_value} ${e.unit} (${s}%)`)}t.length>0&&(l=t.slice(0,3).join(", "))}}catch{}if(0===o.length)throw Error("No recent ships for digest context");let u=[`Shipped this week (${o.length} items): ${o.map(e=>e.title).join(", ")}`,`Categories: ${Array.from(new Set(o.map(e=>e.category))).join(", ")}`];l&&u.push(`KPI movement: ${l}`);let d=u.join("\n"),c=em(i),h=await A({topic:"update",context:d,pastPerformance:c});e=h.text,t=h.hook_type,s=h.estimated_engagement}catch{let t=(0,w.gJ)();if(!t)return{success:!1,output:"No recent activity to summarize in a digest."};e=t}let a=H(i,e,"digest",null);M(i);let o=[`Created digest draft: "${a.text}" (${a.id})`];return t&&o.push(`Hook type: ${t}`),s&&o.push(`Estimated engagement: ${s}`),{success:!0,output:o.join("\n")}}async function et(e){let t;let s=F(),i=s.drafts.find(t=>t.id===e);if(!i)return{success:!1,output:`Draft not found: ${e}`};if("draft"!==i.status)return{success:!1,output:`Draft ${e} is already ${i.status}`};let a=o();if(!a)return{success:!1,output:"X API credentials not configured. Run social-setup-x first."};let n=l(a);if(i.is_thread&&i.thread_tweets&&i.thread_tweets.length>0){let e=await f(n,i.thread_tweets);i.status="published",i.published_at=new Date().toISOString(),i.tweet_id=e[0].id,i.tweet_url=e[0].url,i.thread_tweet_ids=e.map(e=>e.id),s.metrics.total_posts++,s.metrics.last_post_date=new Date().toISOString().split("T")[0],s.metrics.post_streak_days=U(s);let t=e[e.length-1].id,r=i.thread_tweets[i.thread_tweets.length-1],a=await el(n,t,r,!0);a&&(i.self_reply_id=a.id),M(s),e_(s);let o=[`Published thread (${e.length} tweets): ${e[0].url}`];return a&&o.push(`Self-reply posted for +75x algorithm boost: ${a.url}`),o.push(...eu()),{success:!0,output:o.join("\n")}}if(i.media_paths&&i.media_paths.length>0){let e=i.media_paths.filter(e=>r.existsSync(e));if(e.length>0){let s=[];for(let t of e){let e=await c(n,t);s.push(e)}t=await h(n,i.text,s)}else t=await d(n,i.text)}else t=await d(n,i.text);i.status="published",i.published_at=new Date().toISOString(),i.tweet_id=t.id,i.tweet_url=t.url,s.metrics.total_posts++,s.metrics.last_post_date=new Date().toISOString().split("T")[0],s.metrics.post_streak_days=U(s);let u=await el(n,t.id,i.text,!1);u&&(i.self_reply_id=u.id),M(s),e_(s);let p=[`Published tweet: ${t.url}`];return u&&p.push(`Self-reply posted for +75x algorithm boost: ${u.url}`),p.push(...eu()),{success:!0,output:p.join("\n")}}async function es(e,t){let s=F(),r=em(s),i=await A({topic:e,context:t||`A ${e} tweet about our product`,pastPerformance:r}),a=H(s,i.text,"insight"===e||"question"===e?"insight":e,null);return M(s),{success:!0,output:`Created AI-generated ${e} draft: "${a.text}" (${a.id})
|
|
260
260
|
Hook type: ${i.hook_type}
|
|
261
261
|
Estimated engagement: ${i.estimated_engagement}`}}async function er(e,t){let s=F(),r=em(s),i=await I({topic:e,context:t||`A thread about ${e}`,threadLength:5,pastPerformance:r});if(!i.tweets||0===i.tweets.length)return{success:!1,output:"AI failed to generate thread content."};let n={id:`draft-${(0,a.Z)().slice(0,8)}`,text:i.tweets[0],source:"thread",source_ref:null,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,is_thread:!0,thread_tweets:i.tweets};return s.drafts.push(n),M(s),{success:!0,output:[`Created thread draft (${i.tweets.length} tweets): ${n.id}`,`Hook type: ${i.hook_type}`,"Preview:",...i.tweets.map((e,t)=>` ${t+1}. "${e.slice(0,60)}${e.length>60?"...":""}"`)].join("\n")}}async function ei(){let e=F(),t=em(e),s=null;try{r.existsSync(n.Ug)&&(s=JSON.parse(r.readFileSync(n.Ug,"utf-8")))}catch{}let i="";try{if(r.existsSync(n.wE)){let{goals:e}=JSON.parse(r.readFileSync(n.wE,"utf-8")),t=e.filter(e=>"on_track"===e.status||"at_risk"===e.status||"behind"===e.status).map(e=>{let t=null!=e.current_value&&e.target_value?`${Math.round(e.current_value/e.target_value*100)}%`:"unknown";return`- ${e.title} (${e.status}, ${t} complete, deadline: ${e.deadline})`});i=t.length>0?t.join("\n"):"No active goals."}}catch{}let o="";try{if(r.existsSync(n.pF)){let{ideas:e}=JSON.parse(r.readFileSync(n.pF,"utf-8")),t=new Date(Date.now()-12096e5).toISOString(),s=e.filter(e=>"shipped"===e.stage&&e.updated_at>t).map(e=>`- ${e.title} (shipped ${e.updated_at.split("T")[0]})`);o=s.length>0?s.join("\n"):"No recent ships."}}catch{}let l="";try{if(r.existsSync(n.wE)){let{goals:e}=JSON.parse(r.readFileSync(n.wE,"utf-8")),t=[];for(let s of e)for(let e of s.kpis)if(null!=e.current_value&&null!=e.target_value){let s=Math.round(e.current_value/e.target_value*100);t.push(`- ${e.name}: ${e.current_value}/${e.target_value} ${e.unit} (${s}%)`)}l=t.length>0?t.join("\n"):"No KPI data."}}catch{}let u=await $({positioning:s,pastPerformance:t,goalsContext:i,recentShips:o,kpiHighlights:l});if(0===u.days.length)return{success:!1,output:"AI failed to generate a weekly content plan."};let d=[];for(let t of u.days)if("rest"!==t.type&&t.content){if("thread"===t.type&&t.thread_tweets&&t.thread_tweets.length>0){let s={id:`draft-${(0,a.Z)().slice(0,8)}`,text:t.thread_tweets[0],source:"thread",source_ref:null,status:"draft",created_at:new Date().toISOString(),published_at:null,tweet_id:null,tweet_url:null,is_thread:!0,thread_tweets:t.thread_tweets,scheduled_date:t.date};e.drafts.push(s),d.push({day:t.day,date:t.date,type:"thread",id:s.id})}else{let s=["ship","milestone","update","digest","insight"].includes(t.topic)?t.topic:"insight",r=H(e,t.content,s,null);r.scheduled_date=t.date,d.push({day:t.day,date:t.date,type:t.type,id:r.id})}}M(e);let c=u.days.find(e=>"monday"===e.day)?.date??"",h=u.days.find(e=>"sunday"===e.day)?.date??"",p=c&&h?`${ea(c)} - ${ea(h)}`:"This Week",m=[`Weekly Content Plan (${p})`,""];for(let e of u.days){let t=e.day.charAt(0).toUpperCase()+e.day.slice(1,3);if("rest"===e.type)m.push(`${t} -- Rest`);else{let s="thread"===e.type&&e.thread_tweets?` (${e.thread_tweets.length} tweets)`:"",r=e.content.length>60?`"${e.content.slice(0,57)}..."`:`"${e.content}"`;m.push(`${t} [${e.type}] ${r}${s}`),m.push(` Hook: ${e.hook_type} | ${e.rationale}`)}}return m.push(""),m.push(`${d.length} drafts created. Review and edit at: vibebusiness start -> /social`),{success:!0,output:m.join("\n")}}function ea(e){let t=new Date(e+"T00:00:00");return`${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()]} ${t.getDate()}`}async function en(){let e=F(),t=o();if(!t)return{success:!1,output:"X API credentials not configured. Run social-setup-x first."};let s=l(t),r=new Date(Date.now()-6048e5).toISOString(),i=e.drafts.filter(e=>"published"===e.status&&e.published_at&&e.published_at>r&&e.tweet_id);if(0===i.length)return{success:!0,output:"No published tweets in the last 7 days to track."};let a=[];for(let e of i)e.thread_tweet_ids&&e.thread_tweet_ids.length>0?a.push(...e.thread_tweet_ids):e.tweet_id&&a.push(e.tweet_id);let n=await m(s,a);if(0===n.length)return{success:!0,output:"Could not fetch metrics (API may require elevated access)."};for(let e of i)if(e.engagement_history||(e.engagement_history=[]),e.thread_tweet_ids&&e.thread_tweet_ids.length>0){let t=n.filter(t=>e.thread_tweet_ids.includes(t.tweet_id));if(t.length>0){let s={tweet_id:e.tweet_id,impressions:t.reduce((e,t)=>e+t.impressions,0),likes:t.reduce((e,t)=>e+t.likes,0),retweets:t.reduce((e,t)=>e+t.retweets,0),replies:t.reduce((e,t)=>e+t.replies,0),bookmarks:t.reduce((e,t)=>e+t.bookmarks,0),profile_clicks:t.reduce((e,t)=>e+t.profile_clicks,0),engagements:t.reduce((e,t)=>e+t.engagements,0),engagement_rate:0,fetched_at:new Date().toISOString()};s.engagement_rate=s.impressions>0?s.engagements/s.impressions:0,e.engagement_history.push(s)}}else{let t=n.find(t=>t.tweet_id===e.tweet_id);t&&e.engagement_history.push(t)}M(e);let u=[`Tracked metrics for ${n.length} tweet(s):`];for(let e of n)u.push(` ${e.tweet_id}: ${e.impressions} impressions, ${e.likes} likes, ${e.bookmarks} bookmarks, ${(100*e.engagement_rate).toFixed(2)}% rate`);return{success:!0,output:u.join("\n")}}async function eo(e){let t=F(),s=t.drafts.find(t=>t.id===e);if(!s)return{success:!1,output:`Draft not found: ${e}`};let r=s.is_thread&&s.thread_tweets?s.thread_tweets.join("\n\n---\n\n"):s.text,i=em(t),a=await L(r,i);return{success:!0,output:[`Draft Score: ${a.score}/100`,"","Feedback:",...a.feedback.map(e=>` - ${e}`),"",`Optimized version: "${a.optimized_version}"`].join("\n")}}async function el(e,t,s,r){try{let i=await O({originalTweet:s,isThread:r});return await g(e,i.text,t)}catch(e){return console.error("Auto self-reply failed (non-blocking):",e),null}}function eu(){return["","Tweet is live! For maximum reach:"," -> Reply to comments in the next 30 minutes"," -> Post this to the Build in Public community: https://x.com/i/communities/1498648389716148224"," -> Engage with 5-10 tweets in your niche right now (run: social-find-replies)"]}async function ed(e){let t=F(),s=t.drafts.find(t=>t.id===e);if(!s)return{success:!1,output:`Draft not found: ${e}`};if("published"!==s.status)return{success:!1,output:`Draft ${e} is not published (status: ${s.status})`};if(!s.tweet_id)return{success:!1,output:`Draft ${e} has no tweet ID`};if(s.self_reply_id)return{success:!1,output:`Draft ${e} already has a self-reply (${s.self_reply_id})`};let r=o();if(!r)return{success:!1,output:"X API credentials not configured. Run social-setup-x first."};let i=l(r),a=s.is_thread&&s.thread_tweet_ids?.length?s.thread_tweet_ids[s.thread_tweet_ids.length-1]:s.tweet_id,n=s.is_thread&&s.thread_tweets?.length?s.thread_tweets[s.thread_tweets.length-1]:s.text,u=await el(i,a,n,s.is_thread??!1);return u?(s.self_reply_id=u.id,M(t),{success:!0,output:`Self-reply posted for +75x algorithm boost: ${u.url}`}):{success:!1,output:"Failed to generate or post self-reply."}}let ec=["indie hacker","build in public","AI agent","solo founder","shipping feature"];async function eh(){let e=o();if(!e)return{success:!1,output:"X API credentials not configured. Run social-setup-x first."};let t=l(e),s=F(),r=[];for(let e of ec)try{let s=`${e} -is:retweet lang:en`;for(let e of(await _(t,s,10)))e.author_followers>=1e3&&!r.some(t=>t.id===e.id)&&r.push({id:e.id,text:e.text,url:e.url,author_username:e.author_username,author_name:e.author_name,author_followers:e.author_followers,like_count:e.like_count})}catch(t){console.error(`Search failed for "${e}":`,t)}if(0===r.length)return s.last_find_replies_at=new Date().toISOString(),M(s),{success:!0,output:"No high-traffic tweets found in niche. Try again later or check API access level."};r.sort((e,t)=>t.like_count-e.like_count);let i=r.slice(0,5),a=await q({tweets:i}),n=a.map(e=>({tweet_id:e.tweet_id,tweet_text:e.tweet_text,tweet_url:e.tweet_url,author_username:e.author_username,author_name:"",author_followers:e.author_followers,like_count:e.like_count,reply_suggestions:e.suggestions,found_at:new Date().toISOString()}));s.reply_targets=n,s.last_find_replies_at=new Date().toISOString(),M(s);let u=[`Found ${a.length} high-traffic tweets in your niche:
|
|
262
262
|
`];for(let e of a){for(let t of(u.push(`@${e.author_username} (${e.author_followers.toLocaleString()} followers) — ${e.like_count} likes`),u.push(`"${e.tweet_text.slice(0,100)}${e.tweet_text.length>100?"...":""}"`),u.push(`${e.tweet_url}`),e.suggestions))u.push(` -> "${t}"`);u.push("")}return u.push("Copy a reply, visit the tweet, and post manually for best results."),u.push("(API-posted replies risk looking spammy — manual posting is safer)"),{success:!0,output:u.join("\n")}}async function ep(){let e=F(),t=o();if(t)try{let s=l(t),r=new Date(Date.now()-2592e6).toISOString(),i=e.drafts.filter(e=>"published"===e.status&&e.published_at&&e.published_at>r&&e.tweet_id),a=[];for(let e of i)e.thread_tweet_ids?.length?a.push(...e.thread_tweet_ids):e.tweet_id&&a.push(e.tweet_id);if(a.length>0){let t=await m(s,a);for(let e of i)if(e.engagement_history||(e.engagement_history=[]),e.thread_tweet_ids?.length){let s=t.filter(t=>e.thread_tweet_ids.includes(t.tweet_id));if(s.length>0){let t={tweet_id:e.tweet_id,impressions:s.reduce((e,t)=>e+t.impressions,0),likes:s.reduce((e,t)=>e+t.likes,0),retweets:s.reduce((e,t)=>e+t.retweets,0),replies:s.reduce((e,t)=>e+t.replies,0),bookmarks:s.reduce((e,t)=>e+t.bookmarks,0),profile_clicks:s.reduce((e,t)=>e+t.profile_clicks,0),engagements:s.reduce((e,t)=>e+t.engagements,0),engagement_rate:0,fetched_at:new Date().toISOString()};t.engagement_rate=t.impressions>0?t.engagements/t.impressions:0,e.engagement_history.push(t)}}else{let s=t.find(t=>t.tweet_id===e.tweet_id);s&&e.engagement_history.push(s)}M(e)}}catch(e){console.error("Failed to refresh metrics for report:",e)}let s=await j({drafts:e.drafts});e.last_engagement_report_at=new Date().toISOString(),M(e);let r=["Engagement Report","=".repeat(50),"",s.summary,""];if(s.best_hook_types.length>0&&r.push(`Best hook types: ${s.best_hook_types.join(", ")}`),s.best_posting_times.length>0&&r.push(`Best posting times: ${s.best_posting_times.join(", ")}`),s.thread_vs_single&&r.push(`Thread vs Single: ${s.thread_vs_single}`),s.recommendations.length>0)for(let e of(r.push(""),r.push("Recommendations:"),s.recommendations))r.push(` -> ${e}`);if(s.top_performing.length>0)for(let e of(r.push(""),r.push("Top Performing:"),s.top_performing))r.push(` ${e.tweet_id}: ${e.highlight}`);return{success:!0,output:r.join("\n")}}function em(e){let t=[];for(let s of e.drafts)s.engagement_history&&s.engagement_history.length>0&&t.push(s.engagement_history[s.engagement_history.length-1]);return t}async function eg(){let e=F(),t=Y(),s=["Social Media Status:"];if(t.configured){s.push(" Platform: X"),s.push(` Username: ${t.username}`),s.push(` Credentials: ${t.credentials_valid?"valid":"INVALID"}`);let r=o();if(r)try{let t=l(r),i=await u(t);i.valid&&null!=i.followersCount&&(e.metrics.followers_count=i.followersCount,e.credentials_valid=!0,M(e),s.push(` Followers: ${i.followersCount}`))}catch{s.push(` Followers: ${e.metrics.followers_count??"unknown"}`)}}else s.push(" Platform: X (not connected)"),s.push(" Run social-setup-x to connect.");return s.push(` Pending drafts: ${t.draft_count}`),s.push(` Scheduled drafts: ${t.scheduled_draft_count}`),s.push(` Post streak: ${t.post_streak_days} day(s)`),s.push(` Total posts: ${t.total_posts}`),s.push(` Threads published: ${t.thread_count}`),s.push(` Last post: ${t.last_post_date||"never"}`),null!=t.avg_engagement_rate&&s.push(` Avg engagement rate: ${(100*t.avg_engagement_rate).toFixed(2)}%`),t.best_tweet_id&&s.push(` Best tweet: ${t.best_tweet_id} (${((t.best_engagement_rate??0)*100).toFixed(2)}% rate)`),{success:!0,output:s.join("\n")}}function e_(e){try{if(!r.existsSync(n.wE))return;let t=JSON.parse(r.readFileSync(n.wE,"utf-8")),s=!1;for(let r of t.goals)for(let t of r.kpis){if("kpi-daily-posts"===t.id&&e.metrics.post_streak_days>0){t.current_value=e.metrics.post_streak_days;let r=new Date().toISOString().split("T")[0],i=t.history.find(e=>e.date===r);i?i.value=e.metrics.post_streak_days:t.history.push({date:r,value:e.metrics.post_streak_days}),s=!0}if("kpi-twitter-followers"===t.id&&null!=e.metrics.followers_count){t.current_value=e.metrics.followers_count;let r=new Date().toISOString().split("T")[0],i=t.history.find(e=>e.date===r);i?i.value=e.metrics.followers_count:t.history.push({date:r,value:e.metrics.followers_count}),s=!0}}s&&r.writeFileSync(n.wE,JSON.stringify(t,null,2)+"\n")}catch{}}}};
|