gemi 0.33.2 → 0.33.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -65,7 +65,7 @@ ${"".padEnd(f)}${"^".repeat(R)}`}function C6(c){return IU(b$,c)}function bc(c){i
65
65
  `).map((H)=>"> "+H).join(`
66
66
  `)})}function r$(c,f){if(!f)return c;let R=typeof f[0]==="string"?f[0]:"[",h=typeof f[1]==="string"?f[1]:"]";return R+c+h}function w3(c,f,R,h,$){let H=typeof f==="function"?f(c,h,$):c;return H[0]==="/"&&R?qY(R,"/")+H:H}function WN(c,f,R,h){let $=c.attribs||{},H=$.alt?$.alt:"",A=!$.src?"":w3($.src,h.pathRewrite,h.baseUrl,R.metadata,c),G=!A?H:!H?r$(A,h.linkBrackets):H+" "+r$(A,h.linkBrackets);R.addInline(G,{noWordTransform:!0})}function vN(c,f,R,h){function $(){if(h.ignoreHref)return"";if(!c.attribs||!c.attribs.href)return"";let A=c.attribs.href.replace(/^mailto:/,"");if(h.noAnchorUrl&&A[0]==="#")return"";return A=w3(A,h.pathRewrite,h.baseUrl,R.metadata,c),A}let H=$();if(!H)f(c.children,R);else{let A="";if(R.pushWordTransform((y)=>{if(y)A+=y;return y}),f(c.children,R),R.popWordTransform(),!(h.hideLinkHrefIfSameAsText&&H===A))R.addInline(!A?H:" "+r$(H,h.linkBrackets),{noWordTransform:!0})}}function L3(c,f,R,h,$){let H=rf(c,["parent","name"])==="li",A=0,G=(c.children||[]).filter((y)=>y.type!=="text"||!/^\s*$/.test(y.data)).map(function(y){if(y.name!=="li")return{node:y,prefix:""};let F=H?$().trimStart():$();if(F.length>A)A=F.length;return{node:y,prefix:F}});if(!G.length)return;R.openList({interRowLineBreaks:1,leadingLineBreaks:H?1:h.leadingLineBreaks||2,maxPrefixLength:A,prefixAlign:"left"});for(let{node:y,prefix:F}of G)R.openListItem({prefix:F}),f([y],R),R.closeListItem();R.closeList({trailingLineBreaks:H?1:h.trailingLineBreaks||2})}function UN(c,f,R,h){let $=h.itemPrefix||" * ";return L3(c,f,R,h,()=>$)}function YN(c,f,R,h){let $=Number(c.attribs.start||"1"),H=NN(c.attribs.type);return L3(c,f,R,h,()=>" "+H($++)+". ")}function NN(c="1"){switch(c){case"a":return(f)=>Y3(f,"a");case"A":return(f)=>Y3(f,"A");case"i":return(f)=>Z3(f).toLowerCase();case"I":return(f)=>Z3(f);case"1":default:return(f)=>f.toString()}}function ZN(c){let f=[],R=[];for(let h of c)if(h.startsWith("."))f.push(h.substring(1));else if(h.startsWith("#"))R.push(h.substring(1));return{classes:f,ids:R}}function JN(c,f){if(f===!0)return!0;if(!c)return!1;let{classes:R,ids:h}=ZN(f),$=(c.class||"").split(" "),H=(c.id||"").split(" ");return $.some((A)=>R.includes(A))||H.some((A)=>h.includes(A))}function zN(c,f,R,h){return JN(c.attribs,R.options.tables)?x3(c,f,R,h):SN(c,f,R,h)}function SN(c,f,R,h){R.openBlock({leadingLineBreaks:h.leadingLineBreaks}),f(c.children,R),R.closeBlock({trailingLineBreaks:h.trailingLineBreaks})}function x3(c,f,R,h){R.openTable(),c.children.forEach(H),R.closeTable({tableToString:(A)=>RN(A,h.rowSpacing??0,h.colSpacing??3),leadingLineBreaks:h.leadingLineBreaks,trailingLineBreaks:h.trailingLineBreaks});function $(A){let G=+rf(A,["attribs","colspan"])||1,y=+rf(A,["attribs","rowspan"])||1;R.openTableCell({maxColumnWidth:h.maxColumnWidth}),f(A.children,R),R.closeTableCell({colspan:G,rowspan:y})}function H(A){if(A.type!=="tag")return;let G=h.uppercaseHeaderCells!==!1?(y)=>{R.pushWordTransform((F)=>F.toUpperCase()),$(y),R.popWordTransform()}:$;switch(A.name){case"thead":case"tbody":case"tfoot":case"center":A.children.forEach(H);return;case"tr":{R.openTableRow();for(let y of A.children){if(y.type!=="tag")continue;switch(y.name){case"th":{G(y);break}case"td":{$(y);break}}}R.closeTableRow();break}}}}var MN=Object.freeze({__proto__:null,anchor:vN,blockquote:FN,dataTable:x3,heading:yN,horizontalLine:HN,image:WN,lineBreak:hN,orderedList:YN,paragraph:AN,pre:GN,table:zN,unorderedList:UN,wbr:$N}),BN={baseElements:{selectors:["body"],orderBy:"selectors",returnDomByDefault:!0},decodeEntities:!0,encodeCharacters:{},formatters:{},limits:{ellipsis:"...",maxBaseElements:void 0,maxChildNodes:void 0,maxDepth:void 0,maxInputLength:16777216},longWordSplit:{forceWrapOnLimit:!1,wrapCharacters:[]},preserveNewlines:!1,selectors:[{selector:"*",format:"inline"},{selector:"a",format:"anchor",options:{baseUrl:null,hideLinkHrefIfSameAsText:!1,ignoreHref:!1,linkBrackets:["[","]"],noAnchorUrl:!0}},{selector:"article",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"aside",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"blockquote",format:"blockquote",options:{leadingLineBreaks:2,trailingLineBreaks:2,trimEmptyLines:!0}},{selector:"br",format:"lineBreak"},{selector:"div",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"footer",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"form",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"h1",format:"heading",options:{leadingLineBreaks:3,trailingLineBreaks:2,uppercase:!0}},{selector:"h2",format:"heading",options:{leadingLineBreaks:3,trailingLineBreaks:2,uppercase:!0}},{selector:"h3",format:"heading",options:{leadingLineBreaks:3,trailingLineBreaks:2,uppercase:!0}},{selector:"h4",format:"heading",options:{leadingLineBreaks:2,trailingLineBreaks:2,uppercase:!0}},{selector:"h5",format:"heading",options:{leadingLineBreaks:2,trailingLineBreaks:2,uppercase:!0}},{selector:"h6",format:"heading",options:{leadingLineBreaks:2,trailingLineBreaks:2,uppercase:!0}},{selector:"header",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"hr",format:"horizontalLine",options:{leadingLineBreaks:2,length:void 0,trailingLineBreaks:2}},{selector:"img",format:"image",options:{baseUrl:null,linkBrackets:["[","]"]}},{selector:"main",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"nav",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"ol",format:"orderedList",options:{leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"p",format:"paragraph",options:{leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"pre",format:"pre",options:{leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"section",format:"block",options:{leadingLineBreaks:1,trailingLineBreaks:1}},{selector:"table",format:"table",options:{colSpacing:3,leadingLineBreaks:2,maxColumnWidth:60,rowSpacing:0,trailingLineBreaks:2,uppercaseHeaderCells:!0}},{selector:"ul",format:"unorderedList",options:{itemPrefix:" * ",leadingLineBreaks:2,trailingLineBreaks:2}},{selector:"wbr",format:"wbr"}],tables:[],whitespaceCharacters:` \r
67
67
  \f\u200B`,wordwrap:80},XN=(c,f,R)=>[...c,...f],I3=(c,f,R)=>[...f],QN=(c,f,R)=>c.some((h)=>typeof h==="object")?XN(c,f):I3(c,f);function DN(c={}){return c=e$.default(BN,c,{arrayMerge:I3,customMerge:(f)=>f==="selectors"?QN:void 0}),c.formatters=Object.assign({},rY,MN,c.formatters),c.selectors=S3(c.selectors,(f)=>f.selector),jN(c),uY(c)}function R8(c,f={},R=void 0){return DN(f)(c,R)}function jN(c){if(c.tags){let R=Object.entries(c.tags).map(([h,$])=>({...$,selector:h||"*"}));c.selectors.push(...R),c.selectors=S3(c.selectors,(h)=>h.selector)}function f(R,h,$){let H=h.pop();for(let A of h){let G=R[A];if(!G)G={},R[A]=G;R=G}R[H]=$}if(c.baseElement){let R=c.baseElement;f(c,["baseElements","selectors"],Array.isArray(R)?R:[R])}if(c.returnDomByDefault!==void 0)f(c,["baseElements","returnDomByDefault"],c.returnDomByDefault);for(let R of c.selectors)if(R.format==="anchor"&&rf(R,["options","noLinkBrackets"]))f(R,["options","linkBrackets"],!1)}var Ty=Y(Oy(),1);import{Writable as q7}from"stream";var{defineProperty:L7,getOwnPropertySymbols:by}=Object,x7=Object.prototype.hasOwnProperty,I7=Object.prototype.propertyIsEnumerable,qy=(c,f,R)=>(f in c)?L7(c,f,{enumerable:!0,configurable:!0,writable:!0,value:R}):c[f]=R,w8=(c,f)=>{for(var R in f||(f={}))if(x7.call(f,R))qy(c,R,f[R]);if(by){for(var R of by(f))if(I7.call(f,R))qy(c,R,f[R])}return c},L8=(c,f,R)=>{return new Promise((h,$)=>{var H=(y)=>{try{G(R.next(y))}catch(F){$(F)}},A=(y)=>{try{G(R.throw(y))}catch(F){$(F)}},G=(y)=>y.done?h(y.value):Promise.resolve(y.value).then(H,A);G((R=R.apply(c,f)).next())})},K7={unformatted:["code","pre","em","strong","span"],indent_inner_html:!0,indent_char:" ",indent_size:2,sep:`
68
- `},O7=(c,f={})=>{return Ty.default.html(c,w8(w8({},K7),f))},b7=[{selector:"img",format:"skip"},{selector:"#__react-email-preview",format:"skip"},{selector:"a",options:{linkBrackets:!1}}];var Vy=new TextDecoder("utf-8"),Ey=(c)=>L8(void 0,null,function*(){let f="";if("pipeTo"in c){let R=new WritableStream({write(h){f+=Vy.decode(h)}});yield c.pipeTo(R)}else{let R=new q7({write(h,$,H){f+=Vy.decode(h),H()}});return c.pipe(R),new Promise((h,$)=>{R.on("error",$),R.on("close",()=>{h(f)})})}return f}),dh=(c,f)=>L8(void 0,null,function*(){let{default:R}=yield import("react-dom/server"),h;if(Object.hasOwn(R,"renderToReadableStream"))h=yield Ey(yield R.renderToReadableStream(c));else yield new Promise((A,G)=>{let y=R.renderToPipeableStream(c,{onAllReady(){return L8(this,null,function*(){h=yield Ey(y),A()})},onError(F){G(F)}})});if(f==null?void 0:f.plainText)return R8(h,w8({selectors:b7},f.htmlToTextOptions));let H=`${'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'}${h.replace(/<!DOCTYPE.*?>/,"")}`;if(f==null?void 0:f.pretty)return O7(H);return H});var{defineProperty:V7,defineProperties:E7,getOwnPropertyDescriptors:T7,getOwnPropertySymbols:uy}=Object,u7=Object.prototype.hasOwnProperty,g7=Object.prototype.propertyIsEnumerable,gy=(c,f,R)=>(f in c)?V7(c,f,{enumerable:!0,configurable:!0,writable:!0,value:R}):c[f]=R,f0=(c,f)=>{for(var R in f||(f={}))if(u7.call(f,R))gy(c,R,f[R]);if(uy){for(var R of uy(f))if(g7.call(f,R))gy(c,R,f[R])}return c},C7=(c,f)=>E7(c,T7(f)),E=(c,f,R)=>{return new Promise((h,$)=>{var H=(y)=>{try{G(R.next(y))}catch(F){$(F)}},A=(y)=>{try{G(R.throw(y))}catch(F){$(F)}},G=(y)=>y.done?h(y.value):Promise.resolve(y.value).then(H,A);G((R=R.apply(c,f)).next())})},m7="3.5.0",p7=class{constructor(c){this.resend=c}create(c){return E(this,arguments,function*(f,R={}){return yield this.resend.post("/api-keys",f,R)})}list(){return E(this,null,function*(){return yield this.resend.get("/api-keys")})}remove(c){return E(this,null,function*(){return yield this.resend.delete(`/api-keys/${c}`)})}},s7=class{constructor(c){this.resend=c}create(c){return E(this,arguments,function*(f,R={}){return yield this.resend.post("/audiences",f,R)})}list(){return E(this,null,function*(){return yield this.resend.get("/audiences")})}get(c){return E(this,null,function*(){return yield this.resend.get(`/audiences/${c}`)})}remove(c){return E(this,null,function*(){return yield this.resend.delete(`/audiences/${c}`)})}},i7=class{constructor(c){this.resend=c}send(c){return E(this,arguments,function*(f,R={}){return this.create(f,R)})}create(c){return E(this,arguments,function*(f,R={}){for(let $ of f)if($.react)$.html=yield dh($.react),delete $.react;return yield this.resend.post("/emails/batch",f,R)})}},k7=class{constructor(c){this.resend=c}create(c){return E(this,arguments,function*(f,R={}){return yield this.resend.post(`/audiences/${f.audienceId}/contacts`,{unsubscribed:f.unsubscribed,email:f.email,first_name:f.firstName,last_name:f.lastName},R)})}list(c){return E(this,null,function*(){return yield this.resend.get(`/audiences/${c.audienceId}/contacts`)})}get(c){return E(this,null,function*(){return yield this.resend.get(`/audiences/${c.audienceId}/contacts/${c.id}`)})}update(c){return E(this,null,function*(){return yield this.resend.patch(`/audiences/${c.audienceId}/contacts/${c.id}`,{unsubscribed:c.unsubscribed,first_name:c.firstName,last_name:c.lastName})})}remove(c){return E(this,null,function*(){return yield this.resend.delete(`/audiences/${c.audienceId}/contacts/${(c==null?void 0:c.email)?c==null?void 0:c.email:c==null?void 0:c.id}`)})}},l7=class{constructor(c){this.resend=c}create(c){return E(this,arguments,function*(f,R={}){return yield this.resend.post("/domains",f,R)})}list(){return E(this,null,function*(){return yield this.resend.get("/domains")})}get(c){return E(this,null,function*(){return yield this.resend.get(`/domains/${c}`)})}update(c){return E(this,null,function*(){return yield this.resend.patch(`/domains/${c.id}`,{click_tracking:c.clickTracking,open_tracking:c.openTracking,tls:c.tls})})}remove(c){return E(this,null,function*(){return yield this.resend.delete(`/domains/${c}`)})}verify(c){return E(this,null,function*(){return yield this.resend.post(`/domains/${c}/verify`)})}},d7=class{constructor(c){this.resend=c}send(c){return E(this,arguments,function*(f,R={}){return this.create(f,R)})}create(c){return E(this,arguments,function*(f,R={}){if(f.react)f.html=yield dh(f.react),delete f.react;return yield this.resend.post("/emails",f,R)})}get(c){return E(this,null,function*(){return yield this.resend.get(`/emails/${c}`)})}},Cy="https://api.resend.com",my=`resend-node:${m7}`,_7=typeof process<"u"&&process.env?process.env.RESEND_BASE_URL||Cy:Cy,n7=typeof process<"u"&&process.env?process.env.RESEND_USER_AGENT||my:my,py=class{constructor(c){if(this.key=c,this.apiKeys=new p7(this),this.audiences=new s7(this),this.batch=new i7(this),this.contacts=new k7(this),this.domains=new l7(this),this.emails=new d7(this),!c){if(typeof process<"u"&&process.env)this.key=process.env.RESEND_API_KEY;if(!this.key)throw Error('Missing API key. Pass it to the constructor `new Resend("re_123")`')}this.headers=new Headers({Authorization:`Bearer ${this.key}`,"User-Agent":n7,"Content-Type":"application/json"})}fetchRequest(c){return E(this,arguments,function*(f,R={}){try{let h=yield fetch(`${_7}${f}`,R);if(!h.ok)try{let H=yield h.text();return{data:null,error:JSON.parse(H)}}catch(H){if(H instanceof SyntaxError)return{data:null,error:{name:"application_error",message:"Internal server error. We are unable to process your request right now, please try again later."}};let A={message:h.statusText,name:"application_error"};if(H instanceof Error)return{data:null,error:C7(f0({},A),{message:H.message})};return{data:null,error:A}}return{data:yield h.json(),error:null}}catch(h){return{data:null,error:{name:"application_error",message:"Unable to fetch data. The request could not be resolved."}}}})}post(c,f){return E(this,arguments,function*(R,h,$={}){let H=f0({method:"POST",headers:this.headers,body:JSON.stringify(h)},$);return this.fetchRequest(R,H)})}get(c){return E(this,arguments,function*(f,R={}){let h=f0({method:"GET",headers:this.headers},R);return this.fetchRequest(f,h)})}put(c,f){return E(this,arguments,function*(R,h,$={}){let H=f0({method:"PUT",headers:this.headers,body:JSON.stringify(h)},$);return this.fetchRequest(R,H)})}patch(c,f){return E(this,arguments,function*(R,h,$={}){let H=f0({method:"PATCH",headers:this.headers,body:JSON.stringify(h)},$);return this.fetchRequest(R,H)})}delete(c,f){return E(this,null,function*(){let R={method:"DELETE",headers:this.headers,body:JSON.stringify(f)};return this.fetchRequest(c,R)})}};class _h{}class nh extends _h{apiKey;constructor(c=process.env.RESEND_API_KEY){super();this.apiKey=c}async send(c){let f=new py(this.apiKey),{data:R,error:h}=await f.emails.send({...c});if(h)return console.error(h),!1;if(R)return!0;return!1}}class sy extends l{driver=new nh;headers={};boot(){}filterRecipients(c){return c}}class iy extends l{channels={};boot(){}}class ky extends l{root;rootRouter;boot(){}onRequestStart(c){}onRequestEnd(c){}onRequestFail(c,f){}}class ly extends l{rootRouter;boot(){}onRequestStart(c){}onRequestEnd(c){}onRequestFail(c,f){}}class dy extends l{maxFileSize=10485760;boot(){}onLogFileClosed(c){}onLogCreated(c){}}class _y extends l{jobs=[];concurrency=1;boot(){}}class oy{static name="unset";worker=!1;maxAttempts=3;run(...c){}onFail(c,...f){}onSuccess(c,...f){}onDeadletter(c,...f){}static dispatch(...c){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");ny.use().push(this,JSON.stringify(c))}}import o7 from"sharp";class oh{}class ah extends oh{async resize(c,f){let{height:R,width:h,quality:$,fit:H}=f;return await o7(c).resize(h>0?h:void 0,R>0?R:void 0,{fit:H}).webp({quality:$>0?$:80,force:!0}).toBuffer()}}class ay extends l{driver=new ah;boot(){}}class cR{}var a7={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET,redirectPath:"/auth/oauth/google/callback",scope:"https://www.googleapis.com/auth/userinfo.email"};class ty extends cR{config;constructor(c={}){super();this.config={...a7,...c}}getRedirectUrl(){let c=this.config.scope,f=this.config.clientId,R=new URL("https://accounts.google.com/o/oauth2/v2/auth"),h={scope:c,include_granted_scopes:"true",response_type:"code",state:"state_parameter_passthrough_value",redirect_uri:`${process.env.HOST_NAME}/auth/oauth/google/callback`,client_id:f};for(let[H,A]of Object.entries(h))R.searchParams.append(H,A);return R.toString()}async onCallback(c){let f=new URL("https://oauth2.googleapis.com/token");f.searchParams.append("code",c.search.get("code")),f.searchParams.append("client_id",this.config.clientId),f.searchParams.append("client_secret",this.config.clientSecret),f.searchParams.append("grant_type","authorization_code"),f.searchParams.append("redirect_uri",`${process.env.HOST_NAME}${this.config.redirectPath}`);let R=await fetch(f.toString(),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"}}),{access_token:h}=await R.json(),H=await(await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${h}`)).json();return{name:H.name,email:H.email}}}var Gf="https://api.x.com/2/",fR="https://api.x.com/labs/2/",yf="https://api.x.com/1.1/",_c="https://upload.x.com/1.1/",ry="https://stream.x.com/1.1/",RR="https://ads-api.x.com/12/",hR="https://ads-api-sandbox.twitter.com/12/";class x8{constructor({realData:c,rateLimit:f,instance:R,queryParams:h,sharedParams:$}){this._maxResultsWhenFetchLast=100,this._realData=c,this._rateLimit=f,this._instance=R,this._queryParams=h,this._sharedParams=$}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(c){return this._instance.get(this.getEndpoint(),c,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(c,f){return new this.constructor({realData:c.data,rateLimit:c.rateLimit,instance:this._instance,queryParams:f,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(c){return{...c?{max_results:c}:{},...this._queryParams}}async next(c){let f=this.getNextQueryParams(c),R=await this.makeRequest(f);return this.makeNewInstanceFromResult(R,f)}async fetchNext(c){let f=this.getNextQueryParams(c),R=await this.makeRequest(f);return await this.refreshInstanceFromResult(R,!0),this}async fetchLast(c=1/0){let f=this.getNextQueryParams(this._maxResultsWhenFetchLast),R=0;while(R<c&&this._isRateLimitOk){let h=await this.makeRequest(f);if(await this.refreshInstanceFromResult(h,!0),R+=this.getPageLengthFromRequest(h),this.isFetchLastOver(h))break;f=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var c;return{...(c=this._rateLimit)!==null&&c!==void 0?c:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let c=this,f=this.canFetchNextPage(this._realData);while(f&&this._isRateLimitOk&&c.getItemArray().length>0){let R=await c.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:R._realData,headers:{},rateLimit:R._rateLimit},!0),f=this.canFetchNextPage(R._realData),yield*R.getItemArray(),c=R}}async*fetchAndIterate(){for(let R of this.getItemArray())yield[R,this];let c=this,f=this.canFetchNextPage(this._realData);while(f&&this._isRateLimitOk&&c.getItemArray().length>0){let R=await c.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:R._realData,headers:{},rateLimit:R._rateLimit},!0),f=this.canFetchNextPage(R._realData);for(let h of R.getItemArray())yield[h,R];this._rateLimit=R._rateLimit,c=R}}}class I8 extends x8{async previous(c){let f=this.getPreviousQueryParams(c),R=await this.makeRequest(f);return this.makeNewInstanceFromResult(R,f)}async fetchPrevious(c){let f=this.getPreviousQueryParams(c),R=await this.makeRequest(f);return await this.refreshInstanceFromResult(R,!1),this}}var $R=x8;class Ac extends $R{getNextQueryParams(c){var f;return{...this._queryParams,cursor:(f=this._realData.next_cursor_str)!==null&&f!==void 0?f:this._realData.next_cursor,...c?{count:c}:{}}}isFetchLastOver(c){return!this.canFetchNextPage(c.data)}canFetchNextPage(c){return!this.isNextCursorInvalid(c.next_cursor)||!this.isNextCursorInvalid(c.next_cursor_str)}isNextCursorInvalid(c){return c===void 0||c===0||c===-1||c==="0"||c==="-1"}}class P8 extends Ac{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(c,f){let R=c.data;if(this._rateLimit=c.rateLimit,f)this._realData.events.push(...R.events),this._realData.next_cursor=R.next_cursor}getPageLengthFromRequest(c){return c.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class K8 extends Ac{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(c,f){let R=c.data;if(this._rateLimit=c.rateLimit,f)this._realData.welcome_messages.push(...R.welcome_messages),this._realData.next_cursor=R.next_cursor}getPageLengthFromRequest(c){return c.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var i;(function(c){c.Jpeg="image/jpeg",c.Mp4="video/mp4",c.Mov="video/quicktime",c.Gif="image/gif",c.Png="image/png",c.Srt="text/plain",c.Webp="image/webp"})(i||(i={}));var Ff;(function(c){c.Create="message_create",c.WelcomeCreate="welcome_message"})(Ff||(Ff={}));var R0;(function(c){c.Request="request",c.PartialResponse="partial-response",c.Response="response"})(R0||(R0={}));class th extends Error{constructor(){super(...arguments);this.error=!0}}class h0 extends th{constructor(c,f){super(c);this.type=R0.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:f})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class $0 extends th{constructor(c,f){super(c);this.type=R0.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:f})}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 H0 extends th{constructor(c,f){super(c);if(this.type=R0.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:f}),this.code=f.code,this.headers=f.headers,this.rateLimit=f.rateLimit,f.data&&typeof f.data==="object"&&"error"in f.data&&!f.data.errors){let R={...f.data};R.errors=[{code:Qf.InternalError,message:R.error}],this.data=R}else this.data=f.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...c){let f=this.errors;if(!(f===null||f===void 0?void 0:f.length))return!1;if("code"in f[0])return f.some(($)=>c.includes($.code));let R=this.data;return c.includes(R.type)}get errors(){var c;return(c=this.data)===null||c===void 0?void 0:c.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(Qf.AuthTimestampInvalid,Qf.AuthenticationFail,Qf.BadAuthenticationData,Qf.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var Qf;(function(c){c[c.InvalidCoordinates=3]="InvalidCoordinates",c[c.NoLocationFound=13]="NoLocationFound",c[c.AuthenticationFail=32]="AuthenticationFail",c[c.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",c[c.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",c[c.AuthTimestampInvalid=135]="AuthTimestampInvalid",c[c.BadAuthenticationData=215]="BadAuthenticationData",c[c.NoUserMatch=17]="NoUserMatch",c[c.UserNotFound=50]="UserNotFound",c[c.ResourceNotFound=34]="ResourceNotFound",c[c.TweetNotFound=144]="TweetNotFound",c[c.TweetNotVisible=179]="TweetNotVisible",c[c.NotAllowedResource=220]="NotAllowedResource",c[c.MediaIdNotFound=325]="MediaIdNotFound",c[c.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",c[c.TweetViolatedRules=422]="TweetViolatedRules",c[c.TargetUserSuspended=63]="TargetUserSuspended",c[c.YouAreSuspended=64]="YouAreSuspended",c[c.AccountUpdateFailed=120]="AccountUpdateFailed",c[c.NoSelfSpamReport=36]="NoSelfSpamReport",c[c.NoSelfMute=271]="NoSelfMute",c[c.AccountLocked=326]="AccountLocked",c[c.RateLimitExceeded=88]="RateLimitExceeded",c[c.NoDMRightForApp=93]="NoDMRightForApp",c[c.OverCapacity=130]="OverCapacity",c[c.InternalError=131]="InternalError",c[c.TooManyFollowings=161]="TooManyFollowings",c[c.TweetLimitExceeded=185]="TweetLimitExceeded",c[c.DuplicatedTweet=187]="DuplicatedTweet",c[c.TooManySpamReports=205]="TooManySpamReports",c[c.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",c[c.NoWriteRightForApp=261]="NoWriteRightForApp",c[c.TweetActionsDisabled=425]="TweetActionsDisabled",c[c.TweetRepliesRestricted=433]="TweetRepliesRestricted",c[c.NamedParameterMissing=38]="NamedParameterMissing",c[c.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",c[c.TweetTextTooLong=186]="TweetTextTooLong",c[c.MissingUrlParameter=195]="MissingUrlParameter",c[c.NoMultipleGifs=323]="NoMultipleGifs",c[c.InvalidMediaIds=324]="InvalidMediaIds",c[c.InvalidUrl=407]="InvalidUrl",c[c.TooManyTweetAttachments=386]="TooManyTweetAttachments",c[c.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",c[c.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",c[c.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",c[c.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",c[c.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",c[c.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",c[c.UnableToSendDM=151]="UnableToSendDM",c[c.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",c[c.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",c[c.DMTextTooLong=354]="DMTextTooLong",c[c.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",c[c.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",c[c.SuspendedApplication=416]="SuspendedApplication",c[c.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(Qf||(Qf={}));var ey;(function(c){c.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",c.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",c.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",c.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",c.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",c.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",c.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",c.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",c.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",c.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",c.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",c.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",c.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(ey||(ey={}));var L;(function(c){c.Connected="connected",c.ConnectError="connect error",c.ConnectionError="connection error",c.ConnectionClosed="connection closed",c.ConnectionLost="connection lost",c.ReconnectAttempt="reconnect attempt",c.Reconnected="reconnected",c.ReconnectError="reconnect error",c.ReconnectLimitExceeded="reconnect limit exceeded",c.DataKeepAlive="data keep-alive",c.Data="data event content",c.DataError="data twitter error",c.TweetParseError="data tweet parse error",c.Error="stream error"})(L||(L={}));class A0{constructor(c){this.value=c}}import*as R4 from"fs";var Fc={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function O8(c){let f={value:void 0,promise:c().then((R)=>{return f.value=R,R})};return f}function rh(c){if(Array.isArray(c))return c;return[c]}function fF(c){for(let f of Object.keys(c))if(c[f]===void 0)delete c[f]}function eh(c){return typeof c==="object"&&"errors"in c&&!("data"in c)}function G0(c){if(Array.isArray(c)&&c.length>1)return!0;return c.toString().includes(",")}var cF=new Set;function b8(c){if(typeof console>"u"||!console.warn||!Fc.deprecationWarnings)return;let f=`${c.instance}-${c.method}-${c.problem}`;if(cF.has(f))return;let R=`[twitter-api-v2] Deprecation warning: In ${c.instance}.${c.method}() call, ${c.problem}.
68
+ `},O7=(c,f={})=>{return Ty.default.html(c,w8(w8({},K7),f))},b7=[{selector:"img",format:"skip"},{selector:"#__react-email-preview",format:"skip"},{selector:"a",options:{linkBrackets:!1}}];var Vy=new TextDecoder("utf-8"),Ey=(c)=>L8(void 0,null,function*(){let f="";if("pipeTo"in c){let R=new WritableStream({write(h){f+=Vy.decode(h)}});yield c.pipeTo(R)}else{let R=new q7({write(h,$,H){f+=Vy.decode(h),H()}});return c.pipe(R),new Promise((h,$)=>{R.on("error",$),R.on("close",()=>{h(f)})})}return f}),dh=(c,f)=>L8(void 0,null,function*(){let{default:R}=yield import("react-dom/server"),h;if(Object.hasOwn(R,"renderToReadableStream"))h=yield Ey(yield R.renderToReadableStream(c));else yield new Promise((A,G)=>{let y=R.renderToPipeableStream(c,{onAllReady(){return L8(this,null,function*(){h=yield Ey(y),A()})},onError(F){G(F)}})});if(f==null?void 0:f.plainText)return R8(h,w8({selectors:b7},f.htmlToTextOptions));let H=`${'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'}${h.replace(/<!DOCTYPE.*?>/,"")}`;if(f==null?void 0:f.pretty)return O7(H);return H});var{defineProperty:V7,defineProperties:E7,getOwnPropertyDescriptors:T7,getOwnPropertySymbols:uy}=Object,u7=Object.prototype.hasOwnProperty,g7=Object.prototype.propertyIsEnumerable,gy=(c,f,R)=>(f in c)?V7(c,f,{enumerable:!0,configurable:!0,writable:!0,value:R}):c[f]=R,f0=(c,f)=>{for(var R in f||(f={}))if(u7.call(f,R))gy(c,R,f[R]);if(uy){for(var R of uy(f))if(g7.call(f,R))gy(c,R,f[R])}return c},C7=(c,f)=>E7(c,T7(f)),E=(c,f,R)=>{return new Promise((h,$)=>{var H=(y)=>{try{G(R.next(y))}catch(F){$(F)}},A=(y)=>{try{G(R.throw(y))}catch(F){$(F)}},G=(y)=>y.done?h(y.value):Promise.resolve(y.value).then(H,A);G((R=R.apply(c,f)).next())})},m7="3.5.0",p7=class{constructor(c){this.resend=c}create(c){return E(this,arguments,function*(f,R={}){return yield this.resend.post("/api-keys",f,R)})}list(){return E(this,null,function*(){return yield this.resend.get("/api-keys")})}remove(c){return E(this,null,function*(){return yield this.resend.delete(`/api-keys/${c}`)})}},s7=class{constructor(c){this.resend=c}create(c){return E(this,arguments,function*(f,R={}){return yield this.resend.post("/audiences",f,R)})}list(){return E(this,null,function*(){return yield this.resend.get("/audiences")})}get(c){return E(this,null,function*(){return yield this.resend.get(`/audiences/${c}`)})}remove(c){return E(this,null,function*(){return yield this.resend.delete(`/audiences/${c}`)})}},i7=class{constructor(c){this.resend=c}send(c){return E(this,arguments,function*(f,R={}){return this.create(f,R)})}create(c){return E(this,arguments,function*(f,R={}){for(let $ of f)if($.react)$.html=yield dh($.react),delete $.react;return yield this.resend.post("/emails/batch",f,R)})}},k7=class{constructor(c){this.resend=c}create(c){return E(this,arguments,function*(f,R={}){return yield this.resend.post(`/audiences/${f.audienceId}/contacts`,{unsubscribed:f.unsubscribed,email:f.email,first_name:f.firstName,last_name:f.lastName},R)})}list(c){return E(this,null,function*(){return yield this.resend.get(`/audiences/${c.audienceId}/contacts`)})}get(c){return E(this,null,function*(){return yield this.resend.get(`/audiences/${c.audienceId}/contacts/${c.id}`)})}update(c){return E(this,null,function*(){return yield this.resend.patch(`/audiences/${c.audienceId}/contacts/${c.id}`,{unsubscribed:c.unsubscribed,first_name:c.firstName,last_name:c.lastName})})}remove(c){return E(this,null,function*(){return yield this.resend.delete(`/audiences/${c.audienceId}/contacts/${(c==null?void 0:c.email)?c==null?void 0:c.email:c==null?void 0:c.id}`)})}},l7=class{constructor(c){this.resend=c}create(c){return E(this,arguments,function*(f,R={}){return yield this.resend.post("/domains",f,R)})}list(){return E(this,null,function*(){return yield this.resend.get("/domains")})}get(c){return E(this,null,function*(){return yield this.resend.get(`/domains/${c}`)})}update(c){return E(this,null,function*(){return yield this.resend.patch(`/domains/${c.id}`,{click_tracking:c.clickTracking,open_tracking:c.openTracking,tls:c.tls})})}remove(c){return E(this,null,function*(){return yield this.resend.delete(`/domains/${c}`)})}verify(c){return E(this,null,function*(){return yield this.resend.post(`/domains/${c}/verify`)})}},d7=class{constructor(c){this.resend=c}send(c){return E(this,arguments,function*(f,R={}){return this.create(f,R)})}create(c){return E(this,arguments,function*(f,R={}){if(f.react)f.html=yield dh(f.react),delete f.react;return yield this.resend.post("/emails",f,R)})}get(c){return E(this,null,function*(){return yield this.resend.get(`/emails/${c}`)})}},Cy="https://api.resend.com",my=`resend-node:${m7}`,_7=typeof process<"u"&&process.env?process.env.RESEND_BASE_URL||Cy:Cy,n7=typeof process<"u"&&process.env?process.env.RESEND_USER_AGENT||my:my,py=class{constructor(c){if(this.key=c,this.apiKeys=new p7(this),this.audiences=new s7(this),this.batch=new i7(this),this.contacts=new k7(this),this.domains=new l7(this),this.emails=new d7(this),!c){if(typeof process<"u"&&process.env)this.key=process.env.RESEND_API_KEY;if(!this.key)throw Error('Missing API key. Pass it to the constructor `new Resend("re_123")`')}this.headers=new Headers({Authorization:`Bearer ${this.key}`,"User-Agent":n7,"Content-Type":"application/json"})}fetchRequest(c){return E(this,arguments,function*(f,R={}){try{let h=yield fetch(`${_7}${f}`,R);if(!h.ok)try{let H=yield h.text();return{data:null,error:JSON.parse(H)}}catch(H){if(H instanceof SyntaxError)return{data:null,error:{name:"application_error",message:"Internal server error. We are unable to process your request right now, please try again later."}};let A={message:h.statusText,name:"application_error"};if(H instanceof Error)return{data:null,error:C7(f0({},A),{message:H.message})};return{data:null,error:A}}return{data:yield h.json(),error:null}}catch(h){return{data:null,error:{name:"application_error",message:"Unable to fetch data. The request could not be resolved."}}}})}post(c,f){return E(this,arguments,function*(R,h,$={}){let H=f0({method:"POST",headers:this.headers,body:JSON.stringify(h)},$);return this.fetchRequest(R,H)})}get(c){return E(this,arguments,function*(f,R={}){let h=f0({method:"GET",headers:this.headers},R);return this.fetchRequest(f,h)})}put(c,f){return E(this,arguments,function*(R,h,$={}){let H=f0({method:"PUT",headers:this.headers,body:JSON.stringify(h)},$);return this.fetchRequest(R,H)})}patch(c,f){return E(this,arguments,function*(R,h,$={}){let H=f0({method:"PATCH",headers:this.headers,body:JSON.stringify(h)},$);return this.fetchRequest(R,H)})}delete(c,f){return E(this,null,function*(){let R={method:"DELETE",headers:this.headers,body:JSON.stringify(f)};return this.fetchRequest(c,R)})}};class _h{}class nh extends _h{apiKey;constructor(c=process.env.RESEND_API_KEY){super();this.apiKey=c}async send(c){let f=new py(this.apiKey),{data:R,error:h}=await f.emails.send({...c});if(h)return console.error(h),!1;if(R)return!0;return!1}}class sy extends l{driver=new nh;headers={};boot(){}filterRecipients(c){return c}}class iy extends l{channels={};boot(){}}class ky extends l{root;rootRouter;boot(){}onRequestStart(c){}onRequestEnd(c){}onRequestFail(c,f){}}class ly extends l{rootRouter;boot(){}onRequestStart(c){}onRequestEnd(c){}onRequestFail(c,f){}}class dy extends l{maxFileSize=10485760;boot(){}onLogFileClosed(c){}onLogCreated(c){}}class _y extends l{jobs=[];concurrency=1;boot(){}}class oy{static name="unset";worker=!1;maxAttempts=3;run(...c){}onFail(c,...f){}onSuccess(c,...f){}onDeadletter(c,...f){}static dispatch(...c){if(this.name==="unset")throw Error("Cannot dispatch a job with no name");ny.use().push(this,JSON.stringify(c))}}import o7 from"sharp";class oh{}class ah extends oh{async resize(c,f){let{height:R,width:h,quality:$,fit:H}=f;return await o7(c).resize(h>0?h:void 0,R>0?R:void 0,{fit:H}).webp({quality:$>0?$:80,force:!0}).toBuffer()}}class ay extends l{driver=new ah;boot(){}}class cR{}var a7={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET,redirectPath:"/auth/oauth/google/callback",scope:"https://www.googleapis.com/auth/userinfo.profile"};class ty extends cR{config;constructor(c={}){super();this.config={...a7,...c}}getRedirectUrl(){let c=this.config.scope,f=this.config.clientId,R=new URL("https://accounts.google.com/o/oauth2/v2/auth"),h={scope:c,include_granted_scopes:"true",response_type:"code",state:"state_parameter_passthrough_value",redirect_uri:`${process.env.HOST_NAME}/auth/oauth/google/callback`,client_id:f};for(let[H,A]of Object.entries(h))R.searchParams.append(H,A);return R.toString()}async onCallback(c){let f=new URL("https://oauth2.googleapis.com/token");f.searchParams.append("code",c.search.get("code")),f.searchParams.append("client_id",this.config.clientId),f.searchParams.append("client_secret",this.config.clientSecret),f.searchParams.append("grant_type","authorization_code"),f.searchParams.append("redirect_uri",`${process.env.HOST_NAME}${this.config.redirectPath}`);let R=await fetch(f.toString(),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"}}),{access_token:h}=await R.json(),H=await(await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${h}`)).json();return{name:H.name,email:H.email}}}var Gf="https://api.x.com/2/",fR="https://api.x.com/labs/2/",yf="https://api.x.com/1.1/",_c="https://upload.x.com/1.1/",ry="https://stream.x.com/1.1/",RR="https://ads-api.x.com/12/",hR="https://ads-api-sandbox.twitter.com/12/";class x8{constructor({realData:c,rateLimit:f,instance:R,queryParams:h,sharedParams:$}){this._maxResultsWhenFetchLast=100,this._realData=c,this._rateLimit=f,this._instance=R,this._queryParams=h,this._sharedParams=$}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(c){return this._instance.get(this.getEndpoint(),c,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(c,f){return new this.constructor({realData:c.data,rateLimit:c.rateLimit,instance:this._instance,queryParams:f,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(c){return{...c?{max_results:c}:{},...this._queryParams}}async next(c){let f=this.getNextQueryParams(c),R=await this.makeRequest(f);return this.makeNewInstanceFromResult(R,f)}async fetchNext(c){let f=this.getNextQueryParams(c),R=await this.makeRequest(f);return await this.refreshInstanceFromResult(R,!0),this}async fetchLast(c=1/0){let f=this.getNextQueryParams(this._maxResultsWhenFetchLast),R=0;while(R<c&&this._isRateLimitOk){let h=await this.makeRequest(f);if(await this.refreshInstanceFromResult(h,!0),R+=this.getPageLengthFromRequest(h),this.isFetchLastOver(h))break;f=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var c;return{...(c=this._rateLimit)!==null&&c!==void 0?c:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let c=this,f=this.canFetchNextPage(this._realData);while(f&&this._isRateLimitOk&&c.getItemArray().length>0){let R=await c.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:R._realData,headers:{},rateLimit:R._rateLimit},!0),f=this.canFetchNextPage(R._realData),yield*R.getItemArray(),c=R}}async*fetchAndIterate(){for(let R of this.getItemArray())yield[R,this];let c=this,f=this.canFetchNextPage(this._realData);while(f&&this._isRateLimitOk&&c.getItemArray().length>0){let R=await c.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:R._realData,headers:{},rateLimit:R._rateLimit},!0),f=this.canFetchNextPage(R._realData);for(let h of R.getItemArray())yield[h,R];this._rateLimit=R._rateLimit,c=R}}}class I8 extends x8{async previous(c){let f=this.getPreviousQueryParams(c),R=await this.makeRequest(f);return this.makeNewInstanceFromResult(R,f)}async fetchPrevious(c){let f=this.getPreviousQueryParams(c),R=await this.makeRequest(f);return await this.refreshInstanceFromResult(R,!1),this}}var $R=x8;class Ac extends $R{getNextQueryParams(c){var f;return{...this._queryParams,cursor:(f=this._realData.next_cursor_str)!==null&&f!==void 0?f:this._realData.next_cursor,...c?{count:c}:{}}}isFetchLastOver(c){return!this.canFetchNextPage(c.data)}canFetchNextPage(c){return!this.isNextCursorInvalid(c.next_cursor)||!this.isNextCursorInvalid(c.next_cursor_str)}isNextCursorInvalid(c){return c===void 0||c===0||c===-1||c==="0"||c==="-1"}}class P8 extends Ac{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(c,f){let R=c.data;if(this._rateLimit=c.rateLimit,f)this._realData.events.push(...R.events),this._realData.next_cursor=R.next_cursor}getPageLengthFromRequest(c){return c.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class K8 extends Ac{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(c,f){let R=c.data;if(this._rateLimit=c.rateLimit,f)this._realData.welcome_messages.push(...R.welcome_messages),this._realData.next_cursor=R.next_cursor}getPageLengthFromRequest(c){return c.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var i;(function(c){c.Jpeg="image/jpeg",c.Mp4="video/mp4",c.Mov="video/quicktime",c.Gif="image/gif",c.Png="image/png",c.Srt="text/plain",c.Webp="image/webp"})(i||(i={}));var Ff;(function(c){c.Create="message_create",c.WelcomeCreate="welcome_message"})(Ff||(Ff={}));var R0;(function(c){c.Request="request",c.PartialResponse="partial-response",c.Response="response"})(R0||(R0={}));class th extends Error{constructor(){super(...arguments);this.error=!0}}class h0 extends th{constructor(c,f){super(c);this.type=R0.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:f})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class $0 extends th{constructor(c,f){super(c);this.type=R0.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:f})}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 H0 extends th{constructor(c,f){super(c);if(this.type=R0.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:f}),this.code=f.code,this.headers=f.headers,this.rateLimit=f.rateLimit,f.data&&typeof f.data==="object"&&"error"in f.data&&!f.data.errors){let R={...f.data};R.errors=[{code:Qf.InternalError,message:R.error}],this.data=R}else this.data=f.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...c){let f=this.errors;if(!(f===null||f===void 0?void 0:f.length))return!1;if("code"in f[0])return f.some(($)=>c.includes($.code));let R=this.data;return c.includes(R.type)}get errors(){var c;return(c=this.data)===null||c===void 0?void 0:c.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(Qf.AuthTimestampInvalid,Qf.AuthenticationFail,Qf.BadAuthenticationData,Qf.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var Qf;(function(c){c[c.InvalidCoordinates=3]="InvalidCoordinates",c[c.NoLocationFound=13]="NoLocationFound",c[c.AuthenticationFail=32]="AuthenticationFail",c[c.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",c[c.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",c[c.AuthTimestampInvalid=135]="AuthTimestampInvalid",c[c.BadAuthenticationData=215]="BadAuthenticationData",c[c.NoUserMatch=17]="NoUserMatch",c[c.UserNotFound=50]="UserNotFound",c[c.ResourceNotFound=34]="ResourceNotFound",c[c.TweetNotFound=144]="TweetNotFound",c[c.TweetNotVisible=179]="TweetNotVisible",c[c.NotAllowedResource=220]="NotAllowedResource",c[c.MediaIdNotFound=325]="MediaIdNotFound",c[c.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",c[c.TweetViolatedRules=422]="TweetViolatedRules",c[c.TargetUserSuspended=63]="TargetUserSuspended",c[c.YouAreSuspended=64]="YouAreSuspended",c[c.AccountUpdateFailed=120]="AccountUpdateFailed",c[c.NoSelfSpamReport=36]="NoSelfSpamReport",c[c.NoSelfMute=271]="NoSelfMute",c[c.AccountLocked=326]="AccountLocked",c[c.RateLimitExceeded=88]="RateLimitExceeded",c[c.NoDMRightForApp=93]="NoDMRightForApp",c[c.OverCapacity=130]="OverCapacity",c[c.InternalError=131]="InternalError",c[c.TooManyFollowings=161]="TooManyFollowings",c[c.TweetLimitExceeded=185]="TweetLimitExceeded",c[c.DuplicatedTweet=187]="DuplicatedTweet",c[c.TooManySpamReports=205]="TooManySpamReports",c[c.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",c[c.NoWriteRightForApp=261]="NoWriteRightForApp",c[c.TweetActionsDisabled=425]="TweetActionsDisabled",c[c.TweetRepliesRestricted=433]="TweetRepliesRestricted",c[c.NamedParameterMissing=38]="NamedParameterMissing",c[c.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",c[c.TweetTextTooLong=186]="TweetTextTooLong",c[c.MissingUrlParameter=195]="MissingUrlParameter",c[c.NoMultipleGifs=323]="NoMultipleGifs",c[c.InvalidMediaIds=324]="InvalidMediaIds",c[c.InvalidUrl=407]="InvalidUrl",c[c.TooManyTweetAttachments=386]="TooManyTweetAttachments",c[c.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",c[c.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",c[c.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",c[c.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",c[c.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",c[c.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",c[c.UnableToSendDM=151]="UnableToSendDM",c[c.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",c[c.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",c[c.DMTextTooLong=354]="DMTextTooLong",c[c.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",c[c.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",c[c.SuspendedApplication=416]="SuspendedApplication",c[c.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(Qf||(Qf={}));var ey;(function(c){c.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",c.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",c.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",c.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",c.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",c.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",c.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",c.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",c.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",c.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",c.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",c.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",c.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(ey||(ey={}));var L;(function(c){c.Connected="connected",c.ConnectError="connect error",c.ConnectionError="connection error",c.ConnectionClosed="connection closed",c.ConnectionLost="connection lost",c.ReconnectAttempt="reconnect attempt",c.Reconnected="reconnected",c.ReconnectError="reconnect error",c.ReconnectLimitExceeded="reconnect limit exceeded",c.DataKeepAlive="data keep-alive",c.Data="data event content",c.DataError="data twitter error",c.TweetParseError="data tweet parse error",c.Error="stream error"})(L||(L={}));class A0{constructor(c){this.value=c}}import*as R4 from"fs";var Fc={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function O8(c){let f={value:void 0,promise:c().then((R)=>{return f.value=R,R})};return f}function rh(c){if(Array.isArray(c))return c;return[c]}function fF(c){for(let f of Object.keys(c))if(c[f]===void 0)delete c[f]}function eh(c){return typeof c==="object"&&"errors"in c&&!("data"in c)}function G0(c){if(Array.isArray(c)&&c.length>1)return!0;return c.toString().includes(",")}var cF=new Set;function b8(c){if(typeof console>"u"||!console.warn||!Fc.deprecationWarnings)return;let f=`${c.instance}-${c.method}-${c.problem}`;if(cF.has(f))return;let R=`[twitter-api-v2] Deprecation warning: In ${c.instance}.${c.method}() call, ${c.problem}.
69
69
  ${c.resolution}.`;console.warn(R),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),cF.add(f)}import{EventEmitter as fJ}from"events";import{request as t7}from"https";import*as Xc from"zlib";import{EventEmitter as r7}from"events";class RF{constructor(c){this.requestData=c,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let c=this.requestData.url;return c.hostname+c.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(c){if(Fc.debug)Fc.logger.log("Request error:",c);return new h0("Request failed.",{request:this.req,error:c})}createPartialResponseError(c,f){let h=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(f)h+=" (connection abruptly closed)";else h+=" (parse error)";return new $0(h,{request:this.req,response:this.res,responseError:c,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(c){return c.map(({code:f,message:R})=>`${R} (Twitter code ${f})`).join(", ")}formatV2Error(c){return`${c.title}: ${c.detail} (see ${c.type})`}createResponseError({res:c,data:f,rateLimit:R,code:h}){var $;if(Fc.debug)Fc.logger.log(`Request failed with code ${h}, data:`,f),Fc.logger.log("Response headers:",c.headers);let H=`Request failed with code ${h}`;if(($=f===null||f===void 0?void 0:f.errors)===null||$===void 0?void 0:$.length){let A=f.errors;if(typeof A[0]==="object"&&"code"in A[0])H+=" - "+this.formatV1Errors(A);else H+=" - "+this.formatV2Error(f)}return new H0(H,{code:h,data:f,headers:c.headers,request:this.req,response:c,rateLimit:R})}getResponseDataStream(c){if(this.isCompressionDisabled())return c;let f=(c.headers["content-encoding"]||"identity").trim().toLowerCase();if(f==="br"){let R=Xc.createBrotliDecompress({flush:Xc.constants.BROTLI_OPERATION_FLUSH,finishFlush:Xc.constants.BROTLI_OPERATION_FLUSH});return c.pipe(R),R}if(f==="gzip"){let R=Xc.createGunzip({flush:Xc.constants.Z_SYNC_FLUSH,finishFlush:Xc.constants.Z_SYNC_FLUSH});return c.pipe(R),R}if(f==="deflate"){let R=Xc.createInflate({flush:Xc.constants.Z_SYNC_FLUSH,finishFlush:Xc.constants.Z_SYNC_FLUSH});return c.pipe(R),R}return c}detectResponseType(c){var f,R;if(((f=c.headers["content-type"])===null||f===void 0?void 0:f.includes("application/json"))||((R=c.headers["content-type"])===null||R===void 0?void 0:R.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(c){let f=this.responseData,R=this.requestData.forceParseMode||this.detectResponseType(c);if(R==="buffer")return Buffer.concat(f);else if(R==="text")return Buffer.concat(f).toString();else if(R==="json"){let h=Buffer.concat(f).toString();return h.length?JSON.parse(h):void 0}else if(R==="url"){let h=Buffer.concat(f).toString(),$={};for(let[H,A]of new URLSearchParams(h))$[H]=A;return $}else return}getRateLimitFromResponse(c){let f=void 0;if(c.headers["x-rate-limit-limit"]){if(f={limit:Number(c.headers["x-rate-limit-limit"]),remaining:Number(c.headers["x-rate-limit-remaining"]),reset:Number(c.headers["x-rate-limit-reset"])},c.headers["x-app-limit-24hour-limit"])f.day={limit:Number(c.headers["x-app-limit-24hour-limit"]),remaining:Number(c.headers["x-app-limit-24hour-remaining"]),reset:Number(c.headers["x-app-limit-24hour-reset"])};if(c.headers["x-user-limit-24hour-limit"])f.userDay={limit:Number(c.headers["x-user-limit-24hour-limit"]),remaining:Number(c.headers["x-user-limit-24hour-remaining"]),reset:Number(c.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(f)}return f}onSocketEventHandler(c,f,R){let h=this.onSocketCloseHandler.bind(this,c);R.on("close",h),f.on("complete",()=>R.off("close",h))}onSocketCloseHandler(c){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return c(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(c,f){var R,h;(h=(R=this.requestData).requestEventDebugHandler)===null||h===void 0||h.call(R,"request-error",{requestError:f}),this.requestErrorHandled=!0,c(this.createRequestError(f))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(c,f,R){this.res=R;let h=this.getResponseDataStream(R);if(h.on("data",($)=>this.responseData.push($)),h.on("end",this.onResponseEndHandler.bind(this,c,f)),h.on("close",this.onResponseCloseHandler.bind(this,c,f)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:R}),R.on("aborted",($)=>this.requestData.requestEventDebugHandler("response-aborted",{error:$})),R.on("error",($)=>this.requestData.requestEventDebugHandler("response-error",{error:$})),R.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),R.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(c,f){let R=this.getRateLimitFromResponse(this.res),h;try{h=this.getParsedResponse(this.res)}catch(H){f(this.createPartialResponseError(H,!1));return}let $=this.res.statusCode;if($>=400){f(this.createResponseError({data:h,res:this.res,rateLimit:R,code:$}));return}if(Fc.debug)Fc.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),Fc.logger.log("Response body:",h);c({data:h,headers:this.res.headers,rateLimit:R})}onResponseCloseHandler(c,f){let R=this.res;if(R.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(c,f)}catch(h){return f(this.createPartialResponseError(h,!0))}if(!R.complete)return f(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(c,f,R){if(R.statusCode<400){if(Fc.debug)Fc.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${R.statusCode} (starting stream)`);let $=this.getResponseDataStream(R);c({req:this.req,res:$,originalResponse:R,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},f,R)}debugRequest(){let c=this.requestData.url;if(Fc.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),c.search)Fc.logger.log("Request parameters:",[...c.searchParams.entries()].map(([f,R])=>`${f}: ${R}`));if(this.requestData.body)Fc.logger.log("Request body:",this.requestData.body)}buildRequest(){var c;let f=this.requestData.url,R=f.username?`${f.username}:${f.password}`:void 0,h=(c=this.requestData.options.headers)!==null&&c!==void 0?c:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")h["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")h["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")h["accept-encoding"]="deflate;q=1, *;q=0.1";if(Fc.debug)this.debugRequest();this.req=t7({...this.requestData.options,host:f.hostname,port:f.port||void 0,path:f.pathname+f.search,protocol:f.protocol,auth:R,headers:h})}registerRequestEventDebugHandlers(c){c.on("close",()=>this.requestData.requestEventDebugHandler("close")),c.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),c.on("socket",(f)=>{this.requestData.requestEventDebugHandler("socket",{socket:f}),f.on("error",(R)=>this.requestData.requestEventDebugHandler("socket-error",{socket:f,error:R})),f.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:f})),f.on("close",(R)=>this.requestData.requestEventDebugHandler("socket-close",{socket:f,withError:R})),f.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:f})),f.on("lookup",(...R)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:f,data:R})),f.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:f}))})}makeRequest(){return this.buildRequest(),new Promise((c,f)=>{let R=(A)=>{$.emit("complete"),c(A)},h=(A)=>{$.emit("complete"),f(A)},$=new r7,H=this.req;if(H.on("error",this.requestErrorHandler.bind(this,h)),H.on("socket",this.onSocketEventHandler.bind(this,h,$)),H.on("response",this.classicResponseHandler.bind(this,R,h)),this.requestData.options.timeout)H.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(H);if(this.requestData.body)H.write(this.requestData.body);H.end()})}async makeRequestAsStream(){let{req:c,res:f,requestData:R,originalResponse:h}=await this.makeRequestAndResolveWhenReady();return new c1(R,{req:c,res:f,originalResponse:h})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((c,f)=>{let R=this.req;if(R.on("error",this.requestErrorHandler.bind(this,f)),R.on("response",this.streamResponseHandler.bind(this,c,f)),this.requestData.body)R.write(this.requestData.body);R.end()})}}var y0=RF;import{EventEmitter as e7}from"events";class hF extends e7{constructor(c){super();this.stream=c,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),c.on(L.Data,this.onStreamData),c.on(L.ConnectionError,this.onStreamError),c.on(L.TweetParseError,this.onStreamError),c.on(L.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let c=this.stack;return this.stack=[],c}destroy(){this.removeAllListeners(),this.stream.off(L.Data,this.onStreamData),this.stream.off(L.ConnectionError,this.onStreamError),this.stream.off(L.TweetParseError,this.onStreamError),this.stream.off(L.ConnectionClosed,this.onStreamError)}emitEvent(c,f){this.emit("event",{type:c,payload:f})}onStreamError(c){this.emitEvent("error",c)}onStreamData(c){this.stack.push(c),this.emitEvent("data",c)}}var $F=hF;import{EventEmitter as cJ}from"events";class f1 extends cJ{constructor(){super(...arguments);this.currentMessage=""}push(c){this.currentMessage+=c,c=this.currentMessage;let f=c.length,R=0,h=0;while(h<f){if(c.slice(h,h+2)===`\r
70
70
  `){let $=c.slice(R,h);if(R=h+=2,!$.length)continue;try{let H=JSON.parse($);if(H){this.emit(Df.ParsedData,H);continue}}catch(H){this.emit(Df.ParseError,H)}}h++}this.currentMessage=c.slice(R,f)}reset(){this.currentMessage=""}}var Df;(function(c){c.ParsedData="parsed data",c.ParseError="parse error"})(Df||(Df={}));var HF=[5,15,30,60,90,120,180,300,600,900],RJ=(c)=>c>HF.length?901000:HF[c-1]*1000;class AF extends fJ{constructor(c,f){super();if(this.requestData=c,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=RJ,this.parser=new f1,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),f)this.req=f.req,this.res=f.res,this.originalResponse=f.originalResponse,this.initEventsFromRequest()}on(c,f){return super.on(c,f)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let c=(f)=>{this.emit(L.ConnectionError,f),this.emit(L.Error,{type:L.ConnectionError,error:f,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",c),this.res.on("error",c),this.res.on("close",()=>c(Error("Connection closed by Twitter."))),this.res.on("data",(f)=>{if(this.resetKeepAliveTimeout(),f.toString()===`\r
71
71
  `)return this.emit(L.DataKeepAlive);this.parser.push(f.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let c=this.requestData.payloadIsError;this.parser.on(Df.ParsedData,(f)=>{if(c&&c(f))this.emit(L.DataError,f),this.emit(L.Error,{type:L.DataError,error:f,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(L.Data,f)}),this.parser.on(Df.ParseError,(f)=>{this.emit(L.TweetParseError,f),this.emit(L.Error,{type:L.TweetParseError,error:f,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(L.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){if(this.keepAliveTimeout)clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0}unbindRetryTimeout(){if(this.retryTimeout)clearTimeout(this.retryTimeout),this.retryTimeout=void 0}closeWithoutEmit(){if(this.unbindTimeouts(),this.res)this.res.removeAllListeners(),this.res.destroy();if(this.req)this.req.removeAllListeners(),this.req.destroy()}close(){this.emit(L.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let f=await new y0(this.requestData).makeRequestAsStream(),R=this.eventNames();for(let h of R){let $=this.listeners(h);for(let H of $)f.on(h,H)}return f}async connect(c={}){if(typeof c.autoReconnect<"u")this.autoReconnect=c.autoReconnect;if(typeof c.autoReconnectRetries<"u")this.autoReconnectRetries=c.autoReconnectRetries==="unlimited"?1/0:c.autoReconnectRetries;if(typeof c.keepAliveTimeout<"u")this.keepAliveTimeoutMs=c.keepAliveTimeout==="disable"?1/0:c.keepAliveTimeout;if(typeof c.nextRetryTimeout<"u")this.nextRetryTimeout=c.nextRetryTimeout;this.unbindTimeouts();try{await this.reconnect()}catch(f){if(this.emit(L.ConnectError,0),this.emit(L.Error,{type:L.ConnectError,error:f,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,f);else throw f}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let c=!0;if(this.req)c=!1,this.closeWithoutEmit();let{req:f,res:R,originalResponse:h}=await new y0(this.requestData).makeRequestAndResolveWhenReady();this.req=f,this.res=R,this.originalResponse=h,this.emit(c?L.Connected:L.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(c=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(L.ConnectionClosed);return}if(c>=this.autoReconnectRetries){this.emit(L.ReconnectLimitExceeded),this.emit(L.ConnectionClosed);return}try{this.emit(L.ReconnectAttempt,c),await this.reconnect()}catch(f){this.emit(L.ReconnectError,c),this.emit(L.Error,{type:L.ReconnectError,error:f,message:`Reconnect error - ${c+1} attempts made yet.`}),this.makeAutoReconnectRetry(c,f)}}makeAutoReconnectRetry(c,f){let R=this.nextRetryTimeout(c+1,f);this.retryTimeout=setTimeout(()=>{this.onConnectionError(c+1)},R)}async*[Symbol.asyncIterator](){let c=new $F(this);try{while(!0){if(!this.req||this.req.aborted)throw Error("Connection closed");if(c.hasStack())yield*c.popStack();let{type:f,payload:R}=await c.nextEvent();if(f==="error")throw R}}finally{c.destroy()}}}var c1=AF;function GF(c){var f;if(!((f=c.clientSettings.plugins)===null||f===void 0?void 0:f.length))return!1;for(let R of c.clientSettings.plugins)if(R.onRequestError||R.onResponseError)return!0;return!1}async function yF(c,f,R,h){let $;if(h instanceof h0||h instanceof $0)$=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(c.url),params:c,computedParams:f,requestOptions:R,error:h});else if(h instanceof H0)$=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(c.url),params:c,computedParams:f,requestOptions:R,error:h});if($&&$ instanceof A0)return $.value;return Promise.reject(h)}import*as vF from"crypto";class Tc{constructor(c){this.nonceLength=32,this.consumerKeys=c.consumerKeys}static percentEncode(c){return encodeURIComponent(c).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(c,f){return vF.createHmac("sha1",f).update(c).digest("base64")}authorize(c,f={}){let R={oauth_consumer_key:this.consumerKeys.key,oauth_nonce:this.getNonce(),oauth_signature_method:"HMAC-SHA1",oauth_timestamp:this.getTimestamp(),oauth_version:"1.0"};if(f.key!==void 0)R.oauth_token=f.key;if(!c.data)c.data={};return R.oauth_signature=this.getSignature(c,f.secret,R),R}toHeader(c){let f=WF(c),R="OAuth ";for(let h of f){if(h.key.indexOf("oauth_")!==0)continue;R+=Tc.percentEncode(h.key)+'="'+Tc.percentEncode(h.value)+'",'}return{Authorization:R.slice(0,R.length-1)}}getNonce(){let f="";for(let R=0;R<this.nonceLength;R++)f+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.trunc(Math.random()*62)];return f}getTimestamp(){return Math.trunc(new Date().getTime()/1000)}getSignature(c,f,R){return this.hash(this.getBaseString(c,R),this.getSigningKey(f))}getSigningKey(c){return Tc.percentEncode(this.consumerKeys.secret)+"&"+Tc.percentEncode(c||"")}getBaseString(c,f){return c.method.toUpperCase()+"&"+Tc.percentEncode(this.getBaseUrl(c.url))+"&"+Tc.percentEncode(this.getParameterString(c,f))}getParameterString(c,f){let R=WF(HJ(FF(f,FF(c.data,$J(c.url))))),h="";for(let{key:$,value:H}of R)if(H&&Array.isArray(H)){H.sort();let A="";H.forEach((G,y)=>{if(A+=$+"="+G,y<H.length)A+="&"}),h+=A}else h+=$+"="+H+"&";return h.slice(0,h.length-1)}getBaseUrl(c){return c.split("?")[0]}}var F0=Tc;function FF(c,f){return{...c||{},...f||{}}}function WF(c){return Object.keys(c).sort().map((f)=>({key:f,value:c[f]}))}function hJ(c){let f=c.split("&"),R={};for(let h of f){let[$,H=""]=h.split("=");if(R[$]){if(!Array.isArray(R[$]))R[$]=[R[$]];R[$].push(decodeURIComponent(H))}else R[$]=decodeURIComponent(H)}return R}function $J(c){let f=c.split("?");if(f.length===1)return{};return hJ(f[1])}function HJ(c){let f={};for(let R in c){let h=c[R];if(h&&Array.isArray(h))h=h.map(($)=>Tc.percentEncode($));else h=Tc.percentEncode(h);f[Tc.percentEncode(R)]=h}return f}class uc{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...c){let f=c.map((R)=>R instanceof Buffer?R:Buffer.from(R));this._chunks.push(...f)}append(c,f,R){let h=f instanceof Buffer?f:f.toString(),$=this.getMultipartHeader(c,h,R);this.bodyAppend($,h,uc.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((c,f)=>c+f.length,this.getMultipartFooter().length)}getBuffer(){let c=[...this._chunks,this.getMultipartFooter()],f=Buffer.alloc(this.getLength()),R=0;for(let h of c)for(let $=0;$<h.length;R++,$++)f[R]=h[$];return f}getBoundary(){if(!this._boundary)this.generateBoundary();return this._boundary}generateBoundary(){let c="--------------------------";for(let f=0;f<24;f++)c+=Math.floor(Math.random()*10).toString(16);this._boundary=c}getMultipartHeader(c,f,R){if(!R)R=f instanceof Buffer?uc.DEFAULT_CONTENT_TYPE:"";let h={"Content-Disposition":["form-data",`name="${c}"`],"Content-Type":R},$="";for(let[H,A]of Object.entries(h)){if(!A.length)continue;$+=H+": "+rh(A).join("; ")+uc.LINE_BREAK}return"--"+this.getBoundary()+uc.LINE_BREAK+$+uc.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+uc.LINE_BREAK)}}uc.LINE_BREAK=`\r
@@ -73,4 +73,4 @@ ${c.resolution}.`;console.warn(R),console.warn("To disable this message, import
73
73
  `));return await this.put(f.data.upload_url,R,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),f}async complianceJobResult(c){let f=c;while(f.status!=="complete"){if(f.status==="expired"||f.status==="failed")throw Error("Job failed to be completed.");await new Promise((h)=>setTimeout(h,3500)),f=(await this.complianceJob(c.id)).data}return(await this.get(c.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split(`
74
74
  `).filter((h)=>h).map((h)=>JSON.parse(h))}async usage(c={}){return this.get("usage/tweets",c)}community(c,f={}){return this.get("communities/:id",f,{params:{id:c}})}searchCommunities(c,f={}){return this.get("communities/search",{query:c,...f})}}class UR extends WR{constructor(){super(...arguments);this._prefix=fR}get readOnly(){return this}}class YR extends vR{constructor(){super(...arguments);this._prefix=Gf}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new UR(this)}hideReply(c,f){return this.put("tweets/:id/hidden",{hidden:f},{params:{id:c}})}like(c,f){return this.post("users/:id/likes",{tweet_id:f},{params:{id:c}})}unlike(c,f){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:c,tweet_id:f}})}retweet(c,f){return this.post("users/:id/retweets",{tweet_id:f},{params:{id:c}})}unretweet(c,f){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:c,tweet_id:f}})}tweet(c,f={}){if(typeof c==="object")f=c;else f={text:c,...f};return this.post("tweets",f)}async uploadMedia(c,f,R=1048576){let h=f.media_category;if(!f.media_category){if(f.media_type.includes("gif"))h="tweet_gif";else if(f.media_type.includes("image"))h="tweet_image";else if(f.media_type.includes("video"))h="tweet_video"}let $={additional_owners:f.additional_owners,media_type:f.media_type,total_bytes:c.length,media_category:h},A=(await this.post("media/upload/initialize",$)).data.id,G=Math.ceil(c.length/R),y=new Uint8Array(c);for(let U=0;U<G;U++){let N=U*R,z=Math.min(N+R,c.length),Z=y.slice(N,z),j=Buffer.from(Z),V={segment_index:U,media:j};await this.post(`media/upload/${A}/append`,V,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${A}/finalize`)).data.processing_info)await this.waitForMediaProcessing(A);return A}async waitForMediaProcessing(c){var f;let h=(await this.get("media/upload",{command:"STATUS",media_id:c})).data.processing_info;if(!h)return;switch(h.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(f=h.error)===null||f===void 0?void 0:f.message}`);case"pending":case"in_progress":{let $=h===null||h===void 0?void 0:h.check_after_secs;if($&&$>0)await new Promise((H)=>setTimeout(H,$*1000)),await this.waitForMediaProcessing(c)}}}createMediaMetadata(c,f){return this.post("media/metadata",{id:c,metadata:f})}reply(c,f,R={}){var h;let $={in_reply_to_tweet_id:f,...(h=R.reply)!==null&&h!==void 0?h:{}};return this.post("tweets",{text:c,...R,reply:$})}quote(c,f,R={}){return this.tweet(c,{...R,quote_tweet_id:f})}async tweetThread(c){var f,R;let h=[];for(let $ of c){let H=h.length?h[h.length-1]:null,A={...typeof $==="string"?{text:$}:$},G=H?H.data.id:(f=A.reply)===null||f===void 0?void 0:f.in_reply_to_tweet_id,y=(R=A.text)!==null&&R!==void 0?R:"";if(G)h.push(await this.reply(y,G,A));else h.push(await this.tweet(y,A))}return h}deleteTweet(c){return this.delete("tweets/:id",void 0,{params:{id:c}})}async bookmark(c){let f=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:c},{params:{id:f.data.id}})}async deleteBookmark(c){let f=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:f.data.id,tweet_id:c}})}follow(c,f){return this.post("users/:id/following",{target_user_id:f},{params:{id:c}})}unfollow(c,f){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:c,target_user_id:f}})}block(c,f){return this.post("users/:id/blocking",{target_user_id:f},{params:{id:c}})}unblock(c,f){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:c,target_user_id:f}})}mute(c,f){return this.post("users/:id/muting",{target_user_id:f},{params:{id:c}})}unmute(c,f){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:c,target_user_id:f}})}createList(c){return this.post("lists",c)}updateList(c,f={}){return this.put("lists/:id",f,{params:{id:c}})}removeList(c){return this.delete("lists/:id",void 0,{params:{id:c}})}addListMember(c,f){return this.post("lists/:id/members",{user_id:f},{params:{id:c}})}removeListMember(c,f){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:c,user_id:f}})}subscribeToList(c,f){return this.post("users/:id/followed_lists",{list_id:f},{params:{id:c}})}unsubscribeOfList(c,f){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:c,list_id:f}})}pinList(c,f){return this.post("users/:id/pinned_lists",{list_id:f},{params:{id:c}})}unpinList(c,f){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:c,list_id:f}})}sendDmInConversation(c,f){return this.post("dm_conversations/:dm_conversation_id/messages",f,{params:{dm_conversation_id:c}})}sendDmToParticipant(c,f){return this.post("dm_conversations/with/:participant_id/messages",f,{params:{participant_id:c}})}createDmConversation(c){return this.post("dm_conversations",c)}}class zF extends UR{constructor(){super(...arguments);this._prefix=fR}get readWrite(){return this}}var SF=zF;class MF extends YR{constructor(){super(...arguments);this._prefix=Gf}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new SF(this)}}var BF=MF;class W0 extends Wf{get v1(){if(this._v1)return this._v1;return this._v1=new GR(this)}get v2(){if(this._v2)return this._v2;return this._v2=new vR(this)}async currentUser(c=!1){return await this.getCurrentUserObject(c)}async currentUserV2(c=!1){return await this.getCurrentUserV2Object(c)}search(c,f){return this.v2.search(c,f)}async generateAuthLink(c="oob",{authAccessType:f,linkMode:R="authenticate",forceLogin:h,screenName:$}={}){let H=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:c,x_auth_access_type:f}),A=`https://api.x.com/oauth/${R}?oauth_token=${encodeURIComponent(H.oauth_token)}`;if(h!==void 0)A+=`&force_login=${encodeURIComponent(h)}`;if($!==void 0)A+=`&screen_name=${encodeURIComponent($)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:A,oauthResult:H});return{url:A,...H}}async login(c){let f=this.getActiveTokens();if(f.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let R=await this.post("https://api.x.com/oauth/access_token",{oauth_token:f.accessToken,oauth_verifier:c}),h=new this.constructor({appKey:f.appKey,appSecret:f.appSecret,accessToken:R.oauth_token,accessSecret:R.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:R.oauth_token,accessSecret:R.oauth_token_secret,userId:R.user_id,screenName:R.screen_name,client:h}}async appLogin(){let c=this.getActiveTokens();if(c.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let R=await new this.constructor({username:c.appKey,password:c.appSecret},this._requestMaker.clientSettings).post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor(R.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(c,f={}){var R,h;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 $=(R=f.state)!==null&&R!==void 0?R:jf.generateRandomString(32),H=jf.getCodeVerifier(),A=jf.getCodeChallengeFromVerifier(H),G=(h=f.scope)!==null&&h!==void 0?h:"",y=Array.isArray(G)?G.join(" "):G,F=new URL("https://x.com/i/oauth2/authorize"),U={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:c,state:$,code_challenge:A,code_challenge_method:"s256",scope:y};xc.addQueryParamsToUrl(F,U);let N={url:F.toString(),state:$,codeVerifier:H,codeChallenge:A};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:N,redirectUri:c});return N}async loginWithOAuth2({code:c,codeVerifier:f,redirectUri:R}){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 h=await this.post("https://api.x.com/2/oauth2/token",{code:c,code_verifier:f,redirect_uri:R,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(h)}async refreshOAuth2Token(c){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 f=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:c,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(f)}async revokeOAuth2Token(c,f="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:c,token_type_hint:f})}parseOAuth2AccessTokenResult(c){let f=new this.constructor(c.access_token,this._requestMaker.clientSettings),R=c.scope.split(" ").filter((h)=>h);return{client:f,expiresIn:c.expires_in,accessToken:c.access_token,scope:R,refreshToken:c.refresh_token}}}class v0 extends W0{get v1(){if(this._v1)return this._v1;return this._v1=new yR(this)}get v2(){if(this._v2)return this._v2;return this._v2=new YR(this)}get readOnly(){return this}}class W1 extends Ic{constructor(){super(...arguments);this._prefix=RR}}class v1 extends W1{constructor(){super(...arguments);this._prefix=RR}get readOnly(){return this}}class U1 extends Ic{constructor(){super(...arguments);this._prefix=hR}}class Y1 extends U1{constructor(){super(...arguments);this._prefix=hR}get readOnly(){return this}}class XF extends Y1{constructor(){super(...arguments);this._prefix=hR}get readWrite(){return this}}var QF=XF;class DF extends v1{constructor(){super(...arguments);this._prefix=RR}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new QF(this)}}var jF=DF;class I4 extends v0{get v1(){if(this._v1)return this._v1;return this._v1=new A1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new BF(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new jF(this)}static getErrors(c){var f;if(typeof c!=="object")return[];if(!("data"in c))return[];return(f=c.data.errors)!==null&&f!==void 0?f:[]}static getProfileImageInSize(c,f){let R=c.split("/").pop(),h=["normal","bigger","mini"],$=c;for(let A of h)if(R.includes(`_${A}`)){$=c.replace(`_${A}`,"");break}if(f==="original")return $;let H=$.lastIndexOf(".");if(H!==-1){let A=$.slice(H+1);return $.slice(0,H)+"_"+f+"."+A}else return $+"_"+f}}var yJ={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class LF extends cR{config;client;oauthStates=new Map;constructor(c={}){super();this.config={...yJ,...c},this.client=new I4({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}getRedirectUrl(){let{url:c,codeVerifier:f,state:R}=this.client.generateOAuth2AuthLink(`${process.env.HOST_NAME}${this.config.redirectPath}`,{scope:this.config.scope});return this.oauthStates.set(R,{state:R,codeVerifier:f}),wF.to(c),c}async onCallback(c){let f=c.search.get("code"),R=c.search.get("state"),h=this.oauthStates.get(R);if(!h)throw Error("Invalid or expired OAuth state");let $=await this.client.loginWithOAuth2({code:f,codeVerifier:h.codeVerifier,redirectUri:`${process.env.HOST_NAME}${this.config.redirectPath}`});this.oauthStates.delete(R);let{data:H}=await $.client.v2.me({"user.fields":["name","username","entities"]}),{name:A,email:G,id:y="",username:F}=H??{};return{name:A,email:G,username:F,providerId:y}}}class xF extends l{kernel;jobs=[];constructor(c){super();this.kernel=c}boot(){}}class IF{name;cron;callback(){}onTick(){}onComplete(){}static exp(c){return c}}export{Lf as Z,U0 as _,P4 as $,ly as aa,W6 as ba,Yh as ca,Nh as da,v6 as ea,_h as fa,nh as ga,sy as ha,iy as ia,ky as ja,dy as ka,_y as la,oy as ma,oh as na,ah as oa,ay as pa,cR as qa,ty as ra,LF as sa,xF as ta,IF as ua};
75
75
 
76
- //# debugId=F8D7EE3F02ECBCDE64756E2164756E21
76
+ //# debugId=6E0E5328F68BFEFD64756E2164756E21