gemi 0.197.0 → 0.199.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 +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-s57n552b.js → chunk-0kfrwbhg.js} +4 -4
- package/dist/{chunk-s57n552b.js.map → chunk-0kfrwbhg.js.map} +1 -1
- package/dist/{chunk-y9pzr1wc.js → chunk-1yq2b55s.js} +2 -2
- package/dist/{chunk-y9pzr1wc.js.map → chunk-1yq2b55s.js.map} +1 -1
- package/dist/{chunk-6nj9xjsm.js → chunk-206n0q1f.js} +2 -2
- package/dist/{chunk-6nj9xjsm.js.map → chunk-206n0q1f.js.map} +1 -1
- package/dist/{chunk-3bsw9sra.js → chunk-2cyd3h4h.js} +2 -2
- package/dist/{chunk-3bsw9sra.js.map → chunk-2cyd3h4h.js.map} +1 -1
- package/dist/{chunk-2g2cntdm.js → chunk-2kkv8515.js} +2 -2
- package/dist/{chunk-2g2cntdm.js.map → chunk-2kkv8515.js.map} +1 -1
- package/dist/{chunk-wprzrnqh.js → chunk-42b6zzg2.js} +2 -2
- package/dist/{chunk-wprzrnqh.js.map → chunk-42b6zzg2.js.map} +1 -1
- package/dist/{chunk-51n7yky9.js → chunk-4reyxar1.js} +1 -1
- package/dist/{chunk-a4kk68xy.js → chunk-503ce1t9.js} +2 -2
- package/dist/{chunk-a4kk68xy.js.map → chunk-503ce1t9.js.map} +1 -1
- package/dist/{chunk-zryrem89.js → chunk-50nex9wg.js} +3 -3
- package/dist/{chunk-zryrem89.js.map → chunk-50nex9wg.js.map} +1 -1
- package/dist/{chunk-4ftk3z34.js → chunk-5zjw41cv.js} +2 -2
- package/dist/{chunk-4ftk3z34.js.map → chunk-5zjw41cv.js.map} +1 -1
- package/dist/{chunk-spsheyx9.js → chunk-61mcmhjp.js} +1 -1
- package/dist/{chunk-5qaxde5h.js → chunk-64hxqsqx.js} +3 -3
- package/dist/{chunk-5qaxde5h.js.map → chunk-64hxqsqx.js.map} +1 -1
- package/dist/{chunk-zehvtpgm.js → chunk-6brwvyrz.js} +2 -2
- package/dist/{chunk-zehvtpgm.js.map → chunk-6brwvyrz.js.map} +1 -1
- package/dist/{chunk-qx1vc11v.js → chunk-6ftdsrkq.js} +2 -2
- package/dist/{chunk-qx1vc11v.js.map → chunk-6ftdsrkq.js.map} +1 -1
- package/dist/{chunk-bcydd231.js → chunk-6nr97atn.js} +2 -2
- package/dist/{chunk-bcydd231.js.map → chunk-6nr97atn.js.map} +1 -1
- package/dist/{chunk-tvdmx66x.js → chunk-6xa5yqrw.js} +2 -2
- package/dist/{chunk-tvdmx66x.js.map → chunk-6xa5yqrw.js.map} +1 -1
- package/dist/{chunk-zcmfkb9f.js → chunk-81m95se9.js} +2 -2
- package/dist/{chunk-zcmfkb9f.js.map → chunk-81m95se9.js.map} +1 -1
- package/dist/{chunk-j84r2j7a.js → chunk-84stff4t.js} +2 -2
- package/dist/{chunk-j84r2j7a.js.map → chunk-84stff4t.js.map} +1 -1
- package/dist/{chunk-kjygnj7y.js → chunk-8fzcs8dv.js} +2 -2
- package/dist/{chunk-kjygnj7y.js.map → chunk-8fzcs8dv.js.map} +1 -1
- package/dist/{chunk-tv33103m.js → chunk-93j09zw7.js} +1 -1
- package/dist/{chunk-2v83pskm.js → chunk-97g2qc7j.js} +1 -1
- package/dist/{chunk-rnjjn09d.js → chunk-agc5bqdt.js} +2 -2
- package/dist/{chunk-rnjjn09d.js.map → chunk-agc5bqdt.js.map} +1 -1
- package/dist/{chunk-nnn2f1ew.js → chunk-ahss6dcp.js} +2 -2
- package/dist/{chunk-nnn2f1ew.js.map → chunk-ahss6dcp.js.map} +1 -1
- package/dist/{chunk-zzmgz14a.js → chunk-b2n74m40.js} +2 -2
- package/dist/{chunk-zzmgz14a.js.map → chunk-b2n74m40.js.map} +1 -1
- package/dist/{chunk-ng5qfkgp.js → chunk-bcfcwbp4.js} +2 -2
- package/dist/{chunk-ng5qfkgp.js.map → chunk-bcfcwbp4.js.map} +1 -1
- package/dist/{chunk-mk4x0vtp.js → chunk-bdbg2dt6.js} +2 -2
- package/dist/{chunk-mk4x0vtp.js.map → chunk-bdbg2dt6.js.map} +1 -1
- package/dist/{chunk-7sadg8d7.js → chunk-bxxd1awv.js} +3 -3
- package/dist/{chunk-7sadg8d7.js.map → chunk-bxxd1awv.js.map} +1 -1
- package/dist/{chunk-qw6aa9fy.js → chunk-by0afyps.js} +2 -2
- package/dist/{chunk-qw6aa9fy.js.map → chunk-by0afyps.js.map} +1 -1
- package/dist/chunk-ccpp45dm.js +5 -0
- package/dist/{chunk-tgbky7fc.js.map → chunk-ccpp45dm.js.map} +1 -1
- package/dist/{chunk-zv55h4x9.js → chunk-ct1vh28z.js} +2 -2
- package/dist/{chunk-zv55h4x9.js.map → chunk-ct1vh28z.js.map} +1 -1
- package/dist/chunk-dqgn4wgf.js +15 -0
- package/dist/{chunk-es05kqtp.js.map → chunk-dqgn4wgf.js.map} +5 -4
- package/dist/{chunk-fyk66c5e.js → chunk-drb6gpgv.js} +2 -2
- package/dist/{chunk-fyk66c5e.js.map → chunk-drb6gpgv.js.map} +1 -1
- package/dist/{chunk-c601phyd.js → chunk-drqv10sv.js} +2 -2
- package/dist/{chunk-c601phyd.js.map → chunk-drqv10sv.js.map} +1 -1
- package/dist/{chunk-evdca0b9.js → chunk-e603nm1c.js} +2 -2
- package/dist/{chunk-evdca0b9.js.map → chunk-e603nm1c.js.map} +1 -1
- package/dist/{chunk-02jze3te.js → chunk-e7bb26fb.js} +2 -2
- package/dist/{chunk-02jze3te.js.map → chunk-e7bb26fb.js.map} +1 -1
- package/dist/{chunk-4f2xy9ws.js → chunk-ewknbs3b.js} +3 -3
- package/dist/{chunk-4f2xy9ws.js.map → chunk-ewknbs3b.js.map} +1 -1
- package/dist/chunk-ff22412e.js +117 -0
- package/dist/{chunk-7xy7ebkx.js.map → chunk-ff22412e.js.map} +9 -8
- package/dist/chunk-gknvmhby.js +6 -0
- package/dist/{chunk-arb0qkrm.js.map → chunk-gknvmhby.js.map} +2 -2
- package/dist/{chunk-n01mhwkj.js → chunk-gx2fhmnx.js} +3 -3
- package/dist/{chunk-n01mhwkj.js.map → chunk-gx2fhmnx.js.map} +1 -1
- package/dist/{chunk-a77w04sw.js → chunk-ha4er085.js} +2 -2
- package/dist/{chunk-a77w04sw.js.map → chunk-ha4er085.js.map} +1 -1
- package/dist/{chunk-9ky5d5js.js → chunk-jkf5kjaz.js} +3 -3
- package/dist/{chunk-9ky5d5js.js.map → chunk-jkf5kjaz.js.map} +1 -1
- package/dist/{chunk-cpgc5q74.js → chunk-jtbe5n3c.js} +2 -2
- package/dist/{chunk-cpgc5q74.js.map → chunk-jtbe5n3c.js.map} +1 -1
- package/dist/{chunk-ecyq52t3.js → chunk-kz15j07h.js} +3 -3
- package/dist/{chunk-ecyq52t3.js.map → chunk-kz15j07h.js.map} +1 -1
- package/dist/{chunk-mnmz8n5k.js → chunk-mddazdpt.js} +2 -2
- package/dist/{chunk-mnmz8n5k.js.map → chunk-mddazdpt.js.map} +1 -1
- package/dist/{chunk-nbry43s8.js → chunk-mxt88hhp.js} +2 -2
- package/dist/{chunk-nbry43s8.js.map → chunk-mxt88hhp.js.map} +1 -1
- package/dist/{chunk-rk34z2wa.js → chunk-mzns19hy.js} +2 -2
- package/dist/{chunk-rk34z2wa.js.map → chunk-mzns19hy.js.map} +1 -1
- package/dist/{chunk-2z160r1b.js → chunk-mzqhn72h.js} +2 -2
- package/dist/{chunk-2z160r1b.js.map → chunk-mzqhn72h.js.map} +1 -1
- package/dist/{chunk-8mmskn4g.js → chunk-n3p16jpb.js} +3 -3
- package/dist/{chunk-8mmskn4g.js.map → chunk-n3p16jpb.js.map} +1 -1
- package/dist/{chunk-x05mj7ye.js → chunk-n9k29mrs.js} +2 -2
- package/dist/{chunk-x05mj7ye.js.map → chunk-n9k29mrs.js.map} +1 -1
- package/dist/{chunk-v4ka65g8.js → chunk-nnaz5djg.js} +2 -2
- package/dist/{chunk-v4ka65g8.js.map → chunk-nnaz5djg.js.map} +1 -1
- package/dist/{chunk-sxww1ka5.js → chunk-pab6ye4d.js} +2 -2
- package/dist/{chunk-sxww1ka5.js.map → chunk-pab6ye4d.js.map} +1 -1
- package/dist/{chunk-ff16m7gm.js → chunk-q1zj3a0e.js} +2 -2
- package/dist/{chunk-ff16m7gm.js.map → chunk-q1zj3a0e.js.map} +1 -1
- package/dist/{chunk-7q42fej6.js → chunk-rcnpjwp4.js} +2 -2
- package/dist/{chunk-7q42fej6.js.map → chunk-rcnpjwp4.js.map} +1 -1
- package/dist/{chunk-y50h3cd6.js → chunk-rh84xq17.js} +2 -2
- package/dist/{chunk-y50h3cd6.js.map → chunk-rh84xq17.js.map} +1 -1
- package/dist/{chunk-e0d6az7p.js → chunk-s9z0xxth.js} +2 -2
- package/dist/{chunk-e0d6az7p.js.map → chunk-s9z0xxth.js.map} +1 -1
- package/dist/{chunk-kjgy7sk0.js → chunk-sg78cmd1.js} +2 -2
- package/dist/{chunk-kjgy7sk0.js.map → chunk-sg78cmd1.js.map} +1 -1
- package/dist/{chunk-htnbmbx1.js → chunk-t0qs2q9j.js} +2 -2
- package/dist/{chunk-htnbmbx1.js.map → chunk-t0qs2q9j.js.map} +1 -1
- package/dist/{chunk-yzazktke.js → chunk-t4z6rkvw.js} +2 -2
- package/dist/{chunk-yzazktke.js.map → chunk-t4z6rkvw.js.map} +1 -1
- package/dist/{chunk-3am1e8ya.js → chunk-tjsv6e3a.js} +2 -2
- package/dist/{chunk-3am1e8ya.js.map → chunk-tjsv6e3a.js.map} +1 -1
- package/dist/{chunk-8xckmvea.js → chunk-txbram9h.js} +2 -2
- package/dist/{chunk-8xckmvea.js.map → chunk-txbram9h.js.map} +1 -1
- package/dist/{chunk-gk0d26zw.js → chunk-tyvc46ns.js} +2 -2
- package/dist/{chunk-gk0d26zw.js.map → chunk-tyvc46ns.js.map} +1 -1
- package/dist/{chunk-9dnbf9q8.js → chunk-v2pt8h42.js} +2 -2
- package/dist/{chunk-9dnbf9q8.js.map → chunk-v2pt8h42.js.map} +1 -1
- package/dist/{chunk-2qbfvb6m.js → chunk-vpqzzrkn.js} +2 -2
- package/dist/{chunk-2qbfvb6m.js.map → chunk-vpqzzrkn.js.map} +1 -1
- package/dist/{chunk-zrykhpn9.js → chunk-w09wtxr6.js} +3 -3
- package/dist/{chunk-zrykhpn9.js.map → chunk-w09wtxr6.js.map} +1 -1
- package/dist/{chunk-degz94dk.js → chunk-w84ke0bp.js} +2 -2
- package/dist/{chunk-degz94dk.js.map → chunk-w84ke0bp.js.map} +1 -1
- package/dist/{chunk-20y02g4n.js → chunk-wxb2pqqz.js} +2 -2
- package/dist/{chunk-20y02g4n.js.map → chunk-wxb2pqqz.js.map} +1 -1
- package/dist/{chunk-rqs2s5nh.js → chunk-xb0k1br9.js} +2 -2
- package/dist/{chunk-fzy1z97a.js.map → chunk-xb0k1br9.js.map} +1 -1
- package/dist/{chunk-kzy4pyqb.js → chunk-xhc16pv1.js} +3 -3
- package/dist/{chunk-kzy4pyqb.js.map → chunk-xhc16pv1.js.map} +1 -1
- package/dist/{chunk-gk12v51y.js → chunk-xxep62yg.js} +1 -1
- package/dist/{chunk-4k62r4hv.js → chunk-xzt117g6.js} +1 -1
- package/dist/{chunk-xb9zjaes.js → chunk-y167pt0p.js} +2 -2
- package/dist/{chunk-xb9zjaes.js.map → chunk-y167pt0p.js.map} +1 -1
- package/dist/chunk-yw9mn5w7.js +5 -0
- package/dist/{chunk-pvx66dq2.js.map → chunk-yw9mn5w7.js.map} +4 -4
- package/dist/{chunk-g1th116z.js → chunk-yxge0cem.js} +2 -2
- package/dist/{chunk-g1th116z.js.map → chunk-yxge0cem.js.map} +1 -1
- package/dist/{chunk-fzy1z97a.js → chunk-zpqcawmq.js} +2 -2
- package/dist/{chunk-rqs2s5nh.js.map → chunk-zpqcawmq.js.map} +1 -1
- package/dist/{chunk-dbe8zgyb.js → chunk-zwbpcch0.js} +2 -2
- package/dist/{chunk-dbe8zgyb.js.map → chunk-zwbpcch0.js.map} +1 -1
- package/dist/chunks/{RealtimeClient-BVQeh_yg.js → RealtimeClient-B7zh4okq.js} +2 -2
- package/dist/chunks/{RealtimeClient-BVQeh_yg.js.map → RealtimeClient-B7zh4okq.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-G2g5Z1ZS.js → ThemeProvider-D33bPpf8.js} +51 -4
- package/dist/chunks/ThemeProvider-D33bPpf8.js.map +1 -0
- package/dist/chunks/{fetchFileRequest-Bzva9J59.js → fetchFileRequest-Cp0QjioM.js} +2 -2
- package/dist/chunks/{fetchFileRequest-Bzva9J59.js.map → fetchFileRequest-Cp0QjioM.js.map} +1 -1
- package/dist/chunks/{live-C2Sck5PO.js → live-D08wnrrZ.js} +3 -3
- package/dist/chunks/{live-C2Sck5PO.js.map → live-D08wnrrZ.js.map} +1 -1
- package/dist/chunks/{mutationExtras-HC7AC6zn.js → mutationExtras-BbDboF8F.js} +2 -2
- package/dist/chunks/{mutationExtras-HC7AC6zn.js.map → mutationExtras-BbDboF8F.js.map} +1 -1
- package/dist/chunks/{subscriptionStream-CaTWWJwt.js → subscriptionStream-CRj9aV4K.js} +2 -2
- package/dist/chunks/{subscriptionStream-CaTWWJwt.js.map → subscriptionStream-CRj9aV4K.js.map} +1 -1
- package/dist/client/ClientRouterContext.d.ts.map +1 -1
- package/dist/client/Head.d.ts.map +1 -1
- package/dist/client/createRoot.d.ts.map +1 -1
- package/dist/client/cspNonce.d.ts +33 -0
- package/dist/client/cspNonce.d.ts.map +1 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +17 -10
- package/dist/client/index.js.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/Email.d.ts +8 -0
- package/dist/email/Email.d.ts.map +1 -1
- package/dist/email/debugEmail.d.ts +4 -0
- package/dist/email/debugEmail.d.ts.map +1 -1
- package/dist/email/index.js +4 -4
- package/dist/email/index.js.map +4 -4
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/HttpRequest.d.ts +7 -0
- package/dist/http/HttpRequest.d.ts.map +1 -1
- package/dist/http/cspNonce.d.ts +37 -0
- package/dist/http/cspNonce.d.ts.map +1 -0
- package/dist/http/index.d.ts +1 -0
- package/dist/http/index.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.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/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/email/MailManager.d.ts +7 -0
- package/dist/services/email/MailManager.d.ts.map +1 -1
- package/dist/services/email/config.d.ts +6 -0
- package/dist/services/email/config.d.ts.map +1 -1
- package/dist/services/email/drivers/AcsDriver.d.ts +97 -0
- package/dist/services/email/drivers/AcsDriver.d.ts.map +1 -0
- package/dist/services/email/drivers/types.d.ts +7 -0
- package/dist/services/email/drivers/types.d.ts.map +1 -1
- package/dist/services/index.d.ts +2 -0
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +9 -9
- package/dist/services/index.js.map +4 -3
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts +2 -0
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/services/router/config.d.ts +17 -1
- package/dist/services/router/config.d.ts.map +1 -1
- package/dist/services/router/contentSecurityPolicy.d.ts +32 -0
- package/dist/services/router/contentSecurityPolicy.d.ts.map +1 -0
- package/dist/services/router/staticCache.d.ts +1 -0
- package/dist/services/router/staticCache.d.ts.map +1 -1
- package/dist/services/router/staticDocument.d.ts +5 -1
- package/dist/services/router/staticDocument.d.ts.map +1 -1
- package/dist/services/router/streamQueryInjection.d.ts +5 -3
- package/dist/services/router/streamQueryInjection.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/testing/index.js +2 -2
- package/dist/vitest/index.js +1 -1
- package/package.json +9 -1
- package/dist/chunk-7xy7ebkx.js +0 -117
- package/dist/chunk-arb0qkrm.js +0 -6
- package/dist/chunk-es05kqtp.js +0 -15
- package/dist/chunk-pvx66dq2.js +0 -5
- package/dist/chunk-tgbky7fc.js +0 -5
- package/dist/chunks/ThemeProvider-G2g5Z1ZS.js.map +0 -1
- /package/dist/{chunk-51n7yky9.js.map → chunk-4reyxar1.js.map} +0 -0
- /package/dist/{chunk-spsheyx9.js.map → chunk-61mcmhjp.js.map} +0 -0
- /package/dist/{chunk-tv33103m.js.map → chunk-93j09zw7.js.map} +0 -0
- /package/dist/{chunk-2v83pskm.js.map → chunk-97g2qc7j.js.map} +0 -0
- /package/dist/{chunk-gk12v51y.js.map → chunk-xxep62yg.js.map} +0 -0
- /package/dist/{chunk-4k62r4hv.js.map → chunk-xzt117g6.js.map} +0 -0
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{db as P9}from"../chunk-8m9kgynj.js";import{Ab as B9,Bb as j9,Cb as F9,Db as M9,Eb as L9,Fb as y4,Gb as O6,Hb as w,Ib as N9,Jb as D9,Kb as H9,Lb as U9,Mb as x9,Nb as O9,Ob as S9,Pb as R9,Qb as _9,Rb as k9,Sb as f9,Tb as C9,Ub as V9,Vb as T9,eb as bZ,fb as wZ,gb as qZ,hb as vZ,ib as IZ,jb as w4,kb as yZ,lb as V4,mb as T4,nb as E1,ob as AZ,pb as hZ,qb as Z9,ub as $9,vb as J9,wb as Q9,xb as Y9,yb as G9,zb as X9}from"../chunk-nbry43s8.js";import{Yb as v4}from"../chunk-2g2cntdm.js";import{Ad as EZ,Bd as mZ,Cd as cZ,Dd as uZ,Ed as dZ,Fd as lZ,Gd as nZ,Hd as iZ,Id as sZ,Jd as oZ,Kd as aZ,Ld as tZ,Md as rZ,Nd as eZ,Od as W9,zd as gZ}from"../chunk-sxww1ka5.js";import{Pd as pZ}from"../chunk-mndcq5z1.js";import{$d as kZ,Qd as MZ,Rd as LZ,Sd as NZ,Td as DZ,Ud as HZ,Vd as UZ,Wd as xZ,Xd as OZ,Yd as SZ,Zd as RZ,_d as _Z,ae as fZ,be as CZ,ce as VZ,de as TZ,ie as PZ}from"../chunk-dbe8zgyb.js";import{je as K9,ke as z9}from"../chunk-2z160r1b.js";import"../chunk-vqq0z746.js";import{$f as g8,Af as U8,Ag as $Z,Be as M6,Bf as x8,Bg as JZ,Ce as H4,Cf as O8,De as r0,Df as S8,Ee as U4,Ef as R8,Fe as x4,Ff as _8,Gf as k8,If as f8,Ig as QZ,Je as R6,Jf as x6,Ke as _6,Kf as C8,Me as P5,Mg as YZ,Ne as b5,Oe as w5,Of as V8,Pe as q5,Pf as T8,Qe as v5,Qf as b8,Qg as A4,Re as I5,Rg as e,Se as y5,Te as A5,Tf as w8,Ue as h5,Uf as q8,Ve as l0,Vf as v8,We as g5,Wf as I8,Xe as E5,Ye as m5,Yf as y8,Ze as c5,Zf as A8,_e as u5,_f as h8,ag as E8,ah as KZ,bg as m8,bh as zZ,cg as c8,dg as u8,eg as p8,fg as d8,kg as U,lg as m,mg as l8,nf as e5,ng as n8,of as W8,og as i8,pf as Z8,pg as s8,qf as $8,qg as o8,rf as J8,se as F6,sf as Q8,sg as a8,te as f5,tg as t8,ue as C5,ug as r8,ve as V5,vg as e8,wg as WZ,xe as T5,yf as D8,zf as H8,zg as ZZ}from"../chunk-7xy7ebkx.js";import"../chunk-4f2xy9ws.js";import"../chunk-7sadg8d7.js";import{Ai as I1,Bi as p5,Ci as d5,Di as l5,Ei as n5,Fi as i5,Ri as LW,Si as NW,Vh as D4,Vi as s5,Wh as M4,Wi as o5,Xh as H1,Yi as a5,Zi as t5,_i as r5,aj as y1,oi as C4,si as J1,ui as a,yi as L4,zi as U1}from"../chunk-es05kqtp.js";import"../chunk-2qbfvb6m.js";import{lj as V}from"../chunk-zzmgz14a.js";import{tj as j8,uj as F8,vj as q1,wj as M8,xj as m0,yj as L8,zj as N8}from"../chunk-kzy4pyqb.js";import{Fj as G8,Gj as X8,Hj as B8}from"../chunk-ecyq52t3.js";import"../chunk-kjgy7sk0.js";import{ok as P8}from"../chunk-g1th116z.js";import{qk as Y8,rk as K8,sk as z8}from"../chunk-mnmz8n5k.js";import"../chunk-ng5qfkgp.js";import"../chunk-5qaxde5h.js";import"../chunk-htnbmbx1.js";import"../chunk-rnjjn09d.js";import{il as GZ,jl as XZ,kl as BZ,ll as jZ,nl as FZ}from"../chunk-pvx66dq2.js";import"../chunk-yzazktke.js";import{xl as _}from"../chunk-9ky5d5js.js";import"../chunk-a77w04sw.js";import"../chunk-qw6aa9fy.js";import"../chunk-y9pzr1wc.js";import"../chunk-nnn2f1ew.js";import"../chunk-xb9zjaes.js";import{Yl as i0}from"../chunk-fzy1z97a.js";import{Buffer as n0}from"buffer";class s0 extends U1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-s57n552b.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket??Y,J=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);J=J||void 0;let K=$ instanceof n0?$:$ instanceof Blob||$ instanceof File?n0.from(await $.arrayBuffer()):"",{sdk:z,client:G}=await this.connect();return Z?.throwIfAborted(),await G.send(new z.PutObjectCommand({Bucket:Y,Key:Q,Body:K,ContentType:J}),{abortSignal:Z}),Q}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:J,client:Q}=await this.connect();try{await Q.send(new J.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(Y){if(Y?.name==="NoSuchKey"||Y?.$metadata?.httpStatusCode===404)return;throw Y}}async*pages(W,{bucket:Z,signal:$}){let{sdk:J,client:Q}=await this.connect(),Y;do{$?.throwIfAborted();let K=await Q.send(new J.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:Y}),{abortSignal:$});yield(K.Contents??[]).map((z)=>({name:z.Key,size:z.Size??0,lastModified:z.LastModified??new Date(0)})),Y=K.IsTruncated?K.NextContinuationToken:void 0}while(Y)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){L4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect(),Y=0;for await(let K of this.pages(W,{...Z,bucket:$})){if(K.length===0)continue;Z.signal?.throwIfAborted();let G=(await Q.send(new J.DeleteObjectsCommand({Bucket:$,Delete:{Objects:K.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())}Y+=K.length}return Y}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,J;if(typeof W==="string")J=W;else $=W.bucket??$,J=W.name;if(!J)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();Z?.throwIfAborted();let K=await Y.send(new Q.GetObjectCommand({Bucket:$,Key:J}),{abortSignal:Z}),z=I1(K.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(z,{headers:{"Content-Type":K.ContentType,"Content-Length":K.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":K.LastModified?.toUTCString()||"",ETag:K.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:J,range:Q=null}=Z;if(!J)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect(),z;try{z=await K.send(new Y.GetObjectCommand({Bucket:$,Key:J,Range:Q?M4(Q):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new J1(await this.size({name:J,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new a(J);throw j}let G=H1(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:J}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect();try{return(await Q.send(new J.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(Y){if(Y?.name==="NotFound"||Y?.$metadata?.httpStatusCode===404)throw new a(Z);throw Y}}}import{Buffer as o0}from"buffer";import{Readable as UW}from"stream";function N4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function xW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class a0 extends U1{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 $,J,Q,Y;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket,J=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let K=$ instanceof o0?$:o0.from(await $.arrayBuffer()),z=await this.blob(Q,Y);return Z?.throwIfAborted(),await z.uploadData(K,{blobHTTPHeaders:J?{blobContentType:J}:void 0,abortSignal:Z}),Q}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let J=Z??this.config.container??process.env.BUCKET_NAME;if(!J)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let Y=(await this.serviceClient()).getContainerClient(J);for await(let K of Y.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:K.name,size:K.properties?.contentLength??0,lastModified:K.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,J=(await this.serviceClient()).getContainerClient(Z),Q=[];for await(let Y of J.listBlobsFlat({prefix:W}))Q.push(Y.name);return Q}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:J,range:Q=null}=W,Y=await this.blob($,J);Z?.throwIfAborted();let K,z,G=Q?.kind==="suffix"||Q?.kind==="offset"&&Q.end===null&&Q.start===0;if(Q&&G){let S=await this.size({name:$,bucket:J}),o=D4(Q,S);if(!o)throw new J1(S);K=o.start,z=o.length}else if(Q?.kind==="offset")K=Q.start,z=Q.end===null?void 0:Q.end-Q.start+1;let X;try{X=await Y.download(K,z,Z?{abortSignal:Z}:void 0)}catch(S){if(xW(S))throw new J1(await this.size({name:$,bucket:J}));if(N4(S))throw new a($);throw S}let B=H1(X.contentRange),j=Boolean(B),L=B?.total??X.contentLength??0,H=await OW(X);if(H instanceof ReadableStream)H=I1(H,Z);return Z?.throwIfAborted(),{body:H,start:B?.start??0,end:B?.end??L-1,total:L,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,J=await this.blob(Z,$);try{return(await J.getProperties()).contentLength??0}catch(Q){if(N4(Q))throw new a(Z);throw Q}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{await J.delete()}catch(Q){if(N4(Q))return;throw Q}}}async function OW(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return UW.toWeb(W.readableStreamBody);return null}function SW(W){return W}class O4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class A1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var t0=1000,RW=60000,_W=`
|
|
2
|
+
import{db as v9}from"../chunk-8m9kgynj.js";import{Ab as L9,Bb as N9,Cb as D9,Db as H9,Eb as U9,Fb as g4,Gb as _6,Hb as w,Ib as x9,Jb as O9,Kb as S9,Lb as R9,Mb as _9,Nb as k9,Ob as f9,Pb as C9,Qb as V9,Rb as T9,Sb as P9,Tb as b9,Ub as w9,Vb as q9,eb as IZ,fb as yZ,gb as AZ,hb as hZ,ib as EZ,jb as y4,kb as gZ,lb as w4,mb as q4,nb as c1,ob as mZ,pb as cZ,qb as Y9,ub as K9,vb as G9,wb as z9,xb as X9,yb as F9,zb as M9}from"../chunk-mxt88hhp.js";import{Yb as h4}from"../chunk-2kkv8515.js";import{Ad as pZ,Bd as dZ,Cd as lZ,Dd as nZ,Ed as sZ,Fd as oZ,Gd as aZ,Hd as tZ,Id as rZ,Jd as eZ,Kd as W9,Ld as Z9,Md as $9,Nd as J9,Od as Q9,zd as uZ}from"../chunk-pab6ye4d.js";import{Pd as iZ}from"../chunk-mndcq5z1.js";import{$d as TZ,Qd as HZ,Rd as UZ,Sd as xZ,Td as OZ,Ud as SZ,Vd as RZ,Wd as _Z,Xd as kZ,Yd as fZ,Zd as CZ,_d as VZ,ae as PZ,be as bZ,ce as wZ,de as qZ,ie as vZ}from"../chunk-zwbpcch0.js";import{je as B9,ke as j9}from"../chunk-mzqhn72h.js";import"../chunk-vqq0z746.js";import{$f as u8,Af as R8,Ag as KZ,Be as D6,Bf as _8,Bg as GZ,Ce as x4,Cf as k8,De as Z6,Df as f8,Ee as O4,Ef as C8,Eg as zZ,Fe as S4,Ff as V8,Gf as T8,If as P8,Je as f6,Jf as R6,Jg as XZ,Ke as C6,Kf as b8,Me as v5,Ne as I5,Ng as BZ,Oe as y5,Of as w8,Pe as A5,Pf as q8,Qe as h5,Qf as I8,Re as E5,Rg as m4,Se as g5,Sg as e,Te as m5,Tf as y8,Ue as c5,Uf as A8,Ve as o0,Vf as h8,We as u5,Wf as E8,Xe as p5,Ye as d5,Yf as g8,Ze as l5,Zf as m8,_e as n5,_f as c8,ag as p8,bg as d8,bh as jZ,cg as l8,ch as FZ,dg as n8,eg as i8,fg as s8,kg as U,lg as m,mg as o8,nf as J8,ng as a8,of as Q8,og as t8,pf as Y8,pg as r8,qf as K8,qg as e8,rf as G8,se as N6,sf as z8,sg as WZ,te as P5,tg as ZZ,ue as b5,ug as $Z,ve as w5,vg as JZ,wg as QZ,xe as q5,yf as O8,zf as S8,zg as YZ}from"../chunk-ff22412e.js";import"../chunk-ewknbs3b.js";import"../chunk-bxxd1awv.js";import{Ci as D4,Di as U1,Ei as A1,Fi as i5,Gi as s5,Hi as o5,Ii as a5,Ji as t5,Vi as HW,Wh as U4,Wi as UW,Xh as N4,Yh as H1,Zi as r5,_i as e5,aj as W8,bj as Z8,cj as $8,ej as h1,si as b4,wi as J1,yi as a}from"../chunk-dqgn4wgf.js";import"../chunk-vpqzzrkn.js";import{pj as V}from"../chunk-b2n74m40.js";import{Aj as H8,Bj as d0,Cj as U8,Dj as x8,xj as N8,yj as D8,zj as v1}from"../chunk-xhc16pv1.js";import{Jj as F8,Kj as M8,Lj as L8}from"../chunk-kz15j07h.js";import"../chunk-sg78cmd1.js";import{sk as v8}from"../chunk-yxge0cem.js";import{uk as X8,vk as B8,wk as j8}from"../chunk-mddazdpt.js";import"../chunk-bcfcwbp4.js";import"../chunk-64hxqsqx.js";import"../chunk-t0qs2q9j.js";import"../chunk-agc5bqdt.js";import{ml as _4,nl as MZ,ol as LZ,pl as NZ,rl as DZ}from"../chunk-yw9mn5w7.js";import"../chunk-t4z6rkvw.js";import{Bl as _}from"../chunk-jkf5kjaz.js";import"../chunk-ha4er085.js";import"../chunk-by0afyps.js";import"../chunk-1yq2b55s.js";import"../chunk-ahss6dcp.js";import"../chunk-y167pt0p.js";import{am as y1}from"../chunk-zpqcawmq.js";import{Buffer as a0}from"buffer";class t0 extends U1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-0kfrwbhg.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:Z}={}){Z?.throwIfAborted();let $,J,Q,Y=process.env.BUCKET_NAME;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket??Y,J=W.contentType||($ instanceof Blob||$ instanceof File?$.type:void 0);J=J||void 0;let K=$ instanceof a0?$:$ instanceof Blob||$ instanceof File?a0.from(await $.arrayBuffer()):"",{sdk:G,client:z}=await this.connect();return Z?.throwIfAborted(),await z.send(new G.PutObjectCommand({Bucket:Y,Key:Q,Body:K,ContentType:J}),{abortSignal:Z}),Q}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:J,client:Q}=await this.connect();try{await Q.send(new J.DeleteObjectCommand({Bucket:$,Key:Z}))}catch(Y){if(Y?.name==="NoSuchKey"||Y?.$metadata?.httpStatusCode===404)return;throw Y}}async*pages(W,{bucket:Z,signal:$}){let{sdk:J,client:Q}=await this.connect(),Y;do{$?.throwIfAborted();let K=await Q.send(new J.ListObjectsV2Command({Bucket:Z??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:Y}),{abortSignal:$});yield(K.Contents??[]).map((G)=>({name:G.Key,size:G.Size??0,lastModified:G.LastModified??new Date(0)})),Y=K.IsTruncated?K.NextContinuationToken:void 0}while(Y)}async*objects(W,Z={}){for await(let $ of this.pages(W,Z))yield*$}async deletePrefix(W,Z={}){D4(W);let $=Z.bucket??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect(),Y=0;for await(let K of this.pages(W,{...Z,bucket:$})){if(K.length===0)continue;Z.signal?.throwIfAborted();let z=(await Q.send(new J.DeleteObjectsCommand({Bucket:$,Delete:{Objects:K.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:Z.signal}))?.Errors??[];if(z.length>0){let X=z[0];throw Error(`S3 could not delete ${z.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}Y+=K.length}return Y}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,J;if(typeof W==="string")J=W;else $=W.bucket??$,J=W.name;if(!J)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();Z?.throwIfAborted();let K=await Y.send(new Q.GetObjectCommand({Bucket:$,Key:J}),{abortSignal:Z}),G=A1(K.Body.transformToWebStream(),Z);return Z?.throwIfAborted(),new Response(G,{headers:{"Content-Type":K.ContentType,"Content-Length":K.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":K.LastModified?.toUTCString()||"",ETag:K.ETag||""}})}async read(W){let Z=typeof W==="string"?{name:W}:W,$=Z.bucket??process.env.BUCKET_NAME,{name:J,range:Q=null}=Z;if(!J)throw Error("Object name has to be specified");let{sdk:Y,client:K}=await this.connect(),G;try{G=await K.send(new Y.GetObjectCommand({Bucket:$,Key:J,Range:Q?N4(Q):void 0}))}catch(j){if(j?.name==="InvalidRange"||j?.$metadata?.httpStatusCode===416)throw new J1(await this.size({name:J,bucket:$}));if(j?.name==="NoSuchKey"||j?.$metadata?.httpStatusCode===404)throw new a(J);throw j}let z=H1(G.ContentRange),X=Boolean(z)&&G.$metadata?.httpStatusCode===206,B=z?.total??G.ContentLength??0;return{body:G.Body.transformToWebStream(),start:z?.start??0,end:z?.end??B-1,total:B,partial:X,type:G.ContentType??"application/octet-stream",etag:G.ETag||void 0,lastModified:G.LastModified,name:J}}async size(W){let Z=typeof W==="string"?W:W.name,$=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:J,client:Q}=await this.connect();try{return(await Q.send(new J.HeadObjectCommand({Bucket:$,Key:Z}))).ContentLength??0}catch(Y){if(Y?.name==="NotFound"||Y?.$metadata?.httpStatusCode===404)throw new a(Z);throw Y}}}import{Buffer as r0}from"buffer";import{Readable as SW}from"stream";function H4(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function RW(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class e0 extends U1{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 $,J,Q,Y;if(W instanceof Blob)$=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,J=W.type;else $=W.body,Q=W.name,Y=W.bucket,J=W.contentType??($ instanceof Blob||$ instanceof File?$.type:void 0);let K=$ instanceof r0?$:r0.from(await $.arrayBuffer()),G=await this.blob(Q,Y);return Z?.throwIfAborted(),await G.uploadData(K,{blobHTTPHeaders:J?{blobContentType:J}:void 0,abortSignal:Z}),Q}async*objects(W,{bucket:Z,signal:$}={}){$?.throwIfAborted();let J=Z??this.config.container??process.env.BUCKET_NAME;if(!J)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let Y=(await this.serviceClient()).getContainerClient(J);for await(let K of Y.listBlobsFlat({prefix:W}))$?.throwIfAborted(),yield{name:K.name,size:K.properties?.contentLength??0,lastModified:K.properties?.lastModified??new Date(0)}}async list(W){let Z=this.config.container??process.env.BUCKET_NAME,J=(await this.serviceClient()).getContainerClient(Z),Q=[];for await(let Y of J.listBlobsFlat({prefix:W}))Q.push(Y.name);return Q}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:J,range:Q=null}=W,Y=await this.blob($,J);Z?.throwIfAborted();let K,G,z=Q?.kind==="suffix"||Q?.kind==="offset"&&Q.end===null&&Q.start===0;if(Q&&z){let S=await this.size({name:$,bucket:J}),o=U4(Q,S);if(!o)throw new J1(S);K=o.start,G=o.length}else if(Q?.kind==="offset")K=Q.start,G=Q.end===null?void 0:Q.end-Q.start+1;let X;try{X=await Y.download(K,G,Z?{abortSignal:Z}:void 0)}catch(S){if(RW(S))throw new J1(await this.size({name:$,bucket:J}));if(H4(S))throw new a($);throw S}let B=H1(X.contentRange),j=Boolean(B),L=B?.total??X.contentLength??0,H=await _W(X);if(H instanceof ReadableStream)H=A1(H,Z);return Z?.throwIfAborted(),{body:H,start:B?.start??0,end:B?.end??L-1,total:L,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,J=await this.blob(Z,$);try{return(await J.getProperties()).contentLength??0}catch(Q){if(H4(Q))throw new a(Z);throw Q}}async delete(W){let Z=typeof W==="string"?W:W.name,$=typeof W==="string"?void 0:W.bucket,J=await this.blob(Z,$);try{await J.delete()}catch(Q){if(H4(Q))return;throw Q}}}async function _W(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return SW.toWeb(W.readableStreamBody);return null}function kW(W){return W}class R4 extends Error{code="ERR_RATE_LIMITER_TIMEOUT";constructor(W){super(`RedisRateLimiter: Redis did not answer within ${W}ms.`);this.name="RedisRateLimiterTimeoutError"}}class E1 extends Error{code="ERR_RATE_LIMITER_DISCONNECTED";constructor(){super("RedisRateLimiter: the Redis client is not connected.");this.name="RedisRateLimiterDisconnectedError"}}var W6=1000,fW=60000,CW=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
|
@@ -26,7 +26,7 @@ current = redis.call("INCRBY", currentKey, cost)
|
|
|
26
26
|
redis.call("PEXPIRE", currentKey, window * 2)
|
|
27
27
|
|
|
28
28
|
return {1, current, previous}
|
|
29
|
-
`;class
|
|
29
|
+
`;class $6 extends O4{injectedClient;prefix;mode;fallback;timeout;onError;scriptSha=null;down=!1;probing=!1;lastProbeAt=0;seenConnected=new WeakSet;loggedAt=-1/0;failuresSinceLog=0;fallbacksSinceLog=0;constructor(W={}){super();this.injectedClient=W.client,this.prefix=W.prefix??"gemi:rl",this.mode=W.onRedisError??(W.failOpen===void 0?"memory":W.failOpen?"open":"closed"),this.fallback=W.fallback??new S4,this.timeout=W.timeout??250,this.onError=W.onError}async consume(W){let{key:Z,limit:$,window:J}=W,Q=W.cost??1,Y=Date.now(),K=x4(Y,J),G=Y-K,z=K/J;if(this.down)return this.probe(),this.degrade(W,Y);try{let X=this.client;if(X.connected===!1&&this.seenConnected.has(X))throw new E1;let B=await this.withTimeout(this.run(X,[`${this.prefix}:${Z}:${z}`,`${this.prefix}:${Z}:${z-1}`],[String($),String(J),String(G),String(Q)]),()=>{this.scriptSha=null});if(X.connected===!0)this.seenConnected.add(X);let[j,L,H]=(Array.isArray(B)?B:[]).map(Number);return Z6({allowed:j===1,current:Number.isFinite(L)?L:0,previous:Number.isFinite(H)?H:0,now:Y,elapsed:G,window:J,limit:$,cost:Q})}catch(X){if(!this.down)this.down=!0,this.lastProbeAt=Date.now();return this.report(X),this.degrade(W,Y)}}async degrade(W,Z){let{limit:$,window:J}=W,Q=W.cost??1;if(this.fallbacksSinceLog+=1,this.mode==="memory")return await this.fallback.consume(W);if(this.mode==="closed")return{allowed:!1,limit:$,remaining:0,resetAt:Z+J,retryAfter:J};return{allowed:!0,limit:$,remaining:Math.max(0,Math.floor($-Q)),resetAt:x4(Z,J)+J,retryAfter:0}}probe(){let W=Date.now();if(this.probing||W-this.lastProbeAt<W6)return;this.probing=!0,this.lastProbeAt=W,(async()=>{let $=this.client;if($.connected===!1&&this.seenConnected.has($))throw new E1;if(await this.withTimeout($.send("PING",[]),void 0,this.timeout>0?this.timeout:W6),$.connected===!0)this.seenConnected.add($)})().then(()=>{if(this.probing=!1,this.down=!1,!this.onError)this.logRecovery()},($)=>{this.probing=!1;try{this.report($)}catch{}})}report(W){if(this.onError){this.onError(W);return}this.failuresSinceLog+=1;let Z=Date.now();if(Z-this.loggedAt<fW)return;let $=this.mode==="memory"?"counting in memory":this.mode==="open"?"admitting every request":"refusing every request",J=this.loggedAt===-1/0?"":` Since the last report: ${this.failuresSinceLog} failures, ${this.fallbacksSinceLog} calls answered without Redis.`;console.error(`[gemi] RedisRateLimiter: Redis failed, ${$} until it answers again.${J}`,W),this.loggedAt=Z,this.failuresSinceLog=0,this.fallbacksSinceLog=0}logRecovery(){console.info(`[gemi] RedisRateLimiter: Redis answers again; counting in Redis (${this.fallbacksSinceLog} calls answered without it since the last report).`),this.loggedAt=-1/0,this.failuresSinceLog=0,this.fallbacksSinceLog=0}withTimeout(W,Z,$=this.timeout){if(!($>0)||!Number.isFinite($))return W;let J,Q=new Promise((Y,K)=>{J=setTimeout(()=>{Z?.(),K(new R4($))},$)});return W.catch(()=>{}),Promise.race([W,Q]).finally(()=>clearTimeout(J))}get client(){if(this.injectedClient)return this.injectedClient;let W=_(),Z=W.bound(h1)?W.make(h1).client:void 0;if(!Z)throw Error("RedisRateLimiter could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisRateLimiter({ client }).");return Z}async run(W,Z,$){let J=[String(Z.length),...Z,...$];try{return await W.send("EVALSHA",[await this.load(W),...J])}catch(Q){if(!VW(Q))throw Q;return this.scriptSha=null,await W.send("EVALSHA",[await this.load(W),...J])}}load(W){if(!this.scriptSha)this.scriptSha=Promise.resolve(W.send("SCRIPT",["LOAD",CW])).then(String).catch((Z)=>{throw this.scriptSha=null,Z});return this.scriptSha}}function VW(W){return String(W?.message??W).includes("NOSCRIPT")}function x1(W){let Z=/^\s*"?([^"<]*?)"?\s*<([^>]+)>\s*$/.exec(W);if(!Z)return{address:W.trim()};let[,$,J]=Z;return $?{address:J.trim(),displayName:$}:{address:J.trim()}}function TW(W){if(W.contentType)return W.contentType;return Bun.file(W.filename).type.split(";")[0]||"application/octet-stream"}class k4 extends _4{config;provider="acs";supportsIdempotencyKey=!1;clientPromise=null;constructor(W={}){super();this.config=W}async client(){if(this.config.client)return this.config.client;return this.clientPromise??=(async()=>{let W;try{W=await import("@azure/communication-email")}catch{throw Error("AcsDriver requires the '@azure/communication-email' package. Install it with `bun add @azure/communication-email`, or pass a pre-built `client`.")}let Z=this.config.endpoint??process.env.AZURE_COMMUNICATION_ENDPOINT,$=this.config.connectionString??process.env.AZURE_COMMUNICATION_CONNECTION_STRING;if(Z){let J=this.config.credential;if(!J){let Q;try{Q=await import("@azure/identity")}catch{throw Error("AcsDriver with an `endpoint` and no `credential` requires the '@azure/identity' package (for DefaultAzureCredential). Install it with `bun add @azure/identity`.")}J=new Q.DefaultAzureCredential}return new W.EmailClient(Z,J)}if($)return new W.EmailClient($);throw Error("AcsDriver needs an endpoint (AZURE_COMMUNICATION_ENDPOINT, authenticated with managed identity), a connection string (AZURE_COMMUNICATION_CONNECTION_STRING), or a `client`.")})(),this.clientPromise.catch(()=>{this.clientPromise=null}),this.clientPromise}static toMessage(W){let Z={senderAddress:x1(W.from).address,content:{subject:W.subject,html:W.html,...W.text?{plainText:W.text}:{}},recipients:{to:W.to.map(x1),...W.cc?.length?{cc:W.cc.map(x1)}:{},...W.bcc?.length?{bcc:W.bcc.map(x1)}:{}}};if(W.replyTo?.length)Z.replyTo=W.replyTo.map(x1);if(W.headers&&Object.keys(W.headers).length)Z.headers=W.headers;if(W.attachments?.length)Z.attachments=W.attachments.map(($)=>({name:$.filename,contentType:TW($),contentInBase64:Buffer.from($.content).toString("base64")}));return Z}async send(W){return(await this.deliver(W)).ok}async deliver(W){if(W.scheduledAt)throw Error(`AcsDriver can't schedule a send (scheduledAt: "${W.scheduledAt}"): Azure Communication Services has no scheduled delivery. Send from a delayed job instead.`);let Z=k4.toMessage(W),$=await this.client(),J=crypto.randomUUID();try{let Q=await $.beginSend(Z,{operationId:J}),Y=Q.getOperationState?.();if(Y?.status==="failed"||Y?.status==="canceled")return console.error(Y.error),{ok:!1,id:J,error:Y.error};return{ok:!0,id:Q.getResult?.()?.id??J}}catch(Q){return console.error(Q),{ok:!1,id:null,error:Q}}}}import{createHash as A4,randomBytes as t,timingSafeEqual as PW}from"crypto";var g1=Object.freeze({"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"});function J6(W,Z){let $=W.client.name?b(W.client.name):"An application",J=W.scopes.map((Y)=>`<li><strong>${b(Y.name)}</strong><br><span>${b(Y.description)}</span></li>`).join(""),Q=Object.entries(W.form.fields).map(([Y,K])=>`<input type="hidden" name="${b(Y)}" value="${b(K)}">`).join("");return`<!doctype html>
|
|
30
30
|
<html lang="en">
|
|
31
31
|
<head>
|
|
32
32
|
<meta charset="utf-8">
|
|
@@ -61,12 +61,12 @@ return {1, current, previous}
|
|
|
61
61
|
</form>
|
|
62
62
|
</main>
|
|
63
63
|
</body>
|
|
64
|
-
</html>`}function Z6(W){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Authorization failed</title></head><body style="font-family: system-ui, sans-serif; padding: 24px"><h1 style="font-size: 1.2rem">This connection could not be authorized</h1><p>${b(W)}</p></body></html>`}function b(W){return W.replace(/[&<>"']/g,(Z)=>`&#${Z.charCodeAt(0)};`)}var S4="gmcp_at_",R4="gmcp_rt_",$6="gmcp_ac_",CW="gmcp_c_",VW="gmcp_cs_",_4="gemi.mcp.oauth.ticket.v1",J6="gemi.mcp.oauth.consent.v1",TW=600000,Q6=120000,P4=16384,PW={limit:20,window:3600},bW={limit:60,window:60},g1=["none","client_secret_post","client_secret_basic"];class M extends Error{error;description;status;headers;constructor(W,Z,$=400,J={}){super(Z);this.error=W;this.description=Z;this.status=$;this.headers=J}}class L6{options;name="oauth";context;issuer;base;accessTtl;refreshTtl;constructor(W){this.options=W;let Z=W?.store;for(let $ of["createClient","findClient","saveCode","findCode","saveToken","findToken","use","revokeFamily"])if(typeof Z?.[$]!=="function")throw Error(`McpOAuthServer: store.${$} is missing. Use MemoryMcpOAuthStore, or implement McpOAuthStore.`);if(typeof W.findUser!=="function")throw Error("McpOAuthServer: findUser(id) is required: it loads the user a token was issued to.");if(W.consentPath!==void 0&&!/^\/[^/\\]/.test(W.consentPath))throw Error('McpOAuthServer: consentPath must be a path on this app, like "/oauth/consent".');this.accessTtl=Y6("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=Y6("refreshTokenTtl",W.refreshTokenTtl,2592000)}get store(){return this.options.store}boot(W){this.context=W;let Z=new URL(W.resource);this.issuer=Z.origin,this.base=`${Z.pathname}/oauth`}async resolve(W){let Z=w4(W);if(!Z?.startsWith(S4))return null;let $=await this.store.findToken(E(Z)),J=(Y)=>({ok:!1,error:"invalid_token",description:Y});if(!$||$.kind!=="access")return J("The access token is not valid.");if($.expiresAt<=Date.now())return J("The access token expired.");if($.resource!==this.context.resource)return J("The access token was not issued for this server.");let Q=await this.options.findUser($.userId);if(!Q)return J("The access token is not valid.");return{ok:!0,principal:{user:Q,via:this.name,id:$.familyId,scopes:$.scopes,clientId:$.clientId}}}challenge(){let W=this.scopeNames().join(" ");return`Bearer resource_metadata="${this.resourceMetadataUrl()}", scope="${W}"`}async handle(W){let Z=new URL(W.url).pathname,Q={[`/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-protected-resource"]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-authorization-server"]:{methods:["GET"],cors:!0,run:()=>this.serverMetadata()},[`${this.base}/register`]:{methods:["POST"],cors:!0,run:()=>this.register(W)},[`${this.base}/authorize`]:{methods:["GET"],cors:!1,run:()=>this.authorize(W)},[`${this.base}/consent`]:{methods:["GET","POST"],cors:!1,run:()=>W.method==="POST"?this.decide(W):this.consentScreen(W)},[`${this.base}/token`]:{methods:["POST"],cors:!0,run:()=>this.token(W)},[`${this.base}/revoke`]:{methods:["POST"],cors:!0,run:()=>this.revoke(W)}}[Z];if(!Q)return null;if(Z===`${this.base}/register`&&this.options.registration===!1)return null;let Y=Q.cors?wW:{};if(W.method==="OPTIONS"&&Q.cors)return new Response(null,{status:204,headers:{...Y,"Access-Control-Allow-Methods":Q.methods.join(", "),"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}});if(!Q.methods.includes(W.method))return new Response(null,{status:405,headers:{...Y,Allow:Q.methods.join(", ")}});let K;try{K=await Q.run()}catch(z){if(!(z instanceof M))throw z;K=x1({error:z.error,error_description:z.description},z.status,z.headers)}for(let[z,G]of Object.entries(Y))K.headers.set(z,G);return K}async consent(W,Z){if(!Z)return null;let $=E1(_4,"gat1",W);if(!$)return null;let J=await this.store.findClient($.c);if(!J||!J.redirectUris.some((z)=>f4(z,$.r)))return null;let Q=String(Z.id),Y=T4(J6,"gcs1",{t:K6(W),u:Q,exp:$.exp}),K=new Map(this.context.registry.scopes().map((z)=>[z.name,z.description]));return{client:{id:J.clientId,name:J.clientName,redirectHost:new URL($.r).host},scopes:$.s.map((z)=>({name:z,description:K.get(z)??z})),user:{id:Q,label:this.userLabel(Z)},form:{action:`${this.issuer}${this.base}/consent`,method:"POST",fields:{request:W,csrf:Y}}}}resourceMetadata(){return x1({resource:this.context.resource,authorization_servers:[this.issuer],scopes_supported:this.scopeNames(),bearer_methods_supported:["header"]})}serverMetadata(){return x1({issuer:this.issuer,authorization_endpoint:`${this.issuer}${this.base}/authorize`,token_endpoint:`${this.issuer}${this.base}/token`,...this.options.registration===!1?{}:{registration_endpoint:`${this.issuer}${this.base}/register`},revocation_endpoint:`${this.issuer}${this.base}/revoke`,scopes_supported:this.scopeNames(),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],token_endpoint_auth_methods_supported:g1,revocation_endpoint_auth_methods_supported:g1,code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,client_id_metadata_document_supported:!1})}async register(W){let Z=this.options.registration||{},$=await V4(`mcp-oauth-register:${M6(new C4(W,{},"api",`${this.base}/register`))}`,Z.rateLimit??PW);if($!==null)throw new M("slow_down","Too many registrations from this address.",429,{"Retry-After":String($)});if(!/^application\/json\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new M("invalid_client_metadata","Send the client metadata as application/json.");let J;try{J=JSON.parse(await b4(W,P4))}catch{throw new M("invalid_client_metadata","The client metadata is not JSON, or is too large.")}if(typeof J!=="object"||J===null||Array.isArray(J))throw new M("invalid_client_metadata","The client metadata must be a JSON object.");let Q=J.redirect_uris;if(!Array.isArray(Q)||Q.length===0||Q.length>10)throw new M("invalid_redirect_uri","redirect_uris must list one to ten URIs.");for(let L of Q){let H=IW(L);if(H)throw new M("invalid_redirect_uri",`${String(L).slice(0,200)}: ${H}`);if(Z.allowRedirectUri&&Z.allowRedirectUri(new URL(L))!==!0)throw new M("invalid_redirect_uri",`${L}: this server does not accept it.`)}let Y=J.token_endpoint_auth_method??"client_secret_basic";if(!g1.includes(Y))throw new M("invalid_client_metadata",`token_endpoint_auth_method must be one of ${g1.join(", ")}.`);let K=J.grant_types??["authorization_code"];if(!Array.isArray(K)||K.some((L)=>L!=="authorization_code"&&L!=="refresh_token"))throw new M("invalid_client_metadata","grant_types may only be authorization_code and refresh_token.");let z=J.response_types??["code"];if(!Array.isArray(z)||z.some((L)=>L!=="code"))throw new M("invalid_client_metadata","response_types may only be code.");let G=X6(J.client_name,100,"client_name"),X=X6(J.client_uri,512,"client_uri");if(X!==null&&!vW(X))throw new M("invalid_client_metadata","client_uri must be an https URL.");let B=Y==="none"?null:`${VW}${t(32).toString("base64url")}`,j={clientId:`${CW}${t(16).toString("base64url")}`,clientSecretHash:B?E(B):null,tokenEndpointAuthMethod:Y,redirectUris:[...Q],clientName:G,clientUri:X,createdAt:Date.now()};return await this.store.createClient(j),x1({client_id:j.clientId,client_id_issued_at:Math.floor(j.createdAt/1000),...B?{client_secret:B,client_secret_expires_at:0}:{},redirect_uris:j.redirectUris,token_endpoint_auth_method:Y,grant_types:K,response_types:z,...G?{client_name:G}:{},...X?{client_uri:X}:{}},201)}async authorize(W){let Z=new URL(W.url).searchParams;for(let S of new Set(Z.keys()))if(Z.getAll(S).length>1)return A(`The parameter ${S} was sent more than once.`);let $=Z.get("client_id"),J=$?await this.store.findClient($):null;if(!J)return A("The application is not registered with this server.");let Q=Z.get("redirect_uri")??(J.redirectUris.length===1?J.redirectUris[0]:null);if(!Q||!J.redirectUris.some((S)=>f4(S,Q)))return A("The redirect URI is not one the application registered.");let Y=Z.get("state"),K=(S,o)=>this.redirectBack(Q,Y,{error:S,error_description:o});if(Z.get("response_type")!=="code")return K("unsupported_response_type","Only response_type=code is supported.");let z=Z.get("code_challenge");if(Z.get("code_challenge_method")!=="S256"||!z||!/^[A-Za-z0-9_-]{43}$/.test(z))return K("invalid_request","PKCE is required: code_challenge with code_challenge_method=S256.");let G=Z.get("resource");if(G!==null&&!B6(G,this.context.resource))return K("invalid_target","The resource is not this server's.");if(Y!==null&&Y.length>2048)return K("invalid_request","state is too long.");let X=this.scopeNames(),B=Z.get("scope"),j=X;if(B!==null&&B.trim()!==""){if(j=[...new Set(B.split(" ").filter((S)=>X.includes(S)))],j.length===0)return K("invalid_scope","None of the requested scopes exist here.")}let L=T4(_4,"gat1",{c:J.clientId,r:Q,s:j,cc:z,st:Y,n:t(16).toString("base64url"),exp:Date.now()+TW}),H=this.options.consentPath??`${this.base}/consent`;return k4(`${this.issuer}${H}?request=${encodeURIComponent(L)}`,302)}async consentScreen(W){let Z=new URL(W.url).searchParams.get("request"),$=await this.sessionUser(W);if(!$){let Q=`${this.base}/consent?request=${encodeURIComponent(Z??"")}`,Y=this.options.signInPath??_(e).config.signInPath;return k4(`${Y}${Y.includes("?")?"&":"?"}redirect=${encodeURIComponent(Q)}`,302)}let J=await this.consent(Z,$);if(!J)return A("This authorization request has expired or is not valid. Start again from the application.");return new Response(W6(J,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:h1})}async decide(W){let Z=W.headers.get("origin");if(!(Z!==null?Z===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return A("This decision did not come from this site's consent page.",403);if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))return A("The decision must be a form post.");let J;try{J=new URLSearchParams(await b4(W,P4))}catch{return A("The decision is too large.")}let Q=J.get("request"),Y=E1(_4,"gat1",Q),K=E1(J6,"gcs1",J.get("csrf")),z=await this.sessionUser(W);if(!Y||!K||!z||K.t!==K6(Q)||K.u!==String(z.id))return A("This authorization request has expired or is not valid. Start again from the application.",403);let G=await this.store.findClient(Y.c);if(!G||!G.redirectUris.some((B)=>f4(B,Y.r)))return A("The application is not registered with this server.");if(!await this.store.use(`ticket:${Y.n}`,Y.exp))return A("This request was already answered. Start again from the application.");if(J.get("decision")!=="allow")return this.redirectBack(Y.r,Y.st,{error:"access_denied",error_description:"The user denied the request."},303);let X=`${$6}${t(32).toString("base64url")}`;return await this.store.saveCode({hash:E(X),clientId:G.clientId,userId:String(z.id),redirectUri:Y.r,codeChallenge:Y.cc,scopes:Y.s,resource:this.context.resource,familyId:t(16).toString("base64url"),expiresAt:Date.now()+Q6}),this.redirectBack(Y.r,Y.st,{code:X},303)}async token(W){let Z=await G6(W),$=await this.authenticateClient(W,Z),J=await V4(`mcp-oauth-token:${$.clientId}`,bW);if(J!==null)throw new M("slow_down","Too many token requests.",429,{"Retry-After":String(J)});let Q=Z.get("resource");if(Q!==null&&!B6(Q,this.context.resource))throw new M("invalid_target","The resource is not this server's.");switch(Z.get("grant_type")){case"authorization_code":{let Y=Z.get("code")??"",K=Y.startsWith($6)?await this.store.findCode(E(Y)):null;if(!K||K.clientId!==$.clientId)throw new M("invalid_grant","The authorization code is not valid.");if(!await this.store.use(K.hash,K.expiresAt+Q6))throw await this.store.revokeFamily(K.familyId),new M("invalid_grant","The authorization code was already used.");if(K.expiresAt<=Date.now())throw new M("invalid_grant","The authorization code expired.");if(Z.get("redirect_uri")!==null&&Z.get("redirect_uri")!==K.redirectUri)throw new M("invalid_grant","redirect_uri is not the one the code was issued to.");let z=Z.get("code_verifier");if(!z||!/^[A-Za-z0-9._~-]{43,128}$/.test(z)||!z6(qW(z),K.codeChallenge))throw new M("invalid_grant","The PKCE code_verifier does not match.");if(!await this.options.findUser(K.userId))throw new M("invalid_grant","The authorization code is not valid.");return await this.issue(K)}case"refresh_token":{let Y=Z.get("refresh_token")??"",K=Y.startsWith(R4)?await this.store.findToken(E(Y)):null;if(!K||K.kind!=="refresh"||K.clientId!==$.clientId)throw new M("invalid_grant","The refresh token is not valid.");if(K.expiresAt<=Date.now())throw new M("invalid_grant","The refresh token expired.");if(!await this.store.use(K.hash,K.expiresAt))throw await this.store.revokeFamily(K.familyId),new M("invalid_grant","The refresh token was already used.");if(K.resource!==this.context.resource)throw new M("invalid_grant","The refresh token was not issued for this server.");let z=K.scopes,G=Z.get("scope");if(G!==null&&G.trim()!==""){let X=[...new Set(G.split(" ").filter(Boolean))];if(X.some((B)=>!K.scopes.includes(B)))throw new M("invalid_scope","A refresh can only narrow the scopes that were granted.");z=X}if(!await this.options.findUser(K.userId))throw new M("invalid_grant","The refresh token is not valid.");return await this.issue({...K,scopes:z})}default:throw new M("unsupported_grant_type","grant_type must be authorization_code or refresh_token.")}}async issue(W){let Z=Date.now(),$=this.scopeNames(),J=W.scopes.filter((z)=>$.includes(z)),Q=`${S4}${t(32).toString("base64url")}`,Y=`${R4}${t(32).toString("base64url")}`,K={clientId:W.clientId,userId:W.userId,scopes:J,resource:W.resource,familyId:W.familyId};return await this.store.saveToken({...K,hash:E(Q),kind:"access",expiresAt:Z+this.accessTtl*1000}),await this.store.saveToken({...K,hash:E(Y),kind:"refresh",expiresAt:Z+this.refreshTtl*1000}),x1({access_token:Q,token_type:"Bearer",expires_in:this.accessTtl,refresh_token:Y,scope:J.join(" ")})}async revoke(W){let Z=await G6(W),$=await this.authenticateClient(W,Z),J=Z.get("token")??"";if(J.startsWith(S4)||J.startsWith(R4)){let Q=await this.store.findToken(E(J));if(Q&&Q.clientId===$.clientId)await this.store.revokeFamily(Q.familyId)}return new Response(null,{status:200,headers:{"Cache-Control":"no-store"}})}async authenticateClient(W,Z){let $=/^Basic\s+([A-Za-z0-9+/=]+)$/i.exec(W.headers.get("authorization")??""),J=Z.get("client_id"),Q=Z.get("client_secret");if($){let K=Buffer.from($[1],"base64").toString("utf8"),z=K.indexOf(":");if(z<0)throw r(!0);let G=j6(K.slice(0,z));if(G===null)throw r(!0);if(J!==null&&J!==G)throw r(!0);if(J=G,Q=j6(K.slice(z+1)),Q===null)throw r(!0)}let Y=J?await this.store.findClient(J):null;if(!Y)throw r(Boolean($));if(Y.tokenEndpointAuthMethod==="none"){if(Q)throw r(Boolean($));return Y}if(!Q||!Y.clientSecretHash||!z6(E(Q),Y.clientSecretHash))throw r(Boolean($));return Y}redirectBack(W,Z,$,J=302){let Q=new URL(W);for(let[Y,K]of Object.entries($))Q.searchParams.set(Y,K);if(Z!==null)Q.searchParams.set("state",Z);return Q.searchParams.set("iss",this.issuer),k4(Q.href,J)}async sessionUser(W){let Z=new C4(W,{},"api",this.base).cookies;return await F6(_(e),{cookies:Z,headers:{get:($)=>$.toLowerCase()==="user-agent"?W.headers.get("user-agent"):null}})}userLabel(W){if(this.options.userLabel)return this.options.userLabel(W);let Z=W;return String(Z.email??Z.name??Z.id)}scopeNames(){return this.context.registry.scopes().map((W)=>W.name)}resourceMetadataUrl(){return`${this.issuer}/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`}}var wW={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function Y6(W,Z,$){if(Z===void 0)return $;if(!Number.isInteger(Z)||Z<60)throw Error(`McpOAuthServer: ${W} must be a whole number of seconds, at least 60.`);return Z}function E(W){return q4("sha256").update(W).digest("hex")}function K6(W){return q4("sha256").update(W).digest("base64url")}function qW(W){return q4("sha256").update(W).digest("base64url")}function z6(W,Z){let $=Buffer.from(W),J=Buffer.from(Z);return $.length===J.length&&fW($,J)}function x1(W,Z=200,$={}){return new Response(JSON.stringify(W),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache",...$}})}function k4(W,Z){return new Response(null,{status:Z,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function A(W,Z=400){return new Response(Z6(W),{status:Z,headers:h1})}function r(W){return new M("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function b4(W,Z){let $=Number(W.headers.get("content-length"));if(Number.isFinite($)&&$>Z)throw Error("too large");if(!W.body)return"";let J=W.body.getReader(),Q=[],Y=0;for(;;){let{done:K,value:z}=await J.read();if(K)break;if(Y+=z.byteLength,Y>Z)throw await J.cancel(),Error("too large");Q.push(z)}return Buffer.concat(Q).toString("utf8")}async function G6(W){if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new M("invalid_request","Send the request as application/x-www-form-urlencoded.");let Z;try{Z=new URLSearchParams(await b4(W,P4))}catch{throw new M("invalid_request","The request is too large.")}for(let $ of new Set(Z.keys()))if(Z.getAll($).length>1)throw new M("invalid_request",`${$} was sent more than once.`);return Z}function X6(W,Z,$){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>Z||yW(W))throw new M("invalid_client_metadata",`${$} must be text of at most ${Z} characters.`);return W}function vW(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function N6(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function IW(W){if(typeof W!=="string"||W.length>2048)return"not a URI";let Z;try{Z=new URL(W)}catch{return"not an absolute URI"}if(Z.hash||W.includes("#"))return"must not have a fragment";if(Z.username||Z.password)return"must not carry credentials";if(Z.protocol==="https:")return null;if(Z.protocol==="http:"&&N6(Z))return null;return"must be https, or http on a loopback address"}function f4(W,Z){if(W===Z)return!0;let $,J;try{$=new URL(W),J=new URL(Z)}catch{return!1}return $.protocol==="http:"&&J.protocol==="http:"&&N6($)&&$.hostname===J.hostname&&$.pathname===J.pathname&&$.search===J.search&&!J.hash&&!J.username&&!J.password}function B6(W,Z){return W===Z||W===`${Z}/`}function yW(W){for(let Z=0;Z<W.length;Z++){let $=W.charCodeAt(Z);if($<32||$===127)return!0}return!1}function j6(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class D6{clients=new Map;codes=new Map;tokens=new Map;used=new Map;revoked=new Set;async createClient(W){this.clients.set(W.clientId,structuredClone(W))}async findClient(W){let Z=this.clients.get(W);return Z?structuredClone(Z):null}async saveCode(W){this.sweep(),this.codes.set(W.hash,structuredClone(W))}async findCode(W){let Z=this.codes.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async saveToken(W){this.sweep(),this.tokens.set(W.hash,structuredClone(W))}async findToken(W){let Z=this.tokens.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async use(W,Z){if(this.used.has(W))return!1;return this.used.set(W,Z),!0}async revokeFamily(W){this.revoked.add(W);for(let[Z,$]of this.tokens)if($.familyId===W)this.tokens.delete(Z);for(let[Z,$]of this.codes)if($.familyId===W)this.codes.delete(Z)}async families(W){let Z=new Map;for(let $ of this.tokens.values())if($.userId===W&&!this.revoked.has($.familyId)&&$.expiresAt>Date.now())Z.set($.familyId,{familyId:$.familyId,clientId:$.clientId,scopes:[...$.scopes]});return[...Z.values()]}sweep(W=Date.now()){for(let[Z,$]of this.codes)if($.expiresAt<=W)this.codes.delete(Z);for(let[Z,$]of this.tokens)if($.expiresAt<=W)this.tokens.delete(Z);for(let[Z,$]of this.used)if($<=W)this.used.delete(Z)}}class H6{clients;credentials;uses;usesModel;constructor(W){for(let[Z,$]of[["clients",["create","findUnique","findMany"]],["credentials",["create","findFirst","findMany","count","updateMany","deleteMany"]],["uses",["create","deleteMany"]]]){let J=W?.[Z],Q=$.filter((Y)=>typeof J?.[Y]!=="function");if(Q.length>0)throw Error(`PrismaMcpOAuthStore: models.${Z} must be a gemi ORM model or a Prisma delegate (it has no ${Q.join(", ")}()).`)}this.clients=W.clients,this.credentials=W.credentials,this.usesModel=W.uses,this.uses=new v4(W.uses)}async createClient(W){await this.clients.create({data:{clientId:W.clientId,clientSecretHash:W.clientSecretHash,tokenEndpointAuthMethod:W.tokenEndpointAuthMethod,redirectUris:[...W.redirectUris],clientName:W.clientName,clientUri:W.clientUri,createdAt:new Date(W.createdAt)}})}async findClient(W){let Z=await this.clients.findUnique({where:{clientId:W}});if(!Z)return null;return{clientId:Z.clientId,clientSecretHash:Z.clientSecretHash??null,tokenEndpointAuthMethod:Z.tokenEndpointAuthMethod,redirectUris:m1(Z.redirectUris),clientName:Z.clientName??null,clientUri:Z.clientUri??null,createdAt:c1(Z.createdAt)}}async saveCode(W){await this.credentials.create({data:{hash:W.hash,kind:"code",clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,redirectUri:W.redirectUri,codeChallenge:W.codeChallenge,expiresAt:new Date(W.expiresAt)}})}async findCode(W){let Z=await this.findLive(W,["code"]);if(!Z||Z.redirectUri==null||Z.codeChallenge==null)return null;return{hash:Z.hash,clientId:Z.clientId,userId:Z.userId,redirectUri:Z.redirectUri,codeChallenge:Z.codeChallenge,scopes:m1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:c1(Z.expiresAt)}}async saveToken(W){await this.credentials.create({data:{hash:W.hash,kind:W.kind,clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,expiresAt:new Date(W.expiresAt)}})}async findToken(W){let Z=await this.findLive(W,["access","refresh"]);if(!Z)return null;return{hash:Z.hash,kind:Z.kind,clientId:Z.clientId,userId:Z.userId,scopes:m1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:c1(Z.expiresAt)}}use(W,Z){return this.uses.consume(W,Z)}async revokeFamily(W){await this.credentials.updateMany({where:{familyId:W,revokedAt:null},data:{revokedAt:new Date}})}nonces(W={}){return new v4(this.usesModel,{prefix:W.prefix??"nonce:"})}async connectedApps(W,Z=new Date){let $=String(W),J=await this.credentials.findMany({where:{userId:$,kind:"refresh",expiresAt:{gt:Z}},orderBy:{createdAt:"asc"}}),Q=await this.revokedFamilies({userId:$}),Y=new Map;for(let X of J){if(Q.has(X.familyId))continue;if(!Y.has(X.familyId))Y.set(X.familyId,X)}if(Y.size===0)return[];let K=[...new Set([...Y.values()].map((X)=>X.clientId))],z=await this.clients.findMany({where:{clientId:{in:K}}}),G=new Map(z.map((X)=>[X.clientId,X]));return[...Y.values()].map((X)=>({familyId:X.familyId,clientId:X.clientId,clientName:G.get(X.clientId)?.clientName??null,clientUri:G.get(X.clientId)?.clientUri??null,scopes:m1(X.scopes),connectedAt:new Date(c1(X.createdAt))})).reverse()}async disconnect(W,Z){if(await this.credentials.count({where:{familyId:Z,userId:String(W)}})===0)return!1;return await this.revokeFamily(Z),!0}async revokeUser(W){await this.credentials.updateMany({where:{userId:String(W),revokedAt:null},data:{revokedAt:new Date}})}async prune(W=Date.now()){let Z=new Date(W-86400000),$=[...await this.revokedFamilies({expiresAt:{lt:Z}})],J=$.length===0?[]:await this.credentials.findMany({where:{familyId:{in:$},expiresAt:{gte:Z}},select:{familyId:!0}}),Q=[...new Set(J.map((Y)=>Y.familyId))];await this.credentials.deleteMany({where:{expiresAt:{lt:Z},...Q.length>0?{OR:[{revokedAt:null},{familyId:{notIn:Q}}]}:{}}}),await this.usesModel.deleteMany({where:{expiresAt:{lt:new Date(W)}}})}async findLive(W,Z){let $=await this.credentials.findFirst({where:{hash:W,kind:{in:Z},revokedAt:null}});if(!$)return null;return await this.credentials.count({where:{familyId:$.familyId,revokedAt:{not:null}}})>0?null:$}async revokedFamilies(W){let Z=await this.credentials.findMany({where:{...W,revokedAt:{not:null}},select:{familyId:!0}});return new Set(Z.map(($)=>$.familyId))}}function m1(W){return Array.isArray(W)?W.map(String):[]}function c1(W){return W instanceof Date?W.getTime():new Date(W).getTime()}class S1 extends w{application;previous;dispatched=[];static install(W){let Z=W.resolved(w)?W.make(w):void 0;if(Z instanceof S1)return Z;let $=new S1(W,Z);return W.instance(w,$),$}constructor(W,Z){super({listeners:[]});this.application=W;this.previous=Z}dispatch(W,Z){this.dispatched.push({event:W,args:Z})}async dispatchAndWait(W,Z){this.dispatched.push({event:W,args:Z})}restore(){if(this.previous){this.application.instance(w,this.previous);return}this.application.forget(w)}assertDispatched(W,Z){let $=O1(W);if(this.matching($,Z).length>0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} to have been dispatched. ${this.summary($,Z!==void 0)}`)}assertNotDispatched(W,Z){let $=O1(W),J=this.matching($,Z);if(J.length===0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} not to have been dispatched, but it was dispatched ${I4(J.length)}: ${u1(J)}.`)}assertDispatchedTimes(W,Z,$){let J=O1(W),Q=this.matching(J,$);if(Q.length===Z)return;throw Error(`Expected ${J}${$?" matching the predicate":""} to have been dispatched ${I4(Z)}, but it was dispatched ${I4(Q.length)}. ${this.summary(J,$!==void 0)}`)}assertNothingDispatched(){if(this.dispatched.length===0)return;let W=this.dispatched.length;throw Error(`Expected nothing to have been dispatched, but ${W} ${W===1?"event was":"events were"}: ${u1(this.dispatched)}.`)}matching(W,Z){return this.dispatched.filter(($)=>O1($.event.constructor)===W&&(Z===void 0||Z($.event)))}summary(W,Z){if(this.dispatched.length===0)return"Nothing was dispatched.";let $=this.matching(W);if(Z&&$.length>0)return`Dispatched ${W}: ${u1($)}.`;return`Dispatched: ${u1(this.dispatched)}.`}}function O1(W){return W.name}function I4(W){return`${W} ${W===1?"time":"times"}`}function u1(W){return W.map(AW).join(", ")}function AW(W){let Z=O1(W.event.constructor),$=W.args??Object.values({...W.event});return`${Z}(${$.map(hW).join(", ")})`}function hW(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class p1{static name="unset";static afterCommit=!1;static dispatch(...W){U6(this),_(w).dispatch(new this(...W),W)}static dispatchAndWait(...W){return U6(this),_(w).dispatchAndWait(new this(...W),W)}static fake(){return S1.install(gW())}}function gW(){try{return _()}catch(W){throw Error("Event.fake() needs a booted application. The fake works by replacing the container's EventManager with a recorder, so there has to be a "+"container to replace it in \u2014 and a dispatch finds the recorder the "+"same way, by resolving from that container. Boot the app's kernel in the test's setup: `const kernel = new Kernel(); kernel.boot()` is enough on its own, since that is the phase that publishes the application every dispatch outside a request resolves through.",{cause:W})}}function U6(W){if(W.name!=="unset"&&W.name!=="")return;throw Error("Cannot dispatch an event with no name. Add `static name` to this Event "+"subclass \u2014 the listener registry is keyed by that string, and by that "+"string alone, so an event without one cannot reach a listener.")}class S6 extends p1{constructor(){super();Object.defineProperty(this,y4,{value:!0,enumerable:!1})}broadcastAs(){return this.constructor.name}broadcastWith(){return}channel(W,...Z){return{topic:x6(W,Z[0]??{}),pattern:W}}}function k6(){try{let W=_();if(typeof W?.bound==="function"&&W.bound(e))return W.make(e).config.emailCode.fixedCode}catch{}return}function EW(){return R6(k6())}function mW(W){return _6(W,k6())}function cW(W){let Z=null;try{let Y=_();if(typeof Y?.bound==="function"&&Y.bound(A4))Z=_(A4).resolver??null}catch{Z=null}if(Z)return Z.publicOrigin(W);let $=new URL(W.url),J=W.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return`${J==="http"||J==="https"?J:$.protocol.slice(0,-1)}://${$.host}`}function uW(W,Z){let $=typeof W==="string"?W.trim().replace(/\/+$/,""):"",J=URL.canParse($)?new URL($):null;if(!J||J.protocol!=="http:"&&J.protocol!=="https:"||J.origin!==$)throw Error(`${Z}: resolve() returned origin ${JSON.stringify(W)}, which is not an http(s) origin such as https://example.com.`);return $}var f6=new WeakMap;function p(W,Z,$){if(!$.resolve)return Promise.resolve({clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.staticRedirectUri()});let J=Z?.rawRequest;if(!Z||!J)return Promise.resolve(null);let Q=f6.get(W);if(!Q)Q=new WeakMap,f6.set(W,Q);let Y=Q.get(J);if(Y)return Y;let K=$.resolve,z=(async()=>{let G=await K({req:Z,origin:cW(J)});if(G===null||G===void 0)return null;let X=G.origin!==void 0?uW(G.origin,$.name):$.staticOrigin();return{clientId:G.clientId??$.clientId,clientSecret:G.clientSecret??$.clientSecret,redirectUri:`${X}${$.redirectPath}`}})();return Q.set(J,z),z.catch(()=>Q.delete(J)),z}var pW={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET,redirectPath:"/auth/oauth/google/callback",scope:"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",authorizationParams:{}};function dW(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class C6 extends m{config;constructor(W={}){super();this.config={...pW,...W}}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"GoogleOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GoogleOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}authorizationUrl(W,Z){let $=new URL("https://accounts.google.com/o/oauth2/v2/auth"),J={include_granted_scopes:"true",...this.config.authorizationParams,scope:this.config.scope,response_type:"code",redirect_uri:W.redirectUri,client_id:W.clientId};if(Z)J.state=Z.state,J.code_challenge=Z.codeChallenge,J.code_challenge_method=Z.codeChallengeMethod;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new U("missing_code");let J=this.config.resolve?await this.clientFor(W):this.staticClient();if(!J)throw new U("unknown_provider");let Q=new URLSearchParams({code:$,client_id:J.clientId,client_secret:J.clientSecret,grant_type:"authorization_code",redirect_uri:J.redirectUri});if(Z?.codeVerifier)Q.set("code_verifier",Z.codeVerifier);let Y=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Q.toString()}),K=await Y.json().catch(()=>({}));if(!Y.ok||typeof K?.access_token!=="string"||K.access_token==="")throw console.error("Google OAuth error: token exchange failed",K?.error??Y.status),new U(dW(K?.error,"exchange_failed"));let G=await(await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${K.access_token}`}})).json().catch(()=>({}));if(typeof G.sub!=="string"||G.sub==="")return console.error("Google OAuth error: sub not found in user info response",G),{};if(!G.email)console.error("Google OAuth error: email not found in user info response",G);return{providerId:G.sub,name:G.name,email:G.email,emailVerified:G.email_verified===!0||G.email_verified==="true"}}}var lW="https://github.com/login/oauth/authorize",nW="https://github.com/login/oauth/access_token",V6="https://api.github.com";function iW(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class T6 extends m{config;constructor(W={}){super();this.config={clientId:process.env.GITHUB_CLIENT_ID??"",clientSecret:process.env.GITHUB_CLIENT_SECRET??"",redirectPath:"/auth/oauth/github/callback",scope:"read:user user:email",authorizationParams:{},...W}}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"GitHubOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GitHubOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(lW),J={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,scope:this.config.scope,response_type:"code"};if(Z)J.state=Z.state,J.code_challenge=Z.codeChallenge,J.code_challenge_method=Z.codeChallengeMethod;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new U("missing_code");let J=this.config.resolve?await this.clientFor(W):this.staticClient();if(!J)throw new U("unknown_provider");let Q=new URLSearchParams({client_id:J.clientId,client_secret:J.clientSecret,code:$,redirect_uri:J.redirectUri});if(Z?.codeVerifier)Q.set("code_verifier",Z.codeVerifier);let Y=await fetch(nW,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:Q.toString()}),K=await Y.json().catch(()=>({}));if(!Y.ok||typeof K?.access_token!=="string"||K.access_token==="")throw console.error("GitHub OAuth error: token exchange failed",K?.error??Y.status),new U(iW(K?.error,"exchange_failed"));let z={Accept:"application/vnd.github+json",Authorization:`Bearer ${K.access_token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"gemi"},G=await fetch(`${V6}/user`,{headers:z}),X=await G.json().catch(()=>({}));if(!G.ok||typeof X?.id!=="number"||!Number.isSafeInteger(X.id))return console.error("GitHub OAuth error: no user id in the /user response",G.status),{};let B=typeof X.login==="string"&&X.login!==""?X.login:void 0,j=typeof X.name==="string"&&X.name!==""?X.name:B,L=await this.primaryVerifiedEmail(z),H=typeof X.email==="string"&&X.email!==""?X.email:void 0;return{providerId:String(X.id),username:B,name:j,...L?{email:L,emailVerified:!0}:H?{email:H,emailVerified:!1}:{}}}async primaryVerifiedEmail(W){let Z=await fetch(`${V6}/user/emails`,{headers:W}).catch(()=>null);if(!Z?.ok){console.error("GitHub OAuth error: could not read /user/emails",Z?.status);return}let $=await Z.json().catch(()=>null);if(!Array.isArray($))return;let J=$.find((Q)=>Q?.primary===!0&&Q.verified===!0);return typeof J?.email==="string"&&J.email!==""?J.email:void 0}}var d="https://api.x.com/2/",Q1="https://api.x.com/labs/2/",l="https://api.x.com/1.1/",c="https://upload.x.com/1.1/",P6="https://stream.x.com/1.1/",Y1="https://ads-api.x.com/12/",K1="https://ads-api-sandbox.twitter.com/12/";class h4{constructor({realData:W,rateLimit:Z,instance:$,queryParams:J,sharedParams:Q}){this._maxResultsWhenFetchLast=100,this._realData=W,this._rateLimit=Z,this._instance=$,this._queryParams=J,this._sharedParams=Q}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(W){return this._instance.get(this.getEndpoint(),W,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(W,Z){return new this.constructor({realData:W.data,rateLimit:W.rateLimit,instance:this._instance,queryParams:Z,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(W){return{...W?{max_results:W}:{},...this._queryParams}}async next(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchNext(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!0),this}async fetchLast(W=1/0){let Z=this.getNextQueryParams(this._maxResultsWhenFetchLast),$=0;while($<W&&this._isRateLimitOk){let J=await this.makeRequest(Z);if(await this.refreshInstanceFromResult(J,!0),$+=this.getPageLengthFromRequest(J),this.isFetchLastOver(J))break;Z=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var W;return{...(W=this._rateLimit)!==null&&W!==void 0?W:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData),yield*$.getItemArray(),W=$}}async*fetchAndIterate(){for(let $ of this.getItemArray())yield[$,this];let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData);for(let J of $.getItemArray())yield[J,$];this._rateLimit=$._rateLimit,W=$}}}class g4 extends h4{async previous(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchPrevious(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!1),this}}var z1=h4;class x extends z1{getNextQueryParams(W){var Z;return{...this._queryParams,cursor:(Z=this._realData.next_cursor_str)!==null&&Z!==void 0?Z:this._realData.next_cursor,...W?{count:W}:{}}}isFetchLastOver(W){return!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!this.isNextCursorInvalid(W.next_cursor)||!this.isNextCursorInvalid(W.next_cursor_str)}isNextCursorInvalid(W){return W===void 0||W===0||W===-1||W==="0"||W==="-1"}}class E4 extends x{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.events.push(...$.events),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class m4 extends x{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.welcome_messages.push(...$.welcome_messages),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var D;(function(W){W.Jpeg="image/jpeg",W.Mp4="video/mp4",W.Mov="video/quicktime",W.Gif="image/gif",W.Png="image/png",W.Srt="text/plain",W.Webp="image/webp"})(D||(D={}));var n;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(n||(n={}));var R1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(R1||(R1={}));class d1 extends Error{constructor(){super(...arguments);this.error=!0}}class _1 extends d1{constructor(W,Z){super(W);this.type=R1.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class k1 extends d1{constructor(W,Z){super(W);this.type=R1.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}get request(){return this._options.request}get response(){return this._options.response}get responseError(){return this._options.responseError}get rawContent(){return this._options.rawContent}toJSON(){return{type:this.type,error:this.responseError}}}class f1 extends d1{constructor(W,Z){super(W);if(this.type=R1.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z}),this.code=Z.code,this.headers=Z.headers,this.rateLimit=Z.rateLimit,Z.data&&typeof Z.data==="object"&&"error"in Z.data&&!Z.data.errors){let $={...Z.data};$.errors=[{code:W1.InternalError,message:$.error}],this.data=$}else this.data=Z.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...W){let Z=this.errors;if(!(Z===null||Z===void 0?void 0:Z.length))return!1;if("code"in Z[0])return Z.some((Q)=>W.includes(Q.code));let $=this.data;return W.includes($.type)}get errors(){var W;return(W=this.data)===null||W===void 0?void 0:W.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(W1.AuthTimestampInvalid,W1.AuthenticationFail,W1.BadAuthenticationData,W1.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var W1;(function(W){W[W.InvalidCoordinates=3]="InvalidCoordinates",W[W.NoLocationFound=13]="NoLocationFound",W[W.AuthenticationFail=32]="AuthenticationFail",W[W.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",W[W.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",W[W.AuthTimestampInvalid=135]="AuthTimestampInvalid",W[W.BadAuthenticationData=215]="BadAuthenticationData",W[W.NoUserMatch=17]="NoUserMatch",W[W.UserNotFound=50]="UserNotFound",W[W.ResourceNotFound=34]="ResourceNotFound",W[W.TweetNotFound=144]="TweetNotFound",W[W.TweetNotVisible=179]="TweetNotVisible",W[W.NotAllowedResource=220]="NotAllowedResource",W[W.MediaIdNotFound=325]="MediaIdNotFound",W[W.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",W[W.TweetViolatedRules=422]="TweetViolatedRules",W[W.TargetUserSuspended=63]="TargetUserSuspended",W[W.YouAreSuspended=64]="YouAreSuspended",W[W.AccountUpdateFailed=120]="AccountUpdateFailed",W[W.NoSelfSpamReport=36]="NoSelfSpamReport",W[W.NoSelfMute=271]="NoSelfMute",W[W.AccountLocked=326]="AccountLocked",W[W.RateLimitExceeded=88]="RateLimitExceeded",W[W.NoDMRightForApp=93]="NoDMRightForApp",W[W.OverCapacity=130]="OverCapacity",W[W.InternalError=131]="InternalError",W[W.TooManyFollowings=161]="TooManyFollowings",W[W.TweetLimitExceeded=185]="TweetLimitExceeded",W[W.DuplicatedTweet=187]="DuplicatedTweet",W[W.TooManySpamReports=205]="TooManySpamReports",W[W.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",W[W.NoWriteRightForApp=261]="NoWriteRightForApp",W[W.TweetActionsDisabled=425]="TweetActionsDisabled",W[W.TweetRepliesRestricted=433]="TweetRepliesRestricted",W[W.NamedParameterMissing=38]="NamedParameterMissing",W[W.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",W[W.TweetTextTooLong=186]="TweetTextTooLong",W[W.MissingUrlParameter=195]="MissingUrlParameter",W[W.NoMultipleGifs=323]="NoMultipleGifs",W[W.InvalidMediaIds=324]="InvalidMediaIds",W[W.InvalidUrl=407]="InvalidUrl",W[W.TooManyTweetAttachments=386]="TooManyTweetAttachments",W[W.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",W[W.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",W[W.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",W[W.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",W[W.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",W[W.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",W[W.UnableToSendDM=151]="UnableToSendDM",W[W.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",W[W.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",W[W.DMTextTooLong=354]="DMTextTooLong",W[W.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",W[W.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",W[W.SuspendedApplication=416]="SuspendedApplication",W[W.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(W1||(W1={}));var b6;(function(W){W.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",W.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",W.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",W.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",W.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",W.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",W.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",W.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",W.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",W.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",W.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",W.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",W.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(b6||(b6={}));var F;(function(W){W.Connected="connected",W.ConnectError="connect error",W.ConnectionError="connection error",W.ConnectionClosed="connection closed",W.ConnectionLost="connection lost",W.ReconnectAttempt="reconnect attempt",W.Reconnected="reconnected",W.ReconnectError="reconnect error",W.ReconnectLimitExceeded="reconnect limit exceeded",W.DataKeepAlive="data keep-alive",W.Data="data event content",W.DataError="data twitter error",W.TweetParseError="data tweet parse error",W.Error="stream error"})(F||(F={}));class C1{constructor(W){this.value=W}}import*as F0 from"fs";var R={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function c4(W){let Z={value:void 0,promise:W().then(($)=>{return Z.value=$,$})};return Z}function l1(W){if(Array.isArray(W))return W;return[W]}function q6(W){for(let Z of Object.keys(W))if(W[Z]===void 0)delete W[Z]}function n1(W){return typeof W==="object"&&"errors"in W&&!("data"in W)}function V1(W){if(Array.isArray(W)&&W.length>1)return!0;return W.toString().includes(",")}var w6=new Set;function u4(W){if(typeof console>"u"||!console.warn||!R.deprecationWarnings)return;let Z=`${W.instance}-${W.method}-${W.problem}`;if(w6.has(Z))return;let $=`[twitter-api-v2] Deprecation warning: In ${W.instance}.${W.method}() call, ${W.problem}.
|
|
65
|
-
${W.resolution}.`;console.warn($),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),w6.add(Z)}import{EventEmitter as rW}from"events";import{request as sW}from"https";import*as f from"zlib";import{EventEmitter as oW}from"events";class v6{constructor(W){this.requestData=W,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let W=this.requestData.url;return W.hostname+W.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(W){if(R.debug)R.logger.log("Request error:",W);return new _1("Request failed.",{request:this.req,error:W})}createPartialResponseError(W,Z){let J=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(Z)J+=" (connection abruptly closed)";else J+=" (parse error)";return new k1(J,{request:this.req,response:this.res,responseError:W,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(W){return W.map(({code:Z,message:$})=>`${$} (Twitter code ${Z})`).join(", ")}formatV2Error(W){return`${W.title}: ${W.detail} (see ${W.type})`}createResponseError({res:W,data:Z,rateLimit:$,code:J}){var Q;if(R.debug)R.logger.log(`Request failed with code ${J}, data:`,Z),R.logger.log("Response headers:",W.headers);let Y=`Request failed with code ${J}`;if((Q=Z===null||Z===void 0?void 0:Z.errors)===null||Q===void 0?void 0:Q.length){let K=Z.errors;if(typeof K[0]==="object"&&"code"in K[0])Y+=" - "+this.formatV1Errors(K);else Y+=" - "+this.formatV2Error(Z)}return new f1(Y,{code:J,data:Z,headers:W.headers,request:this.req,response:W,rateLimit:$})}getResponseDataStream(W){if(this.isCompressionDisabled())return W;let Z=(W.headers["content-encoding"]||"identity").trim().toLowerCase();if(Z==="br"){let $=f.createBrotliDecompress({flush:f.constants.BROTLI_OPERATION_FLUSH,finishFlush:f.constants.BROTLI_OPERATION_FLUSH});return W.pipe($),$}if(Z==="gzip"){let $=f.createGunzip({flush:f.constants.Z_SYNC_FLUSH,finishFlush:f.constants.Z_SYNC_FLUSH});return W.pipe($),$}if(Z==="deflate"){let $=f.createInflate({flush:f.constants.Z_SYNC_FLUSH,finishFlush:f.constants.Z_SYNC_FLUSH});return W.pipe($),$}return W}detectResponseType(W){var Z,$;if(((Z=W.headers["content-type"])===null||Z===void 0?void 0:Z.includes("application/json"))||(($=W.headers["content-type"])===null||$===void 0?void 0:$.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(W){let Z=this.responseData,$=this.requestData.forceParseMode||this.detectResponseType(W);if($==="buffer")return Buffer.concat(Z);else if($==="text")return Buffer.concat(Z).toString();else if($==="json"){let J=Buffer.concat(Z).toString();return J.length?JSON.parse(J):void 0}else if($==="url"){let J=Buffer.concat(Z).toString(),Q={};for(let[Y,K]of new URLSearchParams(J))Q[Y]=K;return Q}else return}getRateLimitFromResponse(W){let Z=void 0;if(W.headers["x-rate-limit-limit"]){if(Z={limit:Number(W.headers["x-rate-limit-limit"]),remaining:Number(W.headers["x-rate-limit-remaining"]),reset:Number(W.headers["x-rate-limit-reset"])},W.headers["x-app-limit-24hour-limit"])Z.day={limit:Number(W.headers["x-app-limit-24hour-limit"]),remaining:Number(W.headers["x-app-limit-24hour-remaining"]),reset:Number(W.headers["x-app-limit-24hour-reset"])};if(W.headers["x-user-limit-24hour-limit"])Z.userDay={limit:Number(W.headers["x-user-limit-24hour-limit"]),remaining:Number(W.headers["x-user-limit-24hour-remaining"]),reset:Number(W.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(Z)}return Z}onSocketEventHandler(W,Z,$){let J=this.onSocketCloseHandler.bind(this,W);$.on("close",J),Z.on("complete",()=>$.off("close",J))}onSocketCloseHandler(W){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return W(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(W,Z){var $,J;(J=($=this.requestData).requestEventDebugHandler)===null||J===void 0||J.call($,"request-error",{requestError:Z}),this.requestErrorHandled=!0,W(this.createRequestError(Z))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(W,Z,$){this.res=$;let J=this.getResponseDataStream($);if(J.on("data",(Q)=>this.responseData.push(Q)),J.on("end",this.onResponseEndHandler.bind(this,W,Z)),J.on("close",this.onResponseCloseHandler.bind(this,W,Z)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:$}),$.on("aborted",(Q)=>this.requestData.requestEventDebugHandler("response-aborted",{error:Q})),$.on("error",(Q)=>this.requestData.requestEventDebugHandler("response-error",{error:Q})),$.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),$.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(W,Z){let $=this.getRateLimitFromResponse(this.res),J;try{J=this.getParsedResponse(this.res)}catch(Y){Z(this.createPartialResponseError(Y,!1));return}let Q=this.res.statusCode;if(Q>=400){Z(this.createResponseError({data:J,res:this.res,rateLimit:$,code:Q}));return}if(R.debug)R.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),R.logger.log("Response body:",J);W({data:J,headers:this.res.headers,rateLimit:$})}onResponseCloseHandler(W,Z){let $=this.res;if($.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(W,Z)}catch(J){return Z(this.createPartialResponseError(J,!0))}if(!$.complete)return Z(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(W,Z,$){if($.statusCode<400){if(R.debug)R.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${$.statusCode} (starting stream)`);let Q=this.getResponseDataStream($);W({req:this.req,res:Q,originalResponse:$,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},Z,$)}debugRequest(){let W=this.requestData.url;if(R.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),W.search)R.logger.log("Request parameters:",[...W.searchParams.entries()].map(([Z,$])=>`${Z}: ${$}`));if(this.requestData.body)R.logger.log("Request body:",this.requestData.body)}buildRequest(){var W;let Z=this.requestData.url,$=Z.username?`${Z.username}:${Z.password}`:void 0,J=(W=this.requestData.options.headers)!==null&&W!==void 0?W:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")J["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")J["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")J["accept-encoding"]="deflate;q=1, *;q=0.1";if(R.debug)this.debugRequest();this.req=sW({...this.requestData.options,host:Z.hostname,port:Z.port||void 0,path:Z.pathname+Z.search,protocol:Z.protocol,auth:$,headers:J})}registerRequestEventDebugHandlers(W){W.on("close",()=>this.requestData.requestEventDebugHandler("close")),W.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),W.on("socket",(Z)=>{this.requestData.requestEventDebugHandler("socket",{socket:Z}),Z.on("error",($)=>this.requestData.requestEventDebugHandler("socket-error",{socket:Z,error:$})),Z.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:Z})),Z.on("close",($)=>this.requestData.requestEventDebugHandler("socket-close",{socket:Z,withError:$})),Z.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:Z})),Z.on("lookup",(...$)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:Z,data:$})),Z.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:Z}))})}makeRequest(){return this.buildRequest(),new Promise((W,Z)=>{let $=(K)=>{Q.emit("complete"),W(K)},J=(K)=>{Q.emit("complete"),Z(K)},Q=new oW,Y=this.req;if(Y.on("error",this.requestErrorHandler.bind(this,J)),Y.on("socket",this.onSocketEventHandler.bind(this,J,Q)),Y.on("response",this.classicResponseHandler.bind(this,$,J)),this.requestData.options.timeout)Y.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(Y);if(this.requestData.body)Y.write(this.requestData.body);Y.end()})}async makeRequestAsStream(){let{req:W,res:Z,requestData:$,originalResponse:J}=await this.makeRequestAndResolveWhenReady();return new i1($,{req:W,res:Z,originalResponse:J})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((W,Z)=>{let $=this.req;if($.on("error",this.requestErrorHandler.bind(this,Z)),$.on("response",this.streamResponseHandler.bind(this,W,Z)),this.requestData.body)$.write(this.requestData.body);$.end()})}}var T1=v6;import{EventEmitter as aW}from"events";class I6 extends aW{constructor(W){super();this.stream=W,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),W.on(F.Data,this.onStreamData),W.on(F.ConnectionError,this.onStreamError),W.on(F.TweetParseError,this.onStreamError),W.on(F.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let W=this.stack;return this.stack=[],W}destroy(){this.removeAllListeners(),this.stream.off(F.Data,this.onStreamData),this.stream.off(F.ConnectionError,this.onStreamError),this.stream.off(F.TweetParseError,this.onStreamError),this.stream.off(F.ConnectionClosed,this.onStreamError)}emitEvent(W,Z){this.emit("event",{type:W,payload:Z})}onStreamError(W){this.emitEvent("error",W)}onStreamData(W){this.stack.push(W),this.emitEvent("data",W)}}var y6=I6;import{EventEmitter as tW}from"events";class s1 extends tW{constructor(){super(...arguments);this.currentMessage=""}push(W){this.currentMessage+=W,W=this.currentMessage;let Z=W.length,$=0,J=0;while(J<Z){if(W.slice(J,J+2)===`\r
|
|
66
|
-
`){let Q=W.slice($,J);if($=J+=2,!Q.length)continue;try{let Y=JSON.parse(Q);if(Y){this.emit(Z1.ParsedData,Y);continue}}catch(Y){this.emit(Z1.ParseError,Y)}}J++}this.currentMessage=W.slice($,Z)}reset(){this.currentMessage=""}}var Z1;(function(W){W.ParsedData="parsed data",W.ParseError="parse error"})(Z1||(Z1={}));var
|
|
67
|
-
`)return this.emit(F.DataKeepAlive);this.parser.push(Z.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let W=this.requestData.payloadIsError;this.parser.on(Z1.ParsedData,(Z)=>{if(W&&W(Z))this.emit(F.DataError,Z),this.emit(F.Error,{type:F.DataError,error:Z,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(F.Data,Z)}),this.parser.on(Z1.ParseError,(Z)=>{this.emit(F.TweetParseError,Z),this.emit(F.Error,{type:F.TweetParseError,error:Z,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(F.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){if(this.keepAliveTimeout)clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0}unbindRetryTimeout(){if(this.retryTimeout)clearTimeout(this.retryTimeout),this.retryTimeout=void 0}closeWithoutEmit(){if(this.unbindTimeouts(),this.res)this.res.removeAllListeners(),this.res.destroy();if(this.req)this.req.removeAllListeners(),this.req.destroy()}close(){this.emit(F.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let Z=await new
|
|
68
|
-
`;v.DEFAULT_CONTENT_TYPE="application/octet-stream";class p4{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 J="";for(let[Q,Y]of $)J+=(J.length?"&":"?")+`${P1.percentEncode(Q)}=${P1.percentEncode(Y)}`;W.search=J}}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 J=new v;for(let Q in W)J.append(Q,W[Q]);if(!Z["content-type"]){let Q=J.getHeaders();Z["content-type"]=Q["content-type"]}return J.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 J in W)$[J]=W[J];if(this.isOAuthSerializable(Z))for(let J in Z){let Q=Z[J];if(this.isOAuthSerializable(Q))$[J]=typeof Q==="object"&&Q!==null&&"toString"in Q?Q.toString():Q}return $}static moveUrlQueryParamsIntoObject(W,Z){for(let[$,J]of W.searchParams)Z[$]=J;return W.search="",W}static applyRequestParametersToUrl(W,Z){return W.pathname=W.pathname.replace(/:([A-Z_-]+)/ig,($,J)=>{if(Z[J]!==void 0)return String(Z[J]);return $}),W}}p4.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 T=p4;import*as p6 from"crypto";class $1{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url(p6.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 J=0;J<W;J++)Z+=$[Math.floor(Math.random()*$.length)];return Z}static escapeBase64Url(W){return W.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class G1{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,$,J,Q,Y;if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length){let j=await this.applyPreRequestConfigHooks(W);if(j)return j}let K=this.getHttpRequestArgs(W),z={method:K.method,headers:K.headers,timeout:W.timeout,agent:this.clientSettings.httpAgent},G=W.enableRateLimitSave!==!1;if(K.body)T.setBodyLengthHeader(z,K.body);if(($=this.clientSettings.plugins)===null||$===void 0?void 0:$.length)await this.applyPreRequestHooks(W,K,z);let X=new T1({url:K.url,options:z,body:K.body,rateLimitSaver:G?this.saveRateLimit.bind(this,K.rawUrl):void 0,requestEventDebugHandler:W.requestEventDebugHandler,compression:(Q=(J=W.compression)!==null&&J!==void 0?J:this.clientSettings.compression)!==null&&Q!==void 0?Q:!0,forceParseMode:W.forceParseMode}).makeRequest();if(g6(this))X=this.applyResponseErrorHooks(W,K,z,X);let B=await X;if((Y=this.clientSettings.plugins)===null||Y===void 0?void 0:Y.length){let j=await this.applyPostRequestHooks(W,K,z,B);if(j)return j.value}return B}sendStream(W){var Z,$;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(W);let J=this.getHttpRequestArgs(W),Q={method:J.method,headers:J.headers,agent:this.clientSettings.httpAgent},Y=W.enableRateLimitSave!==!1,K=W.autoConnect!==!1;if(J.body)T.setBodyLengthHeader(Q,J.body);let z={url:J.url,options:Q,body:J.body,rateLimitSaver:Y?this.saveRateLimit.bind(this,J.rawUrl):void 0,payloadIsError:W.payloadIsError,compression:($=(Z=W.compression)!==null&&Z!==void 0?Z:this.clientSettings.compression)!==null&&$!==void 0?$:!0},G=new i1(z);if(!K)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 P1({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 J;for(let Q of this.getPlugins()){let Y=await(($=Q[W])===null||$===void 0?void 0:$.call(Q,Z));if(Y&&Y instanceof C1)J=Y}return J}writeAuthHeaders({headers:W,bodyInSignature:Z,url:$,method:J,query:Q,body:Y}){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 "+$1.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let K=Z?T.mergeQueryAndBodyForOAuth(Q,Y):Q,z=this._oauth.authorize({url:$.toString(),method:J,data:K},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:J={},headers:Q,forceBodyMode:Y,enableAuth:K,params:z}){let G=void 0;if(Z=Z.toUpperCase(),Q=Q!==null&&Q!==void 0?Q:{},!Q["x-user-agent"])Q["x-user-agent"]="Node.twitter-api-v2";let X=this.getUrlObjectFromUrlString(W),B=X.origin+X.pathname;if(z)T.applyRequestParametersToUrl(X,z);let j=T.formatQueryToString($);if(T.moveUrlQueryParamsIntoObject(X,j),!(J instanceof Buffer))q6(J);let L=Y!==null&&Y!==void 0?Y:T.autoDetectBodyType(X);if(K!==!1){let H=G1.BODY_METHODS.has(Z)&&L==="url";Q=this.writeAuthHeaders({headers:Q,bodyInSignature:H,method:Z,query:j,url:X,body:J})}if(G1.BODY_METHODS.has(Z))G=T.constructBodyParams(J,Q,L)||void 0;return T.addQueryParamsToUrl(X,j),{rawUrl:B,url:X,method:Z,headers:Q,body:G}}async applyPreRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let J of this.getPlugins()){let Q=await((Z=J.onBeforeRequestConfig)===null||Z===void 0?void 0:Z.call(J,{client:this,url:$,params:W}));if(Q)return Q}}applyPreStreamRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let J of this.getPlugins())(Z=J.onBeforeStreamRequestConfig)===null||Z===void 0||Z.call(J,{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,$,J){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,response:J})}applyResponseErrorHooks(W,Z,$,J){return J.catch(E6.bind(this,W,Z,$))}}G1.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class i{constructor(W,Z={}){if(this._currentUser=null,this._currentUserV2=null,W instanceof i)this._requestMaker=W._requestMaker;else this._requestMaker=new G1(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=c4(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:l})),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=c4(()=>this.get("users/me",void 0,{prefix:d})),this._currentUserV2.promise}async get(W,Z={},{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"GET",query:Z,...Q});return $?Y:Y.data}async delete(W,Z={},{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"DELETE",query:Z,...Q});return $?Y:Y.data}async post(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"POST",body:Z,...Q});return $?Y:Y.data}async put(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"PUT",body:Z,...Q});return $?Y:Y.data}async patch(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"PATCH",body:Z,...Q});return $?Y:Y.data}getStream(W,Z,{prefix:$=this._prefix,...J}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"GET",query:Z,...J})}postStream(W,Z,{prefix:$=this._prefix,...J}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"POST",body:Z,...J})}}class P extends i{constructor(W){if(!(W instanceof i))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(W)}}class X1 extends z1{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 d4 extends X1{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class l4 extends X1{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class o1 extends X1{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class n4 extends X1{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class a1 extends X1{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class i4 extends x{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 s4 extends x{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 o4 extends x{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 a4 extends x{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 t4 extends x{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 r4 extends x{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 e4 extends z1{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 t1 extends x{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 W0 extends t1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class r1 extends x{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 Z0 extends r1{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class $0 extends r1{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class J0 extends r1{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class Q0 extends x{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 Y0 extends Q0{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class K0 extends Q0{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class B1 extends P{constructor(){super(...arguments);this._prefix=l}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 d4({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 l4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},J=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new o1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async userTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},J=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new o1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async favoriteTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},J=await this.get("favorites/list.json",$,{fullResponse:!0});return new a1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async favoriteTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},J=await this.get("favorites/list.json",$,{fullResponse:!0});return new a1({realData:J.data,rateLimit:J.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 i4({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 s4({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 t4({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 o4({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 a4({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 r4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async searchUsers(W,Z={}){let $={q:W,tweet_mode:"extended",page:1,...Z},J=await this.get("users/search.json",$,{fullResponse:!0});return new e4({realData:J.data,rateLimit:J.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 t1({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 W0({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 Y0({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 Z0({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 $0({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 n4({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 K0({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 J0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}mediaInfo(W){return this.get("media/upload.json",{command:"STATUS",media_id:W},{prefix:c})}filterStream({autoConnect:W,...Z}={}){let $={};for(let[Q,Y]of Object.entries(Z))if(Q==="follow"||Q==="track")$[Q]=Y.toString();else if(Q==="locations"){let K=Y;$.locations=l1(K).map((z)=>`${z.lng},${z.lat}`).join(",")}else $[Q]=Y;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 e1(this);return W.setPrefix(P6),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 s from"fs";async function z0(W){let Z=await G0(W);if(typeof Z==="number")return new Promise(($,J)=>{s.readFile(Z,(Q,Y)=>{if(Q)return J(Q);$(Y)})});else if(Z instanceof Buffer)return Z;else return Z.readFile()}function G0(W){if(typeof W==="string")return s.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 d6(W){if(typeof W==="number")return(await new Promise(($,J)=>{s.fstat(W,(Q,Y)=>{if(Q)J(Q);$(Y)})})).size;else if(W instanceof Buffer)return W.length;else return(await W.stat()).size}function l6(W,Z,$){if(typeof $==="string")return $;else if(typeof W==="string"&&!Z)return J5(W);else if(typeof Z==="string")return Q5(Z);throw Error("You must specify type if file is a file handle or Buffer.")}function J5(W){if(W.endsWith(".jpeg")||W.endsWith(".jpg"))return D.Jpeg;if(W.endsWith(".png"))return D.Png;if(W.endsWith(".webp"))return D.Webp;if(W.endsWith(".gif"))return D.Gif;if(W.endsWith(".mpeg4")||W.endsWith(".mp4"))return D.Mp4;if(W.endsWith(".mov")||W.endsWith(".mov"))return D.Mov;if(W.endsWith(".srt"))return D.Srt;return u4({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"}),D.Jpeg}function Q5(W){if(u4({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 D.Gif;if(W==="jpg")return D.Jpeg;if(W==="png")return D.Png;if(W==="webp")return D.Webp;if(W==="srt")return D.Srt;if(W==="mp4"||W==="longmp4")return D.Mp4;if(W==="mov")return D.Mov;return W}function n6(W,Z){if(W===D.Mp4||W===D.Mov)return Z==="tweet"?"TweetVideo":"DmVideo";if(W===D.Gif)return Z==="tweet"?"TweetGif":"DmGif";if(W===D.Srt)return"Subtitles";else return Z==="tweet"?"TweetImage":"DmImage"}function X0(W){return new Promise((Z)=>setTimeout(Z,W*1000))}async function B0(W,Z,$=0,J){if(W instanceof Buffer){let Y=W.slice($,$+Z);return[Y,Y.length]}if(!J)throw Error("Well, we will need a buffer to store file content.");let Q;if(typeof W==="number")Q=await new Promise((Y,K)=>{s.read(W,J,0,Z,$,(z,G)=>{if(z)K(z);Y(G)})});else Q=(await W.read(J,0,Z,$)).bytesRead;return[J,Q]}var j0="media/upload.json";class j1 extends B1{constructor(){super(...arguments);this._prefix=l}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 J="https://x.com/i/statuses/"+Z;return this.tweet(W,{...$,attachment_url:J})}async tweetThread(W){let Z=[];for(let $ of W){let J=Z.length?Z[Z.length-1]:null,Q={...typeof $==="string"?{status:$}:$},Y=J?J.id_str:Q.in_reply_to_status_id,K=Q.status;if(Y)Z.push(await this.reply(K,Y,Q));else Z.push(await this.tweet(K,Q))}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 z0(W),...Z};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,Z={}){let $={tweet_mode:"extended",image:await z0(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&&V1(W.user_id)||W.screen_name&&V1(W.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,W)}removeListMembers(W){let $=W.user_id&&V1(W.user_id)||W.screen_name&&V1(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:c,forceBodyMode:"json"})}createMediaSubtitles(W,Z){return this.post("media/subtitles/create.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z}},{prefix:c,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:c,forceBodyMode:"json"})}async uploadMedia(W,Z={},$=!1){var J;let Q=(J=Z.chunkLength)!==null&&J!==void 0?J:1048576,{fileHandle:Y,mediaCategory:K,fileSize:z,mimeType:G}=await this.getUploadMediaRequirements(W,Z);try{let X=await this.post(j0,{command:"INIT",total_bytes:z,media_type:G,media_category:K,additional_owners:Z.additionalOwners,shared:Z.shared?!0:void 0},{prefix:c});await this.mediaChunkedUpload(Y,Q,X.media_id_string,Z.maxConcurrentUploads);let B=await this.post(j0,{command:"FINALIZE",media_id:X.media_id_string},{prefix:c});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")F0.close(W,()=>{});else if(typeof Y==="object"&&!(Y instanceof Buffer))Y.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:J,message:Q}=$.error;throw Error(`Failed to process media: ${J} - ${Q}.`)}if($.state==="failed")throw Error("Failed to process the media.");if($.check_after_secs)await X0($.check_after_secs);else await X0(5)}}async getUploadMediaRequirements(W,{mimeType:Z,type:$,target:J,longVideo:Q}={}){let Y;try{Y=await G0(W);let K=l6(W,$,Z),z;if(K===D.Mp4&&(!Z&&!$&&J!=="dm"||Q))z="amplify_video";else z=n6(K,J!==null&&J!==void 0?J:"tweet");return{fileHandle:Y,mediaCategory:z,fileSize:await d6(Y),mimeType:K}}catch(K){if(typeof W==="number")F0.close(W,()=>{});else if(typeof Y==="object"&&!(Y instanceof Buffer))Y.close();throw K}}async mediaChunkedUpload(W,Z,$,J=3){let Q=0;if(J<1)throw RangeError("Bad maxConcurrentUploads parameter.");let Y=W instanceof Buffer?void 0:Buffer.alloc(Z),K,z,G=0;[K,z]=await B0(W,Z,G,Y),G+=z;let X=new Set;while(z){let B=K.slice(0,z);if(B.length){let j=this.post(j0,{command:"APPEND",media_id:$,segment_index:Q,media:B},{prefix:c});X.add(j),j.then(()=>{X.delete(j)}),Q++}if(X.size>=J)await Promise.race(X);[K,z]=await B0(W,Z,G,Y),G+=z}await Promise.all([...X])}}class i6 extends j1{constructor(){super(...arguments);this._prefix=l}get readWrite(){return this}sendDm({recipient_id:W,custom_profile_id:Z,...$}){let J={event:{type:n.Create,[n.Create]:{target:{recipient_id:W},message_data:$}}};if(Z)J.event[n.Create].custom_profile_id=Z;return this.post("direct_messages/events/new.json",J,{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 E4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDm(W,Z){let $={[n.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 m4({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 J=await this.listWelcomeDmRules();if(($=J.welcome_message_rules)===null||$===void 0?void 0:$.length){for(let Q of J.welcome_message_rules)if(await this.deleteWelcomeDmRule(Q.id),Z)await this.deleteWelcomeDm(Q.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[n.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 e1=i6;class N{constructor(W){this.result=W}get tweets(){return N.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 N.tweetById(this.result,W)}static tweetById(W,Z){return this.tweets(W).find(($)=>$.id===Z)}retweet(W){return N.retweet(this.result,W)}static retweet(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="retweeted").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}quote(W){return N.quote(this.result,W)}static quote(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="quoted").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}repliedTo(W){return N.repliedTo(this.result,W)}static repliedTo(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="replied_to").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}author(W){return N.author(this.result,W)}static author(W,Z){let $=Z.author_id;return $?this.users(W).find((J)=>J.id===$):void 0}repliedToAuthor(W){return N.repliedToAuthor(this.result,W)}static repliedToAuthor(W,Z){let $=Z.in_reply_to_user_id;return $?this.users(W).find((J)=>J.id===$):void 0}get users(){return N.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 N.userById(this.result,W)}static userById(W,Z){return this.users(W).find(($)=>$.id===Z)}pinnedTweet(W){return N.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 N.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 N.medias(this.result,W)}static medias(W,Z){var $,J;let Q=(J=($=Z.attachments)===null||$===void 0?void 0:$.media_keys)!==null&&J!==void 0?J:[];return this.media(W).filter((Y)=>Q.includes(Y.media_key))}get polls(){return N.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 N.poll(this.result,W)}static poll(W,Z){var $,J;let Q=(J=($=Z.attachments)===null||$===void 0?void 0:$.poll_ids)!==null&&J!==void 0?J:[];if(Q.length){let Y=Q[0];return this.polls(W).find((K)=>K.id===Y)}return}get places(){return N.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 N.place(this.result,W)}static place(W,Z){var $;let J=($=Z.geo)===null||$===void 0?void 0:$.place_id;return J?this.places(W).find((Q)=>Q.id===J):void 0}listOwner(W){return N.listOwner(this.result,W)}static listOwner(W,Z){let $=Z.owner_id;return $?this.users(W).find((J)=>J.id===$):void 0}spaceCreator(W){return N.spaceCreator(this.result,W)}static spaceCreator(W,Z){let $=Z.creator_id;return $?this.users(W).find((J)=>J.id===$):void 0}spaceHosts(W){return N.spaceHosts(this.result,W)}static spaceHosts(W,Z){var $;let J=($=Z.host_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}spaceSpeakers(W){return N.spaceSpeakers(this.result,W)}static spaceSpeakers(W,Z){var $;let J=($=Z.speaker_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}spaceInvitedUsers(W){return N.spaceInvitedUsers(this.result,W)}static spaceInvitedUsers(W,Z){var $;let J=($=Z.invited_user_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}}class W4 extends g4{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[$,J]of Object.entries(W.includes)){if(!Z[$])Z[$]=[];Z[$]=[...Z[$],...J]}}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 N(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new N(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 h extends W4{refreshInstanceFromResult(W,Z){var $;let J=W.data,Q=($=J.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.next_token=J.meta.next_token,this._realData.data.push(...Q);else this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.previous_token=J.meta.previous_token,this._realData.data.unshift(...Q);this.updateIncludes(J)}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 M0 extends W4{refreshInstanceFromResult(W,Z){var $;let J=W.data,Q=($=J.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.oldest_id=J.meta.oldest_id,this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.next_token=J.meta.next_token,this._realData.data.push(...Q);else this._realData.meta.newest_id=J.meta.newest_id,this._realData.meta.result_count+=J.meta.result_count,this._realData.data.unshift(...Q);this.updateIncludes(J)}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 F1 extends h{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 L0 extends M0{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class N0 extends M0{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class D0 extends F1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class H0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class U0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class x0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class O0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class S0 extends h{get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class R0 extends S0{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class _0 extends S0{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class u extends h{getItemArray(){return this.users}get users(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class k0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class f0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class C0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class V0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class T0 extends u{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class P0 extends u{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class b0 extends u{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class w0 extends u{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class Z4 extends h{getItemArray(){return this.lists}get lists(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class q0 extends Z4{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class v0 extends Z4{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class I0 extends Z4{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class M1 extends P{constructor(){super(...arguments);this._prefix=Q1}}class $4 extends h{getItemArray(){return this.events}get events(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class y0 extends $4{constructor(){super(...arguments);this._endpoint="dm_events"}}class A0 extends $4{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class h0 extends $4{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class L1 extends P{constructor(){super(...arguments);this._prefix=d}get labs(){if(this._labs)return this._labs;return this._labs=new M1(this)}async search(W,Z={}){let $=typeof W==="string"?{...Z,query:W}:{...W},J=await this.get("tweets/search/recent",$,{fullResponse:!0});return new L0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async searchAll(W,Z={}){let $={...Z,query:W},J=await this.get("tweets/search/all",$,{fullResponse:!0});return new N0({realData:J.data,rateLimit:J.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:$,...J}=Z,Q=await this.get("tweets/:id/retweeted_by",J,{fullResponse:!0,params:{id:W}});if(!$)return Q.data;return new w0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async tweetLikedBy(W,Z={}){let{asPaginator:$,...J}=Z,Q=await this.get("tweets/:id/liking_users",J,{fullResponse:!0,params:{id:W}});if(!$)return Q.data;return new b0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:J,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 H0({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 U0({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 x0({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 D0({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 O0({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:$,...J}=Z,Q={id:W};if(!$)return this.get("users/:id/followers",J,{params:Q});let Y=await this.get("users/:id/followers",J,{fullResponse:!0,params:Q});return new C0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:J,sharedParams:Q})}async following(W,Z={}){let{asPaginator:$,...J}=Z,Q={id:W};if(!$)return this.get("users/:id/following",J,{params:Q});let Y=await this.get("users/:id/following",J,{fullResponse:!0,params:Q});return new V0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:J,sharedParams:Q})}async userLikedTweets(W,Z={}){let $={id:W},J=await this.get("users/:id/liked_tweets",Z,{fullResponse:!0,params:$});return new R0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userBlockingUsers(W,Z={}){let $={id:W},J=await this.get("users/:id/blocking",Z,{fullResponse:!0,params:$});return new k0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userMutingUsers(W,Z={}){let $={id:W},J=await this.get("users/:id/muting",Z,{fullResponse:!0,params:$});return new f0({realData:J.data,rateLimit:J.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},J=await this.get("users/:id/owned_lists",Z,{fullResponse:!0,params:$});return new q0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMemberships(W,Z={}){let $={id:W},J=await this.get("users/:id/list_memberships",Z,{fullResponse:!0,params:$});return new v0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowed(W,Z={}){let $={id:W},J=await this.get("users/:id/followed_lists",Z,{fullResponse:!0,params:$});return new I0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listTweets(W,Z={}){let $={id:W},J=await this.get("lists/:id/tweets",Z,{fullResponse:!0,params:$});return new _0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMembers(W,Z={}){let $={id:W},J=await this.get("lists/:id/members",Z,{fullResponse:!0,params:$});return new T0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowers(W,Z={}){let $={id:W},J=await this.get("lists/:id/followers",Z,{fullResponse:!0,params:$});return new P0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEvents(W={}){let Z=await this.get("dm_events",W,{fullResponse:!0});return new y0({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:{...W}})}async listDmEventsWithParticipant(W,Z={}){let $={participant_id:W},J=await this.get("dm_conversations/with/:participant_id/dm_events",Z,{fullResponse:!0,params:$});return new A0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEventsOfConversation(W,Z={}){let $={dm_conversation_id:W},J=await this.get("dm_conversations/:dm_conversation_id/dm_events",Z,{fullResponse:!0,params:$});return new h0({realData:J.data,rateLimit:J.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:n1,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:n1,autoConnect:W})}sample10Stream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample10/stream",Z,{payloadIsError:n1,autoConnect:W})}complianceJobs(W){return this.get("compliance/jobs",W)}complianceJob(W){return this.get("compliance/jobs/:id",void 0,{params:{id:W}})}async sendComplianceJob(W){let Z=await this.post("compliance/jobs",{type:W.type,name:W.name}),$=W.ids instanceof Buffer?W.ids:Buffer.from(W.ids.join(`
|
|
64
|
+
</html>`}function Q6(W){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Authorization failed</title></head><body style="font-family: system-ui, sans-serif; padding: 24px"><h1 style="font-size: 1.2rem">This connection could not be authorized</h1><p>${b(W)}</p></body></html>`}function b(W){return W.replace(/[&<>"']/g,(Z)=>`&#${Z.charCodeAt(0)};`)}var f4="gmcp_at_",C4="gmcp_rt_",Y6="gmcp_ac_",bW="gmcp_c_",wW="gmcp_cs_",V4="gemi.mcp.oauth.ticket.v1",K6="gemi.mcp.oauth.consent.v1",qW=600000,G6=120000,v4=16384,vW={limit:20,window:3600},IW={limit:60,window:60},m1=["none","client_secret_post","client_secret_basic"];class M extends Error{error;description;status;headers;constructor(W,Z,$=400,J={}){super(Z);this.error=W;this.description=Z;this.status=$;this.headers=J}}class H6{options;name="oauth";context;issuer;base;accessTtl;refreshTtl;constructor(W){this.options=W;let Z=W?.store;for(let $ of["createClient","findClient","saveCode","findCode","saveToken","findToken","use","revokeFamily"])if(typeof Z?.[$]!=="function")throw Error(`McpOAuthServer: store.${$} is missing. Use MemoryMcpOAuthStore, or implement McpOAuthStore.`);if(typeof W.findUser!=="function")throw Error("McpOAuthServer: findUser(id) is required: it loads the user a token was issued to.");if(W.consentPath!==void 0&&!/^\/[^/\\]/.test(W.consentPath))throw Error('McpOAuthServer: consentPath must be a path on this app, like "/oauth/consent".');this.accessTtl=z6("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=z6("refreshTokenTtl",W.refreshTokenTtl,2592000)}get store(){return this.options.store}boot(W){this.context=W;let Z=new URL(W.resource);this.issuer=Z.origin,this.base=`${Z.pathname}/oauth`}async resolve(W){let Z=y4(W);if(!Z?.startsWith(f4))return null;let $=await this.store.findToken(g(Z)),J=(Y)=>({ok:!1,error:"invalid_token",description:Y});if(!$||$.kind!=="access")return J("The access token is not valid.");if($.expiresAt<=Date.now())return J("The access token expired.");if($.resource!==this.context.resource)return J("The access token was not issued for this server.");let Q=await this.options.findUser($.userId);if(!Q)return J("The access token is not valid.");return{ok:!0,principal:{user:Q,via:this.name,id:$.familyId,scopes:$.scopes,clientId:$.clientId}}}challenge(){let W=this.scopeNames().join(" ");return`Bearer resource_metadata="${this.resourceMetadataUrl()}", scope="${W}"`}async handle(W){let Z=new URL(W.url).pathname,Q={[`/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-protected-resource"]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-authorization-server"]:{methods:["GET"],cors:!0,run:()=>this.serverMetadata()},[`${this.base}/register`]:{methods:["POST"],cors:!0,run:()=>this.register(W)},[`${this.base}/authorize`]:{methods:["GET"],cors:!1,run:()=>this.authorize(W)},[`${this.base}/consent`]:{methods:["GET","POST"],cors:!1,run:()=>W.method==="POST"?this.decide(W):this.consentScreen(W)},[`${this.base}/token`]:{methods:["POST"],cors:!0,run:()=>this.token(W)},[`${this.base}/revoke`]:{methods:["POST"],cors:!0,run:()=>this.revoke(W)}}[Z];if(!Q)return null;if(Z===`${this.base}/register`&&this.options.registration===!1)return null;let Y=Q.cors?yW:{};if(W.method==="OPTIONS"&&Q.cors)return new Response(null,{status:204,headers:{...Y,"Access-Control-Allow-Methods":Q.methods.join(", "),"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}});if(!Q.methods.includes(W.method))return new Response(null,{status:405,headers:{...Y,Allow:Q.methods.join(", ")}});let K;try{K=await Q.run()}catch(G){if(!(G instanceof M))throw G;K=O1({error:G.error,error_description:G.description},G.status,G.headers)}for(let[G,z]of Object.entries(Y))K.headers.set(G,z);return K}async consent(W,Z){if(!Z)return null;let $=c1(V4,"gat1",W);if(!$)return null;let J=await this.store.findClient($.c);if(!J||!J.redirectUris.some((G)=>P4(G,$.r)))return null;let Q=String(Z.id),Y=q4(K6,"gcs1",{t:X6(W),u:Q,exp:$.exp}),K=new Map(this.context.registry.scopes().map((G)=>[G.name,G.description]));return{client:{id:J.clientId,name:J.clientName,redirectHost:new URL($.r).host},scopes:$.s.map((G)=>({name:G,description:K.get(G)??G})),user:{id:Q,label:this.userLabel(Z)},form:{action:`${this.issuer}${this.base}/consent`,method:"POST",fields:{request:W,csrf:Y}}}}resourceMetadata(){return O1({resource:this.context.resource,authorization_servers:[this.issuer],scopes_supported:this.scopeNames(),bearer_methods_supported:["header"]})}serverMetadata(){return O1({issuer:this.issuer,authorization_endpoint:`${this.issuer}${this.base}/authorize`,token_endpoint:`${this.issuer}${this.base}/token`,...this.options.registration===!1?{}:{registration_endpoint:`${this.issuer}${this.base}/register`},revocation_endpoint:`${this.issuer}${this.base}/revoke`,scopes_supported:this.scopeNames(),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],token_endpoint_auth_methods_supported:m1,revocation_endpoint_auth_methods_supported:m1,code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,client_id_metadata_document_supported:!1})}async register(W){let Z=this.options.registration||{},$=await w4(`mcp-oauth-register:${D6(new b4(W,{},"api",`${this.base}/register`))}`,Z.rateLimit??vW);if($!==null)throw new M("slow_down","Too many registrations from this address.",429,{"Retry-After":String($)});if(!/^application\/json\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new M("invalid_client_metadata","Send the client metadata as application/json.");let J;try{J=JSON.parse(await I4(W,v4))}catch{throw new M("invalid_client_metadata","The client metadata is not JSON, or is too large.")}if(typeof J!=="object"||J===null||Array.isArray(J))throw new M("invalid_client_metadata","The client metadata must be a JSON object.");let Q=J.redirect_uris;if(!Array.isArray(Q)||Q.length===0||Q.length>10)throw new M("invalid_redirect_uri","redirect_uris must list one to ten URIs.");for(let L of Q){let H=EW(L);if(H)throw new M("invalid_redirect_uri",`${String(L).slice(0,200)}: ${H}`);if(Z.allowRedirectUri&&Z.allowRedirectUri(new URL(L))!==!0)throw new M("invalid_redirect_uri",`${L}: this server does not accept it.`)}let Y=J.token_endpoint_auth_method??"client_secret_basic";if(!m1.includes(Y))throw new M("invalid_client_metadata",`token_endpoint_auth_method must be one of ${m1.join(", ")}.`);let K=J.grant_types??["authorization_code"];if(!Array.isArray(K)||K.some((L)=>L!=="authorization_code"&&L!=="refresh_token"))throw new M("invalid_client_metadata","grant_types may only be authorization_code and refresh_token.");let G=J.response_types??["code"];if(!Array.isArray(G)||G.some((L)=>L!=="code"))throw new M("invalid_client_metadata","response_types may only be code.");let z=F6(J.client_name,100,"client_name"),X=F6(J.client_uri,512,"client_uri");if(X!==null&&!hW(X))throw new M("invalid_client_metadata","client_uri must be an https URL.");let B=Y==="none"?null:`${wW}${t(32).toString("base64url")}`,j={clientId:`${bW}${t(16).toString("base64url")}`,clientSecretHash:B?g(B):null,tokenEndpointAuthMethod:Y,redirectUris:[...Q],clientName:z,clientUri:X,createdAt:Date.now()};return await this.store.createClient(j),O1({client_id:j.clientId,client_id_issued_at:Math.floor(j.createdAt/1000),...B?{client_secret:B,client_secret_expires_at:0}:{},redirect_uris:j.redirectUris,token_endpoint_auth_method:Y,grant_types:K,response_types:G,...z?{client_name:z}:{},...X?{client_uri:X}:{}},201)}async authorize(W){let Z=new URL(W.url).searchParams;for(let S of new Set(Z.keys()))if(Z.getAll(S).length>1)return A(`The parameter ${S} was sent more than once.`);let $=Z.get("client_id"),J=$?await this.store.findClient($):null;if(!J)return A("The application is not registered with this server.");let Q=Z.get("redirect_uri")??(J.redirectUris.length===1?J.redirectUris[0]:null);if(!Q||!J.redirectUris.some((S)=>P4(S,Q)))return A("The redirect URI is not one the application registered.");let Y=Z.get("state"),K=(S,o)=>this.redirectBack(Q,Y,{error:S,error_description:o});if(Z.get("response_type")!=="code")return K("unsupported_response_type","Only response_type=code is supported.");let G=Z.get("code_challenge");if(Z.get("code_challenge_method")!=="S256"||!G||!/^[A-Za-z0-9_-]{43}$/.test(G))return K("invalid_request","PKCE is required: code_challenge with code_challenge_method=S256.");let z=Z.get("resource");if(z!==null&&!M6(z,this.context.resource))return K("invalid_target","The resource is not this server's.");if(Y!==null&&Y.length>2048)return K("invalid_request","state is too long.");let X=this.scopeNames(),B=Z.get("scope"),j=X;if(B!==null&&B.trim()!==""){if(j=[...new Set(B.split(" ").filter((S)=>X.includes(S)))],j.length===0)return K("invalid_scope","None of the requested scopes exist here.")}let L=q4(V4,"gat1",{c:J.clientId,r:Q,s:j,cc:G,st:Y,n:t(16).toString("base64url"),exp:Date.now()+qW}),H=this.options.consentPath??`${this.base}/consent`;return T4(`${this.issuer}${H}?request=${encodeURIComponent(L)}`,302)}async consentScreen(W){let Z=new URL(W.url).searchParams.get("request"),$=await this.sessionUser(W);if(!$){let Q=`${this.base}/consent?request=${encodeURIComponent(Z??"")}`,Y=this.options.signInPath??_(e).config.signInPath;return T4(`${Y}${Y.includes("?")?"&":"?"}redirect=${encodeURIComponent(Q)}`,302)}let J=await this.consent(Z,$);if(!J)return A("This authorization request has expired or is not valid. Start again from the application.");return new Response(J6(J,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:g1})}async decide(W){let Z=W.headers.get("origin");if(!(Z!==null?Z===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return A("This decision did not come from this site's consent page.",403);if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))return A("The decision must be a form post.");let J;try{J=new URLSearchParams(await I4(W,v4))}catch{return A("The decision is too large.")}let Q=J.get("request"),Y=c1(V4,"gat1",Q),K=c1(K6,"gcs1",J.get("csrf")),G=await this.sessionUser(W);if(!Y||!K||!G||K.t!==X6(Q)||K.u!==String(G.id))return A("This authorization request has expired or is not valid. Start again from the application.",403);let z=await this.store.findClient(Y.c);if(!z||!z.redirectUris.some((B)=>P4(B,Y.r)))return A("The application is not registered with this server.");if(!await this.store.use(`ticket:${Y.n}`,Y.exp))return A("This request was already answered. Start again from the application.");if(J.get("decision")!=="allow")return this.redirectBack(Y.r,Y.st,{error:"access_denied",error_description:"The user denied the request."},303);let X=`${Y6}${t(32).toString("base64url")}`;return await this.store.saveCode({hash:g(X),clientId:z.clientId,userId:String(G.id),redirectUri:Y.r,codeChallenge:Y.cc,scopes:Y.s,resource:this.context.resource,familyId:t(16).toString("base64url"),expiresAt:Date.now()+G6}),this.redirectBack(Y.r,Y.st,{code:X},303)}async token(W){let Z=await j6(W),$=await this.authenticateClient(W,Z),J=await w4(`mcp-oauth-token:${$.clientId}`,IW);if(J!==null)throw new M("slow_down","Too many token requests.",429,{"Retry-After":String(J)});let Q=Z.get("resource");if(Q!==null&&!M6(Q,this.context.resource))throw new M("invalid_target","The resource is not this server's.");switch(Z.get("grant_type")){case"authorization_code":{let Y=Z.get("code")??"",K=Y.startsWith(Y6)?await this.store.findCode(g(Y)):null;if(!K||K.clientId!==$.clientId)throw new M("invalid_grant","The authorization code is not valid.");if(!await this.store.use(K.hash,K.expiresAt+G6))throw await this.store.revokeFamily(K.familyId),new M("invalid_grant","The authorization code was already used.");if(K.expiresAt<=Date.now())throw new M("invalid_grant","The authorization code expired.");if(Z.get("redirect_uri")!==null&&Z.get("redirect_uri")!==K.redirectUri)throw new M("invalid_grant","redirect_uri is not the one the code was issued to.");let G=Z.get("code_verifier");if(!G||!/^[A-Za-z0-9._~-]{43,128}$/.test(G)||!B6(AW(G),K.codeChallenge))throw new M("invalid_grant","The PKCE code_verifier does not match.");if(!await this.options.findUser(K.userId))throw new M("invalid_grant","The authorization code is not valid.");return await this.issue(K)}case"refresh_token":{let Y=Z.get("refresh_token")??"",K=Y.startsWith(C4)?await this.store.findToken(g(Y)):null;if(!K||K.kind!=="refresh"||K.clientId!==$.clientId)throw new M("invalid_grant","The refresh token is not valid.");if(K.expiresAt<=Date.now())throw new M("invalid_grant","The refresh token expired.");if(!await this.store.use(K.hash,K.expiresAt))throw await this.store.revokeFamily(K.familyId),new M("invalid_grant","The refresh token was already used.");if(K.resource!==this.context.resource)throw new M("invalid_grant","The refresh token was not issued for this server.");let G=K.scopes,z=Z.get("scope");if(z!==null&&z.trim()!==""){let X=[...new Set(z.split(" ").filter(Boolean))];if(X.some((B)=>!K.scopes.includes(B)))throw new M("invalid_scope","A refresh can only narrow the scopes that were granted.");G=X}if(!await this.options.findUser(K.userId))throw new M("invalid_grant","The refresh token is not valid.");return await this.issue({...K,scopes:G})}default:throw new M("unsupported_grant_type","grant_type must be authorization_code or refresh_token.")}}async issue(W){let Z=Date.now(),$=this.scopeNames(),J=W.scopes.filter((G)=>$.includes(G)),Q=`${f4}${t(32).toString("base64url")}`,Y=`${C4}${t(32).toString("base64url")}`,K={clientId:W.clientId,userId:W.userId,scopes:J,resource:W.resource,familyId:W.familyId};return await this.store.saveToken({...K,hash:g(Q),kind:"access",expiresAt:Z+this.accessTtl*1000}),await this.store.saveToken({...K,hash:g(Y),kind:"refresh",expiresAt:Z+this.refreshTtl*1000}),O1({access_token:Q,token_type:"Bearer",expires_in:this.accessTtl,refresh_token:Y,scope:J.join(" ")})}async revoke(W){let Z=await j6(W),$=await this.authenticateClient(W,Z),J=Z.get("token")??"";if(J.startsWith(f4)||J.startsWith(C4)){let Q=await this.store.findToken(g(J));if(Q&&Q.clientId===$.clientId)await this.store.revokeFamily(Q.familyId)}return new Response(null,{status:200,headers:{"Cache-Control":"no-store"}})}async authenticateClient(W,Z){let $=/^Basic\s+([A-Za-z0-9+/=]+)$/i.exec(W.headers.get("authorization")??""),J=Z.get("client_id"),Q=Z.get("client_secret");if($){let K=Buffer.from($[1],"base64").toString("utf8"),G=K.indexOf(":");if(G<0)throw r(!0);let z=L6(K.slice(0,G));if(z===null)throw r(!0);if(J!==null&&J!==z)throw r(!0);if(J=z,Q=L6(K.slice(G+1)),Q===null)throw r(!0)}let Y=J?await this.store.findClient(J):null;if(!Y)throw r(Boolean($));if(Y.tokenEndpointAuthMethod==="none"){if(Q)throw r(Boolean($));return Y}if(!Q||!Y.clientSecretHash||!B6(g(Q),Y.clientSecretHash))throw r(Boolean($));return Y}redirectBack(W,Z,$,J=302){let Q=new URL(W);for(let[Y,K]of Object.entries($))Q.searchParams.set(Y,K);if(Z!==null)Q.searchParams.set("state",Z);return Q.searchParams.set("iss",this.issuer),T4(Q.href,J)}async sessionUser(W){let Z=new b4(W,{},"api",this.base).cookies;return await N6(_(e),{cookies:Z,headers:{get:($)=>$.toLowerCase()==="user-agent"?W.headers.get("user-agent"):null}})}userLabel(W){if(this.options.userLabel)return this.options.userLabel(W);let Z=W;return String(Z.email??Z.name??Z.id)}scopeNames(){return this.context.registry.scopes().map((W)=>W.name)}resourceMetadataUrl(){return`${this.issuer}/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`}}var yW={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function z6(W,Z,$){if(Z===void 0)return $;if(!Number.isInteger(Z)||Z<60)throw Error(`McpOAuthServer: ${W} must be a whole number of seconds, at least 60.`);return Z}function g(W){return A4("sha256").update(W).digest("hex")}function X6(W){return A4("sha256").update(W).digest("base64url")}function AW(W){return A4("sha256").update(W).digest("base64url")}function B6(W,Z){let $=Buffer.from(W),J=Buffer.from(Z);return $.length===J.length&&PW($,J)}function O1(W,Z=200,$={}){return new Response(JSON.stringify(W),{status:Z,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache",...$}})}function T4(W,Z){return new Response(null,{status:Z,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function A(W,Z=400){return new Response(Q6(W),{status:Z,headers:g1})}function r(W){return new M("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function I4(W,Z){let $=Number(W.headers.get("content-length"));if(Number.isFinite($)&&$>Z)throw Error("too large");if(!W.body)return"";let J=W.body.getReader(),Q=[],Y=0;for(;;){let{done:K,value:G}=await J.read();if(K)break;if(Y+=G.byteLength,Y>Z)throw await J.cancel(),Error("too large");Q.push(G)}return Buffer.concat(Q).toString("utf8")}async function j6(W){if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new M("invalid_request","Send the request as application/x-www-form-urlencoded.");let Z;try{Z=new URLSearchParams(await I4(W,v4))}catch{throw new M("invalid_request","The request is too large.")}for(let $ of new Set(Z.keys()))if(Z.getAll($).length>1)throw new M("invalid_request",`${$} was sent more than once.`);return Z}function F6(W,Z,$){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>Z||gW(W))throw new M("invalid_client_metadata",`${$} must be text of at most ${Z} characters.`);return W}function hW(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function U6(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function EW(W){if(typeof W!=="string"||W.length>2048)return"not a URI";let Z;try{Z=new URL(W)}catch{return"not an absolute URI"}if(Z.hash||W.includes("#"))return"must not have a fragment";if(Z.username||Z.password)return"must not carry credentials";if(Z.protocol==="https:")return null;if(Z.protocol==="http:"&&U6(Z))return null;return"must be https, or http on a loopback address"}function P4(W,Z){if(W===Z)return!0;let $,J;try{$=new URL(W),J=new URL(Z)}catch{return!1}return $.protocol==="http:"&&J.protocol==="http:"&&U6($)&&$.hostname===J.hostname&&$.pathname===J.pathname&&$.search===J.search&&!J.hash&&!J.username&&!J.password}function M6(W,Z){return W===Z||W===`${Z}/`}function gW(W){for(let Z=0;Z<W.length;Z++){let $=W.charCodeAt(Z);if($<32||$===127)return!0}return!1}function L6(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class x6{clients=new Map;codes=new Map;tokens=new Map;used=new Map;revoked=new Set;async createClient(W){this.clients.set(W.clientId,structuredClone(W))}async findClient(W){let Z=this.clients.get(W);return Z?structuredClone(Z):null}async saveCode(W){this.sweep(),this.codes.set(W.hash,structuredClone(W))}async findCode(W){let Z=this.codes.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async saveToken(W){this.sweep(),this.tokens.set(W.hash,structuredClone(W))}async findToken(W){let Z=this.tokens.get(W);return Z&&!this.revoked.has(Z.familyId)?structuredClone(Z):null}async use(W,Z){if(this.used.has(W))return!1;return this.used.set(W,Z),!0}async revokeFamily(W){this.revoked.add(W);for(let[Z,$]of this.tokens)if($.familyId===W)this.tokens.delete(Z);for(let[Z,$]of this.codes)if($.familyId===W)this.codes.delete(Z)}async families(W){let Z=new Map;for(let $ of this.tokens.values())if($.userId===W&&!this.revoked.has($.familyId)&&$.expiresAt>Date.now())Z.set($.familyId,{familyId:$.familyId,clientId:$.clientId,scopes:[...$.scopes]});return[...Z.values()]}sweep(W=Date.now()){for(let[Z,$]of this.codes)if($.expiresAt<=W)this.codes.delete(Z);for(let[Z,$]of this.tokens)if($.expiresAt<=W)this.tokens.delete(Z);for(let[Z,$]of this.used)if($<=W)this.used.delete(Z)}}class O6{clients;credentials;uses;usesModel;constructor(W){for(let[Z,$]of[["clients",["create","findUnique","findMany"]],["credentials",["create","findFirst","findMany","count","updateMany","deleteMany"]],["uses",["create","deleteMany"]]]){let J=W?.[Z],Q=$.filter((Y)=>typeof J?.[Y]!=="function");if(Q.length>0)throw Error(`PrismaMcpOAuthStore: models.${Z} must be a gemi ORM model or a Prisma delegate (it has no ${Q.join(", ")}()).`)}this.clients=W.clients,this.credentials=W.credentials,this.usesModel=W.uses,this.uses=new h4(W.uses)}async createClient(W){await this.clients.create({data:{clientId:W.clientId,clientSecretHash:W.clientSecretHash,tokenEndpointAuthMethod:W.tokenEndpointAuthMethod,redirectUris:[...W.redirectUris],clientName:W.clientName,clientUri:W.clientUri,createdAt:new Date(W.createdAt)}})}async findClient(W){let Z=await this.clients.findUnique({where:{clientId:W}});if(!Z)return null;return{clientId:Z.clientId,clientSecretHash:Z.clientSecretHash??null,tokenEndpointAuthMethod:Z.tokenEndpointAuthMethod,redirectUris:u1(Z.redirectUris),clientName:Z.clientName??null,clientUri:Z.clientUri??null,createdAt:p1(Z.createdAt)}}async saveCode(W){await this.credentials.create({data:{hash:W.hash,kind:"code",clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,redirectUri:W.redirectUri,codeChallenge:W.codeChallenge,expiresAt:new Date(W.expiresAt)}})}async findCode(W){let Z=await this.findLive(W,["code"]);if(!Z||Z.redirectUri==null||Z.codeChallenge==null)return null;return{hash:Z.hash,clientId:Z.clientId,userId:Z.userId,redirectUri:Z.redirectUri,codeChallenge:Z.codeChallenge,scopes:u1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:p1(Z.expiresAt)}}async saveToken(W){await this.credentials.create({data:{hash:W.hash,kind:W.kind,clientId:W.clientId,userId:W.userId,scopes:[...W.scopes],resource:W.resource,familyId:W.familyId,expiresAt:new Date(W.expiresAt)}})}async findToken(W){let Z=await this.findLive(W,["access","refresh"]);if(!Z)return null;return{hash:Z.hash,kind:Z.kind,clientId:Z.clientId,userId:Z.userId,scopes:u1(Z.scopes),resource:Z.resource,familyId:Z.familyId,expiresAt:p1(Z.expiresAt)}}use(W,Z){return this.uses.consume(W,Z)}async revokeFamily(W){await this.credentials.updateMany({where:{familyId:W,revokedAt:null},data:{revokedAt:new Date}})}nonces(W={}){return new h4(this.usesModel,{prefix:W.prefix??"nonce:"})}async connectedApps(W,Z=new Date){let $=String(W),J=await this.credentials.findMany({where:{userId:$,kind:"refresh",expiresAt:{gt:Z}},orderBy:{createdAt:"asc"}}),Q=await this.revokedFamilies({userId:$}),Y=new Map;for(let X of J){if(Q.has(X.familyId))continue;if(!Y.has(X.familyId))Y.set(X.familyId,X)}if(Y.size===0)return[];let K=[...new Set([...Y.values()].map((X)=>X.clientId))],G=await this.clients.findMany({where:{clientId:{in:K}}}),z=new Map(G.map((X)=>[X.clientId,X]));return[...Y.values()].map((X)=>({familyId:X.familyId,clientId:X.clientId,clientName:z.get(X.clientId)?.clientName??null,clientUri:z.get(X.clientId)?.clientUri??null,scopes:u1(X.scopes),connectedAt:new Date(p1(X.createdAt))})).reverse()}async disconnect(W,Z){if(await this.credentials.count({where:{familyId:Z,userId:String(W)}})===0)return!1;return await this.revokeFamily(Z),!0}async revokeUser(W){await this.credentials.updateMany({where:{userId:String(W),revokedAt:null},data:{revokedAt:new Date}})}async prune(W=Date.now()){let Z=new Date(W-86400000),$=[...await this.revokedFamilies({expiresAt:{lt:Z}})],J=$.length===0?[]:await this.credentials.findMany({where:{familyId:{in:$},expiresAt:{gte:Z}},select:{familyId:!0}}),Q=[...new Set(J.map((Y)=>Y.familyId))];await this.credentials.deleteMany({where:{expiresAt:{lt:Z},...Q.length>0?{OR:[{revokedAt:null},{familyId:{notIn:Q}}]}:{}}}),await this.usesModel.deleteMany({where:{expiresAt:{lt:new Date(W)}}})}async findLive(W,Z){let $=await this.credentials.findFirst({where:{hash:W,kind:{in:Z},revokedAt:null}});if(!$)return null;return await this.credentials.count({where:{familyId:$.familyId,revokedAt:{not:null}}})>0?null:$}async revokedFamilies(W){let Z=await this.credentials.findMany({where:{...W,revokedAt:{not:null}},select:{familyId:!0}});return new Set(Z.map(($)=>$.familyId))}}function u1(W){return Array.isArray(W)?W.map(String):[]}function p1(W){return W instanceof Date?W.getTime():new Date(W).getTime()}class R1 extends w{application;previous;dispatched=[];static install(W){let Z=W.resolved(w)?W.make(w):void 0;if(Z instanceof R1)return Z;let $=new R1(W,Z);return W.instance(w,$),$}constructor(W,Z){super({listeners:[]});this.application=W;this.previous=Z}dispatch(W,Z){this.dispatched.push({event:W,args:Z})}async dispatchAndWait(W,Z){this.dispatched.push({event:W,args:Z})}restore(){if(this.previous){this.application.instance(w,this.previous);return}this.application.forget(w)}assertDispatched(W,Z){let $=S1(W);if(this.matching($,Z).length>0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} to have been dispatched. ${this.summary($,Z!==void 0)}`)}assertNotDispatched(W,Z){let $=S1(W),J=this.matching($,Z);if(J.length===0)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} not to have been dispatched, but it was dispatched ${E4(J.length)}: ${d1(J)}.`)}assertDispatchedTimes(W,Z,$){let J=S1(W),Q=this.matching(J,$);if(Q.length===Z)return;throw Error(`Expected ${J}${$?" matching the predicate":""} to have been dispatched ${E4(Z)}, but it was dispatched ${E4(Q.length)}. ${this.summary(J,$!==void 0)}`)}assertNothingDispatched(){if(this.dispatched.length===0)return;let W=this.dispatched.length;throw Error(`Expected nothing to have been dispatched, but ${W} ${W===1?"event was":"events were"}: ${d1(this.dispatched)}.`)}matching(W,Z){return this.dispatched.filter(($)=>S1($.event.constructor)===W&&(Z===void 0||Z($.event)))}summary(W,Z){if(this.dispatched.length===0)return"Nothing was dispatched.";let $=this.matching(W);if(Z&&$.length>0)return`Dispatched ${W}: ${d1($)}.`;return`Dispatched: ${d1(this.dispatched)}.`}}function S1(W){return W.name}function E4(W){return`${W} ${W===1?"time":"times"}`}function d1(W){return W.map(mW).join(", ")}function mW(W){let Z=S1(W.event.constructor),$=W.args??Object.values({...W.event});return`${Z}(${$.map(cW).join(", ")})`}function cW(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class l1{static name="unset";static afterCommit=!1;static dispatch(...W){S6(this),_(w).dispatch(new this(...W),W)}static dispatchAndWait(...W){return S6(this),_(w).dispatchAndWait(new this(...W),W)}static fake(){return R1.install(uW())}}function uW(){try{return _()}catch(W){throw Error("Event.fake() needs a booted application. The fake works by replacing the container's EventManager with a recorder, so there has to be a "+"container to replace it in \u2014 and a dispatch finds the recorder the "+"same way, by resolving from that container. Boot the app's kernel in the test's setup: `const kernel = new Kernel(); kernel.boot()` is enough on its own, since that is the phase that publishes the application every dispatch outside a request resolves through.",{cause:W})}}function S6(W){if(W.name!=="unset"&&W.name!=="")return;throw Error("Cannot dispatch an event with no name. Add `static name` to this Event "+"subclass \u2014 the listener registry is keyed by that string, and by that "+"string alone, so an event without one cannot reach a listener.")}class k6 extends l1{constructor(){super();Object.defineProperty(this,g4,{value:!0,enumerable:!1})}broadcastAs(){return this.constructor.name}broadcastWith(){return}channel(W,...Z){return{topic:R6(W,Z[0]??{}),pattern:W}}}function V6(){try{let W=_();if(typeof W?.bound==="function"&&W.bound(e))return W.make(e).config.emailCode.fixedCode}catch{}return}function pW(){return f6(V6())}function dW(W){return C6(W,V6())}function lW(W){let Z=null;try{let Y=_();if(typeof Y?.bound==="function"&&Y.bound(m4))Z=_(m4).resolver??null}catch{Z=null}if(Z)return Z.publicOrigin(W);let $=new URL(W.url),J=W.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();return`${J==="http"||J==="https"?J:$.protocol.slice(0,-1)}://${$.host}`}function nW(W,Z){let $=typeof W==="string"?W.trim().replace(/\/+$/,""):"",J=URL.canParse($)?new URL($):null;if(!J||J.protocol!=="http:"&&J.protocol!=="https:"||J.origin!==$)throw Error(`${Z}: resolve() returned origin ${JSON.stringify(W)}, which is not an http(s) origin such as https://example.com.`);return $}var T6=new WeakMap;function p(W,Z,$){if(!$.resolve)return Promise.resolve({clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.staticRedirectUri()});let J=Z?.rawRequest;if(!Z||!J)return Promise.resolve(null);let Q=T6.get(W);if(!Q)Q=new WeakMap,T6.set(W,Q);let Y=Q.get(J);if(Y)return Y;let K=$.resolve,G=(async()=>{let z=await K({req:Z,origin:lW(J)});if(z===null||z===void 0)return null;let X=z.origin!==void 0?nW(z.origin,$.name):$.staticOrigin();return{clientId:z.clientId??$.clientId,clientSecret:z.clientSecret??$.clientSecret,redirectUri:`${X}${$.redirectPath}`}})();return Q.set(J,G),G.catch(()=>Q.delete(J)),G}var iW={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET,redirectPath:"/auth/oauth/google/callback",scope:"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",authorizationParams:{}};function sW(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class P6 extends m{config;constructor(W={}){super();this.config={...iW,...W}}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"GoogleOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GoogleOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}authorizationUrl(W,Z){let $=new URL("https://accounts.google.com/o/oauth2/v2/auth"),J={include_granted_scopes:"true",...this.config.authorizationParams,scope:this.config.scope,response_type:"code",redirect_uri:W.redirectUri,client_id:W.clientId};if(Z)J.state=Z.state,J.code_challenge=Z.codeChallenge,J.code_challenge_method=Z.codeChallengeMethod;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new U("missing_code");let J=this.config.resolve?await this.clientFor(W):this.staticClient();if(!J)throw new U("unknown_provider");let Q=new URLSearchParams({code:$,client_id:J.clientId,client_secret:J.clientSecret,grant_type:"authorization_code",redirect_uri:J.redirectUri});if(Z?.codeVerifier)Q.set("code_verifier",Z.codeVerifier);let Y=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Q.toString()}),K=await Y.json().catch(()=>({}));if(!Y.ok||typeof K?.access_token!=="string"||K.access_token==="")throw console.error("Google OAuth error: token exchange failed",K?.error??Y.status),new U(sW(K?.error,"exchange_failed"));let z=await(await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${K.access_token}`}})).json().catch(()=>({}));if(typeof z.sub!=="string"||z.sub==="")return console.error("Google OAuth error: sub not found in user info response",z),{};if(!z.email)console.error("Google OAuth error: email not found in user info response",z);return{providerId:z.sub,name:z.name,email:z.email,emailVerified:z.email_verified===!0||z.email_verified==="true"}}}var oW="https://github.com/login/oauth/authorize",aW="https://github.com/login/oauth/access_token",b6="https://api.github.com";function tW(W,Z){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:Z}class w6 extends m{config;constructor(W={}){super();this.config={clientId:process.env.GITHUB_CLIENT_ID??"",clientSecret:process.env.GITHUB_CLIENT_SECRET??"",redirectPath:"/auth/oauth/github/callback",scope:"read:user user:email",authorizationParams:{},...W}}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"GitHubOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}staticClient(){return{clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:this.redirectUri()}}getRedirectUrl(W,Z){if(!this.config.resolve)return this.authorizationUrl(this.staticClient(),Z);return this.clientFor(W??null).then(($)=>{if(!$)throw Error("GitHubOAuthProvider is not offered on this request.");return this.authorizationUrl($,Z)})}authorizationUrl(W,Z){let $=new URL(oW),J={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,scope:this.config.scope,response_type:"code"};if(Z)J.state=Z.state,J.code_challenge=Z.codeChallenge,J.code_challenge_method=Z.codeChallengeMethod;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new U("missing_code");let J=this.config.resolve?await this.clientFor(W):this.staticClient();if(!J)throw new U("unknown_provider");let Q=new URLSearchParams({client_id:J.clientId,client_secret:J.clientSecret,code:$,redirect_uri:J.redirectUri});if(Z?.codeVerifier)Q.set("code_verifier",Z.codeVerifier);let Y=await fetch(aW,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/x-www-form-urlencoded"},body:Q.toString()}),K=await Y.json().catch(()=>({}));if(!Y.ok||typeof K?.access_token!=="string"||K.access_token==="")throw console.error("GitHub OAuth error: token exchange failed",K?.error??Y.status),new U(tW(K?.error,"exchange_failed"));let G={Accept:"application/vnd.github+json",Authorization:`Bearer ${K.access_token}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"gemi"},z=await fetch(`${b6}/user`,{headers:G}),X=await z.json().catch(()=>({}));if(!z.ok||typeof X?.id!=="number"||!Number.isSafeInteger(X.id))return console.error("GitHub OAuth error: no user id in the /user response",z.status),{};let B=typeof X.login==="string"&&X.login!==""?X.login:void 0,j=typeof X.name==="string"&&X.name!==""?X.name:B,L=await this.primaryVerifiedEmail(G),H=typeof X.email==="string"&&X.email!==""?X.email:void 0;return{providerId:String(X.id),username:B,name:j,...L?{email:L,emailVerified:!0}:H?{email:H,emailVerified:!1}:{}}}async primaryVerifiedEmail(W){let Z=await fetch(`${b6}/user/emails`,{headers:W}).catch(()=>null);if(!Z?.ok){console.error("GitHub OAuth error: could not read /user/emails",Z?.status);return}let $=await Z.json().catch(()=>null);if(!Array.isArray($))return;let J=$.find((Q)=>Q?.primary===!0&&Q.verified===!0);return typeof J?.email==="string"&&J.email!==""?J.email:void 0}}var d="https://api.x.com/2/",Q1="https://api.x.com/labs/2/",l="https://api.x.com/1.1/",c="https://upload.x.com/1.1/",q6="https://stream.x.com/1.1/",Y1="https://ads-api.x.com/12/",K1="https://ads-api-sandbox.twitter.com/12/";class c4{constructor({realData:W,rateLimit:Z,instance:$,queryParams:J,sharedParams:Q}){this._maxResultsWhenFetchLast=100,this._realData=W,this._rateLimit=Z,this._instance=$,this._queryParams=J,this._sharedParams=Q}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(W){return this._instance.get(this.getEndpoint(),W,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(W,Z){return new this.constructor({realData:W.data,rateLimit:W.rateLimit,instance:this._instance,queryParams:Z,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(W){return{...W?{max_results:W}:{},...this._queryParams}}async next(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchNext(W){let Z=this.getNextQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!0),this}async fetchLast(W=1/0){let Z=this.getNextQueryParams(this._maxResultsWhenFetchLast),$=0;while($<W&&this._isRateLimitOk){let J=await this.makeRequest(Z);if(await this.refreshInstanceFromResult(J,!0),$+=this.getPageLengthFromRequest(J),this.isFetchLastOver(J))break;Z=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var W;return{...(W=this._rateLimit)!==null&&W!==void 0?W:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData),yield*$.getItemArray(),W=$}}async*fetchAndIterate(){for(let $ of this.getItemArray())yield[$,this];let W=this,Z=this.canFetchNextPage(this._realData);while(Z&&this._isRateLimitOk&&W.getItemArray().length>0){let $=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:$._realData,headers:{},rateLimit:$._rateLimit},!0),Z=this.canFetchNextPage($._realData);for(let J of $.getItemArray())yield[J,$];this._rateLimit=$._rateLimit,W=$}}}class u4 extends c4{async previous(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return this.makeNewInstanceFromResult($,Z)}async fetchPrevious(W){let Z=this.getPreviousQueryParams(W),$=await this.makeRequest(Z);return await this.refreshInstanceFromResult($,!1),this}}var G1=c4;class x extends G1{getNextQueryParams(W){var Z;return{...this._queryParams,cursor:(Z=this._realData.next_cursor_str)!==null&&Z!==void 0?Z:this._realData.next_cursor,...W?{count:W}:{}}}isFetchLastOver(W){return!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!this.isNextCursorInvalid(W.next_cursor)||!this.isNextCursorInvalid(W.next_cursor_str)}isNextCursorInvalid(W){return W===void 0||W===0||W===-1||W==="0"||W==="-1"}}class p4 extends x{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.events.push(...$.events),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class d4 extends x{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.welcome_messages.push(...$.welcome_messages),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var D;(function(W){W.Jpeg="image/jpeg",W.Mp4="video/mp4",W.Mov="video/quicktime",W.Gif="image/gif",W.Png="image/png",W.Srt="text/plain",W.Webp="image/webp"})(D||(D={}));var n;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(n||(n={}));var _1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(_1||(_1={}));class n1 extends Error{constructor(){super(...arguments);this.error=!0}}class k1 extends n1{constructor(W,Z){super(W);this.type=_1.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class f1 extends n1{constructor(W,Z){super(W);this.type=_1.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z})}get request(){return this._options.request}get response(){return this._options.response}get responseError(){return this._options.responseError}get rawContent(){return this._options.rawContent}toJSON(){return{type:this.type,error:this.responseError}}}class C1 extends n1{constructor(W,Z){super(W);if(this.type=_1.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:Z}),this.code=Z.code,this.headers=Z.headers,this.rateLimit=Z.rateLimit,Z.data&&typeof Z.data==="object"&&"error"in Z.data&&!Z.data.errors){let $={...Z.data};$.errors=[{code:W1.InternalError,message:$.error}],this.data=$}else this.data=Z.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...W){let Z=this.errors;if(!(Z===null||Z===void 0?void 0:Z.length))return!1;if("code"in Z[0])return Z.some((Q)=>W.includes(Q.code));let $=this.data;return W.includes($.type)}get errors(){var W;return(W=this.data)===null||W===void 0?void 0:W.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(W1.AuthTimestampInvalid,W1.AuthenticationFail,W1.BadAuthenticationData,W1.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var W1;(function(W){W[W.InvalidCoordinates=3]="InvalidCoordinates",W[W.NoLocationFound=13]="NoLocationFound",W[W.AuthenticationFail=32]="AuthenticationFail",W[W.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",W[W.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",W[W.AuthTimestampInvalid=135]="AuthTimestampInvalid",W[W.BadAuthenticationData=215]="BadAuthenticationData",W[W.NoUserMatch=17]="NoUserMatch",W[W.UserNotFound=50]="UserNotFound",W[W.ResourceNotFound=34]="ResourceNotFound",W[W.TweetNotFound=144]="TweetNotFound",W[W.TweetNotVisible=179]="TweetNotVisible",W[W.NotAllowedResource=220]="NotAllowedResource",W[W.MediaIdNotFound=325]="MediaIdNotFound",W[W.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",W[W.TweetViolatedRules=422]="TweetViolatedRules",W[W.TargetUserSuspended=63]="TargetUserSuspended",W[W.YouAreSuspended=64]="YouAreSuspended",W[W.AccountUpdateFailed=120]="AccountUpdateFailed",W[W.NoSelfSpamReport=36]="NoSelfSpamReport",W[W.NoSelfMute=271]="NoSelfMute",W[W.AccountLocked=326]="AccountLocked",W[W.RateLimitExceeded=88]="RateLimitExceeded",W[W.NoDMRightForApp=93]="NoDMRightForApp",W[W.OverCapacity=130]="OverCapacity",W[W.InternalError=131]="InternalError",W[W.TooManyFollowings=161]="TooManyFollowings",W[W.TweetLimitExceeded=185]="TweetLimitExceeded",W[W.DuplicatedTweet=187]="DuplicatedTweet",W[W.TooManySpamReports=205]="TooManySpamReports",W[W.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",W[W.NoWriteRightForApp=261]="NoWriteRightForApp",W[W.TweetActionsDisabled=425]="TweetActionsDisabled",W[W.TweetRepliesRestricted=433]="TweetRepliesRestricted",W[W.NamedParameterMissing=38]="NamedParameterMissing",W[W.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",W[W.TweetTextTooLong=186]="TweetTextTooLong",W[W.MissingUrlParameter=195]="MissingUrlParameter",W[W.NoMultipleGifs=323]="NoMultipleGifs",W[W.InvalidMediaIds=324]="InvalidMediaIds",W[W.InvalidUrl=407]="InvalidUrl",W[W.TooManyTweetAttachments=386]="TooManyTweetAttachments",W[W.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",W[W.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",W[W.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",W[W.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",W[W.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",W[W.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",W[W.UnableToSendDM=151]="UnableToSendDM",W[W.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",W[W.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",W[W.DMTextTooLong=354]="DMTextTooLong",W[W.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",W[W.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",W[W.SuspendedApplication=416]="SuspendedApplication",W[W.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(W1||(W1={}));var v6;(function(W){W.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",W.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",W.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",W.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",W.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",W.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",W.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",W.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",W.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",W.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",W.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",W.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",W.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(v6||(v6={}));var F;(function(W){W.Connected="connected",W.ConnectError="connect error",W.ConnectionError="connection error",W.ConnectionClosed="connection closed",W.ConnectionLost="connection lost",W.ReconnectAttempt="reconnect attempt",W.Reconnected="reconnected",W.ReconnectError="reconnect error",W.ReconnectLimitExceeded="reconnect limit exceeded",W.DataKeepAlive="data keep-alive",W.Data="data event content",W.DataError="data twitter error",W.TweetParseError="data tweet parse error",W.Error="stream error"})(F||(F={}));class V1{constructor(W){this.value=W}}import*as D0 from"fs";var R={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function l4(W){let Z={value:void 0,promise:W().then(($)=>{return Z.value=$,$})};return Z}function i1(W){if(Array.isArray(W))return W;return[W]}function y6(W){for(let Z of Object.keys(W))if(W[Z]===void 0)delete W[Z]}function s1(W){return typeof W==="object"&&"errors"in W&&!("data"in W)}function T1(W){if(Array.isArray(W)&&W.length>1)return!0;return W.toString().includes(",")}var I6=new Set;function n4(W){if(typeof console>"u"||!console.warn||!R.deprecationWarnings)return;let Z=`${W.instance}-${W.method}-${W.problem}`;if(I6.has(Z))return;let $=`[twitter-api-v2] Deprecation warning: In ${W.instance}.${W.method}() call, ${W.problem}.
|
|
65
|
+
${W.resolution}.`;console.warn($),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),I6.add(Z)}import{EventEmitter as $5}from"events";import{request as rW}from"https";import*as f from"zlib";import{EventEmitter as eW}from"events";class A6{constructor(W){this.requestData=W,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let W=this.requestData.url;return W.hostname+W.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(W){if(R.debug)R.logger.log("Request error:",W);return new k1("Request failed.",{request:this.req,error:W})}createPartialResponseError(W,Z){let J=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(Z)J+=" (connection abruptly closed)";else J+=" (parse error)";return new f1(J,{request:this.req,response:this.res,responseError:W,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(W){return W.map(({code:Z,message:$})=>`${$} (Twitter code ${Z})`).join(", ")}formatV2Error(W){return`${W.title}: ${W.detail} (see ${W.type})`}createResponseError({res:W,data:Z,rateLimit:$,code:J}){var Q;if(R.debug)R.logger.log(`Request failed with code ${J}, data:`,Z),R.logger.log("Response headers:",W.headers);let Y=`Request failed with code ${J}`;if((Q=Z===null||Z===void 0?void 0:Z.errors)===null||Q===void 0?void 0:Q.length){let K=Z.errors;if(typeof K[0]==="object"&&"code"in K[0])Y+=" - "+this.formatV1Errors(K);else Y+=" - "+this.formatV2Error(Z)}return new C1(Y,{code:J,data:Z,headers:W.headers,request:this.req,response:W,rateLimit:$})}getResponseDataStream(W){if(this.isCompressionDisabled())return W;let Z=(W.headers["content-encoding"]||"identity").trim().toLowerCase();if(Z==="br"){let $=f.createBrotliDecompress({flush:f.constants.BROTLI_OPERATION_FLUSH,finishFlush:f.constants.BROTLI_OPERATION_FLUSH});return W.pipe($),$}if(Z==="gzip"){let $=f.createGunzip({flush:f.constants.Z_SYNC_FLUSH,finishFlush:f.constants.Z_SYNC_FLUSH});return W.pipe($),$}if(Z==="deflate"){let $=f.createInflate({flush:f.constants.Z_SYNC_FLUSH,finishFlush:f.constants.Z_SYNC_FLUSH});return W.pipe($),$}return W}detectResponseType(W){var Z,$;if(((Z=W.headers["content-type"])===null||Z===void 0?void 0:Z.includes("application/json"))||(($=W.headers["content-type"])===null||$===void 0?void 0:$.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(W){let Z=this.responseData,$=this.requestData.forceParseMode||this.detectResponseType(W);if($==="buffer")return Buffer.concat(Z);else if($==="text")return Buffer.concat(Z).toString();else if($==="json"){let J=Buffer.concat(Z).toString();return J.length?JSON.parse(J):void 0}else if($==="url"){let J=Buffer.concat(Z).toString(),Q={};for(let[Y,K]of new URLSearchParams(J))Q[Y]=K;return Q}else return}getRateLimitFromResponse(W){let Z=void 0;if(W.headers["x-rate-limit-limit"]){if(Z={limit:Number(W.headers["x-rate-limit-limit"]),remaining:Number(W.headers["x-rate-limit-remaining"]),reset:Number(W.headers["x-rate-limit-reset"])},W.headers["x-app-limit-24hour-limit"])Z.day={limit:Number(W.headers["x-app-limit-24hour-limit"]),remaining:Number(W.headers["x-app-limit-24hour-remaining"]),reset:Number(W.headers["x-app-limit-24hour-reset"])};if(W.headers["x-user-limit-24hour-limit"])Z.userDay={limit:Number(W.headers["x-user-limit-24hour-limit"]),remaining:Number(W.headers["x-user-limit-24hour-remaining"]),reset:Number(W.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(Z)}return Z}onSocketEventHandler(W,Z,$){let J=this.onSocketCloseHandler.bind(this,W);$.on("close",J),Z.on("complete",()=>$.off("close",J))}onSocketCloseHandler(W){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return W(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(W,Z){var $,J;(J=($=this.requestData).requestEventDebugHandler)===null||J===void 0||J.call($,"request-error",{requestError:Z}),this.requestErrorHandled=!0,W(this.createRequestError(Z))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(W,Z,$){this.res=$;let J=this.getResponseDataStream($);if(J.on("data",(Q)=>this.responseData.push(Q)),J.on("end",this.onResponseEndHandler.bind(this,W,Z)),J.on("close",this.onResponseCloseHandler.bind(this,W,Z)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:$}),$.on("aborted",(Q)=>this.requestData.requestEventDebugHandler("response-aborted",{error:Q})),$.on("error",(Q)=>this.requestData.requestEventDebugHandler("response-error",{error:Q})),$.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),$.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(W,Z){let $=this.getRateLimitFromResponse(this.res),J;try{J=this.getParsedResponse(this.res)}catch(Y){Z(this.createPartialResponseError(Y,!1));return}let Q=this.res.statusCode;if(Q>=400){Z(this.createResponseError({data:J,res:this.res,rateLimit:$,code:Q}));return}if(R.debug)R.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),R.logger.log("Response body:",J);W({data:J,headers:this.res.headers,rateLimit:$})}onResponseCloseHandler(W,Z){let $=this.res;if($.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(W,Z)}catch(J){return Z(this.createPartialResponseError(J,!0))}if(!$.complete)return Z(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(W,Z,$){if($.statusCode<400){if(R.debug)R.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${$.statusCode} (starting stream)`);let Q=this.getResponseDataStream($);W({req:this.req,res:Q,originalResponse:$,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},Z,$)}debugRequest(){let W=this.requestData.url;if(R.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),W.search)R.logger.log("Request parameters:",[...W.searchParams.entries()].map(([Z,$])=>`${Z}: ${$}`));if(this.requestData.body)R.logger.log("Request body:",this.requestData.body)}buildRequest(){var W;let Z=this.requestData.url,$=Z.username?`${Z.username}:${Z.password}`:void 0,J=(W=this.requestData.options.headers)!==null&&W!==void 0?W:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")J["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")J["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")J["accept-encoding"]="deflate;q=1, *;q=0.1";if(R.debug)this.debugRequest();this.req=rW({...this.requestData.options,host:Z.hostname,port:Z.port||void 0,path:Z.pathname+Z.search,protocol:Z.protocol,auth:$,headers:J})}registerRequestEventDebugHandlers(W){W.on("close",()=>this.requestData.requestEventDebugHandler("close")),W.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),W.on("socket",(Z)=>{this.requestData.requestEventDebugHandler("socket",{socket:Z}),Z.on("error",($)=>this.requestData.requestEventDebugHandler("socket-error",{socket:Z,error:$})),Z.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:Z})),Z.on("close",($)=>this.requestData.requestEventDebugHandler("socket-close",{socket:Z,withError:$})),Z.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:Z})),Z.on("lookup",(...$)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:Z,data:$})),Z.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:Z}))})}makeRequest(){return this.buildRequest(),new Promise((W,Z)=>{let $=(K)=>{Q.emit("complete"),W(K)},J=(K)=>{Q.emit("complete"),Z(K)},Q=new eW,Y=this.req;if(Y.on("error",this.requestErrorHandler.bind(this,J)),Y.on("socket",this.onSocketEventHandler.bind(this,J,Q)),Y.on("response",this.classicResponseHandler.bind(this,$,J)),this.requestData.options.timeout)Y.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(Y);if(this.requestData.body)Y.write(this.requestData.body);Y.end()})}async makeRequestAsStream(){let{req:W,res:Z,requestData:$,originalResponse:J}=await this.makeRequestAndResolveWhenReady();return new o1($,{req:W,res:Z,originalResponse:J})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((W,Z)=>{let $=this.req;if($.on("error",this.requestErrorHandler.bind(this,Z)),$.on("response",this.streamResponseHandler.bind(this,W,Z)),this.requestData.body)$.write(this.requestData.body);$.end()})}}var P1=A6;import{EventEmitter as W5}from"events";class h6 extends W5{constructor(W){super();this.stream=W,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),W.on(F.Data,this.onStreamData),W.on(F.ConnectionError,this.onStreamError),W.on(F.TweetParseError,this.onStreamError),W.on(F.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let W=this.stack;return this.stack=[],W}destroy(){this.removeAllListeners(),this.stream.off(F.Data,this.onStreamData),this.stream.off(F.ConnectionError,this.onStreamError),this.stream.off(F.TweetParseError,this.onStreamError),this.stream.off(F.ConnectionClosed,this.onStreamError)}emitEvent(W,Z){this.emit("event",{type:W,payload:Z})}onStreamError(W){this.emitEvent("error",W)}onStreamData(W){this.stack.push(W),this.emitEvent("data",W)}}var E6=h6;import{EventEmitter as Z5}from"events";class a1 extends Z5{constructor(){super(...arguments);this.currentMessage=""}push(W){this.currentMessage+=W,W=this.currentMessage;let Z=W.length,$=0,J=0;while(J<Z){if(W.slice(J,J+2)===`\r
|
|
66
|
+
`){let Q=W.slice($,J);if($=J+=2,!Q.length)continue;try{let Y=JSON.parse(Q);if(Y){this.emit(Z1.ParsedData,Y);continue}}catch(Y){this.emit(Z1.ParseError,Y)}}J++}this.currentMessage=W.slice($,Z)}reset(){this.currentMessage=""}}var Z1;(function(W){W.ParsedData="parsed data",W.ParseError="parse error"})(Z1||(Z1={}));var g6=[5,15,30,60,90,120,180,300,600,900],J5=(W)=>W>g6.length?901000:g6[W-1]*1000;class m6 extends $5{constructor(W,Z){super();if(this.requestData=W,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=J5,this.parser=new a1,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),Z)this.req=Z.req,this.res=Z.res,this.originalResponse=Z.originalResponse,this.initEventsFromRequest()}on(W,Z){return super.on(W,Z)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let W=(Z)=>{this.emit(F.ConnectionError,Z),this.emit(F.Error,{type:F.ConnectionError,error:Z,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",W),this.res.on("error",W),this.res.on("close",()=>W(Error("Connection closed by Twitter."))),this.res.on("data",(Z)=>{if(this.resetKeepAliveTimeout(),Z.toString()===`\r
|
|
67
|
+
`)return this.emit(F.DataKeepAlive);this.parser.push(Z.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let W=this.requestData.payloadIsError;this.parser.on(Z1.ParsedData,(Z)=>{if(W&&W(Z))this.emit(F.DataError,Z),this.emit(F.Error,{type:F.DataError,error:Z,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(F.Data,Z)}),this.parser.on(Z1.ParseError,(Z)=>{this.emit(F.TweetParseError,Z),this.emit(F.Error,{type:F.TweetParseError,error:Z,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(F.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){if(this.keepAliveTimeout)clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0}unbindRetryTimeout(){if(this.retryTimeout)clearTimeout(this.retryTimeout),this.retryTimeout=void 0}closeWithoutEmit(){if(this.unbindTimeouts(),this.res)this.res.removeAllListeners(),this.res.destroy();if(this.req)this.req.removeAllListeners(),this.req.destroy()}close(){this.emit(F.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let Z=await new P1(this.requestData).makeRequestAsStream(),$=this.eventNames();for(let J of $){let Q=this.listeners(J);for(let Y of Q)Z.on(J,Y)}return Z}async connect(W={}){if(typeof W.autoReconnect<"u")this.autoReconnect=W.autoReconnect;if(typeof W.autoReconnectRetries<"u")this.autoReconnectRetries=W.autoReconnectRetries==="unlimited"?1/0:W.autoReconnectRetries;if(typeof W.keepAliveTimeout<"u")this.keepAliveTimeoutMs=W.keepAliveTimeout==="disable"?1/0:W.keepAliveTimeout;if(typeof W.nextRetryTimeout<"u")this.nextRetryTimeout=W.nextRetryTimeout;this.unbindTimeouts();try{await this.reconnect()}catch(Z){if(this.emit(F.ConnectError,0),this.emit(F.Error,{type:F.ConnectError,error:Z,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,Z);else throw Z}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let W=!0;if(this.req)W=!1,this.closeWithoutEmit();let{req:Z,res:$,originalResponse:J}=await new P1(this.requestData).makeRequestAndResolveWhenReady();this.req=Z,this.res=$,this.originalResponse=J,this.emit(W?F.Connected:F.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(W=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(F.ConnectionClosed);return}if(W>=this.autoReconnectRetries){this.emit(F.ReconnectLimitExceeded),this.emit(F.ConnectionClosed);return}try{this.emit(F.ReconnectAttempt,W),await this.reconnect()}catch(Z){this.emit(F.ReconnectError,W),this.emit(F.Error,{type:F.ReconnectError,error:Z,message:`Reconnect error - ${W+1} attempts made yet.`}),this.makeAutoReconnectRetry(W,Z)}}makeAutoReconnectRetry(W,Z){let $=this.nextRetryTimeout(W+1,Z);this.retryTimeout=setTimeout(()=>{this.onConnectionError(W+1)},$)}async*[Symbol.asyncIterator](){let W=new E6(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 o1=m6;function c6(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 u6(W,Z,$,J){let Q;if(J instanceof k1||J instanceof f1)Q=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:J});else if(J instanceof C1)Q=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,error:J});if(Q&&Q instanceof V1)return Q.value;return Promise.reject(J)}import*as l6 from"crypto";class q{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 l6.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=d6(W),$="OAuth ";for(let J of Z){if(J.key.indexOf("oauth_")!==0)continue;$+=q.percentEncode(J.key)+'="'+q.percentEncode(J.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 q.percentEncode(this.consumerKeys.secret)+"&"+q.percentEncode(W||"")}getBaseString(W,Z){return W.method.toUpperCase()+"&"+q.percentEncode(this.getBaseUrl(W.url))+"&"+q.percentEncode(this.getParameterString(W,Z))}getParameterString(W,Z){let $=d6(K5(p6(Z,p6(W.data,Y5(W.url))))),J="";for(let{key:Q,value:Y}of $)if(Y&&Array.isArray(Y)){Y.sort();let K="";Y.forEach((G,z)=>{if(K+=Q+"="+G,z<Y.length)K+="&"}),J+=K}else J+=Q+"="+Y+"&";return J.slice(0,J.length-1)}getBaseUrl(W){return W.split("?")[0]}}var b1=q;function p6(W,Z){return{...W||{},...Z||{}}}function d6(W){return Object.keys(W).sort().map((Z)=>({key:Z,value:W[Z]}))}function Q5(W){let Z=W.split("&"),$={};for(let J of Z){let[Q,Y=""]=J.split("=");if($[Q]){if(!Array.isArray($[Q]))$[Q]=[$[Q]];$[Q].push(decodeURIComponent(Y))}else $[Q]=decodeURIComponent(Y)}return $}function Y5(W){let Z=W.split("?");if(Z.length===1)return{};return Q5(Z[1])}function K5(W){let Z={};for(let $ in W){let J=W[$];if(J&&Array.isArray(J))J=J.map((Q)=>q.percentEncode(Q));else J=q.percentEncode(J);Z[q.percentEncode($)]=J}return Z}class v{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...W){let Z=W.map(($)=>$ instanceof Buffer?$:Buffer.from($));this._chunks.push(...Z)}append(W,Z,$){let J=Z instanceof Buffer?Z:Z.toString(),Q=this.getMultipartHeader(W,J,$);this.bodyAppend(Q,J,v.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 J of W)for(let Q=0;Q<J.length;$++,Q++)Z[$]=J[Q];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?v.DEFAULT_CONTENT_TYPE:"";let J={"Content-Disposition":["form-data",`name="${W}"`],"Content-Type":$},Q="";for(let[Y,K]of Object.entries(J)){if(!K.length)continue;Q+=Y+": "+i1(K).join("; ")+v.LINE_BREAK}return"--"+this.getBoundary()+v.LINE_BREAK+Q+v.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+v.LINE_BREAK)}}v.LINE_BREAK=`\r
|
|
68
|
+
`;v.DEFAULT_CONTENT_TYPE="application/octet-stream";class i4{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 J="";for(let[Q,Y]of $)J+=(J.length?"&":"?")+`${b1.percentEncode(Q)}=${b1.percentEncode(Y)}`;W.search=J}}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 J=new v;for(let Q in W)J.append(Q,W[Q]);if(!Z["content-type"]){let Q=J.getHeaders();Z["content-type"]=Q["content-type"]}return J.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 J in W)$[J]=W[J];if(this.isOAuthSerializable(Z))for(let J in Z){let Q=Z[J];if(this.isOAuthSerializable(Q))$[J]=typeof Q==="object"&&Q!==null&&"toString"in Q?Q.toString():Q}return $}static moveUrlQueryParamsIntoObject(W,Z){for(let[$,J]of W.searchParams)Z[$]=J;return W.search="",W}static applyRequestParametersToUrl(W,Z){return W.pathname=W.pathname.replace(/:([A-Z_-]+)/ig,($,J)=>{if(Z[J]!==void 0)return String(Z[J]);return $}),W}}i4.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 T=i4;import*as n6 from"crypto";class $1{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url(n6.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 J=0;J<W;J++)Z+=$[Math.floor(Math.random()*$.length)];return Z}static escapeBase64Url(W){return W.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class z1{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,$,J,Q,Y;if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length){let j=await this.applyPreRequestConfigHooks(W);if(j)return j}let K=this.getHttpRequestArgs(W),G={method:K.method,headers:K.headers,timeout:W.timeout,agent:this.clientSettings.httpAgent},z=W.enableRateLimitSave!==!1;if(K.body)T.setBodyLengthHeader(G,K.body);if(($=this.clientSettings.plugins)===null||$===void 0?void 0:$.length)await this.applyPreRequestHooks(W,K,G);let X=new P1({url:K.url,options:G,body:K.body,rateLimitSaver:z?this.saveRateLimit.bind(this,K.rawUrl):void 0,requestEventDebugHandler:W.requestEventDebugHandler,compression:(Q=(J=W.compression)!==null&&J!==void 0?J:this.clientSettings.compression)!==null&&Q!==void 0?Q:!0,forceParseMode:W.forceParseMode}).makeRequest();if(c6(this))X=this.applyResponseErrorHooks(W,K,G,X);let B=await X;if((Y=this.clientSettings.plugins)===null||Y===void 0?void 0:Y.length){let j=await this.applyPostRequestHooks(W,K,G,B);if(j)return j.value}return B}sendStream(W){var Z,$;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(W);let J=this.getHttpRequestArgs(W),Q={method:J.method,headers:J.headers,agent:this.clientSettings.httpAgent},Y=W.enableRateLimitSave!==!1,K=W.autoConnect!==!1;if(J.body)T.setBodyLengthHeader(Q,J.body);let G={url:J.url,options:Q,body:J.body,rateLimitSaver:Y?this.saveRateLimit.bind(this,J.rawUrl):void 0,payloadIsError:W.payloadIsError,compression:($=(Z=W.compression)!==null&&Z!==void 0?Z:this.clientSettings.compression)!==null&&$!==void 0?$:!0},z=new o1(G);if(!K)return z;return z.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 b1({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 J;for(let Q of this.getPlugins()){let Y=await(($=Q[W])===null||$===void 0?void 0:$.call(Q,Z));if(Y&&Y instanceof V1)J=Y}return J}writeAuthHeaders({headers:W,bodyInSignature:Z,url:$,method:J,query:Q,body:Y}){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 "+$1.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let K=Z?T.mergeQueryAndBodyForOAuth(Q,Y):Q,G=this._oauth.authorize({url:$.toString(),method:J,data:K},this.getOAuthAccessTokens());W={...W,...this._oauth.toHeader(G)}}return W}getUrlObjectFromUrlString(W){if(!W.startsWith("http"))W="https://"+W;return new URL(W)}getHttpRequestArgs({url:W,method:Z,query:$={},body:J={},headers:Q,forceBodyMode:Y,enableAuth:K,params:G}){let z=void 0;if(Z=Z.toUpperCase(),Q=Q!==null&&Q!==void 0?Q:{},!Q["x-user-agent"])Q["x-user-agent"]="Node.twitter-api-v2";let X=this.getUrlObjectFromUrlString(W),B=X.origin+X.pathname;if(G)T.applyRequestParametersToUrl(X,G);let j=T.formatQueryToString($);if(T.moveUrlQueryParamsIntoObject(X,j),!(J instanceof Buffer))y6(J);let L=Y!==null&&Y!==void 0?Y:T.autoDetectBodyType(X);if(K!==!1){let H=z1.BODY_METHODS.has(Z)&&L==="url";Q=this.writeAuthHeaders({headers:Q,bodyInSignature:H,method:Z,query:j,url:X,body:J})}if(z1.BODY_METHODS.has(Z))z=T.constructBodyParams(J,Q,L)||void 0;return T.addQueryParamsToUrl(X,j),{rawUrl:B,url:X,method:Z,headers:Q,body:z}}async applyPreRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let J of this.getPlugins()){let Q=await((Z=J.onBeforeRequestConfig)===null||Z===void 0?void 0:Z.call(J,{client:this,url:$,params:W}));if(Q)return Q}}applyPreStreamRequestConfigHooks(W){var Z;let $=this.getUrlObjectFromUrlString(W.url);for(let J of this.getPlugins())(Z=J.onBeforeStreamRequestConfig)===null||Z===void 0||Z.call(J,{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,$,J){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:Z,requestOptions:$,response:J})}applyResponseErrorHooks(W,Z,$,J){return J.catch(u6.bind(this,W,Z,$))}}z1.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class i{constructor(W,Z={}){if(this._currentUser=null,this._currentUserV2=null,W instanceof i)this._requestMaker=W._requestMaker;else this._requestMaker=new z1(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=l4(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:l})),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=l4(()=>this.get("users/me",void 0,{prefix:d})),this._currentUserV2.promise}async get(W,Z={},{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"GET",query:Z,...Q});return $?Y:Y.data}async delete(W,Z={},{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"DELETE",query:Z,...Q});return $?Y:Y.data}async post(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"POST",body:Z,...Q});return $?Y:Y.data}async put(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"PUT",body:Z,...Q});return $?Y:Y.data}async patch(W,Z,{fullResponse:$,prefix:J=this._prefix,...Q}={}){if(J)W=J+W;let Y=await this._requestMaker.send({url:W,method:"PATCH",body:Z,...Q});return $?Y:Y.data}getStream(W,Z,{prefix:$=this._prefix,...J}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"GET",query:Z,...J})}postStream(W,Z,{prefix:$=this._prefix,...J}={}){return this._requestMaker.sendStream({url:$?$+W:W,method:"POST",body:Z,...J})}}class P extends i{constructor(W){if(!(W instanceof i))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(W)}}class X1 extends G1{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 s4 extends X1{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class o4 extends X1{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class t1 extends X1{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class a4 extends X1{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class r1 extends X1{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class t4 extends x{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 r4 extends x{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 e4 extends x{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 W0 extends x{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 Z0 extends x{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 $0 extends x{constructor(){super(...arguments);this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,Z){let $=W.data;if(this._rateLimit=W.rateLimit,Z)this._realData.ids.push(...$.ids),this._realData.next_cursor=$.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class J0 extends G1{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 e1 extends x{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 Q0 extends e1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class W4 extends x{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 Y0 extends W4{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class K0 extends W4{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class G0 extends W4{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class z0 extends x{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 z0{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class B0 extends z0{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class B1 extends P{constructor(){super(...arguments);this._prefix=l}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 s4({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 o4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},J=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new t1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async userTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},J=await this.get("statuses/user_timeline.json",$,{fullResponse:!0});return new t1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async favoriteTimeline(W,Z={}){let $={tweet_mode:"extended",user_id:W,...Z},J=await this.get("favorites/list.json",$,{fullResponse:!0});return new r1({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async favoriteTimelineByUsername(W,Z={}){let $={tweet_mode:"extended",screen_name:W,...Z},J=await this.get("favorites/list.json",$,{fullResponse:!0});return new r1({realData:J.data,rateLimit:J.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 t4({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 r4({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 Z0({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 e4({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 W0({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 $0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async searchUsers(W,Z={}){let $={q:W,tweet_mode:"extended",page:1,...Z},J=await this.get("users/search.json",$,{fullResponse:!0});return new J0({realData:J.data,rateLimit:J.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 e1({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 Q0({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 X0({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 Y0({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 K0({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 a4({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 B0({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 G0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}mediaInfo(W){return this.get("media/upload.json",{command:"STATUS",media_id:W},{prefix:c})}filterStream({autoConnect:W,...Z}={}){let $={};for(let[Q,Y]of Object.entries(Z))if(Q==="follow"||Q==="track")$[Q]=Y.toString();else if(Q==="locations"){let K=Y;$.locations=i1(K).map((G)=>`${G.lng},${G.lat}`).join(",")}else $[Q]=Y;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 Z4(this);return W.setPrefix(q6),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 s from"fs";async function j0(W){let Z=await F0(W);if(typeof Z==="number")return new Promise(($,J)=>{s.readFile(Z,(Q,Y)=>{if(Q)return J(Q);$(Y)})});else if(Z instanceof Buffer)return Z;else return Z.readFile()}function F0(W){if(typeof W==="string")return s.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 i6(W){if(typeof W==="number")return(await new Promise(($,J)=>{s.fstat(W,(Q,Y)=>{if(Q)J(Q);$(Y)})})).size;else if(W instanceof Buffer)return W.length;else return(await W.stat()).size}function s6(W,Z,$){if(typeof $==="string")return $;else if(typeof W==="string"&&!Z)return G5(W);else if(typeof Z==="string")return z5(Z);throw Error("You must specify type if file is a file handle or Buffer.")}function G5(W){if(W.endsWith(".jpeg")||W.endsWith(".jpg"))return D.Jpeg;if(W.endsWith(".png"))return D.Png;if(W.endsWith(".webp"))return D.Webp;if(W.endsWith(".gif"))return D.Gif;if(W.endsWith(".mpeg4")||W.endsWith(".mp4"))return D.Mp4;if(W.endsWith(".mov")||W.endsWith(".mov"))return D.Mov;if(W.endsWith(".srt"))return D.Srt;return n4({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"}),D.Jpeg}function z5(W){if(n4({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 D.Gif;if(W==="jpg")return D.Jpeg;if(W==="png")return D.Png;if(W==="webp")return D.Webp;if(W==="srt")return D.Srt;if(W==="mp4"||W==="longmp4")return D.Mp4;if(W==="mov")return D.Mov;return W}function o6(W,Z){if(W===D.Mp4||W===D.Mov)return Z==="tweet"?"TweetVideo":"DmVideo";if(W===D.Gif)return Z==="tweet"?"TweetGif":"DmGif";if(W===D.Srt)return"Subtitles";else return Z==="tweet"?"TweetImage":"DmImage"}function M0(W){return new Promise((Z)=>setTimeout(Z,W*1000))}async function L0(W,Z,$=0,J){if(W instanceof Buffer){let Y=W.slice($,$+Z);return[Y,Y.length]}if(!J)throw Error("Well, we will need a buffer to store file content.");let Q;if(typeof W==="number")Q=await new Promise((Y,K)=>{s.read(W,J,0,Z,$,(G,z)=>{if(G)K(G);Y(z)})});else Q=(await W.read(J,0,Z,$)).bytesRead;return[J,Q]}var N0="media/upload.json";class j1 extends B1{constructor(){super(...arguments);this._prefix=l}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 J="https://x.com/i/statuses/"+Z;return this.tweet(W,{...$,attachment_url:J})}async tweetThread(W){let Z=[];for(let $ of W){let J=Z.length?Z[Z.length-1]:null,Q={...typeof $==="string"?{status:$}:$},Y=J?J.id_str:Q.in_reply_to_status_id,K=Q.status;if(Y)Z.push(await this.reply(K,Y,Q));else Z.push(await this.tweet(K,Q))}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 j0(W),...Z};return this.post("account/update_profile_banner.json",$,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,Z={}){let $={tweet_mode:"extended",image:await j0(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&&T1(W.user_id)||W.screen_name&&T1(W.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post($,W)}removeListMembers(W){let $=W.user_id&&T1(W.user_id)||W.screen_name&&T1(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:c,forceBodyMode:"json"})}createMediaSubtitles(W,Z){return this.post("media/subtitles/create.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:Z}},{prefix:c,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:c,forceBodyMode:"json"})}async uploadMedia(W,Z={},$=!1){var J;let Q=(J=Z.chunkLength)!==null&&J!==void 0?J:1048576,{fileHandle:Y,mediaCategory:K,fileSize:G,mimeType:z}=await this.getUploadMediaRequirements(W,Z);try{let X=await this.post(N0,{command:"INIT",total_bytes:G,media_type:z,media_category:K,additional_owners:Z.additionalOwners,shared:Z.shared?!0:void 0},{prefix:c});await this.mediaChunkedUpload(Y,Q,X.media_id_string,Z.maxConcurrentUploads);let B=await this.post(N0,{command:"FINALIZE",media_id:X.media_id_string},{prefix:c});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")D0.close(W,()=>{});else if(typeof Y==="object"&&!(Y instanceof Buffer))Y.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:J,message:Q}=$.error;throw Error(`Failed to process media: ${J} - ${Q}.`)}if($.state==="failed")throw Error("Failed to process the media.");if($.check_after_secs)await M0($.check_after_secs);else await M0(5)}}async getUploadMediaRequirements(W,{mimeType:Z,type:$,target:J,longVideo:Q}={}){let Y;try{Y=await F0(W);let K=s6(W,$,Z),G;if(K===D.Mp4&&(!Z&&!$&&J!=="dm"||Q))G="amplify_video";else G=o6(K,J!==null&&J!==void 0?J:"tweet");return{fileHandle:Y,mediaCategory:G,fileSize:await i6(Y),mimeType:K}}catch(K){if(typeof W==="number")D0.close(W,()=>{});else if(typeof Y==="object"&&!(Y instanceof Buffer))Y.close();throw K}}async mediaChunkedUpload(W,Z,$,J=3){let Q=0;if(J<1)throw RangeError("Bad maxConcurrentUploads parameter.");let Y=W instanceof Buffer?void 0:Buffer.alloc(Z),K,G,z=0;[K,G]=await L0(W,Z,z,Y),z+=G;let X=new Set;while(G){let B=K.slice(0,G);if(B.length){let j=this.post(N0,{command:"APPEND",media_id:$,segment_index:Q,media:B},{prefix:c});X.add(j),j.then(()=>{X.delete(j)}),Q++}if(X.size>=J)await Promise.race(X);[K,G]=await L0(W,Z,z,Y),z+=G}await Promise.all([...X])}}class a6 extends j1{constructor(){super(...arguments);this._prefix=l}get readWrite(){return this}sendDm({recipient_id:W,custom_profile_id:Z,...$}){let J={event:{type:n.Create,[n.Create]:{target:{recipient_id:W},message_data:$}}};if(Z)J.event[n.Create].custom_profile_id=Z;return this.post("direct_messages/events/new.json",J,{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 p4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}newWelcomeDm(W,Z){let $={[n.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 d4({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 J=await this.listWelcomeDmRules();if(($=J.welcome_message_rules)===null||$===void 0?void 0:$.length){for(let Q of J.welcome_message_rules)if(await this.deleteWelcomeDmRule(Q.id),Z)await this.deleteWelcomeDm(Q.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[n.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 Z4=a6;class N{constructor(W){this.result=W}get tweets(){return N.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 N.tweetById(this.result,W)}static tweetById(W,Z){return this.tweets(W).find(($)=>$.id===Z)}retweet(W){return N.retweet(this.result,W)}static retweet(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="retweeted").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}quote(W){return N.quote(this.result,W)}static quote(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="quoted").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}repliedTo(W){return N.repliedTo(this.result,W)}static repliedTo(W,Z){var $;let J=(($=Z.referenced_tweets)!==null&&$!==void 0?$:[]).filter((Q)=>Q.type==="replied_to").map((Q)=>Q.id);return this.tweets(W).find((Q)=>J.includes(Q.id))}author(W){return N.author(this.result,W)}static author(W,Z){let $=Z.author_id;return $?this.users(W).find((J)=>J.id===$):void 0}repliedToAuthor(W){return N.repliedToAuthor(this.result,W)}static repliedToAuthor(W,Z){let $=Z.in_reply_to_user_id;return $?this.users(W).find((J)=>J.id===$):void 0}get users(){return N.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 N.userById(this.result,W)}static userById(W,Z){return this.users(W).find(($)=>$.id===Z)}pinnedTweet(W){return N.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 N.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 N.medias(this.result,W)}static medias(W,Z){var $,J;let Q=(J=($=Z.attachments)===null||$===void 0?void 0:$.media_keys)!==null&&J!==void 0?J:[];return this.media(W).filter((Y)=>Q.includes(Y.media_key))}get polls(){return N.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 N.poll(this.result,W)}static poll(W,Z){var $,J;let Q=(J=($=Z.attachments)===null||$===void 0?void 0:$.poll_ids)!==null&&J!==void 0?J:[];if(Q.length){let Y=Q[0];return this.polls(W).find((K)=>K.id===Y)}return}get places(){return N.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 N.place(this.result,W)}static place(W,Z){var $;let J=($=Z.geo)===null||$===void 0?void 0:$.place_id;return J?this.places(W).find((Q)=>Q.id===J):void 0}listOwner(W){return N.listOwner(this.result,W)}static listOwner(W,Z){let $=Z.owner_id;return $?this.users(W).find((J)=>J.id===$):void 0}spaceCreator(W){return N.spaceCreator(this.result,W)}static spaceCreator(W,Z){let $=Z.creator_id;return $?this.users(W).find((J)=>J.id===$):void 0}spaceHosts(W){return N.spaceHosts(this.result,W)}static spaceHosts(W,Z){var $;let J=($=Z.host_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}spaceSpeakers(W){return N.spaceSpeakers(this.result,W)}static spaceSpeakers(W,Z){var $;let J=($=Z.speaker_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}spaceInvitedUsers(W){return N.spaceInvitedUsers(this.result,W)}static spaceInvitedUsers(W,Z){var $;let J=($=Z.invited_user_ids)!==null&&$!==void 0?$:[];return this.users(W).filter((Q)=>J.includes(Q.id))}}class $4 extends u4{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[$,J]of Object.entries(W.includes)){if(!Z[$])Z[$]=[];Z[$]=[...Z[$],...J]}}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 N(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new N(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 h extends $4{refreshInstanceFromResult(W,Z){var $;let J=W.data,Q=($=J.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.next_token=J.meta.next_token,this._realData.data.push(...Q);else this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.previous_token=J.meta.previous_token,this._realData.data.unshift(...Q);this.updateIncludes(J)}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 H0 extends $4{refreshInstanceFromResult(W,Z){var $;let J=W.data,Q=($=J.data)!==null&&$!==void 0?$:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(Z)this._realData.meta.oldest_id=J.meta.oldest_id,this._realData.meta.result_count+=J.meta.result_count,this._realData.meta.next_token=J.meta.next_token,this._realData.data.push(...Q);else this._realData.meta.newest_id=J.meta.newest_id,this._realData.meta.result_count+=J.meta.result_count,this._realData.data.unshift(...Q);this.updateIncludes(J)}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 F1 extends h{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 U0 extends H0{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class x0 extends H0{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class O0 extends F1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class S0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class R0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class _0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class k0 extends F1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class f0 extends h{get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class C0 extends f0{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class V0 extends f0{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class u extends h{getItemArray(){return this.users}get users(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class T0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class P0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class b0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class w0 extends u{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class q0 extends u{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class v0 extends u{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class I0 extends u{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class y0 extends u{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class J4 extends h{getItemArray(){return this.lists}get lists(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class A0 extends J4{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class h0 extends J4{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class E0 extends J4{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class M1 extends P{constructor(){super(...arguments);this._prefix=Q1}}class Q4 extends h{getItemArray(){return this.events}get events(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class g0 extends Q4{constructor(){super(...arguments);this._endpoint="dm_events"}}class m0 extends Q4{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class c0 extends Q4{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class L1 extends P{constructor(){super(...arguments);this._prefix=d}get labs(){if(this._labs)return this._labs;return this._labs=new M1(this)}async search(W,Z={}){let $=typeof W==="string"?{...Z,query:W}:{...W},J=await this.get("tweets/search/recent",$,{fullResponse:!0});return new U0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:$})}async searchAll(W,Z={}){let $={...Z,query:W},J=await this.get("tweets/search/all",$,{fullResponse:!0});return new x0({realData:J.data,rateLimit:J.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:$,...J}=Z,Q=await this.get("tweets/:id/retweeted_by",J,{fullResponse:!0,params:{id:W}});if(!$)return Q.data;return new y0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async tweetLikedBy(W,Z={}){let{asPaginator:$,...J}=Z,Q=await this.get("tweets/:id/liking_users",J,{fullResponse:!0,params:{id:W}});if(!$)return Q.data;return new I0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:J,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 S0({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 R0({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 _0({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 O0({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 k0({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:$,...J}=Z,Q={id:W};if(!$)return this.get("users/:id/followers",J,{params:Q});let Y=await this.get("users/:id/followers",J,{fullResponse:!0,params:Q});return new b0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:J,sharedParams:Q})}async following(W,Z={}){let{asPaginator:$,...J}=Z,Q={id:W};if(!$)return this.get("users/:id/following",J,{params:Q});let Y=await this.get("users/:id/following",J,{fullResponse:!0,params:Q});return new w0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:J,sharedParams:Q})}async userLikedTweets(W,Z={}){let $={id:W},J=await this.get("users/:id/liked_tweets",Z,{fullResponse:!0,params:$});return new C0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userBlockingUsers(W,Z={}){let $={id:W},J=await this.get("users/:id/blocking",Z,{fullResponse:!0,params:$});return new T0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async userMutingUsers(W,Z={}){let $={id:W},J=await this.get("users/:id/muting",Z,{fullResponse:!0,params:$});return new P0({realData:J.data,rateLimit:J.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},J=await this.get("users/:id/owned_lists",Z,{fullResponse:!0,params:$});return new A0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMemberships(W,Z={}){let $={id:W},J=await this.get("users/:id/list_memberships",Z,{fullResponse:!0,params:$});return new h0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowed(W,Z={}){let $={id:W},J=await this.get("users/:id/followed_lists",Z,{fullResponse:!0,params:$});return new E0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listTweets(W,Z={}){let $={id:W},J=await this.get("lists/:id/tweets",Z,{fullResponse:!0,params:$});return new V0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listMembers(W,Z={}){let $={id:W},J=await this.get("lists/:id/members",Z,{fullResponse:!0,params:$});return new q0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listFollowers(W,Z={}){let $={id:W},J=await this.get("lists/:id/followers",Z,{fullResponse:!0,params:$});return new v0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEvents(W={}){let Z=await this.get("dm_events",W,{fullResponse:!0});return new g0({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:{...W}})}async listDmEventsWithParticipant(W,Z={}){let $={participant_id:W},J=await this.get("dm_conversations/with/:participant_id/dm_events",Z,{fullResponse:!0,params:$});return new m0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...Z},sharedParams:$})}async listDmEventsOfConversation(W,Z={}){let $={dm_conversation_id:W},J=await this.get("dm_conversations/:dm_conversation_id/dm_events",Z,{fullResponse:!0,params:$});return new c0({realData:J.data,rateLimit:J.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:s1,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:s1,autoConnect:W})}sample10Stream({autoConnect:W,...Z}={}){return this.getStream("tweets/sample10/stream",Z,{payloadIsError:s1,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((J)=>setTimeout(J,3500)),Z=(await this.complianceJob(W.id)).data}return(await this.get(W.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split(`
|
|
70
|
-
`).filter((J)=>J).map((J)=>JSON.parse(J))}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 N1 extends M1{constructor(){super(...arguments);this._prefix=Q1}get readOnly(){return this}}class D1 extends L1{constructor(){super(...arguments);this._prefix=d}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new N1(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 J=Z.media_category;if(!Z.media_category){if(Z.media_type.includes("gif"))J="tweet_gif";else if(Z.media_type.includes("image"))J="tweet_image";else if(Z.media_type.includes("video"))J="tweet_video"}let Q={additional_owners:Z.additional_owners,media_type:Z.media_type,total_bytes:W.length,media_category:J},K=(await this.post("media/upload/initialize",Q)).data.id,z=Math.ceil(W.length/$),G=new Uint8Array(W);for(let B=0;B<z;B++){let j=B*$,L=Math.min(j+$,W.length),H=G.slice(j,L),S=Buffer.from(H),o={segment_index:B,media:S};await this.post(`media/upload/${K}/append`,o,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${K}/finalize`)).data.processing_info)await this.waitForMediaProcessing(K);return K}async waitForMediaProcessing(W){var Z;let J=(await this.get("media/upload",{command:"STATUS",media_id:W})).data.processing_info;if(!J)return;switch(J.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(Z=J.error)===null||Z===void 0?void 0:Z.message}`);case"pending":case"in_progress":{let Q=J===null||J===void 0?void 0:J.check_after_secs;if(Q&&Q>0)await new Promise((Y)=>setTimeout(Y,Q*1000)),await this.waitForMediaProcessing(W)}}}createMediaMetadata(W,Z){return this.post("media/metadata",{id:W,metadata:Z})}reply(W,Z,$={}){var J;let Q={in_reply_to_tweet_id:Z,...(J=$.reply)!==null&&J!==void 0?J:{}};return this.post("tweets",{text:W,...$,reply:Q})}quote(W,Z,$={}){return this.tweet(W,{...$,quote_tweet_id:Z})}async tweetThread(W){var Z,$;let J=[];for(let Q of W){let Y=J.length?J[J.length-1]:null,K={...typeof Q==="string"?{text:Q}:Q},z=Y?Y.data.id:(Z=K.reply)===null||Z===void 0?void 0:Z.in_reply_to_tweet_id,G=($=K.text)!==null&&$!==void 0?$:"";if(z)J.push(await this.reply(G,z,K));else J.push(await this.tweet(G,K))}return J}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 s6 extends N1{constructor(){super(...arguments);this._prefix=Q1}get readWrite(){return this}}var o6=s6;class a6 extends D1{constructor(){super(...arguments);this._prefix=d}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new o6(this)}}var t6=a6;class b1 extends i{get v1(){if(this._v1)return this._v1;return this._v1=new B1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new L1(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:J,screenName:Q}={}){let Y=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:W,x_auth_access_type:Z}),K=`https://api.x.com/oauth/${$}?oauth_token=${encodeURIComponent(Y.oauth_token)}`;if(J!==void 0)K+=`&force_login=${encodeURIComponent(J)}`;if(Q!==void 0)K+=`&screen_name=${encodeURIComponent(Q)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:K,oauthResult:Y});return{url:K,...Y}}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}),J=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:J}}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 $,J;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 Q=($=Z.state)!==null&&$!==void 0?$:$1.generateRandomString(32),Y=$1.getCodeVerifier(),K=$1.getCodeChallengeFromVerifier(Y),z=(J=Z.scope)!==null&&J!==void 0?J:"",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:Q,code_challenge:K,code_challenge_method:"s256",scope:G};T.addQueryParamsToUrl(X,B);let j={url:X.toString(),state:Q,codeVerifier:Y,codeChallenge:K};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 J=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(J)}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((J)=>J);return{client:Z,expiresIn:W.expires_in,accessToken:W.access_token,scope:$,refreshToken:W.refresh_token}}}class w1 extends b1{get v1(){if(this._v1)return this._v1;return this._v1=new j1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new D1(this)}get readOnly(){return this}}class J4 extends P{constructor(){super(...arguments);this._prefix=Y1}}class Q4 extends J4{constructor(){super(...arguments);this._prefix=Y1}get readOnly(){return this}}class Y4 extends P{constructor(){super(...arguments);this._prefix=K1}}class K4 extends Y4{constructor(){super(...arguments);this._prefix=K1}get readOnly(){return this}}class r6 extends K4{constructor(){super(...arguments);this._prefix=K1}get readWrite(){return this}}var e6=r6;class WW extends Q4{constructor(){super(...arguments);this._prefix=Y1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new e6(this)}}var ZW=WW;class z4 extends w1{get v1(){if(this._v1)return this._v1;return this._v1=new e1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new t6(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new ZW(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(),J=["normal","bigger","mini"],Q=W;for(let K of J)if($.includes(`_${K}`)){Q=W.replace(`_${K}`,"");break}if(Z==="original")return Q;let Y=Q.lastIndexOf(".");if(Y!==-1){let K=Q.slice(Y+1);return Q.slice(0,Y)+"_"+Z+"."+K}else return Q+"_"+Z}}var Y5={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class $W extends m{config;client;constructor(W={}){super();this.config={...Y5,...W},this.client=new z4({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"XOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}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"),J={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[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new U("missing_code");if(!Z?.codeVerifier)throw new U("invalid_state");let J=this.config.resolve?await this.clientFor(W):this.staticClient();if(!J)throw new U("unknown_provider");let Q=this.config.resolve?new z4({clientId:J.clientId,clientSecret:J.clientSecret}):this.client,Y;try{Y=await Q.loginWithOAuth2({code:$,codeVerifier:Z.codeVerifier,redirectUri:J.redirectUri})}catch(j){throw console.error("X OAuth error: token exchange failed",j),new U("exchange_failed")}let{data:K}=await Y.client.v2.me({"user.fields":["name","username","entities"]}),{name:z,email:G,id:X="",username:B}=K??{};return{name:z,email:G,username:B,providerId:X}}}var QW=["instagram_business_basic"],g={authorizeUrl:"https://www.instagram.com/oauth/authorize",tokenUrl:"https://api.instagram.com/oauth/access_token",graphUrl:"https://graph.instagram.com"};class I extends Error{status;type;code;constructor(W,Z,$,J,Q){super(W,Q);this.status=Z;this.type=$;this.code=J;this.name="InstagramApiError"}}async function G4(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 B4(W.tokenUrl??g.tokenUrl,"code exchange",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Z.toString()}),J=Array.isArray($.data)?$.data[0]:$,Q=J?.access_token;if(typeof Q!=="string"||Q==="")throw new I("Instagram's code exchange answered without an access token.",200);let Y=J?.permissions;return{accessToken:Q,userId:g0(J?.user_id),permissions:Array.isArray(Y)?Y.map(String):typeof Y==="string"?Y.split(/[\s,]+/).filter(Boolean):null}}async function YW(W){let Z=new URL("/access_token",W.graphUrl??g.graphUrl);return Z.searchParams.set("grant_type","ig_exchange_token"),Z.searchParams.set("client_secret",W.clientSecret),Z.searchParams.set("access_token",W.accessToken),zW(await B4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function KW(W){let Z=new URL("/refresh_access_token",W.graphUrl??g.graphUrl);return Z.searchParams.set("grant_type","ig_refresh_token"),Z.searchParams.set("access_token",W.accessToken),zW(await B4(Z.toString(),"token refresh",{method:"GET"}))}async function X4(W){let Z=W.graphApiVersion?`/${W.graphApiVersion.replace(/^\/+|\/+$/g,"")}`:"",$=new URL(`${Z}/me`,W.graphUrl??g.graphUrl);$.searchParams.set("fields",(W.fields??["user_id","username","name","account_type","profile_picture_url"]).join(",")),$.searchParams.set("access_token",W.accessToken);let J=await B4($.toString(),"profile request",{method:"GET"}),Q=Array.isArray(J.data)?J.data[0]:J,Y=g0(Q?.user_id);if(!Y)throw new I("Instagram's /me answered without a user_id.",200);let K={user_id:Y},z=g0(Q?.id);if(z)K.id=z;for(let G of["username","name","account_type","profile_picture_url"]){let X=Q?.[G];if(typeof X==="string"&&X!=="")K[G]=X}return K}function zW(W){if(typeof W.access_token!=="string"||W.access_token==="")throw new I("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 B4(W,Z,$){let J;try{J=await fetch(W,{...$,redirect:"error"})}catch(Y){throw new I(`Instagram's ${Z} failed to reach Instagram.`,void 0,void 0,void 0,{cause:Y})}let Q=E0(await J.text().catch(()=>""));if(!J.ok){let Y=Q.error??{},K=JW(Q.error_type)??JW(Y.type),z=Number(Q.code??Y.code);throw new I(`Instagram refused the ${Z} (HTTP ${J.status}${K?`, ${K}`:""}${Number.isFinite(z)?` ${z}`:""}).`,J.status,K,Number.isFinite(z)?z:void 0)}return Q}function E0(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 g0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function JW(W){return typeof W==="string"&&W!==""?W:void 0}class GW extends m{createUsersWithoutEmail=!0;linkByEmail=!1;config;constructor(W={}){super();this.config={clientId:process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:QW,redirectPath:"/auth/oauth/instagram/callback",authorizationParams:{},...W}}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"InstagramOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}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??g.authorizeUrl),J={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,response_type:"code",scope:this.config.scopes.join(",")};if(Z)J.state=Z.state;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W){let Z=W.search.get("code");if(!Z)throw new U("missing_code");let $=this.config.resolve?await this.clientFor(W):this.staticClient();if(!$)throw new U("unknown_provider");let J;try{let Q=await G4({code:Z,clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.redirectUri,tokenUrl:this.config.tokenUrl});J=await X4({accessToken:Q.accessToken,graphUrl:this.config.graphUrl,graphApiVersion:this.config.graphApiVersion,fields:["user_id","username","name"]})}catch(Q){if(Q instanceof I)throw console.error(`Instagram OAuth error: ${Q.message}`),new U("exchange_failed");throw Q}return{providerId:J.user_id,username:J.username,name:J.name||J.username}}}import{createHmac as K5,timingSafeEqual as z5}from"crypto";class y extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function G5(W,Z,$={}){if(!Z)throw Error("parseMetaSignedRequest needs the app secret.");if(typeof W!=="string")throw new y("malformed","No signed_request was given.");let J=W.indexOf(".");if(J<=0||J===W.length-1||W.indexOf(".",J+1)!==-1)throw new y("malformed","A signed_request is <signature>.<payload>.");let Q=W.slice(0,J),Y=W.slice(J+1);if(!/^[A-Za-z0-9_-]+={0,2}$/.test(Q)||!/^[A-Za-z0-9_-]+={0,2}$/.test(Y))throw new y("malformed","A signed_request is base64url.");let K=K5("sha256",Z).update(Y).digest(),z=Buffer.from(Q,"base64url");if(z.length!==K.length||!z5(z,K))throw new y("bad_signature","The signed_request's signature does not match the app secret.");let G;try{let L=Buffer.from(Y,"base64url").toString("utf8").replace(/("user_id"\s*:\s*)(-?\d+)(?=\s*[,}])/g,'$1"$2"');G=JSON.parse(L)}catch{throw new y("malformed","The signed_request's payload is not JSON.")}if(!G||typeof G!=="object")throw new y("malformed","The signed_request's payload is not an object.");if(String(G.algorithm??"").toUpperCase()!=="HMAC-SHA256")throw new y("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 y("expired","The signed_request has expired.");let j=G.user_id;if((typeof j!=="string"||j==="")&&typeof j!=="number")throw new y("missing_user","The signed_request names no user.");return{...G,algorithm:String(G.algorithm),user_id:String(j)}}var X5=86400000;class F4 extends m0{instagram;constructor(W={}){let Z={authorizeUrl:W.authorizeUrl??g.authorizeUrl,tokenUrl:W.tokenUrl??g.tokenUrl,graphUrl:W.graphUrl??g.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:B5,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<X5){if($.reason==="rejected")throw new q1("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let J=await j4("refresh_failed",()=>KW({accessToken:$.accessToken,graphUrl:Z.graphUrl}));return{accessToken:J.accessToken,refreshToken:null,tokenType:J.tokenType,expiresAt:J.expiresIn===null?null:new Date(Date.now()+J.expiresIn*1000),scopes:$.scopes,providerAccountId:$.providerAccountId}}});this.instagram=Z}async exchangeCode(W){let Z=await j4("exchange_failed",()=>G4({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await j4("exchange_failed",()=>YW({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),J=await j4("exchange_failed",()=>X4({accessToken:$.accessToken,graphUrl:this.instagram.graphUrl,graphApiVersion:this.instagram.graphApiVersion}));return{accessToken:$.accessToken,refreshToken:null,tokenType:$.tokenType,expiresAt:$.expiresIn===null?null:new Date(Date.now()+$.expiresIn*1000),scopes:Z.permissions??this.config.scopes,providerAccountId:J.user_id,profile:{...J}}}refresh(){return Promise.reject(new q1("refresh_failed","Instagram connections renew the access token itself; call connection.refresh()."))}}async function B5(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 j4(W,Z){try{return await Z()}catch($){if($ instanceof I)throw new q1(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}class O 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 C={captionLength:2200,hashtags:30,mentions:20,userTags:20,carouselMin:2,carouselMax:10},XW="instagram_business_content_publish",j5={for(W,Z={}){return new p0(W,Z)}};class p0{connection;version;pollIntervalMs;maxPollIntervalMs;timeoutMs;constructor(W,Z={}){this.connection=W;let $=W.connectionProvider();if(!($ instanceof F4))throw TypeError(`Instagram.for() takes an Instagram connection; "${W.provider}" is not an InstagramConnectionProvider.`);let J=Z.graphApiVersion??$.instagram.graphApiVersion;this.version=J?`/${J.replace(/^\/+|\/+$/g,"")}`:"",this.pollIntervalMs=Z.pollIntervalMs??2000,this.maxPollIntervalMs=Z.maxPollIntervalMs??1e4,this.timeoutMs=Z.timeoutMs??300000}async publishImage(W,Z={}){if(v1("imageUrl",W.imageUrl),u0(W.caption),W.altText!==void 0&&typeof W.altText!=="string")k("altText must be a string.");if(W.userTags!==void 0)_5(W.userTags);let $=this.start(Z),J=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(J,!1,$)}async publishCarousel(W,Z={}){let $=W.items;if(!Array.isArray($)||$.length<C.carouselMin||$.length>C.carouselMax)k(`A carousel takes ${C.carouselMin} to ${C.carouselMax} items.`);$.forEach((z,G)=>MW(`items[${G}]`,z)),u0(W.caption);let J=this.start(Z),Q=[];for(let z of $)Q.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"},J));for(let[z,G]of $.entries())if(G.videoUrl!==void 0)await this.waitUntilFinished(Q[z],J);let Y=$.some((z)=>z.videoUrl!==void 0),K=await this.createContainer({media_type:"CAROUSEL",children:Q.join(","),caption:W.caption},J);return this.publishContainer(K,Y,J)}async publishReel(W,Z={}){if(v1("videoUrl",W.videoUrl),W.coverUrl!==void 0)v1("coverUrl",W.coverUrl);if(u0(W.caption),W.thumbOffset!==void 0&&!(Number.isInteger(W.thumbOffset)&&W.thumbOffset>=0))k("thumbOffset must be a whole number of milliseconds, 0 or more.");let $=this.start(Z),J=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(J,!0,$)}async publishStory(W,Z={}){MW("story",W);let $=this.start(Z),J=W.videoUrl!==void 0,Q=await this.createContainer(J?{media_type:"STORIES",video_url:W.videoUrl}:{media_type:"STORIES",image_url:W.imageUrl},$);return this.publishContainer(Q,J,$)}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),J=Array.isArray($.data)?$.data[0]:$,Q=J?.config??{},Y=c0(J?.quota_usage,0),K=c0(Q.quota_total,100);return{quotaUsage:Y,quotaTotal:K,quotaDurationSeconds:c0(Q.quota_duration,86400),remaining:Math.max(0,K-Y)}}async containerStatus(W,Z={}){return this.readStatus(W,this.start(Z))}start(W){if(W.signal?.throwIfAborted(),!this.connection.hasScopes(XW))throw new O("permission_denied",`The Instagram connection was not granted ${XW}; 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 O("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 jW($,"media container request")}async publishContainer(W,Z,$){try{if(Z)await this.waitUntilFinished(W,$);let J=await this.publishOnce(W,Z,$);return{mediaId:J,permalink:await this.permalink(J,$)}}catch(J){throw J instanceof O?S5(J,W):J}}async publishOnce(W,Z,$){try{return await this.mediaPublish(W,$)}catch(J){if(!(J instanceof O))throw J;if(J.code==="transient"){let{statusCode:Q}=await this.readStatus(W,$);if(Q==="PUBLISHED")throw new O("unconfirmed","Instagram's media_publish failed, but the container reads PUBLISHED: the post is probably live. Do not publish it again.",{status:J.status,graphCode:J.graphCode,graphSubcode:J.graphSubcode});if(Q!=="FINISHED")throw J;return this.mediaPublish(W,$)}if(O5(J)&&!Z)return await this.waitUntilFinished(W,$),this.mediaPublish(W,$);throw J}}async mediaPublish(W,Z){let $=await this.call("media_publish request",`/${this.accountId()}/media_publish`,{creation_id:W},Z,{retry:!1});return jW($,"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))k("A container id is a string of digits.");let $=await this.call("container status request",`/${W}?fields=status_code,status`,void 0,Z),J=$.status_code;if(typeof J!=="string"||!F5.has(J))throw new O("graph_error","Instagram's container status answered without a known status_code.",{status:200,containerId:W});let Q={id:W,statusCode:J};if(typeof $.status==="string"&&$.status!=="")Q.status=DW($.status);return Q}async waitUntilFinished(W,Z){let $=this.pollIntervalMs;for(;;){let{statusCode:J,status:Q}=await this.readStatus(W,Z);if(J==="FINISHED")return;if(J==="PUBLISHED")throw new O("invalid_input","That media container has been published already.",{containerId:W});if(J==="ERROR")throw new O("invalid_media",`Instagram could not process the media${Q?` (${Q})`:""}.`,{containerId:W});if(J==="EXPIRED")throw new O("expired","The media container expired before it was published.",{containerId:W});let Y=Z.deadline-Date.now();if(Y<=0)throw new O("timeout","Instagram had not finished processing the media in time; the container is still processing.",{containerId:W});await R5(Math.min($,Y),Z.signal),$=Math.min($*1.5,this.maxPollIntervalMs)}}async call(W,Z,$,J,{retry:Q=!0}={}){try{return await this.callOnce(W,Z,$,J)}catch(Y){if(!Q||!(Y instanceof O)||Y.code!=="transient")throw Y;return this.callOnce(W,Z,$,J)}}async callOnce(W,Z,$,J){J.signal?.throwIfAborted();let Q={method:$?"POST":"GET",signal:J.signal};if($){let z=new URLSearchParams;for(let[G,X]of Object.entries($))if(X!==void 0)z.set(G,X);Q.body=z}let Y;try{Y=await this.connection.fetch(`${this.version}${Z}`,Q)}catch(z){if(J.signal?.aborted)throw J.signal.reason;if(z instanceof TypeError)throw new O("transient",`Instagram's ${W} failed to reach Instagram.`);throw z}let K=E0(await Y.text().catch(()=>""));if(Y.ok)return K;throw x5(W,Y.status,K)}}var F5=new Set(["EXPIRED","ERROR","FINISHED","IN_PROGRESS","PUBLISHED"]),M5=new Set([4,17,32,613,80002]),L5=new Set([3,10]),N5=new Set([9004,352,36000,36001,36002,36003,36004]),D5=new Set([2207004,2207005,2207006,2207009,2207023,2207026,2207028,2207052]),H5=new Set([102,190,463,467]),U5=new Set([2207001,2207003,2207053]),BW={code:9007,subcode:2207027};function x5(W,Z,$){let J=$.error??{},Q=FW(J.code),Y=FW(J.error_subcode),K=typeof J.type==="string"&&J.type!==""?J.type:void 0,z=typeof J.message==="string"&&J.message!==""?`: ${DW(J.message)}`:"",G=[Q,Y].filter((j)=>j!==void 0).join("/"),X=`Instagram refused the ${W} (HTTP ${Z}${K?`, ${K}`:""}${G?` ${G}`:""})${z}`,B="graph_error";if(Y===2207042)B="quota_exceeded";else if(Y===2207010)B="invalid_input";else if(Q!==void 0&&M5.has(Q))B="rate_limited";else if(Q!==void 0&&H5.has(Q))B="reconnect_required";else if(Q!==void 0&&(L5.has(Q)||Q>=200&&Q<=299))B="permission_denied";else if(Q!==void 0&&N5.has(Q)||Y!==void 0&&D5.has(Y))B="invalid_media";else if(J.is_transient===!0||Q===1||Q===2||Y!==void 0&&U5.has(Y)||Z>=500||Z===429)B=Z===429?"rate_limited":"transient";return new O(B,X,{status:Z,graphCode:Q,graphSubcode:Y})}function O5(W){return W.graphCode===BW.code||W.graphSubcode===BW.subcode}function S5(W,Z){if(W.containerId)return W;return new O(W.code,W.message,{status:W.status,graphCode:W.graphCode,graphSubcode:W.graphSubcode,containerId:Z})}function DW(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 jW(W,Z){let $=W.id;if(typeof $==="string"&&$!=="")return $;if(typeof $==="number"&&Number.isSafeInteger($))return String($);throw new O("graph_error",`Instagram's ${Z} answered without an id.`,{status:200})}function FW(W){let Z=Number(W);return W!==void 0&&W!==null&&Number.isFinite(Z)?Z:void 0}function c0(W,Z){let $=Number(W);return W!==void 0&&W!==null&&Number.isFinite($)?$:Z}function R5(W,Z){return new Promise(($,J)=>{if(Z?.aborted)return J(Z.reason);let Q=()=>{clearTimeout(Y),J(Z?.reason)},Y=setTimeout(()=>{Z?.removeEventListener("abort",Q),$()},W);Z?.addEventListener("abort",Q,{once:!0})})}function k(W){throw new O("invalid_input",W)}function u0(W){if(W===void 0)return;if(typeof W!=="string")k("caption must be a string.");if([...W].length>C.captionLength)k(`A caption takes at most ${C.captionLength} characters.`);if((W.match(/#[\p{L}\p{N}_]+/gu)??[]).length>C.hashtags)k(`A caption takes at most ${C.hashtags} hashtags.`);if((W.match(/(?<![\p{L}\p{N}_.@])@[\p{L}\p{N}_.]+/gu)??[]).length>C.mentions)k(`A caption takes at most ${C.mentions} @mentions.`)}function _5(W){if(!Array.isArray(W)||W.length>C.userTags)k(`userTags takes at most ${C.userTags} tags.`);for(let Z of W){let $=(J)=>typeof J==="number"&&J>=0&&J<=1;if(typeof Z?.username!=="string"||Z.username===""||!$(Z.x)||!$(Z.y))k("Each user tag needs a username, and x and y between 0 and 1.")}}function MW(W,Z){let $=Z?.imageUrl!==void 0,J=Z?.videoUrl!==void 0;if($===J)k(`${W} takes exactly one of imageUrl and videoUrl.`);if($)v1(`${W}.imageUrl`,Z.imageUrl);else v1(`${W}.videoUrl`,Z.videoUrl)}function v1(W,Z){let $;try{$=new URL(Z)}catch{k(`${W} is not an absolute URL.`)}if($.protocol!=="https:")k(`${W} must be an https URL: Instagram fetches the media from it.`);let J=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Q=LW(J);if(Q?NW(Q)!==null:!J.includes(".")||/(^|\.)(localhost|local|internal)$/.test(J))k(`${W} must be a public URL: Instagram fetches the media from it.`)}class d0{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 k5(W={}){return new d0(W)}class HW extends l0{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{e8 as viewRouteConfigDefaults,z9 as translationConfigDefaults,M4 as toRangeHeaderValue,y5 as subjectFor,s5 as sniffContentType,lZ as scheduleConfigDefaults,D4 as resolveRange,f9 as redisConfigDefaults,R9 as rateLimiterConfigDefaults,xZ as queueConfigDefaults,G5 as parseMetaSignedRequest,H1 as parseContentRange,V5 as mintSessionToken,zZ as middlewareConfigDefaults,vZ as mcpCallOf,jZ as mailConfigDefaults,t5 as logConfigDefaults,C5 as isSessionToken,mW as isFixedSignInCode,g8 as isFinalRunStatus,O6 as isBroadcastEvent,o5 as isActiveContentType,v5 as inRollout,s8 as imageConfigDefaults,EW as fixedSignInCode,l5 as filesystemConfigDefaults,j9 as featuresConfigDefaults,iZ as eventConfigDefaults,I5 as evaluateFeature,U8 as encodeCursor,ZZ as documentScriptCspHash,tZ as discoverWorkflows,W9 as discoverListeners,aZ as discoverJobs,rZ as discoverCronJobs,eZ as discoverCommands,K9 as defineTranslationConfig,dZ as defineScheduleConfig,y8 as defineRunsConfig,t8 as defineRouteConfig,k9 as defineRedisConfig,S9 as defineRateLimiterConfig,UZ as defineQueueConfig,KZ as defineMiddlewareConfig,BZ as defineMailConfig,a5 as defineLogConfig,i8 as defineImageConfig,d5 as defineFilesystemConfig,B9 as defineFeaturesConfig,k5 as defineFeature,nZ as defineEventConfig,SW as defineEncryptionConfig,mZ as defineCommandConfig,uZ as defineCommand,D8 as defineChangeFeedConfig,e5 as defineCacheConfig,V8 as defineBroadcastConfig,P5 as defineAuthConfig,x8 as decodeCursor,DZ as createWorkflowTableStatements,c8 as createRunsTableStatements,cZ as commandConfigDefaults,H8 as changeFeedConfigDefaults,W8 as cacheConfigDefaults,q5 as bucketOf,w5 as bucketKey,T8 as broadcastConfigDefaults,w4 as bearerToken,b5 as authConfigDefaults,L4 as assertDeletablePrefix,r8 as apiRouteConfigDefaults,$W as XOAuthProvider,VZ as WorkflowRuntime,fZ as WorkflowCancelledError,oZ as Workflow,_Z as WaitTimeoutError,QZ as ViewRouteDispatcher,m5 as UndeclaredFeatureError,Q8 as TaggedCache,i5 as StorageFetchTimeoutError,kZ as StepTimeoutError,RZ as StepFailedError,CZ as Step,HW as StaticFeatureFlagSource,n8 as Sharp,hZ as Scheduler,G9 as ScheduleServiceProvider,JZ as STATIC_NAVIGATION_CSP_HASH,C8 as SOCKET_ID_HEADER,f5 as SESSION_TOKEN_PREFIX,s0 as S3Driver,T9 as RunsServiceProvider,u8 as RunNotFoundError,d8 as RunManager,p8 as RunFailure,V9 as RouteServiceProvider,XZ as ResendDriver,C9 as RedisServiceProvider,O4 as RedisRateLimiterTimeoutError,A1 as RedisRateLimiterDisconnectedError,e0 as RedisRateLimiter,y1 as RedisManager,$8 as RedisCacheStore,b8 as RedisBroadcastDriver,_9 as RateLimiterServiceProvider,U4 as RateLimiterDriver,T5 as RateLimiter,J1 as RangeNotSatisfiableError,Z9 as QueueServiceProvider,TZ as QueueManager,N8 as ProviderConnection,H6 as PrismaMcpOAuthStore,v8 as PendingBroadcast,h8 as OPEN_RUN_STATUSES,M8 as OAuthReconnectRequiredError,m as OAuthProvider,m0 as OAuthConnectionProvider,q1 as OAuthConnectionError,U as OAuthCallbackError,O9 as MiddlewareServiceProvider,a8 as MiddlewareRegistry,y as MetaSignedRequestError,OZ as MemoryWorkflowStore,E8 as MemoryRunStore,SZ as MemoryQueueDriver,D6 as MemoryMcpOAuthStore,LZ as MemoryLockStore,j8 as MemoryConnectionStore,S8 as MemoryChangeFeedDriver,Z8 as MemoryCacheStore,P8 as MemoryBroadcastDriver,wZ as McpToolError,IZ as McpRegistry,L6 as McpOAuthServer,AZ as McpHttpServer,qZ as McpCallRefusedError,yZ as McpApiKeyResolver,M9 as MailServiceProvider,FZ as MailManager,x9 as LogServiceProvider,r5 as LogManager,z8 as LockManager,Y8 as LockLostError,sZ as Listener,U9 as KernelIdServiceProvider,WZ as KernelId,PZ as Job,f8 as InvalidChannelError,p0 as InstagramPublisher,O as InstagramPublishError,GW as InstagramOAuthProvider,F4 as InstagramConnectionProvider,I as InstagramApiError,j5 as Instagram,x4 as InMemoryRateLimiter,H9 as ImageServiceProvider,l8 as ImageOptimizationDriver,o8 as ImageManager,$Z as ISLAND_LOADER_CSP_HASH,C as INSTAGRAM_LIMITS,K8 as HeldLock,C6 as GoogleOAuthProvider,T6 as GitHubOAuthProvider,D9 as FilesystemServiceProvider,n5 as FilesystemManager,p5 as FileSystemDriver,U1 as FileStorageDriver,a as FileNotFoundError,F9 as FeaturesServiceProvider,E5 as FeatureSourceReadOnlyError,c5 as FeatureScope,A5 as FeatureReloadError,g5 as FeatureModelMissingError,u5 as FeatureManager,h5 as FeatureFlagStore,l0 as FeatureFlagSource,d0 as Feature,A8 as FINAL_RUN_STATUSES,N9 as EventServiceProvider,w as EventManager,p1 as Event,L9 as EncryptionServiceProvider,X8 as EncryptionKeyError,G8 as Encrypter,GZ as EmailDriver,B8 as DecryptionError,NZ as DatabaseWorkflowStore,m8 as DatabaseRunStore,HZ as DatabaseQueueDriver,MZ as DatabaseLockStore,X9 as DatabaseFeatureFlagSource,F8 as DatabaseConnectionStore,O8 as DatabaseChangeFeedDriver,bZ as DEFAULT_MCP_SCOPE,pZ as CronJob,L8 as ConnectionManager,P9 as CommandRegistry,gZ as CommandFailed,EZ as Command,k8 as ChangeFeedSubscription,Q9 as ChangeFeedServiceProvider,_8 as ChangeFeedManager,R8 as ChangeFeedFullError,J9 as CacheServiceProvider,J8 as CacheManager,h1 as CONSENT_PAGE_HEADERS,$9 as BroadcastServiceProvider,I8 as BroadcastScope,w8 as BroadcastPayloadTooLargeError,q8 as BroadcastManager,S6 as BroadcastEvent,a0 as AzureBlobDriver,Y9 as AuthServiceProvider,e as AuthManager,YZ as ApiRouteDispatcher};
|
|
70
|
+
`).filter((J)=>J).map((J)=>JSON.parse(J))}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 N1 extends M1{constructor(){super(...arguments);this._prefix=Q1}get readOnly(){return this}}class D1 extends L1{constructor(){super(...arguments);this._prefix=d}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new N1(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 J=Z.media_category;if(!Z.media_category){if(Z.media_type.includes("gif"))J="tweet_gif";else if(Z.media_type.includes("image"))J="tweet_image";else if(Z.media_type.includes("video"))J="tweet_video"}let Q={additional_owners:Z.additional_owners,media_type:Z.media_type,total_bytes:W.length,media_category:J},K=(await this.post("media/upload/initialize",Q)).data.id,G=Math.ceil(W.length/$),z=new Uint8Array(W);for(let B=0;B<G;B++){let j=B*$,L=Math.min(j+$,W.length),H=z.slice(j,L),S=Buffer.from(H),o={segment_index:B,media:S};await this.post(`media/upload/${K}/append`,o,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${K}/finalize`)).data.processing_info)await this.waitForMediaProcessing(K);return K}async waitForMediaProcessing(W){var Z;let J=(await this.get("media/upload",{command:"STATUS",media_id:W})).data.processing_info;if(!J)return;switch(J.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(Z=J.error)===null||Z===void 0?void 0:Z.message}`);case"pending":case"in_progress":{let Q=J===null||J===void 0?void 0:J.check_after_secs;if(Q&&Q>0)await new Promise((Y)=>setTimeout(Y,Q*1000)),await this.waitForMediaProcessing(W)}}}createMediaMetadata(W,Z){return this.post("media/metadata",{id:W,metadata:Z})}reply(W,Z,$={}){var J;let Q={in_reply_to_tweet_id:Z,...(J=$.reply)!==null&&J!==void 0?J:{}};return this.post("tweets",{text:W,...$,reply:Q})}quote(W,Z,$={}){return this.tweet(W,{...$,quote_tweet_id:Z})}async tweetThread(W){var Z,$;let J=[];for(let Q of W){let Y=J.length?J[J.length-1]:null,K={...typeof Q==="string"?{text:Q}:Q},G=Y?Y.data.id:(Z=K.reply)===null||Z===void 0?void 0:Z.in_reply_to_tweet_id,z=($=K.text)!==null&&$!==void 0?$:"";if(G)J.push(await this.reply(z,G,K));else J.push(await this.tweet(z,K))}return J}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 t6 extends N1{constructor(){super(...arguments);this._prefix=Q1}get readWrite(){return this}}var r6=t6;class e6 extends D1{constructor(){super(...arguments);this._prefix=d}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new r6(this)}}var WW=e6;class w1 extends i{get v1(){if(this._v1)return this._v1;return this._v1=new B1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new L1(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:J,screenName:Q}={}){let Y=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:W,x_auth_access_type:Z}),K=`https://api.x.com/oauth/${$}?oauth_token=${encodeURIComponent(Y.oauth_token)}`;if(J!==void 0)K+=`&force_login=${encodeURIComponent(J)}`;if(Q!==void 0)K+=`&screen_name=${encodeURIComponent(Q)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:K,oauthResult:Y});return{url:K,...Y}}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}),J=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:J}}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 $,J;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 Q=($=Z.state)!==null&&$!==void 0?$:$1.generateRandomString(32),Y=$1.getCodeVerifier(),K=$1.getCodeChallengeFromVerifier(Y),G=(J=Z.scope)!==null&&J!==void 0?J:"",z=Array.isArray(G)?G.join(" "):G,X=new URL("https://x.com/i/oauth2/authorize"),B={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:W,state:Q,code_challenge:K,code_challenge_method:"s256",scope:z};T.addQueryParamsToUrl(X,B);let j={url:X.toString(),state:Q,codeVerifier:Y,codeChallenge:K};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 J=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(J)}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((J)=>J);return{client:Z,expiresIn:W.expires_in,accessToken:W.access_token,scope:$,refreshToken:W.refresh_token}}}class q1 extends w1{get v1(){if(this._v1)return this._v1;return this._v1=new j1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new D1(this)}get readOnly(){return this}}class Y4 extends P{constructor(){super(...arguments);this._prefix=Y1}}class K4 extends Y4{constructor(){super(...arguments);this._prefix=Y1}get readOnly(){return this}}class G4 extends P{constructor(){super(...arguments);this._prefix=K1}}class z4 extends G4{constructor(){super(...arguments);this._prefix=K1}get readOnly(){return this}}class ZW extends z4{constructor(){super(...arguments);this._prefix=K1}get readWrite(){return this}}var $W=ZW;class JW extends K4{constructor(){super(...arguments);this._prefix=Y1}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new $W(this)}}var QW=JW;class X4 extends q1{get v1(){if(this._v1)return this._v1;return this._v1=new Z4(this)}get v2(){if(this._v2)return this._v2;return this._v2=new WW(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new QW(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(),J=["normal","bigger","mini"],Q=W;for(let K of J)if($.includes(`_${K}`)){Q=W.replace(`_${K}`,"");break}if(Z==="original")return Q;let Y=Q.lastIndexOf(".");if(Y!==-1){let K=Q.slice(Y+1);return Q.slice(0,Y)+"_"+Z+"."+K}else return Q+"_"+Z}}var X5={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class YW extends m{config;client;constructor(W={}){super();this.config={...X5,...W},this.client=new X4({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"XOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}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"),J={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[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W,Z){let $=W.search.get("code");if(!$)throw new U("missing_code");if(!Z?.codeVerifier)throw new U("invalid_state");let J=this.config.resolve?await this.clientFor(W):this.staticClient();if(!J)throw new U("unknown_provider");let Q=this.config.resolve?new X4({clientId:J.clientId,clientSecret:J.clientSecret}):this.client,Y;try{Y=await Q.loginWithOAuth2({code:$,codeVerifier:Z.codeVerifier,redirectUri:J.redirectUri})}catch(j){throw console.error("X OAuth error: token exchange failed",j),new U("exchange_failed")}let{data:K}=await Y.client.v2.me({"user.fields":["name","username","entities"]}),{name:G,email:z,id:X="",username:B}=K??{};return{name:G,email:z,username:B,providerId:X}}}var GW=["instagram_business_basic"],E={authorizeUrl:"https://www.instagram.com/oauth/authorize",tokenUrl:"https://api.instagram.com/oauth/access_token",graphUrl:"https://graph.instagram.com"};class I extends Error{status;type;code;constructor(W,Z,$,J,Q){super(W,Q);this.status=Z;this.type=$;this.code=J;this.name="InstagramApiError"}}async function B4(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 F4(W.tokenUrl??E.tokenUrl,"code exchange",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Z.toString()}),J=Array.isArray($.data)?$.data[0]:$,Q=J?.access_token;if(typeof Q!=="string"||Q==="")throw new I("Instagram's code exchange answered without an access token.",200);let Y=J?.permissions;return{accessToken:Q,userId:u0(J?.user_id),permissions:Array.isArray(Y)?Y.map(String):typeof Y==="string"?Y.split(/[\s,]+/).filter(Boolean):null}}async function zW(W){let Z=new URL("/access_token",W.graphUrl??E.graphUrl);return Z.searchParams.set("grant_type","ig_exchange_token"),Z.searchParams.set("client_secret",W.clientSecret),Z.searchParams.set("access_token",W.accessToken),BW(await F4(Z.toString(),"long-lived token exchange",{method:"GET"}))}async function XW(W){let Z=new URL("/refresh_access_token",W.graphUrl??E.graphUrl);return Z.searchParams.set("grant_type","ig_refresh_token"),Z.searchParams.set("access_token",W.accessToken),BW(await F4(Z.toString(),"token refresh",{method:"GET"}))}async function j4(W){let Z=W.graphApiVersion?`/${W.graphApiVersion.replace(/^\/+|\/+$/g,"")}`:"",$=new URL(`${Z}/me`,W.graphUrl??E.graphUrl);$.searchParams.set("fields",(W.fields??["user_id","username","name","account_type","profile_picture_url"]).join(",")),$.searchParams.set("access_token",W.accessToken);let J=await F4($.toString(),"profile request",{method:"GET"}),Q=Array.isArray(J.data)?J.data[0]:J,Y=u0(Q?.user_id);if(!Y)throw new I("Instagram's /me answered without a user_id.",200);let K={user_id:Y},G=u0(Q?.id);if(G)K.id=G;for(let z of["username","name","account_type","profile_picture_url"]){let X=Q?.[z];if(typeof X==="string"&&X!=="")K[z]=X}return K}function BW(W){if(typeof W.access_token!=="string"||W.access_token==="")throw new I("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 F4(W,Z,$){let J;try{J=await fetch(W,{...$,redirect:"error"})}catch(Y){throw new I(`Instagram's ${Z} failed to reach Instagram.`,void 0,void 0,void 0,{cause:Y})}let Q=p0(await J.text().catch(()=>""));if(!J.ok){let Y=Q.error??{},K=KW(Q.error_type)??KW(Y.type),G=Number(Q.code??Y.code);throw new I(`Instagram refused the ${Z} (HTTP ${J.status}${K?`, ${K}`:""}${Number.isFinite(G)?` ${G}`:""}).`,J.status,K,Number.isFinite(G)?G:void 0)}return Q}function p0(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 u0(W){if(typeof W==="string"&&W!=="")return W;if(typeof W==="number"&&Number.isSafeInteger(W))return String(W);return null}function KW(W){return typeof W==="string"&&W!==""?W:void 0}class jW extends m{createUsersWithoutEmail=!0;linkByEmail=!1;config;constructor(W={}){super();this.config={clientId:process.env.INSTAGRAM_CLIENT_ID??"",clientSecret:process.env.INSTAGRAM_CLIENT_SECRET??"",scopes:GW,redirectPath:"/auth/oauth/instagram/callback",authorizationParams:{},...W}}redirectUri(){return`${V()??""}${this.config.redirectPath}`}clientFor(W){return p(this,W,{name:"InstagramOAuthProvider",resolve:this.config.resolve,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectPath:this.config.redirectPath,staticRedirectUri:()=>this.redirectUri(),staticOrigin:()=>V()??""})}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??E.authorizeUrl),J={...this.config.authorizationParams,client_id:W.clientId,redirect_uri:W.redirectUri,response_type:"code",scope:this.config.scopes.join(",")};if(Z)J.state=Z.state;for(let[Q,Y]of Object.entries(J))$.searchParams.set(Q,Y);return $.toString()}async onCallback(W){let Z=W.search.get("code");if(!Z)throw new U("missing_code");let $=this.config.resolve?await this.clientFor(W):this.staticClient();if(!$)throw new U("unknown_provider");let J;try{let Q=await B4({code:Z,clientId:$.clientId,clientSecret:$.clientSecret,redirectUri:$.redirectUri,tokenUrl:this.config.tokenUrl});J=await j4({accessToken:Q.accessToken,graphUrl:this.config.graphUrl,graphApiVersion:this.config.graphApiVersion,fields:["user_id","username","name"]})}catch(Q){if(Q instanceof I)throw console.error(`Instagram OAuth error: ${Q.message}`),new U("exchange_failed");throw Q}return{providerId:J.user_id,username:J.username,name:J.name||J.username}}}import{createHmac as B5,timingSafeEqual as j5}from"crypto";class y extends Error{reason;constructor(W,Z){super(Z);this.reason=W;this.name="MetaSignedRequestError"}}function F5(W,Z,$={}){if(!Z)throw Error("parseMetaSignedRequest needs the app secret.");if(typeof W!=="string")throw new y("malformed","No signed_request was given.");let J=W.indexOf(".");if(J<=0||J===W.length-1||W.indexOf(".",J+1)!==-1)throw new y("malformed","A signed_request is <signature>.<payload>.");let Q=W.slice(0,J),Y=W.slice(J+1);if(!/^[A-Za-z0-9_-]+={0,2}$/.test(Q)||!/^[A-Za-z0-9_-]+={0,2}$/.test(Y))throw new y("malformed","A signed_request is base64url.");let K=B5("sha256",Z).update(Y).digest(),G=Buffer.from(Q,"base64url");if(G.length!==K.length||!j5(G,K))throw new y("bad_signature","The signed_request's signature does not match the app secret.");let z;try{let L=Buffer.from(Y,"base64url").toString("utf8").replace(/("user_id"\s*:\s*)(-?\d+)(?=\s*[,}])/g,'$1"$2"');z=JSON.parse(L)}catch{throw new y("malformed","The signed_request's payload is not JSON.")}if(!z||typeof z!=="object")throw new y("malformed","The signed_request's payload is not an object.");if(String(z.algorithm??"").toUpperCase()!=="HMAC-SHA256")throw new y("unsupported_algorithm","Only HMAC-SHA256 signed_requests are accepted.");let X=Math.floor(($.now??Date.now())/1000),B=Number(z.expires);if(Number.isFinite(B)&&B>0&&B<X)throw new y("expired","The signed_request has expired.");let j=z.user_id;if((typeof j!=="string"||j==="")&&typeof j!=="number")throw new y("missing_user","The signed_request names no user.");return{...z,algorithm:String(z.algorithm),user_id:String(j)}}var M5=86400000;class L4 extends d0{instagram;constructor(W={}){let Z={authorizeUrl:W.authorizeUrl??E.authorizeUrl,tokenUrl:W.tokenUrl??E.tokenUrl,graphUrl:W.graphUrl??E.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:L5,refreshStrategy:async($)=>{if(Date.now()-$.issuedAt.getTime()<M5){if($.reason==="rejected")throw new v1("refresh_failed","Instagram refused the access token (OAuthException 190).",{status:401});return null}let J=await M4("refresh_failed",()=>XW({accessToken:$.accessToken,graphUrl:Z.graphUrl}));return{accessToken:J.accessToken,refreshToken:null,tokenType:J.tokenType,expiresAt:J.expiresIn===null?null:new Date(Date.now()+J.expiresIn*1000),scopes:$.scopes,providerAccountId:$.providerAccountId}}});this.instagram=Z}async exchangeCode(W){let Z=await M4("exchange_failed",()=>B4({code:W.code,clientId:this.config.clientId,clientSecret:this.config.clientSecret,redirectUri:W.redirectUri,tokenUrl:this.instagram.tokenUrl})),$=await M4("exchange_failed",()=>zW({accessToken:Z.accessToken,clientSecret:this.config.clientSecret,graphUrl:this.instagram.graphUrl})),J=await M4("exchange_failed",()=>j4({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:J.user_id,profile:{...J}}}refresh(){return Promise.reject(new v1("refresh_failed","Instagram connections renew the access token itself; call connection.refresh()."))}}async function L5(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 M4(W,Z){try{return await Z()}catch($){if($ instanceof I)throw new v1(W,$.message,{cause:$,status:$.status===200?502:$.status});throw $}}class O 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 C={captionLength:2200,hashtags:30,mentions:20,userTags:20,carouselMin:2,carouselMax:10},FW="instagram_business_content_publish",N5={for(W,Z={}){return new i0(W,Z)}};class i0{connection;version;pollIntervalMs;maxPollIntervalMs;timeoutMs;constructor(W,Z={}){this.connection=W;let $=W.connectionProvider();if(!($ instanceof L4))throw TypeError(`Instagram.for() takes an Instagram connection; "${W.provider}" is not an InstagramConnectionProvider.`);let J=Z.graphApiVersion??$.instagram.graphApiVersion;this.version=J?`/${J.replace(/^\/+|\/+$/g,"")}`:"",this.pollIntervalMs=Z.pollIntervalMs??2000,this.maxPollIntervalMs=Z.maxPollIntervalMs??1e4,this.timeoutMs=Z.timeoutMs??300000}async publishImage(W,Z={}){if(I1("imageUrl",W.imageUrl),n0(W.caption),W.altText!==void 0&&typeof W.altText!=="string")k("altText must be a string.");if(W.userTags!==void 0)V5(W.userTags);let $=this.start(Z),J=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(J,!1,$)}async publishCarousel(W,Z={}){let $=W.items;if(!Array.isArray($)||$.length<C.carouselMin||$.length>C.carouselMax)k(`A carousel takes ${C.carouselMin} to ${C.carouselMax} items.`);$.forEach((G,z)=>DW(`items[${z}]`,G)),n0(W.caption);let J=this.start(Z),Q=[];for(let G of $)Q.push(await this.createContainer(G.videoUrl!==void 0?{media_type:"VIDEO",video_url:G.videoUrl,is_carousel_item:"true"}:{image_url:G.imageUrl,is_carousel_item:"true"},J));for(let[G,z]of $.entries())if(z.videoUrl!==void 0)await this.waitUntilFinished(Q[G],J);let Y=$.some((G)=>G.videoUrl!==void 0),K=await this.createContainer({media_type:"CAROUSEL",children:Q.join(","),caption:W.caption},J);return this.publishContainer(K,Y,J)}async publishReel(W,Z={}){if(I1("videoUrl",W.videoUrl),W.coverUrl!==void 0)I1("coverUrl",W.coverUrl);if(n0(W.caption),W.thumbOffset!==void 0&&!(Number.isInteger(W.thumbOffset)&&W.thumbOffset>=0))k("thumbOffset must be a whole number of milliseconds, 0 or more.");let $=this.start(Z),J=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(J,!0,$)}async publishStory(W,Z={}){DW("story",W);let $=this.start(Z),J=W.videoUrl!==void 0,Q=await this.createContainer(J?{media_type:"STORIES",video_url:W.videoUrl}:{media_type:"STORIES",image_url:W.imageUrl},$);return this.publishContainer(Q,J,$)}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),J=Array.isArray($.data)?$.data[0]:$,Q=J?.config??{},Y=l0(J?.quota_usage,0),K=l0(Q.quota_total,100);return{quotaUsage:Y,quotaTotal:K,quotaDurationSeconds:l0(Q.quota_duration,86400),remaining:Math.max(0,K-Y)}}async containerStatus(W,Z={}){return this.readStatus(W,this.start(Z))}start(W){if(W.signal?.throwIfAborted(),!this.connection.hasScopes(FW))throw new O("permission_denied",`The Instagram connection was not granted ${FW}; 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 O("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 LW($,"media container request")}async publishContainer(W,Z,$){try{if(Z)await this.waitUntilFinished(W,$);let J=await this.publishOnce(W,Z,$);return{mediaId:J,permalink:await this.permalink(J,$)}}catch(J){throw J instanceof O?f5(J,W):J}}async publishOnce(W,Z,$){try{return await this.mediaPublish(W,$)}catch(J){if(!(J instanceof O))throw J;if(J.code==="transient"){let{statusCode:Q}=await this.readStatus(W,$);if(Q==="PUBLISHED")throw new O("unconfirmed","Instagram's media_publish failed, but the container reads PUBLISHED: the post is probably live. Do not publish it again.",{status:J.status,graphCode:J.graphCode,graphSubcode:J.graphSubcode});if(Q!=="FINISHED")throw J;return this.mediaPublish(W,$)}if(k5(J)&&!Z)return await this.waitUntilFinished(W,$),this.mediaPublish(W,$);throw J}}async mediaPublish(W,Z){let $=await this.call("media_publish request",`/${this.accountId()}/media_publish`,{creation_id:W},Z,{retry:!1});return LW($,"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))k("A container id is a string of digits.");let $=await this.call("container status request",`/${W}?fields=status_code,status`,void 0,Z),J=$.status_code;if(typeof J!=="string"||!D5.has(J))throw new O("graph_error","Instagram's container status answered without a known status_code.",{status:200,containerId:W});let Q={id:W,statusCode:J};if(typeof $.status==="string"&&$.status!=="")Q.status=xW($.status);return Q}async waitUntilFinished(W,Z){let $=this.pollIntervalMs;for(;;){let{statusCode:J,status:Q}=await this.readStatus(W,Z);if(J==="FINISHED")return;if(J==="PUBLISHED")throw new O("invalid_input","That media container has been published already.",{containerId:W});if(J==="ERROR")throw new O("invalid_media",`Instagram could not process the media${Q?` (${Q})`:""}.`,{containerId:W});if(J==="EXPIRED")throw new O("expired","The media container expired before it was published.",{containerId:W});let Y=Z.deadline-Date.now();if(Y<=0)throw new O("timeout","Instagram had not finished processing the media in time; the container is still processing.",{containerId:W});await C5(Math.min($,Y),Z.signal),$=Math.min($*1.5,this.maxPollIntervalMs)}}async call(W,Z,$,J,{retry:Q=!0}={}){try{return await this.callOnce(W,Z,$,J)}catch(Y){if(!Q||!(Y instanceof O)||Y.code!=="transient")throw Y;return this.callOnce(W,Z,$,J)}}async callOnce(W,Z,$,J){J.signal?.throwIfAborted();let Q={method:$?"POST":"GET",signal:J.signal};if($){let G=new URLSearchParams;for(let[z,X]of Object.entries($))if(X!==void 0)G.set(z,X);Q.body=G}let Y;try{Y=await this.connection.fetch(`${this.version}${Z}`,Q)}catch(G){if(J.signal?.aborted)throw J.signal.reason;if(G instanceof TypeError)throw new O("transient",`Instagram's ${W} failed to reach Instagram.`);throw G}let K=p0(await Y.text().catch(()=>""));if(Y.ok)return K;throw _5(W,Y.status,K)}}var D5=new Set(["EXPIRED","ERROR","FINISHED","IN_PROGRESS","PUBLISHED"]),H5=new Set([4,17,32,613,80002]),U5=new Set([3,10]),x5=new Set([9004,352,36000,36001,36002,36003,36004]),O5=new Set([2207004,2207005,2207006,2207009,2207023,2207026,2207028,2207052]),S5=new Set([102,190,463,467]),R5=new Set([2207001,2207003,2207053]),MW={code:9007,subcode:2207027};function _5(W,Z,$){let J=$.error??{},Q=NW(J.code),Y=NW(J.error_subcode),K=typeof J.type==="string"&&J.type!==""?J.type:void 0,G=typeof J.message==="string"&&J.message!==""?`: ${xW(J.message)}`:"",z=[Q,Y].filter((j)=>j!==void 0).join("/"),X=`Instagram refused the ${W} (HTTP ${Z}${K?`, ${K}`:""}${z?` ${z}`:""})${G}`,B="graph_error";if(Y===2207042)B="quota_exceeded";else if(Y===2207010)B="invalid_input";else if(Q!==void 0&&H5.has(Q))B="rate_limited";else if(Q!==void 0&&S5.has(Q))B="reconnect_required";else if(Q!==void 0&&(U5.has(Q)||Q>=200&&Q<=299))B="permission_denied";else if(Q!==void 0&&x5.has(Q)||Y!==void 0&&O5.has(Y))B="invalid_media";else if(J.is_transient===!0||Q===1||Q===2||Y!==void 0&&R5.has(Y)||Z>=500||Z===429)B=Z===429?"rate_limited":"transient";return new O(B,X,{status:Z,graphCode:Q,graphSubcode:Y})}function k5(W){return W.graphCode===MW.code||W.graphSubcode===MW.subcode}function f5(W,Z){if(W.containerId)return W;return new O(W.code,W.message,{status:W.status,graphCode:W.graphCode,graphSubcode:W.graphSubcode,containerId:Z})}function xW(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 LW(W,Z){let $=W.id;if(typeof $==="string"&&$!=="")return $;if(typeof $==="number"&&Number.isSafeInteger($))return String($);throw new O("graph_error",`Instagram's ${Z} answered without an id.`,{status:200})}function NW(W){let Z=Number(W);return W!==void 0&&W!==null&&Number.isFinite(Z)?Z:void 0}function l0(W,Z){let $=Number(W);return W!==void 0&&W!==null&&Number.isFinite($)?$:Z}function C5(W,Z){return new Promise(($,J)=>{if(Z?.aborted)return J(Z.reason);let Q=()=>{clearTimeout(Y),J(Z?.reason)},Y=setTimeout(()=>{Z?.removeEventListener("abort",Q),$()},W);Z?.addEventListener("abort",Q,{once:!0})})}function k(W){throw new O("invalid_input",W)}function n0(W){if(W===void 0)return;if(typeof W!=="string")k("caption must be a string.");if([...W].length>C.captionLength)k(`A caption takes at most ${C.captionLength} characters.`);if((W.match(/#[\p{L}\p{N}_]+/gu)??[]).length>C.hashtags)k(`A caption takes at most ${C.hashtags} hashtags.`);if((W.match(/(?<![\p{L}\p{N}_.@])@[\p{L}\p{N}_.]+/gu)??[]).length>C.mentions)k(`A caption takes at most ${C.mentions} @mentions.`)}function V5(W){if(!Array.isArray(W)||W.length>C.userTags)k(`userTags takes at most ${C.userTags} tags.`);for(let Z of W){let $=(J)=>typeof J==="number"&&J>=0&&J<=1;if(typeof Z?.username!=="string"||Z.username===""||!$(Z.x)||!$(Z.y))k("Each user tag needs a username, and x and y between 0 and 1.")}}function DW(W,Z){let $=Z?.imageUrl!==void 0,J=Z?.videoUrl!==void 0;if($===J)k(`${W} takes exactly one of imageUrl and videoUrl.`);if($)I1(`${W}.imageUrl`,Z.imageUrl);else I1(`${W}.videoUrl`,Z.videoUrl)}function I1(W,Z){let $;try{$=new URL(Z)}catch{k(`${W} is not an absolute URL.`)}if($.protocol!=="https:")k(`${W} must be an https URL: Instagram fetches the media from it.`);let J=$.hostname.replace(/^\[|\]$/g,"").toLowerCase(),Q=HW(J);if(Q?UW(Q)!==null:!J.includes(".")||/(^|\.)(localhost|local|internal)$/.test(J))k(`${W} must be a public URL: Instagram fetches the media from it.`)}class s0{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 T5(W={}){return new s0(W)}class OW extends o0{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{JZ as viewRouteConfigDefaults,j9 as translationConfigDefaults,N4 as toRangeHeaderValue,g5 as subjectFor,zZ as strictCspPolicy,r5 as sniffContentType,oZ as scheduleConfigDefaults,U4 as resolveRange,P9 as redisConfigDefaults,C9 as rateLimiterConfigDefaults,_Z as queueConfigDefaults,F5 as parseMetaSignedRequest,H1 as parseContentRange,w5 as mintSessionToken,FZ as middlewareConfigDefaults,hZ as mcpCallOf,NZ as mailConfigDefaults,Z8 as logConfigDefaults,b5 as isSessionToken,dW as isFixedSignInCode,u8 as isFinalRunStatus,_6 as isBroadcastEvent,e5 as isActiveContentType,h5 as inRollout,r8 as imageConfigDefaults,pW as fixedSignInCode,o5 as filesystemConfigDefaults,N9 as featuresConfigDefaults,tZ as eventConfigDefaults,E5 as evaluateFeature,R8 as encodeCursor,YZ as documentScriptCspHash,Z9 as discoverWorkflows,Q9 as discoverListeners,W9 as discoverJobs,$9 as discoverCronJobs,J9 as discoverCommands,B9 as defineTranslationConfig,sZ as defineScheduleConfig,g8 as defineRunsConfig,ZZ as defineRouteConfig,T9 as defineRedisConfig,f9 as defineRateLimiterConfig,RZ as defineQueueConfig,jZ as defineMiddlewareConfig,LZ as defineMailConfig,W8 as defineLogConfig,t8 as defineImageConfig,s5 as defineFilesystemConfig,L9 as defineFeaturesConfig,T5 as defineFeature,aZ as defineEventConfig,kW as defineEncryptionConfig,dZ as defineCommandConfig,nZ as defineCommand,O8 as defineChangeFeedConfig,J8 as defineCacheConfig,w8 as defineBroadcastConfig,v5 as defineAuthConfig,_8 as decodeCursor,OZ as createWorkflowTableStatements,l8 as createRunsTableStatements,lZ as commandConfigDefaults,S8 as changeFeedConfigDefaults,Q8 as cacheConfigDefaults,A5 as bucketOf,y5 as bucketKey,q8 as broadcastConfigDefaults,y4 as bearerToken,I5 as authConfigDefaults,D4 as assertDeletablePrefix,$Z as apiRouteConfigDefaults,YW as XOAuthProvider,wZ as WorkflowRuntime,PZ as WorkflowCancelledError,eZ as Workflow,VZ as WaitTimeoutError,XZ as ViewRouteDispatcher,d5 as UndeclaredFeatureError,z8 as TaggedCache,t5 as StorageFetchTimeoutError,TZ as StepTimeoutError,CZ as StepFailedError,bZ as Step,OW as StaticFeatureFlagSource,a8 as Sharp,cZ as Scheduler,F9 as ScheduleServiceProvider,GZ as STATIC_NAVIGATION_CSP_HASH,b8 as SOCKET_ID_HEADER,P5 as SESSION_TOKEN_PREFIX,t0 as S3Driver,q9 as RunsServiceProvider,n8 as RunNotFoundError,s8 as RunManager,i8 as RunFailure,w9 as RouteServiceProvider,MZ as ResendDriver,b9 as RedisServiceProvider,R4 as RedisRateLimiterTimeoutError,E1 as RedisRateLimiterDisconnectedError,$6 as RedisRateLimiter,h1 as RedisManager,K8 as RedisCacheStore,I8 as RedisBroadcastDriver,V9 as RateLimiterServiceProvider,O4 as RateLimiterDriver,q5 as RateLimiter,J1 as RangeNotSatisfiableError,Y9 as QueueServiceProvider,qZ as QueueManager,x8 as ProviderConnection,O6 as PrismaMcpOAuthStore,h8 as PendingBroadcast,c8 as OPEN_RUN_STATUSES,H8 as OAuthReconnectRequiredError,m as OAuthProvider,d0 as OAuthConnectionProvider,v1 as OAuthConnectionError,U as OAuthCallbackError,k9 as MiddlewareServiceProvider,WZ as MiddlewareRegistry,y as MetaSignedRequestError,kZ as MemoryWorkflowStore,p8 as MemoryRunStore,fZ as MemoryQueueDriver,x6 as MemoryMcpOAuthStore,UZ as MemoryLockStore,N8 as MemoryConnectionStore,f8 as MemoryChangeFeedDriver,Y8 as MemoryCacheStore,v8 as MemoryBroadcastDriver,yZ as McpToolError,EZ as McpRegistry,H6 as McpOAuthServer,mZ as McpHttpServer,AZ as McpCallRefusedError,gZ as McpApiKeyResolver,H9 as MailServiceProvider,DZ as MailManager,_9 as LogServiceProvider,$8 as LogManager,j8 as LockManager,X8 as LockLostError,rZ as Listener,R9 as KernelIdServiceProvider,QZ as KernelId,vZ as Job,P8 as InvalidChannelError,i0 as InstagramPublisher,O as InstagramPublishError,jW as InstagramOAuthProvider,L4 as InstagramConnectionProvider,I as InstagramApiError,N5 as Instagram,S4 as InMemoryRateLimiter,S9 as ImageServiceProvider,o8 as ImageOptimizationDriver,e8 as ImageManager,KZ as ISLAND_LOADER_CSP_HASH,C as INSTAGRAM_LIMITS,B8 as HeldLock,P6 as GoogleOAuthProvider,w6 as GitHubOAuthProvider,O9 as FilesystemServiceProvider,a5 as FilesystemManager,i5 as FileSystemDriver,U1 as FileStorageDriver,a as FileNotFoundError,D9 as FeaturesServiceProvider,p5 as FeatureSourceReadOnlyError,l5 as FeatureScope,m5 as FeatureReloadError,u5 as FeatureModelMissingError,n5 as FeatureManager,c5 as FeatureFlagStore,o0 as FeatureFlagSource,s0 as Feature,m8 as FINAL_RUN_STATUSES,x9 as EventServiceProvider,w as EventManager,l1 as Event,U9 as EncryptionServiceProvider,M8 as EncryptionKeyError,F8 as Encrypter,_4 as EmailDriver,L8 as DecryptionError,xZ as DatabaseWorkflowStore,d8 as DatabaseRunStore,SZ as DatabaseQueueDriver,HZ as DatabaseLockStore,M9 as DatabaseFeatureFlagSource,D8 as DatabaseConnectionStore,k8 as DatabaseChangeFeedDriver,IZ as DEFAULT_MCP_SCOPE,iZ as CronJob,U8 as ConnectionManager,v9 as CommandRegistry,uZ as CommandFailed,pZ as Command,T8 as ChangeFeedSubscription,z9 as ChangeFeedServiceProvider,V8 as ChangeFeedManager,C8 as ChangeFeedFullError,G9 as CacheServiceProvider,G8 as CacheManager,g1 as CONSENT_PAGE_HEADERS,K9 as BroadcastServiceProvider,E8 as BroadcastScope,y8 as BroadcastPayloadTooLargeError,A8 as BroadcastManager,k6 as BroadcastEvent,e0 as AzureBlobDriver,X9 as AuthServiceProvider,e as AuthManager,BZ as ApiRouteDispatcher,k4 as AcsDriver};
|
|
71
71
|
|
|
72
|
-
//# debugId=
|
|
72
|
+
//# debugId=F0ABDFE231B0FD6F64756E2164756E21
|