gemi 0.228.0 → 0.229.0

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.
Files changed (46) hide show
  1. package/dist/ai/index.js +1 -1
  2. package/dist/ai/providers/live.d.ts.map +1 -1
  3. package/dist/ai/testing/index.js +1 -1
  4. package/dist/chunk-0zakpsep.js.map +2 -2
  5. package/dist/{chunk-9jz5ts7h.js → chunk-2spm1f1j.js} +1 -1
  6. package/dist/{chunk-hhpme9te.js → chunk-5z7mzg77.js} +1 -1
  7. package/dist/{chunk-xv46emqt.js → chunk-c71dr883.js} +65 -51
  8. package/dist/{chunk-xv46emqt.js.map → chunk-c71dr883.js.map} +4 -4
  9. package/dist/{chunk-z0s09je5.js → chunk-enyer84t.js} +7 -7
  10. package/dist/{chunk-z0s09je5.js.map → chunk-enyer84t.js.map} +3 -3
  11. package/dist/{chunk-dpn78sq7.js → chunk-kpmp5hmc.js} +1 -1
  12. package/dist/chunk-nrcjn6v3.js +10 -0
  13. package/dist/{chunk-hddxvnh7.js.map → chunk-nrcjn6v3.js.map} +6 -6
  14. package/dist/{chunk-wyb6k943.js → chunk-yjn9fbw0.js} +2 -2
  15. package/dist/{chunk-wyb6k943.js.map → chunk-yjn9fbw0.js.map} +1 -1
  16. package/dist/{chunk-z6zvemqa.js → chunk-z2932q74.js} +1 -1
  17. package/dist/console/run.js +1 -1
  18. package/dist/kernel/index.js +1 -1
  19. package/dist/server/index.js +1 -1
  20. package/dist/services/cron/ScheduleServiceProvider.d.ts.map +1 -1
  21. package/dist/services/index.d.ts +1 -0
  22. package/dist/services/index.d.ts.map +1 -1
  23. package/dist/services/index.js +9 -9
  24. package/dist/services/index.js.map +4 -3
  25. package/dist/services/lock/DatabaseLockStore.d.ts +23 -3
  26. package/dist/services/lock/DatabaseLockStore.d.ts.map +1 -1
  27. package/dist/services/lock/LockStore.d.ts +14 -1
  28. package/dist/services/lock/LockStore.d.ts.map +1 -1
  29. package/dist/services/lock/MemoryLockStore.d.ts +3 -1
  30. package/dist/services/lock/MemoryLockStore.d.ts.map +1 -1
  31. package/dist/services/lock/lockStoreContract.d.ts.map +1 -1
  32. package/dist/services/queue/work.js +1 -1
  33. package/dist/services/rate-limiter/RateLimiterServiceProvider.d.ts +11 -0
  34. package/dist/services/rate-limiter/RateLimiterServiceProvider.d.ts.map +1 -1
  35. package/dist/services/rate-limiter/config.d.ts +4 -2
  36. package/dist/services/rate-limiter/config.d.ts.map +1 -1
  37. package/dist/services/rate-limiter/drivers/DatabaseRateLimiterDriver.d.ts +75 -0
  38. package/dist/services/rate-limiter/drivers/DatabaseRateLimiterDriver.d.ts.map +1 -0
  39. package/dist/services/rate-limiter/drivers/rateLimiterDriverContract.d.ts +15 -0
  40. package/dist/services/rate-limiter/drivers/rateLimiterDriverContract.d.ts.map +1 -0
  41. package/package.json +1 -1
  42. package/dist/chunk-hddxvnh7.js +0 -10
  43. /package/dist/{chunk-9jz5ts7h.js.map → chunk-2spm1f1j.js.map} +0 -0
  44. /package/dist/{chunk-hhpme9te.js.map → chunk-5z7mzg77.js.map} +0 -0
  45. /package/dist/{chunk-dpn78sq7.js.map → chunk-kpmp5hmc.js.map} +0 -0
  46. /package/dist/{chunk-z6zvemqa.js.map → chunk-z2932q74.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{rb as J$}from"../chunk-g6tqje74.js";import{$b as t9,Ab as g4,Bb as s1,Cb as F9,Db as L9,Eb as v9,Ib as I9,Jb as f9,Kb as y9,Lb as A9,Mb as g9,Nb as m9,Ob as c9,Pb as u9,Qb as p9,Rb as d9,Sb as l9,Tb as n4,Ub as v6,Vb as h,Wb as n9,Xb as i9,Yb as s9,Zb as o9,_b as a9,ac as r9,bc as e9,cc as W$,dc as Z$,ec as $$,fc as Q$,gc as Y$,hc as K$,sb as z9,tb as G9,ub as X9,vb as B9,wb as j9,xb as u4,yb as M9,zb as E4}from"../chunk-hddxvnh7.js";import{kc as d4}from"../chunk-9jz5ts7h.js";import"../chunk-kx5gycdv.js";import{de as D9,ee as H9,fe as N9,ge as U9,he as x9,ie as R9,je as O9,ke as _9,le as V9,me as k9,ne as C9,oe as T9,pe as P9,qe as b9,re as w9,se as q9}from"../chunk-dpn78sq7.js";import{te as S9}from"../chunk-a2y481gh.js";import{Ae as iZ,Be as sZ,Ce as oZ,De as aZ,Ee as tZ,Fe as rZ,Ge as eZ,He as W9,Ie as Z9,Je as $9,Ke as Q9,Le as Y9,Me as K9,Re as J9,ue as cZ,ve as uZ,we as pZ,xe as dZ,ye as lZ,ze as nZ}from"../chunk-xv46emqt.js";import{Se as h9,Te as E9}from"../chunk-xkrfxcm7.js";import"../chunk-7g3r55sj.js";import{$e as V6,$f as w8,Af as G8,Ag as jZ,Bf as X8,Bg as MZ,Cf as B8,Cg as FZ,Df as j8,Dg as LZ,Ef as Y6,Eg as DZ,Eh as yZ,Ff as M8,Fg as HZ,Fh as AZ,Gf as F8,Gg as NZ,Hf as L8,Hg as UZ,If as D8,Jf as H8,Mg as R,Ng as i,Og as xZ,Pg as SZ,Qg as RZ,Rg as OZ,Sg as _Z,Ug as VZ,Vg as kZ,Wg as CZ,Xg as TZ,Yf as T8,Zf as P8,Zg as PZ,_f as b8,af as e5,ag as q8,ah as bZ,bf as W8,bg as v8,bh as wZ,cf as Z8,ch as qZ,ef as $8,fh as vZ,ig as e8,jg as q6,kf as k6,kg as WZ,kh as IZ,lf as C4,mf as B6,nf as T4,of as P4,og as ZZ,oh as fZ,pg as $Z,qg as YZ,sf as f6,sh as i4,tf as y6,tg as KZ,th as z1,ug as JZ,vf as Q8,vg as zZ,wf as Y8,wg as GZ,xf as K8,yf as J8,yg as XZ,zf as z8,zg as BZ}from"../chunk-vsh9jck0.js";import"../chunk-jkhtybga.js";import"../chunk-mgvrfhy8.js";import{$i as C1,Ri as h4,Vi as j1,Xi as Y1,_i as _4,aj as p1,bj as N8,cj as U8,dj as x8,ej as S8,fj as R8,rj as mW,sj as cW,vj as O8,wj as _8,xi as k4,yi as O4,yj as d1,zi as k1}from"../chunk-vjqpcet2.js";import"../chunk-jqqyj6cr.js";import{Jj as V8,Kj as k8,Lj as C8}from"../chunk-30zs008n.js";import{Nj as q}from"../chunk-m4wagwhr.js";import{$j as p8,Vj as g8,Wj as m8,Xj as U,Yj as c8,Zj as b,_j as u8}from"../chunk-6xt7w9bb.js";import{fk as A8,gk as h8,hk as E8}from"../chunk-c5kd7eac.js";import"../chunk-9bjggtdt.js";import{Qk as QZ}from"../chunk-efnerp0c.js";import{Sk as I8,Tk as f8,Uk as y8,Vk as d8,Wk as l8,Xk as n8,Yk as i8,Zk as s8,_k as o8,dl as a8,el as t8,fl as r8}from"../chunk-0zakpsep.js";import"../chunk-djhr379j.js";import"../chunk-qgka1mvf.js";import"../chunk-znh1mbqs.js";import"../chunk-g0mxdh2x.js";import{am as w4,bm as hZ,cm as EZ,dm as gZ,fm as mZ}from"../chunk-qqe19gtm.js";import"../chunk-7ka1abkd.js";import{pm as C}from"../chunk-6fpjc2eg.js";import"../chunk-dqb257xv.js";import"../chunk-1v1ek1ey.js";import"../chunk-0dp6jvrg.js";import"../chunk-x8by5j7p.js";import"../chunk-kfcz4qa8.js";import{Um as u1}from"../chunk-30jcs49q.js";import{Buffer as K6}from"buffer";class J6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-65wnm25z.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof K6?$:$ instanceof Blob||$ instanceof File?K6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){_4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=p1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?O4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as z6}from"buffer";import{Readable as dW}from"stream";function V4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function lW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class G6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof z6?$:z6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=k4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(lW(V))throw new j1(await this.size({name:$,bucket:Q}));if(V4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await nW(X);if(x instanceof ReadableStream)x=p1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(V4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(V4(Y))return;throw Y}}}async function nW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return dW.toWeb(W.readableStreamBody);return null}function iW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class l1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var X6=1000,sW=60000,oW=`
2
+ import{rb as j$}from"../chunk-g6tqje74.js";import{$b as $$,Ab as m4,Bb as o1,Cb as U9,Db as x9,Eb as h9,Ib as E9,Jb as g9,Kb as m9,Lb as c9,Mb as d9,Nb as l9,Ob as n9,Pb as i9,Qb as s9,Rb as o9,Sb as a9,Tb as i4,Ub as A6,Vb as h,Wb as t9,Xb as r9,Yb as e9,Zb as W$,_b as Z$,ac as Q$,bc as Y$,cc as K$,dc as J$,ec as z$,fc as G$,gc as X$,hc as B$,sb as F9,tb as M9,ub as L9,vb as D9,wb as H9,xb as p4,yb as N9,zb as g4}from"../chunk-nrcjn6v3.js";import{kc as l4}from"../chunk-2spm1f1j.js";import"../chunk-kx5gycdv.js";import{de as S9,ee as R9,fe as O9,ge as _9,he as V9,ie as C9,je as T9,ke as P9,le as b9,me as q9,ne as w9,oe as v9,pe as I9,qe as f9,re as y9,se as A9}from"../chunk-kpmp5hmc.js";import{te as k9}from"../chunk-a2y481gh.js";import{Ae as rZ,Be as eZ,Ce as W9,De as Z9,Ee as $9,Fe as Q9,Ge as Y9,He as K9,Ie as J9,Je as z9,Ke as G9,Le as X9,Me as B9,Re as j9,ue as q4,ve as iZ,we as sZ,xe as oZ,ye as aZ,ze as tZ}from"../chunk-c71dr883.js";import{Se as u9,Te as p9}from"../chunk-xkrfxcm7.js";import"../chunk-7g3r55sj.js";import{$e as P6,$f as A8,Af as L8,Ag as NZ,Bf as D8,Bg as UZ,Cf as H8,Cg as xZ,Df as N8,Dg as SZ,Ef as K6,Eg as RZ,Eh as cZ,Ff as U8,Fg as OZ,Fh as uZ,Gf as x8,Gg as _Z,Hf as S8,Hg as VZ,If as R8,Jf as O8,Mg as R,Ng as i,Og as kZ,Pg as CZ,Qg as TZ,Rg as PZ,Sg as bZ,Ug as qZ,Vg as wZ,Wg as vZ,Xg as IZ,Yf as I8,Zf as f8,Zg as fZ,_f as y8,af as K8,ag as h8,ah as yZ,bf as J8,bg as E8,bh as AZ,cf as z8,ch as hZ,ef as G8,fh as EZ,ig as KZ,jg as y6,kf as b6,kg as JZ,kh as gZ,lf as T4,mf as j6,nf as T1,of as P4,og as zZ,oh as mZ,pg as GZ,qg as BZ,sf as E6,sh as s4,tf as g6,tg as jZ,th as z1,ug as FZ,vf as X8,vg as MZ,wf as B8,wg as LZ,xf as j8,yf as F8,yg as DZ,zf as M8,zg as HZ}from"../chunk-vsh9jck0.js";import"../chunk-jkhtybga.js";import"../chunk-mgvrfhy8.js";import{$i as C1,Ri as E4,Vi as j1,Xi as Y1,_i as V4,aj as d1,bj as _8,cj as V8,dj as k8,ej as C8,fj as T8,rj as dW,sj as lW,vj as P8,wj as b8,xi as C4,yi as _4,yj as l1,zi as k1}from"../chunk-vjqpcet2.js";import"../chunk-jqqyj6cr.js";import{Jj as q8,Kj as w8,Lj as v8,Mj as L6}from"../chunk-30zs008n.js";import{Nj as w}from"../chunk-m4wagwhr.js";import{$j as o8,Vj as l8,Wj as n8,Xj as U,Yj as i8,Zj as b,_j as s8}from"../chunk-6xt7w9bb.js";import{fk as u8,gk as p8,hk as d8}from"../chunk-c5kd7eac.js";import"../chunk-9bjggtdt.js";import{Qk as XZ}from"../chunk-efnerp0c.js";import{Sk as g8,Tk as m8,Uk as c8,Vk as a8,Wk as t8,Xk as r8,Yk as e8,Zk as WZ,_k as ZZ,dl as $Z,el as QZ,fl as YZ}from"../chunk-0zakpsep.js";import"../chunk-djhr379j.js";import"../chunk-qgka1mvf.js";import{Rl as M6}from"../chunk-znh1mbqs.js";import"../chunk-g0mxdh2x.js";import{am as w4,bm as pZ,cm as dZ,dm as lZ,fm as nZ}from"../chunk-qqe19gtm.js";import"../chunk-7ka1abkd.js";import{pm as C}from"../chunk-6fpjc2eg.js";import"../chunk-dqb257xv.js";import"../chunk-1v1ek1ey.js";import"../chunk-0dp6jvrg.js";import"../chunk-x8by5j7p.js";import"../chunk-kfcz4qa8.js";import{Um as p1}from"../chunk-30jcs49q.js";import{Buffer as J6}from"buffer";class z6 extends C1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-65wnm25z.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket??K,Q=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);Q=Q||void 0;let J=$ instanceof J6?$:$ instanceof Blob||$ instanceof File?J6.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:K,Key:Y,Body:J,ContentType:Q}),{abortSignal:Z}),Y}async delete(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!Z)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();try{await Y.send(new Q.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(K){if(K?.name==="NoSuchKey"||K?.$metadata?.httpStatusCode===404)return;throw K}}async*pages(W,{bucket:Z,signal:$}){let{sdk:Q,client:Y}=await this.connect(),K;do{$?.throwIfAborted();let J=await Y.send(new Q.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:K}),{abortSignal:$});yield(J.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),K=J.IsTruncated?J.NextContinuationToken:void 0}while(K)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){V4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect(),K=0;for await(let J of this.pages(W,{...Z,bucket:$})){if(J.length===0)continue;Z.signal?.throwIfAborted();let G=(await Y.send(new Q.DeleteObjectsCommand({Bucket:$,Delete:{Objects:J.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(G.length>0){let X=G[0];throw Error(`S3 could not delete ${G.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}K+=J.length}return K}async list(W){let{sdk:Z,client:$}=await this.connect();return await $.send(new Z.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=process.env.BUCKET_NAME,Q;if(typeof W==="string")Q=W;else $=W.bucket??$,Q=W.name;if(!Q)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect();Z?.throwIfAborted();let J=await K.send(new Y.GetObjectCommand({Bucket:$,Key:Q}),{abortSignal:Z}),z=d1(J.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":J.ContentType,"Content-Length":J.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":J.LastModified?.toUTCString()||"",ETag:J.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:Q,range:Y=null}=Z;if(!Q)throw Error("Object name has to be specified");let{sdk:K,client:J}=await this.connect(),z;try{z=await J.send(new K.GetObjectCommand({Bucket:$,Key:Q,Range:Y?_4(Y):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new j1(await this.size({name:Q,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new Y1(Q);throw j}let G=k1(z.ContentRange),X=Boolean(G)&&z.$metadata?.httpStatusCode===206,B=G?.total??z.ContentLength??0;return{body:z.Body.transformToWebStream(),start:G?.start??0,end:G?.end??B-1,total:B,partial:X,type:z.ContentType??"application/octet-stream",etag:z.ETag||void 0,lastModified:z.LastModified,name:Q}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:Q,client:Y}=await this.connect();try{return(await Y.send(new Q.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(K){if(K?.name==="NotFound"||K?.$metadata?.httpStatusCode===404)throw new Y1(Z);throw K}}}import{Buffer as G6}from"buffer";import{Readable as sW}from"stream";function k4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function oW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class X6 extends C1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let Z=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(Z)return W.BlobServiceClient.fromConnectionString(Z);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,Z){if(!W)throw Error("Object name has to be specified");let $=Z??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient($).getBlockBlobClient(W)}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,Q,Y,K;if(W instanceof Blob)$=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,Q=W.type;else $=W.body,Y=W.name,K=W.bucket,Q=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let J=$ instanceof G6?$:G6.from(await $.arrayBuffer()),z=await this.blob(Y,K);return Z?.throwIfAborted(),await z.uploadData(J,{blobHTTPHeaders:Q?{blobContentType:Q}:void 0,abortSignal:Z}),Y}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let Q=Z??this.config.container??process.env.BUCKET_NAME;if(!Q)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let K=(await this.serviceClient()).getContainerClient(Q);for await(let J of K.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:J.name,size:J.properties?.contentLength??0,lastModified:J.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,Q=(await this.serviceClient()).getContainerClient(Z),Y=[];for await(let K of Q.listBlobsFlat({prefix:W}))Y.push(K.name);return Y}async fetch(W,{signal:Z}={}){Z?.throwIfAborted();let $=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},Z);return new Response($.body,{headers:{"Content-Type":$.type,"Content-Length":String($.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":$.lastModified?.toUTCString()??"",ETag:$.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,Z){let{name:$,bucket:Q,range:Y=null}=W,K=await this.blob($,Q);Z?.throwIfAborted();let J,z,G=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&G){let V=await this.size({name:$,bucket:Q}),Q1=C4(Y,V);if(!Q1)throw new j1(V);J=Q1.start,z=Q1.length}else if(Y?.kind==="offset")J=Y.start,z=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await K.download(J,z,Z?{abortSignal:Z}:void 0)}catch(V){if(oW(V))throw new j1(await this.size({name:$,bucket:Q}));if(k4(V))throw new Y1($);throw V}let B=k1(X.contentRange),j=Boolean(B),D=B?.total??X.contentLength??0,x=await aW(X);if(x instanceof ReadableStream)x=d1(x,Z);return Z?.throwIfAborted(),{body:x,start:B?.start??0,end:B?.end??D-1,total:D,partial:j,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:$}}async size(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{return(await Q.getProperties()).contentLength??0}catch(Y){if(k4(Y))throw new Y1(Z);throw Y}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,Q=await this.blob(Z,$);try{await Q.delete()}catch(Y){if(k4(Y))return;throw Y}}}async function aW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return sW.toWeb(W.readableStreamBody);return null}function tW(W){return W}class b4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class n1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var B6=1000,rW=60000,eW=`
3
3
  local currentKey = KEYS[1]
4
4
  local previousKey = KEYS[2]
5
5
  local limit = tonumber(ARGV[1])
@@ -26,7 +26,7 @@ current = redis.call("INCRBY", currentKey, cost)
26
26
  redis.call("PEXPIRE", currentKey, window * 2)
27
27
 
28
28
  return {1, current, previous}
29
- `;class j6 extends T4{injectedClient;prefix;mode;fallback;timeout;onError;scriptSha=null;down=!1;probing=!1;lastProbeAt=0;seenConnected=new WeakSet;loggedAt=-1/0;failuresSinceLog=0;fallbacksSinceLog=0;constructor(W={}){super();this.injectedClient=W.client,this.prefix=W.prefix??"gemi:rl",this.mode=W.onRedisError??(W.failOpen===void 0?"memory":W.failOpen?"open":"closed"),this.fallback=W.fallback??new P4,this.timeout=W.timeout??250,this.onError=W.onError}async consume(W){let{key:Z,limit:$,window:Q}=W,Y=W.cost??1,K=Date.now(),J=C4(K,Q),z=K-J,G=J/Q;if(this.down)return this.probe(),this.degrade(W,K);try{let X=this.client;if(X.connected===!1&&this.seenConnected.has(X))throw new l1;let B=await this.withTimeout(this.run(X,[`${this.prefix}:${Z}:${G}`,`${this.prefix}:${Z}:${G-1}`],[String($),String(Q),String(z),String(Y)]),()=>{this.scriptSha=null});if(X.connected===!0)this.seenConnected.add(X);let[j,D,x]=(Array.isArray(B)?B:[]).map(Number);return B6({allowed:j===1,current:Number.isFinite(D)?D:0,previous:Number.isFinite(x)?x:0,now:K,elapsed:z,window:Q,limit:$,cost:Y})}catch(X){if(!this.down)this.down=!0,this.lastProbeAt=Date.now();return this.report(X),this.degrade(W,K)}}async degrade(W,Z){let{limit:$,window:Q}=W,Y=W.cost??1;if(this.fallbacksSinceLog+=1,this.mode==="memory")return await this.fallback.consume(W);if(this.mode==="closed")return{allowed:!1,limit:$,remaining:0,resetAt:Z+Q,retryAfter:Q};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-Y)),resetAt:C4(Z,Q)+Q,retryAfter:0}}probe(){let W=Date.now();if(this.probing||W-this.lastProbeAt<X6)return;this.probing=!0,this.lastProbeAt=W,(async()=>{let $=this.client;if($.connected===!1&&this.seenConnected.has($))throw new l1;if(await this.withTimeout($.send("PING",[]),void 0,this.timeout>0?this.timeout:X6),$.connected===!0)this.seenConnected.add($)})().then(()=>{if(this.probing=!1,this.down=!1,!this.onError)this.logRecovery()},($)=>{this.probing=!1;try{this.report($)}catch{}})}report(W){if(this.onError){this.onError(W);return}this.failuresSinceLog+=1;let Z=Date.now();if(Z-this.loggedAt<sW)return;let $=this.mode==="memory"?"counting in memory":this.mode==="open"?"admitting every request":"refusing every request",Q=this.loggedAt===-1/0?"":` Since the last report: ${this.failuresSinceLog} failures, ${this.fallbacksSinceLog} calls answered without Redis.`;console.error(`[gemi] RedisRateLimiter: Redis failed, ${$} until it answers again.${Q}`,W),this.loggedAt=Z,this.failuresSinceLog=0,this.fallbacksSinceLog=0}logRecovery(){console.info(`[gemi] RedisRateLimiter: Redis answers again; counting in Redis (${this.fallbacksSinceLog} calls answered without it since the last report).`),this.loggedAt=-1/0,this.failuresSinceLog=0,this.fallbacksSinceLog=0}withTimeout(W,Z,$=this.timeout){if(!($>0)||!Number.isFinite($))return W;let Q,Y=new Promise((K,J)=>{Q=setTimeout(()=>{Z?.(),J(new b4($))},$)});return W.catch(()=>{}),Promise.race([W,Y]).finally(()=>clearTimeout(Q))}get client(){if(this.injectedClient)return this.injectedClient;let W=C(),Z=W.bound(d1)?W.make(d1).client:void 0;if(!Z)throw Error("RedisRateLimiter could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisRateLimiter({ client }).");return Z}async run(W,Z,$){let Q=[String(Z.length),...Z,...$];try{return await W.send("EVALSHA",[await this.load(W),...Q])}catch(Y){if(!aW(Y))throw Y;return this.scriptSha=null,await W.send("EVALSHA",[await this.load(W),...Q])}}load(W){if(!this.scriptSha)this.scriptSha=Promise.resolve(W.send("SCRIPT",["LOAD",oW])).then(String).catch((Z)=>{throw this.scriptSha=null,Z});return this.scriptSha}}function aW(W){return String(W?.message??W).includes("NOSCRIPT")}function T1(W){let Z=/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/.exec(W);if(!Z)return{address:W.trim()};let[,$,Q]=Z;return $?{address:Q.trim(),displayName:$}:{address:Q.trim()}}function tW(W){if(W.contentType)return W.contentType;return Bun.file(W.filename).type.split(";")[0]||"application/octet-stream"}class q4 extends w4{config;provider="acs";supportsIdempotencyKey=!1;clientPromise=null;constructor(W={}){super();this.config=W}async client(){if(this.config.client)return this.config.client;return this.clientPromise??=(async()=>{let W;try{W=await import("@azure/communication-email")}catch{throw Error("AcsDriver requires the '@azure/communication-email' package. Install it with `bun add @azure/communication-email`, or pass a pre-built `client`.")}let Z=this.config.endpoint??process.env.AZURE_COMMUNICATION_ENDPOINT,$=this.config.connectionString??process.env.AZURE_COMMUNICATION_CONNECTION_STRING;if(Z){let Q=this.config.credential;if(!Q){let Y;try{Y=await import("@azure/identity")}catch{throw Error("AcsDriver with an `endpoint` and no `credential` requires the '@azure/identity' package (for DefaultAzureCredential). Install it with `bun add @azure/identity`.")}Q=new Y.DefaultAzureCredential}return new W.EmailClient(Z,Q)}if($)return new W.EmailClient($);throw Error("AcsDriver needs an endpoint (AZURE_COMMUNICATION_ENDPOINT, authenticated with managed identity), a connection string (AZURE_COMMUNICATION_CONNECTION_STRING), or a `client`.")})(),this.clientPromise.catch(()=>{this.clientPromise=null}),this.clientPromise}static toMessage(W){let Z={senderAddress:T1(W.from).address,content:{subject:W.subject,html:W.html,...W.text?{plainText:W.text}:{}},recipients:{to:W.to.map(T1),...W.cc?.length?{cc:W.cc.map(T1)}:{},...W.bcc?.length?{bcc:W.bcc.map(T1)}:{}}};if(W.replyTo?.length)Z.replyTo=W.replyTo.map(T1);if(W.headers&&Object.keys(W.headers).length)Z.headers=W.headers;if(W.attachments?.length)Z.attachments=W.attachments.map(($)=>({name:$.filename,contentType:tW($),contentInBase64:Buffer.from($.content).toString("base64")}));return Z}async send(W){return(await this.deliver(W)).ok}async deliver(W){if(W.scheduledAt)throw Error(`AcsDriver can't schedule a send (scheduledAt: "${W.scheduledAt}"): Azure Communication Services has no scheduled delivery. Send from a delayed job instead.`);let Z=q4.toMessage(W),$=await this.client(),Q=crypto.randomUUID();try{let Y=await $.beginSend(Z,{operationId:Q}),K=Y.getOperationState?.();if(K?.status==="failed"||K?.status==="canceled")return console.error(K.error),{ok:!1,id:Q,error:K.error};return{ok:!0,id:Y.getResult?.()?.id??Q}}catch(Y){return console.error(Y),{ok:!1,id:null,error:Y}}}}import{createHash as p4,randomBytes as K1,timingSafeEqual as rW}from"crypto";var n1=Object.freeze({"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"});function M6(W,Z){let $=W.client.name?A(W.client.name):"An application",Q=W.scopes.map((K)=>`<li><strong>${A(K.name)}</strong><br><span>${A(K.description)}</span></li>`).join(""),Y=Object.entries(W.form.fields).map(([K,J])=>`<input type="hidden" name="${A(K)}" value="${A(J)}">`).join("");return`<!doctype html>
29
+ `;class F6 extends T1{injectedClient;prefix;mode;fallback;timeout;onError;scriptSha=null;down=!1;probing=!1;lastProbeAt=0;seenConnected=new WeakSet;loggedAt=-1/0;failuresSinceLog=0;fallbacksSinceLog=0;constructor(W={}){super();this.injectedClient=W.client,this.prefix=W.prefix??"gemi:rl",this.mode=W.onRedisError??(W.failOpen===void 0?"memory":W.failOpen?"open":"closed"),this.fallback=W.fallback??new P4,this.timeout=W.timeout??250,this.onError=W.onError}async consume(W){let{key:Z,limit:$,window:Q}=W,Y=W.cost??1,K=Date.now(),J=T4(K,Q),z=K-J,G=J/Q;if(this.down)return this.probe(),this.degrade(W,K);try{let X=this.client;if(X.connected===!1&&this.seenConnected.has(X))throw new n1;let B=await this.withTimeout(this.run(X,[`${this.prefix}:${Z}:${G}`,`${this.prefix}:${Z}:${G-1}`],[String($),String(Q),String(z),String(Y)]),()=>{this.scriptSha=null});if(X.connected===!0)this.seenConnected.add(X);let[j,D,x]=(Array.isArray(B)?B:[]).map(Number);return j6({allowed:j===1,current:Number.isFinite(D)?D:0,previous:Number.isFinite(x)?x:0,now:K,elapsed:z,window:Q,limit:$,cost:Y})}catch(X){if(!this.down)this.down=!0,this.lastProbeAt=Date.now();return this.report(X),this.degrade(W,K)}}async degrade(W,Z){let{limit:$,window:Q}=W,Y=W.cost??1;if(this.fallbacksSinceLog+=1,this.mode==="memory")return await this.fallback.consume(W);if(this.mode==="closed")return{allowed:!1,limit:$,remaining:0,resetAt:Z+Q,retryAfter:Q};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-Y)),resetAt:T4(Z,Q)+Q,retryAfter:0}}probe(){let W=Date.now();if(this.probing||W-this.lastProbeAt<B6)return;this.probing=!0,this.lastProbeAt=W,(async()=>{let $=this.client;if($.connected===!1&&this.seenConnected.has($))throw new n1;if(await this.withTimeout($.send("PING",[]),void 0,this.timeout>0?this.timeout:B6),$.connected===!0)this.seenConnected.add($)})().then(()=>{if(this.probing=!1,this.down=!1,!this.onError)this.logRecovery()},($)=>{this.probing=!1;try{this.report($)}catch{}})}report(W){if(this.onError){this.onError(W);return}this.failuresSinceLog+=1;let Z=Date.now();if(Z-this.loggedAt<rW)return;let $=this.mode==="memory"?"counting in memory":this.mode==="open"?"admitting every request":"refusing every request",Q=this.loggedAt===-1/0?"":` Since the last report: ${this.failuresSinceLog} failures, ${this.fallbacksSinceLog} calls answered without Redis.`;console.error(`[gemi] RedisRateLimiter: Redis failed, ${$} until it answers again.${Q}`,W),this.loggedAt=Z,this.failuresSinceLog=0,this.fallbacksSinceLog=0}logRecovery(){console.info(`[gemi] RedisRateLimiter: Redis answers again; counting in Redis (${this.fallbacksSinceLog} calls answered without it since the last report).`),this.loggedAt=-1/0,this.failuresSinceLog=0,this.fallbacksSinceLog=0}withTimeout(W,Z,$=this.timeout){if(!($>0)||!Number.isFinite($))return W;let Q,Y=new Promise((K,J)=>{Q=setTimeout(()=>{Z?.(),J(new b4($))},$)});return W.catch(()=>{}),Promise.race([W,Y]).finally(()=>clearTimeout(Q))}get client(){if(this.injectedClient)return this.injectedClient;let W=C(),Z=W.bound(l1)?W.make(l1).client:void 0;if(!Z)throw Error("RedisRateLimiter could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisRateLimiter({ client }).");return Z}async run(W,Z,$){let Q=[String(Z.length),...Z,...$];try{return await W.send("EVALSHA",[await this.load(W),...Q])}catch(Y){if(!W5(Y))throw Y;return this.scriptSha=null,await W.send("EVALSHA",[await this.load(W),...Q])}}load(W){if(!this.scriptSha)this.scriptSha=Promise.resolve(W.send("SCRIPT",["LOAD",eW])).then(String).catch((Z)=>{throw this.scriptSha=null,Z});return this.scriptSha}}function W5(W){return String(W?.message??W).includes("NOSCRIPT")}import{createHash as Z5}from"crypto";var $5=150;class D6 extends T1{options;resolved;prefix;pruneEvery;pruneBatch;calls=0;pruning;constructor(W={}){super();this.options=W;if(this.prefix=W.prefix??"ratelimit:",this.prefix==="")throw Error("DatabaseRateLimiter needs a prefix: its rows share the locks table.");this.pruneEvery=Math.max(0,Math.floor(W.pruneEvery??1000)),this.pruneBatch=Math.max(1,Math.floor(W.pruneBatch??1000))}async prune(W=this.pruneBatch){let Z=this.store();return Z.pruneWindows?await Z.pruneWindows(this.prefix,W):0}async consume(W){let{limit:Z,window:$}=W,Q=Math.ceil(W.cost??1),Y=Date.now();if(Q>Z)return{allowed:!1,limit:Z,remaining:0,resetAt:Y+$,retryAfter:$};this.maybePrune();let K=await this.store().hit(this.nameOf(W.key),Z,$,Q),J=Y+K.resetInMs;if(!K.allowed)return{allowed:!1,limit:Z,remaining:0,resetAt:J,retryAfter:Math.max(1,K.resetInMs)};let z=K.count??Z;return{allowed:!0,limit:Z,remaining:Math.max(0,Math.floor(Z-z)),resetAt:J,retryAfter:0}}maybePrune(){if(this.pruneEvery===0||++this.calls%this.pruneEvery!==0||this.pruning)return;this.pruning=this.prune().catch((W)=>{let $={error:W instanceof Error?W.message:String(W)};try{L6.error("DatabaseRateLimiter could not prune ended windows",$)}catch{console.error("[gemi] DatabaseRateLimiter could not prune ended windows",W)}}).finally(()=>{this.pruning=void 0})}store(){if(this.resolved)return this.resolved;let{store:W,table:Z}=this.options;return this.resolved=typeof W==="function"?W():W??new q4(C().make(M6),{table:Z}),this.resolved}nameOf(W){let Z=`${this.prefix}${W}`;if(Z.length<=$5)return Z;return`${this.prefix}#${Z5("sha256").update(W).digest("hex")}`}}function P1(W){let Z=/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/.exec(W);if(!Z)return{address:W.trim()};let[,$,Q]=Z;return $?{address:Q.trim(),displayName:$}:{address:Q.trim()}}function Q5(W){if(W.contentType)return W.contentType;return Bun.file(W.filename).type.split(";")[0]||"application/octet-stream"}class v4 extends w4{config;provider="acs";supportsIdempotencyKey=!1;clientPromise=null;constructor(W={}){super();this.config=W}async client(){if(this.config.client)return this.config.client;return this.clientPromise??=(async()=>{let W;try{W=await import("@azure/communication-email")}catch{throw Error("AcsDriver requires the '@azure/communication-email' package. Install it with `bun add @azure/communication-email`, or pass a pre-built `client`.")}let Z=this.config.endpoint??process.env.AZURE_COMMUNICATION_ENDPOINT,$=this.config.connectionString??process.env.AZURE_COMMUNICATION_CONNECTION_STRING;if(Z){let Q=this.config.credential;if(!Q){let Y;try{Y=await import("@azure/identity")}catch{throw Error("AcsDriver with an `endpoint` and no `credential` requires the '@azure/identity' package (for DefaultAzureCredential). Install it with `bun add @azure/identity`.")}Q=new Y.DefaultAzureCredential}return new W.EmailClient(Z,Q)}if($)return new W.EmailClient($);throw Error("AcsDriver needs an endpoint (AZURE_COMMUNICATION_ENDPOINT, authenticated with managed identity), a connection string (AZURE_COMMUNICATION_CONNECTION_STRING), or a `client`.")})(),this.clientPromise.catch(()=>{this.clientPromise=null}),this.clientPromise}static toMessage(W){let Z={senderAddress:P1(W.from).address,content:{subject:W.subject,html:W.html,...W.text?{plainText:W.text}:{}},recipients:{to:W.to.map(P1),...W.cc?.length?{cc:W.cc.map(P1)}:{},...W.bcc?.length?{bcc:W.bcc.map(P1)}:{}}};if(W.replyTo?.length)Z.replyTo=W.replyTo.map(P1);if(W.headers&&Object.keys(W.headers).length)Z.headers=W.headers;if(W.attachments?.length)Z.attachments=W.attachments.map(($)=>({name:$.filename,contentType:Q5($),contentInBase64:Buffer.from($.content).toString("base64")}));return Z}async send(W){return(await this.deliver(W)).ok}async deliver(W){if(W.scheduledAt)throw Error(`AcsDriver can't schedule a send (scheduledAt: "${W.scheduledAt}"): Azure Communication Services has no scheduled delivery. Send from a delayed job instead.`);let Z=v4.toMessage(W),$=await this.client(),Q=crypto.randomUUID();try{let Y=await $.beginSend(Z,{operationId:Q}),K=Y.getOperationState?.();if(K?.status==="failed"||K?.status==="canceled")return console.error(K.error),{ok:!1,id:Q,error:K.error};return{ok:!0,id:Y.getResult?.()?.id??Q}}catch(Y){return console.error(Y),{ok:!1,id:null,error:Y}}}}import{createHash as d4,randomBytes as K1,timingSafeEqual as Y5}from"crypto";var i1=Object.freeze({"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"});function H6(W,Z){let $=W.client.name?A(W.client.name):"An application",Q=W.scopes.map((K)=>`<li><strong>${A(K.name)}</strong><br><span>${A(K.description)}</span></li>`).join(""),Y=Object.entries(W.form.fields).map(([K,J])=>`<input type="hidden" name="${A(K)}" value="${A(J)}">`).join("");return`<!doctype html>
30
30
  <html lang="en">
31
31
  <head>
32
32
  <meta charset="utf-8">
@@ -61,12 +61,12 @@ return {1, current, previous}
61
61
  </form>
62
62
  </main>
63
63
  </body>
64
- </html>`}function F6(W){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Authorization failed</title></head><body style="font-family: system-ui, sans-serif; padding: 24px"><h1 style="font-size: 1.2rem">This connection could not be authorized</h1><p>${A(W)}</p></body></html>`}function A(W){return W.replace(/[&<>"']/g,(Z)=>`&#${Z.charCodeAt(0)};`)}var v4="gmcp_at_",I4="gmcp_rt_",L6="gmcp_ac_",eW="gmcp_c_",W5="gmcp_cs_",f4="gemi.mcp.oauth.ticket.v1",D6="gemi.mcp.oauth.consent.v1",Z5=600000,H6=120000,m4=16384,$5={limit:20,window:3600},Q5={limit:60,window:60},i1=["none","client_secret_post","client_secret_basic"];class L extends Error{error;description;status;headers;constructor(W,Z,$=400,Q={}){super(Z);this.error=W;this.description=Z;this.status=$;this.headers=Q}}class C6{options;name="oauth";context;issuer;base;accessTtl;refreshTtl;constructor(W){this.options=W;let Z=W?.store;for(let $ of["createClient","findClient","saveCode","findCode","saveToken","findToken","use","revokeFamily"])if(typeof Z?.[$]!=="function")throw Error(`McpOAuthServer: store.${$} is missing. Use MemoryMcpOAuthStore, or implement McpOAuthStore.`);if(typeof W.findUser!=="function")throw Error("McpOAuthServer: findUser(id) is required: it loads the user a token was issued to.");if(W.consentPath!==void 0&&!/^\/[^/\\]/.test(W.consentPath))throw Error('McpOAuthServer: consentPath must be a path on this app, like "/oauth/consent".');this.accessTtl=N6("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=N6("refreshTokenTtl",W.refreshTokenTtl,2592000)}get store(){return this.options.store}boot(W){this.context=W;let Z=new URL(W.resource);this.issuer=Z.origin,this.base=`${Z.pathname}/oauth`}async resolve(W){let Z=u4(W);if(!Z?.startsWith(v4))return null;let $=await this.store.findToken(n(Z)),Q=(K)=>({ok:!1,error:"invalid_token",description:K});if(!$||$.kind!=="access")return Q("The access token is not valid.");if($.expiresAt<=Date.now())return Q("The access token expired.");if($.resource!==this.context.resource)return Q("The access token was not issued for this server.");let Y=await this.options.findUser($.userId);if(!Y)return Q("The access token is not valid.");return{ok:!0,principal:{user:Y,via:this.name,id:$.familyId,scopes:$.scopes,clientId:$.clientId}}}challenge(){let W=this.scopeNames().join(" ");return`Bearer resource_metadata="${this.resourceMetadataUrl()}", scope="${W}"`}async handle(W){let Z=new URL(W.url).pathname,Y={[`/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-protected-resource"]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-authorization-server"]:{methods:["GET"],cors:!0,run:()=>this.serverMetadata()},[`${this.base}/register`]:{methods:["POST"],cors:!0,run:()=>this.register(W)},[`${this.base}/authorize`]:{methods:["GET"],cors:!1,run:()=>this.authorize(W)},[`${this.base}/consent`]:{methods:["GET","POST"],cors:!1,run:()=>W.method==="POST"?this.decide(W):this.consentScreen(W)},[`${this.base}/token`]:{methods:["POST"],cors:!0,run:()=>this.token(W)},[`${this.base}/revoke`]:{methods:["POST"],cors:!0,run:()=>this.revoke(W)}}[Z];if(!Y)return null;if(Z===`${this.base}/register`&&this.options.registration===!1)return null;let K=Y.cors?Y5:{};if(W.method==="OPTIONS"&&Y.cors)return new Response(null,{status:204,headers:{...K,"Access-Control-Allow-Methods":Y.methods.join(", "),"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}});if(!Y.methods.includes(W.method))return new Response(null,{status:405,headers:{...K,Allow:Y.methods.join(", ")}});let J;try{J=await Y.run()}catch(z){if(!(z instanceof L))throw z;J=P1({error:z.error,error_description:z.description},z.status,z.headers)}for(let[z,G]of Object.entries(K))J.headers.set(z,G);return J}async consent(W,Z){if(!Z)return null;let $=s1(f4,"gat1",W);if(!$)return null;let Q=await this.store.findClient($.c);if(!Q||!Q.redirectUris.some((z)=>A4(z,$.r)))return null;let Y=String(Z.id),K=g4(D6,"gcs1",{t:U6(W),u:Y,exp:$.exp}),J=new Map(this.context.registry.scopes().map((z)=>[z.name,z.description]));return{client:{id:Q.clientId,name:Q.clientName,redirectHost:new URL($.r).host},scopes:$.s.map((z)=>({name:z,description:J.get(z)??z})),user:{id:Y,label:this.userLabel(Z)},form:{action:`${this.issuer}${this.base}/consent`,method:"POST",fields:{request:W,csrf:K}}}}resourceMetadata(){return P1({resource:this.context.resource,authorization_servers:[this.issuer],scopes_supported:this.scopeNames(),bearer_methods_supported:["header"]})}serverMetadata(){return P1({issuer:this.issuer,authorization_endpoint:`${this.issuer}${this.base}/authorize`,token_endpoint:`${this.issuer}${this.base}/token`,...this.options.registration===!1?{}:{registration_endpoint:`${this.issuer}${this.base}/register`},revocation_endpoint:`${this.issuer}${this.base}/revoke`,scopes_supported:this.scopeNames(),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],token_endpoint_auth_methods_supported:i1,revocation_endpoint_auth_methods_supported:i1,code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,client_id_metadata_document_supported:!1})}async register(W){let Z=this.options.registration||{},$=await E4(`mcp-oauth-register:${k6(new h4(W,{},"api",`${this.base}/register`))}`,Z.rateLimit??$5);if($!==null)throw new L("slow_down","Too many registrations from this address.",429,{"Retry-After":String($)});if(!/^application\/json\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new L("invalid_client_metadata","Send the client metadata as application/json.");let Q;try{Q=JSON.parse(await c4(W,m4))}catch{throw new L("invalid_client_metadata","The client metadata is not JSON, or is too large.")}if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new L("invalid_client_metadata","The client metadata must be a JSON object.");let Y=Q.redirect_uris;if(!Array.isArray(Y)||Y.length===0||Y.length>10)throw new L("invalid_redirect_uri","redirect_uris must list one to ten URIs.");for(let D of Y){let x=z5(D);if(x)throw new L("invalid_redirect_uri",`${String(D).slice(0,200)}: ${x}`);if(Z.allowRedirectUri&&Z.allowRedirectUri(new URL(D))!==!0)throw new L("invalid_redirect_uri",`${D}: this server does not accept it.`)}let K=Q.token_endpoint_auth_method??"client_secret_basic";if(!i1.includes(K))throw new L("invalid_client_metadata",`token_endpoint_auth_method must be one of ${i1.join(", ")}.`);let J=Q.grant_types??["authorization_code"];if(!Array.isArray(J)||J.some((D)=>D!=="authorization_code"&&D!=="refresh_token"))throw new L("invalid_client_metadata","grant_types may only be authorization_code and refresh_token.");let z=Q.response_types??["code"];if(!Array.isArray(z)||z.some((D)=>D!=="code"))throw new L("invalid_client_metadata","response_types may only be code.");let G=R6(Q.client_name,100,"client_name"),X=R6(Q.client_uri,512,"client_uri");if(X!==null&&!J5(X))throw new L("invalid_client_metadata","client_uri must be an https URL.");let B=K==="none"?null:`${W5}${K1(32).toString("base64url")}`,j={clientId:`${eW}${K1(16).toString("base64url")}`,clientSecretHash:B?n(B):null,tokenEndpointAuthMethod:K,redirectUris:[...Y],clientName:G,clientUri:X,createdAt:Date.now()};return await this.store.createClient(j),P1({client_id:j.clientId,client_id_issued_at:Math.floor(j.createdAt/1000),...B?{client_secret:B,client_secret_expires_at:0}:{},redirect_uris:j.redirectUris,token_endpoint_auth_method:K,grant_types:J,response_types:z,...G?{client_name:G}:{},...X?{client_uri:X}:{}},201)}async authorize(W){let Z=new URL(W.url).searchParams;for(let V of new Set(Z.keys()))if(Z.getAll(V).length>1)return p(`The parameter ${V} was sent more than once.`);let $=Z.get("client_id"),Q=$?await this.store.findClient($):null;if(!Q)return p("The application is not registered with this server.");let Y=Z.get("redirect_uri")??(Q.redirectUris.length===1?Q.redirectUris[0]:null);if(!Y||!Q.redirectUris.some((V)=>A4(V,Y)))return p("The redirect URI is not one the application registered.");let K=Z.get("state"),J=(V,Q1)=>this.redirectBack(Y,K,{error:V,error_description:Q1});if(Z.get("response_type")!=="code")return J("unsupported_response_type","Only response_type=code is supported.");let z=Z.get("code_challenge");if(Z.get("code_challenge_method")!=="S256"||!z||!/^[A-Za-z0-9_-]{43}$/.test(z))return J("invalid_request","PKCE is required: code_challenge with code_challenge_method=S256.");let G=Z.get("resource");if(G!==null&&!O6(G,this.context.resource))return J("invalid_target","The resource is not this server's.");if(K!==null&&K.length>2048)return J("invalid_request","state is too long.");let X=this.scopeNames(),B=Z.get("scope"),j=X;if(B!==null&&B.trim()!==""){if(j=[...new Set(B.split(" ").filter((V)=>X.includes(V)))],j.length===0)return J("invalid_scope","None of the requested scopes exist here.")}let D=g4(f4,"gat1",{c:Q.clientId,r:Y,s:j,cc:z,st:K,n:K1(16).toString("base64url"),exp:Date.now()+Z5}),x=this.options.consentPath??`${this.base}/consent`;return y4(`${this.issuer}${x}?request=${encodeURIComponent(D)}`,302)}async consentScreen(W){let Z=new URL(W.url).searchParams.get("request"),$=await this.sessionUser(W);if(!$){let Y=`${this.base}/consent?request=${encodeURIComponent(Z??"")}`,K=this.options.signInPath??C(z1).config.signInPath;return y4(`${K}${K.includes("?")?"&":"?"}redirect=${encodeURIComponent(Y)}`,302)}let Q=await this.consent(Z,$);if(!Q)return p("This authorization request has expired or is not valid. Start again from the application.");return new Response(M6(Q,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:n1})}async decide(W){let Z=W.headers.get("origin");if(!(Z!==null&&Z!=="null"?Z===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return p("This decision did not come from this site's consent page.",403);if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))return p("The decision must be a form post.");let Q;try{Q=new URLSearchParams(await c4(W,m4))}catch{return p("The decision is too large.")}let Y=Q.get("request"),K=s1(f4,"gat1",Y),J=s1(D6,"gcs1",Q.get("csrf")),z=await this.sessionUser(W);if(!K||!J||!z||J.t!==U6(Y)||J.u!==String(z.id))return p("This authorization request has expired or is not valid. Start again from the application.",403);let G=await this.store.findClient(K.c);if(!G||!G.redirectUris.some((B)=>A4(B,K.r)))return p("The application is not registered with this server.");if(!await this.store.use(`ticket:${K.n}`,K.exp))return p("This request was already answered. Start again from the application.");if(Q.get("decision")!=="allow")return this.redirectBack(K.r,K.st,{error:"access_denied",error_description:"The user denied the request."},303);let X=`${L6}${K1(32).toString("base64url")}`;return await this.store.saveCode({hash:n(X),clientId:G.clientId,userId:String(z.id),redirectUri:K.r,codeChallenge:K.cc,scopes:K.s,resource:this.context.resource,familyId:K1(16).toString("base64url"),expiresAt:Date.now()+H6}),this.redirectBack(K.r,K.st,{code:X},303)}async token(W){let Z=await S6(W),$=await this.authenticateClient(W,Z),Q=await E4(`mcp-oauth-token:${$.clientId}`,Q5);if(Q!==null)throw new L("slow_down","Too many token requests.",429,{"Retry-After":String(Q)});let Y=Z.get("resource");if(Y!==null&&!O6(Y,this.context.resource))throw new L("invalid_target","The resource is not this server's.");switch(Z.get("grant_type")){case"authorization_code":{let K=Z.get("code")??"",J=K.startsWith(L6)?await this.store.findCode(n(K)):null;if(!J||J.clientId!==$.clientId)throw new L("invalid_grant","The authorization code is not valid.");if(!await this.store.use(J.hash,J.expiresAt+H6))throw await this.store.revokeFamily(J.familyId),new L("invalid_grant","The authorization code was already used.");if(J.expiresAt<=Date.now())throw new L("invalid_grant","The authorization code expired.");if(Z.get("redirect_uri")!==null&&Z.get("redirect_uri")!==J.redirectUri)throw new L("invalid_grant","redirect_uri is not the one the code was issued to.");let z=Z.get("code_verifier");if(!z||!/^[A-Za-z0-9._~-]{43,128}$/.test(z)||!x6(K5(z),J.codeChallenge))throw new L("invalid_grant","The PKCE code_verifier does not match.");if(!await this.options.findUser(J.userId))throw new L("invalid_grant","The authorization code is not valid.");return await this.issue(J)}case"refresh_token":{let K=Z.get("refresh_token")??"",J=K.startsWith(I4)?await this.store.findToken(n(K)):null;if(!J||J.kind!=="refresh"||J.clientId!==$.clientId)throw new L("invalid_grant","The refresh token is not valid.");if(J.expiresAt<=Date.now())throw new L("invalid_grant","The refresh token expired.");if(!await this.store.use(J.hash,J.expiresAt))throw await this.store.revokeFamily(J.familyId),new L("invalid_grant","The refresh token was already used.");if(J.resource!==this.context.resource)throw new L("invalid_grant","The refresh token was not issued for this server.");let z=J.scopes,G=Z.get("scope");if(G!==null&&G.trim()!==""){let X=[...new Set(G.split(" ").filter(Boolean))];if(X.some((B)=>!J.scopes.includes(B)))throw new L("invalid_scope","A refresh can only narrow the scopes that were granted.");z=X}if(!await this.options.findUser(J.userId))throw new L("invalid_grant","The refresh token is not valid.");return await this.issue({...J,scopes:z})}default:throw new L("unsupported_grant_type","grant_type must be authorization_code or refresh_token.")}}async issue(W){let Z=Date.now(),$=this.scopeNames(),Q=W.scopes.filter((z)=>$.includes(z)),Y=`${v4}${K1(32).toString("base64url")}`,K=`${I4}${K1(32).toString("base64url")}`,J={clientId:W.clientId,userId:W.userId,scopes:Q,resource:W.resource,familyId:W.familyId};return await this.store.saveToken({...J,hash:n(Y),kind:"access",expiresAt:Z+this.accessTtl*1000}),await this.store.saveToken({...J,hash:n(K),kind:"refresh",expiresAt:Z+this.refreshTtl*1000}),P1({access_token:Y,token_type:"Bearer",expires_in:this.accessTtl,refresh_token:K,scope:Q.join(" ")})}async revoke(W){let Z=await S6(W),$=await this.authenticateClient(W,Z),Q=Z.get("token")??"";if(Q.startsWith(v4)||Q.startsWith(I4)){let Y=await this.store.findToken(n(Q));if(Y&&Y.clientId===$.clientId)await this.store.revokeFamily(Y.familyId)}return new Response(null,{status:200,headers:{"Cache-Control":"no-store"}})}async authenticateClient(W,Z){let $=/^Basic\s+([A-Za-z0-9+/=]+)$/i.exec(W.headers.get("authorization")??""),Q=Z.get("client_id"),Y=Z.get("client_secret");if($){let J=Buffer.from($[1],"base64").toString("utf8"),z=J.indexOf(":");if(z<0)throw J1(!0);let G=_6(J.slice(0,z));if(G===null)throw J1(!0);if(Q!==null&&Q!==G)throw J1(!0);if(Q=G,Y=_6(J.slice(z+1)),Y===null)throw J1(!0)}let K=Q?await this.store.findClient(Q):null;if(!K)throw J1(Boolean($));if(K.tokenEndpointAuthMethod==="none"){if(Y)throw J1(Boolean($));return K}if(!Y||!K.clientSecretHash||!x6(n(Y),K.clientSecretHash))throw J1(Boolean($));return K}redirectBack(W,Z,$,Q=302){let Y=new URL(W);for(let[K,J]of Object.entries($))Y.searchParams.set(K,J);if(Z!==null)Y.searchParams.set("state",Z);return Y.searchParams.set("iss",this.issuer),y4(Y.href,Q)}async sessionUser(W){let Z=new h4(W,{},"api",this.base).cookies;return await V6(C(z1),{cookies:Z,headers:{get:($)=>$.toLowerCase()==="user-agent"?W.headers.get("user-agent"):null}})}userLabel(W){if(this.options.userLabel)return this.options.userLabel(W);let Z=W;return String(Z.email??Z.name??Z.id)}scopeNames(){return this.context.registry.scopes().map((W)=>W.name)}resourceMetadataUrl(){return`${this.issuer}/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`}}var Y5={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function N6(W,Z,$){if(Z===void 0)return $;if(!Number.isInteger(Z)||Z<60)throw Error(`McpOAuthServer: ${W} must be a whole number of seconds, at least 60.`);return Z}function n(W){return p4("sha256").update(W).digest("hex")}function U6(W){return p4("sha256").update(W).digest("base64url")}function K5(W){return p4("sha256").update(W).digest("base64url")}function x6(W,Z){let $=Buffer.from(W),Q=Buffer.from(Z);return $.length===Q.length&&rW($,Q)}function P1(W,Z=200,$={}){return new Response(JSON.stringify(W),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache",...$}})}function y4(W,Z){return new Response(null,{status:Z,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function p(W,Z=400){return new Response(F6(W),{status:Z,headers:n1})}function J1(W){return new L("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function c4(W,Z){let $=Number(W.headers.get("content-length"));if(Number.isFinite($)&&$>Z)throw Error("too large");if(!W.body)return"";let Q=W.body.getReader(),Y=[],K=0;for(;;){let{done:J,value:z}=await Q.read();if(J)break;if(K+=z.byteLength,K>Z)throw await Q.cancel(),Error("too large");Y.push(z)}return Buffer.concat(Y).toString("utf8")}async function S6(W){if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new L("invalid_request","Send the request as application/x-www-form-urlencoded.");let Z;try{Z=new URLSearchParams(await c4(W,m4))}catch{throw new L("invalid_request","The request is too large.")}for(let $ of new Set(Z.keys()))if(Z.getAll($).length>1)throw new L("invalid_request",`${$} was sent more than once.`);return Z}function R6(W,Z,$){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>Z||G5(W))throw new L("invalid_client_metadata",`${$} must be text of at most ${Z} characters.`);return W}function J5(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function T6(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function z5(W){if(typeof W!=="string"||W.length>2048)return"not a URI";let Z;try{Z=new URL(W)}catch{return"not an absolute URI"}if(Z.hash||W.includes("#"))return"must not have a fragment";if(Z.username||Z.password)return"must not carry credentials";if(Z.protocol==="https:")return null;if(Z.protocol==="http:"&&T6(Z))return null;return"must be https, or http on a loopback address"}function A4(W,Z){if(W===Z)return!0;let $,Q;try{$=new URL(W),Q=new URL(Z)}catch{return!1}return $.protocol==="http:"&&Q.protocol==="http:"&&T6($)&&$.hostname===Q.hostname&&$.pathname===Q.pathname&&$.search===Q.search&&!Q.hash&&!Q.username&&!Q.password}function O6(W,Z){return W===Z||W===`${Z}/`}function G5(W){for(let Z=0;Z<W.length;Z++){let $=W.charCodeAt(Z);if($<32||$===127)return!0}return!1}function _6(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class P6{clients=new Map;codes=new Map;tokens=new Map;used=new Map;revoked=new Set;async createClient(W){this.clients.set(W.clientId,structuredClone(W))}async findClient(W){let Z=this.clients.get(W);return Z?structuredClone(Z):null}async saveCode(W){this.sweep(),this.codes.set(W.hash,structuredClone(W))}async findCode(W){let Z=this.codes.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async saveToken(W){this.sweep(),this.tokens.set(W.hash,structuredClone(W))}async findToken(W){let Z=this.tokens.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async use(W,Z){if(this.used.has(W))return!1;return this.used.set(W,Z),!0}async revokeFamily(W){this.revoked.add(W);for(let[Z,$]of this.tokens)if($.familyId===W)this.tokens.delete(Z);for(let[Z,$]of this.codes)if($.familyId===W)this.codes.delete(Z)}async families(W){let Z=new Map;for(let $ of this.tokens.values())if($.userId===W&&!this.revoked.has($.familyId)&&$.expiresAt>Date.now())Z.set($.familyId,{familyId:$.familyId,clientId:$.clientId,scopes:[...$.scopes]});return[...Z.values()]}sweep(W=Date.now()){for(let[Z,$]of this.codes)if($.expiresAt<=W)this.codes.delete(Z);for(let[Z,$]of this.tokens)if($.expiresAt<=W)this.tokens.delete(Z);for(let[Z,$]of this.used)if($<=W)this.used.delete(Z)}}class b6{clients;credentials;uses;usesModel;constructor(W){for(let[Z,$]of[["clients",["create","findUnique","findMany"]],["credentials",["create","findFirst","findMany","count","updateMany","deleteMany"]],["uses",["create","deleteMany"]]]){let Q=W?.[Z],Y=$.filter((K)=>typeof Q?.[K]!=="function");if(Y.length>0)throw Error(`PrismaMcpOAuthStore: models.${Z} must be a gemi ORM model or a Prisma delegate (it has no ${Y.join(", ")}()).`)}this.clients=W.clients,this.credentials=W.credentials,this.usesModel=W.uses,this.uses=new d4(W.uses)}async createClient(W){await this.clients.create({data:{clientId:W.clientId,clientSecretHash:W.clientSecretHash,tokenEndpointAuthMethod:W.tokenEndpointAuthMethod,redirectUris:[...W.redirectUris],clientName:W.clientName,clientUri:W.clientUri,createdAt:new Date(W.createdAt)}})}async findClient(W){let Z=await this.clients.findUnique({where:{clientId:W}});if(!Z)return null;return{clientId:Z.clientId,clientSecretHash:Z.clientSecretHash??null,tokenEndpointAuthMethod:Z.tokenEndpointAuthMethod,redirectUris:o1(Z.redirectUris),clientName:Z.clientName??null,clientUri:Z.clientUri??null,createdAt:a1(Z.createdAt)}}async saveCode(W){await this.credentials.create({data:{hash:W.hash,kind:"code",clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,redirectUri:W.redirectUri,codeChallenge:W.codeChallenge,expiresAt:new Date(W.expiresAt)}})}async findCode(W){let Z=await this.findLive(W,["code"]);if(!Z||Z.redirectUri==null||Z.codeChallenge==null)return null;return{hash:Z.hash,clientId:Z.clientId,userId:Z.userId,redirectUri:Z.redirectUri,codeChallenge:Z.codeChallenge,scopes:o1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:a1(Z.expiresAt)}}async saveToken(W){await this.credentials.create({data:{hash:W.hash,kind:W.kind,clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,expiresAt:new Date(W.expiresAt)}})}async findToken(W){let Z=await this.findLive(W,["access","refresh"]);if(!Z)return null;return{hash:Z.hash,kind:Z.kind,clientId:Z.clientId,userId:Z.userId,scopes:o1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:a1(Z.expiresAt)}}use(W,Z){return this.uses.consume(W,Z)}async revokeFamily(W){await this.credentials.updateMany({where:{familyId:W,revokedAt:null},data:{revokedAt:new Date}})}nonces(W={}){return new d4(this.usesModel,{prefix:W.prefix??"nonce:"})}async connectedApps(W,Z=new Date){let $=String(W),Q=await this.credentials.findMany({where:{userId:$,kind:"refresh",expiresAt:{gt:Z}},orderBy:{createdAt:"asc"}}),Y=await this.revokedFamilies({userId:$}),K=new Map;for(let X of Q){if(Y.has(X.familyId))continue;if(!K.has(X.familyId))K.set(X.familyId,X)}if(K.size===0)return[];let J=[...new Set([...K.values()].map((X)=>X.clientId))],z=await this.clients.findMany({where:{clientId:{in:J}}}),G=new Map(z.map((X)=>[X.clientId,X]));return[...K.values()].map((X)=>({familyId:X.familyId,clientId:X.clientId,clientName:G.get(X.clientId)?.clientName??null,clientUri:G.get(X.clientId)?.clientUri??null,scopes:o1(X.scopes),connectedAt:new Date(a1(X.createdAt))})).reverse()}async disconnect(W,Z){if(await this.credentials.count({where:{familyId:Z,userId:String(W)}})===0)return!1;return await this.revokeFamily(Z),!0}async revokeUser(W){await this.credentials.updateMany({where:{userId:String(W),revokedAt:null},data:{revokedAt:new Date}})}async prune(W=Date.now()){let Z=new Date(W-86400000),$=[...await this.revokedFamilies({expiresAt:{lt:Z}})],Q=$.length===0?[]:await this.credentials.findMany({where:{familyId:{in:$},expiresAt:{gte:Z}},select:{familyId:!0}}),Y=[...new Set(Q.map((K)=>K.familyId))];await this.credentials.deleteMany({where:{expiresAt:{lt:Z},...Y.length>0?{OR:[{revokedAt:null},{familyId:{notIn:Y}}]}:{}}}),await this.usesModel.deleteMany({where:{expiresAt:{lt:new Date(W)}}})}async findLive(W,Z){let $=await this.credentials.findFirst({where:{hash:W,kind:{in:Z},revokedAt:null}});if(!$)return null;return await this.credentials.count({where:{familyId:$.familyId,revokedAt:{not:null}}})>0?null:$}async revokedFamilies(W){let Z=await this.credentials.findMany({where:{...W,revokedAt:{not:null}},select:{familyId:!0}});return new Set(Z.map(($)=>$.familyId))}}function o1(W){return Array.isArray(W)?W.map(String):[]}function a1(W){return W instanceof Date?W.getTime():new Date(W).getTime()}class w1 extends h{application;previous;dispatched=[];static install(W){let Z=W.resolved(h)?W.make(h):void 0;if(Z instanceof w1)return Z;let $=new w1(W,Z);return W.instance(h,$),$}constructor(W,Z){super({listeners:[]});this.application=W;this.previous=Z}dispatch(W,Z){this.dispatched.push({event:W,args:Z})}async dispatchAndWait(W,Z){this.dispatched.push({event:W,args:Z})}restore(){if(this.previous){this.application.instance(h,this.previous);return}this.application.forget(h)}assertDispatched(W,Z){let $=b1(W);if(this.matching($,Z).length>0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} to have been dispatched. ${this.summary($,Z!==void 0)}`)}assertNotDispatched(W,Z){let $=b1(W),Q=this.matching($,Z);if(Q.length===0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} not to have been dispatched, but it was dispatched ${l4(Q.length)}: ${t1(Q)}.`)}assertDispatchedTimes(W,Z,$){let Q=b1(W),Y=this.matching(Q,$);if(Y.length===Z)return;throw Error(`Expected ${Q}${$?" matching the predicate":""} to have been dispatched ${l4(Z)}, but it was dispatched ${l4(Y.length)}. ${this.summary(Q,$!==void 0)}`)}assertNothingDispatched(){if(this.dispatched.length===0)return;let W=this.dispatched.length;throw Error(`Expected nothing to have been dispatched, but ${W} ${W===1?"event was":"events were"}: ${t1(this.dispatched)}.`)}matching(W,Z){return this.dispatched.filter(($)=>b1($.event.constructor)===W&&(Z===void 0||Z($.event)))}summary(W,Z){if(this.dispatched.length===0)return"Nothing was dispatched.";let $=this.matching(W);if(Z&&$.length>0)return`Dispatched ${W}: ${t1($)}.`;return`Dispatched: ${t1(this.dispatched)}.`}}function b1(W){return W.name}function l4(W){return`${W} ${W===1?"time":"times"}`}function t1(W){return W.map(X5).join(", ")}function X5(W){let Z=b1(W.event.constructor),$=W.args??Object.values({...W.event});return`${Z}(${$.map(B5).join(", ")})`}function B5(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class r1{static name="unset";static afterCommit=!1;static dispatch(...W){w6(this),C(h).dispatch(new this(...W),W)}static dispatchAndWait(...W){return w6(this),C(h).dispatchAndWait(new this(...W),W)}static fake(){return w1.install(j5())}}function j5(){try{return C()}catch(W){throw Error("Event.fake() needs a booted application. The fake works by replacing the container's EventManager with a recorder, so there has to be a "+"container to replace it in \u2014 and a dispatch finds the recorder the "+"same way, by resolving from that container. Boot the app's kernel in the test's setup: `const kernel = new Kernel(); kernel.boot()` is enough on its own, since that is the phase that publishes the application every dispatch outside a request resolves through.",{cause:W})}}function w6(W){if(W.name!=="unset"&&W.name!=="")return;throw Error("Cannot dispatch an event with no name. Add `static name` to this Event "+"subclass \u2014 the listener registry is keyed by that string, and by that "+"string alone, so an event without one cannot reach a listener.")}class I6 extends r1{constructor(){super();Object.defineProperty(this,n4,{value:!0,enumerable:!1})}broadcastAs(){return this.constructor.name}broadcastWith(){return}channel(W,...Z){return{topic:q6(W,Z[0]??{}),pattern:W}}}function A6(){try{let W=C();if(typeof W?.bound==="function"&&W.bound(z1))return W.make(z1).config.emailCode}catch{}return}function M5(){return f6(A6())}function F5(W){return y6(W,A6())}function L5(W){let Z=null;try{let K=C();if(typeof K?.bound==="function"&&K.bound(i4))Z=C(i4).resolver??null}catch{Z=null}if(Z)return Z.publicOrigin(W);let $=new URL(W.url),Q=W.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return`${Q==="http"||Q==="https"?Q:$.protocol.slice(0,-1)}://${$.host}`}function D5(W,Z){let $=typeof W==="string"?W.trim().replace(/\/+$/,""):"",Q=URL.canParse($)?new URL($):null;if(!Q||Q.protocol!=="http:"&&Q.protocol!=="https:"||Q.origin!==$)throw Error(`${Z}: resolve() returned origin ${JSON.stringify(W)}, which is not an http(s) origin such as https://example.com.`);return $}var h6=new WeakMap;function a(W,Z,$){if(!$.resolve)return Promise.resolve({clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.staticRedirectUri()});let Q=Z?.rawRequest;if(!Z||!Q)return Promise.resolve(null);let Y=h6.get(W);if(!Y)Y=new WeakMap,h6.set(W,Y);let K=Y.get(Q);if(K)return K;let J=$.resolve,z=(async()=>{let G=await J({req:Z,origin:L5(Q)});if(G===null||G===void 0)return null;let X=G.origin!==void 0?D5(G.origin,$.name):$.staticOrigin();return{clientId:G.clientId??$.clientId,clientSecret:G.clientSecret??$.clientSecret,redirectUri:`${X}${$.redirectPath}`}})();return Y.set(Q,z),z.catch(()=>Y.delete(Q)),z}var H5={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 https://www.googleapis.com/auth/userinfo.email",authorizationParams:{}};function N5(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class E6 extends i{config;constructor(W={}){super();this.config={...H5,...W}}redirectUri(){return`${q()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"GoogleOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>q()??""})}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GoogleOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}authorizationUrl(W,Z){let $=new URL("https://accounts.google.com/o/oauth2/v2/auth"),Q={include_granted_scopes:"true",...this.config.authorizationParams,scope:this.config.scope,response_type:"code",redirect_uri:W.redirectUri,client_id:W.clientId};if(Z)Q.state=Z.state,Q.code_challenge=Z.codeChallenge,Q.code_challenge_method=Z.codeChallengeMethod;for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new R("missing_code");let Q=this.config.resolve?await this.clientFor(W):this.staticClient();if(!Q)throw new R("unknown_provider");let Y=new URLSearchParams({code:$,client_id:Q.clientId,client_secret:Q.clientSecret,grant_type:"authorization_code",redirect_uri:Q.redirectUri});if(Z?.codeVerifier)Y.set("code_verifier",Z.codeVerifier);let K=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y.toString()}),J=await K.json().catch(()=>({}));if(!K.ok||typeof J?.access_token!=="string"||J.access_token==="")throw console.error("Google OAuth error: token exchange failed",J?.error??K.status),new R(N5(J?.error,"exchange_failed"));let G=await(await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${J.access_token}`}})).json().catch(()=>({}));if(typeof G.sub!=="string"||G.sub==="")return console.error("Google OAuth error: sub not found in user info response",G),{};if(!G.email)console.error("Google OAuth error: email not found in user info response",G);return{providerId:G.sub,name:G.name,email:G.email,emailVerified:G.email_verified===!0||G.email_verified==="true"}}}var U5="https://github.com/login/oauth/authorize",x5="https://github.com/login/oauth/access_token",g6="https://api.github.com";function S5(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class m6 extends i{config;constructor(W={}){super();this.config={clientId:process.env.GITHUB_CLIENT_ID??"",clientSecret:process.env.GITHUB_CLIENT_SECRET??"",redirectPath:"/auth/oauth/github/callback",scope:"read:user user:email",authorizationParams:{},...W}}redirectUri(){return`${q()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"GitHubOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>q()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GitHubOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(U5),Q={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,scope:this.config.scope,response_type:"code"};if(Z)Q.state=Z.state,Q.code_challenge=Z.codeChallenge,Q.code_challenge_method=Z.codeChallengeMethod;for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new R("missing_code");let Q=this.config.resolve?await this.clientFor(W):this.staticClient();if(!Q)throw new R("unknown_provider");let Y=new URLSearchParams({client_id:Q.clientId,client_secret:Q.clientSecret,code:$,redirect_uri:Q.redirectUri});if(Z?.codeVerifier)Y.set("code_verifier",Z.codeVerifier);let K=await fetch(x5,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:Y.toString()}),J=await K.json().catch(()=>({}));if(!K.ok||typeof J?.access_token!=="string"||J.access_token==="")throw console.error("GitHub OAuth error: token exchange failed",J?.error??K.status),new R(S5(J?.error,"exchange_failed"));let z={Accept:"application/vnd.github+json",Authorization:`Bearer ${J.access_token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"gemi"},G=await fetch(`${g6}/user`,{headers:z}),X=await G.json().catch(()=>({}));if(!G.ok||typeof X?.id!=="number"||!Number.isSafeInteger(X.id))return console.error("GitHub OAuth error: no user id in the /user response",G.status),{};let B=typeof X.login==="string"&&X.login!==""?X.login:void 0,j=typeof X.name==="string"&&X.name!==""?X.name:B,D=await this.primaryVerifiedEmail(z),x=typeof X.email==="string"&&X.email!==""?X.email:void 0;return{providerId:String(X.id),username:B,name:j,...D?{email:D,emailVerified:!0}:x?{email:x,emailVerified:!1}:{}}}async primaryVerifiedEmail(W){let Z=await fetch(`${g6}/user/emails`,{headers:W}).catch(()=>null);if(!Z?.ok){console.error("GitHub OAuth error: could not read /user/emails",Z?.status);return}let $=await Z.json().catch(()=>null);if(!Array.isArray($))return;let Q=$.find((Y)=>Y?.primary===!0&&Y.verified===!0);return typeof Q?.email==="string"&&Q.email!==""?Q.email:void 0}}var t="https://api.x.com/2/",M1="https://api.x.com/labs/2/",r="https://api.x.com/1.1/",s="https://upload.x.com/1.1/",c6="https://stream.x.com/1.1/",F1="https://ads-api.x.com/12/",L1="https://ads-api-sandbox.twitter.com/12/";class s4{constructor({realData:W,rateLimit:Z,instance:$,queryParams:Q,sharedParams:Y}){this._maxResultsWhenFetchLast=100,this._realData=W,this._rateLimit=Z,this._instance=$,this._queryParams=Q,this._sharedParams=Y}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(W){return this._instance.get(this.getEndpoint(),W,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(W,Z){return new this.constructor({realData:W.data,rateLimit:W.rateLimit,instance:this._instance,queryParams:Z,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(W){return{...W?{max_results:W}:{},...this._queryParams}}async next(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchNext(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!0),this}async fetchLast(W=1/0){let Z=this.getNextQueryParams(this._maxResultsWhenFetchLast),$=0;while($<W&&this._isRateLimitOk){let Q=await this.makeRequest(Z);if(await this.refreshInstanceFromResult(Q,!0),$+=this.getPageLengthFromRequest(Q),this.isFetchLastOver(Q))break;Z=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var W;return{...(W=this._rateLimit)!==null&&W!==void 0?W:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData),yield*$.getItemArray(),W=$}}async*fetchAndIterate(){for(let $ of this.getItemArray())yield[$,this];let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData);for(let Q of $.getItemArray())yield[Q,$];this._rateLimit=$._rateLimit,W=$}}}class o4 extends s4{async previous(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchPrevious(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!1),this}}var D1=s4;class O extends D1{getNextQueryParams(W){var Z;return{...this._queryParams,cursor:(Z=this._realData.next_cursor_str)!==null&&Z!==void 0?Z:this._realData.next_cursor,...W?{count:W}:{}}}isFetchLastOver(W){return!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!this.isNextCursorInvalid(W.next_cursor)||!this.isNextCursorInvalid(W.next_cursor_str)}isNextCursorInvalid(W){return W===void 0||W===0||W===-1||W==="0"||W==="-1"}}class a4 extends O{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.events.push(...$.events),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class t4 extends O{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.welcome_messages.push(...$.welcome_messages),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var N;(function(W){W.Jpeg="image/jpeg",W.Mp4="video/mp4",W.Mov="video/quicktime",W.Gif="image/gif",W.Png="image/png",W.Srt="text/plain",W.Webp="image/webp"})(N||(N={}));var e;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(e||(e={}));var q1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(q1||(q1={}));class e1 extends Error{constructor(){super(...arguments);this.error=!0}}class v1 extends e1{constructor(W,Z){super(W);this.type=q1.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class I1 extends e1{constructor(W,Z){super(W);this.type=q1.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}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 f1 extends e1{constructor(W,Z){super(W);if(this.type=q1.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z}),this.code=Z.code,this.headers=Z.headers,this.rateLimit=Z.rateLimit,Z.data&&typeof Z.data==="object"&&"error"in Z.data&&!Z.data.errors){let $={...Z.data};$.errors=[{code:G1.InternalError,message:$.error}],this.data=$}else this.data=Z.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...W){let Z=this.errors;if(!(Z===null||Z===void 0?void 0:Z.length))return!1;if("code"in Z[0])return Z.some((Y)=>W.includes(Y.code));let $=this.data;return W.includes($.type)}get errors(){var W;return(W=this.data)===null||W===void 0?void 0:W.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(G1.AuthTimestampInvalid,G1.AuthenticationFail,G1.BadAuthenticationData,G1.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var G1;(function(W){W[W.InvalidCoordinates=3]="InvalidCoordinates",W[W.NoLocationFound=13]="NoLocationFound",W[W.AuthenticationFail=32]="AuthenticationFail",W[W.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",W[W.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",W[W.AuthTimestampInvalid=135]="AuthTimestampInvalid",W[W.BadAuthenticationData=215]="BadAuthenticationData",W[W.NoUserMatch=17]="NoUserMatch",W[W.UserNotFound=50]="UserNotFound",W[W.ResourceNotFound=34]="ResourceNotFound",W[W.TweetNotFound=144]="TweetNotFound",W[W.TweetNotVisible=179]="TweetNotVisible",W[W.NotAllowedResource=220]="NotAllowedResource",W[W.MediaIdNotFound=325]="MediaIdNotFound",W[W.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",W[W.TweetViolatedRules=422]="TweetViolatedRules",W[W.TargetUserSuspended=63]="TargetUserSuspended",W[W.YouAreSuspended=64]="YouAreSuspended",W[W.AccountUpdateFailed=120]="AccountUpdateFailed",W[W.NoSelfSpamReport=36]="NoSelfSpamReport",W[W.NoSelfMute=271]="NoSelfMute",W[W.AccountLocked=326]="AccountLocked",W[W.RateLimitExceeded=88]="RateLimitExceeded",W[W.NoDMRightForApp=93]="NoDMRightForApp",W[W.OverCapacity=130]="OverCapacity",W[W.InternalError=131]="InternalError",W[W.TooManyFollowings=161]="TooManyFollowings",W[W.TweetLimitExceeded=185]="TweetLimitExceeded",W[W.DuplicatedTweet=187]="DuplicatedTweet",W[W.TooManySpamReports=205]="TooManySpamReports",W[W.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",W[W.NoWriteRightForApp=261]="NoWriteRightForApp",W[W.TweetActionsDisabled=425]="TweetActionsDisabled",W[W.TweetRepliesRestricted=433]="TweetRepliesRestricted",W[W.NamedParameterMissing=38]="NamedParameterMissing",W[W.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",W[W.TweetTextTooLong=186]="TweetTextTooLong",W[W.MissingUrlParameter=195]="MissingUrlParameter",W[W.NoMultipleGifs=323]="NoMultipleGifs",W[W.InvalidMediaIds=324]="InvalidMediaIds",W[W.InvalidUrl=407]="InvalidUrl",W[W.TooManyTweetAttachments=386]="TooManyTweetAttachments",W[W.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",W[W.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",W[W.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",W[W.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",W[W.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",W[W.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",W[W.UnableToSendDM=151]="UnableToSendDM",W[W.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",W[W.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",W[W.DMTextTooLong=354]="DMTextTooLong",W[W.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",W[W.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",W[W.SuspendedApplication=416]="SuspendedApplication",W[W.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(G1||(G1={}));var u6;(function(W){W.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",W.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",W.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",W.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",W.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",W.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",W.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",W.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",W.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",W.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",W.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",W.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",W.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(u6||(u6={}));var M;(function(W){W.Connected="connected",W.ConnectError="connect error",W.ConnectionError="connection error",W.ConnectionClosed="connection closed",W.ConnectionLost="connection lost",W.ReconnectAttempt="reconnect attempt",W.Reconnected="reconnected",W.ReconnectError="reconnect error",W.ReconnectLimitExceeded="reconnect limit exceeded",W.DataKeepAlive="data keep-alive",W.Data="data event content",W.DataError="data twitter error",W.TweetParseError="data tweet parse error",W.Error="stream error"})(M||(M={}));class y1{constructor(W){this.value=W}}import*as _0 from"fs";var k={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function r4(W){let Z={value:void 0,promise:W().then(($)=>{return Z.value=$,$})};return Z}function W4(W){if(Array.isArray(W))return W;return[W]}function d6(W){for(let Z of Object.keys(W))if(W[Z]===void 0)delete W[Z]}function Z4(W){return typeof W==="object"&&"errors"in W&&!("data"in W)}function A1(W){if(Array.isArray(W)&&W.length>1)return!0;return W.toString().includes(",")}var p6=new Set;function e4(W){if(typeof console>"u"||!console.warn||!k.deprecationWarnings)return;let Z=`${W.instance}-${W.method}-${W.problem}`;if(p6.has(Z))return;let $=`[twitter-api-v2] Deprecation warning: In ${W.instance}.${W.method}() call, ${W.problem}.
65
- ${W.resolution}.`;console.warn($),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),p6.add(Z)}import{EventEmitter as k5}from"events";import{request as R5}from"https";import*as P from"zlib";import{EventEmitter as O5}from"events";class l6{constructor(W){this.requestData=W,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let W=this.requestData.url;return W.hostname+W.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(W){if(k.debug)k.logger.log("Request error:",W);return new v1("Request failed.",{request:this.req,error:W})}createPartialResponseError(W,Z){let Q=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(Z)Q+=" (connection abruptly closed)";else Q+=" (parse error)";return new I1(Q,{request:this.req,response:this.res,responseError:W,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(W){return W.map(({code:Z,message:$})=>`${$} (Twitter code ${Z})`).join(", ")}formatV2Error(W){return`${W.title}: ${W.detail} (see ${W.type})`}createResponseError({res:W,data:Z,rateLimit:$,code:Q}){var Y;if(k.debug)k.logger.log(`Request failed with code ${Q}, data:`,Z),k.logger.log("Response headers:",W.headers);let K=`Request failed with code ${Q}`;if((Y=Z===null||Z===void 0?void 0:Z.errors)===null||Y===void 0?void 0:Y.length){let J=Z.errors;if(typeof J[0]==="object"&&"code"in J[0])K+=" - "+this.formatV1Errors(J);else K+=" - "+this.formatV2Error(Z)}return new f1(K,{code:Q,data:Z,headers:W.headers,request:this.req,response:W,rateLimit:$})}getResponseDataStream(W){if(this.isCompressionDisabled())return W;let Z=(W.headers["content-encoding"]||"identity").trim().toLowerCase();if(Z==="br"){let $=P.createBrotliDecompress({flush:P.constants.BROTLI_OPERATION_FLUSH,finishFlush:P.constants.BROTLI_OPERATION_FLUSH});return W.pipe($),$}if(Z==="gzip"){let $=P.createGunzip({flush:P.constants.Z_SYNC_FLUSH,finishFlush:P.constants.Z_SYNC_FLUSH});return W.pipe($),$}if(Z==="deflate"){let $=P.createInflate({flush:P.constants.Z_SYNC_FLUSH,finishFlush:P.constants.Z_SYNC_FLUSH});return W.pipe($),$}return W}detectResponseType(W){var Z,$;if(((Z=W.headers["content-type"])===null||Z===void 0?void 0:Z.includes("application/json"))||(($=W.headers["content-type"])===null||$===void 0?void 0:$.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(W){let Z=this.responseData,$=this.requestData.forceParseMode||this.detectResponseType(W);if($==="buffer")return Buffer.concat(Z);else if($==="text")return Buffer.concat(Z).toString();else if($==="json"){let Q=Buffer.concat(Z).toString();return Q.length?JSON.parse(Q):void 0}else if($==="url"){let Q=Buffer.concat(Z).toString(),Y={};for(let[K,J]of new URLSearchParams(Q))Y[K]=J;return Y}else return}getRateLimitFromResponse(W){let Z=void 0;if(W.headers["x-rate-limit-limit"]){if(Z={limit:Number(W.headers["x-rate-limit-limit"]),remaining:Number(W.headers["x-rate-limit-remaining"]),reset:Number(W.headers["x-rate-limit-reset"])},W.headers["x-app-limit-24hour-limit"])Z.day={limit:Number(W.headers["x-app-limit-24hour-limit"]),remaining:Number(W.headers["x-app-limit-24hour-remaining"]),reset:Number(W.headers["x-app-limit-24hour-reset"])};if(W.headers["x-user-limit-24hour-limit"])Z.userDay={limit:Number(W.headers["x-user-limit-24hour-limit"]),remaining:Number(W.headers["x-user-limit-24hour-remaining"]),reset:Number(W.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(Z)}return Z}onSocketEventHandler(W,Z,$){let Q=this.onSocketCloseHandler.bind(this,W);$.on("close",Q),Z.on("complete",()=>$.off("close",Q))}onSocketCloseHandler(W){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return W(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(W,Z){var $,Q;(Q=($=this.requestData).requestEventDebugHandler)===null||Q===void 0||Q.call($,"request-error",{requestError:Z}),this.requestErrorHandled=!0,W(this.createRequestError(Z))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(W,Z,$){this.res=$;let Q=this.getResponseDataStream($);if(Q.on("data",(Y)=>this.responseData.push(Y)),Q.on("end",this.onResponseEndHandler.bind(this,W,Z)),Q.on("close",this.onResponseCloseHandler.bind(this,W,Z)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:$}),$.on("aborted",(Y)=>this.requestData.requestEventDebugHandler("response-aborted",{error:Y})),$.on("error",(Y)=>this.requestData.requestEventDebugHandler("response-error",{error:Y})),$.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),$.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(W,Z){let $=this.getRateLimitFromResponse(this.res),Q;try{Q=this.getParsedResponse(this.res)}catch(K){Z(this.createPartialResponseError(K,!1));return}let Y=this.res.statusCode;if(Y>=400){Z(this.createResponseError({data:Q,res:this.res,rateLimit:$,code:Y}));return}if(k.debug)k.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),k.logger.log("Response body:",Q);W({data:Q,headers:this.res.headers,rateLimit:$})}onResponseCloseHandler(W,Z){let $=this.res;if($.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(W,Z)}catch(Q){return Z(this.createPartialResponseError(Q,!0))}if(!$.complete)return Z(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(W,Z,$){if($.statusCode<400){if(k.debug)k.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${$.statusCode} (starting stream)`);let Y=this.getResponseDataStream($);W({req:this.req,res:Y,originalResponse:$,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},Z,$)}debugRequest(){let W=this.requestData.url;if(k.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),W.search)k.logger.log("Request parameters:",[...W.searchParams.entries()].map(([Z,$])=>`${Z}: ${$}`));if(this.requestData.body)k.logger.log("Request body:",this.requestData.body)}buildRequest(){var W;let Z=this.requestData.url,$=Z.username?`${Z.username}:${Z.password}`:void 0,Q=(W=this.requestData.options.headers)!==null&&W!==void 0?W:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")Q["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")Q["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")Q["accept-encoding"]="deflate;q=1, *;q=0.1";if(k.debug)this.debugRequest();this.req=R5({...this.requestData.options,host:Z.hostname,port:Z.port||void 0,path:Z.pathname+Z.search,protocol:Z.protocol,auth:$,headers:Q})}registerRequestEventDebugHandlers(W){W.on("close",()=>this.requestData.requestEventDebugHandler("close")),W.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),W.on("socket",(Z)=>{this.requestData.requestEventDebugHandler("socket",{socket:Z}),Z.on("error",($)=>this.requestData.requestEventDebugHandler("socket-error",{socket:Z,error:$})),Z.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:Z})),Z.on("close",($)=>this.requestData.requestEventDebugHandler("socket-close",{socket:Z,withError:$})),Z.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:Z})),Z.on("lookup",(...$)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:Z,data:$})),Z.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:Z}))})}makeRequest(){return this.buildRequest(),new Promise((W,Z)=>{let $=(J)=>{Y.emit("complete"),W(J)},Q=(J)=>{Y.emit("complete"),Z(J)},Y=new O5,K=this.req;if(K.on("error",this.requestErrorHandler.bind(this,Q)),K.on("socket",this.onSocketEventHandler.bind(this,Q,Y)),K.on("response",this.classicResponseHandler.bind(this,$,Q)),this.requestData.options.timeout)K.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(K);if(this.requestData.body)K.write(this.requestData.body);K.end()})}async makeRequestAsStream(){let{req:W,res:Z,requestData:$,originalResponse:Q}=await this.makeRequestAndResolveWhenReady();return new $4($,{req:W,res:Z,originalResponse:Q})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((W,Z)=>{let $=this.req;if($.on("error",this.requestErrorHandler.bind(this,Z)),$.on("response",this.streamResponseHandler.bind(this,W,Z)),this.requestData.body)$.write(this.requestData.body);$.end()})}}var h1=l6;import{EventEmitter as _5}from"events";class n6 extends _5{constructor(W){super();this.stream=W,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),W.on(M.Data,this.onStreamData),W.on(M.ConnectionError,this.onStreamError),W.on(M.TweetParseError,this.onStreamError),W.on(M.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let W=this.stack;return this.stack=[],W}destroy(){this.removeAllListeners(),this.stream.off(M.Data,this.onStreamData),this.stream.off(M.ConnectionError,this.onStreamError),this.stream.off(M.TweetParseError,this.onStreamError),this.stream.off(M.ConnectionClosed,this.onStreamError)}emitEvent(W,Z){this.emit("event",{type:W,payload:Z})}onStreamError(W){this.emitEvent("error",W)}onStreamData(W){this.stack.push(W),this.emitEvent("data",W)}}var i6=n6;import{EventEmitter as V5}from"events";class Q4 extends V5{constructor(){super(...arguments);this.currentMessage=""}push(W){this.currentMessage+=W,W=this.currentMessage;let Z=W.length,$=0,Q=0;while(Q<Z){if(W.slice(Q,Q+2)===`\r
66
- `){let Y=W.slice($,Q);if($=Q+=2,!Y.length)continue;try{let K=JSON.parse(Y);if(K){this.emit(X1.ParsedData,K);continue}}catch(K){this.emit(X1.ParseError,K)}}Q++}this.currentMessage=W.slice($,Z)}reset(){this.currentMessage=""}}var X1;(function(W){W.ParsedData="parsed data",W.ParseError="parse error"})(X1||(X1={}));var s6=[5,15,30,60,90,120,180,300,600,900],C5=(W)=>W>s6.length?901000:s6[W-1]*1000;class o6 extends k5{constructor(W,Z){super();if(this.requestData=W,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=C5,this.parser=new Q4,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),Z)this.req=Z.req,this.res=Z.res,this.originalResponse=Z.originalResponse,this.initEventsFromRequest()}on(W,Z){return super.on(W,Z)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let W=(Z)=>{this.emit(M.ConnectionError,Z),this.emit(M.Error,{type:M.ConnectionError,error:Z,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",W),this.res.on("error",W),this.res.on("close",()=>W(Error("Connection closed by Twitter."))),this.res.on("data",(Z)=>{if(this.resetKeepAliveTimeout(),Z.toString()===`\r
67
- `)return this.emit(M.DataKeepAlive);this.parser.push(Z.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let W=this.requestData.payloadIsError;this.parser.on(X1.ParsedData,(Z)=>{if(W&&W(Z))this.emit(M.DataError,Z),this.emit(M.Error,{type:M.DataError,error:Z,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(M.Data,Z)}),this.parser.on(X1.ParseError,(Z)=>{this.emit(M.TweetParseError,Z),this.emit(M.Error,{type:M.TweetParseError,error:Z,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(M.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(M.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let Z=await new h1(this.requestData).makeRequestAsStream(),$=this.eventNames();for(let Q of $){let Y=this.listeners(Q);for(let K of Y)Z.on(Q,K)}return Z}async connect(W={}){if(typeof W.autoReconnect<"u")this.autoReconnect=W.autoReconnect;if(typeof W.autoReconnectRetries<"u")this.autoReconnectRetries=W.autoReconnectRetries==="unlimited"?1/0:W.autoReconnectRetries;if(typeof W.keepAliveTimeout<"u")this.keepAliveTimeoutMs=W.keepAliveTimeout==="disable"?1/0:W.keepAliveTimeout;if(typeof W.nextRetryTimeout<"u")this.nextRetryTimeout=W.nextRetryTimeout;this.unbindTimeouts();try{await this.reconnect()}catch(Z){if(this.emit(M.ConnectError,0),this.emit(M.Error,{type:M.ConnectError,error:Z,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,Z);else throw Z}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let W=!0;if(this.req)W=!1,this.closeWithoutEmit();let{req:Z,res:$,originalResponse:Q}=await new h1(this.requestData).makeRequestAndResolveWhenReady();this.req=Z,this.res=$,this.originalResponse=Q,this.emit(W?M.Connected:M.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(W=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(M.ConnectionClosed);return}if(W>=this.autoReconnectRetries){this.emit(M.ReconnectLimitExceeded),this.emit(M.ConnectionClosed);return}try{this.emit(M.ReconnectAttempt,W),await this.reconnect()}catch(Z){this.emit(M.ReconnectError,W),this.emit(M.Error,{type:M.ReconnectError,error:Z,message:`Reconnect error - ${W+1} attempts made yet.`}),this.makeAutoReconnectRetry(W,Z)}}makeAutoReconnectRetry(W,Z){let $=this.nextRetryTimeout(W+1,Z);this.retryTimeout=setTimeout(()=>{this.onConnectionError(W+1)},$)}async*[Symbol.asyncIterator](){let W=new i6(this);try{while(!0){if(!this.req||this.req.aborted)throw Error("Connection closed");if(W.hasStack())yield*W.popStack();let{type:Z,payload:$}=await W.nextEvent();if(Z==="error")throw $}}finally{W.destroy()}}}var $4=o6;function a6(W){var Z;if(!((Z=W.clientSettings.plugins)===null||Z===void 0?void 0:Z.length))return!1;for(let $ of W.clientSettings.plugins)if($.onRequestError||$.onResponseError)return!0;return!1}async function t6(W,Z,$,Q){let Y;if(Q instanceof v1||Q instanceof I1)Y=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:Q});else if(Q instanceof f1)Y=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:Q});if(Y&&Y instanceof y1)return Y.value;return Promise.reject(Q)}import*as WW from"crypto";class E{constructor(W){this.nonceLength=32,this.consumerKeys=W.consumerKeys}static percentEncode(W){return encodeURIComponent(W).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(W,Z){return WW.createHmac("sha1",Z).update(W).digest("base64")}authorize(W,Z={}){let $={oauth_consumer_key:this.consumerKeys.key,oauth_nonce:this.getNonce(),oauth_signature_method:"HMAC-SHA1",oauth_timestamp:this.getTimestamp(),oauth_version:"1.0"};if(Z.key!==void 0)$.oauth_token=Z.key;if(!W.data)W.data={};return $.oauth_signature=this.getSignature(W,Z.secret,$),$}toHeader(W){let Z=e6(W),$="OAuth ";for(let Q of Z){if(Q.key.indexOf("oauth_")!==0)continue;$+=E.percentEncode(Q.key)+'="'+E.percentEncode(Q.value)+'",'}return{Authorization:$.slice(0,$.length-1)}}getNonce(){let Z="";for(let $=0;$<this.nonceLength;$++)Z+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.trunc(Math.random()*62)];return Z}getTimestamp(){return Math.trunc(new Date().getTime()/1000)}getSignature(W,Z,$){return this.hash(this.getBaseString(W,$),this.getSigningKey(Z))}getSigningKey(W){return E.percentEncode(this.consumerKeys.secret)+"&"+E.percentEncode(W||"")}getBaseString(W,Z){return W.method.toUpperCase()+"&"+E.percentEncode(this.getBaseUrl(W.url))+"&"+E.percentEncode(this.getParameterString(W,Z))}getParameterString(W,Z){let $=e6(b5(r6(Z,r6(W.data,P5(W.url))))),Q="";for(let{key:Y,value:K}of $)if(K&&Array.isArray(K)){K.sort();let J="";K.forEach((z,G)=>{if(J+=Y+"="+z,G<K.length)J+="&"}),Q+=J}else Q+=Y+"="+K+"&";return Q.slice(0,Q.length-1)}getBaseUrl(W){return W.split("?")[0]}}var E1=E;function r6(W,Z){return{...W||{},...Z||{}}}function e6(W){return Object.keys(W).sort().map((Z)=>({key:Z,value:W[Z]}))}function T5(W){let Z=W.split("&"),$={};for(let Q of Z){let[Y,K=""]=Q.split("=");if($[Y]){if(!Array.isArray($[Y]))$[Y]=[$[Y]];$[Y].push(decodeURIComponent(K))}else $[Y]=decodeURIComponent(K)}return $}function P5(W){let Z=W.split("?");if(Z.length===1)return{};return T5(Z[1])}function b5(W){let Z={};for(let $ in W){let Q=W[$];if(Q&&Array.isArray(Q))Q=Q.map((Y)=>E.percentEncode(Y));else Q=E.percentEncode(Q);Z[E.percentEncode($)]=Q}return Z}class g{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...W){let Z=W.map(($)=>$ instanceof Buffer?$:Buffer.from($));this._chunks.push(...Z)}append(W,Z,$){let Q=Z instanceof Buffer?Z:Z.toString(),Y=this.getMultipartHeader(W,Q,$);this.bodyAppend(Y,Q,g.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((W,Z)=>W+Z.length,this.getMultipartFooter().length)}getBuffer(){let W=[...this._chunks,this.getMultipartFooter()],Z=Buffer.alloc(this.getLength()),$=0;for(let Q of W)for(let Y=0;Y<Q.length;$++,Y++)Z[$]=Q[Y];return Z}getBoundary(){if(!this._boundary)this.generateBoundary();return this._boundary}generateBoundary(){let W="--------------------------";for(let Z=0;Z<24;Z++)W+=Math.floor(Math.random()*10).toString(16);this._boundary=W}getMultipartHeader(W,Z,$){if(!$)$=Z instanceof Buffer?g.DEFAULT_CONTENT_TYPE:"";let Q={"Content-Disposition":["form-data",`name="${W}"`],"Content-Type":$},Y="";for(let[K,J]of Object.entries(Q)){if(!J.length)continue;Y+=K+": "+W4(J).join("; ")+g.LINE_BREAK}return"--"+this.getBoundary()+g.LINE_BREAK+Y+g.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+g.LINE_BREAK)}}g.LINE_BREAK=`\r
68
- `;g.DEFAULT_CONTENT_TYPE="application/octet-stream";class W0{static formatQueryToString(W){let Z={};for(let $ in W)if(typeof W[$]==="string")Z[$]=W[$];else if(typeof W[$]<"u")Z[$]=String(W[$]);return Z}static autoDetectBodyType(W){if(W.pathname.startsWith("/2/")||W.pathname.startsWith("/labs/2/")){if(W.password.startsWith("/2/oauth2"))return"url";return"json"}if(W.hostname==="upload.x.com"){if(W.pathname==="/1.1/media/upload.json")return"form-data";return"json"}let Z=W.pathname.split("/1.1/",2)[1];if(this.JSON_1_1_ENDPOINTS.has(Z))return"json";return"url"}static addQueryParamsToUrl(W,Z){let $=Object.entries(Z);if($.length){let Q="";for(let[Y,K]of $)Q+=(Q.length?"&":"?")+`${E1.percentEncode(Y)}=${E1.percentEncode(K)}`;W.search=Q}}static constructBodyParams(W,Z,$){if(W instanceof Buffer)return W;if($==="json"){if(!Z["content-type"])Z["content-type"]="application/json;charset=UTF-8";return JSON.stringify(W)}else if($==="url"){if(!Z["content-type"])Z["content-type"]="application/x-www-form-urlencoded;charset=UTF-8";if(Object.keys(W).length)return new URLSearchParams(W).toString().replace(/\*/g,"%2A");return""}else if($==="raw")throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");else{let Q=new g;for(let Y in W)Q.append(Y,W[Y]);if(!Z["content-type"]){let Y=Q.getHeaders();Z["content-type"]=Y["content-type"]}return Q.getBuffer()}}static setBodyLengthHeader(W,Z){var $;if(W.headers=($=W.headers)!==null&&$!==void 0?$:{},typeof Z==="string")W.headers["content-length"]=Buffer.byteLength(Z);else W.headers["content-length"]=Z.length}static isOAuthSerializable(W){return!(W instanceof Buffer)}static mergeQueryAndBodyForOAuth(W,Z){let $={};for(let Q in W)$[Q]=W[Q];if(this.isOAuthSerializable(Z))for(let Q in Z){let Y=Z[Q];if(this.isOAuthSerializable(Y))$[Q]=typeof Y==="object"&&Y!==null&&"toString"in Y?Y.toString():Y}return $}static moveUrlQueryParamsIntoObject(W,Z){for(let[$,Q]of W.searchParams)Z[$]=Q;return W.search="",W}static applyRequestParametersToUrl(W,Z){return W.pathname=W.pathname.replace(/:([A-Z_-]+)/ig,($,Q)=>{if(Z[Q]!==void 0)return String(Z[Q]);return $}),W}}W0.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"]);var v=W0;import*as ZW from"crypto";class B1{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url(ZW.createHash("sha256").update(W).digest("base64"))}static getAuthHeader(W,Z){let $=encodeURIComponent(W)+":"+encodeURIComponent(Z);return Buffer.from($).toString("base64")}static generateRandomString(W){let Z="",$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let Q=0;Q<W;Q++)Z+=$[Math.floor(Math.random()*$.length)];return Z}static escapeBase64Url(W){return W.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class H1{constructor(W){if(this.rateLimits={},this.clientSettings={},W)this.clientSettings=W}getRateLimits(){return this.rateLimits}saveRateLimit(W,Z){this.rateLimits[W]=Z}async send(W){var Z,$,Q,Y,K;if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length){let j=await this.applyPreRequestConfigHooks(W);if(j)return j}let J=this.getHttpRequestArgs(W),z={method:J.method,headers:J.headers,timeout:W.timeout,agent:this.clientSettings.httpAgent},G=W.enableRateLimitSave!==!1;if(J.body)v.setBodyLengthHeader(z,J.body);if(($=this.clientSettings.plugins)===null||$===void 0?void 0:$.length)await this.applyPreRequestHooks(W,J,z);let X=new h1({url:J.url,options:z,body:J.body,rateLimitSaver:G?this.saveRateLimit.bind(this,J.rawUrl):void 0,requestEventDebugHandler:W.requestEventDebugHandler,compression:(Y=(Q=W.compression)!==null&&Q!==void 0?Q:this.clientSettings.compression)!==null&&Y!==void 0?Y:!0,forceParseMode:W.forceParseMode}).makeRequest();if(a6(this))X=this.applyResponseErrorHooks(W,J,z,X);let B=await X;if((K=this.clientSettings.plugins)===null||K===void 0?void 0:K.length){let j=await this.applyPostRequestHooks(W,J,z,B);if(j)return j.value}return B}sendStream(W){var Z,$;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(W);let Q=this.getHttpRequestArgs(W),Y={method:Q.method,headers:Q.headers,agent:this.clientSettings.httpAgent},K=W.enableRateLimitSave!==!1,J=W.autoConnect!==!1;if(Q.body)v.setBodyLengthHeader(Y,Q.body);let z={url:Q.url,options:Y,body:Q.body,rateLimitSaver:K?this.saveRateLimit.bind(this,Q.rawUrl):void 0,payloadIsError:W.payloadIsError,compression:($=(Z=W.compression)!==null&&Z!==void 0?Z:this.clientSettings.compression)!==null&&$!==void 0?$:!0},G=new $4(z);if(!J)return G;return G.connect()}initializeToken(W){if(typeof W==="string")this.bearerToken=W;else if(typeof W==="object"&&"appKey"in W){if(this.consumerToken=W.appKey,this.consumerSecret=W.appSecret,W.accessToken&&W.accessSecret)this.accessToken=W.accessToken,this.accessSecret=W.accessSecret;this._oauth=this.buildOAuth()}else if(typeof W==="object"&&"username"in W){let Z=encodeURIComponent(W.username)+":"+encodeURIComponent(W.password);this.basicToken=Buffer.from(Z).toString("base64")}else if(typeof W==="object"&&"clientId"in W)this.clientId=W.clientId,this.clientSecret=W.clientSecret}getActiveTokens(){if(this.bearerToken)return{type:"oauth2",bearerToken:this.bearerToken};else if(this.basicToken)return{type:"basic",token:this.basicToken};else if(this.consumerSecret&&this._oauth)return{type:"oauth-1.0a",appKey:this.consumerToken,appSecret:this.consumerSecret,accessToken:this.accessToken,accessSecret:this.accessSecret};else if(this.clientId)return{type:"oauth2-user",clientId:this.clientId};return{type:"none"}}buildOAuth(){if(!this.consumerSecret||!this.consumerToken)throw Error("Invalid consumer tokens");return new E1({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(!this.accessSecret||!this.accessToken)return;return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var W;return(W=this.clientSettings.plugins)!==null&&W!==void 0?W:[]}hasPlugins(){var W;return!!((W=this.clientSettings.plugins)===null||W===void 0?void 0:W.length)}async applyPluginMethod(W,Z){var $;let Q;for(let Y of this.getPlugins()){let K=await(($=Y[W])===null||$===void 0?void 0:$.call(Y,Z));if(K&&K instanceof y1)Q=K}return Q}writeAuthHeaders({headers:W,bodyInSignature:Z,url:$,method:Q,query:Y,body:K}){if(W={...W},this.bearerToken)W.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)W.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)W.Authorization="Basic "+B1.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let J=Z?v.mergeQueryAndBodyForOAuth(Y,K):Y,z=this._oauth.authorize({url:$.toString(),method:Q,data:J},this.getOAuthAccessTokens());W={...W,...this._oauth.toHeader(z)}}return W}getUrlObjectFromUrlString(W){if(!W.startsWith("http"))W="https://"+W;return new URL(W)}getHttpRequestArgs({url:W,method:Z,query:$={},body:Q={},headers:Y,forceBodyMode:K,enableAuth:J,params:z}){let G=void 0;if(Z=Z.toUpperCase(),Y=Y!==null&&Y!==void 0?Y:{},!Y["x-user-agent"])Y["x-user-agent"]="Node.twitter-api-v2";let X=this.getUrlObjectFromUrlString(W),B=X.origin+X.pathname;if(z)v.applyRequestParametersToUrl(X,z);let j=v.formatQueryToString($);if(v.moveUrlQueryParamsIntoObject(X,j),!(Q instanceof Buffer))d6(Q);let D=K!==null&&K!==void 0?K:v.autoDetectBodyType(X);if(J!==!1){let x=H1.BODY_METHODS.has(Z)&&D==="url";Y=this.writeAuthHeaders({headers:Y,bodyInSignature:x,method:Z,query:j,url:X,body:Q})}if(H1.BODY_METHODS.has(Z))G=v.constructBodyParams(Q,Y,D)||void 0;return v.addQueryParamsToUrl(X,j),{rawUrl:B,url:X,method:Z,headers:Y,body:G}}async applyPreRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let Q of this.getPlugins()){let Y=await((Z=Q.onBeforeRequestConfig)===null||Z===void 0?void 0:Z.call(Q,{client:this,url:$,params:W}));if(Y)return Y}}applyPreStreamRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let Q of this.getPlugins())(Z=Q.onBeforeStreamRequestConfig)===null||Z===void 0||Z.call(Q,{client:this,url:$,params:W})}async applyPreRequestHooks(W,Z,$){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$})}async applyPostRequestHooks(W,Z,$,Q){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,response:Q})}applyResponseErrorHooks(W,Z,$,Q){return Q.catch(t6.bind(this,W,Z,$))}}H1.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class W1{constructor(W,Z={}){if(this._currentUser=null,this._currentUserV2=null,W instanceof W1)this._requestMaker=W._requestMaker;else this._requestMaker=new H1(Z),this._requestMaker.initializeToken(W)}setPrefix(W){this._prefix=W}cloneWithPrefix(W){let Z=this.constructor(this);return Z.setPrefix(W),Z}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(W){return this.getPlugins().find((Z)=>Z instanceof W)}hasHitRateLimit(W){var Z;if(this.isRateLimitStatusObsolete(W))return!1;return((Z=this.getLastRateLimitStatus(W))===null||Z===void 0?void 0:Z.remaining)===0}isRateLimitStatusObsolete(W){let Z=this.getLastRateLimitStatus(W);if(Z===void 0)return!0;return Z.reset*1000<Date.now()}getLastRateLimitStatus(W){let Z=W.match(/^https?:\/\//)?W:this._prefix+W;return this._requestMaker.getRateLimits()[Z]}getCurrentUserObject(W=!1){if(!W&&this._currentUser){if(this._currentUser.value)return Promise.resolve(this._currentUser.value);return this._currentUser.promise}return this._currentUser=r4(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:r})),this._currentUser.promise}getCurrentUserV2Object(W=!1){if(!W&&this._currentUserV2){if(this._currentUserV2.value)return Promise.resolve(this._currentUserV2.value);return this._currentUserV2.promise}return this._currentUserV2=r4(()=>this.get("users/me",void 0,{prefix:t})),this._currentUserV2.promise}async get(W,Z={},{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"GET",query:Z,...Y});return $?K:K.data}async delete(W,Z={},{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"DELETE",query:Z,...Y});return $?K:K.data}async post(W,Z,{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"POST",body:Z,...Y});return $?K:K.data}async put(W,Z,{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"PUT",body:Z,...Y});return $?K:K.data}async patch(W,Z,{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"PATCH",body:Z,...Y});return $?K:K.data}getStream(W,Z,{prefix:$=this._prefix,...Q}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"GET",query:Z,...Q})}postStream(W,Z,{prefix:$=this._prefix,...Q}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"POST",body:Z,...Q})}}class I extends W1{constructor(W){if(!(W instanceof W1))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(W)}}class N1 extends D1{constructor(){super(...arguments);this.hasFinishedFetch=!1}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.push(...$),this.hasFinishedFetch=$.length===0}getNextQueryParams(W){let Z=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(W),max_id:(Z-BigInt(1)).toString()}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class Z0 extends N1{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class $0 extends N1{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class Y4 extends N1{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class Q0 extends N1{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class K4 extends N1{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class Y0 extends O{constructor(){super(...arguments);this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class K0 extends O{constructor(){super(...arguments);this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class J0 extends O{constructor(){super(...arguments);this._endpoint="followers/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class z0 extends O{constructor(){super(...arguments);this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class G0 extends O{constructor(){super(...arguments);this._endpoint="friends/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class X0 extends O{constructor(){super(...arguments);this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class B0 extends D1{constructor(){super(...arguments);this._endpoint="users/search.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.push(...$)}getNextQueryParams(W){var Z;let $=Number((Z=this._queryParams.page)!==null&&Z!==void 0?Z:"1");return{...this._queryParams,page:$+1,...W?{count:W}:{}}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.users}get users(){return this._realData}}class J4 extends O{constructor(){super(...arguments);this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class j0 extends J4{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class z4 extends O{refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.lists.push(...$.lists),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class M0 extends z4{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class F0 extends z4{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class L0 extends z4{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class D0 extends O{refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class H0 extends D0{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class N0 extends D0{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class U1 extends I{constructor(){super(...arguments);this._prefix=r}singleTweet(W,Z={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:W,...Z})}tweets(W,Z={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:W,...Z})}oembedTweet(W,Z={}){return this.get("oembed",{url:`https://x.com/i/statuses/${W}`,...Z},{prefix:"https://publish.x.com/"})}async homeTimeline(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("statuses/home_timeline.json",Z,{fullResponse:!0});return new Z0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async mentionTimeline(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("statuses/mentions_timeline.json",Z,{fullResponse:!0});return new $0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},Q=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new Y4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async userTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},Q=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new Y4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async favoriteTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},Q=await this.get("favorites/list.json",$,{fullResponse:!0});return new K4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async favoriteTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},Q=await this.get("favorites/list.json",$,{fullResponse:!0});return new K4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}user(W){return this.get("users/show.json",{tweet_mode:"extended",...W})}users(W){return this.get("users/lookup.json",{tweet_mode:"extended",...W})}verifyCredentials(W={}){return this.get("account/verify_credentials.json",W)}async listMutedUsers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("mutes/users/list.json",Z,{fullResponse:!0});return new Y0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listMutedUserIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("mutes/users/ids.json",Z,{fullResponse:!0});return new K0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFriendList(W={}){let Z={...W},$=await this.get("friends/list.json",Z,{fullResponse:!0});return new G0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowerList(W={}){let Z={...W},$=await this.get("followers/list.json",Z,{fullResponse:!0});return new J0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowerIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("followers/ids.json",Z,{fullResponse:!0});return new z0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowingIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friends/ids.json",Z,{fullResponse:!0});return new X0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async searchUsers(W,Z={}){let $={q:W,tweet_mode:"extended",page:1,...Z},Q=await this.get("users/search.json",$,{fullResponse:!0});return new B0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}friendship(W){return this.get("friendships/show.json",W)}friendships(W){return this.get("friendships/lookup.json",W)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friendships/incoming.json",Z,{fullResponse:!0});return new J4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async friendshipsOutgoing(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friendships/outgoing.json",Z,{fullResponse:!0});return new j0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(W){return this.get("users/profile_banner.json",W)}list(W){return this.get("lists/show.json",{tweet_mode:"extended",...W})}lists(W={}){return this.get("lists/list.json",{tweet_mode:"extended",...W})}async listMembers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/members.json",Z,{fullResponse:!0});return new H0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}listGetMember(W){return this.get("lists/members/show.json",{tweet_mode:"extended",...W})}async listMemberships(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/memberships.json",Z,{fullResponse:!0});return new M0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listOwnerships(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/ownerships.json",Z,{fullResponse:!0});return new F0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listStatuses(W){let Z={tweet_mode:"extended",...W},$=await this.get("lists/statuses.json",Z,{fullResponse:!0});return new Q0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listSubscribers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/subscribers.json",Z,{fullResponse:!0});return new N0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}listGetSubscriber(W){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...W})}async listSubscriptions(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/subscriptions.json",Z,{fullResponse:!0});return new L0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}mediaInfo(W){return this.get("media/upload.json",{command:"STATUS",media_id:W},{prefix:s})}filterStream({autoConnect:W,...Z}={}){let $={};for(let[Y,K]of Object.entries(Z))if(Y==="follow"||Y==="track")$[Y]=K.toString();else if(Y==="locations"){let J=K;$.locations=W4(J).map((z)=>`${z.lng},${z.lat}`).join(",")}else $[Y]=K;return this.stream.postStream("statuses/filter.json",$,{autoConnect:W})}sampleStream({autoConnect:W,...Z}={}){return this.stream.getStream("statuses/sample.json",Z,{autoConnect:W})}get stream(){let W=new G4(this);return W.setPrefix(c6),W}trendsByPlace(W,Z={}){return this.get("trends/place.json",{id:W,...Z})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(W,Z){return this.get("trends/closest.json",{lat:W,long:Z})}geoPlace(W){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:W}})}geoSearch(W){return this.get("geo/search.json",W)}geoReverseGeoCode(W){return this.get("geo/reverse_geocode.json",W)}rateLimitStatuses(...W){return this.get("application/rate_limit_status.json",{resources:W})}supportedLanguages(){return this.get("help/languages.json")}}import*as Z1 from"fs";async function U0(W){let Z=await x0(W);if(typeof Z==="number")return new Promise(($,Q)=>{Z1.readFile(Z,(Y,K)=>{if(Y)return Q(Y);$(K)})});else if(Z instanceof Buffer)return Z;else return Z.readFile()}function x0(W){if(typeof W==="string")return Z1.promises.open(W,"r");else if(typeof W==="number")return W;else if(typeof W==="object"&&!(W instanceof Buffer))return W;else if(!(W instanceof Buffer))throw Error("Given file is not valid, please check its type.");else return W}async function $W(W){if(typeof W==="number")return(await new Promise(($,Q)=>{Z1.fstat(W,(Y,K)=>{if(Y)Q(Y);$(K)})})).size;else if(W instanceof Buffer)return W.length;else return(await W.stat()).size}function QW(W,Z,$){if(typeof $==="string")return $;else if(typeof W==="string"&&!Z)return w5(W);else if(typeof Z==="string")return q5(Z);throw Error("You must specify type if file is a file handle or Buffer.")}function w5(W){if(W.endsWith(".jpeg")||W.endsWith(".jpg"))return N.Jpeg;if(W.endsWith(".png"))return N.Png;if(W.endsWith(".webp"))return N.Webp;if(W.endsWith(".gif"))return N.Gif;if(W.endsWith(".mpeg4")||W.endsWith(".mp4"))return N.Mp4;if(W.endsWith(".mov")||W.endsWith(".mov"))return N.Mov;if(W.endsWith(".srt"))return N.Srt;return e4({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"}),N.Jpeg}function q5(W){if(e4({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"}),W==="gif")return N.Gif;if(W==="jpg")return N.Jpeg;if(W==="png")return N.Png;if(W==="webp")return N.Webp;if(W==="srt")return N.Srt;if(W==="mp4"||W==="longmp4")return N.Mp4;if(W==="mov")return N.Mov;return W}function YW(W,Z){if(W===N.Mp4||W===N.Mov)return Z==="tweet"?"TweetVideo":"DmVideo";if(W===N.Gif)return Z==="tweet"?"TweetGif":"DmGif";if(W===N.Srt)return"Subtitles";else return Z==="tweet"?"TweetImage":"DmImage"}function S0(W){return new Promise((Z)=>setTimeout(Z,W*1000))}async function R0(W,Z,$=0,Q){if(W instanceof Buffer){let K=W.slice($,$+Z);return[K,K.length]}if(!Q)throw Error("Well, we will need a buffer to store file content.");let Y;if(typeof W==="number")Y=await new Promise((K,J)=>{Z1.read(W,Q,0,Z,$,(z,G)=>{if(z)J(z);K(G)})});else Y=(await W.read(Q,0,Z,$)).bytesRead;return[Q,Y]}var O0="media/upload.json";class x1 extends U1{constructor(){super(...arguments);this._prefix=r}get readOnly(){return this}tweet(W,Z={}){let $={status:W,tweet_mode:"extended",...Z};return this.post("statuses/update.json",$)}async quote(W,Z,$={}){let Q="https://x.com/i/statuses/"+Z;return this.tweet(W,{...$,attachment_url:Q})}async tweetThread(W){let Z=[];for(let $ of W){let Q=Z.length?Z[Z.length-1]:null,Y={...typeof $==="string"?{status:$}:$},K=Q?Q.id_str:Y.in_reply_to_status_id,J=Y.status;if(K)Z.push(await this.reply(J,K,Y));else Z.push(await this.tweet(J,Y))}return Z}reply(W,Z,$={}){return this.tweet(W,{auto_populate_reply_metadata:!0,in_reply_to_status_id:Z,...$})}deleteTweet(W){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:W}})}reportUserAsSpam(W){return this.post("users/report_spam.json",{tweet_mode:"extended",...W})}updateFriendship(W){return this.post("friendships/update.json",W)}createFriendship(W){return this.post("friendships/create.json",W)}destroyFriendship(W){return this.post("friendships/destroy.json",W)}updateAccountSettings(W){return this.post("account/settings.json",W)}updateAccountProfile(W){return this.post("account/update_profile.json",W)}async updateAccountProfileBanner(W,Z={}){let $={banner:await U0(W),...Z};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,Z={}){let $={tweet_mode:"extended",image:await U0(W),...Z};return this.post("account/update_profile_image.json",$,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(W){return this.post("lists/create.json",{tweet_mode:"extended",...W})}updateList(W){return this.post("lists/update.json",{tweet_mode:"extended",...W})}removeList(W){return this.post("lists/destroy.json",{tweet_mode:"extended",...W})}addListMembers(W){let $=W.user_id&&A1(W.user_id)||W.screen_name&&A1(W.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,W)}removeListMembers(W){let $=W.user_id&&A1(W.user_id)||W.screen_name&&A1(W.screen_name)?"lists/members/destroy_all.json":"lists/members/destroy.json";return this.post($,W)}subscribeToList(W){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...W})}unsubscribeOfList(W){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...W})}createMediaMetadata(W,Z){return this.post("media/metadata/create.json",{media_id:W,...Z},{prefix:s,forceBodyMode:"json"})}createMediaSubtitles(W,Z){return this.post("media/subtitles/create.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z}},{prefix:s,forceBodyMode:"json"})}deleteMediaSubtitles(W,...Z){return this.post("media/subtitles/delete.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z.map(($)=>({language_code:$}))}},{prefix:s,forceBodyMode:"json"})}async uploadMedia(W,Z={},$=!1){var Q;let Y=(Q=Z.chunkLength)!==null&&Q!==void 0?Q:1048576,{fileHandle:K,mediaCategory:J,fileSize:z,mimeType:G}=await this.getUploadMediaRequirements(W,Z);try{let X=await this.post(O0,{command:"INIT",total_bytes:z,media_type:G,media_category:J,additional_owners:Z.additionalOwners,shared:Z.shared?!0:void 0},{prefix:s});await this.mediaChunkedUpload(K,Y,X.media_id_string,Z.maxConcurrentUploads);let B=await this.post(O0,{command:"FINALIZE",media_id:X.media_id_string},{prefix:s});if(B.processing_info&&B.processing_info.state!=="succeeded")await this.awaitForMediaProcessingCompletion(B);if($)return B;else return B.media_id_string}finally{if(typeof W==="number")_0.close(W,()=>{});else if(typeof K==="object"&&!(K instanceof Buffer))K.close()}}async awaitForMediaProcessingCompletion(W){var Z;while(!0){W=await this.mediaInfo(W.media_id_string);let{processing_info:$}=W;if(!$||$.state==="succeeded")return;if((Z=$.error)===null||Z===void 0?void 0:Z.code){let{name:Q,message:Y}=$.error;throw Error(`Failed to process media: ${Q} - ${Y}.`)}if($.state==="failed")throw Error("Failed to process the media.");if($.check_after_secs)await S0($.check_after_secs);else await S0(5)}}async getUploadMediaRequirements(W,{mimeType:Z,type:$,target:Q,longVideo:Y}={}){let K;try{K=await x0(W);let J=QW(W,$,Z),z;if(J===N.Mp4&&(!Z&&!$&&Q!=="dm"||Y))z="amplify_video";else z=YW(J,Q!==null&&Q!==void 0?Q:"tweet");return{fileHandle:K,mediaCategory:z,fileSize:await $W(K),mimeType:J}}catch(J){if(typeof W==="number")_0.close(W,()=>{});else if(typeof K==="object"&&!(K instanceof Buffer))K.close();throw J}}async mediaChunkedUpload(W,Z,$,Q=3){let Y=0;if(Q<1)throw RangeError("Bad maxConcurrentUploads parameter.");let K=W instanceof Buffer?void 0:Buffer.alloc(Z),J,z,G=0;[J,z]=await R0(W,Z,G,K),G+=z;let X=new Set;while(z){let B=J.slice(0,z);if(B.length){let j=this.post(O0,{command:"APPEND",media_id:$,segment_index:Y,media:B},{prefix:s});X.add(j),j.then(()=>{X.delete(j)}),Y++}if(X.size>=Q)await Promise.race(X);[J,z]=await R0(W,Z,G,K),G+=z}await Promise.all([...X])}}class KW extends x1{constructor(){super(...arguments);this._prefix=r}get readWrite(){return this}sendDm({recipient_id:W,custom_profile_id:Z,...$}){let Q={event:{type:e.Create,[e.Create]:{target:{recipient_id:W},message_data:$}}};if(Z)Q.event[e.Create].custom_profile_id=Z;return this.post("direct_messages/events/new.json",Q,{forceBodyMode:"json"})}getDmEvent(W){return this.get("direct_messages/events/show.json",{id:W})}deleteDm(W){return this.delete("direct_messages/events/destroy.json",{id:W})}async listDmEvents(W={}){let Z={...W},$=await this.get("direct_messages/events/list.json",Z,{fullResponse:!0});return new a4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDm(W,Z){let $={[e.WelcomeCreate]:{name:W,message_data:Z}};return this.post("direct_messages/welcome_messages/new.json",$,{forceBodyMode:"json"})}getWelcomeDm(W){return this.get("direct_messages/welcome_messages/show.json",{id:W})}deleteWelcomeDm(W){return this.delete("direct_messages/welcome_messages/destroy.json",{id:W})}updateWelcomeDm(W,Z){let $={message_data:Z};return this.put("direct_messages/welcome_messages/update.json",$,{forceBodyMode:"json",query:{id:W}})}async listWelcomeDms(W={}){let Z={...W},$=await this.get("direct_messages/welcome_messages/list.json",Z,{fullResponse:!0});return new t4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDmRule(W){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:W}},{forceBodyMode:"json"})}getWelcomeDmRule(W){return this.get("direct_messages/welcome_messages/rules/show.json",{id:W})}deleteWelcomeDmRule(W){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:W})}async listWelcomeDmRules(W={}){let Z={...W};return this.get("direct_messages/welcome_messages/rules/list.json",Z)}async setWelcomeDm(W,Z=!0){var $;let Q=await this.listWelcomeDmRules();if(($=Q.welcome_message_rules)===null||$===void 0?void 0:$.length){for(let Y of Q.welcome_message_rules)if(await this.deleteWelcomeDmRule(Y.id),Z)await this.deleteWelcomeDm(Y.welcome_message_id)}return this.newWelcomeDmRule(W)}markDmAsRead(W,Z){return this.post("direct_messages/mark_read.json",{last_read_event_id:W,recipient_id:Z},{forceBodyMode:"url"})}indicateDmTyping(W){return this.post("direct_messages/indicate_typing.json",{recipient_id:W},{forceBodyMode:"url"})}async downloadDmImage(W){if(typeof W!=="string"){let $=W[e.Create].message_data.attachment;if(!$)throw Error("The given direct message doesn't contain any attachment");W=$.media.media_url_https}let Z=await this.get(W,void 0,{forceParseMode:"buffer",prefix:""});if(!Z.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return Z}}var G4=KW;class H{constructor(W){this.result=W}get tweets(){return H.tweets(this.result)}static tweets(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.tweets)!==null&&$!==void 0?$:[]}tweetById(W){return H.tweetById(this.result,W)}static tweetById(W,Z){return this.tweets(W).find(($)=>$.id===Z)}retweet(W){return H.retweet(this.result,W)}static retweet(W,Z){var $;let Q=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Y)=>Y.type==="retweeted").map((Y)=>Y.id);return this.tweets(W).find((Y)=>Q.includes(Y.id))}quote(W){return H.quote(this.result,W)}static quote(W,Z){var $;let Q=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Y)=>Y.type==="quoted").map((Y)=>Y.id);return this.tweets(W).find((Y)=>Q.includes(Y.id))}repliedTo(W){return H.repliedTo(this.result,W)}static repliedTo(W,Z){var $;let Q=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Y)=>Y.type==="replied_to").map((Y)=>Y.id);return this.tweets(W).find((Y)=>Q.includes(Y.id))}author(W){return H.author(this.result,W)}static author(W,Z){let $=Z.author_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}repliedToAuthor(W){return H.repliedToAuthor(this.result,W)}static repliedToAuthor(W,Z){let $=Z.in_reply_to_user_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}get users(){return H.users(this.result)}static users(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.users)!==null&&$!==void 0?$:[]}userById(W){return H.userById(this.result,W)}static userById(W,Z){return this.users(W).find(($)=>$.id===Z)}pinnedTweet(W){return H.pinnedTweet(this.result,W)}static pinnedTweet(W,Z){return Z.pinned_tweet_id?this.tweets(W).find(($)=>$.id===Z.pinned_tweet_id):void 0}get media(){return H.media(this.result)}static media(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.media)!==null&&$!==void 0?$:[]}medias(W){return H.medias(this.result,W)}static medias(W,Z){var $,Q;let Y=(Q=($=Z.attachments)===null||$===void 0?void 0:$.media_keys)!==null&&Q!==void 0?Q:[];return this.media(W).filter((K)=>Y.includes(K.media_key))}get polls(){return H.polls(this.result)}static polls(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.polls)!==null&&$!==void 0?$:[]}poll(W){return H.poll(this.result,W)}static poll(W,Z){var $,Q;let Y=(Q=($=Z.attachments)===null||$===void 0?void 0:$.poll_ids)!==null&&Q!==void 0?Q:[];if(Y.length){let K=Y[0];return this.polls(W).find((J)=>J.id===K)}return}get places(){return H.places(this.result)}static places(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.places)!==null&&$!==void 0?$:[]}place(W){return H.place(this.result,W)}static place(W,Z){var $;let Q=($=Z.geo)===null||$===void 0?void 0:$.place_id;return Q?this.places(W).find((Y)=>Y.id===Q):void 0}listOwner(W){return H.listOwner(this.result,W)}static listOwner(W,Z){let $=Z.owner_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}spaceCreator(W){return H.spaceCreator(this.result,W)}static spaceCreator(W,Z){let $=Z.creator_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}spaceHosts(W){return H.spaceHosts(this.result,W)}static spaceHosts(W,Z){var $;let Q=($=Z.host_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Y)=>Q.includes(Y.id))}spaceSpeakers(W){return H.spaceSpeakers(this.result,W)}static spaceSpeakers(W,Z){var $;let Q=($=Z.speaker_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Y)=>Q.includes(Y.id))}spaceInvitedUsers(W){return H.spaceInvitedUsers(this.result,W)}static spaceInvitedUsers(W,Z){var $;let Q=($=Z.invited_user_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Y)=>Q.includes(Y.id))}}class X4 extends o4{updateIncludes(W){if(W.errors){if(!this._realData.errors)this._realData.errors=[];this._realData.errors=[...this._realData.errors,...W.errors]}if(!W.includes)return;if(!this._realData.includes)this._realData.includes={};let Z=this._realData.includes;for(let[$,Q]of Object.entries(W.includes)){if(!Z[$])Z[$]=[];Z[$]=[...Z[$],...Q]}}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 W;if(!((W=this._realData)===null||W===void 0?void 0:W.includes))return new H(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new H(this._realData)}get errors(){var W;return(W=this._realData.errors)!==null&&W!==void 0?W:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class d extends X4{refreshInstanceFromResult(W,Z){var $;let Q=W.data,Y=($=Q.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.result_count+=Q.meta.result_count,this._realData.meta.next_token=Q.meta.next_token,this._realData.data.push(...Y);else this._realData.meta.result_count+=Q.meta.result_count,this._realData.meta.previous_token=Q.meta.previous_token,this._realData.data.unshift(...Y);this.updateIncludes(Q)}getNextQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(W){var Z,$;return($=(Z=W.data.data)===null||Z===void 0?void 0:Z.length)!==null&&$!==void 0?$:0}isFetchLastOver(W){var Z;return!((Z=W.data.data)===null||Z===void 0?void 0:Z.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){var Z;return!!((Z=W.meta)===null||Z===void 0?void 0:Z.next_token)}}class V0 extends X4{refreshInstanceFromResult(W,Z){var $;let Q=W.data,Y=($=Q.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.oldest_id=Q.meta.oldest_id,this._realData.meta.result_count+=Q.meta.result_count,this._realData.meta.next_token=Q.meta.next_token,this._realData.data.push(...Y);else this._realData.meta.newest_id=Q.meta.newest_id,this._realData.meta.result_count+=Q.meta.result_count,this._realData.data.unshift(...Y);this.updateIncludes(Q)}getNextQueryParams(W){this.assertUsable();let Z={...this.injectQueryParams(W)};if(this._realData.meta.next_token)Z.next_token=this._realData.meta.next_token;else{if(Z.start_time)Z.since_id=this.dateStringToSnowflakeId(Z.start_time),delete Z.start_time;if(Z.end_time)delete Z.end_time;Z.until_id=this._realData.meta.oldest_id}return Z}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(W){var Z,$;return($=(Z=W.data.data)===null||Z===void 0?void 0:Z.length)!==null&&$!==void 0?$:0}isFetchLastOver(W){var Z;return!((Z=W.data.data)===null||Z===void 0?void 0:Z.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!!W.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(W){let Z=BigInt("1288834974657"),$=new Date(W);if(isNaN($.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($.valueOf())-Z<<BigInt("22")).toString()}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class S1 extends d{refreshInstanceFromResult(W,Z){super.refreshInstanceFromResult(W,Z);let $=W.data;if(Z)this._realData.meta.oldest_id=$.meta.oldest_id;else this._realData.meta.newest_id=$.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class k0 extends V0{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class C0 extends V0{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class T0 extends S1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class P0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class b0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class w0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class q0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class v0 extends d{get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class I0 extends v0{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class f0 extends v0{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class o extends d{getItemArray(){return this.users}get users(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class y0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class A0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class h0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class E0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class g0 extends o{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class m0 extends o{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class c0 extends o{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class u0 extends o{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class B4 extends d{getItemArray(){return this.lists}get lists(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class p0 extends B4{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class d0 extends B4{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class l0 extends B4{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class R1 extends I{constructor(){super(...arguments);this._prefix=M1}}class j4 extends d{getItemArray(){return this.events}get events(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class n0 extends j4{constructor(){super(...arguments);this._endpoint="dm_events"}}class i0 extends j4{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class s0 extends j4{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class O1 extends I{constructor(){super(...arguments);this._prefix=t}get labs(){if(this._labs)return this._labs;return this._labs=new R1(this)}async search(W,Z={}){let $=typeof W==="string"?{...Z,query:W}:{...W},Q=await this.get("tweets/search/recent",$,{fullResponse:!0});return new k0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async searchAll(W,Z={}){let $={...Z,query:W},Q=await this.get("tweets/search/all",$,{fullResponse:!0});return new C0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}singleTweet(W,Z={}){return this.get("tweets/:id",Z,{params:{id:W}})}tweets(W,Z={}){return this.get("tweets",{ids:W,...Z})}tweetCountRecent(W,Z={}){return this.get("tweets/counts/recent",{query:W,...Z})}tweetCountAll(W,Z={}){return this.get("tweets/counts/all",{query:W,...Z})}async tweetRetweetedBy(W,Z={}){let{asPaginator:$,...Q}=Z,Y=await this.get("tweets/:id/retweeted_by",Q,{fullResponse:!0,params:{id:W}});if(!$)return Y.data;return new u0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:Q,sharedParams:{id:W}})}async tweetLikedBy(W,Z={}){let{asPaginator:$,...Q}=Z,Y=await this.get("tweets/:id/liking_users",Q,{fullResponse:!0,params:{id:W}});if(!$)return Y.data;return new c0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:Q,sharedParams:{id:W}})}async homeTimeline(W={}){let Z=await this.getCurrentUserV2Object(),$=await this.get("users/:id/timelines/reverse_chronological",W,{fullResponse:!0,params:{id:Z.data.id}});return new P0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:Z.data.id}})}async userTimeline(W,Z={}){let $=await this.get("users/:id/tweets",Z,{fullResponse:!0,params:{id:W}});return new b0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async userMentionTimeline(W,Z={}){let $=await this.get("users/:id/mentions",Z,{fullResponse:!0,params:{id:W}});return new w0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async quotes(W,Z={}){let $=await this.get("tweets/:id/quote_tweets",Z,{fullResponse:!0,params:{id:W}});return new T0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async bookmarks(W={}){let Z=await this.getCurrentUserV2Object(),$=await this.get("users/:id/bookmarks",W,{fullResponse:!0,params:{id:Z.data.id}});return new q0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:Z.data.id}})}me(W={}){return this.get("users/me",W)}user(W,Z={}){return this.get("users/:id",Z,{params:{id:W}})}users(W,Z={}){let $=Array.isArray(W)?W.join(","):W;return this.get("users",{...Z,ids:$})}userByUsername(W,Z={}){return this.get("users/by/username/:username",Z,{params:{username:W}})}usersByUsernames(W,Z={}){return W=Array.isArray(W)?W.join(","):W,this.get("users/by",{...Z,usernames:W})}async followers(W,Z={}){let{asPaginator:$,...Q}=Z,Y={id:W};if(!$)return this.get("users/:id/followers",Q,{params:Y});let K=await this.get("users/:id/followers",Q,{fullResponse:!0,params:Y});return new h0({realData:K.data,rateLimit:K.rateLimit,instance:this,queryParams:Q,sharedParams:Y})}async following(W,Z={}){let{asPaginator:$,...Q}=Z,Y={id:W};if(!$)return this.get("users/:id/following",Q,{params:Y});let K=await this.get("users/:id/following",Q,{fullResponse:!0,params:Y});return new E0({realData:K.data,rateLimit:K.rateLimit,instance:this,queryParams:Q,sharedParams:Y})}async userLikedTweets(W,Z={}){let $={id:W},Q=await this.get("users/:id/liked_tweets",Z,{fullResponse:!0,params:$});return new I0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userBlockingUsers(W,Z={}){let $={id:W},Q=await this.get("users/:id/blocking",Z,{fullResponse:!0,params:$});return new y0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userMutingUsers(W,Z={}){let $={id:W},Q=await this.get("users/:id/muting",Z,{fullResponse:!0,params:$});return new A0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}list(W,Z={}){return this.get("lists/:id",Z,{params:{id:W}})}async listsOwned(W,Z={}){let $={id:W},Q=await this.get("users/:id/owned_lists",Z,{fullResponse:!0,params:$});return new p0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMemberships(W,Z={}){let $={id:W},Q=await this.get("users/:id/list_memberships",Z,{fullResponse:!0,params:$});return new d0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowed(W,Z={}){let $={id:W},Q=await this.get("users/:id/followed_lists",Z,{fullResponse:!0,params:$});return new l0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listTweets(W,Z={}){let $={id:W},Q=await this.get("lists/:id/tweets",Z,{fullResponse:!0,params:$});return new f0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMembers(W,Z={}){let $={id:W},Q=await this.get("lists/:id/members",Z,{fullResponse:!0,params:$});return new g0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowers(W,Z={}){let $={id:W},Q=await this.get("lists/:id/followers",Z,{fullResponse:!0,params:$});return new m0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEvents(W={}){let Z=await this.get("dm_events",W,{fullResponse:!0});return new n0({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:{...W}})}async listDmEventsWithParticipant(W,Z={}){let $={participant_id:W},Q=await this.get("dm_conversations/with/:participant_id/dm_events",Z,{fullResponse:!0,params:$});return new i0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEventsOfConversation(W,Z={}){let $={dm_conversation_id:W},Q=await this.get("dm_conversations/:dm_conversation_id/dm_events",Z,{fullResponse:!0,params:$});return new s0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}space(W,Z={}){return this.get("spaces/:id",Z,{params:{id:W}})}spaces(W,Z={}){return this.get("spaces",{ids:W,...Z})}spacesByCreators(W,Z={}){return this.get("spaces/by/creator_ids",{user_ids:W,...Z})}searchSpaces(W){return this.get("spaces/search",W)}spaceBuyers(W,Z={}){return this.get("spaces/:id/buyers",Z,{params:{id:W}})}spaceTweets(W,Z={}){return this.get("spaces/:id/tweets",Z,{params:{id:W}})}searchStream({autoConnect:W,...Z}={}){return this.getStream("tweets/search/stream",Z,{payloadIsError:Z4,autoConnect:W})}streamRules(W={}){return this.get("tweets/search/stream/rules",W)}updateStreamRules(W,Z={}){return this.post("tweets/search/stream/rules",W,{query:Z})}sampleStream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample/stream",Z,{payloadIsError:Z4,autoConnect:W})}sample10Stream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample10/stream",Z,{payloadIsError:Z4,autoConnect:W})}complianceJobs(W){return this.get("compliance/jobs",W)}complianceJob(W){return this.get("compliance/jobs/:id",void 0,{params:{id:W}})}async sendComplianceJob(W){let Z=await this.post("compliance/jobs",{type:W.type,name:W.name}),$=W.ids instanceof Buffer?W.ids:Buffer.from(W.ids.join(`
64
+ </html>`}function N6(W){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Authorization failed</title></head><body style="font-family: system-ui, sans-serif; padding: 24px"><h1 style="font-size: 1.2rem">This connection could not be authorized</h1><p>${A(W)}</p></body></html>`}function A(W){return W.replace(/[&<>"']/g,(Z)=>`&#${Z.charCodeAt(0)};`)}var I4="gmcp_at_",f4="gmcp_rt_",U6="gmcp_ac_",K5="gmcp_c_",J5="gmcp_cs_",y4="gemi.mcp.oauth.ticket.v1",x6="gemi.mcp.oauth.consent.v1",z5=600000,S6=120000,c4=16384,G5={limit:20,window:3600},X5={limit:60,window:60},s1=["none","client_secret_post","client_secret_basic"];class L extends Error{error;description;status;headers;constructor(W,Z,$=400,Q={}){super(Z);this.error=W;this.description=Z;this.status=$;this.headers=Q}}class q6{options;name="oauth";context;issuer;base;accessTtl;refreshTtl;constructor(W){this.options=W;let Z=W?.store;for(let $ of["createClient","findClient","saveCode","findCode","saveToken","findToken","use","revokeFamily"])if(typeof Z?.[$]!=="function")throw Error(`McpOAuthServer: store.${$} is missing. Use MemoryMcpOAuthStore, or implement McpOAuthStore.`);if(typeof W.findUser!=="function")throw Error("McpOAuthServer: findUser(id) is required: it loads the user a token was issued to.");if(W.consentPath!==void 0&&!/^\/[^/\\]/.test(W.consentPath))throw Error('McpOAuthServer: consentPath must be a path on this app, like "/oauth/consent".');this.accessTtl=R6("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=R6("refreshTokenTtl",W.refreshTokenTtl,2592000)}get store(){return this.options.store}boot(W){this.context=W;let Z=new URL(W.resource);this.issuer=Z.origin,this.base=`${Z.pathname}/oauth`}async resolve(W){let Z=p4(W);if(!Z?.startsWith(I4))return null;let $=await this.store.findToken(n(Z)),Q=(K)=>({ok:!1,error:"invalid_token",description:K});if(!$||$.kind!=="access")return Q("The access token is not valid.");if($.expiresAt<=Date.now())return Q("The access token expired.");if($.resource!==this.context.resource)return Q("The access token was not issued for this server.");let Y=await this.options.findUser($.userId);if(!Y)return Q("The access token is not valid.");return{ok:!0,principal:{user:Y,via:this.name,id:$.familyId,scopes:$.scopes,clientId:$.clientId}}}challenge(){let W=this.scopeNames().join(" ");return`Bearer resource_metadata="${this.resourceMetadataUrl()}", scope="${W}"`}async handle(W){let Z=new URL(W.url).pathname,Y={[`/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-protected-resource"]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-authorization-server"]:{methods:["GET"],cors:!0,run:()=>this.serverMetadata()},[`${this.base}/register`]:{methods:["POST"],cors:!0,run:()=>this.register(W)},[`${this.base}/authorize`]:{methods:["GET"],cors:!1,run:()=>this.authorize(W)},[`${this.base}/consent`]:{methods:["GET","POST"],cors:!1,run:()=>W.method==="POST"?this.decide(W):this.consentScreen(W)},[`${this.base}/token`]:{methods:["POST"],cors:!0,run:()=>this.token(W)},[`${this.base}/revoke`]:{methods:["POST"],cors:!0,run:()=>this.revoke(W)}}[Z];if(!Y)return null;if(Z===`${this.base}/register`&&this.options.registration===!1)return null;let K=Y.cors?B5:{};if(W.method==="OPTIONS"&&Y.cors)return new Response(null,{status:204,headers:{...K,"Access-Control-Allow-Methods":Y.methods.join(", "),"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}});if(!Y.methods.includes(W.method))return new Response(null,{status:405,headers:{...K,Allow:Y.methods.join(", ")}});let J;try{J=await Y.run()}catch(z){if(!(z instanceof L))throw z;J=b1({error:z.error,error_description:z.description},z.status,z.headers)}for(let[z,G]of Object.entries(K))J.headers.set(z,G);return J}async consent(W,Z){if(!Z)return null;let $=o1(y4,"gat1",W);if(!$)return null;let Q=await this.store.findClient($.c);if(!Q||!Q.redirectUris.some((z)=>h4(z,$.r)))return null;let Y=String(Z.id),K=m4(x6,"gcs1",{t:O6(W),u:Y,exp:$.exp}),J=new Map(this.context.registry.scopes().map((z)=>[z.name,z.description]));return{client:{id:Q.clientId,name:Q.clientName,redirectHost:new URL($.r).host},scopes:$.s.map((z)=>({name:z,description:J.get(z)??z})),user:{id:Y,label:this.userLabel(Z)},form:{action:`${this.issuer}${this.base}/consent`,method:"POST",fields:{request:W,csrf:K}}}}resourceMetadata(){return b1({resource:this.context.resource,authorization_servers:[this.issuer],scopes_supported:this.scopeNames(),bearer_methods_supported:["header"]})}serverMetadata(){return b1({issuer:this.issuer,authorization_endpoint:`${this.issuer}${this.base}/authorize`,token_endpoint:`${this.issuer}${this.base}/token`,...this.options.registration===!1?{}:{registration_endpoint:`${this.issuer}${this.base}/register`},revocation_endpoint:`${this.issuer}${this.base}/revoke`,scopes_supported:this.scopeNames(),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],token_endpoint_auth_methods_supported:s1,revocation_endpoint_auth_methods_supported:s1,code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,client_id_metadata_document_supported:!1})}async register(W){let Z=this.options.registration||{},$=await g4(`mcp-oauth-register:${b6(new E4(W,{},"api",`${this.base}/register`))}`,Z.rateLimit??G5);if($!==null)throw new L("slow_down","Too many registrations from this address.",429,{"Retry-After":String($)});if(!/^application\/json\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new L("invalid_client_metadata","Send the client metadata as application/json.");let Q;try{Q=JSON.parse(await u4(W,c4))}catch{throw new L("invalid_client_metadata","The client metadata is not JSON, or is too large.")}if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw new L("invalid_client_metadata","The client metadata must be a JSON object.");let Y=Q.redirect_uris;if(!Array.isArray(Y)||Y.length===0||Y.length>10)throw new L("invalid_redirect_uri","redirect_uris must list one to ten URIs.");for(let D of Y){let x=M5(D);if(x)throw new L("invalid_redirect_uri",`${String(D).slice(0,200)}: ${x}`);if(Z.allowRedirectUri&&Z.allowRedirectUri(new URL(D))!==!0)throw new L("invalid_redirect_uri",`${D}: this server does not accept it.`)}let K=Q.token_endpoint_auth_method??"client_secret_basic";if(!s1.includes(K))throw new L("invalid_client_metadata",`token_endpoint_auth_method must be one of ${s1.join(", ")}.`);let J=Q.grant_types??["authorization_code"];if(!Array.isArray(J)||J.some((D)=>D!=="authorization_code"&&D!=="refresh_token"))throw new L("invalid_client_metadata","grant_types may only be authorization_code and refresh_token.");let z=Q.response_types??["code"];if(!Array.isArray(z)||z.some((D)=>D!=="code"))throw new L("invalid_client_metadata","response_types may only be code.");let G=k6(Q.client_name,100,"client_name"),X=k6(Q.client_uri,512,"client_uri");if(X!==null&&!F5(X))throw new L("invalid_client_metadata","client_uri must be an https URL.");let B=K==="none"?null:`${J5}${K1(32).toString("base64url")}`,j={clientId:`${K5}${K1(16).toString("base64url")}`,clientSecretHash:B?n(B):null,tokenEndpointAuthMethod:K,redirectUris:[...Y],clientName:G,clientUri:X,createdAt:Date.now()};return await this.store.createClient(j),b1({client_id:j.clientId,client_id_issued_at:Math.floor(j.createdAt/1000),...B?{client_secret:B,client_secret_expires_at:0}:{},redirect_uris:j.redirectUris,token_endpoint_auth_method:K,grant_types:J,response_types:z,...G?{client_name:G}:{},...X?{client_uri:X}:{}},201)}async authorize(W){let Z=new URL(W.url).searchParams;for(let V of new Set(Z.keys()))if(Z.getAll(V).length>1)return p(`The parameter ${V} was sent more than once.`);let $=Z.get("client_id"),Q=$?await this.store.findClient($):null;if(!Q)return p("The application is not registered with this server.");let Y=Z.get("redirect_uri")??(Q.redirectUris.length===1?Q.redirectUris[0]:null);if(!Y||!Q.redirectUris.some((V)=>h4(V,Y)))return p("The redirect URI is not one the application registered.");let K=Z.get("state"),J=(V,Q1)=>this.redirectBack(Y,K,{error:V,error_description:Q1});if(Z.get("response_type")!=="code")return J("unsupported_response_type","Only response_type=code is supported.");let z=Z.get("code_challenge");if(Z.get("code_challenge_method")!=="S256"||!z||!/^[A-Za-z0-9_-]{43}$/.test(z))return J("invalid_request","PKCE is required: code_challenge with code_challenge_method=S256.");let G=Z.get("resource");if(G!==null&&!C6(G,this.context.resource))return J("invalid_target","The resource is not this server's.");if(K!==null&&K.length>2048)return J("invalid_request","state is too long.");let X=this.scopeNames(),B=Z.get("scope"),j=X;if(B!==null&&B.trim()!==""){if(j=[...new Set(B.split(" ").filter((V)=>X.includes(V)))],j.length===0)return J("invalid_scope","None of the requested scopes exist here.")}let D=m4(y4,"gat1",{c:Q.clientId,r:Y,s:j,cc:z,st:K,n:K1(16).toString("base64url"),exp:Date.now()+z5}),x=this.options.consentPath??`${this.base}/consent`;return A4(`${this.issuer}${x}?request=${encodeURIComponent(D)}`,302)}async consentScreen(W){let Z=new URL(W.url).searchParams.get("request"),$=await this.sessionUser(W);if(!$){let Y=`${this.base}/consent?request=${encodeURIComponent(Z??"")}`,K=this.options.signInPath??C(z1).config.signInPath;return A4(`${K}${K.includes("?")?"&":"?"}redirect=${encodeURIComponent(Y)}`,302)}let Q=await this.consent(Z,$);if(!Q)return p("This authorization request has expired or is not valid. Start again from the application.");return new Response(H6(Q,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:i1})}async decide(W){let Z=W.headers.get("origin");if(!(Z!==null&&Z!=="null"?Z===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return p("This decision did not come from this site's consent page.",403);if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))return p("The decision must be a form post.");let Q;try{Q=new URLSearchParams(await u4(W,c4))}catch{return p("The decision is too large.")}let Y=Q.get("request"),K=o1(y4,"gat1",Y),J=o1(x6,"gcs1",Q.get("csrf")),z=await this.sessionUser(W);if(!K||!J||!z||J.t!==O6(Y)||J.u!==String(z.id))return p("This authorization request has expired or is not valid. Start again from the application.",403);let G=await this.store.findClient(K.c);if(!G||!G.redirectUris.some((B)=>h4(B,K.r)))return p("The application is not registered with this server.");if(!await this.store.use(`ticket:${K.n}`,K.exp))return p("This request was already answered. Start again from the application.");if(Q.get("decision")!=="allow")return this.redirectBack(K.r,K.st,{error:"access_denied",error_description:"The user denied the request."},303);let X=`${U6}${K1(32).toString("base64url")}`;return await this.store.saveCode({hash:n(X),clientId:G.clientId,userId:String(z.id),redirectUri:K.r,codeChallenge:K.cc,scopes:K.s,resource:this.context.resource,familyId:K1(16).toString("base64url"),expiresAt:Date.now()+S6}),this.redirectBack(K.r,K.st,{code:X},303)}async token(W){let Z=await V6(W),$=await this.authenticateClient(W,Z),Q=await g4(`mcp-oauth-token:${$.clientId}`,X5);if(Q!==null)throw new L("slow_down","Too many token requests.",429,{"Retry-After":String(Q)});let Y=Z.get("resource");if(Y!==null&&!C6(Y,this.context.resource))throw new L("invalid_target","The resource is not this server's.");switch(Z.get("grant_type")){case"authorization_code":{let K=Z.get("code")??"",J=K.startsWith(U6)?await this.store.findCode(n(K)):null;if(!J||J.clientId!==$.clientId)throw new L("invalid_grant","The authorization code is not valid.");if(!await this.store.use(J.hash,J.expiresAt+S6))throw await this.store.revokeFamily(J.familyId),new L("invalid_grant","The authorization code was already used.");if(J.expiresAt<=Date.now())throw new L("invalid_grant","The authorization code expired.");if(Z.get("redirect_uri")!==null&&Z.get("redirect_uri")!==J.redirectUri)throw new L("invalid_grant","redirect_uri is not the one the code was issued to.");let z=Z.get("code_verifier");if(!z||!/^[A-Za-z0-9._~-]{43,128}$/.test(z)||!_6(j5(z),J.codeChallenge))throw new L("invalid_grant","The PKCE code_verifier does not match.");if(!await this.options.findUser(J.userId))throw new L("invalid_grant","The authorization code is not valid.");return await this.issue(J)}case"refresh_token":{let K=Z.get("refresh_token")??"",J=K.startsWith(f4)?await this.store.findToken(n(K)):null;if(!J||J.kind!=="refresh"||J.clientId!==$.clientId)throw new L("invalid_grant","The refresh token is not valid.");if(J.expiresAt<=Date.now())throw new L("invalid_grant","The refresh token expired.");if(!await this.store.use(J.hash,J.expiresAt))throw await this.store.revokeFamily(J.familyId),new L("invalid_grant","The refresh token was already used.");if(J.resource!==this.context.resource)throw new L("invalid_grant","The refresh token was not issued for this server.");let z=J.scopes,G=Z.get("scope");if(G!==null&&G.trim()!==""){let X=[...new Set(G.split(" ").filter(Boolean))];if(X.some((B)=>!J.scopes.includes(B)))throw new L("invalid_scope","A refresh can only narrow the scopes that were granted.");z=X}if(!await this.options.findUser(J.userId))throw new L("invalid_grant","The refresh token is not valid.");return await this.issue({...J,scopes:z})}default:throw new L("unsupported_grant_type","grant_type must be authorization_code or refresh_token.")}}async issue(W){let Z=Date.now(),$=this.scopeNames(),Q=W.scopes.filter((z)=>$.includes(z)),Y=`${I4}${K1(32).toString("base64url")}`,K=`${f4}${K1(32).toString("base64url")}`,J={clientId:W.clientId,userId:W.userId,scopes:Q,resource:W.resource,familyId:W.familyId};return await this.store.saveToken({...J,hash:n(Y),kind:"access",expiresAt:Z+this.accessTtl*1000}),await this.store.saveToken({...J,hash:n(K),kind:"refresh",expiresAt:Z+this.refreshTtl*1000}),b1({access_token:Y,token_type:"Bearer",expires_in:this.accessTtl,refresh_token:K,scope:Q.join(" ")})}async revoke(W){let Z=await V6(W),$=await this.authenticateClient(W,Z),Q=Z.get("token")??"";if(Q.startsWith(I4)||Q.startsWith(f4)){let Y=await this.store.findToken(n(Q));if(Y&&Y.clientId===$.clientId)await this.store.revokeFamily(Y.familyId)}return new Response(null,{status:200,headers:{"Cache-Control":"no-store"}})}async authenticateClient(W,Z){let $=/^Basic\s+([A-Za-z0-9+/=]+)$/i.exec(W.headers.get("authorization")??""),Q=Z.get("client_id"),Y=Z.get("client_secret");if($){let J=Buffer.from($[1],"base64").toString("utf8"),z=J.indexOf(":");if(z<0)throw J1(!0);let G=T6(J.slice(0,z));if(G===null)throw J1(!0);if(Q!==null&&Q!==G)throw J1(!0);if(Q=G,Y=T6(J.slice(z+1)),Y===null)throw J1(!0)}let K=Q?await this.store.findClient(Q):null;if(!K)throw J1(Boolean($));if(K.tokenEndpointAuthMethod==="none"){if(Y)throw J1(Boolean($));return K}if(!Y||!K.clientSecretHash||!_6(n(Y),K.clientSecretHash))throw J1(Boolean($));return K}redirectBack(W,Z,$,Q=302){let Y=new URL(W);for(let[K,J]of Object.entries($))Y.searchParams.set(K,J);if(Z!==null)Y.searchParams.set("state",Z);return Y.searchParams.set("iss",this.issuer),A4(Y.href,Q)}async sessionUser(W){let Z=new E4(W,{},"api",this.base).cookies;return await P6(C(z1),{cookies:Z,headers:{get:($)=>$.toLowerCase()==="user-agent"?W.headers.get("user-agent"):null}})}userLabel(W){if(this.options.userLabel)return this.options.userLabel(W);let Z=W;return String(Z.email??Z.name??Z.id)}scopeNames(){return this.context.registry.scopes().map((W)=>W.name)}resourceMetadataUrl(){return`${this.issuer}/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`}}var B5={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function R6(W,Z,$){if(Z===void 0)return $;if(!Number.isInteger(Z)||Z<60)throw Error(`McpOAuthServer: ${W} must be a whole number of seconds, at least 60.`);return Z}function n(W){return d4("sha256").update(W).digest("hex")}function O6(W){return d4("sha256").update(W).digest("base64url")}function j5(W){return d4("sha256").update(W).digest("base64url")}function _6(W,Z){let $=Buffer.from(W),Q=Buffer.from(Z);return $.length===Q.length&&Y5($,Q)}function b1(W,Z=200,$={}){return new Response(JSON.stringify(W),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache",...$}})}function A4(W,Z){return new Response(null,{status:Z,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function p(W,Z=400){return new Response(N6(W),{status:Z,headers:i1})}function J1(W){return new L("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function u4(W,Z){let $=Number(W.headers.get("content-length"));if(Number.isFinite($)&&$>Z)throw Error("too large");if(!W.body)return"";let Q=W.body.getReader(),Y=[],K=0;for(;;){let{done:J,value:z}=await Q.read();if(J)break;if(K+=z.byteLength,K>Z)throw await Q.cancel(),Error("too large");Y.push(z)}return Buffer.concat(Y).toString("utf8")}async function V6(W){if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new L("invalid_request","Send the request as application/x-www-form-urlencoded.");let Z;try{Z=new URLSearchParams(await u4(W,c4))}catch{throw new L("invalid_request","The request is too large.")}for(let $ of new Set(Z.keys()))if(Z.getAll($).length>1)throw new L("invalid_request",`${$} was sent more than once.`);return Z}function k6(W,Z,$){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>Z||L5(W))throw new L("invalid_client_metadata",`${$} must be text of at most ${Z} characters.`);return W}function F5(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function w6(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function M5(W){if(typeof W!=="string"||W.length>2048)return"not a URI";let Z;try{Z=new URL(W)}catch{return"not an absolute URI"}if(Z.hash||W.includes("#"))return"must not have a fragment";if(Z.username||Z.password)return"must not carry credentials";if(Z.protocol==="https:")return null;if(Z.protocol==="http:"&&w6(Z))return null;return"must be https, or http on a loopback address"}function h4(W,Z){if(W===Z)return!0;let $,Q;try{$=new URL(W),Q=new URL(Z)}catch{return!1}return $.protocol==="http:"&&Q.protocol==="http:"&&w6($)&&$.hostname===Q.hostname&&$.pathname===Q.pathname&&$.search===Q.search&&!Q.hash&&!Q.username&&!Q.password}function C6(W,Z){return W===Z||W===`${Z}/`}function L5(W){for(let Z=0;Z<W.length;Z++){let $=W.charCodeAt(Z);if($<32||$===127)return!0}return!1}function T6(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class v6{clients=new Map;codes=new Map;tokens=new Map;used=new Map;revoked=new Set;async createClient(W){this.clients.set(W.clientId,structuredClone(W))}async findClient(W){let Z=this.clients.get(W);return Z?structuredClone(Z):null}async saveCode(W){this.sweep(),this.codes.set(W.hash,structuredClone(W))}async findCode(W){let Z=this.codes.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async saveToken(W){this.sweep(),this.tokens.set(W.hash,structuredClone(W))}async findToken(W){let Z=this.tokens.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async use(W,Z){if(this.used.has(W))return!1;return this.used.set(W,Z),!0}async revokeFamily(W){this.revoked.add(W);for(let[Z,$]of this.tokens)if($.familyId===W)this.tokens.delete(Z);for(let[Z,$]of this.codes)if($.familyId===W)this.codes.delete(Z)}async families(W){let Z=new Map;for(let $ of this.tokens.values())if($.userId===W&&!this.revoked.has($.familyId)&&$.expiresAt>Date.now())Z.set($.familyId,{familyId:$.familyId,clientId:$.clientId,scopes:[...$.scopes]});return[...Z.values()]}sweep(W=Date.now()){for(let[Z,$]of this.codes)if($.expiresAt<=W)this.codes.delete(Z);for(let[Z,$]of this.tokens)if($.expiresAt<=W)this.tokens.delete(Z);for(let[Z,$]of this.used)if($<=W)this.used.delete(Z)}}class I6{clients;credentials;uses;usesModel;constructor(W){for(let[Z,$]of[["clients",["create","findUnique","findMany"]],["credentials",["create","findFirst","findMany","count","updateMany","deleteMany"]],["uses",["create","deleteMany"]]]){let Q=W?.[Z],Y=$.filter((K)=>typeof Q?.[K]!=="function");if(Y.length>0)throw Error(`PrismaMcpOAuthStore: models.${Z} must be a gemi ORM model or a Prisma delegate (it has no ${Y.join(", ")}()).`)}this.clients=W.clients,this.credentials=W.credentials,this.usesModel=W.uses,this.uses=new l4(W.uses)}async createClient(W){await this.clients.create({data:{clientId:W.clientId,clientSecretHash:W.clientSecretHash,tokenEndpointAuthMethod:W.tokenEndpointAuthMethod,redirectUris:[...W.redirectUris],clientName:W.clientName,clientUri:W.clientUri,createdAt:new Date(W.createdAt)}})}async findClient(W){let Z=await this.clients.findUnique({where:{clientId:W}});if(!Z)return null;return{clientId:Z.clientId,clientSecretHash:Z.clientSecretHash??null,tokenEndpointAuthMethod:Z.tokenEndpointAuthMethod,redirectUris:a1(Z.redirectUris),clientName:Z.clientName??null,clientUri:Z.clientUri??null,createdAt:t1(Z.createdAt)}}async saveCode(W){await this.credentials.create({data:{hash:W.hash,kind:"code",clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,redirectUri:W.redirectUri,codeChallenge:W.codeChallenge,expiresAt:new Date(W.expiresAt)}})}async findCode(W){let Z=await this.findLive(W,["code"]);if(!Z||Z.redirectUri==null||Z.codeChallenge==null)return null;return{hash:Z.hash,clientId:Z.clientId,userId:Z.userId,redirectUri:Z.redirectUri,codeChallenge:Z.codeChallenge,scopes:a1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:t1(Z.expiresAt)}}async saveToken(W){await this.credentials.create({data:{hash:W.hash,kind:W.kind,clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,expiresAt:new Date(W.expiresAt)}})}async findToken(W){let Z=await this.findLive(W,["access","refresh"]);if(!Z)return null;return{hash:Z.hash,kind:Z.kind,clientId:Z.clientId,userId:Z.userId,scopes:a1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:t1(Z.expiresAt)}}use(W,Z){return this.uses.consume(W,Z)}async revokeFamily(W){await this.credentials.updateMany({where:{familyId:W,revokedAt:null},data:{revokedAt:new Date}})}nonces(W={}){return new l4(this.usesModel,{prefix:W.prefix??"nonce:"})}async connectedApps(W,Z=new Date){let $=String(W),Q=await this.credentials.findMany({where:{userId:$,kind:"refresh",expiresAt:{gt:Z}},orderBy:{createdAt:"asc"}}),Y=await this.revokedFamilies({userId:$}),K=new Map;for(let X of Q){if(Y.has(X.familyId))continue;if(!K.has(X.familyId))K.set(X.familyId,X)}if(K.size===0)return[];let J=[...new Set([...K.values()].map((X)=>X.clientId))],z=await this.clients.findMany({where:{clientId:{in:J}}}),G=new Map(z.map((X)=>[X.clientId,X]));return[...K.values()].map((X)=>({familyId:X.familyId,clientId:X.clientId,clientName:G.get(X.clientId)?.clientName??null,clientUri:G.get(X.clientId)?.clientUri??null,scopes:a1(X.scopes),connectedAt:new Date(t1(X.createdAt))})).reverse()}async disconnect(W,Z){if(await this.credentials.count({where:{familyId:Z,userId:String(W)}})===0)return!1;return await this.revokeFamily(Z),!0}async revokeUser(W){await this.credentials.updateMany({where:{userId:String(W),revokedAt:null},data:{revokedAt:new Date}})}async prune(W=Date.now()){let Z=new Date(W-86400000),$=[...await this.revokedFamilies({expiresAt:{lt:Z}})],Q=$.length===0?[]:await this.credentials.findMany({where:{familyId:{in:$},expiresAt:{gte:Z}},select:{familyId:!0}}),Y=[...new Set(Q.map((K)=>K.familyId))];await this.credentials.deleteMany({where:{expiresAt:{lt:Z},...Y.length>0?{OR:[{revokedAt:null},{familyId:{notIn:Y}}]}:{}}}),await this.usesModel.deleteMany({where:{expiresAt:{lt:new Date(W)}}})}async findLive(W,Z){let $=await this.credentials.findFirst({where:{hash:W,kind:{in:Z},revokedAt:null}});if(!$)return null;return await this.credentials.count({where:{familyId:$.familyId,revokedAt:{not:null}}})>0?null:$}async revokedFamilies(W){let Z=await this.credentials.findMany({where:{...W,revokedAt:{not:null}},select:{familyId:!0}});return new Set(Z.map(($)=>$.familyId))}}function a1(W){return Array.isArray(W)?W.map(String):[]}function t1(W){return W instanceof Date?W.getTime():new Date(W).getTime()}class w1 extends h{application;previous;dispatched=[];static install(W){let Z=W.resolved(h)?W.make(h):void 0;if(Z instanceof w1)return Z;let $=new w1(W,Z);return W.instance(h,$),$}constructor(W,Z){super({listeners:[]});this.application=W;this.previous=Z}dispatch(W,Z){this.dispatched.push({event:W,args:Z})}async dispatchAndWait(W,Z){this.dispatched.push({event:W,args:Z})}restore(){if(this.previous){this.application.instance(h,this.previous);return}this.application.forget(h)}assertDispatched(W,Z){let $=q1(W);if(this.matching($,Z).length>0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} to have been dispatched. ${this.summary($,Z!==void 0)}`)}assertNotDispatched(W,Z){let $=q1(W),Q=this.matching($,Z);if(Q.length===0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} not to have been dispatched, but it was dispatched ${n4(Q.length)}: ${r1(Q)}.`)}assertDispatchedTimes(W,Z,$){let Q=q1(W),Y=this.matching(Q,$);if(Y.length===Z)return;throw Error(`Expected ${Q}${$?" matching the predicate":""} to have been dispatched ${n4(Z)}, but it was dispatched ${n4(Y.length)}. ${this.summary(Q,$!==void 0)}`)}assertNothingDispatched(){if(this.dispatched.length===0)return;let W=this.dispatched.length;throw Error(`Expected nothing to have been dispatched, but ${W} ${W===1?"event was":"events were"}: ${r1(this.dispatched)}.`)}matching(W,Z){return this.dispatched.filter(($)=>q1($.event.constructor)===W&&(Z===void 0||Z($.event)))}summary(W,Z){if(this.dispatched.length===0)return"Nothing was dispatched.";let $=this.matching(W);if(Z&&$.length>0)return`Dispatched ${W}: ${r1($)}.`;return`Dispatched: ${r1(this.dispatched)}.`}}function q1(W){return W.name}function n4(W){return`${W} ${W===1?"time":"times"}`}function r1(W){return W.map(D5).join(", ")}function D5(W){let Z=q1(W.event.constructor),$=W.args??Object.values({...W.event});return`${Z}(${$.map(H5).join(", ")})`}function H5(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class e1{static name="unset";static afterCommit=!1;static dispatch(...W){f6(this),C(h).dispatch(new this(...W),W)}static dispatchAndWait(...W){return f6(this),C(h).dispatchAndWait(new this(...W),W)}static fake(){return w1.install(N5())}}function N5(){try{return C()}catch(W){throw Error("Event.fake() needs a booted application. The fake works by replacing the container's EventManager with a recorder, so there has to be a "+"container to replace it in \u2014 and a dispatch finds the recorder the "+"same way, by resolving from that container. Boot the app's kernel in the test's setup: `const kernel = new Kernel(); kernel.boot()` is enough on its own, since that is the phase that publishes the application every dispatch outside a request resolves through.",{cause:W})}}function f6(W){if(W.name!=="unset"&&W.name!=="")return;throw Error("Cannot dispatch an event with no name. Add `static name` to this Event "+"subclass \u2014 the listener registry is keyed by that string, and by that "+"string alone, so an event without one cannot reach a listener.")}class h6 extends e1{constructor(){super();Object.defineProperty(this,i4,{value:!0,enumerable:!1})}broadcastAs(){return this.constructor.name}broadcastWith(){return}channel(W,...Z){return{topic:y6(W,Z[0]??{}),pattern:W}}}function m6(){try{let W=C();if(typeof W?.bound==="function"&&W.bound(z1))return W.make(z1).config.emailCode}catch{}return}function U5(){return E6(m6())}function x5(W){return g6(W,m6())}function S5(W){let Z=null;try{let K=C();if(typeof K?.bound==="function"&&K.bound(s4))Z=C(s4).resolver??null}catch{Z=null}if(Z)return Z.publicOrigin(W);let $=new URL(W.url),Q=W.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return`${Q==="http"||Q==="https"?Q:$.protocol.slice(0,-1)}://${$.host}`}function R5(W,Z){let $=typeof W==="string"?W.trim().replace(/\/+$/,""):"",Q=URL.canParse($)?new URL($):null;if(!Q||Q.protocol!=="http:"&&Q.protocol!=="https:"||Q.origin!==$)throw Error(`${Z}: resolve() returned origin ${JSON.stringify(W)}, which is not an http(s) origin such as https://example.com.`);return $}var c6=new WeakMap;function a(W,Z,$){if(!$.resolve)return Promise.resolve({clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.staticRedirectUri()});let Q=Z?.rawRequest;if(!Z||!Q)return Promise.resolve(null);let Y=c6.get(W);if(!Y)Y=new WeakMap,c6.set(W,Y);let K=Y.get(Q);if(K)return K;let J=$.resolve,z=(async()=>{let G=await J({req:Z,origin:S5(Q)});if(G===null||G===void 0)return null;let X=G.origin!==void 0?R5(G.origin,$.name):$.staticOrigin();return{clientId:G.clientId??$.clientId,clientSecret:G.clientSecret??$.clientSecret,redirectUri:`${X}${$.redirectPath}`}})();return Y.set(Q,z),z.catch(()=>Y.delete(Q)),z}var O5={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 https://www.googleapis.com/auth/userinfo.email",authorizationParams:{}};function _5(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class u6 extends i{config;constructor(W={}){super();this.config={...O5,...W}}redirectUri(){return`${w()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"GoogleOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>w()??""})}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GoogleOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}authorizationUrl(W,Z){let $=new URL("https://accounts.google.com/o/oauth2/v2/auth"),Q={include_granted_scopes:"true",...this.config.authorizationParams,scope:this.config.scope,response_type:"code",redirect_uri:W.redirectUri,client_id:W.clientId};if(Z)Q.state=Z.state,Q.code_challenge=Z.codeChallenge,Q.code_challenge_method=Z.codeChallengeMethod;for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new R("missing_code");let Q=this.config.resolve?await this.clientFor(W):this.staticClient();if(!Q)throw new R("unknown_provider");let Y=new URLSearchParams({code:$,client_id:Q.clientId,client_secret:Q.clientSecret,grant_type:"authorization_code",redirect_uri:Q.redirectUri});if(Z?.codeVerifier)Y.set("code_verifier",Z.codeVerifier);let K=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y.toString()}),J=await K.json().catch(()=>({}));if(!K.ok||typeof J?.access_token!=="string"||J.access_token==="")throw console.error("Google OAuth error: token exchange failed",J?.error??K.status),new R(_5(J?.error,"exchange_failed"));let G=await(await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${J.access_token}`}})).json().catch(()=>({}));if(typeof G.sub!=="string"||G.sub==="")return console.error("Google OAuth error: sub not found in user info response",G),{};if(!G.email)console.error("Google OAuth error: email not found in user info response",G);return{providerId:G.sub,name:G.name,email:G.email,emailVerified:G.email_verified===!0||G.email_verified==="true"}}}var V5="https://github.com/login/oauth/authorize",k5="https://github.com/login/oauth/access_token",p6="https://api.github.com";function C5(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class d6 extends i{config;constructor(W={}){super();this.config={clientId:process.env.GITHUB_CLIENT_ID??"",clientSecret:process.env.GITHUB_CLIENT_SECRET??"",redirectPath:"/auth/oauth/github/callback",scope:"read:user user:email",authorizationParams:{},...W}}redirectUri(){return`${w()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"GitHubOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>w()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GitHubOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(V5),Q={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,scope:this.config.scope,response_type:"code"};if(Z)Q.state=Z.state,Q.code_challenge=Z.codeChallenge,Q.code_challenge_method=Z.codeChallengeMethod;for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new R("missing_code");let Q=this.config.resolve?await this.clientFor(W):this.staticClient();if(!Q)throw new R("unknown_provider");let Y=new URLSearchParams({client_id:Q.clientId,client_secret:Q.clientSecret,code:$,redirect_uri:Q.redirectUri});if(Z?.codeVerifier)Y.set("code_verifier",Z.codeVerifier);let K=await fetch(k5,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:Y.toString()}),J=await K.json().catch(()=>({}));if(!K.ok||typeof J?.access_token!=="string"||J.access_token==="")throw console.error("GitHub OAuth error: token exchange failed",J?.error??K.status),new R(C5(J?.error,"exchange_failed"));let z={Accept:"application/vnd.github+json",Authorization:`Bearer ${J.access_token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"gemi"},G=await fetch(`${p6}/user`,{headers:z}),X=await G.json().catch(()=>({}));if(!G.ok||typeof X?.id!=="number"||!Number.isSafeInteger(X.id))return console.error("GitHub OAuth error: no user id in the /user response",G.status),{};let B=typeof X.login==="string"&&X.login!==""?X.login:void 0,j=typeof X.name==="string"&&X.name!==""?X.name:B,D=await this.primaryVerifiedEmail(z),x=typeof X.email==="string"&&X.email!==""?X.email:void 0;return{providerId:String(X.id),username:B,name:j,...D?{email:D,emailVerified:!0}:x?{email:x,emailVerified:!1}:{}}}async primaryVerifiedEmail(W){let Z=await fetch(`${p6}/user/emails`,{headers:W}).catch(()=>null);if(!Z?.ok){console.error("GitHub OAuth error: could not read /user/emails",Z?.status);return}let $=await Z.json().catch(()=>null);if(!Array.isArray($))return;let Q=$.find((Y)=>Y?.primary===!0&&Y.verified===!0);return typeof Q?.email==="string"&&Q.email!==""?Q.email:void 0}}var t="https://api.x.com/2/",F1="https://api.x.com/labs/2/",r="https://api.x.com/1.1/",s="https://upload.x.com/1.1/",l6="https://stream.x.com/1.1/",M1="https://ads-api.x.com/12/",L1="https://ads-api-sandbox.twitter.com/12/";class o4{constructor({realData:W,rateLimit:Z,instance:$,queryParams:Q,sharedParams:Y}){this._maxResultsWhenFetchLast=100,this._realData=W,this._rateLimit=Z,this._instance=$,this._queryParams=Q,this._sharedParams=Y}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(W){return this._instance.get(this.getEndpoint(),W,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(W,Z){return new this.constructor({realData:W.data,rateLimit:W.rateLimit,instance:this._instance,queryParams:Z,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(W){return{...W?{max_results:W}:{},...this._queryParams}}async next(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchNext(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!0),this}async fetchLast(W=1/0){let Z=this.getNextQueryParams(this._maxResultsWhenFetchLast),$=0;while($<W&&this._isRateLimitOk){let Q=await this.makeRequest(Z);if(await this.refreshInstanceFromResult(Q,!0),$+=this.getPageLengthFromRequest(Q),this.isFetchLastOver(Q))break;Z=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var W;return{...(W=this._rateLimit)!==null&&W!==void 0?W:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData),yield*$.getItemArray(),W=$}}async*fetchAndIterate(){for(let $ of this.getItemArray())yield[$,this];let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData);for(let Q of $.getItemArray())yield[Q,$];this._rateLimit=$._rateLimit,W=$}}}class a4 extends o4{async previous(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchPrevious(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!1),this}}var D1=o4;class O extends D1{getNextQueryParams(W){var Z;return{...this._queryParams,cursor:(Z=this._realData.next_cursor_str)!==null&&Z!==void 0?Z:this._realData.next_cursor,...W?{count:W}:{}}}isFetchLastOver(W){return!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!this.isNextCursorInvalid(W.next_cursor)||!this.isNextCursorInvalid(W.next_cursor_str)}isNextCursorInvalid(W){return W===void 0||W===0||W===-1||W==="0"||W==="-1"}}class t4 extends O{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.events.push(...$.events),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class r4 extends O{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.welcome_messages.push(...$.welcome_messages),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var N;(function(W){W.Jpeg="image/jpeg",W.Mp4="video/mp4",W.Mov="video/quicktime",W.Gif="image/gif",W.Png="image/png",W.Srt="text/plain",W.Webp="image/webp"})(N||(N={}));var e;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(e||(e={}));var v1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(v1||(v1={}));class W4 extends Error{constructor(){super(...arguments);this.error=!0}}class I1 extends W4{constructor(W,Z){super(W);this.type=v1.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class f1 extends W4{constructor(W,Z){super(W);this.type=v1.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}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 y1 extends W4{constructor(W,Z){super(W);if(this.type=v1.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z}),this.code=Z.code,this.headers=Z.headers,this.rateLimit=Z.rateLimit,Z.data&&typeof Z.data==="object"&&"error"in Z.data&&!Z.data.errors){let $={...Z.data};$.errors=[{code:G1.InternalError,message:$.error}],this.data=$}else this.data=Z.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...W){let Z=this.errors;if(!(Z===null||Z===void 0?void 0:Z.length))return!1;if("code"in Z[0])return Z.some((Y)=>W.includes(Y.code));let $=this.data;return W.includes($.type)}get errors(){var W;return(W=this.data)===null||W===void 0?void 0:W.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(G1.AuthTimestampInvalid,G1.AuthenticationFail,G1.BadAuthenticationData,G1.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var G1;(function(W){W[W.InvalidCoordinates=3]="InvalidCoordinates",W[W.NoLocationFound=13]="NoLocationFound",W[W.AuthenticationFail=32]="AuthenticationFail",W[W.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",W[W.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",W[W.AuthTimestampInvalid=135]="AuthTimestampInvalid",W[W.BadAuthenticationData=215]="BadAuthenticationData",W[W.NoUserMatch=17]="NoUserMatch",W[W.UserNotFound=50]="UserNotFound",W[W.ResourceNotFound=34]="ResourceNotFound",W[W.TweetNotFound=144]="TweetNotFound",W[W.TweetNotVisible=179]="TweetNotVisible",W[W.NotAllowedResource=220]="NotAllowedResource",W[W.MediaIdNotFound=325]="MediaIdNotFound",W[W.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",W[W.TweetViolatedRules=422]="TweetViolatedRules",W[W.TargetUserSuspended=63]="TargetUserSuspended",W[W.YouAreSuspended=64]="YouAreSuspended",W[W.AccountUpdateFailed=120]="AccountUpdateFailed",W[W.NoSelfSpamReport=36]="NoSelfSpamReport",W[W.NoSelfMute=271]="NoSelfMute",W[W.AccountLocked=326]="AccountLocked",W[W.RateLimitExceeded=88]="RateLimitExceeded",W[W.NoDMRightForApp=93]="NoDMRightForApp",W[W.OverCapacity=130]="OverCapacity",W[W.InternalError=131]="InternalError",W[W.TooManyFollowings=161]="TooManyFollowings",W[W.TweetLimitExceeded=185]="TweetLimitExceeded",W[W.DuplicatedTweet=187]="DuplicatedTweet",W[W.TooManySpamReports=205]="TooManySpamReports",W[W.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",W[W.NoWriteRightForApp=261]="NoWriteRightForApp",W[W.TweetActionsDisabled=425]="TweetActionsDisabled",W[W.TweetRepliesRestricted=433]="TweetRepliesRestricted",W[W.NamedParameterMissing=38]="NamedParameterMissing",W[W.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",W[W.TweetTextTooLong=186]="TweetTextTooLong",W[W.MissingUrlParameter=195]="MissingUrlParameter",W[W.NoMultipleGifs=323]="NoMultipleGifs",W[W.InvalidMediaIds=324]="InvalidMediaIds",W[W.InvalidUrl=407]="InvalidUrl",W[W.TooManyTweetAttachments=386]="TooManyTweetAttachments",W[W.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",W[W.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",W[W.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",W[W.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",W[W.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",W[W.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",W[W.UnableToSendDM=151]="UnableToSendDM",W[W.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",W[W.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",W[W.DMTextTooLong=354]="DMTextTooLong",W[W.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",W[W.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",W[W.SuspendedApplication=416]="SuspendedApplication",W[W.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(G1||(G1={}));var n6;(function(W){W.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",W.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",W.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",W.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",W.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",W.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",W.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",W.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",W.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",W.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",W.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",W.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",W.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(n6||(n6={}));var F;(function(W){W.Connected="connected",W.ConnectError="connect error",W.ConnectionError="connection error",W.ConnectionClosed="connection closed",W.ConnectionLost="connection lost",W.ReconnectAttempt="reconnect attempt",W.Reconnected="reconnected",W.ReconnectError="reconnect error",W.ReconnectLimitExceeded="reconnect limit exceeded",W.DataKeepAlive="data keep-alive",W.Data="data event content",W.DataError="data twitter error",W.TweetParseError="data tweet parse error",W.Error="stream error"})(F||(F={}));class A1{constructor(W){this.value=W}}import*as V0 from"fs";var k={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function e4(W){let Z={value:void 0,promise:W().then(($)=>{return Z.value=$,$})};return Z}function Z4(W){if(Array.isArray(W))return W;return[W]}function s6(W){for(let Z of Object.keys(W))if(W[Z]===void 0)delete W[Z]}function $4(W){return typeof W==="object"&&"errors"in W&&!("data"in W)}function h1(W){if(Array.isArray(W)&&W.length>1)return!0;return W.toString().includes(",")}var i6=new Set;function W0(W){if(typeof console>"u"||!console.warn||!k.deprecationWarnings)return;let Z=`${W.instance}-${W.method}-${W.problem}`;if(i6.has(Z))return;let $=`[twitter-api-v2] Deprecation warning: In ${W.instance}.${W.method}() call, ${W.problem}.
65
+ ${W.resolution}.`;console.warn($),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),i6.add(Z)}import{EventEmitter as w5}from"events";import{request as T5}from"https";import*as P from"zlib";import{EventEmitter as P5}from"events";class o6{constructor(W){this.requestData=W,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let W=this.requestData.url;return W.hostname+W.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(W){if(k.debug)k.logger.log("Request error:",W);return new I1("Request failed.",{request:this.req,error:W})}createPartialResponseError(W,Z){let Q=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(Z)Q+=" (connection abruptly closed)";else Q+=" (parse error)";return new f1(Q,{request:this.req,response:this.res,responseError:W,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(W){return W.map(({code:Z,message:$})=>`${$} (Twitter code ${Z})`).join(", ")}formatV2Error(W){return`${W.title}: ${W.detail} (see ${W.type})`}createResponseError({res:W,data:Z,rateLimit:$,code:Q}){var Y;if(k.debug)k.logger.log(`Request failed with code ${Q}, data:`,Z),k.logger.log("Response headers:",W.headers);let K=`Request failed with code ${Q}`;if((Y=Z===null||Z===void 0?void 0:Z.errors)===null||Y===void 0?void 0:Y.length){let J=Z.errors;if(typeof J[0]==="object"&&"code"in J[0])K+=" - "+this.formatV1Errors(J);else K+=" - "+this.formatV2Error(Z)}return new y1(K,{code:Q,data:Z,headers:W.headers,request:this.req,response:W,rateLimit:$})}getResponseDataStream(W){if(this.isCompressionDisabled())return W;let Z=(W.headers["content-encoding"]||"identity").trim().toLowerCase();if(Z==="br"){let $=P.createBrotliDecompress({flush:P.constants.BROTLI_OPERATION_FLUSH,finishFlush:P.constants.BROTLI_OPERATION_FLUSH});return W.pipe($),$}if(Z==="gzip"){let $=P.createGunzip({flush:P.constants.Z_SYNC_FLUSH,finishFlush:P.constants.Z_SYNC_FLUSH});return W.pipe($),$}if(Z==="deflate"){let $=P.createInflate({flush:P.constants.Z_SYNC_FLUSH,finishFlush:P.constants.Z_SYNC_FLUSH});return W.pipe($),$}return W}detectResponseType(W){var Z,$;if(((Z=W.headers["content-type"])===null||Z===void 0?void 0:Z.includes("application/json"))||(($=W.headers["content-type"])===null||$===void 0?void 0:$.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(W){let Z=this.responseData,$=this.requestData.forceParseMode||this.detectResponseType(W);if($==="buffer")return Buffer.concat(Z);else if($==="text")return Buffer.concat(Z).toString();else if($==="json"){let Q=Buffer.concat(Z).toString();return Q.length?JSON.parse(Q):void 0}else if($==="url"){let Q=Buffer.concat(Z).toString(),Y={};for(let[K,J]of new URLSearchParams(Q))Y[K]=J;return Y}else return}getRateLimitFromResponse(W){let Z=void 0;if(W.headers["x-rate-limit-limit"]){if(Z={limit:Number(W.headers["x-rate-limit-limit"]),remaining:Number(W.headers["x-rate-limit-remaining"]),reset:Number(W.headers["x-rate-limit-reset"])},W.headers["x-app-limit-24hour-limit"])Z.day={limit:Number(W.headers["x-app-limit-24hour-limit"]),remaining:Number(W.headers["x-app-limit-24hour-remaining"]),reset:Number(W.headers["x-app-limit-24hour-reset"])};if(W.headers["x-user-limit-24hour-limit"])Z.userDay={limit:Number(W.headers["x-user-limit-24hour-limit"]),remaining:Number(W.headers["x-user-limit-24hour-remaining"]),reset:Number(W.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(Z)}return Z}onSocketEventHandler(W,Z,$){let Q=this.onSocketCloseHandler.bind(this,W);$.on("close",Q),Z.on("complete",()=>$.off("close",Q))}onSocketCloseHandler(W){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return W(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(W,Z){var $,Q;(Q=($=this.requestData).requestEventDebugHandler)===null||Q===void 0||Q.call($,"request-error",{requestError:Z}),this.requestErrorHandled=!0,W(this.createRequestError(Z))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(W,Z,$){this.res=$;let Q=this.getResponseDataStream($);if(Q.on("data",(Y)=>this.responseData.push(Y)),Q.on("end",this.onResponseEndHandler.bind(this,W,Z)),Q.on("close",this.onResponseCloseHandler.bind(this,W,Z)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:$}),$.on("aborted",(Y)=>this.requestData.requestEventDebugHandler("response-aborted",{error:Y})),$.on("error",(Y)=>this.requestData.requestEventDebugHandler("response-error",{error:Y})),$.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),$.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(W,Z){let $=this.getRateLimitFromResponse(this.res),Q;try{Q=this.getParsedResponse(this.res)}catch(K){Z(this.createPartialResponseError(K,!1));return}let Y=this.res.statusCode;if(Y>=400){Z(this.createResponseError({data:Q,res:this.res,rateLimit:$,code:Y}));return}if(k.debug)k.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),k.logger.log("Response body:",Q);W({data:Q,headers:this.res.headers,rateLimit:$})}onResponseCloseHandler(W,Z){let $=this.res;if($.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(W,Z)}catch(Q){return Z(this.createPartialResponseError(Q,!0))}if(!$.complete)return Z(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(W,Z,$){if($.statusCode<400){if(k.debug)k.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${$.statusCode} (starting stream)`);let Y=this.getResponseDataStream($);W({req:this.req,res:Y,originalResponse:$,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},Z,$)}debugRequest(){let W=this.requestData.url;if(k.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),W.search)k.logger.log("Request parameters:",[...W.searchParams.entries()].map(([Z,$])=>`${Z}: ${$}`));if(this.requestData.body)k.logger.log("Request body:",this.requestData.body)}buildRequest(){var W;let Z=this.requestData.url,$=Z.username?`${Z.username}:${Z.password}`:void 0,Q=(W=this.requestData.options.headers)!==null&&W!==void 0?W:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")Q["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")Q["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")Q["accept-encoding"]="deflate;q=1, *;q=0.1";if(k.debug)this.debugRequest();this.req=T5({...this.requestData.options,host:Z.hostname,port:Z.port||void 0,path:Z.pathname+Z.search,protocol:Z.protocol,auth:$,headers:Q})}registerRequestEventDebugHandlers(W){W.on("close",()=>this.requestData.requestEventDebugHandler("close")),W.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),W.on("socket",(Z)=>{this.requestData.requestEventDebugHandler("socket",{socket:Z}),Z.on("error",($)=>this.requestData.requestEventDebugHandler("socket-error",{socket:Z,error:$})),Z.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:Z})),Z.on("close",($)=>this.requestData.requestEventDebugHandler("socket-close",{socket:Z,withError:$})),Z.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:Z})),Z.on("lookup",(...$)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:Z,data:$})),Z.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:Z}))})}makeRequest(){return this.buildRequest(),new Promise((W,Z)=>{let $=(J)=>{Y.emit("complete"),W(J)},Q=(J)=>{Y.emit("complete"),Z(J)},Y=new P5,K=this.req;if(K.on("error",this.requestErrorHandler.bind(this,Q)),K.on("socket",this.onSocketEventHandler.bind(this,Q,Y)),K.on("response",this.classicResponseHandler.bind(this,$,Q)),this.requestData.options.timeout)K.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(K);if(this.requestData.body)K.write(this.requestData.body);K.end()})}async makeRequestAsStream(){let{req:W,res:Z,requestData:$,originalResponse:Q}=await this.makeRequestAndResolveWhenReady();return new Q4($,{req:W,res:Z,originalResponse:Q})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((W,Z)=>{let $=this.req;if($.on("error",this.requestErrorHandler.bind(this,Z)),$.on("response",this.streamResponseHandler.bind(this,W,Z)),this.requestData.body)$.write(this.requestData.body);$.end()})}}var E1=o6;import{EventEmitter as b5}from"events";class a6 extends b5{constructor(W){super();this.stream=W,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),W.on(F.Data,this.onStreamData),W.on(F.ConnectionError,this.onStreamError),W.on(F.TweetParseError,this.onStreamError),W.on(F.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let W=this.stack;return this.stack=[],W}destroy(){this.removeAllListeners(),this.stream.off(F.Data,this.onStreamData),this.stream.off(F.ConnectionError,this.onStreamError),this.stream.off(F.TweetParseError,this.onStreamError),this.stream.off(F.ConnectionClosed,this.onStreamError)}emitEvent(W,Z){this.emit("event",{type:W,payload:Z})}onStreamError(W){this.emitEvent("error",W)}onStreamData(W){this.stack.push(W),this.emitEvent("data",W)}}var t6=a6;import{EventEmitter as q5}from"events";class Y4 extends q5{constructor(){super(...arguments);this.currentMessage=""}push(W){this.currentMessage+=W,W=this.currentMessage;let Z=W.length,$=0,Q=0;while(Q<Z){if(W.slice(Q,Q+2)===`\r
66
+ `){let Y=W.slice($,Q);if($=Q+=2,!Y.length)continue;try{let K=JSON.parse(Y);if(K){this.emit(X1.ParsedData,K);continue}}catch(K){this.emit(X1.ParseError,K)}}Q++}this.currentMessage=W.slice($,Z)}reset(){this.currentMessage=""}}var X1;(function(W){W.ParsedData="parsed data",W.ParseError="parse error"})(X1||(X1={}));var r6=[5,15,30,60,90,120,180,300,600,900],v5=(W)=>W>r6.length?901000:r6[W-1]*1000;class e6 extends w5{constructor(W,Z){super();if(this.requestData=W,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=v5,this.parser=new Y4,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),Z)this.req=Z.req,this.res=Z.res,this.originalResponse=Z.originalResponse,this.initEventsFromRequest()}on(W,Z){return super.on(W,Z)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let W=(Z)=>{this.emit(F.ConnectionError,Z),this.emit(F.Error,{type:F.ConnectionError,error:Z,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",W),this.res.on("error",W),this.res.on("close",()=>W(Error("Connection closed by Twitter."))),this.res.on("data",(Z)=>{if(this.resetKeepAliveTimeout(),Z.toString()===`\r
67
+ `)return this.emit(F.DataKeepAlive);this.parser.push(Z.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let W=this.requestData.payloadIsError;this.parser.on(X1.ParsedData,(Z)=>{if(W&&W(Z))this.emit(F.DataError,Z),this.emit(F.Error,{type:F.DataError,error:Z,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(F.Data,Z)}),this.parser.on(X1.ParseError,(Z)=>{this.emit(F.TweetParseError,Z),this.emit(F.Error,{type:F.TweetParseError,error:Z,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(F.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(F.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let Z=await new E1(this.requestData).makeRequestAsStream(),$=this.eventNames();for(let Q of $){let Y=this.listeners(Q);for(let K of Y)Z.on(Q,K)}return Z}async connect(W={}){if(typeof W.autoReconnect<"u")this.autoReconnect=W.autoReconnect;if(typeof W.autoReconnectRetries<"u")this.autoReconnectRetries=W.autoReconnectRetries==="unlimited"?1/0:W.autoReconnectRetries;if(typeof W.keepAliveTimeout<"u")this.keepAliveTimeoutMs=W.keepAliveTimeout==="disable"?1/0:W.keepAliveTimeout;if(typeof W.nextRetryTimeout<"u")this.nextRetryTimeout=W.nextRetryTimeout;this.unbindTimeouts();try{await this.reconnect()}catch(Z){if(this.emit(F.ConnectError,0),this.emit(F.Error,{type:F.ConnectError,error:Z,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,Z);else throw Z}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let W=!0;if(this.req)W=!1,this.closeWithoutEmit();let{req:Z,res:$,originalResponse:Q}=await new E1(this.requestData).makeRequestAndResolveWhenReady();this.req=Z,this.res=$,this.originalResponse=Q,this.emit(W?F.Connected:F.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(W=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(F.ConnectionClosed);return}if(W>=this.autoReconnectRetries){this.emit(F.ReconnectLimitExceeded),this.emit(F.ConnectionClosed);return}try{this.emit(F.ReconnectAttempt,W),await this.reconnect()}catch(Z){this.emit(F.ReconnectError,W),this.emit(F.Error,{type:F.ReconnectError,error:Z,message:`Reconnect error - ${W+1} attempts made yet.`}),this.makeAutoReconnectRetry(W,Z)}}makeAutoReconnectRetry(W,Z){let $=this.nextRetryTimeout(W+1,Z);this.retryTimeout=setTimeout(()=>{this.onConnectionError(W+1)},$)}async*[Symbol.asyncIterator](){let W=new t6(this);try{while(!0){if(!this.req||this.req.aborted)throw Error("Connection closed");if(W.hasStack())yield*W.popStack();let{type:Z,payload:$}=await W.nextEvent();if(Z==="error")throw $}}finally{W.destroy()}}}var Q4=e6;function WW(W){var Z;if(!((Z=W.clientSettings.plugins)===null||Z===void 0?void 0:Z.length))return!1;for(let $ of W.clientSettings.plugins)if($.onRequestError||$.onResponseError)return!0;return!1}async function ZW(W,Z,$,Q){let Y;if(Q instanceof I1||Q instanceof f1)Y=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:Q});else if(Q instanceof y1)Y=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:Q});if(Y&&Y instanceof A1)return Y.value;return Promise.reject(Q)}import*as YW from"crypto";class E{constructor(W){this.nonceLength=32,this.consumerKeys=W.consumerKeys}static percentEncode(W){return encodeURIComponent(W).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(W,Z){return YW.createHmac("sha1",Z).update(W).digest("base64")}authorize(W,Z={}){let $={oauth_consumer_key:this.consumerKeys.key,oauth_nonce:this.getNonce(),oauth_signature_method:"HMAC-SHA1",oauth_timestamp:this.getTimestamp(),oauth_version:"1.0"};if(Z.key!==void 0)$.oauth_token=Z.key;if(!W.data)W.data={};return $.oauth_signature=this.getSignature(W,Z.secret,$),$}toHeader(W){let Z=QW(W),$="OAuth ";for(let Q of Z){if(Q.key.indexOf("oauth_")!==0)continue;$+=E.percentEncode(Q.key)+'="'+E.percentEncode(Q.value)+'",'}return{Authorization:$.slice(0,$.length-1)}}getNonce(){let Z="";for(let $=0;$<this.nonceLength;$++)Z+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.trunc(Math.random()*62)];return Z}getTimestamp(){return Math.trunc(new Date().getTime()/1000)}getSignature(W,Z,$){return this.hash(this.getBaseString(W,$),this.getSigningKey(Z))}getSigningKey(W){return E.percentEncode(this.consumerKeys.secret)+"&"+E.percentEncode(W||"")}getBaseString(W,Z){return W.method.toUpperCase()+"&"+E.percentEncode(this.getBaseUrl(W.url))+"&"+E.percentEncode(this.getParameterString(W,Z))}getParameterString(W,Z){let $=QW(y5($W(Z,$W(W.data,f5(W.url))))),Q="";for(let{key:Y,value:K}of $)if(K&&Array.isArray(K)){K.sort();let J="";K.forEach((z,G)=>{if(J+=Y+"="+z,G<K.length)J+="&"}),Q+=J}else Q+=Y+"="+K+"&";return Q.slice(0,Q.length-1)}getBaseUrl(W){return W.split("?")[0]}}var g1=E;function $W(W,Z){return{...W||{},...Z||{}}}function QW(W){return Object.keys(W).sort().map((Z)=>({key:Z,value:W[Z]}))}function I5(W){let Z=W.split("&"),$={};for(let Q of Z){let[Y,K=""]=Q.split("=");if($[Y]){if(!Array.isArray($[Y]))$[Y]=[$[Y]];$[Y].push(decodeURIComponent(K))}else $[Y]=decodeURIComponent(K)}return $}function f5(W){let Z=W.split("?");if(Z.length===1)return{};return I5(Z[1])}function y5(W){let Z={};for(let $ in W){let Q=W[$];if(Q&&Array.isArray(Q))Q=Q.map((Y)=>E.percentEncode(Y));else Q=E.percentEncode(Q);Z[E.percentEncode($)]=Q}return Z}class g{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...W){let Z=W.map(($)=>$ instanceof Buffer?$:Buffer.from($));this._chunks.push(...Z)}append(W,Z,$){let Q=Z instanceof Buffer?Z:Z.toString(),Y=this.getMultipartHeader(W,Q,$);this.bodyAppend(Y,Q,g.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((W,Z)=>W+Z.length,this.getMultipartFooter().length)}getBuffer(){let W=[...this._chunks,this.getMultipartFooter()],Z=Buffer.alloc(this.getLength()),$=0;for(let Q of W)for(let Y=0;Y<Q.length;$++,Y++)Z[$]=Q[Y];return Z}getBoundary(){if(!this._boundary)this.generateBoundary();return this._boundary}generateBoundary(){let W="--------------------------";for(let Z=0;Z<24;Z++)W+=Math.floor(Math.random()*10).toString(16);this._boundary=W}getMultipartHeader(W,Z,$){if(!$)$=Z instanceof Buffer?g.DEFAULT_CONTENT_TYPE:"";let Q={"Content-Disposition":["form-data",`name="${W}"`],"Content-Type":$},Y="";for(let[K,J]of Object.entries(Q)){if(!J.length)continue;Y+=K+": "+Z4(J).join("; ")+g.LINE_BREAK}return"--"+this.getBoundary()+g.LINE_BREAK+Y+g.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+g.LINE_BREAK)}}g.LINE_BREAK=`\r
68
+ `;g.DEFAULT_CONTENT_TYPE="application/octet-stream";class Z0{static formatQueryToString(W){let Z={};for(let $ in W)if(typeof W[$]==="string")Z[$]=W[$];else if(typeof W[$]<"u")Z[$]=String(W[$]);return Z}static autoDetectBodyType(W){if(W.pathname.startsWith("/2/")||W.pathname.startsWith("/labs/2/")){if(W.password.startsWith("/2/oauth2"))return"url";return"json"}if(W.hostname==="upload.x.com"){if(W.pathname==="/1.1/media/upload.json")return"form-data";return"json"}let Z=W.pathname.split("/1.1/",2)[1];if(this.JSON_1_1_ENDPOINTS.has(Z))return"json";return"url"}static addQueryParamsToUrl(W,Z){let $=Object.entries(Z);if($.length){let Q="";for(let[Y,K]of $)Q+=(Q.length?"&":"?")+`${g1.percentEncode(Y)}=${g1.percentEncode(K)}`;W.search=Q}}static constructBodyParams(W,Z,$){if(W instanceof Buffer)return W;if($==="json"){if(!Z["content-type"])Z["content-type"]="application/json;charset=UTF-8";return JSON.stringify(W)}else if($==="url"){if(!Z["content-type"])Z["content-type"]="application/x-www-form-urlencoded;charset=UTF-8";if(Object.keys(W).length)return new URLSearchParams(W).toString().replace(/\*/g,"%2A");return""}else if($==="raw")throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");else{let Q=new g;for(let Y in W)Q.append(Y,W[Y]);if(!Z["content-type"]){let Y=Q.getHeaders();Z["content-type"]=Y["content-type"]}return Q.getBuffer()}}static setBodyLengthHeader(W,Z){var $;if(W.headers=($=W.headers)!==null&&$!==void 0?$:{},typeof Z==="string")W.headers["content-length"]=Buffer.byteLength(Z);else W.headers["content-length"]=Z.length}static isOAuthSerializable(W){return!(W instanceof Buffer)}static mergeQueryAndBodyForOAuth(W,Z){let $={};for(let Q in W)$[Q]=W[Q];if(this.isOAuthSerializable(Z))for(let Q in Z){let Y=Z[Q];if(this.isOAuthSerializable(Y))$[Q]=typeof Y==="object"&&Y!==null&&"toString"in Y?Y.toString():Y}return $}static moveUrlQueryParamsIntoObject(W,Z){for(let[$,Q]of W.searchParams)Z[$]=Q;return W.search="",W}static applyRequestParametersToUrl(W,Z){return W.pathname=W.pathname.replace(/:([A-Z_-]+)/ig,($,Q)=>{if(Z[Q]!==void 0)return String(Z[Q]);return $}),W}}Z0.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"]);var v=Z0;import*as KW from"crypto";class B1{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url(KW.createHash("sha256").update(W).digest("base64"))}static getAuthHeader(W,Z){let $=encodeURIComponent(W)+":"+encodeURIComponent(Z);return Buffer.from($).toString("base64")}static generateRandomString(W){let Z="",$="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let Q=0;Q<W;Q++)Z+=$[Math.floor(Math.random()*$.length)];return Z}static escapeBase64Url(W){return W.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class H1{constructor(W){if(this.rateLimits={},this.clientSettings={},W)this.clientSettings=W}getRateLimits(){return this.rateLimits}saveRateLimit(W,Z){this.rateLimits[W]=Z}async send(W){var Z,$,Q,Y,K;if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length){let j=await this.applyPreRequestConfigHooks(W);if(j)return j}let J=this.getHttpRequestArgs(W),z={method:J.method,headers:J.headers,timeout:W.timeout,agent:this.clientSettings.httpAgent},G=W.enableRateLimitSave!==!1;if(J.body)v.setBodyLengthHeader(z,J.body);if(($=this.clientSettings.plugins)===null||$===void 0?void 0:$.length)await this.applyPreRequestHooks(W,J,z);let X=new E1({url:J.url,options:z,body:J.body,rateLimitSaver:G?this.saveRateLimit.bind(this,J.rawUrl):void 0,requestEventDebugHandler:W.requestEventDebugHandler,compression:(Y=(Q=W.compression)!==null&&Q!==void 0?Q:this.clientSettings.compression)!==null&&Y!==void 0?Y:!0,forceParseMode:W.forceParseMode}).makeRequest();if(WW(this))X=this.applyResponseErrorHooks(W,J,z,X);let B=await X;if((K=this.clientSettings.plugins)===null||K===void 0?void 0:K.length){let j=await this.applyPostRequestHooks(W,J,z,B);if(j)return j.value}return B}sendStream(W){var Z,$;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(W);let Q=this.getHttpRequestArgs(W),Y={method:Q.method,headers:Q.headers,agent:this.clientSettings.httpAgent},K=W.enableRateLimitSave!==!1,J=W.autoConnect!==!1;if(Q.body)v.setBodyLengthHeader(Y,Q.body);let z={url:Q.url,options:Y,body:Q.body,rateLimitSaver:K?this.saveRateLimit.bind(this,Q.rawUrl):void 0,payloadIsError:W.payloadIsError,compression:($=(Z=W.compression)!==null&&Z!==void 0?Z:this.clientSettings.compression)!==null&&$!==void 0?$:!0},G=new Q4(z);if(!J)return G;return G.connect()}initializeToken(W){if(typeof W==="string")this.bearerToken=W;else if(typeof W==="object"&&"appKey"in W){if(this.consumerToken=W.appKey,this.consumerSecret=W.appSecret,W.accessToken&&W.accessSecret)this.accessToken=W.accessToken,this.accessSecret=W.accessSecret;this._oauth=this.buildOAuth()}else if(typeof W==="object"&&"username"in W){let Z=encodeURIComponent(W.username)+":"+encodeURIComponent(W.password);this.basicToken=Buffer.from(Z).toString("base64")}else if(typeof W==="object"&&"clientId"in W)this.clientId=W.clientId,this.clientSecret=W.clientSecret}getActiveTokens(){if(this.bearerToken)return{type:"oauth2",bearerToken:this.bearerToken};else if(this.basicToken)return{type:"basic",token:this.basicToken};else if(this.consumerSecret&&this._oauth)return{type:"oauth-1.0a",appKey:this.consumerToken,appSecret:this.consumerSecret,accessToken:this.accessToken,accessSecret:this.accessSecret};else if(this.clientId)return{type:"oauth2-user",clientId:this.clientId};return{type:"none"}}buildOAuth(){if(!this.consumerSecret||!this.consumerToken)throw Error("Invalid consumer tokens");return new g1({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(!this.accessSecret||!this.accessToken)return;return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var W;return(W=this.clientSettings.plugins)!==null&&W!==void 0?W:[]}hasPlugins(){var W;return!!((W=this.clientSettings.plugins)===null||W===void 0?void 0:W.length)}async applyPluginMethod(W,Z){var $;let Q;for(let Y of this.getPlugins()){let K=await(($=Y[W])===null||$===void 0?void 0:$.call(Y,Z));if(K&&K instanceof A1)Q=K}return Q}writeAuthHeaders({headers:W,bodyInSignature:Z,url:$,method:Q,query:Y,body:K}){if(W={...W},this.bearerToken)W.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)W.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)W.Authorization="Basic "+B1.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let J=Z?v.mergeQueryAndBodyForOAuth(Y,K):Y,z=this._oauth.authorize({url:$.toString(),method:Q,data:J},this.getOAuthAccessTokens());W={...W,...this._oauth.toHeader(z)}}return W}getUrlObjectFromUrlString(W){if(!W.startsWith("http"))W="https://"+W;return new URL(W)}getHttpRequestArgs({url:W,method:Z,query:$={},body:Q={},headers:Y,forceBodyMode:K,enableAuth:J,params:z}){let G=void 0;if(Z=Z.toUpperCase(),Y=Y!==null&&Y!==void 0?Y:{},!Y["x-user-agent"])Y["x-user-agent"]="Node.twitter-api-v2";let X=this.getUrlObjectFromUrlString(W),B=X.origin+X.pathname;if(z)v.applyRequestParametersToUrl(X,z);let j=v.formatQueryToString($);if(v.moveUrlQueryParamsIntoObject(X,j),!(Q instanceof Buffer))s6(Q);let D=K!==null&&K!==void 0?K:v.autoDetectBodyType(X);if(J!==!1){let x=H1.BODY_METHODS.has(Z)&&D==="url";Y=this.writeAuthHeaders({headers:Y,bodyInSignature:x,method:Z,query:j,url:X,body:Q})}if(H1.BODY_METHODS.has(Z))G=v.constructBodyParams(Q,Y,D)||void 0;return v.addQueryParamsToUrl(X,j),{rawUrl:B,url:X,method:Z,headers:Y,body:G}}async applyPreRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let Q of this.getPlugins()){let Y=await((Z=Q.onBeforeRequestConfig)===null||Z===void 0?void 0:Z.call(Q,{client:this,url:$,params:W}));if(Y)return Y}}applyPreStreamRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let Q of this.getPlugins())(Z=Q.onBeforeStreamRequestConfig)===null||Z===void 0||Z.call(Q,{client:this,url:$,params:W})}async applyPreRequestHooks(W,Z,$){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$})}async applyPostRequestHooks(W,Z,$,Q){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,response:Q})}applyResponseErrorHooks(W,Z,$,Q){return Q.catch(ZW.bind(this,W,Z,$))}}H1.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class W1{constructor(W,Z={}){if(this._currentUser=null,this._currentUserV2=null,W instanceof W1)this._requestMaker=W._requestMaker;else this._requestMaker=new H1(Z),this._requestMaker.initializeToken(W)}setPrefix(W){this._prefix=W}cloneWithPrefix(W){let Z=this.constructor(this);return Z.setPrefix(W),Z}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(W){return this.getPlugins().find((Z)=>Z instanceof W)}hasHitRateLimit(W){var Z;if(this.isRateLimitStatusObsolete(W))return!1;return((Z=this.getLastRateLimitStatus(W))===null||Z===void 0?void 0:Z.remaining)===0}isRateLimitStatusObsolete(W){let Z=this.getLastRateLimitStatus(W);if(Z===void 0)return!0;return Z.reset*1000<Date.now()}getLastRateLimitStatus(W){let Z=W.match(/^https?:\/\//)?W:this._prefix+W;return this._requestMaker.getRateLimits()[Z]}getCurrentUserObject(W=!1){if(!W&&this._currentUser){if(this._currentUser.value)return Promise.resolve(this._currentUser.value);return this._currentUser.promise}return this._currentUser=e4(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:r})),this._currentUser.promise}getCurrentUserV2Object(W=!1){if(!W&&this._currentUserV2){if(this._currentUserV2.value)return Promise.resolve(this._currentUserV2.value);return this._currentUserV2.promise}return this._currentUserV2=e4(()=>this.get("users/me",void 0,{prefix:t})),this._currentUserV2.promise}async get(W,Z={},{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"GET",query:Z,...Y});return $?K:K.data}async delete(W,Z={},{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"DELETE",query:Z,...Y});return $?K:K.data}async post(W,Z,{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"POST",body:Z,...Y});return $?K:K.data}async put(W,Z,{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"PUT",body:Z,...Y});return $?K:K.data}async patch(W,Z,{fullResponse:$,prefix:Q=this._prefix,...Y}={}){if(Q)W=Q+W;let K=await this._requestMaker.send({url:W,method:"PATCH",body:Z,...Y});return $?K:K.data}getStream(W,Z,{prefix:$=this._prefix,...Q}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"GET",query:Z,...Q})}postStream(W,Z,{prefix:$=this._prefix,...Q}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"POST",body:Z,...Q})}}class I extends W1{constructor(W){if(!(W instanceof W1))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(W)}}class N1 extends D1{constructor(){super(...arguments);this.hasFinishedFetch=!1}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.push(...$),this.hasFinishedFetch=$.length===0}getNextQueryParams(W){let Z=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(W),max_id:(Z-BigInt(1)).toString()}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class $0 extends N1{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class Q0 extends N1{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class K4 extends N1{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class Y0 extends N1{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class J4 extends N1{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class K0 extends O{constructor(){super(...arguments);this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class J0 extends O{constructor(){super(...arguments);this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class z0 extends O{constructor(){super(...arguments);this._endpoint="followers/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class G0 extends O{constructor(){super(...arguments);this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class X0 extends O{constructor(){super(...arguments);this._endpoint="friends/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class B0 extends O{constructor(){super(...arguments);this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class j0 extends D1{constructor(){super(...arguments);this._endpoint="users/search.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.push(...$)}getNextQueryParams(W){var Z;let $=Number((Z=this._queryParams.page)!==null&&Z!==void 0?Z:"1");return{...this._queryParams,page:$+1,...W?{count:W}:{}}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.users}get users(){return this._realData}}class z4 extends O{constructor(){super(...arguments);this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class F0 extends z4{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class G4 extends O{refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.lists.push(...$.lists),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class M0 extends G4{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class L0 extends G4{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class D0 extends G4{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class H0 extends O{refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.users.push(...$.users),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class N0 extends H0{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class U0 extends H0{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class U1 extends I{constructor(){super(...arguments);this._prefix=r}singleTweet(W,Z={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:W,...Z})}tweets(W,Z={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:W,...Z})}oembedTweet(W,Z={}){return this.get("oembed",{url:`https://x.com/i/statuses/${W}`,...Z},{prefix:"https://publish.x.com/"})}async homeTimeline(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("statuses/home_timeline.json",Z,{fullResponse:!0});return new $0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async mentionTimeline(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("statuses/mentions_timeline.json",Z,{fullResponse:!0});return new Q0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},Q=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new K4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async userTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},Q=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new K4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async favoriteTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},Q=await this.get("favorites/list.json",$,{fullResponse:!0});return new J4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async favoriteTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},Q=await this.get("favorites/list.json",$,{fullResponse:!0});return new J4({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}user(W){return this.get("users/show.json",{tweet_mode:"extended",...W})}users(W){return this.get("users/lookup.json",{tweet_mode:"extended",...W})}verifyCredentials(W={}){return this.get("account/verify_credentials.json",W)}async listMutedUsers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("mutes/users/list.json",Z,{fullResponse:!0});return new K0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listMutedUserIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("mutes/users/ids.json",Z,{fullResponse:!0});return new J0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFriendList(W={}){let Z={...W},$=await this.get("friends/list.json",Z,{fullResponse:!0});return new X0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowerList(W={}){let Z={...W},$=await this.get("followers/list.json",Z,{fullResponse:!0});return new z0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowerIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("followers/ids.json",Z,{fullResponse:!0});return new G0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userFollowingIds(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friends/ids.json",Z,{fullResponse:!0});return new B0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async searchUsers(W,Z={}){let $={q:W,tweet_mode:"extended",page:1,...Z},Q=await this.get("users/search.json",$,{fullResponse:!0});return new j0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}friendship(W){return this.get("friendships/show.json",W)}friendships(W){return this.get("friendships/lookup.json",W)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friendships/incoming.json",Z,{fullResponse:!0});return new z4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async friendshipsOutgoing(W={}){let Z={stringify_ids:!0,...W},$=await this.get("friendships/outgoing.json",Z,{fullResponse:!0});return new F0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(W){return this.get("users/profile_banner.json",W)}list(W){return this.get("lists/show.json",{tweet_mode:"extended",...W})}lists(W={}){return this.get("lists/list.json",{tweet_mode:"extended",...W})}async listMembers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/members.json",Z,{fullResponse:!0});return new N0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}listGetMember(W){return this.get("lists/members/show.json",{tweet_mode:"extended",...W})}async listMemberships(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/memberships.json",Z,{fullResponse:!0});return new M0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listOwnerships(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/ownerships.json",Z,{fullResponse:!0});return new L0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listStatuses(W){let Z={tweet_mode:"extended",...W},$=await this.get("lists/statuses.json",Z,{fullResponse:!0});return new Y0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async listSubscribers(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/subscribers.json",Z,{fullResponse:!0});return new U0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}listGetSubscriber(W){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...W})}async listSubscriptions(W={}){let Z={tweet_mode:"extended",...W},$=await this.get("lists/subscriptions.json",Z,{fullResponse:!0});return new D0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}mediaInfo(W){return this.get("media/upload.json",{command:"STATUS",media_id:W},{prefix:s})}filterStream({autoConnect:W,...Z}={}){let $={};for(let[Y,K]of Object.entries(Z))if(Y==="follow"||Y==="track")$[Y]=K.toString();else if(Y==="locations"){let J=K;$.locations=Z4(J).map((z)=>`${z.lng},${z.lat}`).join(",")}else $[Y]=K;return this.stream.postStream("statuses/filter.json",$,{autoConnect:W})}sampleStream({autoConnect:W,...Z}={}){return this.stream.getStream("statuses/sample.json",Z,{autoConnect:W})}get stream(){let W=new X4(this);return W.setPrefix(l6),W}trendsByPlace(W,Z={}){return this.get("trends/place.json",{id:W,...Z})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(W,Z){return this.get("trends/closest.json",{lat:W,long:Z})}geoPlace(W){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:W}})}geoSearch(W){return this.get("geo/search.json",W)}geoReverseGeoCode(W){return this.get("geo/reverse_geocode.json",W)}rateLimitStatuses(...W){return this.get("application/rate_limit_status.json",{resources:W})}supportedLanguages(){return this.get("help/languages.json")}}import*as Z1 from"fs";async function x0(W){let Z=await S0(W);if(typeof Z==="number")return new Promise(($,Q)=>{Z1.readFile(Z,(Y,K)=>{if(Y)return Q(Y);$(K)})});else if(Z instanceof Buffer)return Z;else return Z.readFile()}function S0(W){if(typeof W==="string")return Z1.promises.open(W,"r");else if(typeof W==="number")return W;else if(typeof W==="object"&&!(W instanceof Buffer))return W;else if(!(W instanceof Buffer))throw Error("Given file is not valid, please check its type.");else return W}async function JW(W){if(typeof W==="number")return(await new Promise(($,Q)=>{Z1.fstat(W,(Y,K)=>{if(Y)Q(Y);$(K)})})).size;else if(W instanceof Buffer)return W.length;else return(await W.stat()).size}function zW(W,Z,$){if(typeof $==="string")return $;else if(typeof W==="string"&&!Z)return A5(W);else if(typeof Z==="string")return h5(Z);throw Error("You must specify type if file is a file handle or Buffer.")}function A5(W){if(W.endsWith(".jpeg")||W.endsWith(".jpg"))return N.Jpeg;if(W.endsWith(".png"))return N.Png;if(W.endsWith(".webp"))return N.Webp;if(W.endsWith(".gif"))return N.Gif;if(W.endsWith(".mpeg4")||W.endsWith(".mp4"))return N.Mp4;if(W.endsWith(".mov")||W.endsWith(".mov"))return N.Mov;if(W.endsWith(".srt"))return N.Srt;return W0({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"}),N.Jpeg}function h5(W){if(W0({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"}),W==="gif")return N.Gif;if(W==="jpg")return N.Jpeg;if(W==="png")return N.Png;if(W==="webp")return N.Webp;if(W==="srt")return N.Srt;if(W==="mp4"||W==="longmp4")return N.Mp4;if(W==="mov")return N.Mov;return W}function GW(W,Z){if(W===N.Mp4||W===N.Mov)return Z==="tweet"?"TweetVideo":"DmVideo";if(W===N.Gif)return Z==="tweet"?"TweetGif":"DmGif";if(W===N.Srt)return"Subtitles";else return Z==="tweet"?"TweetImage":"DmImage"}function R0(W){return new Promise((Z)=>setTimeout(Z,W*1000))}async function O0(W,Z,$=0,Q){if(W instanceof Buffer){let K=W.slice($,$+Z);return[K,K.length]}if(!Q)throw Error("Well, we will need a buffer to store file content.");let Y;if(typeof W==="number")Y=await new Promise((K,J)=>{Z1.read(W,Q,0,Z,$,(z,G)=>{if(z)J(z);K(G)})});else Y=(await W.read(Q,0,Z,$)).bytesRead;return[Q,Y]}var _0="media/upload.json";class x1 extends U1{constructor(){super(...arguments);this._prefix=r}get readOnly(){return this}tweet(W,Z={}){let $={status:W,tweet_mode:"extended",...Z};return this.post("statuses/update.json",$)}async quote(W,Z,$={}){let Q="https://x.com/i/statuses/"+Z;return this.tweet(W,{...$,attachment_url:Q})}async tweetThread(W){let Z=[];for(let $ of W){let Q=Z.length?Z[Z.length-1]:null,Y={...typeof $==="string"?{status:$}:$},K=Q?Q.id_str:Y.in_reply_to_status_id,J=Y.status;if(K)Z.push(await this.reply(J,K,Y));else Z.push(await this.tweet(J,Y))}return Z}reply(W,Z,$={}){return this.tweet(W,{auto_populate_reply_metadata:!0,in_reply_to_status_id:Z,...$})}deleteTweet(W){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:W}})}reportUserAsSpam(W){return this.post("users/report_spam.json",{tweet_mode:"extended",...W})}updateFriendship(W){return this.post("friendships/update.json",W)}createFriendship(W){return this.post("friendships/create.json",W)}destroyFriendship(W){return this.post("friendships/destroy.json",W)}updateAccountSettings(W){return this.post("account/settings.json",W)}updateAccountProfile(W){return this.post("account/update_profile.json",W)}async updateAccountProfileBanner(W,Z={}){let $={banner:await x0(W),...Z};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,Z={}){let $={tweet_mode:"extended",image:await x0(W),...Z};return this.post("account/update_profile_image.json",$,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(W){return this.post("lists/create.json",{tweet_mode:"extended",...W})}updateList(W){return this.post("lists/update.json",{tweet_mode:"extended",...W})}removeList(W){return this.post("lists/destroy.json",{tweet_mode:"extended",...W})}addListMembers(W){let $=W.user_id&&h1(W.user_id)||W.screen_name&&h1(W.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,W)}removeListMembers(W){let $=W.user_id&&h1(W.user_id)||W.screen_name&&h1(W.screen_name)?"lists/members/destroy_all.json":"lists/members/destroy.json";return this.post($,W)}subscribeToList(W){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...W})}unsubscribeOfList(W){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...W})}createMediaMetadata(W,Z){return this.post("media/metadata/create.json",{media_id:W,...Z},{prefix:s,forceBodyMode:"json"})}createMediaSubtitles(W,Z){return this.post("media/subtitles/create.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z}},{prefix:s,forceBodyMode:"json"})}deleteMediaSubtitles(W,...Z){return this.post("media/subtitles/delete.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z.map(($)=>({language_code:$}))}},{prefix:s,forceBodyMode:"json"})}async uploadMedia(W,Z={},$=!1){var Q;let Y=(Q=Z.chunkLength)!==null&&Q!==void 0?Q:1048576,{fileHandle:K,mediaCategory:J,fileSize:z,mimeType:G}=await this.getUploadMediaRequirements(W,Z);try{let X=await this.post(_0,{command:"INIT",total_bytes:z,media_type:G,media_category:J,additional_owners:Z.additionalOwners,shared:Z.shared?!0:void 0},{prefix:s});await this.mediaChunkedUpload(K,Y,X.media_id_string,Z.maxConcurrentUploads);let B=await this.post(_0,{command:"FINALIZE",media_id:X.media_id_string},{prefix:s});if(B.processing_info&&B.processing_info.state!=="succeeded")await this.awaitForMediaProcessingCompletion(B);if($)return B;else return B.media_id_string}finally{if(typeof W==="number")V0.close(W,()=>{});else if(typeof K==="object"&&!(K instanceof Buffer))K.close()}}async awaitForMediaProcessingCompletion(W){var Z;while(!0){W=await this.mediaInfo(W.media_id_string);let{processing_info:$}=W;if(!$||$.state==="succeeded")return;if((Z=$.error)===null||Z===void 0?void 0:Z.code){let{name:Q,message:Y}=$.error;throw Error(`Failed to process media: ${Q} - ${Y}.`)}if($.state==="failed")throw Error("Failed to process the media.");if($.check_after_secs)await R0($.check_after_secs);else await R0(5)}}async getUploadMediaRequirements(W,{mimeType:Z,type:$,target:Q,longVideo:Y}={}){let K;try{K=await S0(W);let J=zW(W,$,Z),z;if(J===N.Mp4&&(!Z&&!$&&Q!=="dm"||Y))z="amplify_video";else z=GW(J,Q!==null&&Q!==void 0?Q:"tweet");return{fileHandle:K,mediaCategory:z,fileSize:await JW(K),mimeType:J}}catch(J){if(typeof W==="number")V0.close(W,()=>{});else if(typeof K==="object"&&!(K instanceof Buffer))K.close();throw J}}async mediaChunkedUpload(W,Z,$,Q=3){let Y=0;if(Q<1)throw RangeError("Bad maxConcurrentUploads parameter.");let K=W instanceof Buffer?void 0:Buffer.alloc(Z),J,z,G=0;[J,z]=await O0(W,Z,G,K),G+=z;let X=new Set;while(z){let B=J.slice(0,z);if(B.length){let j=this.post(_0,{command:"APPEND",media_id:$,segment_index:Y,media:B},{prefix:s});X.add(j),j.then(()=>{X.delete(j)}),Y++}if(X.size>=Q)await Promise.race(X);[J,z]=await O0(W,Z,G,K),G+=z}await Promise.all([...X])}}class XW extends x1{constructor(){super(...arguments);this._prefix=r}get readWrite(){return this}sendDm({recipient_id:W,custom_profile_id:Z,...$}){let Q={event:{type:e.Create,[e.Create]:{target:{recipient_id:W},message_data:$}}};if(Z)Q.event[e.Create].custom_profile_id=Z;return this.post("direct_messages/events/new.json",Q,{forceBodyMode:"json"})}getDmEvent(W){return this.get("direct_messages/events/show.json",{id:W})}deleteDm(W){return this.delete("direct_messages/events/destroy.json",{id:W})}async listDmEvents(W={}){let Z={...W},$=await this.get("direct_messages/events/list.json",Z,{fullResponse:!0});return new t4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDm(W,Z){let $={[e.WelcomeCreate]:{name:W,message_data:Z}};return this.post("direct_messages/welcome_messages/new.json",$,{forceBodyMode:"json"})}getWelcomeDm(W){return this.get("direct_messages/welcome_messages/show.json",{id:W})}deleteWelcomeDm(W){return this.delete("direct_messages/welcome_messages/destroy.json",{id:W})}updateWelcomeDm(W,Z){let $={message_data:Z};return this.put("direct_messages/welcome_messages/update.json",$,{forceBodyMode:"json",query:{id:W}})}async listWelcomeDms(W={}){let Z={...W},$=await this.get("direct_messages/welcome_messages/list.json",Z,{fullResponse:!0});return new r4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDmRule(W){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:W}},{forceBodyMode:"json"})}getWelcomeDmRule(W){return this.get("direct_messages/welcome_messages/rules/show.json",{id:W})}deleteWelcomeDmRule(W){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:W})}async listWelcomeDmRules(W={}){let Z={...W};return this.get("direct_messages/welcome_messages/rules/list.json",Z)}async setWelcomeDm(W,Z=!0){var $;let Q=await this.listWelcomeDmRules();if(($=Q.welcome_message_rules)===null||$===void 0?void 0:$.length){for(let Y of Q.welcome_message_rules)if(await this.deleteWelcomeDmRule(Y.id),Z)await this.deleteWelcomeDm(Y.welcome_message_id)}return this.newWelcomeDmRule(W)}markDmAsRead(W,Z){return this.post("direct_messages/mark_read.json",{last_read_event_id:W,recipient_id:Z},{forceBodyMode:"url"})}indicateDmTyping(W){return this.post("direct_messages/indicate_typing.json",{recipient_id:W},{forceBodyMode:"url"})}async downloadDmImage(W){if(typeof W!=="string"){let $=W[e.Create].message_data.attachment;if(!$)throw Error("The given direct message doesn't contain any attachment");W=$.media.media_url_https}let Z=await this.get(W,void 0,{forceParseMode:"buffer",prefix:""});if(!Z.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return Z}}var X4=XW;class H{constructor(W){this.result=W}get tweets(){return H.tweets(this.result)}static tweets(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.tweets)!==null&&$!==void 0?$:[]}tweetById(W){return H.tweetById(this.result,W)}static tweetById(W,Z){return this.tweets(W).find(($)=>$.id===Z)}retweet(W){return H.retweet(this.result,W)}static retweet(W,Z){var $;let Q=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Y)=>Y.type==="retweeted").map((Y)=>Y.id);return this.tweets(W).find((Y)=>Q.includes(Y.id))}quote(W){return H.quote(this.result,W)}static quote(W,Z){var $;let Q=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Y)=>Y.type==="quoted").map((Y)=>Y.id);return this.tweets(W).find((Y)=>Q.includes(Y.id))}repliedTo(W){return H.repliedTo(this.result,W)}static repliedTo(W,Z){var $;let Q=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Y)=>Y.type==="replied_to").map((Y)=>Y.id);return this.tweets(W).find((Y)=>Q.includes(Y.id))}author(W){return H.author(this.result,W)}static author(W,Z){let $=Z.author_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}repliedToAuthor(W){return H.repliedToAuthor(this.result,W)}static repliedToAuthor(W,Z){let $=Z.in_reply_to_user_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}get users(){return H.users(this.result)}static users(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.users)!==null&&$!==void 0?$:[]}userById(W){return H.userById(this.result,W)}static userById(W,Z){return this.users(W).find(($)=>$.id===Z)}pinnedTweet(W){return H.pinnedTweet(this.result,W)}static pinnedTweet(W,Z){return Z.pinned_tweet_id?this.tweets(W).find(($)=>$.id===Z.pinned_tweet_id):void 0}get media(){return H.media(this.result)}static media(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.media)!==null&&$!==void 0?$:[]}medias(W){return H.medias(this.result,W)}static medias(W,Z){var $,Q;let Y=(Q=($=Z.attachments)===null||$===void 0?void 0:$.media_keys)!==null&&Q!==void 0?Q:[];return this.media(W).filter((K)=>Y.includes(K.media_key))}get polls(){return H.polls(this.result)}static polls(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.polls)!==null&&$!==void 0?$:[]}poll(W){return H.poll(this.result,W)}static poll(W,Z){var $,Q;let Y=(Q=($=Z.attachments)===null||$===void 0?void 0:$.poll_ids)!==null&&Q!==void 0?Q:[];if(Y.length){let K=Y[0];return this.polls(W).find((J)=>J.id===K)}return}get places(){return H.places(this.result)}static places(W){var Z,$;return($=(Z=W.includes)===null||Z===void 0?void 0:Z.places)!==null&&$!==void 0?$:[]}place(W){return H.place(this.result,W)}static place(W,Z){var $;let Q=($=Z.geo)===null||$===void 0?void 0:$.place_id;return Q?this.places(W).find((Y)=>Y.id===Q):void 0}listOwner(W){return H.listOwner(this.result,W)}static listOwner(W,Z){let $=Z.owner_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}spaceCreator(W){return H.spaceCreator(this.result,W)}static spaceCreator(W,Z){let $=Z.creator_id;return $?this.users(W).find((Q)=>Q.id===$):void 0}spaceHosts(W){return H.spaceHosts(this.result,W)}static spaceHosts(W,Z){var $;let Q=($=Z.host_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Y)=>Q.includes(Y.id))}spaceSpeakers(W){return H.spaceSpeakers(this.result,W)}static spaceSpeakers(W,Z){var $;let Q=($=Z.speaker_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Y)=>Q.includes(Y.id))}spaceInvitedUsers(W){return H.spaceInvitedUsers(this.result,W)}static spaceInvitedUsers(W,Z){var $;let Q=($=Z.invited_user_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Y)=>Q.includes(Y.id))}}class B4 extends a4{updateIncludes(W){if(W.errors){if(!this._realData.errors)this._realData.errors=[];this._realData.errors=[...this._realData.errors,...W.errors]}if(!W.includes)return;if(!this._realData.includes)this._realData.includes={};let Z=this._realData.includes;for(let[$,Q]of Object.entries(W.includes)){if(!Z[$])Z[$]=[];Z[$]=[...Z[$],...Q]}}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 W;if(!((W=this._realData)===null||W===void 0?void 0:W.includes))return new H(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new H(this._realData)}get errors(){var W;return(W=this._realData.errors)!==null&&W!==void 0?W:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class d extends B4{refreshInstanceFromResult(W,Z){var $;let Q=W.data,Y=($=Q.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.result_count+=Q.meta.result_count,this._realData.meta.next_token=Q.meta.next_token,this._realData.data.push(...Y);else this._realData.meta.result_count+=Q.meta.result_count,this._realData.meta.previous_token=Q.meta.previous_token,this._realData.data.unshift(...Y);this.updateIncludes(Q)}getNextQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(W){var Z,$;return($=(Z=W.data.data)===null||Z===void 0?void 0:Z.length)!==null&&$!==void 0?$:0}isFetchLastOver(W){var Z;return!((Z=W.data.data)===null||Z===void 0?void 0:Z.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){var Z;return!!((Z=W.meta)===null||Z===void 0?void 0:Z.next_token)}}class k0 extends B4{refreshInstanceFromResult(W,Z){var $;let Q=W.data,Y=($=Q.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.oldest_id=Q.meta.oldest_id,this._realData.meta.result_count+=Q.meta.result_count,this._realData.meta.next_token=Q.meta.next_token,this._realData.data.push(...Y);else this._realData.meta.newest_id=Q.meta.newest_id,this._realData.meta.result_count+=Q.meta.result_count,this._realData.data.unshift(...Y);this.updateIncludes(Q)}getNextQueryParams(W){this.assertUsable();let Z={...this.injectQueryParams(W)};if(this._realData.meta.next_token)Z.next_token=this._realData.meta.next_token;else{if(Z.start_time)Z.since_id=this.dateStringToSnowflakeId(Z.start_time),delete Z.start_time;if(Z.end_time)delete Z.end_time;Z.until_id=this._realData.meta.oldest_id}return Z}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(W){var Z,$;return($=(Z=W.data.data)===null||Z===void 0?void 0:Z.length)!==null&&$!==void 0?$:0}isFetchLastOver(W){var Z;return!((Z=W.data.data)===null||Z===void 0?void 0:Z.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!!W.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(W){let Z=BigInt("1288834974657"),$=new Date(W);if(isNaN($.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($.valueOf())-Z<<BigInt("22")).toString()}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class S1 extends d{refreshInstanceFromResult(W,Z){super.refreshInstanceFromResult(W,Z);let $=W.data;if(Z)this._realData.meta.oldest_id=$.meta.oldest_id;else this._realData.meta.newest_id=$.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class C0 extends k0{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class T0 extends k0{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class P0 extends S1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class b0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class q0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class w0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class v0 extends S1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class I0 extends d{get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class f0 extends I0{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class y0 extends I0{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class o extends d{getItemArray(){return this.users}get users(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class A0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class h0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class E0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class g0 extends o{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class m0 extends o{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class c0 extends o{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class u0 extends o{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class p0 extends o{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class j4 extends d{getItemArray(){return this.lists}get lists(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class d0 extends j4{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class l0 extends j4{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class n0 extends j4{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class R1 extends I{constructor(){super(...arguments);this._prefix=F1}}class F4 extends d{getItemArray(){return this.events}get events(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class i0 extends F4{constructor(){super(...arguments);this._endpoint="dm_events"}}class s0 extends F4{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class o0 extends F4{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class O1 extends I{constructor(){super(...arguments);this._prefix=t}get labs(){if(this._labs)return this._labs;return this._labs=new R1(this)}async search(W,Z={}){let $=typeof W==="string"?{...Z,query:W}:{...W},Q=await this.get("tweets/search/recent",$,{fullResponse:!0});return new C0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}async searchAll(W,Z={}){let $={...Z,query:W},Q=await this.get("tweets/search/all",$,{fullResponse:!0});return new T0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$})}singleTweet(W,Z={}){return this.get("tweets/:id",Z,{params:{id:W}})}tweets(W,Z={}){return this.get("tweets",{ids:W,...Z})}tweetCountRecent(W,Z={}){return this.get("tweets/counts/recent",{query:W,...Z})}tweetCountAll(W,Z={}){return this.get("tweets/counts/all",{query:W,...Z})}async tweetRetweetedBy(W,Z={}){let{asPaginator:$,...Q}=Z,Y=await this.get("tweets/:id/retweeted_by",Q,{fullResponse:!0,params:{id:W}});if(!$)return Y.data;return new p0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:Q,sharedParams:{id:W}})}async tweetLikedBy(W,Z={}){let{asPaginator:$,...Q}=Z,Y=await this.get("tweets/:id/liking_users",Q,{fullResponse:!0,params:{id:W}});if(!$)return Y.data;return new u0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:Q,sharedParams:{id:W}})}async homeTimeline(W={}){let Z=await this.getCurrentUserV2Object(),$=await this.get("users/:id/timelines/reverse_chronological",W,{fullResponse:!0,params:{id:Z.data.id}});return new b0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:Z.data.id}})}async userTimeline(W,Z={}){let $=await this.get("users/:id/tweets",Z,{fullResponse:!0,params:{id:W}});return new q0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async userMentionTimeline(W,Z={}){let $=await this.get("users/:id/mentions",Z,{fullResponse:!0,params:{id:W}});return new w0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async quotes(W,Z={}){let $=await this.get("tweets/:id/quote_tweets",Z,{fullResponse:!0,params:{id:W}});return new P0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z,sharedParams:{id:W}})}async bookmarks(W={}){let Z=await this.getCurrentUserV2Object(),$=await this.get("users/:id/bookmarks",W,{fullResponse:!0,params:{id:Z.data.id}});return new v0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:W,sharedParams:{id:Z.data.id}})}me(W={}){return this.get("users/me",W)}user(W,Z={}){return this.get("users/:id",Z,{params:{id:W}})}users(W,Z={}){let $=Array.isArray(W)?W.join(","):W;return this.get("users",{...Z,ids:$})}userByUsername(W,Z={}){return this.get("users/by/username/:username",Z,{params:{username:W}})}usersByUsernames(W,Z={}){return W=Array.isArray(W)?W.join(","):W,this.get("users/by",{...Z,usernames:W})}async followers(W,Z={}){let{asPaginator:$,...Q}=Z,Y={id:W};if(!$)return this.get("users/:id/followers",Q,{params:Y});let K=await this.get("users/:id/followers",Q,{fullResponse:!0,params:Y});return new E0({realData:K.data,rateLimit:K.rateLimit,instance:this,queryParams:Q,sharedParams:Y})}async following(W,Z={}){let{asPaginator:$,...Q}=Z,Y={id:W};if(!$)return this.get("users/:id/following",Q,{params:Y});let K=await this.get("users/:id/following",Q,{fullResponse:!0,params:Y});return new g0({realData:K.data,rateLimit:K.rateLimit,instance:this,queryParams:Q,sharedParams:Y})}async userLikedTweets(W,Z={}){let $={id:W},Q=await this.get("users/:id/liked_tweets",Z,{fullResponse:!0,params:$});return new f0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userBlockingUsers(W,Z={}){let $={id:W},Q=await this.get("users/:id/blocking",Z,{fullResponse:!0,params:$});return new A0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userMutingUsers(W,Z={}){let $={id:W},Q=await this.get("users/:id/muting",Z,{fullResponse:!0,params:$});return new h0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}list(W,Z={}){return this.get("lists/:id",Z,{params:{id:W}})}async listsOwned(W,Z={}){let $={id:W},Q=await this.get("users/:id/owned_lists",Z,{fullResponse:!0,params:$});return new d0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMemberships(W,Z={}){let $={id:W},Q=await this.get("users/:id/list_memberships",Z,{fullResponse:!0,params:$});return new l0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowed(W,Z={}){let $={id:W},Q=await this.get("users/:id/followed_lists",Z,{fullResponse:!0,params:$});return new n0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listTweets(W,Z={}){let $={id:W},Q=await this.get("lists/:id/tweets",Z,{fullResponse:!0,params:$});return new y0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMembers(W,Z={}){let $={id:W},Q=await this.get("lists/:id/members",Z,{fullResponse:!0,params:$});return new m0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowers(W,Z={}){let $={id:W},Q=await this.get("lists/:id/followers",Z,{fullResponse:!0,params:$});return new c0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEvents(W={}){let Z=await this.get("dm_events",W,{fullResponse:!0});return new i0({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:{...W}})}async listDmEventsWithParticipant(W,Z={}){let $={participant_id:W},Q=await this.get("dm_conversations/with/:participant_id/dm_events",Z,{fullResponse:!0,params:$});return new s0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEventsOfConversation(W,Z={}){let $={dm_conversation_id:W},Q=await this.get("dm_conversations/:dm_conversation_id/dm_events",Z,{fullResponse:!0,params:$});return new o0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}space(W,Z={}){return this.get("spaces/:id",Z,{params:{id:W}})}spaces(W,Z={}){return this.get("spaces",{ids:W,...Z})}spacesByCreators(W,Z={}){return this.get("spaces/by/creator_ids",{user_ids:W,...Z})}searchSpaces(W){return this.get("spaces/search",W)}spaceBuyers(W,Z={}){return this.get("spaces/:id/buyers",Z,{params:{id:W}})}spaceTweets(W,Z={}){return this.get("spaces/:id/tweets",Z,{params:{id:W}})}searchStream({autoConnect:W,...Z}={}){return this.getStream("tweets/search/stream",Z,{payloadIsError:$4,autoConnect:W})}streamRules(W={}){return this.get("tweets/search/stream/rules",W)}updateStreamRules(W,Z={}){return this.post("tweets/search/stream/rules",W,{query:Z})}sampleStream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample/stream",Z,{payloadIsError:$4,autoConnect:W})}sample10Stream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample10/stream",Z,{payloadIsError:$4,autoConnect:W})}complianceJobs(W){return this.get("compliance/jobs",W)}complianceJob(W){return this.get("compliance/jobs/:id",void 0,{params:{id:W}})}async sendComplianceJob(W){let Z=await this.post("compliance/jobs",{type:W.type,name:W.name}),$=W.ids instanceof Buffer?W.ids:Buffer.from(W.ids.join(`
69
69
  `));return await this.put(Z.data.upload_url,$,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),Z}async complianceJobResult(W){let Z=W;while(Z.status!=="complete"){if(Z.status==="expired"||Z.status==="failed")throw Error("Job failed to be completed.");await new Promise((Q)=>setTimeout(Q,3500)),Z=(await this.complianceJob(W.id)).data}return(await this.get(W.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split(`
70
- `).filter((Q)=>Q).map((Q)=>JSON.parse(Q))}async usage(W={}){return this.get("usage/tweets",W)}community(W,Z={}){return this.get("communities/:id",Z,{params:{id:W}})}searchCommunities(W,Z={}){return this.get("communities/search",{query:W,...Z})}}class _1 extends R1{constructor(){super(...arguments);this._prefix=M1}get readOnly(){return this}}class V1 extends O1{constructor(){super(...arguments);this._prefix=t}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new _1(this)}hideReply(W,Z){return this.put("tweets/:id/hidden",{hidden:Z},{params:{id:W}})}like(W,Z){return this.post("users/:id/likes",{tweet_id:Z},{params:{id:W}})}unlike(W,Z){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:W,tweet_id:Z}})}retweet(W,Z){return this.post("users/:id/retweets",{tweet_id:Z},{params:{id:W}})}unretweet(W,Z){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:W,tweet_id:Z}})}tweet(W,Z={}){if(typeof W==="object")Z=W;else Z={text:W,...Z};return this.post("tweets",Z)}async uploadMedia(W,Z,$=1048576){let Q=Z.media_category;if(!Z.media_category){if(Z.media_type.includes("gif"))Q="tweet_gif";else if(Z.media_type.includes("image"))Q="tweet_image";else if(Z.media_type.includes("video"))Q="tweet_video"}let Y={additional_owners:Z.additional_owners,media_type:Z.media_type,total_bytes:W.length,media_category:Q},J=(await this.post("media/upload/initialize",Y)).data.id,z=Math.ceil(W.length/$),G=new Uint8Array(W);for(let B=0;B<z;B++){let j=B*$,D=Math.min(j+$,W.length),x=G.slice(j,D),V=Buffer.from(x),Q1={segment_index:B,media:V};await this.post(`media/upload/${J}/append`,Q1,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${J}/finalize`)).data.processing_info)await this.waitForMediaProcessing(J);return J}async waitForMediaProcessing(W){var Z;let Q=(await this.get("media/upload",{command:"STATUS",media_id:W})).data.processing_info;if(!Q)return;switch(Q.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(Z=Q.error)===null||Z===void 0?void 0:Z.message}`);case"pending":case"in_progress":{let Y=Q===null||Q===void 0?void 0:Q.check_after_secs;if(Y&&Y>0)await new Promise((K)=>setTimeout(K,Y*1000)),await this.waitForMediaProcessing(W)}}}createMediaMetadata(W,Z){return this.post("media/metadata",{id:W,metadata:Z})}reply(W,Z,$={}){var Q;let Y={in_reply_to_tweet_id:Z,...(Q=$.reply)!==null&&Q!==void 0?Q:{}};return this.post("tweets",{text:W,...$,reply:Y})}quote(W,Z,$={}){return this.tweet(W,{...$,quote_tweet_id:Z})}async tweetThread(W){var Z,$;let Q=[];for(let Y of W){let K=Q.length?Q[Q.length-1]:null,J={...typeof Y==="string"?{text:Y}:Y},z=K?K.data.id:(Z=J.reply)===null||Z===void 0?void 0:Z.in_reply_to_tweet_id,G=($=J.text)!==null&&$!==void 0?$:"";if(z)Q.push(await this.reply(G,z,J));else Q.push(await this.tweet(G,J))}return Q}deleteTweet(W){return this.delete("tweets/:id",void 0,{params:{id:W}})}async bookmark(W){let Z=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:W},{params:{id:Z.data.id}})}async deleteBookmark(W){let Z=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:Z.data.id,tweet_id:W}})}follow(W,Z){return this.post("users/:id/following",{target_user_id:Z},{params:{id:W}})}unfollow(W,Z){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}block(W,Z){return this.post("users/:id/blocking",{target_user_id:Z},{params:{id:W}})}unblock(W,Z){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}mute(W,Z){return this.post("users/:id/muting",{target_user_id:Z},{params:{id:W}})}unmute(W,Z){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}createList(W){return this.post("lists",W)}updateList(W,Z={}){return this.put("lists/:id",Z,{params:{id:W}})}removeList(W){return this.delete("lists/:id",void 0,{params:{id:W}})}addListMember(W,Z){return this.post("lists/:id/members",{user_id:Z},{params:{id:W}})}removeListMember(W,Z){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:W,user_id:Z}})}subscribeToList(W,Z){return this.post("users/:id/followed_lists",{list_id:Z},{params:{id:W}})}unsubscribeOfList(W,Z){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:W,list_id:Z}})}pinList(W,Z){return this.post("users/:id/pinned_lists",{list_id:Z},{params:{id:W}})}unpinList(W,Z){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:W,list_id:Z}})}sendDmInConversation(W,Z){return this.post("dm_conversations/:dm_conversation_id/messages",Z,{params:{dm_conversation_id:W}})}sendDmToParticipant(W,Z){return this.post("dm_conversations/with/:participant_id/messages",Z,{params:{participant_id:W}})}createDmConversation(W){return this.post("dm_conversations",W)}}class JW extends _1{constructor(){super(...arguments);this._prefix=M1}get readWrite(){return this}}var zW=JW;class GW extends V1{constructor(){super(...arguments);this._prefix=t}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new zW(this)}}var XW=GW;class g1 extends W1{get v1(){if(this._v1)return this._v1;return this._v1=new U1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new O1(this)}async currentUser(W=!1){return await this.getCurrentUserObject(W)}async currentUserV2(W=!1){return await this.getCurrentUserV2Object(W)}search(W,Z){return this.v2.search(W,Z)}async generateAuthLink(W="oob",{authAccessType:Z,linkMode:$="authenticate",forceLogin:Q,screenName:Y}={}){let K=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:W,x_auth_access_type:Z}),J=`https://api.x.com/oauth/${$}?oauth_token=${encodeURIComponent(K.oauth_token)}`;if(Q!==void 0)J+=`&force_login=${encodeURIComponent(Q)}`;if(Y!==void 0)J+=`&screen_name=${encodeURIComponent(Y)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:J,oauthResult:K});return{url:J,...K}}async login(W){let Z=this.getActiveTokens();if(Z.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let $=await this.post("https://api.x.com/oauth/access_token",{oauth_token:Z.accessToken,oauth_verifier:W}),Q=new this.constructor({appKey:Z.appKey,appSecret:Z.appSecret,accessToken:$.oauth_token,accessSecret:$.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:$.oauth_token,accessSecret:$.oauth_token_secret,userId:$.user_id,screenName:$.screen_name,client:Q}}async appLogin(){let W=this.getActiveTokens();if(W.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let $=await new this.constructor({username:W.appKey,password:W.appSecret},this._requestMaker.clientSettings).post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor($.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(W,Z={}){var $,Q;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 Y=($=Z.state)!==null&&$!==void 0?$:B1.generateRandomString(32),K=B1.getCodeVerifier(),J=B1.getCodeChallengeFromVerifier(K),z=(Q=Z.scope)!==null&&Q!==void 0?Q:"",G=Array.isArray(z)?z.join(" "):z,X=new URL("https://x.com/i/oauth2/authorize"),B={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:W,state:Y,code_challenge:J,code_challenge_method:"s256",scope:G};v.addQueryParamsToUrl(X,B);let j={url:X.toString(),state:Y,codeVerifier:K,codeChallenge:J};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:j,redirectUri:W});return j}async loginWithOAuth2({code:W,codeVerifier:Z,redirectUri:$}){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 Q=await this.post("https://api.x.com/2/oauth2/token",{code:W,code_verifier:Z,redirect_uri:$,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(Q)}async refreshOAuth2Token(W){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 Z=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:W,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(Z)}async revokeOAuth2Token(W,Z="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:W,token_type_hint:Z})}parseOAuth2AccessTokenResult(W){let Z=new this.constructor(W.access_token,this._requestMaker.clientSettings),$=W.scope.split(" ").filter((Q)=>Q);return{client:Z,expiresIn:W.expires_in,accessToken:W.access_token,scope:$,refreshToken:W.refresh_token}}}class m1 extends g1{get v1(){if(this._v1)return this._v1;return this._v1=new x1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new V1(this)}get readOnly(){return this}}class M4 extends I{constructor(){super(...arguments);this._prefix=F1}}class F4 extends M4{constructor(){super(...arguments);this._prefix=F1}get readOnly(){return this}}class L4 extends I{constructor(){super(...arguments);this._prefix=L1}}class D4 extends L4{constructor(){super(...arguments);this._prefix=L1}get readOnly(){return this}}class BW extends D4{constructor(){super(...arguments);this._prefix=L1}get readWrite(){return this}}var jW=BW;class MW extends F4{constructor(){super(...arguments);this._prefix=F1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new jW(this)}}var FW=MW;class H4 extends m1{get v1(){if(this._v1)return this._v1;return this._v1=new G4(this)}get v2(){if(this._v2)return this._v2;return this._v2=new XW(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new FW(this)}static getErrors(W){var Z;if(typeof W!=="object")return[];if(!("data"in W))return[];return(Z=W.data.errors)!==null&&Z!==void 0?Z:[]}static getProfileImageInSize(W,Z){let $=W.split("/").pop(),Q=["normal","bigger","mini"],Y=W;for(let J of Q)if($.includes(`_${J}`)){Y=W.replace(`_${J}`,"");break}if(Z==="original")return Y;let K=Y.lastIndexOf(".");if(K!==-1){let J=Y.slice(K+1);return Y.slice(0,K)+"_"+Z+"."+J}else return Y+"_"+Z}}var v5={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class LW extends i{config;client;constructor(W={}){super();this.config={...v5,...W},this.client=new H4({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${q()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"XOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>q()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!Z)throw Error("XOAuthProvider needs the state and PKCE challenge gemi passes.");if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("XOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL("https://x.com/i/oauth2/authorize"),Q={response_type:"code",client_id:W.clientId,redirect_uri:W.redirectUri,state:Z.state,code_challenge:Z.codeChallenge,code_challenge_method:Z.codeChallengeMethod,scope:this.config.scope.join(" ")};for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new R("missing_code");if(!Z?.codeVerifier)throw new R("invalid_state");let Q=this.config.resolve?await this.clientFor(W):this.staticClient();if(!Q)throw new R("unknown_provider");let Y=this.config.resolve?new H4({clientId:Q.clientId,clientSecret:Q.clientSecret}):this.client,K;try{K=await Y.loginWithOAuth2({code:$,codeVerifier:Z.codeVerifier,redirectUri:Q.redirectUri})}catch(j){throw console.error("X OAuth error: token exchange failed",j),new R("exchange_failed")}let{data:J}=await K.client.v2.me({"user.fields":["name","username","entities"]}),{name:z,email:G,id:X="",username:B}=J??{};return{name:z,email:G,username:B,providerId:X}}}var HW=["instagram_business_basic"],l={authorizeUrl:"https://www.instagram.com/oauth/authorize",tokenUrl:"https://api.instagram.com/oauth/access_token",graphUrl:"https://graph.instagram.com"};class m extends Error{status;type;code;constructor(W,Z,$,Q,Y){super(W,Y);this.status=Z;this.type=$;this.code=Q;this.name="InstagramApiError"}}async function N4(W){let Z=new URLSearchParams({client_id:W.clientId,client_secret:W.clientSecret,grant_type:"authorization_code",redirect_uri:W.redirectUri,code:W.code.replace(/#_$/,"")}),$=await x4(W.tokenUrl??l.tokenUrl,"code exchange",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Z.toString()}),Q=Array.isArray($.data)?$.data[0]:$,Y=Q?.access_token;if(typeof Y!=="string"||Y==="")throw new m("Instagram's code exchange answered without an access token.",200);let K=Q?.permissions;return{accessToken:Y,userId:o0(Q?.user_id),permissions:Array.isArray(K)?K.map(String):typeof K==="string"?K.split(/[\s,]+/).filter(Boolean):null}}async function NW(W){let Z=new URL("/access_token",W.graphUrl??l.graphUrl);return Z.searchParams.set("grant_type","ig_exchange_token"),Z.searchParams.set("client_secret",W.clientSecret),Z.searchParams.set("access_token",W.accessToken),xW(await x4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function UW(W){let Z=new URL("/refresh_access_token",W.graphUrl??l.graphUrl);return Z.searchParams.set("grant_type","ig_refresh_token"),Z.searchParams.set("access_token",W.accessToken),xW(await x4(Z.toString(),"token refresh",{method:"GET"}))}async function U4(W){let Z=W.graphApiVersion?`/${W.graphApiVersion.replace(/^\/+|\/+$/g,"")}`:"",$=new URL(`${Z}/me`,W.graphUrl??l.graphUrl);$.searchParams.set("fields",(W.fields??["user_id","username","name","account_type","profile_picture_url"]).join(",")),$.searchParams.set("access_token",W.accessToken);let Q=await x4($.toString(),"profile request",{method:"GET"}),Y=Array.isArray(Q.data)?Q.data[0]:Q,K=o0(Y?.user_id);if(!K)throw new m("Instagram's /me answered without a user_id.",200);let J={user_id:K},z=o0(Y?.id);if(z)J.id=z;for(let G of["username","name","account_type","profile_picture_url"]){let X=Y?.[G];if(typeof X==="string"&&X!=="")J[G]=X}return J}function xW(W){if(typeof W.access_token!=="string"||W.access_token==="")throw new m("Instagram answered without an access token.",200);let Z=Number(W.expires_in);return{accessToken:W.access_token,tokenType:typeof W.token_type==="string"?W.token_type:null,expiresIn:Number.isFinite(Z)&&Z>0?Z:null}}async function x4(W,Z,$){let Q;try{Q=await fetch(W,{...$,redirect:"error"})}catch(K){throw new m(`Instagram's ${Z} failed to reach Instagram.`,void 0,void 0,void 0,{cause:K})}let Y=a0(await Q.text().catch(()=>""));if(!Q.ok){let K=Y.error??{},J=DW(Y.error_type)??DW(K.type),z=Number(Y.code??K.code);throw new m(`Instagram refused the ${Z} (HTTP ${Q.status}${J?`, ${J}`:""}${Number.isFinite(z)?` ${z}`:""}).`,Q.status,J,Number.isFinite(z)?z:void 0)}return Y}function a0(W){try{let Z=JSON.parse(W.replace(/("(?:user_id|id)"\s*:\s*)(-?\d+)(?=\s*[,}\]])/g,'$1"$2"'));return Z&&typeof Z==="object"?Z:{}}catch{return{}}}function o0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function DW(W){return typeof W==="string"&&W!==""?W:void 0}class SW extends i{createUsersWithoutEmail=!0;linkByEmail=!1;config;constructor(W={}){super();this.config={clientId:process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:HW,redirectPath:"/auth/oauth/instagram/callback",authorizationParams:{},...W}}redirectUri(){return`${q()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"InstagramOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>q()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("InstagramOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(this.config.authorizeUrl??l.authorizeUrl),Q={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,response_type:"code",scope:this.config.scopes.join(",")};if(Z)Q.state=Z.state;for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W){let Z=W.search.get("code");if(!Z)throw new R("missing_code");let $=this.config.resolve?await this.clientFor(W):this.staticClient();if(!$)throw new R("unknown_provider");let Q;try{let Y=await N4({code:Z,clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.redirectUri,tokenUrl:this.config.tokenUrl});Q=await U4({accessToken:Y.accessToken,graphUrl:this.config.graphUrl,graphApiVersion:this.config.graphApiVersion,fields:["user_id","username","name"]})}catch(Y){if(Y instanceof m)throw console.error(`Instagram OAuth error: ${Y.message}`),new R("exchange_failed");throw Y}return{providerId:Q.user_id,username:Q.username,name:Q.name||Q.username}}}import{createHmac as I5,timingSafeEqual as f5}from"crypto";class c extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function y5(W,Z,$={}){if(!Z)throw Error("parseMetaSignedRequest needs the app secret.");if(typeof W!=="string")throw new c("malformed","No signed_request was given.");let Q=W.indexOf(".");if(Q<=0||Q===W.length-1||W.indexOf(".",Q+1)!==-1)throw new c("malformed","A signed_request is <signature>.<payload>.");let Y=W.slice(0,Q),K=W.slice(Q+1);if(!/^[A-Za-z0-9_-]+={0,2}$/.test(Y)||!/^[A-Za-z0-9_-]+={0,2}$/.test(K))throw new c("malformed","A signed_request is base64url.");let J=I5("sha256",Z).update(K).digest(),z=Buffer.from(Y,"base64url");if(z.length!==J.length||!f5(z,J))throw new c("bad_signature","The signed_request's signature does not match the app secret.");let G;try{let D=Buffer.from(K,"base64url").toString("utf8").replace(/("user_id"\s*:\s*)(-?\d+)(?=\s*[,}])/g,'$1"$2"');G=JSON.parse(D)}catch{throw new c("malformed","The signed_request's payload is not JSON.")}if(!G||typeof G!=="object")throw new c("malformed","The signed_request's payload is not an object.");if(String(G.algorithm??"").toUpperCase()!=="HMAC-SHA256")throw new c("unsupported_algorithm","Only HMAC-SHA256 signed_requests are accepted.");let X=Math.floor(($.now??Date.now())/1000),B=Number(G.expires);if(Number.isFinite(B)&&B>0&&B<X)throw new c("expired","The signed_request has expired.");let j=G.user_id;if((typeof j!=="string"||j==="")&&typeof j!=="number")throw new c("missing_user","The signed_request names no user.");return{...G,algorithm:String(G.algorithm),user_id:String(j)}}var A5=86400000;class R4 extends b{instagram;constructor(W={}){let Z={authorizeUrl:W.authorizeUrl??l.authorizeUrl,tokenUrl:W.tokenUrl??l.tokenUrl,graphUrl:W.graphUrl??l.graphUrl,graphApiVersion:W.graphApiVersion};super({authorizeUrl:Z.authorizeUrl,tokenUrl:Z.tokenUrl,clientId:W.clientId??process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:W.scopes??["instagram_business_basic","instagram_business_content_publish"],scopeSeparator:",",pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,apiBaseUrl:Z.graphUrl,refreshLeewaySeconds:W.refreshLeewaySeconds??864000,multiple:W.multiple??!1,tokenPlacement:"query",isTokenRejected:t0,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<A5){if($.reason==="rejected")throw new U("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let Q=await S4("refresh_failed",()=>UW({accessToken:$.accessToken,graphUrl:Z.graphUrl}));return{accessToken:Q.accessToken,refreshToken:null,tokenType:Q.tokenType,expiresAt:Q.expiresIn===null?null:new Date(Date.now()+Q.expiresIn*1000),scopes:$.scopes,providerAccountId:$.providerAccountId}}});this.instagram=Z}async exchangeCode(W){let Z=await S4("exchange_failed",()=>N4({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await S4("exchange_failed",()=>NW({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),Q=await S4("exchange_failed",()=>U4({accessToken:$.accessToken,graphUrl:this.instagram.graphUrl,graphApiVersion:this.instagram.graphApiVersion}));return{accessToken:$.accessToken,refreshToken:null,tokenType:$.tokenType,expiresAt:$.expiresIn===null?null:new Date(Date.now()+$.expiresIn*1000),scopes:Z.permissions??this.config.scopes,providerAccountId:Q.user_id,profile:{...Q}}}refresh(){return Promise.reject(new U("refresh_failed","Instagram connections renew the access token itself; call connection.refresh()."))}}async function t0(W){if(W.status===401)return!0;if(W.status!==400)return!1;let Z=await W.clone().json().catch(()=>null);return Number(Z?.error?.code)===190}async function S4(W,Z){try{return await Z()}catch($){if($ instanceof m)throw new U(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}async function S(W,Z,$){let Q;try{Q=await $()}catch(K){if(K instanceof U)throw K;throw new U(Z,`The ${W} request failed.`,{cause:K})}let Y=await Q.json().catch(()=>null);if(!Q.ok||Y===null||typeof Y!=="object")throw new U(Z,`The ${W} request was refused (HTTP ${Q.status}).`,{status:Q.ok?502:Q.status});return Y}function $1(W,Z,$={}){return fetch(W,{headers:{...$,Authorization:`Bearer ${Z}`,Accept:"application/json"},redirect:"error"})}function f(W,Z,$){if(W.connectionProvider()!==Z)throw TypeError(`${$} takes a connection to this provider; "${W.provider}" is configured with another one.`)}function F(W){return typeof W==="string"&&W!==""?W:null}var y=F;function u(W){return new U("exchange_failed",`${W} did not say which account was connected.`,{status:502})}var RW=["pages_show_list","pages_read_engagement","pages_manage_posts"];class OW extends b{configId;graphApiVersion;constructor(W={}){let Z=W.graphApiVersion?.replace(/^\/+|\/+$/g,""),$=Z?`/${Z}`:"",Q=W.apiBaseUrl??"https://graph.facebook.com";super({authorizeUrl:W.authorizeUrl??`${W.dialogUrl??"https://www.facebook.com"}${$}/dialog/oauth`,tokenUrl:W.tokenUrl??`${Q}${$}/oauth/access_token`,revokeUrl:W.revokeUrl??`${Q}${$}/me/permissions`,apiBaseUrl:Q,clientId:W.clientId??process.env.FACEBOOK_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.FACEBOOK_CLIENT_SECRET??"",scopes:W.scopes??RW,scopeSeparator:",",pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??60,multiple:W.multiple??!1,tokenPlacement:"query",revokeTokenHint:"access_token",isTokenRejected:t0,refreshStrategy:async(Y)=>{if(Y.reason==="rejected")throw new U("refresh_failed","Facebook refused the access token (OAuthException 190).",{status:401});return null}});this.configId=W.configId??(process.env.FACEBOOK_CONFIG_ID||void 0),this.graphApiVersion=Z||void 0}authorizationUrl(W){let Z=new URL(super.authorizationUrl(W));if(this.configId)Z.searchParams.delete("scope"),Z.searchParams.set("config_id",this.configId);return Z.toString()}async exchangeCode(W){let Z=await this.tokenCall({client_id:this.config.clientId,client_secret:this.config.clientSecret,redirect_uri:W.redirectUri,code:W.code}),$=await this.tokenCall({grant_type:"fb_exchange_token",client_id:this.config.clientId,client_secret:this.config.clientSecret,fb_exchange_token:Z.accessToken}),Q=$.accessToken,Y=await S("Facebook /me","exchange_failed",()=>fetch(this.graphUrl(this.path("/me",{fields:"id,name,picture{url}"}),Q),{redirect:"error"})),K=y(Y.id);if(!K)throw u("Facebook");let J=await S("Facebook /me/permissions","exchange_failed",()=>fetch(this.graphUrl(this.path("/me/permissions"),Q),{redirect:"error"})),z=(Array.isArray(J.data)?J.data:[]).filter((B)=>B.status==="granted"&&typeof B.permission==="string").map((B)=>B.permission),G=await this.listPages((B)=>fetch(this.graphUrl(B,Q),{redirect:"error"}),"exchange_failed"),X={id:K,name:F(Y.name),username:null,avatarUrl:r0(Y.picture),pages:G.map(({accessToken:B,...j})=>j)};return{accessToken:Q,refreshToken:null,tokenType:$.tokenType,expiresAt:$.expiresIn===null?null:new Date(Date.now()+$.expiresIn*1000),scopes:z.length>0?z:this.config.scopes,providerAccountId:K,profile:{...X}}}refresh(){return Promise.reject(new U("refresh_failed","Facebook issues no refresh token; reconnect the account."))}async revoke(W){let Z=new URL(this.config.revokeUrl);Z.searchParams.set("access_token",W);let $;try{$=await fetch(Z,{method:"DELETE",redirect:"error"})}catch(Q){throw new U("revoke_failed","The revocation request failed.",{cause:Q})}if(await $.body?.cancel().catch(()=>{}),!$.ok)throw new U("revoke_failed",`Facebook refused the revocation (HTTP ${$.status}).`,{status:$.status})}async profile(W){f(W,this,"FacebookConnectionProvider.profile()");let Z=await S("Facebook /me","request_failed",()=>W.fetch(this.path("/me",{fields:"id,name,picture{url}"}))),$=y(Z.id);if(!$)throw u("Facebook");let Q=await this.pages(W);return{id:$,name:F(Z.name),username:null,avatarUrl:r0(Z.picture),pages:Q.map((Y)=>Y.toJSON())}}async pages(W){return f(W,this,"FacebookConnectionProvider.pages()"),(await this.listPages(($)=>W.fetch($),"request_failed")).map(($)=>new e0(W,$))}path(W,Z={}){let $=this.graphApiVersion?`/${this.graphApiVersion}`:"",Q=new URL(`${$}${W}`,this.config.apiBaseUrl);for(let[Y,K]of Object.entries(Z))Q.searchParams.set(Y,K);return`${Q.pathname}${Q.search}`}graphUrl(W,Z){let $=new URL(W,this.config.apiBaseUrl);if($.origin!==new URL(this.config.apiBaseUrl).origin)throw new U("forbidden_url","Facebook paged to another origin.");return $.searchParams.set("access_token",Z),$}async listPages(W,Z){let $=[],Q=this.path("/me/accounts",{fields:"id,name,category,tasks,access_token,picture{url}",limit:"100"});for(let Y=0;Q!==null&&Y<20;Y++){let K=Q,J=await S("Facebook /me/accounts",Z,()=>W(K));for(let G of Array.isArray(J.data)?J.data:[]){let X=y(G.id);if(!X)continue;$.push({id:X,name:F(G.name),category:F(G.category),tasks:Array.isArray(G.tasks)?G.tasks.filter((B)=>typeof B==="string"):[],avatarUrl:r0(G.picture),accessToken:F(G.access_token)})}let z=J.paging??{};Q=typeof z.next==="string"?z.next:null}return $}async tokenCall(W){let Z=new URL(this.config.tokenUrl);for(let[K,J]of Object.entries(W))Z.searchParams.set(K,J);let $=await S("Facebook token","exchange_failed",()=>fetch(Z,{headers:{Accept:"application/json"},redirect:"error"})),Q=F($.access_token);if(!Q)throw new U("exchange_failed","Facebook answered the code exchange without a token.",{status:502});let Y=Number($.expires_in);return{accessToken:Q,tokenType:F($.token_type),expiresIn:Number.isFinite(Y)&&Y>0?Y:null}}}class e0{connection;id;name;category;tasks;avatarUrl;#W;constructor(W,Z){this.connection=W;this.id=Z.id,this.name=Z.name,this.category=Z.category,this.tasks=Z.tasks,this.avatarUrl=Z.avatarUrl,this.#W=Z.accessToken}get canPost(){return this.tasks.includes("CREATE_CONTENT")}accessToken(){if(this.#W===null)throw new U("request_failed",`Facebook gave no Page token for Page ${this.id}.`);return this.#W}fetch(W,Z={}){return this.connection.fetchWithToken(this.accessToken(),W,Z)}toJSON(){return{id:this.id,name:this.name,category:this.category,tasks:[...this.tasks],avatarUrl:this.avatarUrl}}[Symbol.for("nodejs.util.inspect.custom")](){return{FacebookPage:this.toJSON()}}}function r0(W){let Z=W?.data;return F(Z?.url)}var VW=["openid","profile","w_member_social"],h5=["w_organization_social","r_organization_social"];class kW extends b{apiVersion;constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:W.tokenUrl??"https://www.linkedin.com/oauth/v2/accessToken",revokeUrl:W.revokeUrl,apiBaseUrl:W.apiBaseUrl??"https://api.linkedin.com",clientId:W.clientId??process.env.LINKEDIN_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.LINKEDIN_CLIENT_SECRET??"",scopes:W.scopes??VW,pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??86400,multiple:W.multiple??!1});this.apiVersion=W.apiVersion??"202610"}async exchangeCode(W){let Z=await super.exchangeCode(W),$=_W(await S("LinkedIn userinfo","exchange_failed",()=>$1(this.userInfoUrl(),Z.accessToken)));return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"LinkedInConnectionProvider.profile()"),_W(await S("LinkedIn userinfo","request_failed",()=>W.fetch(this.userInfoUrl())))}async organizations(W){f(W,this,"LinkedInConnectionProvider.organizations()");let Z=new URL("/rest/organizationAcls",this.config.apiBaseUrl);Z.searchParams.set("q","roleAssignee"),Z.searchParams.set("state","APPROVED");let $=await S("LinkedIn organizationAcls","request_failed",()=>W.fetch(Z,{headers:this.restHeaders()})),Q=new Map;for(let J of Array.isArray($.elements)?$.elements:[]){let z=F(J.organization)??F(J.organizationTarget),G=z?.match(/^urn:li:organization:(\d+)$/)?.[1];if(!z||!G||Q.has(G))continue;Q.set(G,{id:G,urn:z,role:F(J.role)??"UNKNOWN",name:null,vanityName:null})}if(Q.size===0)return[];let Y=`/rest/organizations?ids=List(${[...Q.keys()].join(",")})`,K=await W.fetch(Y,{headers:this.restHeaders()});if(K.ok){let J=await K.json().catch(()=>({}));for(let[z,G]of Object.entries(J.results??{})){let X=Q.get(z);if(!X)continue;X.name=F(G.localizedName),X.vanityName=F(G.vanityName)}}else await K.body?.cancel().catch(()=>{});return[...Q.values()]}restHeaders(){return{"LinkedIn-Version":this.apiVersion,"X-Restli-Protocol-Version":"2.0.0"}}userInfoUrl(){return new URL("/v2/userinfo",this.config.apiBaseUrl)}}function _W(W){let Z=y(W.sub);if(!Z)throw u("LinkedIn");let $=F(W.given_name),Q=F(W.family_name);return{id:Z,name:F(W.name)??([$,Q].filter(Boolean).join(" ")||null),username:null,avatarUrl:F(W.picture),authorUrn:`urn:li:person:${Z}`,email:F(W.email)}}var TW=["user.info.basic","video.publish","video.upload"];class PW extends b{constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://www.tiktok.com/v2/auth/authorize/",tokenUrl:W.tokenUrl??"https://open.tiktokapis.com/v2/oauth/token/",revokeUrl:W.revokeUrl??"https://open.tiktokapis.com/v2/oauth/revoke/",apiBaseUrl:W.apiBaseUrl??"https://open.tiktokapis.com",clientId:W.clientKey??W.clientId??process.env.TIKTOK_CLIENT_KEY??"",clientSecret:W.clientSecret??process.env.TIKTOK_CLIENT_SECRET??"",clientIdParam:"client_key",scopes:W.scopes??TW,scopeSeparator:",",pkce:!1,revokeTokenHint:"access_token",authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??300,multiple:W.multiple??!1})}async exchangeCode(W){let Z=await super.exchangeCode(W),$=CW(await S("TikTok user info","exchange_failed",()=>$1(this.userInfoUrl(Z.scopes),Z.accessToken)),"exchange_failed");return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"TikTokConnectionProvider.profile()"),CW(await S("TikTok user info","request_failed",()=>W.fetch(this.userInfoUrl([...W.scopes]))),"request_failed")}userInfoUrl(W){let Z=new URL("/v2/user/info/",this.config.apiBaseUrl),$=["open_id","union_id","avatar_url","display_name"];if(W.includes("user.info.profile"))$.push("username");return Z.searchParams.set("fields",$.join(",")),Z}}function CW(W,Z){let $=W.error??{};if(typeof $.code==="string"&&$.code!=="ok")throw new U(Z,`TikTok refused the user info request (${E5($.code)}).`,{status:400});let Q=(W.data??{}).user,Y=y(Q?.open_id);if(!Q||!Y)throw u("TikTok");return{id:Y,name:F(Q.display_name),username:F(Q.username),avatarUrl:F(Q.avatar_url),unionId:F(Q.union_id)}}function E5(W){return/^[a-z0-9_]{1,64}$/.test(W)?W:"error"}var wW=["https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.readonly"];class qW extends b{constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:W.tokenUrl??"https://oauth2.googleapis.com/token",revokeUrl:W.revokeUrl??"https://oauth2.googleapis.com/revoke",apiBaseUrl:W.apiBaseUrl??"https://www.googleapis.com",clientId:W.clientId??process.env.GOOGLE_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.GOOGLE_CLIENT_SECRET??"",scopes:W.scopes??wW,pkce:!0,authorizationParams:{access_type:"offline",prompt:"consent",include_granted_scopes:"true",...W.authorizationParams},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??300,multiple:W.multiple??!1})}async exchangeCode(W){let Z=await super.exchangeCode(W),$=bW(await S("YouTube channel","exchange_failed",()=>$1(this.channelUrl(),Z.accessToken)));return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"YouTubeConnectionProvider.profile()"),bW(await S("YouTube channel","request_failed",()=>W.fetch(this.channelUrl())))}channelUrl(){let W=new URL("/youtube/v3/channels",this.config.apiBaseUrl);return W.searchParams.set("part","snippet"),W.searchParams.set("mine","true"),W}}function bW(W){let[Z]=Array.isArray(W.items)?W.items:[],$=y(Z?.id);if(!$)throw u("YouTube (the Google account has no channel)");let Q=Z.snippet??{},Y=Q.thumbnails??{},K=Y.high?.url??Y.medium?.url??Y.default?.url;return{id:$,name:F(Q.title),username:F(Q.customUrl),avatarUrl:F(K)}}var IW=["tweet.read","tweet.write","users.read","media.write","offline.access"];class fW extends b{constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://x.com/i/oauth2/authorize",tokenUrl:W.tokenUrl??"https://api.x.com/2/oauth2/token",revokeUrl:W.revokeUrl??"https://api.x.com/2/oauth2/revoke",apiBaseUrl:W.apiBaseUrl??"https://api.x.com",clientId:W.clientId??process.env.X_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.X_CLIENT_SECRET??process.env.X_SECRET??"",scopes:W.scopes??IW,clientAuth:"basic",pkce:!0,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??300,multiple:W.multiple??!1})}async exchangeCode(W){let Z=await super.exchangeCode(W),$=vW(await S("X profile","exchange_failed",()=>$1(this.profileUrl(),Z.accessToken)));return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"XConnectionProvider.profile()"),vW(await S("X profile","request_failed",()=>W.fetch(this.profileUrl())))}profileUrl(){let W=new URL("/2/users/me",this.config.apiBaseUrl);return W.searchParams.set("user.fields","profile_image_url"),W}}function vW(W){let Z=W.data??{},$=y(Z.id);if(!$)throw u("X");return{id:$,name:F(Z.name),username:F(Z.username),avatarUrl:F(Z.profile_image_url)}}class _ extends Error{code;status;graphCode;graphSubcode;containerId;constructor(W,Z,$={}){super(Z);this.code=W;this.name="InstagramPublishError",this.status=$.status,this.graphCode=$.graphCode,this.graphSubcode=$.graphSubcode,this.containerId=$.containerId}}var w={captionLength:2200,hashtags:30,mentions:20,userTags:20,carouselMin:2,carouselMax:10},yW="instagram_business_content_publish",g5={for(W,Z={}){return new $6(W,Z)}};class $6{connection;version;pollIntervalMs;maxPollIntervalMs;timeoutMs;constructor(W,Z={}){this.connection=W;let $=W.connectionProvider();if(!($ instanceof R4))throw TypeError(`Instagram.for() takes an Instagram connection; "${W.provider}" is not an InstagramConnectionProvider.`);let Q=Z.graphApiVersion??$.instagram.graphApiVersion;this.version=Q?`/${Q.replace(/^\/+|\/+$/g,"")}`:"",this.pollIntervalMs=Z.pollIntervalMs??2000,this.maxPollIntervalMs=Z.maxPollIntervalMs??1e4,this.timeoutMs=Z.timeoutMs??300000}async publishImage(W,Z={}){if(c1("imageUrl",W.imageUrl),Z6(W.caption),W.altText!==void 0&&typeof W.altText!=="string")T("altText must be a string.");if(W.userTags!==void 0)t5(W.userTags);let $=this.start(Z),Q=await this.createContainer({image_url:W.imageUrl,caption:W.caption,alt_text:W.altText,user_tags:W.userTags?JSON.stringify(W.userTags):void 0,location_id:W.locationId},$);return this.publishContainer(Q,!1,$)}async publishCarousel(W,Z={}){let $=W.items;if(!Array.isArray($)||$.length<w.carouselMin||$.length>w.carouselMax)T(`A carousel takes ${w.carouselMin} to ${w.carouselMax} items.`);$.forEach((z,G)=>gW(`items[${G}]`,z)),Z6(W.caption);let Q=this.start(Z),Y=[];for(let z of $)Y.push(await this.createContainer(z.videoUrl!==void 0?{media_type:"VIDEO",video_url:z.videoUrl,is_carousel_item:"true"}:{image_url:z.imageUrl,is_carousel_item:"true"},Q));for(let[z,G]of $.entries())if(G.videoUrl!==void 0)await this.waitUntilFinished(Y[z],Q);let K=$.some((z)=>z.videoUrl!==void 0),J=await this.createContainer({media_type:"CAROUSEL",children:Y.join(","),caption:W.caption},Q);return this.publishContainer(J,K,Q)}async publishReel(W,Z={}){if(c1("videoUrl",W.videoUrl),W.coverUrl!==void 0)c1("coverUrl",W.coverUrl);if(Z6(W.caption),W.thumbOffset!==void 0&&!(Number.isInteger(W.thumbOffset)&&W.thumbOffset>=0))T("thumbOffset must be a whole number of milliseconds, 0 or more.");let $=this.start(Z),Q=await this.createContainer({media_type:"REELS",video_url:W.videoUrl,caption:W.caption,cover_url:W.coverUrl,share_to_feed:W.shareToFeed===void 0?void 0:String(W.shareToFeed),thumb_offset:W.thumbOffset===void 0?void 0:String(W.thumbOffset)},$);return this.publishContainer(Q,!0,$)}async publishStory(W,Z={}){gW("story",W);let $=this.start(Z),Q=W.videoUrl!==void 0,Y=await this.createContainer(Q?{media_type:"STORIES",video_url:W.videoUrl}:{media_type:"STORIES",image_url:W.imageUrl},$);return this.publishContainer(Y,Q,$)}async publishingLimit(W={}){let Z=this.start(W),$=await this.call("publishing limit request",`/${this.accountId()}/content_publishing_limit?fields=quota_usage,config`,void 0,Z),Q=Array.isArray($.data)?$.data[0]:$,Y=Q?.config??{},K=W6(Q?.quota_usage,0),J=W6(Y.quota_total,100);return{quotaUsage:K,quotaTotal:J,quotaDurationSeconds:W6(Y.quota_duration,86400),remaining:Math.max(0,J-K)}}async containerStatus(W,Z={}){return this.readStatus(W,this.start(Z))}start(W){if(W.signal?.throwIfAborted(),!this.connection.hasScopes(yW))throw new _("permission_denied",`The Instagram connection was not granted ${yW}; connect it again with that scope.`);return{signal:W.signal,deadline:Date.now()+(W.timeoutMs??this.timeoutMs)}}accountId(){let W=this.connection.providerAccountId;if(!W)throw new _("invalid_input","The Instagram connection has no account id (providerAccountId).");return W}async createContainer(W,Z){let $=await this.call("media container request",`/${this.accountId()}/media`,W,Z);return hW($,"media container request")}async publishContainer(W,Z,$){try{if(Z)await this.waitUntilFinished(W,$);let Q=await this.publishOnce(W,Z,$);return{mediaId:Q,permalink:await this.permalink(Q,$)}}catch(Q){throw Q instanceof _?o5(Q,W):Q}}async publishOnce(W,Z,$){try{return await this.mediaPublish(W,$)}catch(Q){if(!(Q instanceof _))throw Q;if(Q.code==="transient"){let{statusCode:Y}=await this.readStatus(W,$);if(Y==="PUBLISHED")throw new _("unconfirmed","Instagram's media_publish failed, but the container reads PUBLISHED: the post is probably live. Do not publish it again.",{status:Q.status,graphCode:Q.graphCode,graphSubcode:Q.graphSubcode});if(Y!=="FINISHED")throw Q;return this.mediaPublish(W,$)}if(s5(Q)&&!Z)return await this.waitUntilFinished(W,$),this.mediaPublish(W,$);throw Q}}async mediaPublish(W,Z){let $=await this.call("media_publish request",`/${this.accountId()}/media_publish`,{creation_id:W},Z,{retry:!1});return hW($,"media_publish request")}async permalink(W,Z){try{let $=await this.call("permalink request",`/${W}?fields=permalink`,void 0,Z,{retry:!1});return typeof $.permalink==="string"?$.permalink:void 0}catch{return}}async readStatus(W,Z){if(!/^\d+$/.test(W))T("A container id is a string of digits.");let $=await this.call("container status request",`/${W}?fields=status_code,status`,void 0,Z),Q=$.status_code;if(typeof Q!=="string"||!m5.has(Q))throw new _("graph_error","Instagram's container status answered without a known status_code.",{status:200,containerId:W});let Y={id:W,statusCode:Q};if(typeof $.status==="string"&&$.status!=="")Y.status=uW($.status);return Y}async waitUntilFinished(W,Z){let $=this.pollIntervalMs;for(;;){let{statusCode:Q,status:Y}=await this.readStatus(W,Z);if(Q==="FINISHED")return;if(Q==="PUBLISHED")throw new _("invalid_input","That media container has been published already.",{containerId:W});if(Q==="ERROR")throw new _("invalid_media",`Instagram could not process the media${Y?` (${Y})`:""}.`,{containerId:W});if(Q==="EXPIRED")throw new _("expired","The media container expired before it was published.",{containerId:W});let K=Z.deadline-Date.now();if(K<=0)throw new _("timeout","Instagram had not finished processing the media in time; the container is still processing.",{containerId:W});await a5(Math.min($,K),Z.signal),$=Math.min($*1.5,this.maxPollIntervalMs)}}async call(W,Z,$,Q,{retry:Y=!0}={}){try{return await this.callOnce(W,Z,$,Q)}catch(K){if(!Y||!(K instanceof _)||K.code!=="transient")throw K;return this.callOnce(W,Z,$,Q)}}async callOnce(W,Z,$,Q){Q.signal?.throwIfAborted();let Y={method:$?"POST":"GET",signal:Q.signal};if($){let z=new URLSearchParams;for(let[G,X]of Object.entries($))if(X!==void 0)z.set(G,X);Y.body=z}let K;try{K=await this.connection.fetch(`${this.version}${Z}`,Y)}catch(z){if(Q.signal?.aborted)throw Q.signal.reason;if(z instanceof TypeError)throw new _("transient",`Instagram's ${W} failed to reach Instagram.`);throw z}let J=a0(await K.text().catch(()=>""));if(K.ok)return J;throw i5(W,K.status,J)}}var m5=new Set(["EXPIRED","ERROR","FINISHED","IN_PROGRESS","PUBLISHED"]),c5=new Set([4,17,32,613,80002]),u5=new Set([3,10]),p5=new Set([9004,352,36000,36001,36002,36003,36004]),d5=new Set([2207004,2207005,2207006,2207009,2207023,2207026,2207028,2207052]),l5=new Set([102,190,463,467]),n5=new Set([2207001,2207003,2207053]),AW={code:9007,subcode:2207027};function i5(W,Z,$){let Q=$.error??{},Y=EW(Q.code),K=EW(Q.error_subcode),J=typeof Q.type==="string"&&Q.type!==""?Q.type:void 0,z=typeof Q.message==="string"&&Q.message!==""?`: ${uW(Q.message)}`:"",G=[Y,K].filter((j)=>j!==void 0).join("/"),X=`Instagram refused the ${W} (HTTP ${Z}${J?`, ${J}`:""}${G?` ${G}`:""})${z}`,B="graph_error";if(K===2207042)B="quota_exceeded";else if(K===2207010)B="invalid_input";else if(Y!==void 0&&c5.has(Y))B="rate_limited";else if(Y!==void 0&&l5.has(Y))B="reconnect_required";else if(Y!==void 0&&(u5.has(Y)||Y>=200&&Y<=299))B="permission_denied";else if(Y!==void 0&&p5.has(Y)||K!==void 0&&d5.has(K))B="invalid_media";else if(Q.is_transient===!0||Y===1||Y===2||K!==void 0&&n5.has(K)||Z>=500||Z===429)B=Z===429?"rate_limited":"transient";return new _(B,X,{status:Z,graphCode:Y,graphSubcode:K})}function s5(W){return W.graphCode===AW.code||W.graphSubcode===AW.subcode}function o5(W,Z){if(W.containerId)return W;return new _(W.code,W.message,{status:W.status,graphCode:W.graphCode,graphSubcode:W.graphSubcode,containerId:Z})}function uW(W){return W.replace(/access_token=[^&\s"']*/gi,"access_token=[redacted]").replace(/\b(?:IG|EAA)[A-Za-z0-9_-]{20,}/g,"[redacted]").slice(0,500)}function hW(W,Z){let $=W.id;if(typeof $==="string"&&$!=="")return $;if(typeof $==="number"&&Number.isSafeInteger($))return String($);throw new _("graph_error",`Instagram's ${Z} answered without an id.`,{status:200})}function EW(W){let Z=Number(W);return W!==void 0&&W!==null&&Number.isFinite(Z)?Z:void 0}function W6(W,Z){let $=Number(W);return W!==void 0&&W!==null&&Number.isFinite($)?$:Z}function a5(W,Z){return new Promise(($,Q)=>{if(Z?.aborted)return Q(Z.reason);let Y=()=>{clearTimeout(K),Q(Z?.reason)},K=setTimeout(()=>{Z?.removeEventListener("abort",Y),$()},W);Z?.addEventListener("abort",Y,{once:!0})})}function T(W){throw new _("invalid_input",W)}function Z6(W){if(W===void 0)return;if(typeof W!=="string")T("caption must be a string.");if([...W].length>w.captionLength)T(`A caption takes at most ${w.captionLength} characters.`);if((W.match(/#[\p{L}\p{N}_]+/gu)??[]).length>w.hashtags)T(`A caption takes at most ${w.hashtags} hashtags.`);if((W.match(/(?<![\p{L}\p{N}_.@])@[\p{L}\p{N}_.]+/gu)??[]).length>w.mentions)T(`A caption takes at most ${w.mentions} @mentions.`)}function t5(W){if(!Array.isArray(W)||W.length>w.userTags)T(`userTags takes at most ${w.userTags} tags.`);for(let Z of W){let $=(Q)=>typeof Q==="number"&&Q>=0&&Q<=1;if(typeof Z?.username!=="string"||Z.username===""||!$(Z.x)||!$(Z.y))T("Each user tag needs a username, and x and y between 0 and 1.")}}function gW(W,Z){let $=Z?.imageUrl!==void 0,Q=Z?.videoUrl!==void 0;if($===Q)T(`${W} takes exactly one of imageUrl and videoUrl.`);if($)c1(`${W}.imageUrl`,Z.imageUrl);else c1(`${W}.videoUrl`,Z.videoUrl)}function c1(W,Z){let $;try{$=new URL(Z)}catch{T(`${W} is not an absolute URL.`)}if($.protocol!=="https:")T(`${W} must be an https URL: Instagram fetches the media from it.`);let Q=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Y=mW(Q);if(Y?cW(Y)!==null:!Q.includes(".")||/(^|\.)(localhost|local|internal)$/.test(Q))T(`${W} must be a public URL: Instagram fetches the media from it.`)}class Q6{describe;rollout;when;serverOnly;salt;constructor(W={}){if(W.rollout!==void 0){let{rollout:Z}=W;if(!Number.isFinite(Z)||Z<0||Z>100)throw Error(`A feature's \`rollout\` must be a number between 0 and 100, received ${String(Z)}.`)}this.describe=W.describe,this.rollout=W.rollout,this.when=W.when,this.serverOnly=W.serverOnly??!1,this.salt=W.salt}}function r5(W={}){return new Q6(W)}class pW extends Y6{rows=new Map;constructor(W={}){super();for(let[Z,$]of Object.entries(W))this.rows.set(Z,{key:Z,active:$})}async load(){return[...this.rows.values()].map((W)=>({...W}))}async write(W,Z,$){return this.rows.set(W,{key:W,active:Z,updatedBy:$.actor,updatedAt:new Date}),{actorRecorded:!0}}}export{Q9 as workflowEnded,TZ as viewRouteConfigDefaults,E9 as translationConfigDefaults,O4 as toRangeHeaderValue,X8 as subjectFor,vZ as strictCspPolicy,O8 as sniffContentType,O9 as scheduleConfigDefaults,k4 as resolveRange,$$ as redisConfigDefaults,e9 as rateLimiterConfigDefaults,iZ as queueConfigDefaults,y5 as parseMetaSignedRequest,k1 as parseContentRange,Z8 as mintSessionToken,AZ as middlewareConfigDefaults,B9 as mcpCallOf,gZ as mailConfigDefaults,k8 as logConfigDefaults,W8 as isSessionToken,F5 as isFixedSignInCode,MZ as isFinalRunStatus,v6 as isBroadcastEvent,_8 as isActiveContentType,z8 as inRollout,OZ as imageConfigDefaults,M5 as fixedSignInCode,x8 as filesystemConfigDefaults,u9 as featuresConfigDefaults,V9 as eventConfigDefaults,G8 as evaluateFeature,n8 as encodeCursor,bZ as documentScriptCspHash,P9 as discoverWorkflows,q9 as discoverListeners,T9 as discoverJobs,b9 as discoverCronJobs,w9 as discoverCommands,h9 as defineTranslationConfig,R9 as defineScheduleConfig,XZ as defineRunsConfig,kZ as defineRouteConfig,Z$ as defineRedisConfig,r9 as defineRateLimiterConfig,nZ as defineQueueConfig,yZ as defineMiddlewareConfig,EZ as defineMailConfig,V8 as defineLogConfig,RZ as defineImageConfig,U8 as defineFilesystemConfig,c9 as defineFeaturesConfig,r5 as defineFeature,_9 as defineEventConfig,iW as defineEncryptionConfig,N9 as defineCommandConfig,x9 as defineCommand,d8 as defineChangeFeedConfig,T8 as defineCacheConfig,ZZ as defineBroadcastConfig,Q8 as defineAuthConfig,i8 as decodeCursor,dZ as createWorkflowTableStatements,DZ as createRunsTableStatements,U9 as commandConfigDefaults,l8 as changeFeedConfigDefaults,P8 as cacheConfigDefaults,J8 as bucketOf,K8 as bucketKey,$Z as broadcastConfigDefaults,u4 as bearerToken,Y8 as authConfigDefaults,_4 as assertDeletablePrefix,CZ as apiRouteConfigDefaults,qW as YouTubeConnectionProvider,wW as YOUTUBE_DEFAULT_SCOPES,IW as X_DEFAULT_SCOPES,LW as XOAuthProvider,fW as XConnectionProvider,Y9 as WorkflowRuntime,Z9 as WorkflowCancelledError,C9 as Workflow,eZ as WaitTimeoutError,IZ as ViewRouteDispatcher,L8 as UndeclaredFeatureError,PW as TikTokConnectionProvider,v8 as TaggedCache,TW as TIKTOK_DEFAULT_SCOPES,R8 as StorageFetchTimeoutError,W9 as StepTimeoutError,rZ as StepFailedError,$9 as Step,pW as StaticFeatureFlagSource,SZ as Sharp,L9 as Scheduler,g9 as ScheduleServiceProvider,qZ as STATIC_NAVIGATION_CSP_HASH,WZ as SOCKET_ID_HEADER,e5 as SESSION_TOKEN_PREFIX,J6 as S3Driver,K$ as RunsServiceProvider,HZ as RunNotFoundError,UZ as RunManager,NZ as RunFailure,Y$ as RouteServiceProvider,hZ as ResendDriver,Q$ as RedisServiceProvider,b4 as RedisRateLimiterTimeoutError,l1 as RedisRateLimiterDisconnectedError,j6 as RedisRateLimiter,d1 as RedisManager,w8 as RedisCacheStore,YZ as RedisBroadcastDriver,W$ as RateLimiterServiceProvider,T4 as RateLimiterDriver,$8 as RateLimiter,j1 as RangeNotSatisfiableError,v9 as QueueServiceProvider,K9 as QueueManager,p8 as ProviderConnection,b6 as PrismaMcpOAuthStore,zZ as PendingBroadcast,jZ as OPEN_RUN_STATUSES,c8 as OAuthReconnectRequiredError,i as OAuthProvider,b as OAuthConnectionProvider,U as OAuthConnectionError,R as OAuthCallbackError,t9 as MiddlewareServiceProvider,VZ as MiddlewareRegistry,c as MetaSignedRequestError,sZ as MemoryWorkflowStore,FZ as MemoryRunStore,oZ as MemoryQueueDriver,P6 as MemoryMcpOAuthStore,uZ as MemoryLockStore,g8 as MemoryConnectionStore,o8 as MemoryChangeFeedDriver,b8 as MemoryCacheStore,QZ as MemoryBroadcastDriver,G9 as McpToolError,j9 as McpRegistry,C6 as McpOAuthServer,F9 as McpHttpServer,X9 as McpCallRefusedError,M9 as McpApiKeyResolver,d9 as MailServiceProvider,mZ as MailManager,a9 as LogServiceProvider,C8 as LogManager,y8 as LockManager,I8 as LockLostError,k9 as Listener,kW as LinkedInConnectionProvider,h5 as LINKEDIN_ORGANIZATION_SCOPES,VW as LINKEDIN_DEFAULT_SCOPES,o9 as KernelIdServiceProvider,PZ as KernelId,J9 as Job,tZ as ItemSource,e8 as InvalidChannelError,$6 as InstagramPublisher,_ as InstagramPublishError,SW as InstagramOAuthProvider,R4 as InstagramConnectionProvider,m as InstagramApiError,g5 as Instagram,P4 as InMemoryRateLimiter,s9 as ImageServiceProvider,xZ as ImageOptimizationDriver,_Z as ImageManager,aZ as ITEM_SOURCE_ITEM_LIMIT,wZ as ISLAND_LOADER_CSP_HASH,w as INSTAGRAM_LIMITS,f8 as HeldLock,E6 as GoogleOAuthProvider,m6 as GitHubOAuthProvider,i9 as FilesystemServiceProvider,S8 as FilesystemManager,N8 as FileSystemDriver,C1 as FileStorageDriver,Y1 as FileNotFoundError,p9 as FeaturesServiceProvider,F8 as FeatureSourceReadOnlyError,D8 as FeatureScope,B8 as FeatureReloadError,M8 as FeatureModelMissingError,H8 as FeatureManager,j8 as FeatureFlagStore,Y6 as FeatureFlagSource,Q6 as Feature,e0 as FacebookPage,OW as FacebookConnectionProvider,BZ as FINAL_RUN_STATUSES,RW as FACEBOOK_DEFAULT_SCOPES,n9 as EventServiceProvider,h as EventManager,r1 as Event,l9 as EncryptionServiceProvider,h8 as EncryptionKeyError,A8 as Encrypter,w4 as EmailDriver,E8 as DecryptionError,pZ as DatabaseWorkflowStore,LZ as DatabaseRunStore,lZ as DatabaseQueueDriver,cZ as DatabaseLockStore,m9 as DatabaseFeatureFlagSource,m8 as DatabaseConnectionStore,s8 as DatabaseChangeFeedDriver,z9 as DEFAULT_MCP_SCOPE,S9 as CronJob,u8 as ConnectionManager,J$ as CommandRegistry,D9 as CommandFailed,H9 as Command,r8 as ChangeFeedSubscription,y9 as ChangeFeedServiceProvider,t8 as ChangeFeedManager,a8 as ChangeFeedFullError,f9 as CacheServiceProvider,q8 as CacheManager,n1 as CONSENT_PAGE_HEADERS,I9 as BroadcastServiceProvider,GZ as BroadcastScope,KZ as BroadcastPayloadTooLargeError,JZ as BroadcastManager,I6 as BroadcastEvent,G6 as AzureBlobDriver,A9 as AuthServiceProvider,z1 as AuthManager,fZ as ApiRouteDispatcher,q4 as AcsDriver};
70
+ `).filter((Q)=>Q).map((Q)=>JSON.parse(Q))}async usage(W={}){return this.get("usage/tweets",W)}community(W,Z={}){return this.get("communities/:id",Z,{params:{id:W}})}searchCommunities(W,Z={}){return this.get("communities/search",{query:W,...Z})}}class _1 extends R1{constructor(){super(...arguments);this._prefix=F1}get readOnly(){return this}}class V1 extends O1{constructor(){super(...arguments);this._prefix=t}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new _1(this)}hideReply(W,Z){return this.put("tweets/:id/hidden",{hidden:Z},{params:{id:W}})}like(W,Z){return this.post("users/:id/likes",{tweet_id:Z},{params:{id:W}})}unlike(W,Z){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:W,tweet_id:Z}})}retweet(W,Z){return this.post("users/:id/retweets",{tweet_id:Z},{params:{id:W}})}unretweet(W,Z){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:W,tweet_id:Z}})}tweet(W,Z={}){if(typeof W==="object")Z=W;else Z={text:W,...Z};return this.post("tweets",Z)}async uploadMedia(W,Z,$=1048576){let Q=Z.media_category;if(!Z.media_category){if(Z.media_type.includes("gif"))Q="tweet_gif";else if(Z.media_type.includes("image"))Q="tweet_image";else if(Z.media_type.includes("video"))Q="tweet_video"}let Y={additional_owners:Z.additional_owners,media_type:Z.media_type,total_bytes:W.length,media_category:Q},J=(await this.post("media/upload/initialize",Y)).data.id,z=Math.ceil(W.length/$),G=new Uint8Array(W);for(let B=0;B<z;B++){let j=B*$,D=Math.min(j+$,W.length),x=G.slice(j,D),V=Buffer.from(x),Q1={segment_index:B,media:V};await this.post(`media/upload/${J}/append`,Q1,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${J}/finalize`)).data.processing_info)await this.waitForMediaProcessing(J);return J}async waitForMediaProcessing(W){var Z;let Q=(await this.get("media/upload",{command:"STATUS",media_id:W})).data.processing_info;if(!Q)return;switch(Q.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(Z=Q.error)===null||Z===void 0?void 0:Z.message}`);case"pending":case"in_progress":{let Y=Q===null||Q===void 0?void 0:Q.check_after_secs;if(Y&&Y>0)await new Promise((K)=>setTimeout(K,Y*1000)),await this.waitForMediaProcessing(W)}}}createMediaMetadata(W,Z){return this.post("media/metadata",{id:W,metadata:Z})}reply(W,Z,$={}){var Q;let Y={in_reply_to_tweet_id:Z,...(Q=$.reply)!==null&&Q!==void 0?Q:{}};return this.post("tweets",{text:W,...$,reply:Y})}quote(W,Z,$={}){return this.tweet(W,{...$,quote_tweet_id:Z})}async tweetThread(W){var Z,$;let Q=[];for(let Y of W){let K=Q.length?Q[Q.length-1]:null,J={...typeof Y==="string"?{text:Y}:Y},z=K?K.data.id:(Z=J.reply)===null||Z===void 0?void 0:Z.in_reply_to_tweet_id,G=($=J.text)!==null&&$!==void 0?$:"";if(z)Q.push(await this.reply(G,z,J));else Q.push(await this.tweet(G,J))}return Q}deleteTweet(W){return this.delete("tweets/:id",void 0,{params:{id:W}})}async bookmark(W){let Z=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:W},{params:{id:Z.data.id}})}async deleteBookmark(W){let Z=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:Z.data.id,tweet_id:W}})}follow(W,Z){return this.post("users/:id/following",{target_user_id:Z},{params:{id:W}})}unfollow(W,Z){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}block(W,Z){return this.post("users/:id/blocking",{target_user_id:Z},{params:{id:W}})}unblock(W,Z){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}mute(W,Z){return this.post("users/:id/muting",{target_user_id:Z},{params:{id:W}})}unmute(W,Z){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:Z}})}createList(W){return this.post("lists",W)}updateList(W,Z={}){return this.put("lists/:id",Z,{params:{id:W}})}removeList(W){return this.delete("lists/:id",void 0,{params:{id:W}})}addListMember(W,Z){return this.post("lists/:id/members",{user_id:Z},{params:{id:W}})}removeListMember(W,Z){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:W,user_id:Z}})}subscribeToList(W,Z){return this.post("users/:id/followed_lists",{list_id:Z},{params:{id:W}})}unsubscribeOfList(W,Z){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:W,list_id:Z}})}pinList(W,Z){return this.post("users/:id/pinned_lists",{list_id:Z},{params:{id:W}})}unpinList(W,Z){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:W,list_id:Z}})}sendDmInConversation(W,Z){return this.post("dm_conversations/:dm_conversation_id/messages",Z,{params:{dm_conversation_id:W}})}sendDmToParticipant(W,Z){return this.post("dm_conversations/with/:participant_id/messages",Z,{params:{participant_id:W}})}createDmConversation(W){return this.post("dm_conversations",W)}}class BW extends _1{constructor(){super(...arguments);this._prefix=F1}get readWrite(){return this}}var jW=BW;class FW extends V1{constructor(){super(...arguments);this._prefix=t}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new jW(this)}}var MW=FW;class m1 extends W1{get v1(){if(this._v1)return this._v1;return this._v1=new U1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new O1(this)}async currentUser(W=!1){return await this.getCurrentUserObject(W)}async currentUserV2(W=!1){return await this.getCurrentUserV2Object(W)}search(W,Z){return this.v2.search(W,Z)}async generateAuthLink(W="oob",{authAccessType:Z,linkMode:$="authenticate",forceLogin:Q,screenName:Y}={}){let K=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:W,x_auth_access_type:Z}),J=`https://api.x.com/oauth/${$}?oauth_token=${encodeURIComponent(K.oauth_token)}`;if(Q!==void 0)J+=`&force_login=${encodeURIComponent(Q)}`;if(Y!==void 0)J+=`&screen_name=${encodeURIComponent(Y)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:J,oauthResult:K});return{url:J,...K}}async login(W){let Z=this.getActiveTokens();if(Z.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let $=await this.post("https://api.x.com/oauth/access_token",{oauth_token:Z.accessToken,oauth_verifier:W}),Q=new this.constructor({appKey:Z.appKey,appSecret:Z.appSecret,accessToken:$.oauth_token,accessSecret:$.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:$.oauth_token,accessSecret:$.oauth_token_secret,userId:$.user_id,screenName:$.screen_name,client:Q}}async appLogin(){let W=this.getActiveTokens();if(W.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let $=await new this.constructor({username:W.appKey,password:W.appSecret},this._requestMaker.clientSettings).post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor($.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(W,Z={}){var $,Q;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 Y=($=Z.state)!==null&&$!==void 0?$:B1.generateRandomString(32),K=B1.getCodeVerifier(),J=B1.getCodeChallengeFromVerifier(K),z=(Q=Z.scope)!==null&&Q!==void 0?Q:"",G=Array.isArray(z)?z.join(" "):z,X=new URL("https://x.com/i/oauth2/authorize"),B={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:W,state:Y,code_challenge:J,code_challenge_method:"s256",scope:G};v.addQueryParamsToUrl(X,B);let j={url:X.toString(),state:Y,codeVerifier:K,codeChallenge:J};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:j,redirectUri:W});return j}async loginWithOAuth2({code:W,codeVerifier:Z,redirectUri:$}){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 Q=await this.post("https://api.x.com/2/oauth2/token",{code:W,code_verifier:Z,redirect_uri:$,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(Q)}async refreshOAuth2Token(W){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 Z=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:W,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(Z)}async revokeOAuth2Token(W,Z="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:W,token_type_hint:Z})}parseOAuth2AccessTokenResult(W){let Z=new this.constructor(W.access_token,this._requestMaker.clientSettings),$=W.scope.split(" ").filter((Q)=>Q);return{client:Z,expiresIn:W.expires_in,accessToken:W.access_token,scope:$,refreshToken:W.refresh_token}}}class c1 extends m1{get v1(){if(this._v1)return this._v1;return this._v1=new x1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new V1(this)}get readOnly(){return this}}class M4 extends I{constructor(){super(...arguments);this._prefix=M1}}class L4 extends M4{constructor(){super(...arguments);this._prefix=M1}get readOnly(){return this}}class D4 extends I{constructor(){super(...arguments);this._prefix=L1}}class H4 extends D4{constructor(){super(...arguments);this._prefix=L1}get readOnly(){return this}}class LW extends H4{constructor(){super(...arguments);this._prefix=L1}get readWrite(){return this}}var DW=LW;class HW extends L4{constructor(){super(...arguments);this._prefix=M1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new DW(this)}}var NW=HW;class N4 extends c1{get v1(){if(this._v1)return this._v1;return this._v1=new X4(this)}get v2(){if(this._v2)return this._v2;return this._v2=new MW(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new NW(this)}static getErrors(W){var Z;if(typeof W!=="object")return[];if(!("data"in W))return[];return(Z=W.data.errors)!==null&&Z!==void 0?Z:[]}static getProfileImageInSize(W,Z){let $=W.split("/").pop(),Q=["normal","bigger","mini"],Y=W;for(let J of Q)if($.includes(`_${J}`)){Y=W.replace(`_${J}`,"");break}if(Z==="original")return Y;let K=Y.lastIndexOf(".");if(K!==-1){let J=Y.slice(K+1);return Y.slice(0,K)+"_"+Z+"."+J}else return Y+"_"+Z}}var E5={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class UW extends i{config;client;constructor(W={}){super();this.config={...E5,...W},this.client=new N4({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${w()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"XOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>w()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!Z)throw Error("XOAuthProvider needs the state and PKCE challenge gemi passes.");if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("XOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL("https://x.com/i/oauth2/authorize"),Q={response_type:"code",client_id:W.clientId,redirect_uri:W.redirectUri,state:Z.state,code_challenge:Z.codeChallenge,code_challenge_method:Z.codeChallengeMethod,scope:this.config.scope.join(" ")};for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new R("missing_code");if(!Z?.codeVerifier)throw new R("invalid_state");let Q=this.config.resolve?await this.clientFor(W):this.staticClient();if(!Q)throw new R("unknown_provider");let Y=this.config.resolve?new N4({clientId:Q.clientId,clientSecret:Q.clientSecret}):this.client,K;try{K=await Y.loginWithOAuth2({code:$,codeVerifier:Z.codeVerifier,redirectUri:Q.redirectUri})}catch(j){throw console.error("X OAuth error: token exchange failed",j),new R("exchange_failed")}let{data:J}=await K.client.v2.me({"user.fields":["name","username","entities"]}),{name:z,email:G,id:X="",username:B}=J??{};return{name:z,email:G,username:B,providerId:X}}}var SW=["instagram_business_basic"],l={authorizeUrl:"https://www.instagram.com/oauth/authorize",tokenUrl:"https://api.instagram.com/oauth/access_token",graphUrl:"https://graph.instagram.com"};class m extends Error{status;type;code;constructor(W,Z,$,Q,Y){super(W,Y);this.status=Z;this.type=$;this.code=Q;this.name="InstagramApiError"}}async function U4(W){let Z=new URLSearchParams({client_id:W.clientId,client_secret:W.clientSecret,grant_type:"authorization_code",redirect_uri:W.redirectUri,code:W.code.replace(/#_$/,"")}),$=await S4(W.tokenUrl??l.tokenUrl,"code exchange",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Z.toString()}),Q=Array.isArray($.data)?$.data[0]:$,Y=Q?.access_token;if(typeof Y!=="string"||Y==="")throw new m("Instagram's code exchange answered without an access token.",200);let K=Q?.permissions;return{accessToken:Y,userId:a0(Q?.user_id),permissions:Array.isArray(K)?K.map(String):typeof K==="string"?K.split(/[\s,]+/).filter(Boolean):null}}async function RW(W){let Z=new URL("/access_token",W.graphUrl??l.graphUrl);return Z.searchParams.set("grant_type","ig_exchange_token"),Z.searchParams.set("client_secret",W.clientSecret),Z.searchParams.set("access_token",W.accessToken),_W(await S4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function OW(W){let Z=new URL("/refresh_access_token",W.graphUrl??l.graphUrl);return Z.searchParams.set("grant_type","ig_refresh_token"),Z.searchParams.set("access_token",W.accessToken),_W(await S4(Z.toString(),"token refresh",{method:"GET"}))}async function x4(W){let Z=W.graphApiVersion?`/${W.graphApiVersion.replace(/^\/+|\/+$/g,"")}`:"",$=new URL(`${Z}/me`,W.graphUrl??l.graphUrl);$.searchParams.set("fields",(W.fields??["user_id","username","name","account_type","profile_picture_url"]).join(",")),$.searchParams.set("access_token",W.accessToken);let Q=await S4($.toString(),"profile request",{method:"GET"}),Y=Array.isArray(Q.data)?Q.data[0]:Q,K=a0(Y?.user_id);if(!K)throw new m("Instagram's /me answered without a user_id.",200);let J={user_id:K},z=a0(Y?.id);if(z)J.id=z;for(let G of["username","name","account_type","profile_picture_url"]){let X=Y?.[G];if(typeof X==="string"&&X!=="")J[G]=X}return J}function _W(W){if(typeof W.access_token!=="string"||W.access_token==="")throw new m("Instagram answered without an access token.",200);let Z=Number(W.expires_in);return{accessToken:W.access_token,tokenType:typeof W.token_type==="string"?W.token_type:null,expiresIn:Number.isFinite(Z)&&Z>0?Z:null}}async function S4(W,Z,$){let Q;try{Q=await fetch(W,{...$,redirect:"error"})}catch(K){throw new m(`Instagram's ${Z} failed to reach Instagram.`,void 0,void 0,void 0,{cause:K})}let Y=t0(await Q.text().catch(()=>""));if(!Q.ok){let K=Y.error??{},J=xW(Y.error_type)??xW(K.type),z=Number(Y.code??K.code);throw new m(`Instagram refused the ${Z} (HTTP ${Q.status}${J?`, ${J}`:""}${Number.isFinite(z)?` ${z}`:""}).`,Q.status,J,Number.isFinite(z)?z:void 0)}return Y}function t0(W){try{let Z=JSON.parse(W.replace(/("(?:user_id|id)"\s*:\s*)(-?\d+)(?=\s*[,}\]])/g,'$1"$2"'));return Z&&typeof Z==="object"?Z:{}}catch{return{}}}function a0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function xW(W){return typeof W==="string"&&W!==""?W:void 0}class VW extends i{createUsersWithoutEmail=!0;linkByEmail=!1;config;constructor(W={}){super();this.config={clientId:process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:SW,redirectPath:"/auth/oauth/instagram/callback",authorizationParams:{},...W}}redirectUri(){return`${w()??""}${this.config.redirectPath}`}clientFor(W){return a(this,W,{name:"InstagramOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>w()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("InstagramOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(this.config.authorizeUrl??l.authorizeUrl),Q={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,response_type:"code",scope:this.config.scopes.join(",")};if(Z)Q.state=Z.state;for(let[Y,K]of Object.entries(Q))$.searchParams.set(Y,K);return $.toString()}async onCallback(W){let Z=W.search.get("code");if(!Z)throw new R("missing_code");let $=this.config.resolve?await this.clientFor(W):this.staticClient();if(!$)throw new R("unknown_provider");let Q;try{let Y=await U4({code:Z,clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.redirectUri,tokenUrl:this.config.tokenUrl});Q=await x4({accessToken:Y.accessToken,graphUrl:this.config.graphUrl,graphApiVersion:this.config.graphApiVersion,fields:["user_id","username","name"]})}catch(Y){if(Y instanceof m)throw console.error(`Instagram OAuth error: ${Y.message}`),new R("exchange_failed");throw Y}return{providerId:Q.user_id,username:Q.username,name:Q.name||Q.username}}}import{createHmac as g5,timingSafeEqual as m5}from"crypto";class c extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function c5(W,Z,$={}){if(!Z)throw Error("parseMetaSignedRequest needs the app secret.");if(typeof W!=="string")throw new c("malformed","No signed_request was given.");let Q=W.indexOf(".");if(Q<=0||Q===W.length-1||W.indexOf(".",Q+1)!==-1)throw new c("malformed","A signed_request is <signature>.<payload>.");let Y=W.slice(0,Q),K=W.slice(Q+1);if(!/^[A-Za-z0-9_-]+={0,2}$/.test(Y)||!/^[A-Za-z0-9_-]+={0,2}$/.test(K))throw new c("malformed","A signed_request is base64url.");let J=g5("sha256",Z).update(K).digest(),z=Buffer.from(Y,"base64url");if(z.length!==J.length||!m5(z,J))throw new c("bad_signature","The signed_request's signature does not match the app secret.");let G;try{let D=Buffer.from(K,"base64url").toString("utf8").replace(/("user_id"\s*:\s*)(-?\d+)(?=\s*[,}])/g,'$1"$2"');G=JSON.parse(D)}catch{throw new c("malformed","The signed_request's payload is not JSON.")}if(!G||typeof G!=="object")throw new c("malformed","The signed_request's payload is not an object.");if(String(G.algorithm??"").toUpperCase()!=="HMAC-SHA256")throw new c("unsupported_algorithm","Only HMAC-SHA256 signed_requests are accepted.");let X=Math.floor(($.now??Date.now())/1000),B=Number(G.expires);if(Number.isFinite(B)&&B>0&&B<X)throw new c("expired","The signed_request has expired.");let j=G.user_id;if((typeof j!=="string"||j==="")&&typeof j!=="number")throw new c("missing_user","The signed_request names no user.");return{...G,algorithm:String(G.algorithm),user_id:String(j)}}var u5=86400000;class O4 extends b{instagram;constructor(W={}){let Z={authorizeUrl:W.authorizeUrl??l.authorizeUrl,tokenUrl:W.tokenUrl??l.tokenUrl,graphUrl:W.graphUrl??l.graphUrl,graphApiVersion:W.graphApiVersion};super({authorizeUrl:Z.authorizeUrl,tokenUrl:Z.tokenUrl,clientId:W.clientId??process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:W.scopes??["instagram_business_basic","instagram_business_content_publish"],scopeSeparator:",",pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,apiBaseUrl:Z.graphUrl,refreshLeewaySeconds:W.refreshLeewaySeconds??864000,multiple:W.multiple??!1,tokenPlacement:"query",isTokenRejected:r0,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<u5){if($.reason==="rejected")throw new U("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let Q=await R4("refresh_failed",()=>OW({accessToken:$.accessToken,graphUrl:Z.graphUrl}));return{accessToken:Q.accessToken,refreshToken:null,tokenType:Q.tokenType,expiresAt:Q.expiresIn===null?null:new Date(Date.now()+Q.expiresIn*1000),scopes:$.scopes,providerAccountId:$.providerAccountId}}});this.instagram=Z}async exchangeCode(W){let Z=await R4("exchange_failed",()=>U4({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await R4("exchange_failed",()=>RW({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),Q=await R4("exchange_failed",()=>x4({accessToken:$.accessToken,graphUrl:this.instagram.graphUrl,graphApiVersion:this.instagram.graphApiVersion}));return{accessToken:$.accessToken,refreshToken:null,tokenType:$.tokenType,expiresAt:$.expiresIn===null?null:new Date(Date.now()+$.expiresIn*1000),scopes:Z.permissions??this.config.scopes,providerAccountId:Q.user_id,profile:{...Q}}}refresh(){return Promise.reject(new U("refresh_failed","Instagram connections renew the access token itself; call connection.refresh()."))}}async function r0(W){if(W.status===401)return!0;if(W.status!==400)return!1;let Z=await W.clone().json().catch(()=>null);return Number(Z?.error?.code)===190}async function R4(W,Z){try{return await Z()}catch($){if($ instanceof m)throw new U(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}async function S(W,Z,$){let Q;try{Q=await $()}catch(K){if(K instanceof U)throw K;throw new U(Z,`The ${W} request failed.`,{cause:K})}let Y=await Q.json().catch(()=>null);if(!Q.ok||Y===null||typeof Y!=="object")throw new U(Z,`The ${W} request was refused (HTTP ${Q.status}).`,{status:Q.ok?502:Q.status});return Y}function $1(W,Z,$={}){return fetch(W,{headers:{...$,Authorization:`Bearer ${Z}`,Accept:"application/json"},redirect:"error"})}function f(W,Z,$){if(W.connectionProvider()!==Z)throw TypeError(`${$} takes a connection to this provider; "${W.provider}" is configured with another one.`)}function M(W){return typeof W==="string"&&W!==""?W:null}var y=M;function u(W){return new U("exchange_failed",`${W} did not say which account was connected.`,{status:502})}var kW=["pages_show_list","pages_read_engagement","pages_manage_posts"];class CW extends b{configId;graphApiVersion;constructor(W={}){let Z=W.graphApiVersion?.replace(/^\/+|\/+$/g,""),$=Z?`/${Z}`:"",Q=W.apiBaseUrl??"https://graph.facebook.com";super({authorizeUrl:W.authorizeUrl??`${W.dialogUrl??"https://www.facebook.com"}${$}/dialog/oauth`,tokenUrl:W.tokenUrl??`${Q}${$}/oauth/access_token`,revokeUrl:W.revokeUrl??`${Q}${$}/me/permissions`,apiBaseUrl:Q,clientId:W.clientId??process.env.FACEBOOK_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.FACEBOOK_CLIENT_SECRET??"",scopes:W.scopes??kW,scopeSeparator:",",pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??60,multiple:W.multiple??!1,tokenPlacement:"query",revokeTokenHint:"access_token",isTokenRejected:r0,refreshStrategy:async(Y)=>{if(Y.reason==="rejected")throw new U("refresh_failed","Facebook refused the access token (OAuthException 190).",{status:401});return null}});this.configId=W.configId??(process.env.FACEBOOK_CONFIG_ID||void 0),this.graphApiVersion=Z||void 0}authorizationUrl(W){let Z=new URL(super.authorizationUrl(W));if(this.configId)Z.searchParams.delete("scope"),Z.searchParams.set("config_id",this.configId);return Z.toString()}async exchangeCode(W){let Z=await this.tokenCall({client_id:this.config.clientId,client_secret:this.config.clientSecret,redirect_uri:W.redirectUri,code:W.code}),$=await this.tokenCall({grant_type:"fb_exchange_token",client_id:this.config.clientId,client_secret:this.config.clientSecret,fb_exchange_token:Z.accessToken}),Q=$.accessToken,Y=await S("Facebook /me","exchange_failed",()=>fetch(this.graphUrl(this.path("/me",{fields:"id,name,picture{url}"}),Q),{redirect:"error"})),K=y(Y.id);if(!K)throw u("Facebook");let J=await S("Facebook /me/permissions","exchange_failed",()=>fetch(this.graphUrl(this.path("/me/permissions"),Q),{redirect:"error"})),z=(Array.isArray(J.data)?J.data:[]).filter((B)=>B.status==="granted"&&typeof B.permission==="string").map((B)=>B.permission),G=await this.listPages((B)=>fetch(this.graphUrl(B,Q),{redirect:"error"}),"exchange_failed"),X={id:K,name:M(Y.name),username:null,avatarUrl:e0(Y.picture),pages:G.map(({accessToken:B,...j})=>j)};return{accessToken:Q,refreshToken:null,tokenType:$.tokenType,expiresAt:$.expiresIn===null?null:new Date(Date.now()+$.expiresIn*1000),scopes:z.length>0?z:this.config.scopes,providerAccountId:K,profile:{...X}}}refresh(){return Promise.reject(new U("refresh_failed","Facebook issues no refresh token; reconnect the account."))}async revoke(W){let Z=new URL(this.config.revokeUrl);Z.searchParams.set("access_token",W);let $;try{$=await fetch(Z,{method:"DELETE",redirect:"error"})}catch(Q){throw new U("revoke_failed","The revocation request failed.",{cause:Q})}if(await $.body?.cancel().catch(()=>{}),!$.ok)throw new U("revoke_failed",`Facebook refused the revocation (HTTP ${$.status}).`,{status:$.status})}async profile(W){f(W,this,"FacebookConnectionProvider.profile()");let Z=await S("Facebook /me","request_failed",()=>W.fetch(this.path("/me",{fields:"id,name,picture{url}"}))),$=y(Z.id);if(!$)throw u("Facebook");let Q=await this.pages(W);return{id:$,name:M(Z.name),username:null,avatarUrl:e0(Z.picture),pages:Q.map((Y)=>Y.toJSON())}}async pages(W){return f(W,this,"FacebookConnectionProvider.pages()"),(await this.listPages(($)=>W.fetch($),"request_failed")).map(($)=>new W6(W,$))}path(W,Z={}){let $=this.graphApiVersion?`/${this.graphApiVersion}`:"",Q=new URL(`${$}${W}`,this.config.apiBaseUrl);for(let[Y,K]of Object.entries(Z))Q.searchParams.set(Y,K);return`${Q.pathname}${Q.search}`}graphUrl(W,Z){let $=new URL(W,this.config.apiBaseUrl);if($.origin!==new URL(this.config.apiBaseUrl).origin)throw new U("forbidden_url","Facebook paged to another origin.");return $.searchParams.set("access_token",Z),$}async listPages(W,Z){let $=[],Q=this.path("/me/accounts",{fields:"id,name,category,tasks,access_token,picture{url}",limit:"100"});for(let Y=0;Q!==null&&Y<20;Y++){let K=Q,J=await S("Facebook /me/accounts",Z,()=>W(K));for(let G of Array.isArray(J.data)?J.data:[]){let X=y(G.id);if(!X)continue;$.push({id:X,name:M(G.name),category:M(G.category),tasks:Array.isArray(G.tasks)?G.tasks.filter((B)=>typeof B==="string"):[],avatarUrl:e0(G.picture),accessToken:M(G.access_token)})}let z=J.paging??{};Q=typeof z.next==="string"?z.next:null}return $}async tokenCall(W){let Z=new URL(this.config.tokenUrl);for(let[K,J]of Object.entries(W))Z.searchParams.set(K,J);let $=await S("Facebook token","exchange_failed",()=>fetch(Z,{headers:{Accept:"application/json"},redirect:"error"})),Q=M($.access_token);if(!Q)throw new U("exchange_failed","Facebook answered the code exchange without a token.",{status:502});let Y=Number($.expires_in);return{accessToken:Q,tokenType:M($.token_type),expiresIn:Number.isFinite(Y)&&Y>0?Y:null}}}class W6{connection;id;name;category;tasks;avatarUrl;#W;constructor(W,Z){this.connection=W;this.id=Z.id,this.name=Z.name,this.category=Z.category,this.tasks=Z.tasks,this.avatarUrl=Z.avatarUrl,this.#W=Z.accessToken}get canPost(){return this.tasks.includes("CREATE_CONTENT")}accessToken(){if(this.#W===null)throw new U("request_failed",`Facebook gave no Page token for Page ${this.id}.`);return this.#W}fetch(W,Z={}){return this.connection.fetchWithToken(this.accessToken(),W,Z)}toJSON(){return{id:this.id,name:this.name,category:this.category,tasks:[...this.tasks],avatarUrl:this.avatarUrl}}[Symbol.for("nodejs.util.inspect.custom")](){return{FacebookPage:this.toJSON()}}}function e0(W){let Z=W?.data;return M(Z?.url)}var PW=["openid","profile","w_member_social"],p5=["w_organization_social","r_organization_social"];class bW extends b{apiVersion;constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://www.linkedin.com/oauth/v2/authorization",tokenUrl:W.tokenUrl??"https://www.linkedin.com/oauth/v2/accessToken",revokeUrl:W.revokeUrl,apiBaseUrl:W.apiBaseUrl??"https://api.linkedin.com",clientId:W.clientId??process.env.LINKEDIN_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.LINKEDIN_CLIENT_SECRET??"",scopes:W.scopes??PW,pkce:!1,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??86400,multiple:W.multiple??!1});this.apiVersion=W.apiVersion??"202610"}async exchangeCode(W){let Z=await super.exchangeCode(W),$=TW(await S("LinkedIn userinfo","exchange_failed",()=>$1(this.userInfoUrl(),Z.accessToken)));return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"LinkedInConnectionProvider.profile()"),TW(await S("LinkedIn userinfo","request_failed",()=>W.fetch(this.userInfoUrl())))}async organizations(W){f(W,this,"LinkedInConnectionProvider.organizations()");let Z=new URL("/rest/organizationAcls",this.config.apiBaseUrl);Z.searchParams.set("q","roleAssignee"),Z.searchParams.set("state","APPROVED");let $=await S("LinkedIn organizationAcls","request_failed",()=>W.fetch(Z,{headers:this.restHeaders()})),Q=new Map;for(let J of Array.isArray($.elements)?$.elements:[]){let z=M(J.organization)??M(J.organizationTarget),G=z?.match(/^urn:li:organization:(\d+)$/)?.[1];if(!z||!G||Q.has(G))continue;Q.set(G,{id:G,urn:z,role:M(J.role)??"UNKNOWN",name:null,vanityName:null})}if(Q.size===0)return[];let Y=`/rest/organizations?ids=List(${[...Q.keys()].join(",")})`,K=await W.fetch(Y,{headers:this.restHeaders()});if(K.ok){let J=await K.json().catch(()=>({}));for(let[z,G]of Object.entries(J.results??{})){let X=Q.get(z);if(!X)continue;X.name=M(G.localizedName),X.vanityName=M(G.vanityName)}}else await K.body?.cancel().catch(()=>{});return[...Q.values()]}restHeaders(){return{"LinkedIn-Version":this.apiVersion,"X-Restli-Protocol-Version":"2.0.0"}}userInfoUrl(){return new URL("/v2/userinfo",this.config.apiBaseUrl)}}function TW(W){let Z=y(W.sub);if(!Z)throw u("LinkedIn");let $=M(W.given_name),Q=M(W.family_name);return{id:Z,name:M(W.name)??([$,Q].filter(Boolean).join(" ")||null),username:null,avatarUrl:M(W.picture),authorUrn:`urn:li:person:${Z}`,email:M(W.email)}}var wW=["user.info.basic","video.publish","video.upload"];class vW extends b{constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://www.tiktok.com/v2/auth/authorize/",tokenUrl:W.tokenUrl??"https://open.tiktokapis.com/v2/oauth/token/",revokeUrl:W.revokeUrl??"https://open.tiktokapis.com/v2/oauth/revoke/",apiBaseUrl:W.apiBaseUrl??"https://open.tiktokapis.com",clientId:W.clientKey??W.clientId??process.env.TIKTOK_CLIENT_KEY??"",clientSecret:W.clientSecret??process.env.TIKTOK_CLIENT_SECRET??"",clientIdParam:"client_key",scopes:W.scopes??wW,scopeSeparator:",",pkce:!1,revokeTokenHint:"access_token",authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??300,multiple:W.multiple??!1})}async exchangeCode(W){let Z=await super.exchangeCode(W),$=qW(await S("TikTok user info","exchange_failed",()=>$1(this.userInfoUrl(Z.scopes),Z.accessToken)),"exchange_failed");return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"TikTokConnectionProvider.profile()"),qW(await S("TikTok user info","request_failed",()=>W.fetch(this.userInfoUrl([...W.scopes]))),"request_failed")}userInfoUrl(W){let Z=new URL("/v2/user/info/",this.config.apiBaseUrl),$=["open_id","union_id","avatar_url","display_name"];if(W.includes("user.info.profile"))$.push("username");return Z.searchParams.set("fields",$.join(",")),Z}}function qW(W,Z){let $=W.error??{};if(typeof $.code==="string"&&$.code!=="ok")throw new U(Z,`TikTok refused the user info request (${d5($.code)}).`,{status:400});let Q=(W.data??{}).user,Y=y(Q?.open_id);if(!Q||!Y)throw u("TikTok");return{id:Y,name:M(Q.display_name),username:M(Q.username),avatarUrl:M(Q.avatar_url),unionId:M(Q.union_id)}}function d5(W){return/^[a-z0-9_]{1,64}$/.test(W)?W:"error"}var fW=["https://www.googleapis.com/auth/youtube.upload","https://www.googleapis.com/auth/youtube.readonly"];class yW extends b{constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:W.tokenUrl??"https://oauth2.googleapis.com/token",revokeUrl:W.revokeUrl??"https://oauth2.googleapis.com/revoke",apiBaseUrl:W.apiBaseUrl??"https://www.googleapis.com",clientId:W.clientId??process.env.GOOGLE_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.GOOGLE_CLIENT_SECRET??"",scopes:W.scopes??fW,pkce:!0,authorizationParams:{access_type:"offline",prompt:"consent",include_granted_scopes:"true",...W.authorizationParams},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??300,multiple:W.multiple??!1})}async exchangeCode(W){let Z=await super.exchangeCode(W),$=IW(await S("YouTube channel","exchange_failed",()=>$1(this.channelUrl(),Z.accessToken)));return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"YouTubeConnectionProvider.profile()"),IW(await S("YouTube channel","request_failed",()=>W.fetch(this.channelUrl())))}channelUrl(){let W=new URL("/youtube/v3/channels",this.config.apiBaseUrl);return W.searchParams.set("part","snippet"),W.searchParams.set("mine","true"),W}}function IW(W){let[Z]=Array.isArray(W.items)?W.items:[],$=y(Z?.id);if(!$)throw u("YouTube (the Google account has no channel)");let Q=Z.snippet??{},Y=Q.thumbnails??{},K=Y.high?.url??Y.medium?.url??Y.default?.url;return{id:$,name:M(Q.title),username:M(Q.customUrl),avatarUrl:M(K)}}var hW=["tweet.read","tweet.write","users.read","media.write","offline.access"];class EW extends b{constructor(W={}){super({authorizeUrl:W.authorizeUrl??"https://x.com/i/oauth2/authorize",tokenUrl:W.tokenUrl??"https://api.x.com/2/oauth2/token",revokeUrl:W.revokeUrl??"https://api.x.com/2/oauth2/revoke",apiBaseUrl:W.apiBaseUrl??"https://api.x.com",clientId:W.clientId??process.env.X_CLIENT_ID??"",clientSecret:W.clientSecret??process.env.X_CLIENT_SECRET??process.env.X_SECRET??"",scopes:W.scopes??hW,clientAuth:"basic",pkce:!0,authorizationParams:W.authorizationParams??{},redirectUri:W.redirectUri,refreshLeewaySeconds:W.refreshLeewaySeconds??300,multiple:W.multiple??!1})}async exchangeCode(W){let Z=await super.exchangeCode(W),$=AW(await S("X profile","exchange_failed",()=>$1(this.profileUrl(),Z.accessToken)));return{...Z,providerAccountId:$.id,profile:{...$}}}async profile(W){return f(W,this,"XConnectionProvider.profile()"),AW(await S("X profile","request_failed",()=>W.fetch(this.profileUrl())))}profileUrl(){let W=new URL("/2/users/me",this.config.apiBaseUrl);return W.searchParams.set("user.fields","profile_image_url"),W}}function AW(W){let Z=W.data??{},$=y(Z.id);if(!$)throw u("X");return{id:$,name:M(Z.name),username:M(Z.username),avatarUrl:M(Z.profile_image_url)}}class _ extends Error{code;status;graphCode;graphSubcode;containerId;constructor(W,Z,$={}){super(Z);this.code=W;this.name="InstagramPublishError",this.status=$.status,this.graphCode=$.graphCode,this.graphSubcode=$.graphSubcode,this.containerId=$.containerId}}var q={captionLength:2200,hashtags:30,mentions:20,userTags:20,carouselMin:2,carouselMax:10},gW="instagram_business_content_publish",l5={for(W,Z={}){return new Q6(W,Z)}};class Q6{connection;version;pollIntervalMs;maxPollIntervalMs;timeoutMs;constructor(W,Z={}){this.connection=W;let $=W.connectionProvider();if(!($ instanceof O4))throw TypeError(`Instagram.for() takes an Instagram connection; "${W.provider}" is not an InstagramConnectionProvider.`);let Q=Z.graphApiVersion??$.instagram.graphApiVersion;this.version=Q?`/${Q.replace(/^\/+|\/+$/g,"")}`:"",this.pollIntervalMs=Z.pollIntervalMs??2000,this.maxPollIntervalMs=Z.maxPollIntervalMs??1e4,this.timeoutMs=Z.timeoutMs??300000}async publishImage(W,Z={}){if(u1("imageUrl",W.imageUrl),$6(W.caption),W.altText!==void 0&&typeof W.altText!=="string")T("altText must be a string.");if(W.userTags!==void 0)Q8(W.userTags);let $=this.start(Z),Q=await this.createContainer({image_url:W.imageUrl,caption:W.caption,alt_text:W.altText,user_tags:W.userTags?JSON.stringify(W.userTags):void 0,location_id:W.locationId},$);return this.publishContainer(Q,!1,$)}async publishCarousel(W,Z={}){let $=W.items;if(!Array.isArray($)||$.length<q.carouselMin||$.length>q.carouselMax)T(`A carousel takes ${q.carouselMin} to ${q.carouselMax} items.`);$.forEach((z,G)=>pW(`items[${G}]`,z)),$6(W.caption);let Q=this.start(Z),Y=[];for(let z of $)Y.push(await this.createContainer(z.videoUrl!==void 0?{media_type:"VIDEO",video_url:z.videoUrl,is_carousel_item:"true"}:{image_url:z.imageUrl,is_carousel_item:"true"},Q));for(let[z,G]of $.entries())if(G.videoUrl!==void 0)await this.waitUntilFinished(Y[z],Q);let K=$.some((z)=>z.videoUrl!==void 0),J=await this.createContainer({media_type:"CAROUSEL",children:Y.join(","),caption:W.caption},Q);return this.publishContainer(J,K,Q)}async publishReel(W,Z={}){if(u1("videoUrl",W.videoUrl),W.coverUrl!==void 0)u1("coverUrl",W.coverUrl);if($6(W.caption),W.thumbOffset!==void 0&&!(Number.isInteger(W.thumbOffset)&&W.thumbOffset>=0))T("thumbOffset must be a whole number of milliseconds, 0 or more.");let $=this.start(Z),Q=await this.createContainer({media_type:"REELS",video_url:W.videoUrl,caption:W.caption,cover_url:W.coverUrl,share_to_feed:W.shareToFeed===void 0?void 0:String(W.shareToFeed),thumb_offset:W.thumbOffset===void 0?void 0:String(W.thumbOffset)},$);return this.publishContainer(Q,!0,$)}async publishStory(W,Z={}){pW("story",W);let $=this.start(Z),Q=W.videoUrl!==void 0,Y=await this.createContainer(Q?{media_type:"STORIES",video_url:W.videoUrl}:{media_type:"STORIES",image_url:W.imageUrl},$);return this.publishContainer(Y,Q,$)}async publishingLimit(W={}){let Z=this.start(W),$=await this.call("publishing limit request",`/${this.accountId()}/content_publishing_limit?fields=quota_usage,config`,void 0,Z),Q=Array.isArray($.data)?$.data[0]:$,Y=Q?.config??{},K=Z6(Q?.quota_usage,0),J=Z6(Y.quota_total,100);return{quotaUsage:K,quotaTotal:J,quotaDurationSeconds:Z6(Y.quota_duration,86400),remaining:Math.max(0,J-K)}}async containerStatus(W,Z={}){return this.readStatus(W,this.start(Z))}start(W){if(W.signal?.throwIfAborted(),!this.connection.hasScopes(gW))throw new _("permission_denied",`The Instagram connection was not granted ${gW}; connect it again with that scope.`);return{signal:W.signal,deadline:Date.now()+(W.timeoutMs??this.timeoutMs)}}accountId(){let W=this.connection.providerAccountId;if(!W)throw new _("invalid_input","The Instagram connection has no account id (providerAccountId).");return W}async createContainer(W,Z){let $=await this.call("media container request",`/${this.accountId()}/media`,W,Z);return cW($,"media container request")}async publishContainer(W,Z,$){try{if(Z)await this.waitUntilFinished(W,$);let Q=await this.publishOnce(W,Z,$);return{mediaId:Q,permalink:await this.permalink(Q,$)}}catch(Q){throw Q instanceof _?Z8(Q,W):Q}}async publishOnce(W,Z,$){try{return await this.mediaPublish(W,$)}catch(Q){if(!(Q instanceof _))throw Q;if(Q.code==="transient"){let{statusCode:Y}=await this.readStatus(W,$);if(Y==="PUBLISHED")throw new _("unconfirmed","Instagram's media_publish failed, but the container reads PUBLISHED: the post is probably live. Do not publish it again.",{status:Q.status,graphCode:Q.graphCode,graphSubcode:Q.graphSubcode});if(Y!=="FINISHED")throw Q;return this.mediaPublish(W,$)}if(W8(Q)&&!Z)return await this.waitUntilFinished(W,$),this.mediaPublish(W,$);throw Q}}async mediaPublish(W,Z){let $=await this.call("media_publish request",`/${this.accountId()}/media_publish`,{creation_id:W},Z,{retry:!1});return cW($,"media_publish request")}async permalink(W,Z){try{let $=await this.call("permalink request",`/${W}?fields=permalink`,void 0,Z,{retry:!1});return typeof $.permalink==="string"?$.permalink:void 0}catch{return}}async readStatus(W,Z){if(!/^\d+$/.test(W))T("A container id is a string of digits.");let $=await this.call("container status request",`/${W}?fields=status_code,status`,void 0,Z),Q=$.status_code;if(typeof Q!=="string"||!n5.has(Q))throw new _("graph_error","Instagram's container status answered without a known status_code.",{status:200,containerId:W});let Y={id:W,statusCode:Q};if(typeof $.status==="string"&&$.status!=="")Y.status=nW($.status);return Y}async waitUntilFinished(W,Z){let $=this.pollIntervalMs;for(;;){let{statusCode:Q,status:Y}=await this.readStatus(W,Z);if(Q==="FINISHED")return;if(Q==="PUBLISHED")throw new _("invalid_input","That media container has been published already.",{containerId:W});if(Q==="ERROR")throw new _("invalid_media",`Instagram could not process the media${Y?` (${Y})`:""}.`,{containerId:W});if(Q==="EXPIRED")throw new _("expired","The media container expired before it was published.",{containerId:W});let K=Z.deadline-Date.now();if(K<=0)throw new _("timeout","Instagram had not finished processing the media in time; the container is still processing.",{containerId:W});await $8(Math.min($,K),Z.signal),$=Math.min($*1.5,this.maxPollIntervalMs)}}async call(W,Z,$,Q,{retry:Y=!0}={}){try{return await this.callOnce(W,Z,$,Q)}catch(K){if(!Y||!(K instanceof _)||K.code!=="transient")throw K;return this.callOnce(W,Z,$,Q)}}async callOnce(W,Z,$,Q){Q.signal?.throwIfAborted();let Y={method:$?"POST":"GET",signal:Q.signal};if($){let z=new URLSearchParams;for(let[G,X]of Object.entries($))if(X!==void 0)z.set(G,X);Y.body=z}let K;try{K=await this.connection.fetch(`${this.version}${Z}`,Y)}catch(z){if(Q.signal?.aborted)throw Q.signal.reason;if(z instanceof TypeError)throw new _("transient",`Instagram's ${W} failed to reach Instagram.`);throw z}let J=t0(await K.text().catch(()=>""));if(K.ok)return J;throw e5(W,K.status,J)}}var n5=new Set(["EXPIRED","ERROR","FINISHED","IN_PROGRESS","PUBLISHED"]),i5=new Set([4,17,32,613,80002]),s5=new Set([3,10]),o5=new Set([9004,352,36000,36001,36002,36003,36004]),a5=new Set([2207004,2207005,2207006,2207009,2207023,2207026,2207028,2207052]),t5=new Set([102,190,463,467]),r5=new Set([2207001,2207003,2207053]),mW={code:9007,subcode:2207027};function e5(W,Z,$){let Q=$.error??{},Y=uW(Q.code),K=uW(Q.error_subcode),J=typeof Q.type==="string"&&Q.type!==""?Q.type:void 0,z=typeof Q.message==="string"&&Q.message!==""?`: ${nW(Q.message)}`:"",G=[Y,K].filter((j)=>j!==void 0).join("/"),X=`Instagram refused the ${W} (HTTP ${Z}${J?`, ${J}`:""}${G?` ${G}`:""})${z}`,B="graph_error";if(K===2207042)B="quota_exceeded";else if(K===2207010)B="invalid_input";else if(Y!==void 0&&i5.has(Y))B="rate_limited";else if(Y!==void 0&&t5.has(Y))B="reconnect_required";else if(Y!==void 0&&(s5.has(Y)||Y>=200&&Y<=299))B="permission_denied";else if(Y!==void 0&&o5.has(Y)||K!==void 0&&a5.has(K))B="invalid_media";else if(Q.is_transient===!0||Y===1||Y===2||K!==void 0&&r5.has(K)||Z>=500||Z===429)B=Z===429?"rate_limited":"transient";return new _(B,X,{status:Z,graphCode:Y,graphSubcode:K})}function W8(W){return W.graphCode===mW.code||W.graphSubcode===mW.subcode}function Z8(W,Z){if(W.containerId)return W;return new _(W.code,W.message,{status:W.status,graphCode:W.graphCode,graphSubcode:W.graphSubcode,containerId:Z})}function nW(W){return W.replace(/access_token=[^&\s"']*/gi,"access_token=[redacted]").replace(/\b(?:IG|EAA)[A-Za-z0-9_-]{20,}/g,"[redacted]").slice(0,500)}function cW(W,Z){let $=W.id;if(typeof $==="string"&&$!=="")return $;if(typeof $==="number"&&Number.isSafeInteger($))return String($);throw new _("graph_error",`Instagram's ${Z} answered without an id.`,{status:200})}function uW(W){let Z=Number(W);return W!==void 0&&W!==null&&Number.isFinite(Z)?Z:void 0}function Z6(W,Z){let $=Number(W);return W!==void 0&&W!==null&&Number.isFinite($)?$:Z}function $8(W,Z){return new Promise(($,Q)=>{if(Z?.aborted)return Q(Z.reason);let Y=()=>{clearTimeout(K),Q(Z?.reason)},K=setTimeout(()=>{Z?.removeEventListener("abort",Y),$()},W);Z?.addEventListener("abort",Y,{once:!0})})}function T(W){throw new _("invalid_input",W)}function $6(W){if(W===void 0)return;if(typeof W!=="string")T("caption must be a string.");if([...W].length>q.captionLength)T(`A caption takes at most ${q.captionLength} characters.`);if((W.match(/#[\p{L}\p{N}_]+/gu)??[]).length>q.hashtags)T(`A caption takes at most ${q.hashtags} hashtags.`);if((W.match(/(?<![\p{L}\p{N}_.@])@[\p{L}\p{N}_.]+/gu)??[]).length>q.mentions)T(`A caption takes at most ${q.mentions} @mentions.`)}function Q8(W){if(!Array.isArray(W)||W.length>q.userTags)T(`userTags takes at most ${q.userTags} tags.`);for(let Z of W){let $=(Q)=>typeof Q==="number"&&Q>=0&&Q<=1;if(typeof Z?.username!=="string"||Z.username===""||!$(Z.x)||!$(Z.y))T("Each user tag needs a username, and x and y between 0 and 1.")}}function pW(W,Z){let $=Z?.imageUrl!==void 0,Q=Z?.videoUrl!==void 0;if($===Q)T(`${W} takes exactly one of imageUrl and videoUrl.`);if($)u1(`${W}.imageUrl`,Z.imageUrl);else u1(`${W}.videoUrl`,Z.videoUrl)}function u1(W,Z){let $;try{$=new URL(Z)}catch{T(`${W} is not an absolute URL.`)}if($.protocol!=="https:")T(`${W} must be an https URL: Instagram fetches the media from it.`);let Q=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Y=dW(Q);if(Y?lW(Y)!==null:!Q.includes(".")||/(^|\.)(localhost|local|internal)$/.test(Q))T(`${W} must be a public URL: Instagram fetches the media from it.`)}class Y6{describe;rollout;when;serverOnly;salt;constructor(W={}){if(W.rollout!==void 0){let{rollout:Z}=W;if(!Number.isFinite(Z)||Z<0||Z>100)throw Error(`A feature's \`rollout\` must be a number between 0 and 100, received ${String(Z)}.`)}this.describe=W.describe,this.rollout=W.rollout,this.when=W.when,this.serverOnly=W.serverOnly??!1,this.salt=W.salt}}function Y8(W={}){return new Y6(W)}class iW extends K6{rows=new Map;constructor(W={}){super();for(let[Z,$]of Object.entries(W))this.rows.set(Z,{key:Z,active:$})}async load(){return[...this.rows.values()].map((W)=>({...W}))}async write(W,Z,$){return this.rows.set(W,{key:W,active:Z,updatedBy:$.actor,updatedAt:new Date}),{actorRecorded:!0}}}export{G9 as workflowEnded,IZ as viewRouteConfigDefaults,p9 as translationConfigDefaults,_4 as toRangeHeaderValue,D8 as subjectFor,EZ as strictCspPolicy,P8 as sniffContentType,T9 as scheduleConfigDefaults,C4 as resolveRange,z$ as redisConfigDefaults,Y$ as rateLimiterConfigDefaults,rZ as queueConfigDefaults,c5 as parseMetaSignedRequest,k1 as parseContentRange,z8 as mintSessionToken,uZ as middlewareConfigDefaults,D9 as mcpCallOf,lZ as mailConfigDefaults,w8 as logConfigDefaults,J8 as isSessionToken,x5 as isFixedSignInCode,UZ as isFinalRunStatus,A6 as isBroadcastEvent,b8 as isActiveContentType,M8 as inRollout,PZ as imageConfigDefaults,U5 as fixedSignInCode,k8 as filesystemConfigDefaults,i9 as featuresConfigDefaults,b9 as eventConfigDefaults,L8 as evaluateFeature,r8 as encodeCursor,yZ as documentScriptCspHash,I9 as discoverWorkflows,A9 as discoverListeners,v9 as discoverJobs,f9 as discoverCronJobs,y9 as discoverCommands,u9 as defineTranslationConfig,C9 as defineScheduleConfig,DZ as defineRunsConfig,wZ as defineRouteConfig,J$ as defineRedisConfig,Q$ as defineRateLimiterConfig,tZ as defineQueueConfig,cZ as defineMiddlewareConfig,dZ as defineMailConfig,q8 as defineLogConfig,TZ as defineImageConfig,V8 as defineFilesystemConfig,n9 as defineFeaturesConfig,Y8 as defineFeature,P9 as defineEventConfig,tW as defineEncryptionConfig,O9 as defineCommandConfig,V9 as defineCommand,a8 as defineChangeFeedConfig,I8 as defineCacheConfig,zZ as defineBroadcastConfig,X8 as defineAuthConfig,e8 as decodeCursor,oZ as createWorkflowTableStatements,RZ as createRunsTableStatements,_9 as commandConfigDefaults,t8 as changeFeedConfigDefaults,f8 as cacheConfigDefaults,F8 as bucketOf,j8 as bucketKey,GZ as broadcastConfigDefaults,p4 as bearerToken,B8 as authConfigDefaults,V4 as assertDeletablePrefix,vZ as apiRouteConfigDefaults,yW as YouTubeConnectionProvider,fW as YOUTUBE_DEFAULT_SCOPES,hW as X_DEFAULT_SCOPES,UW as XOAuthProvider,EW as XConnectionProvider,X9 as WorkflowRuntime,J9 as WorkflowCancelledError,w9 as Workflow,Y9 as WaitTimeoutError,gZ as ViewRouteDispatcher,S8 as UndeclaredFeatureError,vW as TikTokConnectionProvider,E8 as TaggedCache,wW as TIKTOK_DEFAULT_SCOPES,T8 as StorageFetchTimeoutError,K9 as StepTimeoutError,Q9 as StepFailedError,z9 as Step,iW as StaticFeatureFlagSource,CZ as Sharp,x9 as Scheduler,d9 as ScheduleServiceProvider,hZ as STATIC_NAVIGATION_CSP_HASH,JZ as SOCKET_ID_HEADER,K8 as SESSION_TOKEN_PREFIX,z6 as S3Driver,B$ as RunsServiceProvider,OZ as RunNotFoundError,VZ as RunManager,_Z as RunFailure,X$ as RouteServiceProvider,pZ as ResendDriver,G$ as RedisServiceProvider,b4 as RedisRateLimiterTimeoutError,n1 as RedisRateLimiterDisconnectedError,F6 as RedisRateLimiter,l1 as RedisManager,A8 as RedisCacheStore,BZ as RedisBroadcastDriver,K$ as RateLimiterServiceProvider,T1 as RateLimiterDriver,G8 as RateLimiter,j1 as RangeNotSatisfiableError,h9 as QueueServiceProvider,B9 as QueueManager,o8 as ProviderConnection,I6 as PrismaMcpOAuthStore,MZ as PendingBroadcast,NZ as OPEN_RUN_STATUSES,i8 as OAuthReconnectRequiredError,i as OAuthProvider,b as OAuthConnectionProvider,U as OAuthConnectionError,R as OAuthCallbackError,$$ as MiddlewareServiceProvider,qZ as MiddlewareRegistry,c as MetaSignedRequestError,eZ as MemoryWorkflowStore,xZ as MemoryRunStore,W9 as MemoryQueueDriver,v6 as MemoryMcpOAuthStore,iZ as MemoryLockStore,l8 as MemoryConnectionStore,ZZ as MemoryChangeFeedDriver,y8 as MemoryCacheStore,XZ as MemoryBroadcastDriver,M9 as McpToolError,H9 as McpRegistry,q6 as McpOAuthServer,U9 as McpHttpServer,L9 as McpCallRefusedError,N9 as McpApiKeyResolver,o9 as MailServiceProvider,nZ as MailManager,Z$ as LogServiceProvider,v8 as LogManager,c8 as LockManager,g8 as LockLostError,q9 as Listener,bW as LinkedInConnectionProvider,p5 as LINKEDIN_ORGANIZATION_SCOPES,PW as LINKEDIN_DEFAULT_SCOPES,W$ as KernelIdServiceProvider,fZ as KernelId,j9 as Job,$9 as ItemSource,KZ as InvalidChannelError,Q6 as InstagramPublisher,_ as InstagramPublishError,VW as InstagramOAuthProvider,O4 as InstagramConnectionProvider,m as InstagramApiError,l5 as Instagram,P4 as InMemoryRateLimiter,e9 as ImageServiceProvider,kZ as ImageOptimizationDriver,bZ as ImageManager,Z9 as ITEM_SOURCE_ITEM_LIMIT,AZ as ISLAND_LOADER_CSP_HASH,q as INSTAGRAM_LIMITS,m8 as HeldLock,u6 as GoogleOAuthProvider,d6 as GitHubOAuthProvider,r9 as FilesystemServiceProvider,C8 as FilesystemManager,_8 as FileSystemDriver,C1 as FileStorageDriver,Y1 as FileNotFoundError,s9 as FeaturesServiceProvider,x8 as FeatureSourceReadOnlyError,R8 as FeatureScope,H8 as FeatureReloadError,U8 as FeatureModelMissingError,O8 as FeatureManager,N8 as FeatureFlagStore,K6 as FeatureFlagSource,Y6 as Feature,W6 as FacebookPage,CW as FacebookConnectionProvider,HZ as FINAL_RUN_STATUSES,kW as FACEBOOK_DEFAULT_SCOPES,t9 as EventServiceProvider,h as EventManager,e1 as Event,a9 as EncryptionServiceProvider,p8 as EncryptionKeyError,u8 as Encrypter,w4 as EmailDriver,d8 as DecryptionError,sZ as DatabaseWorkflowStore,SZ as DatabaseRunStore,D6 as DatabaseRateLimiter,aZ as DatabaseQueueDriver,q4 as DatabaseLockStore,l9 as DatabaseFeatureFlagSource,n8 as DatabaseConnectionStore,WZ as DatabaseChangeFeedDriver,F9 as DEFAULT_MCP_SCOPE,k9 as CronJob,s8 as ConnectionManager,j$ as CommandRegistry,S9 as CommandFailed,R9 as Command,YZ as ChangeFeedSubscription,m9 as ChangeFeedServiceProvider,QZ as ChangeFeedManager,$Z as ChangeFeedFullError,g9 as CacheServiceProvider,h8 as CacheManager,i1 as CONSENT_PAGE_HEADERS,E9 as BroadcastServiceProvider,LZ as BroadcastScope,jZ as BroadcastPayloadTooLargeError,FZ as BroadcastManager,h6 as BroadcastEvent,X6 as AzureBlobDriver,c9 as AuthServiceProvider,z1 as AuthManager,mZ as ApiRouteDispatcher,v4 as AcsDriver};
71
71
 
72
- //# debugId=0E013E17045B270364756E2164756E21
72
+ //# debugId=C065A328FA79649964756E2164756E21