gemi 0.218.0 → 0.219.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.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +2 -2
- package/dist/ai/testing/index.js +2 -2
- package/dist/ai/testing/index.js.map +1 -1
- package/dist/{chunk-ww62b10k.js → chunk-0egjv6cj.js} +2 -2
- package/dist/{chunk-ww62b10k.js.map → chunk-0egjv6cj.js.map} +1 -1
- package/dist/{chunk-9g5qh1ya.js → chunk-2vktfp1f.js} +2 -2
- package/dist/{chunk-9g5qh1ya.js.map → chunk-2vktfp1f.js.map} +1 -1
- package/dist/chunk-4g24ffv8.js +5 -0
- package/dist/{chunk-d6bgh2nr.js.map → chunk-4g24ffv8.js.map} +1 -1
- package/dist/chunk-4kkb85z8.js +8 -0
- package/dist/{chunk-xese0rng.js.map → chunk-4kkb85z8.js.map} +4 -5
- package/dist/{chunk-b1pps9bj.js → chunk-59p034g3.js} +2 -2
- package/dist/{chunk-b1pps9bj.js.map → chunk-59p034g3.js.map} +1 -1
- package/dist/{chunk-c95ds04p.js → chunk-66re5qsr.js} +2 -2
- package/dist/{chunk-c95ds04p.js.map → chunk-66re5qsr.js.map} +1 -1
- package/dist/{chunk-sqqh78tf.js → chunk-6my6c6b1.js} +2 -2
- package/dist/{chunk-sqqh78tf.js.map → chunk-6my6c6b1.js.map} +1 -1
- package/dist/chunk-71r1x773.js +19 -0
- package/dist/{chunk-4sbrvmz9.js.map → chunk-71r1x773.js.map} +3 -3
- package/dist/chunk-ak85ee4e.js +39 -0
- package/dist/chunk-ak85ee4e.js.map +20 -0
- package/dist/{chunk-gxd1388t.js → chunk-c250kpcm.js} +2 -2
- package/dist/{chunk-gxd1388t.js.map → chunk-c250kpcm.js.map} +1 -1
- package/dist/{chunk-4s72m6zx.js → chunk-cmyt2txd.js} +3 -3
- package/dist/{chunk-4s72m6zx.js.map → chunk-cmyt2txd.js.map} +1 -1
- package/dist/{chunk-fq7wkefg.js → chunk-cw50n89n.js} +2 -2
- package/dist/{chunk-fq7wkefg.js.map → chunk-cw50n89n.js.map} +1 -1
- package/dist/{chunk-7rmb1v9c.js → chunk-g5drp5xx.js} +2 -2
- package/dist/{chunk-7rmb1v9c.js.map → chunk-g5drp5xx.js.map} +1 -1
- package/dist/{chunk-snt0523y.js → chunk-gf3m0866.js} +2 -2
- package/dist/{chunk-snt0523y.js.map → chunk-gf3m0866.js.map} +1 -1
- package/dist/{chunk-tw338bbv.js → chunk-jfpwjqvq.js} +2 -2
- package/dist/{chunk-tw338bbv.js.map → chunk-jfpwjqvq.js.map} +1 -1
- package/dist/{chunk-gxfyd8wr.js → chunk-kt174y9e.js} +3 -3
- package/dist/{chunk-gxfyd8wr.js.map → chunk-kt174y9e.js.map} +1 -1
- package/dist/{chunk-s7jwsbfd.js → chunk-nrv7hdeh.js} +3 -3
- package/dist/{chunk-s7jwsbfd.js.map → chunk-nrv7hdeh.js.map} +1 -1
- package/dist/{chunk-7t13vyzg.js → chunk-p4b5hmr8.js} +2 -2
- package/dist/{chunk-7t13vyzg.js.map → chunk-p4b5hmr8.js.map} +1 -1
- package/dist/chunk-pnt0c59g.js +484 -0
- package/dist/{chunk-ktee4gy4.js.map → chunk-pnt0c59g.js.map} +8 -7
- package/dist/{chunk-m0pfdc1n.js → chunk-s4sx97fn.js} +3 -3
- package/dist/{chunk-m0pfdc1n.js.map → chunk-s4sx97fn.js.map} +1 -1
- package/dist/{chunk-ncw3zjxm.js → chunk-w4aw44zg.js} +2 -2
- package/dist/{chunk-ncw3zjxm.js.map → chunk-w4aw44zg.js.map} +1 -1
- package/dist/{chunk-7081awrd.js → chunk-w9a3b4vs.js} +2 -2
- package/dist/{chunk-7081awrd.js.map → chunk-w9a3b4vs.js.map} +1 -1
- package/dist/{chunk-bcfwa370.js → chunk-xm6hfksv.js} +2 -2
- package/dist/{chunk-bcfwa370.js.map → chunk-xm6hfksv.js.map} +1 -1
- package/dist/{chunk-k8nsefzb.js → chunk-xrkr2yzz.js} +2 -2
- package/dist/{chunk-k8nsefzb.js.map → chunk-xrkr2yzz.js.map} +1 -1
- package/dist/{chunk-evgs2tr8.js → chunk-xvf1hcxg.js} +2 -2
- package/dist/{chunk-evgs2tr8.js.map → chunk-xvf1hcxg.js.map} +2 -2
- package/dist/{chunk-eh3ktv8k.js → chunk-y12m6w7b.js} +2 -2
- package/dist/{chunk-eh3ktv8k.js.map → chunk-y12m6w7b.js.map} +1 -1
- package/dist/chunk-yv3y3r9q.js +88 -0
- package/dist/{chunk-sxxkkx75.js.map → chunk-yv3y3r9q.js.map} +3 -10
- package/dist/client/index.d.ts +2 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +54 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/useWorkflow.d.ts +51 -0
- package/dist/client/useWorkflow.d.ts.map +1 -0
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/database/index.js +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.d.ts +2 -1
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +3 -3
- package/dist/services/index.js.map +2 -2
- package/dist/services/queue/QueueManager.d.ts +2 -0
- package/dist/services/queue/QueueManager.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/queue/workflow/Step.d.ts +2 -9
- package/dist/services/queue/workflow/Step.d.ts.map +1 -1
- package/dist/services/queue/workflow/Workflow.d.ts +26 -38
- package/dist/services/queue/workflow/Workflow.d.ts.map +1 -1
- package/dist/services/queue/workflow/WorkflowRuntime.d.ts +45 -0
- package/dist/services/queue/workflow/WorkflowRuntime.d.ts.map +1 -1
- package/dist/services/queue/workflow/WorkflowStore.d.ts +2 -16
- package/dist/services/queue/workflow/WorkflowStore.d.ts.map +1 -1
- package/dist/services/queue/workflow/wire.d.ts +71 -0
- package/dist/services/queue/workflow/wire.d.ts.map +1 -0
- package/dist/services/queue/workflow/workflowContract.d.ts.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-4sbrvmz9.js +0 -19
- package/dist/chunk-d6bgh2nr.js +0 -5
- package/dist/chunk-ktee4gy4.js +0 -484
- package/dist/chunk-sxxkkx75.js +0 -117
- package/dist/chunk-xb0evp2m.js +0 -5
- package/dist/chunk-xb0evp2m.js.map +0 -12
- package/dist/chunk-xese0rng.js +0 -13
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rb as Q$}from"../chunk-g6tqje74.js";import{$b as s9,Ab as g4,Bb as s1,Cb as B9,Db as j9,Eb as b9,Ib as w9,Jb as q9,Kb as v9,Lb as I9,Mb as A9,Nb as h9,Ob as E9,Pb as g9,Qb as m9,Rb as c9,Sb as u9,Tb as n4,Ub as v6,Vb as h,Wb as p9,Xb as d9,Yb as l9,Zb as n9,_b as i9,ac as o9,bc as a9,cc as t9,dc as r9,ec as e9,fc as W$,gc as Z$,hc as $$,sb as Y9,tb as K9,ub as J9,vb as z9,wb as G9,xb as u4,yb as X9,zb as E4}from"../chunk-9g5qh1ya.js";import{kc as d4}from"../chunk-evgs2tr8.js";import"../chunk-bcfwa370.js";import{be as M9,ce as F9,de as L9,ee as D9,fe as H9,ge as U9,he as x9,ie as S9,je as R9,ke as O9,le as _9,me as V9,ne as k9,oe as C9,pe as T9,qe as P9}from"../chunk-4sbrvmz9.js";import{re as N9}from"../chunk-7xe5vd4w.js";import{Ae as oZ,Be as aZ,Ce as tZ,De as rZ,Ee as eZ,Fe as W9,Ge as Z9,He as $9,Me as Q9,se as cZ,te as uZ,ue as pZ,ve as dZ,we as lZ,xe as nZ,ye as iZ,ze as sZ}from"../chunk-ktee4gy4.js";import{Ne as f9,Oe as y9}from"../chunk-7t13vyzg.js";import"../chunk-sqqh78tf.js";import{$e as $8,$g as PZ,Af as L8,Ag as XZ,Bf as D8,Bg as BZ,Cf as H8,Cg as jZ,Dg as MZ,Eg as FZ,Fg as LZ,Gg as DZ,Gh as yZ,Hg as HZ,Hh as AZ,Ig as NZ,Jg as UZ,Og as R,Pg as i,Qg as xZ,Rf as T8,Rg as SZ,Sf as P8,Sg as RZ,Tf as b8,Tg as OZ,Uf as w8,Ug as _Z,Vf as q8,We as V6,Wf as v8,Wg as VZ,Xe as e5,Xg as kZ,Ye as W8,Yg as CZ,Ze as Z8,Zg as TZ,ag as d8,bg as l8,cg as n8,ch as bZ,df as k6,dg as i8,dh as wZ,ef as C4,eg as s8,eh as qZ,ff as B6,fg as o8,gf as T4,gg as a8,hf as P4,hg as t8,hh as vZ,ig as r8,kg as e8,lf as f6,lg as q6,mf as y6,mg as WZ,mh as IZ,of as Q8,pf as Y8,qf as K8,qg as ZZ,qh as fZ,rf as J8,rg as $Z,sf as z8,sg as YZ,tf as G8,uf as X8,uh as i4,vf as B8,vg as KZ,vh as z1,wf as j8,wg as JZ,xf as Y6,xg as zZ,yf as M8,yg as GZ,zf as F8}from"../chunk-sxxkkx75.js";import"../chunk-s7jwsbfd.js";import"../chunk-4s72m6zx.js";import{Ai as O4,Bi as k1,Bj as V8,Cj as k8,Dj as C8,Fj as d1,Ti as h4,Xi as j1,Zi as Y1,bj as _4,cj as C1,dj as p1,ej as N8,fj as U8,gj as x8,hj as S8,ij as R8,uj as mW,vj as cW,yj as O8,zi as k4,zj as _8}from"../chunk-xese0rng.js";import"../chunk-eh3ktv8k.js";import{Qj as q}from"../chunk-snt0523y.js";import"../chunk-ww62b10k.js";import{ak as g8,bk as m8,ck as U,dk as c8,ek as b,fk as u8,gk as p8}from"../chunk-gxfyd8wr.js";import{mk as A8,nk as h8,ok as E8}from"../chunk-m0pfdc1n.js";import"../chunk-ncw3zjxm.js";import{Xk as QZ}from"../chunk-k8nsefzb.js";import{$k as y8,Zk as I8,_k as f8}from"../chunk-xb0evp2m.js";import"../chunk-yxtfg4wy.js";import"../chunk-xyv3y476.js";import"../chunk-qa528feb.js";import"../chunk-jzqywxpj.js";import{$l as mZ,Wl as w4,Xl as hZ,Yl as EZ,Zl as gZ}from"../chunk-zyvmbqcx.js";import"../chunk-qstjm3cb.js";import{jm as C}from"../chunk-aes0ecnp.js";import"../chunk-sba3s380.js";import"../chunk-cwm5x7rf.js";import"../chunk-q0d45r2j.js";import"../chunk-hmtn7996.js";import"../chunk-rp2f9mq1.js";import{Om as u1}from"../chunk-yedb5vvg.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-g178aect.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 Y$}from"../chunk-g6tqje74.js";import{$b as o9,Ab as g4,Bb as s1,Cb as j9,Db as M9,Eb as w9,Ib as q9,Jb as v9,Kb as I9,Lb as f9,Mb as h9,Nb as E9,Ob as g9,Pb as m9,Qb as c9,Rb as u9,Sb as p9,Tb as n4,Ub as v6,Vb as h,Wb as d9,Xb as l9,Yb as n9,Zb as i9,_b as s9,ac as a9,bc as t9,cc as r9,dc as e9,ec as W$,fc as Z$,gc as $$,hc as Q$,sb as K9,tb as J9,ub as z9,vb as G9,wb as X9,xb as u4,yb as B9,zb as E4}from"../chunk-2vktfp1f.js";import{kc as d4}from"../chunk-xvf1hcxg.js";import"../chunk-xm6hfksv.js";import{be as F9,ce as L9,de as D9,ee as H9,fe as N9,ge as x9,he as S9,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}from"../chunk-71r1x773.js";import{re as U9}from"../chunk-7xe5vd4w.js";import{Ae as oZ,Be as aZ,Ce as tZ,De as rZ,Ee as eZ,Fe as W9,Ge as Z9,He as $9,Ie as Q9,Ne as Y9,se as cZ,te as uZ,ue as pZ,ve as dZ,we as lZ,xe as nZ,ye as iZ,ze as sZ}from"../chunk-pnt0c59g.js";import{Oe as y9,Pe as A9}from"../chunk-p4b5hmr8.js";import"../chunk-6my6c6b1.js";import{$g as vZ,Af as F8,Ag as NZ,Bf as L8,Bg as UZ,Cf as D8,Df as H8,Gg as R,Hg as i,Ig as xZ,Jg as SZ,Kg as RZ,Lg as OZ,Mg as _Z,Og as VZ,Pg as kZ,Qg as CZ,Rg as TZ,Sf as T8,Tf as P8,Tg as PZ,Uf as b8,Vf as w8,Wf as q8,Wg as bZ,Xe as V6,Xf as v8,Xg as wZ,Ye as e5,Yg as qZ,Ze as W8,_e as Z8,af as $8,cg as e8,dg as q6,ef as k6,eg as WZ,eh as IZ,ff as C4,gf as B6,hf as T4,if as P4,ig as ZZ,ih as fZ,jg as $Z,kg as YZ,mf as f6,mh as i4,nf as y6,ng as KZ,nh as z1,og as JZ,pf as Q8,pg as zZ,qf as Y8,qg as GZ,rf as K8,sf as J8,sg as XZ,tf as z8,tg as BZ,uf as G8,ug as jZ,vf as X8,vg as MZ,wf as B8,wg as FZ,xf as j8,xg as LZ,yf as Y6,yg as DZ,yh as yZ,zf as M8,zg as HZ,zh as AZ}from"../chunk-yv3y3r9q.js";import"../chunk-nrv7hdeh.js";import"../chunk-cmyt2txd.js";import{$i as S8,Li as h4,Pi as j1,Ri as Y1,Vi as _4,Wi as C1,Xi as p1,Yi as N8,Zi as U8,_i as x8,aj as R8,mj as mW,nj as cW,qj as O8,ri as k4,rj as _8,si as O4,ti as k1,tj as V8,uj as k8,vj as C8,xj as d1}from"../chunk-4kkb85z8.js";import"../chunk-y12m6w7b.js";import{Dj as q}from"../chunk-gf3m0866.js";import"../chunk-0egjv6cj.js";import{Pj as g8,Qj as m8,Rj as U,Sj as c8,Tj as b,Uj as u8,Vj as p8}from"../chunk-kt174y9e.js";import{$j as A8,ak as h8,bk as E8}from"../chunk-s4sx97fn.js";import"../chunk-w4aw44zg.js";import{Kk as QZ}from"../chunk-xrkr2yzz.js";import{$k as r8,Mk as I8,Nk as f8,Ok as y8,Pk as d8,Qk as l8,Rk as n8,Sk as i8,Tk as s8,Uk as o8,Zk as a8,_k as t8}from"../chunk-ak85ee4e.js";import"../chunk-yxtfg4wy.js";import"../chunk-xyv3y476.js";import"../chunk-qa528feb.js";import"../chunk-jzqywxpj.js";import{$l as mZ,Wl as w4,Xl as hZ,Yl as EZ,Zl as gZ}from"../chunk-zyvmbqcx.js";import"../chunk-qstjm3cb.js";import{jm as C}from"../chunk-aes0ecnp.js";import"../chunk-sba3s380.js";import"../chunk-cwm5x7rf.js";import"../chunk-q0d45r2j.js";import"../chunk-hmtn7996.js";import"../chunk-rp2f9mq1.js";import{Om as u1}from"../chunk-yedb5vvg.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-g178aect.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=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
|
@@ -67,6 +67,6 @@ ${W.resolution}.`;console.warn($),console.warn("To disable this message, import
|
|
|
67
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
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(`
|
|
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{TZ as viewRouteConfigDefaults,y9 as translationConfigDefaults,O4 as toRangeHeaderValue,X8 as subjectFor,vZ as strictCspPolicy,O8 as sniffContentType,x9 as scheduleConfigDefaults,k4 as resolveRange,e9 as redisConfigDefaults,a9 as rateLimiterConfigDefaults,iZ as queueConfigDefaults,y5 as parseMetaSignedRequest,k1 as parseContentRange,Z8 as mintSessionToken,AZ as middlewareConfigDefaults,z9 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,g9 as featuresConfigDefaults,R9 as eventConfigDefaults,G8 as evaluateFeature,n8 as encodeCursor,bZ as documentScriptCspHash,k9 as discoverWorkflows,P9 as discoverListeners,V9 as discoverJobs,C9 as discoverCronJobs,T9 as discoverCommands,f9 as defineTranslationConfig,U9 as defineScheduleConfig,XZ as defineRunsConfig,kZ as defineRouteConfig,r9 as defineRedisConfig,o9 as defineRateLimiterConfig,nZ as defineQueueConfig,yZ as defineMiddlewareConfig,EZ as defineMailConfig,V8 as defineLogConfig,RZ as defineImageConfig,U8 as defineFilesystemConfig,E9 as defineFeaturesConfig,r5 as defineFeature,S9 as defineEventConfig,iW as defineEncryptionConfig,L9 as defineCommandConfig,H9 as defineCommand,d8 as defineChangeFeedConfig,T8 as defineCacheConfig,ZZ as defineBroadcastConfig,Q8 as defineAuthConfig,i8 as decodeCursor,dZ as createWorkflowTableStatements,DZ as createRunsTableStatements,D9 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,Z9 as WorkflowRuntime,eZ as WorkflowCancelledError,_9 as Workflow,tZ as WaitTimeoutError,IZ as ViewRouteDispatcher,L8 as UndeclaredFeatureError,PW as TikTokConnectionProvider,v8 as TaggedCache,TW as TIKTOK_DEFAULT_SCOPES,R8 as StorageFetchTimeoutError,rZ as StepTimeoutError,aZ as StepFailedError,W9 as Step,pW as StaticFeatureFlagSource,SZ as Sharp,j9 as Scheduler,A9 as ScheduleServiceProvider,qZ as STATIC_NAVIGATION_CSP_HASH,WZ as SOCKET_ID_HEADER,e5 as SESSION_TOKEN_PREFIX,J6 as S3Driver,$$ as RunsServiceProvider,HZ as RunNotFoundError,UZ as RunManager,NZ as RunFailure,Z$ as RouteServiceProvider,hZ as ResendDriver,W$ as RedisServiceProvider,b4 as RedisRateLimiterTimeoutError,l1 as RedisRateLimiterDisconnectedError,j6 as RedisRateLimiter,d1 as RedisManager,w8 as RedisCacheStore,YZ as RedisBroadcastDriver,t9 as RateLimiterServiceProvider,T4 as RateLimiterDriver,$8 as RateLimiter,j1 as RangeNotSatisfiableError,b9 as QueueServiceProvider,$9 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,s9 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,K9 as McpToolError,G9 as McpRegistry,C6 as McpOAuthServer,B9 as McpHttpServer,J9 as McpCallRefusedError,X9 as McpApiKeyResolver,c9 as MailServiceProvider,mZ as MailManager,i9 as LogServiceProvider,C8 as LogManager,y8 as LockManager,I8 as LockLostError,O9 as Listener,kW as LinkedInConnectionProvider,h5 as LINKEDIN_ORGANIZATION_SCOPES,VW as LINKEDIN_DEFAULT_SCOPES,n9 as KernelIdServiceProvider,PZ as KernelId,Q9 as Job,e8 as InvalidChannelError,$6 as InstagramPublisher,_ as InstagramPublishError,SW as InstagramOAuthProvider,R4 as InstagramConnectionProvider,m as InstagramApiError,g5 as Instagram,P4 as InMemoryRateLimiter,l9 as ImageServiceProvider,xZ as ImageOptimizationDriver,_Z as ImageManager,wZ as ISLAND_LOADER_CSP_HASH,w as INSTAGRAM_LIMITS,f8 as HeldLock,E6 as GoogleOAuthProvider,m6 as GitHubOAuthProvider,d9 as FilesystemServiceProvider,S8 as FilesystemManager,N8 as FileSystemDriver,C1 as FileStorageDriver,Y1 as FileNotFoundError,m9 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,p9 as EventServiceProvider,h as EventManager,r1 as Event,u9 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,h9 as DatabaseFeatureFlagSource,m8 as DatabaseConnectionStore,s8 as DatabaseChangeFeedDriver,Y9 as DEFAULT_MCP_SCOPE,N9 as CronJob,u8 as ConnectionManager,Q$ as CommandRegistry,M9 as CommandFailed,F9 as Command,r8 as ChangeFeedSubscription,v9 as ChangeFeedServiceProvider,t8 as ChangeFeedManager,a8 as ChangeFeedFullError,q9 as CacheServiceProvider,q8 as CacheManager,n1 as CONSENT_PAGE_HEADERS,w9 as BroadcastServiceProvider,GZ as BroadcastScope,KZ as BroadcastPayloadTooLargeError,JZ as BroadcastManager,I6 as BroadcastEvent,G6 as AzureBlobDriver,I9 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=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{Z9 as workflowEnded,TZ as viewRouteConfigDefaults,A9 as translationConfigDefaults,O4 as toRangeHeaderValue,X8 as subjectFor,vZ as strictCspPolicy,O8 as sniffContentType,S9 as scheduleConfigDefaults,k4 as resolveRange,W$ as redisConfigDefaults,t9 as rateLimiterConfigDefaults,iZ as queueConfigDefaults,y5 as parseMetaSignedRequest,k1 as parseContentRange,Z8 as mintSessionToken,AZ as middlewareConfigDefaults,G9 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,m9 as featuresConfigDefaults,O9 as eventConfigDefaults,G8 as evaluateFeature,n8 as encodeCursor,bZ as documentScriptCspHash,C9 as discoverWorkflows,b9 as discoverListeners,k9 as discoverJobs,T9 as discoverCronJobs,P9 as discoverCommands,y9 as defineTranslationConfig,x9 as defineScheduleConfig,XZ as defineRunsConfig,kZ as defineRouteConfig,e9 as defineRedisConfig,a9 as defineRateLimiterConfig,nZ as defineQueueConfig,yZ as defineMiddlewareConfig,EZ as defineMailConfig,V8 as defineLogConfig,RZ as defineImageConfig,U8 as defineFilesystemConfig,g9 as defineFeaturesConfig,r5 as defineFeature,R9 as defineEventConfig,iW as defineEncryptionConfig,D9 as defineCommandConfig,N9 as defineCommand,d8 as defineChangeFeedConfig,T8 as defineCacheConfig,ZZ as defineBroadcastConfig,Q8 as defineAuthConfig,i8 as decodeCursor,dZ as createWorkflowTableStatements,DZ as createRunsTableStatements,H9 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,$9 as WorkflowRuntime,eZ as WorkflowCancelledError,V9 as Workflow,tZ as WaitTimeoutError,IZ as ViewRouteDispatcher,L8 as UndeclaredFeatureError,PW as TikTokConnectionProvider,v8 as TaggedCache,TW as TIKTOK_DEFAULT_SCOPES,R8 as StorageFetchTimeoutError,rZ as StepTimeoutError,aZ as StepFailedError,W9 as Step,pW as StaticFeatureFlagSource,SZ as Sharp,M9 as Scheduler,h9 as ScheduleServiceProvider,qZ as STATIC_NAVIGATION_CSP_HASH,WZ as SOCKET_ID_HEADER,e5 as SESSION_TOKEN_PREFIX,J6 as S3Driver,Q$ as RunsServiceProvider,HZ as RunNotFoundError,UZ as RunManager,NZ as RunFailure,$$ as RouteServiceProvider,hZ as ResendDriver,Z$ as RedisServiceProvider,b4 as RedisRateLimiterTimeoutError,l1 as RedisRateLimiterDisconnectedError,j6 as RedisRateLimiter,d1 as RedisManager,w8 as RedisCacheStore,YZ as RedisBroadcastDriver,r9 as RateLimiterServiceProvider,T4 as RateLimiterDriver,$8 as RateLimiter,j1 as RangeNotSatisfiableError,w9 as QueueServiceProvider,Q9 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,o9 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,J9 as McpToolError,X9 as McpRegistry,C6 as McpOAuthServer,j9 as McpHttpServer,z9 as McpCallRefusedError,B9 as McpApiKeyResolver,u9 as MailServiceProvider,mZ as MailManager,s9 as LogServiceProvider,C8 as LogManager,y8 as LockManager,I8 as LockLostError,_9 as Listener,kW as LinkedInConnectionProvider,h5 as LINKEDIN_ORGANIZATION_SCOPES,VW as LINKEDIN_DEFAULT_SCOPES,i9 as KernelIdServiceProvider,PZ as KernelId,Y9 as Job,e8 as InvalidChannelError,$6 as InstagramPublisher,_ as InstagramPublishError,SW as InstagramOAuthProvider,R4 as InstagramConnectionProvider,m as InstagramApiError,g5 as Instagram,P4 as InMemoryRateLimiter,n9 as ImageServiceProvider,xZ as ImageOptimizationDriver,_Z as ImageManager,wZ as ISLAND_LOADER_CSP_HASH,w as INSTAGRAM_LIMITS,f8 as HeldLock,E6 as GoogleOAuthProvider,m6 as GitHubOAuthProvider,l9 as FilesystemServiceProvider,S8 as FilesystemManager,N8 as FileSystemDriver,C1 as FileStorageDriver,Y1 as FileNotFoundError,c9 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,d9 as EventServiceProvider,h as EventManager,r1 as Event,p9 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,E9 as DatabaseFeatureFlagSource,m8 as DatabaseConnectionStore,s8 as DatabaseChangeFeedDriver,K9 as DEFAULT_MCP_SCOPE,U9 as CronJob,u8 as ConnectionManager,Y$ as CommandRegistry,F9 as CommandFailed,L9 as Command,r8 as ChangeFeedSubscription,I9 as ChangeFeedServiceProvider,t8 as ChangeFeedManager,a8 as ChangeFeedFullError,v9 as CacheServiceProvider,q8 as CacheManager,n1 as CONSENT_PAGE_HEADERS,q9 as BroadcastServiceProvider,GZ as BroadcastScope,KZ as BroadcastPayloadTooLargeError,JZ as BroadcastManager,I6 as BroadcastEvent,G6 as AzureBlobDriver,f9 as AuthServiceProvider,z1 as AuthManager,fZ as ApiRouteDispatcher,q4 as AcsDriver};
|
|
71
71
|
|
|
72
|
-
//# debugId=
|
|
72
|
+
//# debugId=05528C2DC66EC37B64756E2164756E21
|