@vookav2/play-dl
Version:
YouTube, SoundCloud, Spotify, Deezer searching and streaming for discord-js bots
7 lines • 82.6 kB
JavaScript
var St=Object.defineProperty;var a=(i,e)=>St(i,"name",{value:e,configurable:!0});import{request as Ot}from"node:https";import{URL as $t}from"node:url";import{createGunzip as Pt,createBrotliDecompress as Nt,createDeflate as At}from"node:zlib";import{existsSync as Et,readFileSync as Tt,writeFileSync as xt}from"node:fs";var k;Et(".data/youtube.data")&&(k=JSON.parse(Tt(".data/youtube.data","utf-8")),k.file=!0);function Oe(){let i="";if(!!k?.cookie){for(let[e,t]of Object.entries(k.cookie))i+=`${e}=${t};`;return i}}a(Oe,"getCookies");function Dt(i,e){return k?.cookie?(i=i.trim(),e=e.trim(),Object.assign(k.cookie,{[i]:e}),!0):!1}a(Dt,"setCookie");function It(){k.cookie&&k.file&&xt(".data/youtube.data",JSON.stringify(k,void 0,4))}a(It,"uploadCookie");function $e(i){let e=i.cookie,t={};e.split(";").forEach(r=>{let s=r.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($e,"setCookieToken");function Pe(i){!k?.cookie||(i.forEach(e=>{e.split(";").forEach(t=>{let r=t.split("=");if(r.length<=1)return;let s=r.shift()?.trim(),n=r.join("=").trim();Dt(s,n)})}),It())}a(Pe,"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 Ne(i){j.push(...i)}a(Ne,"setUserAgent");function Ct(i,e){return i=Math.ceil(i),e=Math.floor(e),Math.floor(Math.random()*(e-i+1))+i}a(Ct,"getRandomInt");function Ae(){let i=Ct(0,j.length-1);return j[i]}a(Ae,"getRandomUserAgent");function w(i,e={method:"GET"}){return new Promise(async(t,r)=>{let s=await G(i,e).catch(n=>n);if(s instanceof Error){r(s);return}Number(s.statusCode)>=300&&Number(s.statusCode)<400&&(s=await w(s.headers.location,e)),t(s)})}a(w,"request_stream");function ze(i,e={method:"GET"}){return new Promise(async(t,r)=>{let s=await G(i,e).catch(n=>n);if(s instanceof Error){r(s);return}if(Number(s.statusCode)>=300&&Number(s.statusCode)<400)s=await ze(s.headers.location,e);else if(Number(s.statusCode)>400){r(new Error(`Got ${s.statusCode} from the request`));return}t(s)})}a(ze,"internalRequest");function h(i,e={method:"GET"}){return new Promise(async(t,r)=>{let s=!1;if(e.cookies){let u=Oe();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":Ae()});let n=await ze(i,e).catch(u=>u);if(n instanceof Error){r(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&&Pe(n.headers["set-cookie"])}let o=[],l,c=n.headers["content-encoding"];c==="gzip"?l=Pt():c==="br"?l=Nt():c==="deflate"&&(l=At()),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(i){return new Promise(async(e,t)=>{let r=await G(i,{method:"HEAD"}).catch(n=>n);if(r instanceof Error){t(r);return}let s=Number(r.statusCode);if(s<300)e(i);else if(s<400){let n=await K(r.headers.location).catch(o=>o);if(n instanceof Error){t(n);return}e(n)}else t(new Error(`${r.statusCode}: ${r.statusMessage}, ${i}`))})}a(K,"request_resolve_redirect");function ae(i){return new Promise(async(e,t)=>{let r=await G(i,{method:"HEAD"}).catch(n=>n);if(r instanceof Error){t(r);return}let s=Number(r.statusCode);if(s<300)e(Number(r.headers["content-length"]));else if(s<400){let n=await K(r.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: ${r.statusCode}, ${r.statusMessage}, ${i}`))})}a(ae,"request_content_length");function G(i,e={}){return new Promise((t,r)=>{let s=new $t(i);e.method??="GET";let n={host:s.hostname,path:s.pathname+s.search,headers:e.headers??{},method:e.method},o=Ot(n,t);o.on("error",l=>{r(l)}),e.method==="POST"&&o.write(e.body),o.end()})}a(G,"https_getter");import{Readable as Ke}from"node:stream";import{URL as zt,URLSearchParams as Lt}from"node:url";var W="[a-zA-Z_\\$]\\w*",Mt="'[^'\\\\]*(:?\\\\[\\s\\S][^'\\\\]*)*'",qt='"[^"\\\\]*(:?\\\\[\\s\\S][^"\\\\]*)*"',Me=`(?:${Mt}|${qt})`,O=`(?:${W}|${Me})`,Ut=`(?:\\.${W}|\\[${Me}\\])`,Le=`(?:''|"")`,qe=":function\\(a\\)\\{(?:return )?a\\.reverse\\(\\)\\}",Ue=":function\\(a,b\\)\\{return a\\.slice\\(b\\)\\}",Be=":function\\(a,b\\)\\{a\\.splice\\(0,b\\)\\}",Ye=":function\\(a,b\\)\\{var c=a\\[0\\];a\\[0\\]=a\\[b(?:%a\\.length)?\\];a\\[b(?:%a\\.length)?\\]=c(?:;return a)?\\}",Bt=new RegExp(`var (${W})=\\{((?:(?:${O}${qe}|${O}${Ue}|${O}${Be}|${O}${Ye}),?\\r?\\n?)+)\\};`),Yt=new RegExp(`${`function(?: ${W})?\\(a\\)\\{a=a\\.split\\(${Le}\\);\\s*((?:(?:a=)?${W}`}${Ut}\\(a,\\d+\\);)+)return a\\.join\\(${Le}\\)\\}`),Wt=new RegExp(`(?:^|,)(${O})${qe}`,"m"),Jt=new RegExp(`(?:^|,)(${O})${Ue}`,"m"),Vt=new RegExp(`(?:^|,)(${O})${Be}`,"m"),Ft=new RegExp(`(?:^|,)(${O})${Ye}`,"m");function jt(i){let e=Yt.exec(i),t=Bt.exec(i);if(!e||!t)return null;let r=t[1].replace(/\$/g,"\\$"),s=t[2].replace(/\$/g,"\\$"),n=e[1].replace(/\$/g,"\\$"),o=Wt.exec(s),l=o&&o[1].replace(/\$/g,"\\$").replace(/\$|^'|^"|'$|"$/g,"");o=Jt.exec(s);let c=o&&o[1].replace(/\$/g,"\\$").replace(/\$|^'|^"|'$|"$/g,"");o=Vt.exec(s);let u=o&&o[1].replace(/\$/g,"\\$").replace(/\$|^'|^"|'$|"$/g,"");o=Ft.exec(s);let m=o&&o[1].replace(/\$/g,"\\$").replace(/\$|^'|^"|'$|"$/g,""),y=`(${[l,c,u,m].join("|")})`,f=`(?:a=)?${r}(?:\\.${y}|\\['${y}'\\]|\\["${y}"\\])\\(a,(\\d+)\\)`,b=new RegExp(f,"g"),D=[];for(;(o=b.exec(n))!==null;)switch(o[1]||o[2]||o[3]){case m:D.push(`sw${o[4]}`);break;case l:D.push("rv");break;case c:D.push(`sl${o[4]}`);break;case u:D.push(`sp${o[4]}`);break}return D}a(jt,"js_tokens");function Kt(i,e){let t=e.split(""),r=i.length;for(let s=0;s<r;s++){let n=i[s],o;switch(n.slice(0,2)){case"sw":o=parseInt(n.slice(2)),Gt(t,o);break;case"rv":t.reverse();break;case"sl":o=parseInt(n.slice(2)),t=t.slice(o);break;case"sp":o=parseInt(n.slice(2)),t.splice(0,o);break}}return t.join("")}a(Kt,"deciper_signature");function Gt(i,e){let t=i[0];i[0]=i[e],i[e]=t}a(Gt,"swappositions");function Ht(i,e){if(!i.url)return;let t=decodeURIComponent(i.url),r=new zt(t);r.searchParams.set("ratebypass","yes"),e&&r.searchParams.set(i.sp||"signature",e),i.url=r.toString()}a(Ht,"download_url");async function We(i,e){let t=await h(e),r=jt(t);return i.forEach(s=>{let n=s.signatureCipher||s.cipher;if(n){let o=Object.fromEntries(new Lt(n));Object.assign(s,o),delete s.signatureCipher,delete s.cipher}if(r&&s.s){let o=Kt(r,s.s);Ht(s,o),delete s.s,delete s.sp}}),i}a(We,"format_decipher");var S=class{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(S,"YouTubeChannel");var N=class{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(N,"YouTubeThumbnail");var E=class{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 r of e.thumbnails)t.push(new N(r));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(E,"YouTubeVideo");var Qt="https://www.youtube.com/youtubei/v1/browse?key=",I=class{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??"<important data>"}__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(`${Qt}${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:{}}})}),r=JSON.parse(t)?.onResponseReceivedActions[0]?.appendContinuationItemsAction?.continuationItems;if(!r)return[];let s=le(r,e);return this.fetched_videos.set(`${this.__count}`,s),this._continuation.token=H(r),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 r=await this.next();if(e-=r.length,e<=0||!r.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(I,"YouTubePlayList");import{URL as Zt,URLSearchParams as Xt}from"node:url";var Q=/^[a-zA-Z\d_-]{11,12}$/,ei=/^(PL|UU|LL|RD|OL)[a-zA-Z\d_-]{10,}$/,Z="AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8",Ve=/^((?:https?:)?\/\/)?(?:(?:www|m|music)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|shorts\/|embed\/|live\/|v\/)?)([\w\-]+)(\S+)?$/,ti=/^((?:https?:)?\/\/)?(?:(?:www|m|music)\.)?((?:youtube\.com|youtu.be))\/(?:(playlist|watch))?(.*)?((\?|\&)list=)(PL|UU|LL|RD|OL)[a-zA-Z\d_-]{10,}(&.*)?$/;function Y(i){let e=i.trim();if(e.indexOf("list=")===-1)if(e.startsWith("https"))if(e.match(Ve)){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(ei)?"playlist":"search";else return e.match(ti)?"playlist":Y(e.replace(/(\?|\&)list=[^&]*/,""))}a(Y,"yt_validate");function ue(i){if(i.startsWith("https://")&&i.match(Ve)){let e;if(i.includes("youtu.be/")?e=i.split("youtu.be/")[1].split(/(\?|\/|&)/)[0]:i.includes("youtube.com/embed/")?e=i.split("youtube.com/embed/")[1].split(/(\?|\/|&)/)[0]:i.includes("youtube.com/shorts/")?e=i.split("youtube.com/shorts/")[1].split(/(\?|\/|&)/)[0]:i.includes("youtube.com/live/")?e=i.split("youtube.com/live/")[1].split(/(\?|\/|&)/)[0]:e=(i.split("watch?v=")[1]??i.split("&v=")[1]).split(/(\?|\/|&)/)[0],e.match(Q))return e}else if(i.match(Q))return i;return!1}a(ue,"extractVideoId");function ce(i){let e=Y(i);if(!e||e==="search")throw new Error("This is not a YouTube url or videoId or PlaylistID");let t=i.trim();if(t.startsWith("https"))if(t.indexOf("list=")===-1){let r=ue(t);if(!r)throw new Error("This is not a YouTube url or videoId or PlaylistID");return r}else return t.split("list=")[1].split("&")[0];else return t}a(ce,"extractID");async function X(i,e={}){if(typeof i!="string")throw new Error("url parameter is not a URL string or a string of HTML");let t=i.trim(),r,s={};if(e.htmldata)r=t;else{let p=ue(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`;r=await h(g,{headers:{"accept-language":e.language||"en-US;q=0.9"},cookies:!0,cookieJar:s})}if(r.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=r.split("var ytInitialPlayerResponse = ")?.[1]?.split(";<\/script>")[0].split(/(?<=}}});\s*(var|const|let)\s/)[0];if(!n)throw new Error("Initial Player Response Data is undefined.");let o=r.split("var ytInitialData = ")?.[1]?.split(";<\/script>")[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 Fe(u.videoId,s,r,!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(),D=`https://www.youtube.com${r.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,Se=c.engagementPanels.find(p=>p?.engagementPanelSectionListRenderer?.panelIdentifier=="engagement-panel-structured-description")?.engagementPanelSectionListRenderer.content.structuredDescriptionContentRenderer.items.find(p=>p.videoDescriptionMusicSectionRenderer)?.videoDescriptionMusicSectionRenderer.carouselLockups,Ee=[];Se&&Se.forEach(p=>{if(!p.carouselLockupRenderer)return;let g=p.carouselLockupRenderer,wt=g.videoLockup?.compactVideoRenderer.title.simpleText??g.videoLockup?.compactVideoRenderer.title.runs?.find(v=>v.text)?.text,_t=g.infoRows?.map(v=>[v.infoRowRenderer.title.simpleText.toLowerCase(),(v.infoRowRenderer.expandedMetadata??v.infoRowRenderer.defaultMetadata)?.runs?.map(vt=>vt.text).join("")??v.infoRowRenderer.defaultMetadata?.simpleText??v.infoRowRenderer.expandedMetadata?.simpleText??""]),kt=Object.fromEntries(_t??{}),Ce=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;Ee.push({song:wt,url:Ce?`https://www.youtube.com/watch?v=${Ce}`:null,...kt})});let Te=c.playerOverlays.playerOverlayRenderer.decoratedPlayerBarRenderer?.decoratedPlayerBarRenderer.playerBar?.multiMarkersPlayerBarRenderer.markersMap?.find(p=>p.key==="DESCRIPTION_CHAPTERS")?.value?.chapters,xe=[];if(Te)for(let{chapterRenderer:p}of Te)xe.push({title:p.title.simpleText,timestamp:Je(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 De=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"),Ie=new E({id:u.videoId,title:u.title,description:u.shortDescription,duration:Number(u.lengthSeconds),duration_raw:Je(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:Boolean(b?.includes("verified")),artist:Boolean(b?.includes("artist")),icons:f?.thumbnail?.thumbnails||void 0},views:u.viewCount,tags:u.keywords,likes:parseInt(De?.toggleButtonRenderer?.defaultText.accessibility?.accessibilityData.label.replace(/\D+/g,"")??De?.segmentedLikeDislikeButtonRenderer?.likeButton.toggleButtonRenderer?.defaultText.accessibility?.accessibilityData.label.replace(/\D+/g,"")??0),live:u.isLiveContent,private:u.isPrivate,discretionAdvised:m,music:Ee,chapters:xe}),Re=[];return y||(Re=await je(u.videoId,s,r)),{LiveStreamData:{isLive:Ie.live,dashManifestUrl:l.streamingData?.dashManifestUrl??null,hlsManifestUrl:l.streamingData?.hlsManifestUrl??null},html5player:D,format:Re,video_details:Ie,related_videos:V}}a(X,"video_basic_info");async function A(i,e={}){if(typeof i!="string")throw new Error("url parameter is not a URL string or a string of HTML");let t,r={};if(e.htmldata)t=i;else{let f=ue(i);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:r})}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(";<\/script>")[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(";<\/script>")[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(r,{VISITOR_INFO1_LIVE:b.visitorCookie,CONSENT:b.consentCookie});let D=await Fe(n.videoDetails.videoId,r,t,!1);n.streamingData=D.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 je(n.videoDetails.videoId,r,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 Je(i){let e=Number(i),t=Math.floor(e/3600),r=Math.floor(e%3600/60),s=Math.floor(e%3600%60),n=t>0?(t<10?`0${t}`:t)+":":"",o=r>0?(r<10?`0${r}`:r)+":":"00:",l=s>0?s<10?`0${s}`:s:"00";return n+o+l}a(Je,"parseSeconds");async function he(i,e={}){let t=await X(i.trim(),e);return await J(t)}a(he,"video_info");async function J(i,e=!1){return i.LiveStreamData.isLive===!0&&i.LiveStreamData.dashManifestUrl!==null&&i.video_details.durationInSec===0||i.format.length>0&&(i.format[0].signatureCipher||i.format[0].cipher)&&(e&&(i.format=z(i.format)),i.format=await We(i.format,i.html5player)),i}a(J,"decipher_info");async function de(i,e={}){if(!i||typeof i!="string")throw new Error(`Expected playlist url, received ${typeof i}!`);let t=i.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 Zt(t);n.hostname="www.youtube.com",t=n.toString()}let r=await h(t,{headers:{"accept-language":e.language||"en-US;q=0.9"}});if(r.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(r.split("var ytInitialData = ")[1].split(";<\/script>")[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?ii(s,r,t):ri(s,r)}a(de,"playlist_info");function le(i,e=1/0){let t=[];for(let r=0;r<i.length&&e!==t.length;r++){let s=i[r].playlistVideoRenderer;!s||!s.shortBylineText||t.push(new E({id:s.videoId,duration:parseInt(s.lengthSeconds)||0,duration_raw:s.lengthText?.simpleText??"0:00",thumbnails:s.thumbnail.thumbnails,title:s.title.runs[0].text,upcoming:s.upcomingEventData?.startTime?new Date(parseInt(s.upcomingEventData.startTime)*1e3):void 0,channel:{id:s.shortBylineText.runs[0].navigationEndpoint.browseEndpoint.browseId||void 0,name:s.shortBylineText.runs[0].text||void 0,url:`https://www.youtube.com${s.shortBylineText.runs[0].navigationEndpoint.browseEndpoint.canonicalBaseUrl||s.shortBylineText.runs[0].navigationEndpoint.commandMetadata.webCommandMetadata.url}`,icon:void 0}}))}return t}a(le,"getPlaylistVideos");function H(i){return i.find(e=>Object.keys(e)[0]==="continuationItemRenderer")?.continuationItemRenderer.continuationEndpoint?.continuationCommand?.token}a(H,"getContinuationToken");async function Fe(i,e,t,r){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: ${i}.`);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]??"<some version>"},user:{},request:{}},nextEndpoint:{urlEndpoint:{url:`/watch?v=${i}&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 Xt([["command",JSON.stringify(l)],["session_token",n]]).toString(),cookies:!0,cookieJar:e});if(c.includes("<h1>Something went wrong</h1>"))throw new Error(`Unable to accept the viewer discretion popup for video: ${i}`);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 ${i}
${u[2].playerResponse.playabilityStatus.errorScreen.playerErrorMessageRenderer?.reason.simpleText??u[2].playerResponse.playabilityStatus.errorScreen.playerKavRenderer?.reason.simpleText}`);let m=u[2].playerResponse.streamingData;return r?{streamingData:m,relatedVideos:u[3].response.contents.twoColumnWatchNextResults.secondaryResults}:{streamingData:m}}a(Fe,"acceptViewerDiscretion");async function je(i,e,t){let r=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=${r}&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:i,playbackContext:{contentPlaybackContext:{html5Preference:"HTML5_PREF_WANTS"}},contentCheckOk:!0,racyCheckOk:!0}),cookies:!0,cookieJar:e}),n=JSON.parse(s);return n?.streamingData?.adaptiveFormats?n.streamingData.adaptiveFormats:[]}a(je,"getIosFormat");function ii(i,e,t){let r=i.contents.twoColumnWatchNextResults.playlist?.playlist;if(!r)throw new Error("Watch playlist unavailable due to YouTube layout changes.");let s=si(r.contents),n=e.split('INNERTUBE_API_KEY":"')[1]?.split('"')[0]??e.split('innertubeApiKey":"')[1]?.split('"')[0]??Z,o=r.totalVideos,l=r.shortBylineText?.runs?.[0],c=r.badges?.[0]?.metadataBadgeRenderer?.style.toLowerCase();return new I({continuation:{api:n,token:H(r.contents),clientVersion:e.split('"INNERTUBE_CONTEXT_CLIENT_VERSION":"')[1]?.split('"')[0]??e.split('"innertube_context_client_version":"')[1]?.split('"')[0]??"<some version>"},id:r.playlistId||"",title:r.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:Boolean(c?.includes("verified")),artist:Boolean(c?.includes("artist"))}})}a(ii,"getWatchPlaylist");function ri(i,e){let t=i.contents.twoColumnBrowseResultsRenderer.tabs[0].tabRenderer.content.sectionListRenderer.contents[0].itemSectionRenderer.contents[0].playlistVideoListRenderer.contents,r=i.sidebar.playlistSidebarRenderer.items,s=e.split('INNERTUBE_API_KEY":"')[1]?.split('"')[0]??e.split('innertubeApiKey":"')[1]?.split('"')[0]??Z,n=le(t,100),o=r[0].playlistSidebarPrimaryInfoRenderer;if(!o.title.runs||!o.title.runs.length)throw new Error("Failed to Parse Playlist info.");let l=r[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 I({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]??"<some version>"},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(ri,"getNormalPlaylist");function si(i,e=1/0){let t=[];for(let r=0;r<i.length&&e!==t.length;r++){let s=i[r].playlistPanelVideoRenderer;if(!s||!s.shortBylineText)continue;let n=s.shortBylineText.runs[0];t.push(new E({id:s.videoId,duration:ni(s.lengthText?.simpleText)||0,duration_raw:s.lengthText?.simpleText??"0:00",thumbnails:s.thumbnail.thumbnails,title:s.title.simpleText,upcoming:s.thumbnailOverlays[0].thumbnailOverlayTimeStatusRenderer?.style==="UPCOMING"||void 0,channel:{id:n.navigationEndpoint.browseEndpoint.browseId||void 0,name:n.text||void 0,url:`https://www.youtube.com${n.navigationEndpoint.browseEndpoint.canonicalBaseUrl||n.navigationEndpoint.commandMetadata.webCommandMetadata.url}`,icon:void 0}}))}return t}a(si,"getWatchPlaylistVideos");function ni(i){if(!i)return 0;let e=i.split(":");switch(e.length){case 2:return parseInt(e[0])*60+parseInt(e[1]);case 3:return parseInt(e[0])*60*60+parseInt(e[1])*60+parseInt(e[2]);default:return 0}}a(ni,"parseDuration");import{URL as oi}from"node:url";var ee=class{constructor(e,t,r,s){this.stream=new Ke({highWaterMark:5*1e3*1e3,read(){}}),this.type="arbitrary",this.sequence=0,this.dash_url=e,this.base_url="",this.interval=t,this.video_url=r,this.precache=s||3,this.dash_timer=new C(()=>{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('<AdaptationSet id="0"')[1].split("</AdaptationSet>")[0].split("</Representation>");if(t[t.length-1]===""&&t.pop(),this.base_url=t[t.length-1].split("<BaseURL>")[1].split("</BaseURL>")[0],await w(`https://${new oi(this.base_url).host}/generate_204`),this.sequence===0){let r=t[t.length-1].split("<SegmentList>")[1].split("</SegmentList>")[0].replaceAll('<SegmentURL media="',"").split('"/>');r[r.length-1]===""&&r.pop(),r.length>this.precache&&r.splice(0,r.length-this.precache),this.sequence=Number(r[0].split("sq/")[1].split("/")[0]),this.first_data(r.length)}}async first_data(e){for(let t=1;t<=e;t++)await new Promise(async r=>{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++,r("")}),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(r=>r);if(t instanceof Error){this.stream.emit("error",t);return}this.request=t,t.on("data",r=>{this.stream.push(r)}),t.on("end",()=>{this.sequence++,e("")}),t.once("error",r=>{this.stream.emit("error",r)})})}pause(){}resume(){}};a(ee,"LiveStream");var te=class{constructor(e,t,r,s,n,o){this.stream=new Ke({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/r),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(r=>r);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",r=>{this.stream.push(r)}),t.once("error",async()=>{this.cleanup(),await this.retry(),this.timer.reuse(),this.loop()}),t.on("data",r=>{this.bytes_count+=r.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(te,"Stream");var C=class{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(C,"Timer");import{WebmElements as Ge,WebmHeader as ai}from"play-audio";import{Duplex as li}from"node:stream";var ui=Object.keys(Ge),ie=class extends li{constructor(e,t){super(t);this.state="READING_HEAD",this.cursor=0,this.header=new ai,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.length<this.cursor+e)return!1;let t=this.chunk[this.cursor]&(1<<8-e)-1;for(let r=this.cursor+1;r<this.cursor+e;r++)t=(t<<8)+this.chunk[r];return this.data_size=e,this.data_length=t,!0}cleanup(){this.cursor=0,this.chunk=void 0,this.remaining=void 0}_read(){}seek(e){let t=0,r=0,s=(this.sec-this.time)*1e3||0;if(s=Math.round(s/20)*20,!this.header.segment.cues)return new Error("Failed to Parse Cues");for(let n=0;n<this.header.segment.cues.length;n++){let o=this.header.segment.cues[n];if(Math.floor(o.time/1e3)===this.time){r=o.position,t=(this.header.segment.cues[n+1]?.position||e)-r-1;break}else continue}return t===0?r:this.offset+Math.round(r+s/20*(t/500))}_write(e,t,r){this.remaining?(this.chunk=Buffer.concat([this.remaining,e]),this.remaining=void 0):this.chunk=e;let s;this.state==="READING_HEAD"?s=this.readHead():this.seekfound?s=this.readTag():s=this.getClosestBlock(),s?r(s):r()}readHead(){if(!this.chunk)return new Error("Chunk is missing");for(;this.chunk.length>this.cursor;){let e=this.cursor,t=this.vint_length;if(this.chunk.length<this.cursor+t)break;let r=this.parseEbmlID(this.chunk.slice(this.cursor,this.cursor+t).toString("hex"));if(this.cursor+=t,!this.vint_value()){this.cursor=e;break}if(!r){this.cursor+=this.data_size+this.data_length;continue}if(!this.headfound)if(r.name==="ebml")this.headfound=!0;else return new Error("Failed to find EBML ID at start of stream.");let s=this.chunk.slice(this.cursor+this.data_size,this.cursor+this.data_size+this.data_length),n=this.header.parse(r,s);if(n instanceof Error)return n;if(r.name==="seekHead"&&(this.offset=e),r.name==="cueClusterPosition"&&this.header.segment.cues.length>2&&this.time===this.header.segment.cues.at(-2).time/1e3&&this.emit("headComplete"),r.type===0){this.cursor+=this.data_size;continue}if(this.chunk.length<this.cursor+this.data_size+this.data_length){this.cursor=e;break}else this.cursor+=this.data_size+this.data_length}this.remaining=this.chunk.slice(this.cursor),this.cursor=0}readTag(){if(!this.chunk)return new Error("Chunk is missing");for(;this.chunk.length>this.cursor;){let e=this.cursor,t=this.vint_length;if(this.chunk.length<this.cursor+t)break;let r=this.parseEbmlID(this.chunk.slice(this.cursor,this.cursor+t).toString("hex"));if(this.cursor+=t,!this.vint_value()){this.cursor=e;break}if(!r){this.cursor+=this.data_size+this.data_length;continue}let s=this.chunk.slice(this.cursor+this.data_size,this.cursor+this.data_size+this.data_length),n=this.header.parse(r,s);if(n instanceof Error)return n;if(r.type===0){this.cursor+=this.data_size;continue}if(this.chunk.length<this.cursor+this.data_size+this.data_length){this.cursor=e;break}else this.cursor+=this.data_size+this.data_length;if(r.name==="simpleBlock"){let o=this.header.segment.tracks[this.header.audioTrack];if(!o||o.trackType!==2)return new Error("No audio Track in this webm file.");(s[0]&15)===o.trackNumber&&this.push(s.slice(4))}}this.remaining=this.chunk.slice(this.cursor),this.cursor=0}getClosestBlock(){if(this.sec===0)return this.seekfound=!0,this.readTag();if(!this.chunk)return new Error("Chunk is missing");this.cursor=0;let e=!1;for(;!e&&this.cursor<this.chunk.length;){if(this.cursor=this.chunk.indexOf("a3",this.cursor,"hex"),this.cursor===-1)return new Error("Failed to find nearest Block.");if(this.cursor++,!this.vint_value())return new Error("Failed to find correct simpleBlock in first chunk");if(this.cursor+this.data_length+this.data_length>this.chunk.length)continue;let t=this.chunk.slice(this.cursor+this.data_size,this.cursor+this.data_size+this.data_length),r=this.header.segment.tracks[this.header.audioTrack];if(!r||r.trackType!==2)return new Error("No audio Track in this webm file.");if((t[0]&15)===r.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 ui.includes(e)?Ge[e]:!1}_destroy(e,t){this.cleanup(),t(e)}_final(e){this.cleanup(),e()}};a(ie,"WebmSeeker");var re=class{constructor(e,t,r,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=r,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(r,s)=>{if(this.stream.headerparsed)r("");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",r("")}),this.stream.once("headComplete",()=>{n.unpipe(this.stream),n.destroy(),this.stream.state="READING_DATA",r("")})}}).catch(r=>r);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(r=>r);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",r=>{this.bytes_count+=r.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(re,"SeekStream");import{URL as ci}from"node:url";function z(i){let e=[];return i.forEach(t=>{let r=t.mimeType;r.startsWith("audio")&&(t.codec=r.split('codecs="')[1].split('"')[0],t.container=r.split("audio/")[1].split(";")[0],e.push(t))}),e}a(z,"parseAudioFormats");async function se(i,e={}){let t=await A(i,{htmldata:e.htmldata,language:e.language});return await ne(t,e)}a(se,"stream");async function ne(i,e={}){if(i.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(i.LiveStreamData.isLive===!0&&i.LiveStreamData.dashManifestUrl!==null&&i.video_details.durationInSec===0)return new ee(i.LiveStreamData.dashManifestUrl,i.format[i.format.length-1].targetDurationSec,i.video_details.url,e.precache);let r=z(i.format);typeof e.quality!="number"?e.quality=r.length-1:e.quality<=0?e.quality=0:e.quality>=r.length&&(e.quality=r.length-1),r.length!==0?t.push(r[e.quality]):t.push(i.format[i.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>=i.video_details.durationInSec||e.seek<0)throw new Error(`Seeking beyond limit. [ 0 - ${i.video_details.durationInSec-1}]`);return new re(t[0].url,i.video_details.durationInSec,t[0].indexRange.end,Number(t[0].contentLength),Number(t[0].bitrate),i.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,i.video_details.durationInSec,n,i.video_details.url,e)}a(ne,"stream_from_info");var hi=["-oaymwEpCOADEI4CSFryq4qpAxsIARUAAAAAGAElAADIQj0AgKJDeAHtAZmZGUI=","-oaymwEiCOADEI4CSFXyq4qpAxQIARUAAIhCGAFwAcABBu0BmZkZQg==","-oaymwEiCOgCEMoBSFXyq4qpAxQIARUAAIhCGAFwAcABBu0BZmbmQQ==","-oaymwEiCNAFEJQDSFXyq4qpAxQIARUAAIhCGAFwAcABBu0BZmZmQg==","-oaymwEdCNAFEJQDSFryq4qpAw8IARUAAIhCGAHtAWZmZkI=","-oaymwEdCNACELwBSFryq4qpAw8IARUAAIhCGAHtAT0K10E="];function Qe(i,e){if(!i)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 r=i.split("var ytInitialData = ")?.[1]?.split(";<\/script>")[0].split(/;\s*(var|const|let)\s/)[0],s=JSON.parse(r),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=mi(l);c&&(e.unblurNSFWThumbnails&&c.thumbnails.forEach(He),n.push(c));break}case"channel":{let c=pi(l);c&&n.push(c);break}case"playlist":{let c=fi(l);c&&(e.unblurNSFWThumbnails&&c.thumbnail&&He(c.thumbnail),n.push(c));break}default:throw new Error(`Unknown search type: ${e.type}`)}}return n}a(Qe,"ParseSearchResult");function di(i){if(!i)return 0;let e=i.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(di,"parseDuration");function pi(i){if(!i||!i.channelRenderer)throw new Error("Failed to Parse YouTube Channel");let e=i.channelRenderer.ownerBadges?.[0]?.metadataBadgeRenderer?.style?.toLowerCase(),t=`https://www.youtube.com${i.channelRenderer.navigationEndpoint.browseEndpoint.canonicalBaseUrl||i.channelRenderer.navigationEndpoint.commandMetadata.webCommandMetadata.url}`,r=i.channelRenderer.thumbnail.thumbnails[i.channelRenderer.thumbnail.thumbnails.length-1];return new S({id:i.channelRenderer.channelId,name:i.channelRenderer.title.simpleText,icon:{url:r.url.replace("//","https://"),width:r.width,height:r.height},url:t,verified:Boolean(e?.includes("verified")),artist:Boolean(e?.includes("artist")),subscribers:i.channelRenderer.subscriberCountText?.simpleText??"0 subscribers"})}a(pi,"parseChannel");function mi(i){if(!i||!i.videoRenderer)throw new Error("Failed to Parse YouTube Video");let e=i.videoRenderer.ownerText.runs[0],t=i.videoRenderer.ownerBadges?.[0]?.metadataBadgeRenderer?.style?.toLowerCase(),r=i.videoRenderer.lengthText;return new E({id:i.videoRenderer.videoId,url:`https://www.youtube.com/watch?v=${i.videoRenderer.videoId}`,title:i.videoRenderer.title.runs[0].text,description:i.videoRenderer.detailedMetadataSnippets?.[0].snippetText.runs?.length?i.videoRenderer.detailedMetadataSnippets[0].snippetText.runs.map(n=>n.text).join(""):"",duration:r?di(r.simpleText):0,duration_raw:r?r.simpleText:null,thumbnails:i.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:i.videoRenderer.channelThumbnailSupportedRenderers.channelThumbnailWithLinkRenderer.thumbnail.thumbnails,verified:Boolean(t?.includes("verified")),artist:Boolean(t?.includes("artist"))},uploadedAt:i.videoRenderer.publishedTimeText?.simpleText??null,upcoming:i.videoRenderer.upcomingEventData?.startTime?new Date(parseInt(i.videoRenderer.upcomingEventData.startTime)*1e3):void 0,views:i.videoRenderer.viewCountText?.simpleText?.replace(/\D/g,"")??0,live:!r})}a(mi,"parseVideo");function fi(i){if(!i||!i.playlistRenderer)throw new Error("Failed to Parse YouTube Playlist");let e=i.playlistRenderer.thumbnails[0].thumbnails[i.playlistRenderer.thumbnails[0].thumbnails.length-1],t=i.playlistRenderer.shortBylineText.runs?.[0];return new I({id:i.playlistRenderer.playlistId,title:i.playlistRenderer.title.simpleText,thumbnail:{id:i.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(i.playlistRenderer.videoCount.replace(/\D/g,""))},!0)}a(fi,"parsePlaylist");function He(i){if(hi.find(e=>i.url.includes(e)))switch(i.url=i.url.split("?")[0],i.url.split("/").at(-1).split(".")[0]){case"hq2":case"hqdefault":i.width=480,i.height=360;break;case"hq720":i.width=1280,i.height=720;break;case"sddefault":i.width=640,i.height=480;break;case"mqdefault":i.width=320,i.height=180;break;case"default":i.width=120