var Wt=Object.defineProperty;var a=(r,e)=>Wt(r,"name",{value:e,configurable:!0});import{request as Qt}from"node:https";import{URL as Zt}from"node:url";import{createGunzip as Xt,createBrotliDecompress as ei,createDeflate as ti}from"node:zlib";import{existsSync as Jt,readFileSync as Vt,writeFileSync as Ft}from"node:fs";var k;Jt(".data/youtube.data")&&(k=JSON.parse(Vt(".data/youtube.data","utf-8")),k.file=!0);function Qe(){let r="";if(k?.cookie){for(let[e,t]of Object.entries(k.cookie))r+=`${e}=${t};`;return r}}a(Qe,"getCookies");function jt(r,e){return k?.cookie?(r=r.trim(),e=e.trim(),Object.assign(k.cookie,{[r]:e}),!0):!1}a(jt,"setCookie");function Kt(){k.cookie&&k.file&&Ft(".data/youtube.data",JSON.stringify(k,void 0,4))}a(Kt,"uploadCookie");function Ze(r){let e=r.cookie,t={};e.split(";").forEach(i=>{let s=i.split("=");if(s.length<=1)return;let n=s.shift()?.trim(),o=s.join("=").trim();Object.assign(t,{[n]:o})}),k={cookie:t},k.file=!1}a(Ze,"setCookieToken");function Xe(r){k?.cookie&&(r.forEach(e=>{e.split(";").forEach(t=>{let i=t.split("=");if(i.length<=1)return;let s=i.shift()?.trim(),n=i.join("=").trim();jt(s,n)})}),Kt())}a(Xe,"cookieHeaders");var j=["Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.53","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.30","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 YaBrowser/19.10.3.281 Yowser/2.5 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36"];function et(r){j.push(...r)}a(et,"setUserAgent");function Ht(r,e){return r=Math.ceil(r),e=Math.floor(e),Math.floor(Math.random()*(e-r+1))+r}a(Ht,"getRandomInt");function tt(){let r=Ht(0,j.length-1);return j[r]}a(tt,"getRandomUserAgent");function w(r,e={method:"GET"}){return new Promise(async(t,i)=>{let s=await G(r,e).catch(n=>n);if(s instanceof Error){i(s);return}Number(s.statusCode)>=300&&Number(s.statusCode)<400&&(s=await w(s.headers.location,e)),t(s)})}a(w,"request_stream");function it(r,e={method:"GET"}){return new Promise(async(t,i)=>{let s=await G(r,e).catch(n=>n);if(s instanceof Error){i(s);return}if(Number(s.statusCode)>=300&&Number(s.statusCode)<400)s=await it(s.headers.location,e);else if(Number(s.statusCode)>400){i(new Error(`Got ${s.statusCode} from the request`));return}t(s)})}a(it,"internalRequest");function h(r,e={method:"GET"}){return new Promise(async(t,i)=>{let s=!1;if(e.cookies){let u=Qe();typeof u=="string"&&e.headers&&(Object.assign(e.headers,{cookie:u}),s=!0)}if(e.cookieJar){let u=[];for(let m of Object.entries(e.cookieJar))u.push(m.join("="));if(u.length!==0){e.headers||(e.headers={});let m=s?`; ${e.headers.cookie}`:"";Object.assign(e.headers,{cookie:`${u.join("; ")}${m}`})}}e.headers&&(e.headers={...e.headers,"accept-encoding":"gzip, deflate, br","user-agent":tt()});let n=await it(r,e).catch(u=>u);if(n instanceof Error){i(n);return}if(n.headers&&n.headers["set-cookie"]){if(e.cookieJar)for(let u of n.headers["set-cookie"]){let m=u.split(";")[0].trim().split("=");e.cookieJar[m.shift()]=m.join("=")}s&&Xe(n.headers["set-cookie"])}let o=[],l,c=n.headers["content-encoding"];c==="gzip"?l=Xt():c==="br"?l=ei():c==="deflate"&&(l=ti()),l?(n.pipe(l),l.setEncoding("utf-8"),l.on("data",u=>o.push(u)),l.on("end",()=>t(o.join("")))):(n.setEncoding("utf-8"),n.on("data",u=>o.push(u)),n.on("end",()=>t(o.join(""))))})}a(h,"request");function K(r){return new Promise(async(e,t)=>{let i=await G(r,{method:"HEAD"}).catch(n=>n);if(i instanceof Error){t(i);return}let s=Number(i.statusCode);if(s<300)e(r);else if(s<400){let n=await K(i.headers.location).catch(o=>o);if(n instanceof Error){t(n);return}e(n)}else t(new Error(`${i.statusCode}: ${i.statusMessage}, ${r}`))})}a(K,"request_resolve_redirect");function ae(r){return new Promise(async(e,t)=>{let i=await G(r,{method:"HEAD"}).catch(n=>n);if(i instanceof Error){t(i);return}let s=Number(i.statusCode);if(s<300)e(Number(i.headers["content-length"]));else if(s<400){let n=await K(i.headers.location).catch(l=>l);if(n instanceof Error){t(n);return}let o=await ae(n).catch(l=>l);if(o instanceof Error){t(o);return}e(o)}else t(new Error(`Failed to get content length with error: ${i.statusCode}, ${i.statusMessage}, ${r}`))})}a(ae,"request_content_length");function G(r,e={}){return new Promise((t,i)=>{let s=new Zt(r);e.method??="GET";let n={host:s.hostname,path:s.pathname+s.search,headers:e.headers??{},method:e.method},o=Qt(n,t);o.on("error",l=>{i(l)}),e.method==="POST"&&o.write(e.body),o.end()})}a(G,"https_getter");import{Readable as mt}from"node:stream";import{URL as ii,URLSearchParams as ri}from"node:url";var W="[a-zA-Z_\\$]\\w*",si="'[^'\\\\]*(:?\\\\[\\s\\S][^'\\\\]*)*'",ni='"[^"\\\\]*(:?\\\\[\\s\\S][^"\\\\]*)*"',st=`(?:${si}|${ni})`,O=`(?:${W}|${st})`,oi=`(?:\\.${W}|\\[${st}\\])`,rt=`(?:''|"")`,nt=":function\\(a\\)\\{(?:return )?a\\.reverse\\(\\)\\}",ot=":function\\(a,b\\)\\{return a\\.slice\\(b\\)\\}",at=":function\\(a,b\\)\\{a\\.splice\\(0,b\\)\\}",lt=":function\\(a,b\\)\\{var c=a\\[0\\];a\\[0\\]=a\\[b(?:%a\\.length)?\\];a\\[b(?:%a\\.length)?\\]=c(?:;return a)?\\}",ai=new RegExp(`var (${W})=\\{((?:(?:${O}${nt}|${O}${ot}|${O}${at}|${O}${lt}),?\\r?\\n?)+)\\};`),li=new RegExp(`${`function(?: ${W})?\\(a\\)\\{a=a\\.split\\(${rt}\\);\\s*((?:(?:a=)?${W}`}${oi}\\(a,\\d+\\);)+)return a\\.join\\(${rt}\\)\\}`),ui=new RegExp(`(?:^|,)(${O})${nt}`,"m"),ci=new RegExp(`(?:^|,)(${O})${ot}`,"m"),hi=new RegExp(`(?:^|,)(${O})${at}`,"m"),di=new RegExp(`(?:^|,)(${O})${lt}`,"m");function pi(r){let e=li.exec(r),t=ai.exec(r);if(!e||!t)return null;let i=t[1].replace(/\$/g,"\\$"),s=t[2].replace(/\$/g,"\\$"),n=e[1].replace(/\$/g,"\\$"),o=ui.exec(s),l=o&&o[1].replace(/\$/g,"\\$").replace(/\$|^'|^"|'$|"$/g,"");o=ci.exec(s);let c=o&&o[1].replace(/\$/g,"\\$").replace(/\$|^'|^"|'$|"$/g,"");o=hi.exec(s);let u=o&&o[1].replace(/\$/g,"\\$").replace(/\$|^'|^"|'$|"$/g,"");o=di.exec(s);let m=o&&o[1].replace(/\$/g,"\\$").replace(/\$|^'|^"|'$|"$/g,""),y=`(${[l,c,u,m].join("|")})`,f=`(?:a=)?${i}(?:\\.${y}|\\['${y}'\\]|\\["${y}"\\])\\(a,(\\d+)\\)`,b=new RegExp(f,"g"),I=[];for(;(o=b.exec(n))!==null;)switch(o[1]||o[2]||o[3]){case m:I.push(`sw${o[4]}`);break;case l:I.push("rv");break;case c:I.push(`sl${o[4]}`);break;case u:I.push(`sp${o[4]}`);break}return I}a(pi,"js_tokens");function mi(r,e){let t=e.split(""),i=r.length;for(let s=0;s{let n=s.signatureCipher||s.cipher;if(n){let o=Object.fromEntries(new ri(n));Object.assign(s,o),delete s.signatureCipher,delete s.cipher}if(i&&s.s){let o=mi(i,s.s);yi(s,o),delete s.s,delete s.sp}}),r}a(ut,"format_decipher");var le=class le{constructor(e={}){if(!e)throw new Error(`Cannot instantiate the ${this.constructor.name} class without data!`);this.type="channel",this.name=e.name||null,this.verified=!!e.verified||!1,this.artist=!!e.artist||!1,this.id=e.id||null,this.url=e.url||null,this.icons=e.icons||[{url:null,width:0,height:0}],this.subscribers=e.subscribers||null}iconURL(e={size:0}){if(typeof e.size!="number"||e.size<0)throw new Error("invalid icon size");if(!this.icons?.[0]?.url)return;let t=this.icons?.[0]?.url.split("=s")[1].split("-c")[0];return this.icons?.[0]?.url.replace(`=s${t}-c`,`=s${e.size}-c`)}toString(){return this.name||""}toJSON(){return{name:this.name,verified:this.verified,artist:this.artist,id:this.id,url:this.url,icons:this.icons,type:this.type,subscribers:this.subscribers}}};a(le,"YouTubeChannel");var S=le;var ue=class ue{constructor(e){this.url=e.url,this.width=e.width,this.height=e.height}toJSON(){return{url:this.url,width:this.width,height:this.height}}};a(ue,"YouTubeThumbnail");var N=ue;var ce=class ce{constructor(e){if(!e)throw new Error(`Can not initiate ${this.constructor.name} without data`);this.id=e.id||void 0,this.url=`https://www.youtube.com/watch?v=${this.id}`,this.type="video",this.title=e.title||void 0,this.description=e.description||void 0,this.durationRaw=e.duration_raw||"0:00",this.durationInSec=(e.duration<0?0:e.duration)||0,this.uploadedAt=e.uploadedAt||void 0,this.liveAt=e.liveAt||void 0,this.upcoming=e.upcoming,this.views=parseInt(e.views)||0;let t=[];for(let i of e.thumbnails)t.push(new N(i));this.thumbnails=t||[],this.channel=new S(e.channel)||{},this.likes=e.likes||0,this.live=!!e.live,this.private=!!e.private,this.tags=e.tags||[],this.discretionAdvised=e.discretionAdvised??void 0,this.music=e.music||[],this.chapters=e.chapters||[]}toString(){return this.url||""}toJSON(){return{id:this.id,url:this.url,title:this.title,description:this.description,durationInSec:this.durationInSec,durationRaw:this.durationRaw,uploadedAt:this.uploadedAt,thumbnail:this.thumbnails[this.thumbnails.length-1].toJSON()||this.thumbnails,channel:this.channel,views:this.views,tags:this.tags,likes:this.likes,live:this.live,private:this.private,discretionAdvised:this.discretionAdvised,music:this.music,chapters:this.chapters}}};a(ce,"YouTubeVideo");var E=ce;var bi="https://www.youtube.com/youtubei/v1/browse?key=",he=class he{constructor(e,t=!1){this._continuation={};if(!e)throw new Error(`Cannot instantiate the ${this.constructor.name} class without data!`);this.__count=0,this.fetched_videos=new Map,this.type="playlist",t?this.__patchSearch(e):this.__patch(e)}__patch(e){this.id=e.id||void 0,this.url=e.url||void 0,this.title=e.title||void 0,this.videoCount=e.videoCount||0,this.lastUpdate=e.lastUpdate||void 0,this.views=e.views||0,this.link=e.link||void 0,this.channel=new S(e.channel)||void 0,this.thumbnail=e.thumbnail?new N(e.thumbnail):void 0,this.videos=e.videos||[],this.__count++,this.fetched_videos.set(`${this.__count}`,this.videos),this._continuation.api=e.continuation?.api??void 0,this._continuation.token=e.continuation?.token??void 0,this._continuation.clientVersion=e.continuation?.clientVersion??""}__patchSearch(e){this.id=e.id||void 0,this.url=this.id?`https://www.youtube.com/playlist?list=${this.id}`:void 0,this.title=e.title||void 0,this.thumbnail=new N(e.thumbnail)||void 0,this.channel=e.channel||void 0,this.videos=[],this.videoCount=e.videos||0,this.link=void 0,this.lastUpdate=void 0,this.views=0}async next(e=1/0){if(!this._continuation||!this._continuation.token)return[];let t=await h(`${bi}${this._continuation.api}&prettyPrint=false`,{method:"POST",body:JSON.stringify({continuation:this._continuation.token,context:{client:{utcOffsetMinutes:0,gl:"US",hl:"en",clientName:"WEB",clientVersion:this._continuation.clientVersion},user:{},request:{}}})}),i=JSON.parse(t)?.onResponseReceivedActions[0]?.appendContinuationItemsAction?.continuationItems;if(!i)return[];let s=de(i,e);return this.fetched_videos.set(`${this.__count}`,s),this._continuation.token=H(i),s}async fetch(e=1/0){if(!this._continuation.token)return this;for(e<1&&(e=1/0);typeof this._continuation.token=="string"&&this._continuation.token.length;){this.__count++;let i=await this.next();if(e-=i.length,e<=0||!i.length)break}return this}page(e){if(!e)throw new Error("Page number is not provided");if(!this.fetched_videos.has(`${e}`))throw new Error("Given Page number is invalid");return this.fetched_videos.get(`${e}`)}get total_pages(){return this.fetched_videos.size}get total_videos(){let e=this.total_pages;return(e-1)*100+this.fetched_videos.get(`${e}`).length}async all_videos(){await this.fetch();let e=[];for(let t of this.fetched_videos.values())e.push(...t);return e}toJSON(){return{id:this.id,title:this.title,thumbnail:this.thumbnail?.toJSON()||this.thumbnail,channel:this.channel,url:this.url,videos:this.videos}}};a(he,"YouTubePlayList");var D=he;import{URL as gi,URLSearchParams as wi}from"node:url";var Q=/^[a-zA-Z\d_-]{11,12}$/,_i=/^(PL|UU|LL|RD|OL)[a-zA-Z\d_-]{10,}$/,Z="AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8",ht=/^((?:https?:)?\/\/)?(?:(?:www|m|music)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|shorts\/|embed\/|live\/|v\/)?)([\w\-]+)(\S+)?$/,ki=/^((?:https?:)?\/\/)?(?:(?:www|m|music)\.)?((?:youtube\.com|youtu.be))\/(?:(playlist|watch))?(.*)?((\?|\&)list=)(PL|UU|LL|RD|OL)[a-zA-Z\d_-]{10,}(&.*)?$/;function Y(r){let e=r.trim();if(e.indexOf("list=")===-1)if(e.startsWith("https"))if(e.match(ht)){let t;return e.includes("youtu.be/")?t=e.split("youtu.be/")[1].split(/(\?|\/|&)/)[0]:e.includes("youtube.com/embed/")?t=e.split("youtube.com/embed/")[1].split(/(\?|\/|&)/)[0]:e.includes("youtube.com/shorts/")?t=e.split("youtube.com/shorts/")[1].split(/(\?|\/|&)/)[0]:t=e.split("watch?v=")[1]?.split(/(\?|\/|&)/)[0],t?.match(Q)?"video":!1}else return!1;else return e.match(Q)?"video":e.match(_i)?"playlist":"search";else return e.match(ki)?"playlist":Y(e.replace(/(\?|\&)list=[^&]*/,""))}a(Y,"yt_validate");function pe(r){if(r.startsWith("https://")&&r.match(ht)){let e;if(r.includes("youtu.be/")?e=r.split("youtu.be/")[1].split(/(\?|\/|&)/)[0]:r.includes("youtube.com/embed/")?e=r.split("youtube.com/embed/")[1].split(/(\?|\/|&)/)[0]:r.includes("youtube.com/shorts/")?e=r.split("youtube.com/shorts/")[1].split(/(\?|\/|&)/)[0]:r.includes("youtube.com/live/")?e=r.split("youtube.com/live/")[1].split(/(\?|\/|&)/)[0]:e=(r.split("watch?v=")[1]??r.split("&v=")[1]).split(/(\?|\/|&)/)[0],e.match(Q))return e}else if(r.match(Q))return r;return!1}a(pe,"extractVideoId");function me(r){let e=Y(r);if(!e||e==="search")throw new Error("This is not a YouTube url or videoId or PlaylistID");let t=r.trim();if(t.startsWith("https"))if(t.indexOf("list=")===-1){let i=pe(t);if(!i)throw new Error("This is not a YouTube url or videoId or PlaylistID");return i}else return t.split("list=")[1].split("&")[0];else return t}a(me,"extractID");async function X(r,e={}){if(typeof r!="string")throw new Error("url parameter is not a URL string or a string of HTML");let t=r.trim(),i,s={};if(e.htmldata)i=t;else{let p=pe(t);if(!p)throw new Error("This is not a YouTube Watch URL");let g=`https://www.youtube.com/watch?v=${p}&has_verified=1`;i=await h(g,{headers:{"accept-language":e.language||"en-US;q=0.9"},cookies:!0,cookieJar:s})}if(i.indexOf("Our systems have detected unusual traffic from your computer network.")!==-1)throw new Error("Captcha page: YouTube has detected that you are a bot!");let n=i.split("var ytInitialPlayerResponse = ")?.[1]?.split(";")[0].split(/(?<=}}});\s*(var|const|let)\s/)[0];if(!n)throw new Error("Initial Player Response Data is undefined.");let o=i.split("var ytInitialData = ")?.[1]?.split(";")[0].split(/;\s*(var|const|let)\s/)[0];if(!o)throw new Error("Initial Response Data is undefined.");let l=JSON.parse(n),c=JSON.parse(o),u=l.videoDetails,m=!1,y=!1;if(l.playabilityStatus.status!=="OK")if(l.playabilityStatus.status==="CONTENT_CHECK_REQUIRED"){if(e.htmldata)throw new Error(`Accepting the viewer discretion is not supported when using htmldata, video: ${u.videoId}`);m=!0;let p=c.topbar.desktopTopbarRenderer.interstitial?.consentBumpV2Renderer.agreeButton.buttonRenderer.command.saveConsentAction;p&&Object.assign(s,{VISITOR_INFO1_LIVE:p.visitorCookie,CONSENT:p.consentCookie});let g=await dt(u.videoId,s,i,!0);l.streamingData=g.streamingData,c.contents.twoColumnWatchNextResults.secondaryResults=g.relatedVideos}else if(l.playabilityStatus.status==="LIVE_STREAM_OFFLINE")y=!0;else throw new Error(`While getting info from url ${l.playabilityStatus.errorScreen.playerErrorMessageRenderer?.reason.simpleText??l.playabilityStatus.errorScreen.playerKavRenderer?.reason.simpleText??l.playabilityStatus.reason}`);let f=c.contents.twoColumnWatchNextResults.results?.results?.contents[1]?.videoSecondaryInfoRenderer?.owner?.videoOwnerRenderer,b=f?.badges?.[0]?.metadataBadgeRenderer?.style?.toLowerCase(),I=`https://www.youtube.com${i.split('"jsUrl":"')[1].split('"')[0]}`,V=[];c.contents.twoColumnWatchNextResults.secondaryResults.secondaryResults.results.forEach(p=>{p.compactVideoRenderer&&V.push(`https://www.youtube.com/watch?v=${p.compactVideoRenderer.videoId}`),p.itemSectionRenderer?.contents&&p.itemSectionRenderer.contents.forEach(g=>{g.compactVideoRenderer&&V.push(`https://www.youtube.com/watch?v=${g.compactVideoRenderer.videoId}`)})});let F=l.microformat.playerMicroformatRenderer,We=c.engagementPanels.find(p=>p?.engagementPanelSectionListRenderer?.panelIdentifier=="engagement-panel-structured-description")?.engagementPanelSectionListRenderer.content.structuredDescriptionContentRenderer.items.find(p=>p.videoDescriptionMusicSectionRenderer)?.videoDescriptionMusicSectionRenderer.carouselLockups,Je=[];We&&We.forEach(p=>{if(!p.carouselLockupRenderer)return;let g=p.carouselLockupRenderer,qt=g.videoLockup?.compactVideoRenderer.title.simpleText??g.videoLockup?.compactVideoRenderer.title.runs?.find(v=>v.text)?.text,Ut=g.infoRows?.map(v=>[v.infoRowRenderer.title.simpleText.toLowerCase(),(v.infoRowRenderer.expandedMetadata??v.infoRowRenderer.defaultMetadata)?.runs?.map(Yt=>Yt.text).join("")??v.infoRowRenderer.defaultMetadata?.simpleText??v.infoRowRenderer.expandedMetadata?.simpleText??""]),Bt=Object.fromEntries(Ut??{}),He=g.videoLockup?.compactVideoRenderer.navigationEndpoint?.watchEndpoint.videoId??g.infoRows?.find(v=>v.infoRowRenderer.title.simpleText.toLowerCase()=="song")?.infoRowRenderer.defaultMetadata.runs?.find(v=>v.navigationEndpoint)?.navigationEndpoint.watchEndpoint?.videoId;Je.push({song:qt,url:He?`https://www.youtube.com/watch?v=${He}`:null,...Bt})});let Ve=c.playerOverlays.playerOverlayRenderer.decoratedPlayerBarRenderer?.decoratedPlayerBarRenderer.playerBar?.multiMarkersPlayerBarRenderer.markersMap?.find(p=>p.key==="DESCRIPTION_CHAPTERS")?.value?.chapters,Fe=[];if(Ve)for(let{chapterRenderer:p}of Ve)Fe.push({title:p.title.simpleText,timestamp:ct(p.timeRangeStartMillis/1e3),seconds:p.timeRangeStartMillis/1e3,thumbnails:p.thumbnail.thumbnails});let oe;if(y)if(F.liveBroadcastDetails.startTimestamp)oe=new Date(F.liveBroadcastDetails.startTimestamp);else{let p=l.playabilityStatus.liveStreamability.liveStreamabilityRenderer.offlineSlate.liveStreamOfflineSlateRenderer.scheduledStartTime;oe=new Date(parseInt(p)*1e3)}let je=c.contents.twoColumnWatchNextResults.results.results.contents.find(p=>p.videoPrimaryInfoRenderer)?.videoPrimaryInfoRenderer.videoActions.menuRenderer.topLevelButtons?.find(p=>p.toggleButtonRenderer?.defaultIcon.iconType==="LIKE"||p.segmentedLikeDislikeButtonRenderer?.likeButton.toggleButtonRenderer?.defaultIcon.iconType==="LIKE"),Ke=new E({id:u.videoId,title:u.title,description:u.shortDescription,duration:Number(u.lengthSeconds),duration_raw:ct(u.lengthSeconds),uploadedAt:F.publishDate,liveAt:F.liveBroadcastDetails?.startTimestamp,upcoming:oe,thumbnails:u.thumbnail.thumbnails,channel:{name:u.author,id:u.channelId,url:`https://www.youtube.com/channel/${u.channelId}`,verified:!!b?.includes("verified"),artist:!!b?.includes("artist"),icons:f?.thumbnail?.thumbnails||void 0},views:u.viewCount,tags:u.keywords,likes:parseInt(je?.toggleButtonRenderer?.defaultText.accessibility?.accessibilityData.label.replace(/\D+/g,"")??je?.segmentedLikeDislikeButtonRenderer?.likeButton.toggleButtonRenderer?.defaultText.accessibility?.accessibilityData.label.replace(/\D+/g,"")??0),live:u.isLiveContent,private:u.isPrivate,discretionAdvised:m,music:Je,chapters:Fe}),Ge=[];return y||(Ge=await pt(u.videoId,s,i)),{LiveStreamData:{isLive:Ke.live,dashManifestUrl:l.streamingData?.dashManifestUrl??null,hlsManifestUrl:l.streamingData?.hlsManifestUrl??null},html5player:I,format:Ge,video_details:Ke,related_videos:V}}a(X,"video_basic_info");async function A(r,e={}){if(typeof r!="string")throw new Error("url parameter is not a URL string or a string of HTML");let t,i={};if(e.htmldata)t=r;else{let f=pe(r);if(!f)throw new Error("This is not a YouTube Watch URL");let b=`https://www.youtube.com/watch?v=${f}&has_verified=1`;t=await h(b,{headers:{"accept-language":"en-US,en;q=0.9"},cookies:!0,cookieJar:i})}if(t.indexOf("Our systems have detected unusual traffic from your computer network.")!==-1)throw new Error("Captcha page: YouTube has detected that you are a bot!");let s=t.split("var ytInitialPlayerResponse = ")?.[1]?.split(";")[0].split(/(?<=}}});\s*(var|const|let)\s/)[0];if(!s)throw new Error("Initial Player Response Data is undefined.");let n=JSON.parse(s),o=!1;if(n.playabilityStatus.status!=="OK")if(n.playabilityStatus.status==="CONTENT_CHECK_REQUIRED"){if(e.htmldata)throw new Error(`Accepting the viewer discretion is not supported when using htmldata, video: ${n.videoDetails.videoId}`);let f=t.split("var ytInitialData = ")?.[1]?.split(";")[0].split(/;\s*(var|const|let)\s/)[0];if(!f)throw new Error("Initial Response Data is undefined.");let b=JSON.parse(f).topbar.desktopTopbarRenderer.interstitial?.consentBumpV2Renderer.agreeButton.buttonRenderer.command.saveConsentAction;b&&Object.assign(i,{VISITOR_INFO1_LIVE:b.visitorCookie,CONSENT:b.consentCookie});let I=await dt(n.videoDetails.videoId,i,t,!1);n.streamingData=I.streamingData}else if(n.playabilityStatus.status==="LIVE_STREAM_OFFLINE")o=!0;else throw new Error(`While getting info from url ${n.playabilityStatus.errorScreen.playerErrorMessageRenderer?.reason.simpleText??n.playabilityStatus.errorScreen.playerKavRenderer?.reason.simpleText??n.playabilityStatus.reason}`);let l=`https://www.youtube.com${t.split('"jsUrl":"')[1].split('"')[0]}`,c=Number(n.videoDetails.lengthSeconds),u={url:`https://www.youtube.com/watch?v=${n.videoDetails.videoId}`,durationInSec:(c<0?0:c)||0},m=[];o||(m=await pt(n.videoDetails.videoId,i,t));let y={isLive:n.videoDetails.isLiveContent,dashManifestUrl:n.streamingData?.dashManifestUrl??null,hlsManifestUrl:n.streamingData?.hlsManifestUrl??null};return await J({LiveStreamData:y,html5player:l,format:m,video_details:u},!0)}a(A,"video_stream_info");function ct(r){let e=Number(r),t=Math.floor(e/3600),i=Math.floor(e%3600/60),s=Math.floor(e%3600%60),n=t>0?(t<10?`0${t}`:t)+":":"",o=i>0?(i<10?`0${i}`:i)+":":"00:",l=s>0?s<10?`0${s}`:s:"00";return n+o+l}a(ct,"parseSeconds");async function fe(r,e={}){let t=await X(r.trim(),e);return await J(t)}a(fe,"video_info");async function J(r,e=!1){return r.LiveStreamData.isLive===!0&&r.LiveStreamData.dashManifestUrl!==null&&r.video_details.durationInSec===0||r.format.length>0&&(r.format[0].signatureCipher||r.format[0].cipher)&&(e&&(r.format=z(r.format)),r.format=await ut(r.format,r.html5player)),r}a(J,"decipher_info");async function ye(r,e={}){if(!r||typeof r!="string")throw new Error(`Expected playlist url, received ${typeof r}!`);let t=r.trim();if(t.startsWith("https")||(t=`https://www.youtube.com/playlist?list=${t}`),t.indexOf("list=")===-1)throw new Error("This is not a Playlist URL");if(t.includes("music.youtube.com")){let n=new gi(t);n.hostname="www.youtube.com",t=n.toString()}let i=await h(t,{headers:{"accept-language":e.language||"en-US;q=0.9"}});if(i.indexOf("Our systems have detected unusual traffic from your computer network.")!==-1)throw new Error("Captcha page: YouTube has detected that you are a bot!");let s=JSON.parse(i.split("var ytInitialData = ")[1].split(";")[0].split(/;\s*(var|const|let)\s/)[0]);if(s.alerts)if(s.alerts[0].alertWithButtonRenderer?.type==="INFO"){if(!e.incomplete)throw new Error(`While parsing playlist url ${s.alerts[0].alertWithButtonRenderer.text.simpleText}`)}else throw s.alerts[0].alertRenderer?.type==="ERROR"?new Error(`While parsing playlist url ${s.alerts[0].alertRenderer.text.runs[0].text}`):new Error(`While parsing playlist url Unknown Playlist Error`);return s.currentVideoEndpoint?vi(s,i,t):Si(s,i)}a(ye,"playlist_info");function de(r,e=1/0){let t=[];for(let i=0;iObject.keys(e)[0]==="continuationItemRenderer")?.continuationItemRenderer.continuationEndpoint?.continuationCommand?.token}a(H,"getContinuationToken");async function dt(r,e,t,i){let s=t.split('INNERTUBE_API_KEY":"')[1]?.split('"')[0]??t.split('innertubeApiKey":"')[1]?.split('"')[0]??Z,n=t.split('"XSRF_TOKEN":"')[1]?.split('"')[0].replaceAll("\\u003d","=")??t.split('"xsrf_token":"')[1]?.split('"')[0].replaceAll("\\u003d","=");if(!n)throw new Error(`Unable to extract XSRF_TOKEN to accept the viewer discretion popup for video: ${r}.`);let o=await h(`https://www.youtube.com/youtubei/v1/verify_age?key=${s}&prettyPrint=false`,{method:"POST",body:JSON.stringify({context:{client:{utcOffsetMinutes:0,gl:"US",hl:"en",clientName:"WEB",clientVersion:t.split('"INNERTUBE_CONTEXT_CLIENT_VERSION":"')[1]?.split('"')[0]??t.split('"innertube_context_client_version":"')[1]?.split('"')[0]??""},user:{},request:{}},nextEndpoint:{urlEndpoint:{url:`/watch?v=${r}&has_verified=1`}},setControvercy:!0}),cookies:!0,cookieJar:e}),l=JSON.parse(o).actions[0].navigateAction.endpoint,c=await h(`https://www.youtube.com/${l.urlEndpoint.url}&pbj=1`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new wi([["command",JSON.stringify(l)],["session_token",n]]).toString(),cookies:!0,cookieJar:e});if(c.includes("

Something went wrong

"))throw new Error(`Unable to accept the viewer discretion popup for video: ${r}`);let u=JSON.parse(c);if(u[2].playerResponse.playabilityStatus.status!=="OK")throw new Error(`While getting info from url after trying to accept the discretion popup for video ${r} ${u[2].playerResponse.playabilityStatus.errorScreen.playerErrorMessageRenderer?.reason.simpleText??u[2].playerResponse.playabilityStatus.errorScreen.playerKavRenderer?.reason.simpleText}`);let m=u[2].playerResponse.streamingData;return i?{streamingData:m,relatedVideos:u[3].response.contents.twoColumnWatchNextResults.secondaryResults}:{streamingData:m}}a(dt,"acceptViewerDiscretion");async function pt(r,e,t){let i=t.split('INNERTUBE_API_KEY":"')[1]?.split('"')[0]??t.split('innertubeApiKey":"')[1]?.split('"')[0]??Z,s=await h(`https://www.youtube.com/youtubei/v1/player?key=${i}&prettyPrint=false`,{method:"POST",body:JSON.stringify({context:{client:{clientName:"IOS",clientVersion:"19.09.3",deviceModel:"iPhone16,1",userAgent:"com.google.ios.youtube/19.09.3 (iPhone; CPU iPhone OS 17_5 like Mac OS X)",hl:"en",timeZone:"UTC",utcOffsetMinutes:0}},videoId:r,playbackContext:{contentPlaybackContext:{html5Preference:"HTML5_PREF_WANTS"}},contentCheckOk:!0,racyCheckOk:!0}),cookies:!0,cookieJar:e});return JSON.parse(s).streamingData.adaptiveFormats}a(pt,"getIosFormats");function vi(r,e,t){let i=r.contents.twoColumnWatchNextResults.playlist?.playlist;if(!i)throw new Error("Watch playlist unavailable due to YouTube layout changes.");let s=Ei(i.contents),n=e.split('INNERTUBE_API_KEY":"')[1]?.split('"')[0]??e.split('innertubeApiKey":"')[1]?.split('"')[0]??Z,o=i.totalVideos,l=i.shortBylineText?.runs?.[0],c=i.badges?.[0]?.metadataBadgeRenderer?.style.toLowerCase();return new D({continuation:{api:n,token:H(i.contents),clientVersion:e.split('"INNERTUBE_CONTEXT_CLIENT_VERSION":"')[1]?.split('"')[0]??e.split('"innertube_context_client_version":"')[1]?.split('"')[0]??""},id:i.playlistId||"",title:i.title||"",videoCount:parseInt(o)||0,videos:s,url:t,channel:{id:l?.navigationEndpoint?.browseEndpoint?.browseId||null,name:l?.text||null,url:`https://www.youtube.com${l?.navigationEndpoint?.browseEndpoint?.canonicalBaseUrl||l?.navigationEndpoint?.commandMetadata?.webCommandMetadata?.url}`,verified:!!c?.includes("verified"),artist:!!c?.includes("artist")}})}a(vi,"getWatchPlaylist");function Si(r,e){let t=r.contents.twoColumnBrowseResultsRenderer.tabs[0].tabRenderer.content.sectionListRenderer.contents[0].itemSectionRenderer.contents[0].playlistVideoListRenderer.contents,i=r.sidebar.playlistSidebarRenderer.items,s=e.split('INNERTUBE_API_KEY":"')[1]?.split('"')[0]??e.split('innertubeApiKey":"')[1]?.split('"')[0]??Z,n=de(t,100),o=i[0].playlistSidebarPrimaryInfoRenderer;if(!o.title.runs||!o.title.runs.length)throw new Error("Failed to Parse Playlist info.");let l=i[1]?.playlistSidebarSecondaryInfoRenderer.videoOwner,c=o.stats.length===3?o.stats[1].simpleText.replace(/\D/g,""):0,u=o.stats.find(f=>"runs"in f&&f.runs.find(b=>b.text.toLowerCase().includes("last update")))?.runs.pop()?.text??null,m=o.stats[0].runs[0].text.replace(/\D/g,"")||0;return new D({continuation:{api:s,token:H(t),clientVersion:e.split('"INNERTUBE_CONTEXT_CLIENT_VERSION":"')[1]?.split('"')[0]??e.split('"innertube_context_client_version":"')[1]?.split('"')[0]??""},id:o.title.runs[0].navigationEndpoint.watchEndpoint.playlistId,title:o.title.runs[0].text,videoCount:parseInt(m)||0,lastUpdate:u,views:parseInt(c)||0,videos:n,url:`https://www.youtube.com/playlist?list=${o.title.runs[0].navigationEndpoint.watchEndpoint.playlistId}`,link:`https://www.youtube.com${o.title.runs[0].navigationEndpoint.commandMetadata.webCommandMetadata.url}`,channel:l?{name:l.videoOwnerRenderer.title.runs[0].text,id:l.videoOwnerRenderer.title.runs[0].navigationEndpoint.browseEndpoint.browseId,url:`https://www.youtube.com${l.videoOwnerRenderer.navigationEndpoint.commandMetadata.webCommandMetadata.url||l.videoOwnerRenderer.navigationEndpoint.browseEndpoint.canonicalBaseUrl}`,icons:l.videoOwnerRenderer.thumbnail.thumbnails??[]}:{},thumbnail:o.thumbnailRenderer.playlistVideoThumbnailRenderer?.thumbnail.thumbnails.length?o.thumbnailRenderer.playlistVideoThumbnailRenderer.thumbnail.thumbnails[o.thumbnailRenderer.playlistVideoThumbnailRenderer.thumbnail.thumbnails.length-1]:null})}a(Si,"getNormalPlaylist");function Ei(r,e=1/0){let t=[];for(let i=0;i{this.dash_updater(),this.dash_timer.reuse()},1800),this.stream.on("close",()=>{this.cleanup()}),this.initialize_dash()}cleanup(){this.normal_timer?.destroy(),this.dash_timer.destroy(),this.request?.destroy(),this.video_url="",this.request=void 0,this.dash_url="",this.base_url="",this.interval=0}async dash_updater(){let e=await A(this.video_url);return e.LiveStreamData.dashManifestUrl&&(this.dash_url=e.LiveStreamData.dashManifestUrl),this.initialize_dash()}async initialize_dash(){let t=(await h(this.dash_url)).split('")[0].split("");if(t[t.length-1]===""&&t.pop(),this.base_url=t[t.length-1].split("")[1].split("")[0],await w(`https://${new xi(this.base_url).host}/generate_204`),this.sequence===0){let i=t[t.length-1].split("")[1].split("")[0].replaceAll('');i[i.length-1]===""&&i.pop(),i.length>this.precache&&i.splice(0,i.length-this.precache),this.sequence=Number(i[0].split("sq/")[1].split("/")[0]),this.first_data(i.length)}}async first_data(e){for(let t=1;t<=e;t++)await new Promise(async i=>{let s=await w(this.base_url+"sq/"+this.sequence).catch(n=>n);if(s instanceof Error){this.stream.emit("error",s);return}this.request=s,s.on("data",n=>{this.stream.push(n)}),s.on("end",()=>{this.sequence++,i("")}),s.once("error",n=>{this.stream.emit("error",n)})});this.normal_timer=new C(()=>{this.loop(),this.normal_timer?.reuse()},this.interval)}loop(){return new Promise(async e=>{let t=await w(this.base_url+"sq/"+this.sequence).catch(i=>i);if(t instanceof Error){this.stream.emit("error",t);return}this.request=t,t.on("data",i=>{this.stream.push(i)}),t.on("end",()=>{this.sequence++,e("")}),t.once("error",i=>{this.stream.emit("error",i)})})}pause(){}resume(){}};a(be,"LiveStream");var ee=be,ge=class ge{constructor(e,t,i,s,n,o){this.stream=new mt({highWaterMark:5*1e3*1e3,read(){}}),this.url=e,this.quality=o.quality,this.type=t,this.bytes_count=0,this.video_url=n,this.per_sec_bytes=Math.ceil(s/i),this.content_length=s,this.request=null,this.timer=new C(()=>{this.timer.reuse(),this.loop()},265),this.stream.on("close",()=>{this.timer.destroy(),this.cleanup()}),this.loop()}async retry(){let e=await A(this.video_url),t=z(e.format);this.url=t[this.quality].url}cleanup(){this.request?.destroy(),this.request=null,this.url=""}async loop(){if(this.stream.destroyed){this.timer.destroy(),this.cleanup();return}let e=this.bytes_count+this.per_sec_bytes*300,t=await w(this.url,{headers:{range:`bytes=${this.bytes_count}-${e>=this.content_length?"":e}`}}).catch(i=>i);if(t instanceof Error){this.stream.emit("error",t),this.bytes_count=0,this.per_sec_bytes=0,this.cleanup();return}if(Number(t.statusCode)>=400){this.cleanup(),await this.retry(),this.timer.reuse(),this.loop();return}this.request=t,t.on("data",i=>{this.stream.push(i)}),t.once("error",async()=>{this.cleanup(),await this.retry(),this.timer.reuse(),this.loop()}),t.on("data",i=>{this.bytes_count+=i.length}),t.on("end",()=>{e>=this.content_length&&(this.timer.destroy(),this.stream.push(null),this.cleanup())})}pause(){this.timer.pause()}resume(){this.timer.resume()}};a(ge,"Stream");var te=ge,we=class we{constructor(e,t){this.callback=e,this.time_total=t,this.time_left=t,this.paused=!1,this.destroyed=!1,this.time_start=process.hrtime()[0],this.timer=setTimeout(this.callback,this.time_total*1e3)}pause(){return!this.paused&&!this.destroyed?(this.paused=!0,clearTimeout(this.timer),this.time_left=this.time_left-(process.hrtime()[0]-this.time_start),!0):!1}resume(){return this.paused&&!this.destroyed?(this.paused=!1,this.time_start=process.hrtime()[0],this.timer=setTimeout(this.callback,this.time_left*1e3),!0):!1}reuse(){return this.destroyed?!1:(clearTimeout(this.timer),this.time_left=this.time_total,this.paused=!1,this.time_start=process.hrtime()[0],this.timer=setTimeout(this.callback,this.time_total*1e3),!0)}destroy(){clearTimeout(this.timer),this.destroyed=!0,this.callback=()=>{},this.time_total=0,this.time_left=0,this.paused=!1,this.time_start=0}};a(we,"Timer");var C=we;import{WebmElements as ft,WebmHeader as Ii}from"play-audio";import{Duplex as Di}from"node:stream";var Ri=Object.keys(ft),ke=class ke extends Di{constructor(e,t){super(t),this.state="READING_HEAD",this.cursor=0,this.header=new Ii,this.headfound=!1,this.headerparsed=!1,this.seekfound=!1,this.data_length=0,this.data_size=0,this.offset=0,this.sec=e,this.time=Math.floor(e/10)*10}get vint_length(){let e=0;for(;e<8&&!(1<<7-e&this.chunk[this.cursor]);e++);return++e}vint_value(){if(!this.chunk)return!1;let e=this.vint_length;if(this.chunk.lengththis.cursor;){let e=this.cursor,t=this.vint_length;if(this.chunk.length2&&this.time===this.header.segment.cues.at(-2).time/1e3&&this.emit("headComplete"),i.type===0){this.cursor+=this.data_size;continue}if(this.chunk.lengththis.cursor;){let e=this.cursor,t=this.vint_length;if(this.chunk.lengththis.chunk.length)continue;let t=this.chunk.slice(this.cursor+this.data_size,this.cursor+this.data_size+this.data_length),i=this.header.segment.tracks[this.header.audioTrack];if(!i||i.trackType!==2)return new Error("No audio Track in this webm file.");if((t[0]&15)===i.trackNumber)this.cursor+=this.data_size+this.data_length,this.push(t.slice(4)),e=!0;else continue}return e?(this.seekfound=!0,this.readTag()):new Error("Failed to find nearest correct simple Block.")}parseEbmlID(e){return Ri.includes(e)?ft[e]:!1}_destroy(e,t){this.cleanup(),t(e)}_final(e){this.cleanup(),e()}};a(ke,"WebmSeeker");var ie=ke;var ve=class ve{constructor(e,t,i,s,n,o,l){this.stream=new ie(l.seek,{highWaterMark:5*1e3*1e3,readableObjectMode:!0}),this.url=e,this.quality=l.quality,this.type="opus",this.bytes_count=0,this.video_url=o,this.per_sec_bytes=Math.ceil(n?n/8:s/t),this.header_length=i,this.content_length=s,this.request=null,this.timer=new C(()=>{this.timer.reuse(),this.loop()},265),this.stream.on("close",()=>{this.timer.destroy(),this.cleanup()}),this.seek()}async seek(){let e=await new Promise(async(i,s)=>{if(this.stream.headerparsed)i("");else{let n=await w(this.url,{headers:{range:`bytes=0-${this.header_length}`}}).catch(o=>o);if(n instanceof Error){s(n);return}if(Number(n.statusCode)>=400){s(400);return}this.request=n,n.pipe(this.stream,{end:!1}),n.once("end",()=>{this.stream.state="READING_DATA",i("")}),this.stream.once("headComplete",()=>{n.unpipe(this.stream),n.destroy(),this.stream.state="READING_DATA",i("")})}}).catch(i=>i);if(e instanceof Error){this.stream.emit("error",e),this.bytes_count=0,this.per_sec_bytes=0,this.cleanup();return}else if(e===400)return await this.retry(),this.timer.reuse(),this.seek();let t=this.stream.seek(this.content_length);if(t instanceof Error){this.stream.emit("error",t),this.bytes_count=0,this.per_sec_bytes=0,this.cleanup();return}this.stream.seekfound=!1,this.bytes_count=t,this.timer.reuse(),this.loop()}async retry(){let e=await A(this.video_url),t=z(e.format);this.url=t[this.quality].url}cleanup(){this.request?.destroy(),this.request=null,this.url=""}async loop(){if(this.stream.destroyed){this.timer.destroy(),this.cleanup();return}let e=this.bytes_count+this.per_sec_bytes*300,t=await w(this.url,{headers:{range:`bytes=${this.bytes_count}-${e>=this.content_length?"":e}`}}).catch(i=>i);if(t instanceof Error){this.stream.emit("error",t),this.bytes_count=0,this.per_sec_bytes=0,this.cleanup();return}if(Number(t.statusCode)>=400){this.cleanup(),await this.retry(),this.timer.reuse(),this.loop();return}this.request=t,t.pipe(this.stream,{end:!1}),t.once("error",async()=>{this.cleanup(),await this.retry(),this.timer.reuse(),this.loop()}),t.on("data",i=>{this.bytes_count+=i.length}),t.on("end",()=>{e>=this.content_length&&(this.timer.destroy(),this.stream.end(),this.cleanup())})}pause(){this.timer.pause()}resume(){this.timer.resume()}};a(ve,"SeekStream");var re=ve;import{URL as Ci}from"node:url";function z(r){let e=[];return r.forEach(t=>{let i=t.mimeType;i.startsWith("audio")&&(t.codec=i.split('codecs="')[1].split('"')[0],t.container=i.split("audio/")[1].split(";")[0],e.push(t))}),e}a(z,"parseAudioFormats");async function se(r,e={}){let t=await A(r,{htmldata:e.htmldata,language:e.language});return await ne(t,e)}a(se,"stream");async function ne(r,e={}){if(r.format.length===0)throw new Error("Upcoming and premiere videos that are not currently live cannot be streamed.");if(e.quality&&!Number.isInteger(e.quality))throw new Error("Quality must be set to an integer.");let t=[];if(r.LiveStreamData.isLive===!0&&r.LiveStreamData.dashManifestUrl!==null&&r.video_details.durationInSec===0)return new ee(r.LiveStreamData.dashManifestUrl,r.format[r.format.length-1].targetDurationSec,r.video_details.url,e.precache);let i=z(r.format);typeof e.quality!="number"?e.quality=i.length-1:e.quality<=0?e.quality=0:e.quality>=i.length&&(e.quality=i.length-1),i.length!==0?t.push(i[e.quality]):t.push(r.format[r.format.length-1]);let s=t[0].codec==="opus"&&t[0].container==="webm"?"webm/opus":"arbitrary";if(await w(`https://${new Ci(t[0].url).host}/generate_204`),s==="webm/opus")if(e.discordPlayerCompatibility){if(e.seek)throw new Error("Can not seek with discordPlayerCompatibility set to true.")}else{if(e.seek??=0,e.seek>=r.video_details.durationInSec||e.seek<0)throw new Error(`Seeking beyond limit. [ 0 - ${r.video_details.durationInSec-1}]`);return new re(t[0].url,r.video_details.durationInSec,t[0].indexRange.end,Number(t[0].contentLength),Number(t[0].bitrate),r.video_details.url,e)}let n;return t[0].contentLength?n=Number(t[0].contentLength):n=await ae(t[0].url),new te(t[0].url,s,r.video_details.durationInSec,n,r.video_details.url,e)}a(ne,"stream_from_info");var Oi=["-oaymwEpCOADEI4CSFryq4qpAxsIARUAAAAAGAElAADIQj0AgKJDeAHtAZmZGUI=","-oaymwEiCOADEI4CSFXyq4qpAxQIARUAAIhCGAFwAcABBu0BmZkZQg==","-oaymwEiCOgCEMoBSFXyq4qpAxQIARUAAIhCGAFwAcABBu0BZmbmQQ==","-oaymwEiCNAFEJQDSFXyq4qpAxQIARUAAIhCGAFwAcABBu0BZmZmQg==","-oaymwEdCNAFEJQDSFryq4qpAw8IARUAAIhCGAHtAWZmZkI=","-oaymwEdCNACELwBSFryq4qpAw8IARUAAIhCGAHtAT0K10E="];function bt(r,e){if(!r)throw new Error("Can't parse Search result without data");e?e.type||(e.type="video"):e={type:"video",limit:0};let t=typeof e.limit=="number"&&e.limit>0;e.unblurNSFWThumbnails??=!1;let i=r.split("var ytInitialData = ")?.[1]?.split(";")[0].split(/;\s*(var|const|let)\s/)[0],s=JSON.parse(i),n=[],o=s.contents.twoColumnSearchResultsRenderer.primaryContents.sectionListRenderer.contents.flatMap(l=>l.itemSectionRenderer?.contents);for(let l of o){if(t&&n.length===e.limit)break;if(!(!l||!l.videoRenderer&&!l.channelRenderer&&!l.playlistRenderer))switch(e.type){case"video":{let c=Ni(l);c&&(e.unblurNSFWThumbnails&&c.thumbnails.forEach(yt),n.push(c));break}case"channel":{let c=Pi(l);c&&n.push(c);break}case"playlist":{let c=Ai(l);c&&(e.unblurNSFWThumbnails&&c.thumbnail&&yt(c.thumbnail),n.push(c));break}default:throw new Error(`Unknown search type: ${e.type}`)}}return n}a(bt,"ParseSearchResult");function $i(r){if(!r)return 0;let e=r.split(":"),t=0;switch(e.length){case 3:t=parseInt(e[0])*60*60+parseInt(e[1])*60+parseInt(e[2]);break;case 2:t=parseInt(e[0])*60+parseInt(e[1]);break;default:t=parseInt(e[0])}return t}a($i,"parseDuration");function Pi(r){if(!r||!r.channelRenderer)throw new Error("Failed to Parse YouTube Channel");let e=r.channelRenderer.ownerBadges?.[0]?.metadataBadgeRenderer?.style?.toLowerCase(),t=`https://www.youtube.com${r.channelRenderer.navigationEndpoint.browseEndpoint.canonicalBaseUrl||r.channelRenderer.navigationEndpoint.commandMetadata.webCommandMetadata.url}`,i=r.channelRenderer.thumbnail.thumbnails[r.channelRenderer.thumbnail.thumbnails.length-1];return new S({id:r.channelRenderer.channelId,name:r.channelRenderer.title.simpleText,icon:{url:i.url.replace("//","https://"),width:i.width,height:i.height},url:t,verified:!!e?.includes("verified"),artist:!!e?.includes("artist"),subscribers:r.channelRenderer.subscriberCountText?.simpleText??"0 subscribers"})}a(Pi,"parseChannel");function Ni(r){if(!r||!r.videoRenderer)throw new Error("Failed to Parse YouTube Video");let e=r.videoRenderer.ownerText.runs[0],t=r.videoRenderer.ownerBadges?.[0]?.metadataBadgeRenderer?.style?.toLowerCase(),i=r.videoRenderer.lengthText;return new E({id:r.videoRenderer.videoId,url:`https://www.youtube.com/watch?v=${r.videoRenderer.videoId}`,title:r.videoRenderer.title.runs[0].text,description:r.videoRenderer.detailedMetadataSnippets?.[0].snippetText.runs?.length?r.videoRenderer.detailedMetadataSnippets[0].snippetText.runs.map(n=>n.text).join(""):"",duration:i?$i(i.simpleText):0,duration_raw:i?i.simpleText:null,thumbnails:r.videoRenderer.thumbnail.thumbnails,channel:{id:e.navigationEndpoint.browseEndpoint.browseId||null,name:e.text||null,url:`https://www.youtube.com${e.navigationEndpoint.browseEndpoint.canonicalBaseUrl||e.navigationEndpoint.commandMetadata.webCommandMetadata.url}`,icons:r.videoRenderer.channelThumbnailSupportedRenderers.channelThumbnailWithLinkRenderer.thumbnail.thumbnails,verified:!!t?.includes("verified"),artist:!!t?.includes("artist")},uploadedAt:r.videoRenderer.publishedTimeText?.simpleText??null,upcoming:r.videoRenderer.upcomingEventData?.startTime?new Date(parseInt(r.videoRenderer.upcomingEventData.startTime)*1e3):void 0,views:r.videoRenderer.viewCountText?.simpleText?.replace(/\D/g,"")??0,live:!i})}a(Ni,"parseVideo");function Ai(r){if(!r||!r.playlistRenderer)throw new Error("Failed to Parse YouTube Playlist");let e=r.playlistRenderer.thumbnails[0].thumbnails[r.playlistRenderer.thumbnails[0].thumbnails.length-1],t=r.playlistRenderer.shortBylineText.runs?.[0];return new D({id:r.playlistRenderer.playlistId,title:r.playlistRenderer.title.simpleText,thumbnail:{id:r.playlistRenderer.playlistId,url:e.url,height:e.height,width:e.width},channel:{id:t?.navigationEndpoint.browseEndpoint.browseId,name:t?.text,url:`https://www.youtube.com${t?.navigationEndpoint.commandMetadata.webCommandMetadata.url}`},videos:parseInt(r.playlistRenderer.videoCount.replace(/\D/g,""))},!0)}a(Ai,"parsePlaylist");function yt(r){if(Oi.find(e=>r.url.includes(e)))switch(r.url=r.url.split("?")[0],r.url.split("/").at(-1).split(".")[0]){case"hq2":case"hqdefault":r.width=480,r.height=360;break;case"hq720":r.width=1280,r.height=720;break;case"sddefault":r.width=640,r.height=480;break;case"mqdefault":r.width=320,r.height=180;break;case"default":r.width=120,r.height=90;break;default:r.width=r.height=NaN}}a(yt,"unblurThumbnail");async function gt(r,e={}){let t="https://www.youtube.com/results?search_query="+r;if(e.type??="video",t.indexOf("&sp=")===-1)switch(t+="&sp=",e.type){case"channel":t+="EgIQAg%253D%253D";break;case"playlist":t+="EgIQAw%253D%253D";break;case"video":t+="EgIQAQ%253D%253D";break;default:throw new Error(`Unknown search type: ${e.type}`)}let i=await h(t,{headers:{"accept-language":e.language||"en-US;q=0.9"}});if(i.indexOf("Our systems have detected unusual traffic from your computer network.")!==-1)throw new Error("Captcha page: YouTube has detected that you are a bot!");return bt(i,e)}a(gt,"yt_search");var Se=class Se{constructor(e){this.name=e.name,this.id=e.id,this.isrc=e.external_ids?.isrc||"",this.type="track",this.url=e.external_urls.spotify,this.explicit=e.explicit,this.playable=e.is_playable,this.durationInMs=e.duration_ms,this.durationInSec=Math.round(this.durationInMs/1e3);let t=[];e.artists.forEach(i=>{t.push({name:i.name,id:i.id,url:i.external_urls.spotify})}),this.artists=t,e.album?.name?this.album={name:e.album.name,url:e.external_urls.spotify,id:e.album.id,release_date:e.album.release_date,release_date_precision:e.album.release_date_precision,total_tracks:e.album.total_tracks}:this.album=void 0,e.album?.images?.[0]?this.thumbnail=e.album.images[0]:this.thumbnail=void 0}toJSON(){return{name:this.name,id:this.id,url:this.url,explicit:this.explicit,durationInMs:this.durationInMs,durationInSec:this.durationInSec,artists:this.artists,album:this.album,thumbnail:this.thumbnail}}};a(Se,"SpotifyTrack");var T=Se,Ee=class Ee{constructor(e,t,i){this.name=e.name,this.type="playlist",this.search=i,this.collaborative=e.collaborative,this.description=e.description,this.url=e.external_urls.spotify,this.id=e.id,this.thumbnail=e.images[0],this.owner={name:e.owner.display_name,url:e.owner.external_urls.spotify,id:e.owner.id},this.tracksCount=Number(e.tracks.total);let s=[];this.search||e.tracks.items.forEach(n=>{n.track&&s.push(new T(n.track))}),this.fetched_tracks=new Map,this.fetched_tracks.set("1",s),this.spotifyData=t}async fetch(){if(this.search)return this;let e;if(this.tracksCount>1e3?e=1e3:e=this.tracksCount,e<=100)return this;let t=[];for(let i=2;i<=Math.ceil(e/100);i++)t.push(new Promise(async(s,n)=>{let o=await h(`https://api.spotify.com/v1/playlists/${this.id}/tracks?offset=${(i-1)*100}&limit=100&market=${this.spotifyData.market}`,{headers:{Authorization:`${this.spotifyData.token_type} ${this.spotifyData.access_token}`}}).catch(u=>n(`Response Error : ${u}`)),l=[];if(typeof o!="string")return;JSON.parse(o).items.forEach(u=>{u.track&&l.push(new T(u.track))}),this.fetched_tracks.set(`${i}`,l),s("Success")}));return await Promise.allSettled(t),this}page(e){if(!e)throw new Error("Page number is not provided");if(!this.fetched_tracks.has(`${e}`))throw new Error("Given Page number is invalid");return this.fetched_tracks.get(`${e}`)}get total_pages(){return this.fetched_tracks.size}get total_tracks(){if(this.search)return this.tracksCount;let e=this.total_pages;return(e-1)*100+this.fetched_tracks.get(`${e}`).length}async all_tracks(){await this.fetch();let e=[];for(let t of this.fetched_tracks.values())e.push(...t);return e}toJSON(){return{name:this.name,collaborative:this.collaborative,description:this.description,url:this.url,id:this.id,thumbnail:this.thumbnail,owner:this.owner,tracksCount:this.tracksCount}}};a(Ee,"SpotifyPlaylist");var L=Ee,Te=class Te{constructor(e,t,i){this.name=e.name,this.type="album",this.id=e.id,this.search=i,this.url=e.external_urls.spotify,this.thumbnail=e.images[0];let s=[];e.artists.forEach(o=>{s.push({name:o.name,id:o.id,url:o.external_urls.spotify})}),this.artists=s,this.copyrights=e.copyrights,this.release_date=e.release_date,this.release_date_precision=e.release_date_precision,this.tracksCount=e.total_tracks;let n=[];this.search||e.tracks.items.forEach(o=>{n.push(new T(o))}),this.fetched_tracks=new Map,this.fetched_tracks.set("1",n),this.spotifyData=t}async fetch(){if(this.search)return this;let e;if(this.tracksCount>500?e=500:e=this.tracksCount,e<=50)return this;let t=[];for(let i=2;i<=Math.ceil(e/50);i++)t.push(new Promise(async(s,n)=>{let o=await h(`https://api.spotify.com/v1/albums/${this.id}/tracks?offset=${(i-1)*50}&limit=50&market=${this.spotifyData.market}`,{headers:{Authorization:`${this.spotifyData.token_type} ${this.spotifyData.access_token}`}}).catch(u=>n(`Response Error : ${u}`)),l=[];if(typeof o!="string")return;JSON.parse(o).items.forEach(u=>{u&&l.push(new T(u))}),this.fetched_tracks.set(`${i}`,l),s("Success")}));return await Promise.allSettled(t),this}page(e){if(!e)throw new Error("Page number is not provided");if(!this.fetched_tracks.has(`${e}`))throw new Error("Given Page number is invalid");return this.fetched_tracks.get(`${e}`)}get total_pages(){return this.fetched_tracks.size}get total_tracks(){if(this.search)return this.tracksCount;let e=this.total_pages;return(e-1)*100+this.fetched_tracks.get(`${e}`).length}async all_tracks(){await this.fetch();let e=[];for(let t of this.fetched_tracks.values())e.push(...t);return e}toJSON(){return{name:this.name,id:this.id,type:this.type,url:this.url,thumbnail:this.thumbnail,artists:this.artists,copyrights:this.copyrights,release_date:this.release_date,release_date_precision:this.release_date_precision,tracksCount:this.tracksCount}}};a(Te,"SpotifyAlbum");var M=Te;import{existsSync as zi,readFileSync as Li,writeFileSync as wt}from"node:fs";var d;zi(".data/spotify.data")&&(d=JSON.parse(Li(".data/spotify.data","utf-8")),d.file=!0);var _t=/^((https:)?\/\/)?open\.spotify\.com\/(?:intl\-.{2}\/)?(track|album|playlist)\//;async function kt(r){if(!d)throw new Error(`Spotify Data is missing Did you forgot to do authorization ?`);let e=r.trim();if(!e.match(_t))throw new Error("This is not a Spotify URL");if(e.indexOf("track/")!==-1){let t=e.split("track/")[1].split("&")[0].split("?")[0],i=await h(`https://api.spotify.com/v1/tracks/${t}?market=${d.market}`,{headers:{Authorization:`${d.token_type} ${d.access_token}`}}).catch(n=>n);if(i instanceof Error)throw i;let s=JSON.parse(i);if(s.error)throw new Error(`Got ${s.error.status} from the spotify request: ${s.error.message}`);return new T(s)}else if(e.indexOf("album/")!==-1){let t=r.split("album/")[1].split("&")[0].split("?")[0],i=await h(`https://api.spotify.com/v1/albums/${t}?market=${d.market}`,{headers:{Authorization:`${d.token_type} ${d.access_token}`}}).catch(n=>n);if(i instanceof Error)throw i;let s=JSON.parse(i);if(s.error)throw new Error(`Got ${s.error.status} from the spotify request: ${s.error.message}`);return new M(s,d,!1)}else if(e.indexOf("playlist/")!==-1){let t=r.split("playlist/")[1].split("&")[0].split("?")[0],i=await h(`https://api.spotify.com/v1/playlists/${t}?market=${d.market}`,{headers:{Authorization:`${d.token_type} ${d.access_token}`}}).catch(n=>n);if(i instanceof Error)throw i;let s=JSON.parse(i);if(s.error)throw new Error(`Got ${s.error.status} from the spotify request: ${s.error.message}`);return new L(s,d,!1)}else throw new Error("URL is out of scope for play-dl.")}a(kt,"spotify");function xe(r){let e=r.trim();return e.startsWith("https")?e.match(_t)?e.indexOf("track/")!==-1?"track":e.indexOf("album/")!==-1?"album":e.indexOf("playlist/")!==-1?"playlist":!1:!1:"search"}a(xe,"sp_validate");async function vt(r,e){let t=await h("https://accounts.spotify.com/api/token",{headers:{Authorization:`Basic ${Buffer.from(`${r.client_id}:${r.client_secret}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded"},body:`grant_type=authorization_code&code=${r.authorization_code}&redirect_uri=${encodeURI(r.redirect_url)}`,method:"POST"}).catch(s=>s);if(t instanceof Error)throw t;let i=JSON.parse(t);return d={client_id:r.client_id,client_secret:r.client_secret,redirect_url:r.redirect_url,access_token:i.access_token,refresh_token:i.refresh_token,expires_in:Number(i.expires_in),expiry:Date.now()+(i.expires_in-1)*1e3,token_type:i.token_type,market:r.market},e?wt(".data/spotify.data",JSON.stringify(d,void 0,4)):(console.log(`Client ID : ${d.client_id}`),console.log(`Client Secret : ${d.client_secret}`),console.log(`Refresh Token : ${d.refresh_token}`),console.log(`Market : ${d.market}`),console.log(` Paste above info in setToken function.`)),!0}a(vt,"SpotifyAuthorize");function St(){return Date.now()>=d.expiry}a(St,"is_expired");async function Et(r,e,t=10){let i=[];if(!d)throw new Error(`Spotify Data is missing Did you forget to do authorization ?`);if(r.length===0)throw new Error("Pass some query to search.");if(t>50||t<0)throw new Error("You crossed limit range of Spotify [ 0 - 50 ]");let s=await h(`https://api.spotify.com/v1/search?type=${e}&q=${r}&limit=${t}&market=${d.market}`,{headers:{Authorization:`${d.token_type} ${d.access_token}`}}).catch(o=>o);if(s instanceof Error)throw s;let n=JSON.parse(s);return e==="track"?n.tracks.items.forEach(o=>{i.push(new T(o))}):e==="album"?n.albums.items.forEach(o=>{i.push(new M(o,d,!0))}):e==="playlist"&&n.playlists.items.forEach(o=>{i.push(new L(o,d,!0))}),i}a(Et,"sp_search");async function Ie(){let r=await h("https://accounts.spotify.com/api/token",{headers:{Authorization:`Basic ${Buffer.from(`${d.client_id}:${d.client_secret}`).toString("base64")}`,"Content-Type":"application/x-www-form-urlencoded"},body:`grant_type=refresh_token&refresh_token=${d.refresh_token}`,method:"POST"}).catch(t=>t);if(r instanceof Error)return!1;let e=JSON.parse(r);return d.access_token=e.access_token,d.expires_in=Number(e.expires_in),d.expiry=Date.now()+(e.expires_in-1)*1e3,d.token_type=e.token_type,d.file&&wt(".data/spotify.data",JSON.stringify(d,void 0,4)),!0}a(Ie,"refreshToken");async function Tt(r){d=r,d.file=!1,await Ie()}a(Tt,"setSpotifyToken");import{existsSync as qi,readFileSync as Ui}from"node:fs";import{Readable as Mi}from"node:stream";var De=class De{constructor(e){this.name=e.title,this.id=e.id,this.url=e.uri,this.permalink=e.permalink_url,this.fetched=!0,this.type="track",this.durationInSec=Math.round(Number(e.duration)/1e3),this.durationInMs=Number(e.duration),e.publisher_metadata?this.publisher={name:e.publisher_metadata.publisher,id:e.publisher_metadata.id,artist:e.publisher_metadata.artist,contains_music:!!e.publisher_metadata.contains_music||!1,writer_composer:e.publisher_metadata.writer_composer}:this.publisher=null,this.formats=e.media.transcodings,this.user={name:e.user.username,id:e.user.id,type:"user",url:e.user.permalink_url,verified:!!e.user.verified||!1,description:e.user.description,first_name:e.user.first_name,full_name:e.user.full_name,last_name:e.user.last_name,thumbnail:e.user.avatar_url},this.thumbnail=e.artwork_url}toJSON(){return{name:this.name,id:this.id,url:this.url,permalink:this.permalink,fetched:this.fetched,durationInMs:this.durationInMs,durationInSec:this.durationInSec,publisher:this.publisher,formats:this.formats,thumbnail:this.thumbnail,user:this.user}}};a(De,"SoundCloudTrack");var x=De,Re=class Re{constructor(e,t){this.name=e.title,this.id=e.id,this.url=e.uri,this.client_id=t,this.type="playlist",this.sub_type=e.set_type,this.durationInSec=Math.round(Number(e.duration)/1e3),this.durationInMs=Number(e.duration),this.user={name:e.user.username,id:e.user.id,type:"user",url:e.user.permalink_url,verified:!!e.user.verified||!1,description:e.user.description,first_name:e.user.first_name,full_name:e.user.full_name,last_name:e.user.last_name,thumbnail:e.user.avatar_url},this.tracksCount=e.track_count;let i=[];e.tracks.forEach(s=>{s.title?i.push(new x(s)):i.push({id:s.id,fetched:!1,type:"track"})}),this.tracks=i}async fetch(){let e=[];for(let t=0;t{let s=t,n=await h(`https://api-v2.soundcloud.com/tracks/${this.tracks[t].id}?client_id=${this.client_id}`);this.tracks[s]=new x(JSON.parse(n)),i("")}));return await Promise.allSettled(e),this}get total_tracks(){let e=0;return this.tracks.forEach(t=>{if(t instanceof x)e++;else return}),e}async all_tracks(){return await this.fetch(),this.tracks}toJSON(){return{name:this.name,id:this.id,sub_type:this.sub_type,url:this.url,durationInMs:this.durationInMs,durationInSec:this.durationInSec,tracksCount:this.tracksCount,user:this.user,tracks:this.tracks}}};a(Re,"SoundCloudPlaylist");var $=Re,Ce=class Ce{constructor(e,t="arbitrary"){this.stream=new Mi({highWaterMark:5*1e3*1e3,read(){}}),this.type=t,this.url=e,this.downloaded_time=0,this.request=null,this.downloaded_segments=0,this.time=[],this.timer=new C(()=>{this.timer.reuse(),this.start()},280),this.segment_urls=[],this.stream.on("close",()=>{this.cleanup()}),this.start()}async parser(){let e=await h(this.url).catch(i=>i);if(e instanceof Error)throw e;e.split(` `).forEach(i=>{i.startsWith("#EXTINF:")?this.time.push(parseFloat(i.replace("#EXTINF:",""))):i.startsWith("https")&&this.segment_urls.push(i)})}async start(){if(this.stream.destroyed){this.cleanup();return}this.time=[],this.segment_urls=[],this.downloaded_time=0,await this.parser(),this.segment_urls.splice(0,this.downloaded_segments),this.loop()}async loop(){if(this.stream.destroyed){this.cleanup();return}if(this.time.length===0||this.segment_urls.length===0){this.cleanup(),this.stream.push(null);return}this.downloaded_time+=this.time.shift(),this.downloaded_segments++;let e=await w(this.segment_urls.shift()).catch(t=>t);if(e instanceof Error){this.stream.emit("error",e),this.cleanup();return}this.request=e,e.on("data",t=>{this.stream.push(t)}),e.on("end",()=>{this.downloaded_time>=300||this.loop()}),e.once("error",t=>{this.stream.emit("error",t)})}cleanup(){this.timer.destroy(),this.request?.destroy(),this.url="",this.downloaded_time=0,this.downloaded_segments=0,this.request=null,this.time=[],this.segment_urls=[]}pause(){this.timer.pause()}resume(){this.timer.resume()}};a(Ce,"SoundCloudStream");var q=Ce;var R;qi(".data/soundcloud.data")&&(R=JSON.parse(Ui(".data/soundcloud.data","utf-8")));var xt=/^(?:(https?):\/\/)?(?:(?:www|m)\.)?(api\.soundcloud\.com|soundcloud\.com|snd\.sc)\/(.*)$/;async function Oe(r){if(!R)throw new Error(`SoundCloud Data is missing Did you forget to do authorization ?`);let e=r.trim();if(!e.match(xt))throw new Error("This is not a SoundCloud URL");let t=await h(`https://api-v2.soundcloud.com/resolve?url=${e}&client_id=${R.client_id}`).catch(s=>s);if(t instanceof Error)throw t;let i=JSON.parse(t);if(i.kind!=="track"&&i.kind!=="playlist")throw new Error("This url is out of scope for play-dl.");return i.kind==="track"?new x(i):new $(i,R.client_id)}a(Oe,"soundcloud");async function It(r,e,t=10){let i=await h(`https://api-v2.soundcloud.com/search/${e}?q=${r}&client_id=${R.client_id}&limit=${t}`),s=[];return JSON.parse(i).collection.forEach(o=>{e==="tracks"?s.push(new x(o)):s.push(new $(o,R.client_id))}),s}a(It,"so_search");async function Dt(r,e){let t=await Oe(r);if(t instanceof $)throw new Error("Streams can't be created from playlist urls");let i=$t(t.formats);typeof e!="number"?e=i.length-1:e<=0?e=0:e>=i.length&&(e=i.length-1);let s=i[e].url+"?client_id="+R.client_id,n=JSON.parse(await h(s)),o=i[e].format.mime_type.startsWith("audio/ogg")?"ogg/opus":"arbitrary";return new q(n.url,o)}a(Dt,"stream");async function Rt(){let r=await h("https://soundcloud.com/",{headers:{}}).catch(s=>s);if(r instanceof Error)throw new Error("Failed to get response from soundcloud.com: "+r.message);let e=r.split('