ytdlp-nodejs
Advanced tools
+5
-5
@@ -1,5 +0,5 @@ | ||
| "use strict";var Ee=Object.create;var V=Object.defineProperty;var Ie=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Oe=Object.getPrototypeOf,Ve=Object.prototype.hasOwnProperty;var Ce=(e,t)=>{for(var r in t)V(e,r,{get:t[r],enumerable:!0})},ne=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Re(t))!Ve.call(e,i)&&i!==r&&V(e,i,{get:()=>t[i],enumerable:!(s=Ie(t,i))||s.enumerable});return e};var c=(e,t,r)=>(r=e!=null?Ee(Oe(e)):{},ne(t||!e||!e.__esModule?V(r,"default",{value:e,enumerable:!0}):r,e)),$e=e=>ne(V({},"__esModule",{value:!0}),e);var Qe={};Ce(Qe,{BIN_DIR:()=>w,Download:()=>A,Exec:()=>y,Stream:()=>D,YtDlp:()=>se,createDownload:()=>Pe,createExec:()=>ke,createStreamBuilder:()=>Ae,helpers:()=>qe});module.exports=$e(Qe);var k=require("child_process"),re=c(require("fs")),Se=c(require("path")),_e=require("buffer"),Be=require("stream");function C(e){let t=[];if(e.printHelp&&t.push("--help"),e.printVersion&&t.push("--version"),e.update&&t.push("--update"),e.noUpdate&&t.push("--no-update"),e.updateTo&&t.push("--update-to",e.updateTo),e.ignoreErrors&&t.push("--ignore-errors"),e.noAbortOnError&&t.push("--no-abort-on-error"),e.abortOnError&&t.push("--abort-on-error"),e.dumpUserAgent&&t.push("--dump-user-agent"),e.listExtractors&&t.push("--list-extractors"),e.extractorDescriptions&&t.push("--extractor-descriptions"),e.useExtractors&&e.useExtractors.length>0&&t.push("--use-extractors",e.useExtractors.join(",")),e.defaultSearch&&t.push("--default-search",e.defaultSearch),e.ignoreConfig&&t.push("--ignore-config"),e.noConfigLocations&&t.push("--no-config-location"),e.configLocations&&e.configLocations.length>0&&t.push("--config-locations",...e.configLocations),e.pluginDirs&&e.pluginDirs.length>0)for(let s of e.pluginDirs)t.push("--plugin-dirs",s);e.noPluginDirs&&t.push("--no-plugin-dirs"),e.flatPlaylist&&t.push("--flat-playlist"),e.noFlatPlaylist&&t.push("--no-flat-playlist"),e.liveFromStart&&t.push("--live-from-start"),e.noLiveFromStart&&t.push("--no-live-from-start"),e.waitForVideo&&t.push("--wait-for-video",e.waitForVideo.toString()),e.noWaitForVideo&&t.push("--no-wait-for-video"),e.markWatched&&t.push("--mark-watched"),e.noMarkWatched&&t.push("--no-mark-watched"),e.color&&t.push("--color",e.color),e.compatOptions&&e.compatOptions.length>0&&t.push("--compat-options",e.compatOptions.join(",")),e.aliases&&e.aliases.length>0&&t.push("--alias",...e.aliases);let r=e.jsRuntime??"node";if(r&&t.push("--js-runtime",r),e.proxy&&t.push("--proxy",e.proxy),e.socketTimeout&&t.push("--socket-timeout",e.socketTimeout.toString()),e.sourceAddress&&t.push("--source-address",e.sourceAddress),e.impersonate&&e.impersonate.length>0&&t.push("--impersonate",e.impersonate.join(",")),e.listImpersonateTargets&&t.push("--list-impersonate-targets"),e.forceIpv4&&t.push("--force-ipv4"),e.forceIpv6&&t.push("--force-ipv6"),e.enableFileUrls&&t.push("--enable-file-urls"),e.geoVerificationProxy&&t.push("--geo-verification-proxy",e.geoVerificationProxy),e.xff&&t.push("--xff",e.xff),e.playlistItems&&t.push("--playlist-items",e.playlistItems),e.minFilesize&&t.push("--min-filesize",e.minFilesize),e.maxFilesize&&t.push("--max-filesize",e.maxFilesize),e.date&&t.push("--date",e.date),e.dateBefore&&t.push("--datebefore",e.dateBefore),e.dateAfter&&t.push("--dateafter",e.dateAfter),e.matchFilter&&t.push("--match-filter",e.matchFilter),e.noMatchFilters&&t.push("--no-match-filters"),e.breakMatchFilters&&t.push("--break-match-filters",e.breakMatchFilters),e.noBreakMatchFilters&&t.push("--no-break-match-filters"),e.noPlaylist&&t.push("--no-playlist"),e.yesPlaylist&&t.push("--yes-playlist"),e.ageLimit&&t.push("--age-limit",e.ageLimit.toString()),e.downloadArchive&&t.push("--download-archive",e.downloadArchive),e.noDownloadArchive&&t.push("--no-download-archive"),e.maxDownloads&&t.push("--max-downloads",e.maxDownloads.toString()),e.breakOnExisting&&t.push("--break-on-existing"),e.noBreakOnExisting&&t.push("--no-break-on-existing"),e.breakPerInput&&t.push("--break-per-input"),e.noBreakPerInput&&t.push("--break-per-input"),e.skipPlaylistAfterErrors&&t.push("--skip-playlist-after-errors",e.skipPlaylistAfterErrors.toString()),e.concurrentFragments&&t.push("--concurrent-fragments",e.concurrentFragments.toString()),e.limitRate&&t.push("--limit-rate",e.limitRate),e.throttledRate&&t.push("--throttled-rate",e.throttledRate),e.retries&&t.push("--retries",e.retries.toString()),e.fileAccessRetries&&t.push("--file-access-retries",e.fileAccessRetries.toString()),e.fragmentRetries&&t.push("--fragment-retries",e.fragmentRetries.toString()),e.retrySleep&&t.push("--retry-sleep",e.retrySleep.toString()),e.retrySleepByType)for(let[s,i]of Object.entries(e.retrySleepByType))t.push("--retry-sleep",`${s}:${i}`);if(e.skipUnavailableFragments&&t.push("--skip-unavailable-fragments"),e.abortOnUnavailableFragment&&t.push("--abort-on-unavailable-fragment"),e.keepFragments&&t.push("--keep-fragments"),e.noKeepFragments&&t.push("--no-keep-fragments"),e.bufferSize&&t.push("--buffer-size",e.bufferSize),e.resizeBuffer&&t.push("--resize-buffer"),e.noResizeBuffer&&t.push("--no-resize-buffer"),e.httpChunkSize&&t.push("--http-chunk-size",e.httpChunkSize),e.playlistRandom&&t.push("--playlist-random"),e.lazyPlaylist&&t.push("--lazy-playlist"),e.noLazyPlaylist&&t.push("--no-lazy-playlist"),e.xattrSetFilesize&&t.push("--xattr-set-filesize"),e.hlsUseMpegts&&t.push("--hls-use-mpegts"),e.noHlsUseMpegts&&t.push("--no-hls-use-mpegts"),e.downloadSections&&t.push("--download-sections",e.downloadSections.toString()),e.downloader&&t.push("--downloader",e.downloader),e.downloaderArgs&&t.push("--downloader-args",e.downloaderArgs),e.batchFile&&t.push("--batch-file",e.batchFile),e.noBatchFile&&t.push("--no-batch-file"),e.paths)if(typeof e.paths=="string")t.push("--paths",e.paths);else for(let[s,i]of Object.entries(e.paths))t.push("--paths",`${s}:${i}`);if(e.output&&t.push("-o",e.output),e.outputNaPlaceholder&&t.push("--output-na-placeholder",e.outputNaPlaceholder),e.restrictFilenames&&t.push("--restrict-filenames"),e.noRestrictFilenames&&t.push("--no-restrict-filenames"),e.windowsFilenames&&t.push("--windows-filenames"),e.noWindowsFilenames&&t.push("--no-windows-filenames"),e.trimFileNames&&t.push("--trim-file-names",e.trimFileNames.toString()),e.noOverwrites&&t.push("--no-overwrites"),e.forceOverwrites&&t.push("--force-overwrites"),e.noForceOverwrites&&t.push("--no-force-overwrites"),e.continue&&t.push("--continue"),e.noContinue&&t.push("--no-continue"),e.part&&t.push("--part"),e.noPart&&t.push("--no-part"),e.mtime&&t.push("--mtime"),e.noMtime&&t.push("--no-mtime"),e.writeDescription&&t.push("--write-description"),e.noWriteDescription&&t.push("--no-write-description"),e.writeInfoJson&&t.push("--write-info-json"),e.noWriteInfoJson&&t.push("--no-write-info-json"),e.writePlaylistMetafiles&&t.push("--write-playlist-metafiles"),e.noWritePlaylistMetafiles&&t.push("--no-write-playlist-metafiles"),e.cleanInfoJson&&t.push("--clean-info-json"),e.noCleanInfoJson&&t.push("--no-clean-info-json"),e.writeComments&&t.push("--write-comments"),e.noWriteComments&&t.push("--no-write-comments"),e.loadInfoJson&&t.push("--load-info-json",e.loadInfoJson.toString()),e.cookies&&t.push("--cookies",e.cookies),e.noCookies&&t.push("--no-cookies"),e.cookiesFromBrowser&&t.push("--cookies-from-browser",e.cookiesFromBrowser),e.noCookiesFromBrowser&&t.push("--no-cookies-from-browser"),e.cacheDir&&t.push("--cache-dir",e.cacheDir),e.noCacheDir&&t.push("--no-cache-dir"),e.rmCacheDir&&t.push("--rm-cache-dir"),e.writeThumbnail&&t.push("--write-thumbnail"),e.noWriteThumbnails&&t.push("--no-write-thumbnails"),e.writeAllThumbnails&&t.push("--write-all-thumbnails"),e.listThumbnails&&t.push("--list-thumbnails"),e.writeLink&&t.push("--write-link"),e.writeUrlLink&&t.push("--write-url-link"),e.writeWeblocLink&&t.push("--write-webloc-link"),e.writeDesktopLink&&t.push("--write-desktop-link"),e.quiet&&t.push("--quiet"),e.noQuiet&&t.push("--no-quiet"),e.noWarnings&&t.push("--no-warnings"),e.simulate&&t.push("--simulate"),e.noSimulate&&t.push("--no-simulate"),e.ignoreNoFormatsError&&t.push("--ignore-no-formats-error"),e.noIgnoreNoFormatsError&&t.push("--no-ignore-no-formats-error"),e.skipDownload&&t.push("--skip-download"),e.print&&t.push("--print",e.print),e.printToFile&&t.push("--print-to-file",e.printToFile),e.dumpJson&&t.push("--dump-json"),e.dumpSingleJson&&t.push("--dump-single-json"),e.forceWriteArchive&&t.push("--force-write-archive"),e.newline&&t.push("--newline"),e.noProgress&&t.push("--no-progress"),e.progress&&t.push("--progress"),e.consoleTitle&&t.push("--console-title"),e.progressTemplate&&t.push("--progress-template",e.progressTemplate),e.progressDelta&&t.push("--progress-delta",e.progressDelta.toString()),e.verbose&&t.push("--verbose"),e.dumpPages&&t.push("--dump-pages"),e.writePages&&t.push("--write-pages"),e.printTraffic&&t.push("--print-traffic"),e.encoding&&t.push("--encoding",e.encoding),e.legacyServerConnect&&t.push("--legacy-server-connect"),e.noCheckCertificates&&t.push("--no-check-certificates"),e.preferInsecure&&t.push("--prefer-insecure"),e.addHeaders)for(let[s,i]of Object.entries(e.addHeaders))t.push("--add-header",`${s}:${i}`);if(e.headers)for(let[s,i]of Object.entries(e.headers))t.push("--add-header",`${s}:${i}`);if(e.bidiWorkaround&&t.push("--bidi-workaround"),e.sleepRequests&&t.push("--sleep-requests",e.sleepRequests.toString()),e.sleepInterval&&t.push("--sleep-interval",e.sleepInterval.toString()),e.maxSleepInterval&&t.push("--max-sleep-interval",e.maxSleepInterval.toString()),e.sleepSubtitles&&t.push("--sleep-subtitles",e.sleepSubtitles.toString()),e.format&&t.push("-f",e.format),e.formatSort&&e.formatSort.length>0&&t.push("--format-sort",e.formatSort.join(",")),e.formatSortForce&&t.push("--format-sort-force"),e.noFormatSortForce&&t.push("--no-format-sort-force"),e.videoMultiStreams&&t.push("--video-multistreams"),e.noVideoMultiStreams&&t.push("--no-video-multistreams"),e.audioMultiStreams&&t.push("--audio-multistreams"),e.noAudioMultiStreams&&t.push("--no-audio-multistreams"),e.preferFreeFormats&&t.push("--prefer-free-formats"),e.noPreferFreeFormats&&t.push("--no-prefer-free-formats"),e.checkFormats&&t.push("--check-formats"),e.checkAllFormats&&t.push("--check-all-formats"),e.noCheckFormats&&t.push("--no-check-formats"),e.listFormats&&t.push("--list-formats"),e.mergeOutputFormat&&t.push("--merge-output-format",e.mergeOutputFormat),e.writeSubs&&t.push("--write-subs"),e.noWriteSubs&&t.push("--no-write-subs"),e.writeAutoSubs&&t.push("--write-auto-subs"),e.writeAllSubs&&t.push("--all-subs"),e.listSubs&&t.push("--list-subs"),e.subFormat&&t.push("--sub-format",e.subFormat),e.subLangs&&e.subLangs.length>0&&t.push("--sub-langs",e.subLangs.join(",")),e.username&&t.push("--username",e.username),e.password&&t.push("--password",e.password),e.twoFactor&&t.push("--twofactor",e.twoFactor),e.netrc&&t.push("--netrc"),e.videoPassword&&t.push("--video-password",e.videoPassword),e.apMso&&t.push("--ap-mso",e.apMso),e.apUsername&&t.push("--ap-username",e.apUsername),e.apPassword&&t.push("--ap-password",e.apPassword),e.netrcLocation&&t.push("--netrc-location",e.netrcLocation),e.netrcCmd&&t.push("--netrc-cmd",e.netrcCmd),e.apListMso&&t.push("--ap-list-mso"),e.clientCertificate&&t.push("--client-certificate",e.clientCertificate),e.clientCertificateKey&&t.push("--client-certificate-key",e.clientCertificateKey),e.clientCertificatePassword&&t.push("--client-certificate-password",e.clientCertificatePassword),e.extractorRetries!==void 0&&t.push("--extractor-retries",e.extractorRetries.toString()),e.allowDynamicMpd&&t.push("--allow-dynamic-mpd"),e.ignoreDynamicMpd&&t.push("--ignore-dynamic-mpd"),e.hlsSplitDiscontinuity&&t.push("--hls-split-discontinuity"),e.noHlsSplitDiscontinuity&&t.push("--no-hls-split-discontinuity"),e.extractorArgs)for(let[s,i]of Object.entries(e.extractorArgs))t.push("--extractor-args",`${s}:${i.join(" ")}`);if(e.playlistStart!==void 0&&t.push("--playlist-start",e.playlistStart.toString()),e.playlistEnd!==void 0&&t.push("--playlist-end",e.playlistEnd.toString()),e.matchTitle&&t.push("--match-title",e.matchTitle),e.rejectTitle&&t.push("--reject-title",e.rejectTitle),e.includeAds&&t.push("--include-ads"),e.breakOnReject&&t.push("--break-on-reject"),e.noDownload&&t.push("--no-download"),e.playlistReverse&&t.push("--playlist-reverse"),e.geoBypass&&t.push("--geo-bypass"),e.geoBypassCountry&&t.push("--geo-bypass-country",e.geoBypassCountry),e.geoBypassIpBlock&&t.push("--geo-bypass-ip-block",e.geoBypassIpBlock),e.convertThumbnails&&t.push("--convert-thumbnails",e.convertThumbnails),e.writeLink&&t.push("--write-link"),e.writeUrlLink&&t.push("--write-url-link"),e.writeWeblocLink&&t.push("--write-webloc-link"),e.writeLnkLink&&t.push("--write-lnk-link"),e.referer&&t.push("--referer",e.referer),e.userAgent&&t.push("--user-agent",e.userAgent),e.extractAudio&&t.push("--extract-audio"),e.audioFormat&&t.push("--audio-format",e.audioFormat),e.audioQuality&&t.push("--audio-quality",e.audioQuality),e.remuxVideo&&t.push("--remux-video",e.remuxVideo),e.recodeVideo&&t.push("--recode-video",e.recodeVideo),e.postprocessorArgs)for(let[s,i]of Object.entries(e.postprocessorArgs))t.push("--postprocessor-args",`${s}:${i.join(" ")}`);if(e.keepVideo&&t.push("--keep-video"),e.noKeepVideo&&t.push("--no-keep-video"),e.postOverwrites&&t.push("--post-overwrites"),e.noPostOverwrites&&t.push("--no-post-overwrites"),e.embedSubs&&t.push("--embed-subs"),e.noEmbedSubs&&t.push("--no-embed-subs"),e.embedThumbnail&&t.push("--embed-thumbnail"),e.noEmbedThumbnail&&t.push("--no-embed-thumbnail"),e.embedMetadata&&t.push("--embed-metadata"),e.noEmbedMetadata&&t.push("--no-embed-metadata"),e.embedChapters&&t.push("--embed-chapters"),e.noEmbedChapters&&t.push("--no-embed-chapters"),e.embedInfoJson&&t.push("--embed-info-json"),e.noEmbedInfoJson&&t.push("--no-embed-info-json"),e.parseMetadata)for(let[s,i]of Object.entries(e.parseMetadata))t.push("--parse-metadata",`${s}:${i}`);if(e.replaceInMetadata)for(let[s,[i,n]]of Object.entries(e.replaceInMetadata))t.push("--replace-in-metadata",`${s} ${i} ${n}`);if(e.xattrs&&t.push("--xattrs"),e.concatPlaylist&&t.push("--concat-playlist",e.concatPlaylist),e.fixup&&t.push("--fixup",e.fixup),e.ffmpegLocation&&t.push("--ffmpeg-location",e.ffmpegLocation),e.exec&&t.push("--exec",e.exec),e.noExec&&t.push("--no-exec"),e.convertSubs&&t.push("--convert-subs",e.convertSubs),e.convertThumbnails&&t.push("--convert-thumbnails",e.convertThumbnails),e.splitChapters&&t.push("--split-chapters"),e.noSplitChapters&&t.push("--no-split-chapters"),e.removeChapters&&t.push("--remove-chapters",e.removeChapters),e.noRemoveChapters&&t.push("--no-remove-chapters"),e.forceKeyframesAtCuts&&t.push("--force-keyframes-at-cuts"),e.noForceKeyframesAtCuts&&t.push("--no-force-keyframes-at-cuts"),e.usePostProcessor&&e.usePostProcessor.length>0)for(let s of e.usePostProcessor)t.push("--use-postprocessor",s);return e.sponsorblockMark&&e.sponsorblockMark.length>0&&t.push("--sponsorblock-mark",e.sponsorblockMark.join(",")),e.sponsorblockRemove&&e.sponsorblockRemove.length>0&&t.push("--sponsorblock-remove",e.sponsorblockRemove.join(",")),e.sponsorblockChapterTitle&&t.push("--sponsorblock-chapter-title",e.sponsorblockChapterTitle),e.noSponsorblock&&t.push("--no-sponsorblock"),e.sponsorblockApi&&t.push("--sponsorblock-api",e.sponsorblockApi),e.additionalOptions&&e.additionalOptions.length>0&&t.push(...e.additionalOptions),e.rawArgs&&e.rawArgs.length>0&&t.push(...e.rawArgs),t}function oe(e){let t=[],r=e.split(` | ||
| `).slice(1);for(let s of r){let i=s.match(/(\d+)\s+(\S+)\s+(\S+)\s+(https:\/\/[\S]+)/);i&&t.push({id:parseInt(i[1],10),width:i[2]==="unknown"?"unknown":parseInt(i[2],10),height:i[3]==="unknown"?"unknown":parseInt(i[3],10),url:i[4]})}return t}var ae={"2160p":"bv*[height<=2160]","1440p":"bv*[height<=1440]","1080p":"bv*[height<=1080]","720p":"bv*[height<=720]","480p":"bv*[height<=480]","360p":"bv*[height<=360]","240p":"bv*[height<=240]","144p":"bv*[height<=133]",highest:"bv*",lowest:"wv*"},ue=["audioonly","videoonly","audioandvideo","mergevideo"];function T(e){let t,r,s;if(!e)return[];if(typeof e=="string"&&!ue.includes(e))return["-f",e];if(typeof e=="string"&&ue.includes(e)&&(t=e),Object.keys(e).length===0||!e||typeof e!="object")return["-f","bv*+ba"];typeof e=="object"&&(t=e.filter,r=e.type,s=e.quality);let i=[];return t==="audioonly"&&(i=["-x","--audio-format",r||"mp3","--audio-quality",s?s.toString():"5"]),t==="videoonly"&&(i=["-f",(s?ae[s]:"bv*")+"[acodec=none]"]),t==="audioandvideo"&&(i=["-f",(s=="lowest"?"w*":"b*")+"[vcodec!=none][acodec!=none][ext="+(r||"mp4")+"]"]),t==="mergevideo"&&(i=["-f",`${s?ae[s]:"bv*"}+ba`],r&&i.push("--merge-output-format",r)),i}function J(e){if(!e||typeof e=="string")return"video/mp4";let{filter:t,type:r}=e;switch(t){case"videoonly":case"audioandvideo":switch(r){case"mp4":return"video/mp4";case"webm":return"video/webm";default:return"video/mp4"}case"audioonly":switch(r){case"aac":return"audio/aac";case"flac":return"audio/flac";case"mp3":return"audio/mp3";case"m4a":return"audio/mp4";case"opus":return"audio/opus";case"vorbis":return"audio/vorbis";case"wav":return"audio/wav";case"alac":return"audio/mp4";default:return"audio/mpeg"}case"mergevideo":switch(r){case"webm":return"video/webm";case"mkv":return"video/x-matroska";case"ogg":return"video/ogg";case"flv":return"video/x-flv";default:return"video/mp4"}}}function Y(e){if(!e||typeof e=="string")return"mp4";let{filter:t,type:r}=e;return r||(t==="audioonly"?"mp3":"mp4")}function le(e){if(!e?.extractAudio)return null;switch(e.audioFormat||"mp3"){case"aac":return"audio/aac";case"flac":return"audio/flac";case"mp3":return"audio/mpeg";case"m4a":return"audio/mp4";case"opus":return"audio/opus";case"vorbis":return"audio/vorbis";case"wav":return"audio/wav";case"alac":return"audio/mp4";default:return"audio/mpeg"}}function fe(e){return e?.extractAudio?e.audioFormat||"mp3":null}var $="~ytdlp-progress-%(progress)#j";function q(e,t=2){let r=Number(e);if(r===0||isNaN(r))return r+" Bytes";let s=1024,i=t<0?0:t,n=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],o=Math.floor(Math.log(r)/Math.log(s));return parseFloat((r/Math.pow(s,o)).toFixed(i))+" "+n[o]}function Ne(e,t,r){let s=Math.pow(r||10,t);return Math.round(e*s)/s}function je(e){e=Number(e);let t=Math.floor(e/3600),r=Math.floor(e%3600/60),s=Math.floor(e%3600%60),i=t>0?t+(t==1?" hour, ":" hours, "):"",n=r>0?r+(r==1?" minute, ":" minutes, "):"",o=s>=0?s+(s==1?" second":" seconds"):"";return i+n+o}function m(e){try{if(!e.includes("~ytdlp-progress-"))throw new Error;let t=e.trim().replace("~ytdlp-progress-","");if(!t)throw new Error;let r=JSON.parse(t),s=l=>{if(l==null||l==="NA")return;let f=Number(l);return isNaN(f)?void 0:f},i=s(r.downloaded_bytes),n=s(r.total_bytes)??s(r.total_bytes_estimate),o=s(r.speed),a=s(r.eta),u=i!==void 0&&n!==void 0&&n>0?Ne(100*i/n,2):void 0;return{filename:r.filename,status:r.status,downloaded:i,downloaded_str:i!==void 0?q(i):void 0,total:n,total_str:n!==void 0?q(n):void 0,speed:o,speed_str:o!==void 0?q(o)+"/s":void 0,eta:a,eta_str:a!==void 0?je(a):void 0,percentage:u,percentage_str:u!==void 0?u+"%":void 0}}catch{return}}var N=c(require("path")),E=c(require("fs"));var Le=c(require("https")),Ke=c(require("http")),Q=require("url"),g=c(require("fs"));function G(e,t={}){return new Promise((r,s)=>{let o=(new Q.URL(e).protocol==="https:"?Le:Ke).get(e,t,a=>{if(a.statusCode>=300&&a.statusCode<400&&a.headers.location){let u=new Q.URL(a.headers.location,e).toString();G(u,t).then(r).catch(s);return}r(a)});o.on("error",s),o.setTimeout(3e4,()=>{o.destroy(),s(new Error("Request timed out"))})})}async function S(e,t){try{let r=g.createWriteStream(t),s=await G(e);if(s.statusCode!==200)throw r.close(),g.unlinkSync(t),new Error(`Failed to download file: ${s.statusCode} ${s.statusMessage}`);let i=parseInt(s.headers["content-length"]||"0",10),n=0;return s.on("data",o=>{n+=o.length;let a=n/i*100;process.stdout.write(`Progress: ${Math.round(a)}%\r`)}),s.pipe(r),new Promise((o,a)=>{r.on("finish",()=>{r.close(),console.log(` | ||
| Download complete!`),o()}),r.on("error",u=>{r.close(),g.unlinkSync(t),a(u)}),s.on("error",u=>{r.close(),g.unlinkSync(t),a(u)})})}catch(r){throw g.existsSync(t)&&g.unlinkSync(t),r}}async function de(e,t={}){let r=await G(e,t);if(r.statusCode!==200)throw new Error(`Failed to fetch text: ${r.statusCode} ${r.statusMessage}`);return new Promise((s,i)=>{let n="";r.setEncoding("utf8"),r.on("data",o=>{n+=o}),r.on("end",()=>s(n)),r.on("error",i)})}var he=c(require("fs")),_=c(require("path"));function Me(e){let t=e;for(;;){if(he.existsSync(_.join(t,"package.json")))return t;let r=_.dirname(t);if(r===t)return e;t=r}}var ce=Me(__dirname),w=_.join(ce,"bin"),ut=_.join(ce,"package.json");var We="https://github.com/iqbal-rashed/ytdlp-nodejs/releases/download/ffmpeg-latest",H={win32:{x64:["win-x64-ffmpeg.exe","win-x64-ffprobe.exe"],ia32:["win-ia32-ffmpeg.exe","win-ia32-ffprobe.exe"],arm64:["win-arm64-ffmpeg.exe","win-arm64-ffprobe.exe"]},linux:{x64:["linux-x64-ffmpeg","linux-x64-ffprobe"],arm64:["linux-arm64-ffmpeg","linux-arm64-ffprobe"]},darwin:{x64:["macos-x64-ffmpeg","macos-x64-ffprobe"],arm64:["macos-arm64-ffmpeg","macos-arm64-ffprobe"]},android:{arm64:["linux-arm64-ffmpeg","linux-arm64-ffprobe"]}};function me(){let e=process.platform,t=process.arch;if(!H[e]||!H[e][t])throw new Error(`No FFmpeg build available for platform: ${e}, architecture: ${t}`);return H[e][t]}async function Z(e){let t=e||w,r=F();if(r)return r;try{let s=me();if(!s.length)throw new Error;let i=s.map(o=>`${We}/${o}`),n=s.map(o=>N.default.join(t,String(o.split("-").pop())));E.default.existsSync(t)||E.default.mkdirSync(t,{recursive:!0}),console.log("Downloading FFmpeg and FFprobe...");for(let o=0;o<s.length;o++){let a=i[o],u=n[o];console.log("Downloading...",N.default.basename(a)),await S(a,u)}if(process.platform!=="win32")for(let o of n)E.default.chmodSync(o,493);return F()}catch(s){throw console.error(`Download failed: ${s}`),s}}function F(){try{let e=me();if(!e.length)throw new Error;let t=N.default.join(w,String(e[0].split("-").pop()));if(!E.default.existsSync(t))throw new Error("FFmpeg binary not found. Please download it first.");return t}catch{return}}var p=c(require("fs")),I=c(require("path"));var pe=c(require("crypto")),ge="https://github.com/yt-dlp/yt-dlp/releases/latest/download",j={win32:{x64:"yt-dlp.exe",ia32:"yt-dlp_x86.exe"},linux:{x64:"yt-dlp",armv7l:"yt-dlp_linux_armv7l",aarch64:"yt-dlp_linux_aarch64",arm64:"yt-dlp"},darwin:{x64:"yt-dlp_macos",arm64:"yt-dlp_macos"},android:{arm64:"yt-dlp"}};function Ue(){let e=process.platform,t=process.arch;if(!j[e]||!j[e][t])throw new Error(`No yt-dlp build available for ${e} ${t}`);return j[e][t]}async function L(e){let t=e||w,r=Ue(),s=`${ge}/${r}`,i=I.join(t,r);if(p.existsSync(i))return i;console.log("Downloading yt-dlp...",s),p.existsSync(t)||p.mkdirSync(t,{recursive:!0});try{return await S(s,i),console.log(`yt-dlp downloaded successfully to: ${i}`),process.platform!=="win32"&&p.chmodSync(i,493),i}catch(o){throw console.error(`Download failed: ${o}`),o}}async function ze(e){return new Promise((t,r)=>{let s=pe.default.createHash("sha256"),i=p.createReadStream(e);i.on("data",n=>s.update(n)),i.on("end",()=>t(s.digest("hex"))),i.on("error",r)})}async function Je(e){try{let s=(await de(`${ge}/SHA2-256SUMS`)).split(/\r?\n/).find(n=>n.includes(e));if(!s)return;let[i]=s.trim().split(/\s+/);return i||void 0}catch{return}}async function X(e){let t=await L(e),r=I.basename(t),s=await Je(r);if(!s)return{path:t,verified:!1};let i=await ze(t);if(i.toLowerCase()!==s.toLowerCase())throw new Error(`Checksum mismatch for ${r}. Expected ${s}, got ${i}`);return{path:t,verified:!0,checksum:s}}function R(){let e=process.platform,t=process.arch;try{let r=j[e][t],s=I.join(w,r);if(!p.existsSync(s))throw new Error("Ytdlp binary not found. Please download it first.");return s}catch{return}}function K(e){return e.replace(/~ytdlp-progress-\{[\s\S]*?\}\n?/g,"").split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0).filter(t=>!t.includes("__YTDLP_FILEPATH__:")).filter(t=>!t.includes("__YTDLP_VIDEO_INFO__:")).filter(t=>!t.includes("__YTDLP_BEFORE_DL__:")).join(` | ||
| `)}function M(e){let t=[],r=e.split(/\r?\n/);for(let s of r){let i=s.trim();if(i.startsWith("__YTDLP_VIDEO_INFO__:")){let n=i.replace("__YTDLP_VIDEO_INFO__:","").trim();try{let o=n.replace(/:"N\/A"/g,":null").replace(/:"NA"/g,":null").replace(/:""/g,':"NA"'),a=JSON.parse(o),u={};for(let[l,f]of Object.entries(a))if(f==="NA")u[l]=null;else if(typeof f=="string"&&f==="N/A")u[l]=null;else if((l.includes("_count")||l.includes("_timestamp")||l==="autonumber"||l==="video_autonumber"||l==="n_entries"||l==="playlist_count"||l==="release_year"||l==="start_time"||l==="end_time"||l==="epoch"||l==="duration"||l==="age_limit")&&typeof f=="string"){let d=Number(f);u[l]=isNaN(d)?null:d}else(l==="is_live"||l==="was_live"||l==="channel_is_verified")&&typeof f=="string"?u[l]=f==="true"||f==="True":(l==="categories"||l==="tags"||l==="creators"||l==="cast")&&typeof f=="string"?f==="NA"||f==="N/A"||f===""?u[l]=null:u[l]=f.split(",").map(d=>d.trim()):u[l]=f;t.push(u)}catch{}}}return t}function b(e){let t=e.trim();if(!t.startsWith("__YTDLP_BEFORE_DL__:"))return null;let r=t.replace("__YTDLP_BEFORE_DL__:","").trim();try{let s=r.replace(/:"N\/A"/g,":null").replace(/:"NA"/g,":null").replace(/:""/,':"NA"'),i=JSON.parse(s),n={};for(let[o,a]of Object.entries(i))if(a==="NA"||a==="N/A")n[o]=null;else if((o.includes("_count")||o.includes("_timestamp")||o==="autonumber"||o==="video_autonumber"||o==="n_entries"||o==="playlist_count"||o==="release_year"||o==="start_time"||o==="end_time"||o==="epoch"||o==="duration"||o==="age_limit")&&typeof a=="string"){let u=Number(a);n[o]=isNaN(u)?null:u}else(o==="is_live"||o==="was_live"||o==="channel_is_verified")&&typeof a=="string"?n[o]=a==="true"||a==="True":(o==="categories"||o==="tags"||o==="creators"||o==="cast")&&typeof a=="string"?a==="NA"||a==="N/A"||a===""?n[o]=null:n[o]=a.split(",").map(u=>u.trim()):n[o]=a;return n}catch{return null}}var be=require("events");function we({url:e,options:t,ffmpegPath:r,withProgressTemplate:s,extra:i}){let n=C(t||{});return r&&n.push("--ffmpeg-location",r),s&&n.push("--progress-template",$),i&&i.length>0&&n.push(...i),e&&n.push("--",e),n}var ee=c(require("fs")),P=class extends be.EventEmitter{constructor(r,s){super();this.binaryPath="";this.videoUrl="";this.extraArgs={};this.rawArgs=[];this.videoUrl=r,this.binaryPath=s?.binaryPath||R()||"",this.ffmpegPath=s?.ffmpegPath||F(),(!this.binaryPath||!ee.default.existsSync(this.binaryPath))&&console.error(new Error("yt-dlp binary not found. Please install yt-dlp or specify correct binaryPath in options.")),this.ffmpegPath&&!ee.default.existsSync(this.ffmpegPath)&&console.error(new Error(`FFmpeg binary not found at: ${this.ffmpegPath}. Please install FFmpeg or specify correct ffmpegPath.`))}setBinaryPath(r){return this.binaryPath=r,this}setFfmpegPath(r){return this.ffmpegPath=r,this}format(r){return this.formatValue=r,this}filter(r){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={...s,filter:r},this}quality(r){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={filter:this.formatValue,...s,quality:r},this}type(r){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={filter:this.formatValue,...s,type:r},this}options(r){return this.extraArgs={...this.extraArgs,...r},this}rateLimit(r){return this.extraArgs.limitRate=r,this}cookies(r){return this.extraArgs.cookies=r,this}cookiesFromBrowser(r){return this.extraArgs.cookiesFromBrowser=r,this}proxy(r){return this.extraArgs.proxy=r,this}addOption(r,s){return this.extraArgs[r]=s,this}addArgs(...r){return this.rawArgs.push(...r),this}extractAudio(r){return this.extraArgs.extractAudio=!0,r&&(this.extraArgs.audioFormat=r),this}audioFormat(r){return this.extraArgs.audioFormat=r,this}audioQuality(r){return this.extraArgs.audioQuality=r,this}embedThumbnail(){return this.extraArgs.embedThumbnail=!0,this}embedSubs(){return this.extraArgs.embedSubs=!0,this}embedMetadata(){return this.extraArgs.embedMetadata=!0,this}writeSubs(){return this.extraArgs.writeSubs=!0,this}writeAutoSubs(){return this.extraArgs.writeAutoSubs=!0,this}subLangs(r){return this.extraArgs.subLangs=r,this}writeThumbnail(){return this.extraArgs.writeThumbnail=!0,this}username(r){return this.extraArgs.username=r,this}password(r){return this.extraArgs.password=r,this}playlistStart(r){return this.extraArgs.playlistStart=r,this}playlistEnd(r){return this.extraArgs.playlistEnd=r,this}playlistItems(r){return this.extraArgs.playlistItems=r,this}buildFormatArgs(){return this.formatValue?T(this.formatValue):[]}buildBaseArgs(r=[]){if(!this.videoUrl)throw new Error("URL is required.");let s=this.buildFormatArgs();return we({url:this.videoUrl,options:this.extraArgs,ffmpegPath:this.ffmpegPath,withProgressTemplate:!0,extra:[...s,...r,...this.rawArgs]})}debugPrint(r=!0){return this.extraArgs.debugPrintCommandLine=r,this}getCommand(){let r=this.buildArgs();return`${this.binaryPath} ${r.join(" ")}`}printDebugCommandLine(r){if(this.extraArgs.debugPrintCommandLine){let s=`${this.binaryPath} ${r.join(" ")}`;console.error(`[ytdlp-nodejs] Command: ${s}`)}}validateBinaryPath(){if(!this.binaryPath)throw new Error("Binary path is required. Use .setBinaryPath() or pass it in constructor.")}kill(r){return this.process?.kill(r)??!1}get pid(){return this.process?.pid}};var ye=["id","title","fulltitle","ext","alt_title","description","display_id","uploader","uploader_id","uploader_url","license","creators","creator","timestamp","upload_date","release_timestamp","release_date","release_year","modified_timestamp","modified_date","channel","channel_id","channel_url","channel_follower_count","channel_is_verified","location","duration","duration_string","view_count","concurrent_view_count","like_count","dislike_count","repost_count","average_rating","comment_count","save_count","age_limit","live_status","is_live","was_live","playable_in_embed","availability","media_type","start_time","end_time","extractor","extractor_key","epoch","autonumber","video_autonumber","n_entries","playlist_id","playlist_title","playlist","playlist_count","playlist_index","playlist_autonumber","playlist_uploader","playlist_uploader_id","playlist_channel","playlist_channel_id","playlist_webpage_url","webpage_url","webpage_url_basename","webpage_url_domain","original_url","categories","tags","cast","filepath"];function Ye(){return`after_move:__YTDLP_VIDEO_INFO__:{${ye.map(t=>`"${t}":%(${t}|null)j`).join(",")}}`}function B(){return`before_dl:__YTDLP_BEFORE_DL__:{${ye.map(t=>`"${t}":%(${t}|null)j`).join(",")}}`}function W(){return["--print",Ye(),"--progress","--newline"]}var xe=require("child_process"),A=class extends P{constructor(t,r){super(t,r),this.on("error",()=>{})}on(t,r){return super.on(t,r)}once(t,r){return super.once(t,r)}emit(t,...r){return super.emit(t,...r)}output(t){return this.outputDir=t,this}setOutputTemplate(t){return this.outputPath=t,this}skipDownload(){return this.extraArgs.skipDownload=!0,this}buildArgs(){let t={...this.extraArgs};this.outputDir&&(t.output=`${this.outputDir}/%(title)s.%(ext)s`),this.outputPath&&(t.output=this.outputPath);let r=this.extraArgs;this.extraArgs=t;let s=[...W()];this.listenerCount("beforeDownload")>0&&s.unshift("--print",B());let i=this.buildBaseArgs(s);return this.extraArgs=r,i}run(){return this.resultPromise?this.resultPromise:(this.resultPromise=new Promise((t,r)=>{try{this.validateBinaryPath();let s=this.buildArgs(),i=`${this.binaryPath} ${s.join(" ")}`;this.printDebugCommandLine(s),this.process=(0,xe.spawn)(this.binaryPath,s),this.emit("start",i);let n="",o="";this.process.stdout?.on("data",a=>{let u=a.toString();n+=u,this.emit("stdout",u);let l=b(u);l&&this.emit("beforeDownload",l);let f=m(u);f&&this.emit("progress",f)}),this.process.stderr?.on("data",a=>{let u=a.toString();o+=u,this.emit("stderr",u);let l=m(u);l&&this.emit("progress",l)}),this.process.on("error",a=>{this.emit("error",a),r(a)}),this.process.on("close",a=>{if(a!==0&&a!==null){let d=new Error(`yt-dlp exited with code ${a}: ${o}`);this.emit("error",d),r(d);return}let u=K(n),l=M(n),f={output:u,filePaths:l.map(d=>d?.filepath??"").filter(Boolean),info:l,stderr:o};this.emit("finish",f),t(f)})}catch(s){r(s)}}),this.resultPromise)}then(t,r){return this.run().then(t,r)}catch(t){return this.run().catch(t)}finally(t){return this.run().finally(t)}};function Pe(e,t){return new A(e,t)}var ve=require("stream");var Fe=require("child_process"),D=class extends P{constructor(r,s){super(r,s);this.totalBytes=0;this.started=!1;this.on("error",()=>{})}on(r,s){return super.on(r,s)}once(r,s){return super.once(r,s)}emit(r,...s){return super.emit(r,...s)}buildArgs(){let r=["-o","-","--no-playlist","--progress","--no-quiet"];return this.listenerCount("beforeDownload")>0&&r.push("--print",B()),this.buildBaseArgs(r)}startStream(){if(this.started)return this.passThrough;this.validateBinaryPath(),this.started=!0,this.passThrough=new ve.PassThrough;let r=this.buildArgs(),s=`${this.binaryPath} ${r.join(" ")}`;return this.printDebugCommandLine(r),this.process=(0,Fe.spawn)(this.binaryPath,r,{shell:!1}),this.emit("start",s),this.process.stdout?.on("data",i=>{this.totalBytes+=i.length,this.passThrough.write(i),this.emit("data",i)}),this.process.stderr?.on("data",i=>{let n=i.toString(),o=b(n);o&&this.emit("beforeDownload",o);let a=m(n);a&&this.emit("progress",a)}),this.process.on("error",i=>{this.emit("error",i),this.passThrough.destroy(i)}),this.process.on("close",i=>{if(i!==0&&i!==null){let n=new Error(`yt-dlp exited with code ${i}`);this.emit("error",n),this.passThrough.destroy(n)}else this.passThrough.end(),this.emit("end")}),this.passThrough}pipe(r,s){let i=Date.now(),n=this.startStream();return new Promise((o,a)=>{n.pipe(r,s),r.on("finish",()=>{o({bytes:this.totalBytes,duration:Date.now()-i})}),r.on("error",a),this.passThrough.on("error",a)})}pipeAsync(r,s){return this.pipe(r,s)}async toBuffer(){let r=[];return new Promise((s,i)=>{let n=this.startStream();n.on("data",o=>{r.push(o)}),n.on("end",()=>{s(Buffer.concat(r))}),n.on("error",i)})}getStream(){return this.startStream()}};function Ae(e,t){return new D(e,t)}var De=require("stream");var te=require("child_process"),y=class extends P{constructor(r,s){super(r,s);this.totalBytes=0;this.started=!1;this.output="";this.on("error",()=>{})}on(r,s){return super.on(r,s)}once(r,s){return super.once(r,s)}emit(r,...s){return super.emit(r,...s)}buildArgs(){let r=[],s=[...W()];return this.listenerCount("beforeDownload")>0&&s.unshift("--print",B()),this.listenerCount("afterDownload")>0&&s.push("--print","after_move:filepath"),this.buildBaseArgs([...r,...s])}startStream(){if(this.started)return this.passThrough;this.validateBinaryPath(),this.started=!0,this.passThrough=new De.PassThrough,this.output="";let r=this.buildArgs();r.includes("--no-playlist")||(r=["--no-playlist",...r]);let s=`${this.binaryPath} ${r.join(" ")}`;return this.printDebugCommandLine(r),this.process=(0,te.spawn)(this.binaryPath,r,{shell:!1}),this.emit("start",s),this.process.stdout?.on("data",i=>{this.totalBytes+=i.length,this.passThrough.write(i),this.emit("data",i);let n=i.toString();this.emit("stdout",n);let o=b(n);o&&(this.beforeDownloadInfo=o,this.emit("beforeDownload",this.beforeDownloadInfo));let a=m(n);a&&this.emit("progress",a)}),this.process.stderr?.on("data",i=>{let n=i.toString();this.emit("stderr",n),this.output+=n;let o=b(n);o&&(this.beforeDownloadInfo=o,this.emit("beforeDownload",this.beforeDownloadInfo));let a=m(n);a&&(this.emit("progress",a),a.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:a.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.on("error",i=>{this.emit("error",i),this.passThrough.destroy(i)}),this.process.on("close",i=>{if(i!==0&&i!==null){let n=new Error(`yt-dlp exited with code ${i}`);this.emit("error",n),this.passThrough.destroy(n)}else this.passThrough.end(),this.emit("end")}),this.passThrough}pipe(r,s){let i=Date.now(),n=this.startStream();return new Promise((o,a)=>{n.pipe(r,s),r.on("finish",()=>{o({bytes:this.totalBytes,duration:Date.now()-i,info:this.afterDownloadInfo,output:this.output})}),r.on("error",a),this.passThrough.on("error",a)})}pipeAsync(r,s){return this.pipe(r,s)}async toBuffer(){let r=[];return new Promise((s,i)=>{let n=this.startStream();n.on("data",o=>{r.push(o)}),n.on("end",()=>{s(Buffer.concat(r))}),n.on("error",i)})}getStream(){return this.startStream()}exec(){return this.resultPromise?this.resultPromise:(this.resultPromise=new Promise((r,s)=>{try{this.validateBinaryPath();let i=this.buildArgs(),n=`${this.binaryPath} ${i.join(" ")}`;this.printDebugCommandLine(i),this.process=(0,te.spawn)(this.binaryPath,i,{shell:!1}),this.emit("start",n);let o="",a="";this.process.stdout?.on("data",u=>{let l=u.toString();o+=l,this.emit("stdout",l);let f=b(l);f&&(this.beforeDownloadInfo=f,this.emit("beforeDownload",this.beforeDownloadInfo)),this.emit("data",u);let d=m(l);d&&(this.emit("progress",d),d.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:d.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.stderr?.on("data",u=>{let l=u.toString();a+=l,this.emit("stderr",l);let f=b(l);f&&(this.beforeDownloadInfo=f,this.emit("beforeDownload",this.beforeDownloadInfo));let d=m(l);d&&(this.emit("progress",d),d.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:d.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.on("error",u=>{this.emit("error",u),s(u)}),this.process.on("close",u=>{let l=K(o),f=M(o),d={stdout:o,stderr:a,exitCode:u,command:n,info:f,output:l,filePaths:f.map(x=>x?.filepath??"").filter(Boolean)};this.emit("complete",d),this.emit("end"),r(d)})}catch(i){s(i)}}),this.resultPromise)}run(){return this.exec()}then(r,s){return this.exec().then(r,s)}catch(r){return this.exec().catch(r)}finally(r){return this.exec().finally(r)}};function ke(e,t){return new y(e,t)}var se=class{constructor(t){this.binaryPath=t?.binaryPath||R()||"",this.ffmpegPath=t?.ffmpegPath||F(),(!this.binaryPath||!re.existsSync(this.binaryPath))&&console.error(new Error("yt-dlp binary not found. Please install yt-dlp or specify correct binaryPath in options.")),this.ffmpegPath&&!re.existsSync(this.ffmpegPath)&&console.error(new Error(`FFmpeg binary not found at: ${this.ffmpegPath}. Please install FFmpeg or specify correct ffmpegPath.`))}async checkInstallationAsync(t){return new Promise((r,s)=>{if(t?.ffmpeg&&!this.ffmpegPath)return s(new Error("FFmpeg path is not set"));let i=(0,k.spawn)(this.binaryPath,["--version"]),n=!1,o=!t?.ffmpeg;i.on("error",()=>n=!1),i.on("exit",a=>{if(n=a===0,t?.ffmpeg){let u=(0,k.spawn)(this.ffmpegPath,["-version"]);u.on("error",()=>o=!1),u.on("exit",l=>{o=l===0,r(n&&o)})}else r(n)})})}checkInstallation(t){if(t?.ffmpeg&&!this.ffmpegPath)throw new Error("FFmpeg path is not set");let r=(0,k.spawnSync)(this.binaryPath,["--version"],{stdio:"ignore"}),s=t?.ffmpeg?(0,k.spawnSync)(this.ffmpegPath,["-version"],{stdio:"ignore"}):{status:0};return r.status===0&&s.status===0}async getInfoAsync(t,r){let s=await this.execAsync(t,{dumpSingleJson:!0,flatPlaylist:!0,...r});return JSON.parse(s.output)}async execAsync(t,r){let s=new y(t,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{onData:i,onProgress:n,onBeforeDownload:o,pipeTo:a,...u}=r||{};return u&&s.options(u),i&&s.on("stdout",i),n&&s.on("progress",n),o&&s.on("beforeDownload",o),a?s.pipe(a):s.exec()}exec(t,r){let s=new y(t,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath});return r&&s.options(r),s}download(t,r){let s=new A(t,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=r||{};return i&&s.format(i),n&&s.options(n),s}async downloadAsync(t,r){let{onProgress:s,beforeDownload:i,...n}=r||{},o=this.download(t,n);s&&o.on("progress",s),i&&o.on("beforeDownload",i);let a=await o.run();return{output:a.output,filePaths:a.filePaths,info:a.info}}stream(t,r){let s=new D(t,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=r||{};return i&&s.format(i),n&&s.options(n),s}execBuilder(t,r){let s=new y(t,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=r||{};return i&&s.format(i),n&&s.options(n),s}async downloadAudio(t,r="mp3",s){let i=["aac","flac","mp3","m4a","opus","vorbis","wav","alac"];if(!i.includes(r))throw new Error(`Invalid audio format: ${r}. Supported: ${i.join(", ")}`);return this.downloadAsync(t,{...s,extractAudio:!0,audioFormat:r})}async downloadVideo(t,r="best",s){let i=["best","2160p","1440p","1080p","720p","480p","360p","240p","144p","highest","lowest"];if(!i.includes(r))throw new Error(`Invalid video quality: ${r}. Supported: ${i.join(", ")}`);let n=r==="best"?"bestvideo+bestaudio/best":`bestvideo[height<=${parseInt(r)||1080}]+bestaudio/best[height<=${parseInt(r)||1080}]`;return this.downloadAsync(t,{...s,format:n})}async getSubtitles(t,r){return(await this.execAsync(t,{...r,listSubs:!0,skipDownload:!0})).output?[]:[]}async getComments(t,r=20,s){let i=await this.execAsync(t,{...s,writeComments:!0,dumpSingleJson:!0,skipDownload:!0,extractorArgs:{youtube:[`max_comments=${r}`,"player_skip=webpage"]}});try{return JSON.parse(i.output).comments||[]}catch{return[]}}async getDirectUrlsAsync(t,r){return(await this.getInfoAsync(t,r)).formats.map(i=>i.url)}async getFormatsAsync(t,r){let s=await this.getInfoAsync(t,r);return{source:"json",info:s,formats:s.formats}}async getThumbnailsAsync(t){return(await this.getInfoAsync(t)).thumbnails}async getTitleAsync(t){return(await this.execAsync(t,{print:"title"})).output.trim()}async getVersionAsync(){return(await this.execAsync("",{printVersion:!0})).output.trim()}async downloadFFmpeg(){return Z()}async getFileAsync(t,r){let s,{onBeforeDownload:i,onProgress:n,filename:o,metadata:a,format:u,...l}=r||{},f=[],d=new Be.PassThrough;d.on("data",v=>f.push(Buffer.from(v)));let x=T(u),U={...l};if(x.length>=2&&x[0]==="-f"&&(U.format=x[1]),x.includes("--merge-output-format")){let v=x.indexOf("--merge-output-format");U.mergeOutputFormat=x[v+1]}await this.execAsync(t,{...U,noPlaylist:!0,pipeTo:d,onProgress:n,onBeforeDownload:v=>{s=v,i?.(v)},output:"-"});let O,z;u&&typeof u=="object"?(O=J(u),z=Y(u)):(O=le(l)||"video/mp4",z=fe(l)||"mp4");let Te=new _e.Blob(f,{type:O}),ie={name:o||`${s?.title||"download"}.${z}`,type:O,size:Te.size,...a};return new File([Buffer.concat(f)],ie.name,{type:ie.type})}async getUrlsAsync(t,r){return(await this.execAsync(t,{...r,print:"urls"})).output.split(` | ||
| `).filter(Boolean)}async updateYtDlpAsync(t){if(t?.preferBuiltIn!==!1&&this.binaryPath)try{await this.execAsync("",{update:!0});let a=await this.getVersionAsync().catch(()=>{});return{method:"built-in",binaryPath:this.binaryPath,version:a}}catch{}let s=t?.outDir||(this.binaryPath?Se.default.dirname(this.binaryPath):void 0);if(t?.verifyChecksum!==!1){let a=await X(s),u=await this.getVersionAsyncUsingBinary(a.path).catch(()=>{});return{method:"download",binaryPath:a.path,version:u,verified:a.verified}}let n=await L(s),o=await this.getVersionAsyncUsingBinary(n).catch(()=>{});return{method:"download",binaryPath:n,version:o,verified:!1}}async getVersionAsyncUsingBinary(t){return new Promise((r,s)=>{let i=(0,k.spawn)(t,["--version"]),n="",o="";i.stdout?.on("data",a=>{n+=a.toString()}),i.stderr?.on("data",a=>{o+=a.toString()}),i.on("close",a=>{a===0?r(n.trim()):s(new Error(`Failed to get version: ${o}`))}),i.on("error",s)})}},qe={downloadFFmpeg:Z,findFFmpegBinary:F,PROGRESS_STRING:$,getContentType:J,getFileExtension:Y,parseFormatOptions:T,stringToProgress:m,createArgs:C,extractThumbnails:oe,downloadFile:S,BIN_DIR:w,downloadYtDlp:L,downloadYtDlpVerified:X,findYtdlpBinary:R};0&&(module.exports={BIN_DIR,Download,Exec,Stream,YtDlp,createDownload,createExec,createStreamBuilder,helpers}); | ||
| "use strict";var Oe=Object.create;var C=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,$e=Object.prototype.hasOwnProperty;var je=(e,r)=>{for(var t in r)C(e,t,{get:r[t],enumerable:!0})},oe=(e,r,t,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Ce(r))!$e.call(e,i)&&i!==t&&C(e,i,{get:()=>r[i],enumerable:!(s=Ve(r,i))||s.enumerable});return e};var c=(e,r,t)=>(t=e!=null?Oe(Ne(e)):{},oe(r||!e||!e.__esModule?C(t,"default",{value:e,enumerable:!0}):t,e)),Le=e=>oe(C({},"__esModule",{value:!0}),e);var rr={};je(rr,{BIN_DIR:()=>y,Download:()=>A,Exec:()=>x,Stream:()=>k,YtDlp:()=>ie,createDownload:()=>Ae,createExec:()=>Ee,createStreamBuilder:()=>Se,helpers:()=>er});module.exports=Le(rr);var D=require("child_process"),se=c(require("fs")),Re=c(require("path")),Be=require("buffer"),Te=require("stream");function N(e){let r=[];if(e.printHelp&&r.push("--help"),e.printVersion&&r.push("--version"),e.update&&r.push("--update"),e.noUpdate&&r.push("--no-update"),e.updateTo&&r.push("--update-to",e.updateTo),e.ignoreErrors&&r.push("--ignore-errors"),e.noAbortOnError&&r.push("--no-abort-on-error"),e.abortOnError&&r.push("--abort-on-error"),e.dumpUserAgent&&r.push("--dump-user-agent"),e.listExtractors&&r.push("--list-extractors"),e.extractorDescriptions&&r.push("--extractor-descriptions"),e.useExtractors&&e.useExtractors.length>0&&r.push("--use-extractors",e.useExtractors.join(",")),e.defaultSearch&&r.push("--default-search",e.defaultSearch),e.ignoreConfig&&r.push("--ignore-config"),e.noConfigLocations&&r.push("--no-config-location"),e.configLocations&&e.configLocations.length>0&&r.push("--config-locations",...e.configLocations),e.pluginDirs&&e.pluginDirs.length>0)for(let s of e.pluginDirs)r.push("--plugin-dirs",s);e.noPluginDirs&&r.push("--no-plugin-dirs"),e.flatPlaylist&&r.push("--flat-playlist"),e.noFlatPlaylist&&r.push("--no-flat-playlist"),e.liveFromStart&&r.push("--live-from-start"),e.noLiveFromStart&&r.push("--no-live-from-start"),e.waitForVideo&&r.push("--wait-for-video",e.waitForVideo.toString()),e.noWaitForVideo&&r.push("--no-wait-for-video"),e.markWatched&&r.push("--mark-watched"),e.noMarkWatched&&r.push("--no-mark-watched"),e.color&&r.push("--color",e.color),e.compatOptions&&e.compatOptions.length>0&&r.push("--compat-options",e.compatOptions.join(",")),e.aliases&&e.aliases.length>0&&r.push("--alias",...e.aliases);let t=e.jsRuntime??"node";if(t&&r.push("--js-runtime",t),e.proxy&&r.push("--proxy",e.proxy),e.socketTimeout&&r.push("--socket-timeout",e.socketTimeout.toString()),e.sourceAddress&&r.push("--source-address",e.sourceAddress),e.impersonate&&e.impersonate.length>0&&r.push("--impersonate",e.impersonate.join(",")),e.listImpersonateTargets&&r.push("--list-impersonate-targets"),e.forceIpv4&&r.push("--force-ipv4"),e.forceIpv6&&r.push("--force-ipv6"),e.enableFileUrls&&r.push("--enable-file-urls"),e.geoVerificationProxy&&r.push("--geo-verification-proxy",e.geoVerificationProxy),e.xff&&r.push("--xff",e.xff),e.playlistItems&&r.push("--playlist-items",e.playlistItems),e.minFilesize&&r.push("--min-filesize",e.minFilesize),e.maxFilesize&&r.push("--max-filesize",e.maxFilesize),e.date&&r.push("--date",e.date),e.dateBefore&&r.push("--datebefore",e.dateBefore),e.dateAfter&&r.push("--dateafter",e.dateAfter),e.matchFilter&&r.push("--match-filter",e.matchFilter),e.noMatchFilters&&r.push("--no-match-filters"),e.breakMatchFilters&&r.push("--break-match-filters",e.breakMatchFilters),e.noBreakMatchFilters&&r.push("--no-break-match-filters"),e.noPlaylist&&r.push("--no-playlist"),e.yesPlaylist&&r.push("--yes-playlist"),e.ageLimit&&r.push("--age-limit",e.ageLimit.toString()),e.downloadArchive&&r.push("--download-archive",e.downloadArchive),e.noDownloadArchive&&r.push("--no-download-archive"),e.maxDownloads&&r.push("--max-downloads",e.maxDownloads.toString()),e.breakOnExisting&&r.push("--break-on-existing"),e.noBreakOnExisting&&r.push("--no-break-on-existing"),e.breakPerInput&&r.push("--break-per-input"),e.noBreakPerInput&&r.push("--break-per-input"),e.skipPlaylistAfterErrors&&r.push("--skip-playlist-after-errors",e.skipPlaylistAfterErrors.toString()),e.concurrentFragments&&r.push("--concurrent-fragments",e.concurrentFragments.toString()),e.limitRate&&r.push("--limit-rate",e.limitRate),e.throttledRate&&r.push("--throttled-rate",e.throttledRate),e.retries&&r.push("--retries",e.retries.toString()),e.fileAccessRetries&&r.push("--file-access-retries",e.fileAccessRetries.toString()),e.fragmentRetries&&r.push("--fragment-retries",e.fragmentRetries.toString()),e.retrySleep&&r.push("--retry-sleep",e.retrySleep.toString()),e.retrySleepByType)for(let[s,i]of Object.entries(e.retrySleepByType))r.push("--retry-sleep",`${s}:${i}`);if(e.skipUnavailableFragments&&r.push("--skip-unavailable-fragments"),e.abortOnUnavailableFragment&&r.push("--abort-on-unavailable-fragment"),e.keepFragments&&r.push("--keep-fragments"),e.noKeepFragments&&r.push("--no-keep-fragments"),e.bufferSize&&r.push("--buffer-size",e.bufferSize),e.resizeBuffer&&r.push("--resize-buffer"),e.noResizeBuffer&&r.push("--no-resize-buffer"),e.httpChunkSize&&r.push("--http-chunk-size",e.httpChunkSize),e.playlistRandom&&r.push("--playlist-random"),e.lazyPlaylist&&r.push("--lazy-playlist"),e.noLazyPlaylist&&r.push("--no-lazy-playlist"),e.xattrSetFilesize&&r.push("--xattr-set-filesize"),e.hlsUseMpegts&&r.push("--hls-use-mpegts"),e.noHlsUseMpegts&&r.push("--no-hls-use-mpegts"),e.downloadSections&&r.push("--download-sections",e.downloadSections.toString()),e.downloader&&r.push("--downloader",e.downloader),e.downloaderArgs&&r.push("--downloader-args",e.downloaderArgs),e.batchFile&&r.push("--batch-file",e.batchFile),e.noBatchFile&&r.push("--no-batch-file"),e.paths)if(typeof e.paths=="string")r.push("--paths",e.paths);else for(let[s,i]of Object.entries(e.paths))r.push("--paths",`${s}:${i}`);if(e.output&&r.push("-o",e.output),e.outputNaPlaceholder&&r.push("--output-na-placeholder",e.outputNaPlaceholder),e.restrictFilenames&&r.push("--restrict-filenames"),e.noRestrictFilenames&&r.push("--no-restrict-filenames"),e.windowsFilenames&&r.push("--windows-filenames"),e.noWindowsFilenames&&r.push("--no-windows-filenames"),e.trimFileNames&&r.push("--trim-file-names",e.trimFileNames.toString()),e.noOverwrites&&r.push("--no-overwrites"),e.forceOverwrites&&r.push("--force-overwrites"),e.noForceOverwrites&&r.push("--no-force-overwrites"),e.continue&&r.push("--continue"),e.noContinue&&r.push("--no-continue"),e.part&&r.push("--part"),e.noPart&&r.push("--no-part"),e.mtime&&r.push("--mtime"),e.noMtime&&r.push("--no-mtime"),e.writeDescription&&r.push("--write-description"),e.noWriteDescription&&r.push("--no-write-description"),e.writeInfoJson&&r.push("--write-info-json"),e.noWriteInfoJson&&r.push("--no-write-info-json"),e.writePlaylistMetafiles&&r.push("--write-playlist-metafiles"),e.noWritePlaylistMetafiles&&r.push("--no-write-playlist-metafiles"),e.cleanInfoJson&&r.push("--clean-info-json"),e.noCleanInfoJson&&r.push("--no-clean-info-json"),e.writeComments&&r.push("--write-comments"),e.noWriteComments&&r.push("--no-write-comments"),e.loadInfoJson&&r.push("--load-info-json",e.loadInfoJson.toString()),e.cookies&&r.push("--cookies",e.cookies),e.noCookies&&r.push("--no-cookies"),e.cookiesFromBrowser&&r.push("--cookies-from-browser",e.cookiesFromBrowser),e.noCookiesFromBrowser&&r.push("--no-cookies-from-browser"),e.cacheDir&&r.push("--cache-dir",e.cacheDir),e.noCacheDir&&r.push("--no-cache-dir"),e.rmCacheDir&&r.push("--rm-cache-dir"),e.writeThumbnail&&r.push("--write-thumbnail"),e.noWriteThumbnails&&r.push("--no-write-thumbnails"),e.writeAllThumbnails&&r.push("--write-all-thumbnails"),e.listThumbnails&&r.push("--list-thumbnails"),e.writeLink&&r.push("--write-link"),e.writeUrlLink&&r.push("--write-url-link"),e.writeWeblocLink&&r.push("--write-webloc-link"),e.writeDesktopLink&&r.push("--write-desktop-link"),e.quiet&&r.push("--quiet"),e.noQuiet&&r.push("--no-quiet"),e.noWarnings&&r.push("--no-warnings"),e.simulate&&r.push("--simulate"),e.noSimulate&&r.push("--no-simulate"),e.ignoreNoFormatsError&&r.push("--ignore-no-formats-error"),e.noIgnoreNoFormatsError&&r.push("--no-ignore-no-formats-error"),e.skipDownload&&r.push("--skip-download"),e.print&&r.push("--print",e.print),e.printToFile&&r.push("--print-to-file",e.printToFile),e.dumpJson&&r.push("--dump-json"),e.dumpSingleJson&&r.push("--dump-single-json"),e.forceWriteArchive&&r.push("--force-write-archive"),e.newline&&r.push("--newline"),e.noProgress&&r.push("--no-progress"),e.progress&&r.push("--progress"),e.consoleTitle&&r.push("--console-title"),e.progressTemplate&&r.push("--progress-template",e.progressTemplate),e.progressDelta&&r.push("--progress-delta",e.progressDelta.toString()),e.verbose&&r.push("--verbose"),e.dumpPages&&r.push("--dump-pages"),e.writePages&&r.push("--write-pages"),e.printTraffic&&r.push("--print-traffic"),e.encoding&&r.push("--encoding",e.encoding),e.legacyServerConnect&&r.push("--legacy-server-connect"),e.noCheckCertificates&&r.push("--no-check-certificates"),e.preferInsecure&&r.push("--prefer-insecure"),e.addHeaders)for(let[s,i]of Object.entries(e.addHeaders))r.push("--add-header",`${s}:${i}`);if(e.headers)for(let[s,i]of Object.entries(e.headers))r.push("--add-header",`${s}:${i}`);if(e.bidiWorkaround&&r.push("--bidi-workaround"),e.sleepRequests&&r.push("--sleep-requests",e.sleepRequests.toString()),e.sleepInterval&&r.push("--sleep-interval",e.sleepInterval.toString()),e.maxSleepInterval&&r.push("--max-sleep-interval",e.maxSleepInterval.toString()),e.sleepSubtitles&&r.push("--sleep-subtitles",e.sleepSubtitles.toString()),e.format&&r.push("-f",e.format),e.formatSort&&e.formatSort.length>0&&r.push("--format-sort",e.formatSort.join(",")),e.formatSortForce&&r.push("--format-sort-force"),e.noFormatSortForce&&r.push("--no-format-sort-force"),e.videoMultiStreams&&r.push("--video-multistreams"),e.noVideoMultiStreams&&r.push("--no-video-multistreams"),e.audioMultiStreams&&r.push("--audio-multistreams"),e.noAudioMultiStreams&&r.push("--no-audio-multistreams"),e.preferFreeFormats&&r.push("--prefer-free-formats"),e.noPreferFreeFormats&&r.push("--no-prefer-free-formats"),e.checkFormats&&r.push("--check-formats"),e.checkAllFormats&&r.push("--check-all-formats"),e.noCheckFormats&&r.push("--no-check-formats"),e.listFormats&&r.push("--list-formats"),e.mergeOutputFormat&&r.push("--merge-output-format",e.mergeOutputFormat),e.writeSubs&&r.push("--write-subs"),e.noWriteSubs&&r.push("--no-write-subs"),e.writeAutoSubs&&r.push("--write-auto-subs"),e.writeAllSubs&&r.push("--all-subs"),e.listSubs&&r.push("--list-subs"),e.subFormat&&r.push("--sub-format",e.subFormat),e.subLangs&&e.subLangs.length>0&&r.push("--sub-langs",e.subLangs.join(",")),e.username&&r.push("--username",e.username),e.password&&r.push("--password",e.password),e.twoFactor&&r.push("--twofactor",e.twoFactor),e.netrc&&r.push("--netrc"),e.videoPassword&&r.push("--video-password",e.videoPassword),e.apMso&&r.push("--ap-mso",e.apMso),e.apUsername&&r.push("--ap-username",e.apUsername),e.apPassword&&r.push("--ap-password",e.apPassword),e.netrcLocation&&r.push("--netrc-location",e.netrcLocation),e.netrcCmd&&r.push("--netrc-cmd",e.netrcCmd),e.apListMso&&r.push("--ap-list-mso"),e.clientCertificate&&r.push("--client-certificate",e.clientCertificate),e.clientCertificateKey&&r.push("--client-certificate-key",e.clientCertificateKey),e.clientCertificatePassword&&r.push("--client-certificate-password",e.clientCertificatePassword),e.extractorRetries!==void 0&&r.push("--extractor-retries",e.extractorRetries.toString()),e.allowDynamicMpd&&r.push("--allow-dynamic-mpd"),e.ignoreDynamicMpd&&r.push("--ignore-dynamic-mpd"),e.hlsSplitDiscontinuity&&r.push("--hls-split-discontinuity"),e.noHlsSplitDiscontinuity&&r.push("--no-hls-split-discontinuity"),e.extractorArgs)for(let[s,i]of Object.entries(e.extractorArgs))r.push("--extractor-args",`${s}:${i.join(" ")}`);if(e.playlistStart!==void 0&&r.push("--playlist-start",e.playlistStart.toString()),e.playlistEnd!==void 0&&r.push("--playlist-end",e.playlistEnd.toString()),e.matchTitle&&r.push("--match-title",e.matchTitle),e.rejectTitle&&r.push("--reject-title",e.rejectTitle),e.includeAds&&r.push("--include-ads"),e.breakOnReject&&r.push("--break-on-reject"),e.noDownload&&r.push("--no-download"),e.playlistReverse&&r.push("--playlist-reverse"),e.geoBypass&&r.push("--geo-bypass"),e.geoBypassCountry&&r.push("--geo-bypass-country",e.geoBypassCountry),e.geoBypassIpBlock&&r.push("--geo-bypass-ip-block",e.geoBypassIpBlock),e.convertThumbnails&&r.push("--convert-thumbnails",e.convertThumbnails),e.writeLink&&r.push("--write-link"),e.writeUrlLink&&r.push("--write-url-link"),e.writeWeblocLink&&r.push("--write-webloc-link"),e.writeLnkLink&&r.push("--write-lnk-link"),e.referer&&r.push("--referer",e.referer),e.userAgent&&r.push("--user-agent",e.userAgent),e.extractAudio&&r.push("--extract-audio"),e.audioFormat&&r.push("--audio-format",e.audioFormat),e.audioQuality&&r.push("--audio-quality",e.audioQuality),e.remuxVideo&&r.push("--remux-video",e.remuxVideo),e.recodeVideo&&r.push("--recode-video",e.recodeVideo),e.postprocessorArgs)for(let[s,i]of Object.entries(e.postprocessorArgs))r.push("--postprocessor-args",`${s}:${i.join(" ")}`);if(e.keepVideo&&r.push("--keep-video"),e.noKeepVideo&&r.push("--no-keep-video"),e.postOverwrites&&r.push("--post-overwrites"),e.noPostOverwrites&&r.push("--no-post-overwrites"),e.embedSubs&&r.push("--embed-subs"),e.noEmbedSubs&&r.push("--no-embed-subs"),e.embedThumbnail&&r.push("--embed-thumbnail"),e.noEmbedThumbnail&&r.push("--no-embed-thumbnail"),e.embedMetadata&&r.push("--embed-metadata"),e.noEmbedMetadata&&r.push("--no-embed-metadata"),e.embedChapters&&r.push("--embed-chapters"),e.noEmbedChapters&&r.push("--no-embed-chapters"),e.embedInfoJson&&r.push("--embed-info-json"),e.noEmbedInfoJson&&r.push("--no-embed-info-json"),e.parseMetadata)for(let[s,i]of Object.entries(e.parseMetadata))r.push("--parse-metadata",`${s}:${i}`);if(e.replaceInMetadata)for(let[s,[i,n]]of Object.entries(e.replaceInMetadata))r.push("--replace-in-metadata",`${s} ${i} ${n}`);if(e.xattrs&&r.push("--xattrs"),e.concatPlaylist&&r.push("--concat-playlist",e.concatPlaylist),e.fixup&&r.push("--fixup",e.fixup),e.ffmpegLocation&&r.push("--ffmpeg-location",e.ffmpegLocation),e.exec&&r.push("--exec",e.exec),e.noExec&&r.push("--no-exec"),e.convertSubs&&r.push("--convert-subs",e.convertSubs),e.convertThumbnails&&r.push("--convert-thumbnails",e.convertThumbnails),e.splitChapters&&r.push("--split-chapters"),e.noSplitChapters&&r.push("--no-split-chapters"),e.removeChapters&&r.push("--remove-chapters",e.removeChapters),e.noRemoveChapters&&r.push("--no-remove-chapters"),e.forceKeyframesAtCuts&&r.push("--force-keyframes-at-cuts"),e.noForceKeyframesAtCuts&&r.push("--no-force-keyframes-at-cuts"),e.usePostProcessor&&e.usePostProcessor.length>0)for(let s of e.usePostProcessor)r.push("--use-postprocessor",s);return e.sponsorblockMark&&e.sponsorblockMark.length>0&&r.push("--sponsorblock-mark",e.sponsorblockMark.join(",")),e.sponsorblockRemove&&e.sponsorblockRemove.length>0&&r.push("--sponsorblock-remove",e.sponsorblockRemove.join(",")),e.sponsorblockChapterTitle&&r.push("--sponsorblock-chapter-title",e.sponsorblockChapterTitle),e.noSponsorblock&&r.push("--no-sponsorblock"),e.sponsorblockApi&&r.push("--sponsorblock-api",e.sponsorblockApi),e.additionalOptions&&e.additionalOptions.length>0&&r.push(...e.additionalOptions),e.rawArgs&&e.rawArgs.length>0&&r.push(...e.rawArgs),r}function ae(e){let r=[],t=e.split(` | ||
| `).slice(1);for(let s of t){let i=s.match(/(\d+)\s+(\S+)\s+(\S+)\s+(https:\/\/[\S]+)/);i&&r.push({id:parseInt(i[1],10),width:i[2]==="unknown"?"unknown":parseInt(i[2],10),height:i[3]==="unknown"?"unknown":parseInt(i[3],10),url:i[4]})}return r}var ue={"2160p":"bv*[height<=2160]","1440p":"bv*[height<=1440]","1080p":"bv*[height<=1080]","720p":"bv*[height<=720]","480p":"bv*[height<=480]","360p":"bv*[height<=360]","240p":"bv*[height<=240]","144p":"bv*[height<=133]",highest:"bv*",lowest:"wv*"},le=["audioonly","videoonly","audioandvideo","mergevideo"];function B(e){let r,t,s;if(!e)return[];if(typeof e=="string"&&!le.includes(e))return["-f",e];if(typeof e=="string"&&le.includes(e)&&(r=e),Object.keys(e).length===0||!e||typeof e!="object")return["-f","bv*+ba"];typeof e=="object"&&(r=e.filter,t=e.type,s=e.quality);let i=[];return r==="audioonly"&&(i=["-x","--audio-format",t||"mp3","--audio-quality",s?s.toString():"5"]),r==="videoonly"&&(i=["-f",(s?ue[s]:"bv*")+"[acodec=none]"]),r==="audioandvideo"&&(i=["-f",(s=="lowest"?"w*":"b*")+"[vcodec!=none][acodec!=none][ext="+(t||"mp4")+"]"]),r==="mergevideo"&&(i=["-f",`${s?ue[s]:"bv*"}+ba`],t&&i.push("--merge-output-format",t)),i}function Y(e){if(!e||typeof e=="string")return"video/mp4";let{filter:r,type:t}=e;switch(r){case"videoonly":case"audioandvideo":switch(t){case"mp4":return"video/mp4";case"webm":return"video/webm";default:return"video/mp4"}case"audioonly":switch(t){case"aac":return"audio/aac";case"flac":return"audio/flac";case"mp3":return"audio/mp3";case"m4a":return"audio/mp4";case"opus":return"audio/opus";case"vorbis":return"audio/vorbis";case"wav":return"audio/wav";case"alac":return"audio/mp4";default:return"audio/mpeg"}case"mergevideo":switch(t){case"webm":return"video/webm";case"mkv":return"video/x-matroska";case"ogg":return"video/ogg";case"flv":return"video/x-flv";default:return"video/mp4"}}}function q(e){if(!e||typeof e=="string")return"mp4";let{filter:r,type:t}=e;return t||(r==="audioonly"?"mp3":"mp4")}function fe(e){if(!e?.extractAudio)return null;switch(e.audioFormat||"mp3"){case"aac":return"audio/aac";case"flac":return"audio/flac";case"mp3":return"audio/mpeg";case"m4a":return"audio/mp4";case"opus":return"audio/opus";case"vorbis":return"audio/vorbis";case"wav":return"audio/wav";case"alac":return"audio/mp4";default:return"audio/mpeg"}}function de(e){return e?.extractAudio?e.audioFormat||"mp3":null}var $="~ytdlp-progress-%(progress)#j";function Q(e,r=2){let t=Number(e);if(t===0||isNaN(t))return t+" Bytes";let s=1024,i=r<0?0:r,n=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],o=Math.floor(Math.log(t)/Math.log(s));return parseFloat((t/Math.pow(s,o)).toFixed(i))+" "+n[o]}function Ke(e,r,t){let s=Math.pow(t||10,r);return Math.round(e*s)/s}function Me(e){e=Number(e);let r=Math.floor(e/3600),t=Math.floor(e%3600/60),s=Math.floor(e%3600%60),i=r>0?r+(r==1?" hour, ":" hours, "):"",n=t>0?t+(t==1?" minute, ":" minutes, "):"",o=s>=0?s+(s==1?" second":" seconds"):"";return i+n+o}function m(e){try{if(!e.includes("~ytdlp-progress-"))throw new Error;let r=e.trim().replace("~ytdlp-progress-","");if(!r)throw new Error;let t=JSON.parse(r),s=l=>{if(l==null||l==="NA")return;let f=Number(l);return isNaN(f)?void 0:f},i=s(t.downloaded_bytes),n=s(t.total_bytes)??s(t.total_bytes_estimate),o=s(t.speed),a=s(t.eta),u=i!==void 0&&n!==void 0&&n>0?Ke(100*i/n,2):void 0;return{filename:t.filename,status:t.status,downloaded:i,downloaded_str:i!==void 0?Q(i):void 0,total:n,total_str:n!==void 0?Q(n):void 0,speed:o,speed_str:o!==void 0?Q(o)+"/s":void 0,eta:a,eta_str:a!==void 0?Me(a):void 0,percentage:u,percentage_str:u!==void 0?u+"%":void 0}}catch{return}}var j=c(require("path")),T=c(require("fs"));var We=c(require("https")),Ue=c(require("http")),G=require("url"),b=c(require("fs"));function H(e,r={}){return new Promise((t,s)=>{let o=(new G.URL(e).protocol==="https:"?We:Ue).get(e,r,a=>{if(a.statusCode>=300&&a.statusCode<400&&a.headers.location){let u=new G.URL(a.headers.location,e).toString();H(u,r).then(t).catch(s);return}t(a)});o.on("error",s),o.setTimeout(3e4,()=>{o.destroy(),s(new Error("Request timed out"))})})}async function S(e,r){try{let t=b.createWriteStream(r),s=await H(e);if(s.statusCode!==200)throw t.close(),b.unlinkSync(r),new Error(`Failed to download file: ${s.statusCode} ${s.statusMessage}`);let i=parseInt(s.headers["content-length"]||"0",10),n=0;return s.on("data",o=>{n+=o.length;let a=n/i*100;process.stdout.write(`Progress: ${Math.round(a)}%\r`)}),s.pipe(t),new Promise((o,a)=>{t.on("finish",()=>{t.close(),console.log(` | ||
| Download complete!`),o()}),t.on("error",u=>{t.close(),b.unlinkSync(r),a(u)}),s.on("error",u=>{t.close(),b.unlinkSync(r),a(u)})})}catch(t){throw b.existsSync(r)&&b.unlinkSync(r),t}}async function he(e,r={}){let t=await H(e,r);if(t.statusCode!==200)throw new Error(`Failed to fetch text: ${t.statusCode} ${t.statusMessage}`);return new Promise((s,i)=>{let n="";t.setEncoding("utf8"),t.on("data",o=>{n+=o}),t.on("end",()=>s(n)),t.on("error",i)})}var ce=c(require("fs")),_=c(require("path"));function ze(e){let r=e;for(;;){if(ce.existsSync(_.join(r,"package.json")))return r;let t=_.dirname(r);if(t===r)return e;r=t}}var me=ze(__dirname),y=_.join(me,"bin"),mr=_.join(me,"package.json");var Je="https://github.com/iqbal-rashed/ytdlp-nodejs/releases/download/ffmpeg-latest",Z={win32:{x64:["win-x64-ffmpeg.exe","win-x64-ffprobe.exe"],ia32:["win-ia32-ffmpeg.exe","win-ia32-ffprobe.exe"],arm64:["win-arm64-ffmpeg.exe","win-arm64-ffprobe.exe"]},linux:{x64:["linux-x64-ffmpeg","linux-x64-ffprobe"],arm64:["linux-arm64-ffmpeg","linux-arm64-ffprobe"]},darwin:{x64:["macos-x64-ffmpeg","macos-x64-ffprobe"],arm64:["macos-arm64-ffmpeg","macos-arm64-ffprobe"]},android:{arm64:["linux-arm64-ffmpeg","linux-arm64-ffprobe"]}};function pe(){let e=process.platform,r=process.arch;if(!Z[e]||!Z[e][r])throw new Error(`No FFmpeg build available for platform: ${e}, architecture: ${r}`);return Z[e][r]}async function X(e){let r=e||y,t=F();if(t)return t;try{let s=pe();if(!s.length)throw new Error;let i=s.map(o=>`${Je}/${o}`),n=s.map(o=>j.default.join(r,String(o.split("-").pop())));T.default.existsSync(r)||T.default.mkdirSync(r,{recursive:!0}),console.log("Downloading FFmpeg and FFprobe...");for(let o=0;o<s.length;o++){let a=i[o],u=n[o];console.log("Downloading...",j.default.basename(a)),await S(a,u)}if(process.platform!=="win32")for(let o of n)T.default.chmodSync(o,493);return F()}catch(s){throw console.error(`Download failed: ${s}`),s}}function F(){try{let e=pe();if(!e.length)throw new Error;let r=j.default.join(y,String(e[0].split("-").pop()));if(!T.default.existsSync(r))throw new Error("FFmpeg binary not found. Please download it first.");return r}catch{return}}var g=c(require("fs")),I=c(require("path"));var ge=c(require("crypto")),be="https://github.com/yt-dlp/yt-dlp/releases/latest/download",L={win32:{x64:"yt-dlp.exe",ia32:"yt-dlp_x86.exe"},linux:{x64:"yt-dlp",armv7l:"yt-dlp_linux_armv7l",aarch64:"yt-dlp_linux_aarch64",arm64:"yt-dlp"},darwin:{x64:"yt-dlp_macos",arm64:"yt-dlp_macos"},android:{arm64:"yt-dlp"}};function Ye(){let e=process.platform,r=process.arch;if(!L[e]||!L[e][r])throw new Error(`No yt-dlp build available for ${e} ${r}`);return L[e][r]}async function K(e){let r=e||y,t=Ye(),s=`${be}/${t}`,i=I.join(r,t);if(g.existsSync(i))return i;console.log("Downloading yt-dlp...",s),g.existsSync(r)||g.mkdirSync(r,{recursive:!0});try{return await S(s,i),console.log(`yt-dlp downloaded successfully to: ${i}`),process.platform!=="win32"&&g.chmodSync(i,493),i}catch(o){throw console.error(`Download failed: ${o}`),o}}async function qe(e){return new Promise((r,t)=>{let s=ge.default.createHash("sha256"),i=g.createReadStream(e);i.on("data",n=>s.update(n)),i.on("end",()=>r(s.digest("hex"))),i.on("error",t)})}async function Qe(e){try{let s=(await he(`${be}/SHA2-256SUMS`)).split(/\r?\n/).find(n=>n.includes(e));if(!s)return;let[i]=s.trim().split(/\s+/);return i||void 0}catch{return}}async function ee(e){let r=await K(e),t=I.basename(r),s=await Qe(t);if(!s)return{path:r,verified:!1};let i=await qe(r);if(i.toLowerCase()!==s.toLowerCase())throw new Error(`Checksum mismatch for ${t}. Expected ${s}, got ${i}`);return{path:r,verified:!0,checksum:s}}function O(){let e=process.platform,r=process.arch;try{let t=L[e][r],s=I.join(y,t);if(!g.existsSync(s))throw new Error("Ytdlp binary not found. Please download it first.");return s}catch{return}}function M(e){return e.replace(/~ytdlp-progress-\{[\s\S]*?\}\n?/g,"").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>!r.includes("__YTDLP_FILEPATH__:")).filter(r=>!r.includes("__YTDLP_VIDEO_INFO__:")).filter(r=>!r.includes("__YTDLP_BEFORE_DL__:")).join(` | ||
| `)}function W(e){let r=[],t=e.split(/\r?\n/);for(let s of t){let i=s.trim();if(i.startsWith("__YTDLP_VIDEO_INFO__:")){let n=i.replace("__YTDLP_VIDEO_INFO__:","").trim();try{let o=n.replace(/:"N\/A"/g,":null").replace(/:"NA"/g,":null").replace(/:""/g,':"NA"'),a=JSON.parse(o),u={};for(let[l,f]of Object.entries(a))if(f==="NA")u[l]=null;else if(typeof f=="string"&&f==="N/A")u[l]=null;else if((l.includes("_count")||l.includes("_timestamp")||l==="autonumber"||l==="video_autonumber"||l==="n_entries"||l==="playlist_count"||l==="release_year"||l==="start_time"||l==="end_time"||l==="epoch"||l==="duration"||l==="age_limit")&&typeof f=="string"){let d=Number(f);u[l]=isNaN(d)?null:d}else(l==="is_live"||l==="was_live"||l==="channel_is_verified")&&typeof f=="string"?u[l]=f==="true"||f==="True":(l==="categories"||l==="tags"||l==="creators"||l==="cast")&&typeof f=="string"?f==="NA"||f==="N/A"||f===""?u[l]=null:u[l]=f.split(",").map(d=>d.trim()):u[l]=f;r.push(u)}catch{}}}return r}function w(e){let r=e.trim();if(!r.startsWith("__YTDLP_BEFORE_DL__:"))return null;let t=r.replace("__YTDLP_BEFORE_DL__:","").trim();try{let s=t.replace(/:"N\/A"/g,":null").replace(/:"NA"/g,":null").replace(/:""/,':"NA"'),i=JSON.parse(s),n={};for(let[o,a]of Object.entries(i))if(a==="NA"||a==="N/A")n[o]=null;else if((o.includes("_count")||o.includes("_timestamp")||o==="autonumber"||o==="video_autonumber"||o==="n_entries"||o==="playlist_count"||o==="release_year"||o==="start_time"||o==="end_time"||o==="epoch"||o==="duration"||o==="age_limit")&&typeof a=="string"){let u=Number(a);n[o]=isNaN(u)?null:u}else(o==="is_live"||o==="was_live"||o==="channel_is_verified")&&typeof a=="string"?n[o]=a==="true"||a==="True":(o==="categories"||o==="tags"||o==="creators"||o==="cast")&&typeof a=="string"?a==="NA"||a==="N/A"||a===""?n[o]=null:n[o]=a.split(",").map(u=>u.trim()):n[o]=a;return n}catch{return null}}var Ge=/^ERROR:\s*(?:\[.+?\]\s*)?(.+)/m,He=[/ERROR:\s*\[.*?\]\s*.*?:\s*Sign in to confirm/i,/ERROR:\s*\[.*?\]\s*Unable to extract/i,/ERROR:\s*\[.*?\]\s*This video is unavailable/i,/ERROR:\s*\[.*?\]\s*Video unavailable/i,/ERROR:\s*\[.*?\]\s*Private video/i,/ERROR:\s*\[.*?\]\s*.*?requires premium/i,/ERROR:\s*\[.*?\]\s*This live event has ended/i,/ERROR:\s*\[.*?\]\s*.*?is not available/i,/ERROR:\s*No video formats found/i,/ERROR:\s*Unsupported URL/i];function we(e){if(!e)return{hasError:!1};let r=e.match(Ge);return r?{hasError:!0,message:r[1]?.trim(),fullError:r[0]}:{hasError:!1}}function Ze(e){return e?He.some(r=>r.test(e)):!1}function ye(e,r){let s=we(e).message||"Unknown yt-dlp error";return r!=null&&r!==0&&(s=`yt-dlp exited with code ${r}: ${s}`),new Error(s)}function E(e,r,t){let{exitCodeOnly:s=!1,fatalOnly:i=!1}=t||{};if(r!==0&&r!==null)return ye(e,r);if(s)return;if(we(e).hasError)return i&&!Ze(e)?void 0:ye(e)}var Pe=require("events");function xe({url:e,options:r,ffmpegPath:t,withProgressTemplate:s,extra:i}){let n=N(r||{});return t&&n.push("--ffmpeg-location",t),s&&n.push("--progress-template",$),i&&i.length>0&&n.push(...i),e&&n.push("--",e),n}var re=c(require("fs")),P=class extends Pe.EventEmitter{constructor(t,s){super();this.binaryPath="";this.videoUrl="";this.extraArgs={};this.rawArgs=[];this.videoUrl=t,this.binaryPath=s?.binaryPath||O()||"",this.ffmpegPath=s?.ffmpegPath||F(),(!this.binaryPath||!re.default.existsSync(this.binaryPath))&&console.error(new Error("yt-dlp binary not found. Please install yt-dlp or specify correct binaryPath in options.")),this.ffmpegPath&&!re.default.existsSync(this.ffmpegPath)&&console.error(new Error(`FFmpeg binary not found at: ${this.ffmpegPath}. Please install FFmpeg or specify correct ffmpegPath.`))}setBinaryPath(t){return this.binaryPath=t,this}setFfmpegPath(t){return this.ffmpegPath=t,this}format(t){return this.formatValue=t,this}filter(t){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={...s,filter:t},this}quality(t){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={filter:this.formatValue,...s,quality:t},this}type(t){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={filter:this.formatValue,...s,type:t},this}options(t){return this.extraArgs={...this.extraArgs,...t},this}rateLimit(t){return this.extraArgs.limitRate=t,this}cookies(t){return this.extraArgs.cookies=t,this}cookiesFromBrowser(t){return this.extraArgs.cookiesFromBrowser=t,this}proxy(t){return this.extraArgs.proxy=t,this}addOption(t,s){return this.extraArgs[t]=s,this}addArgs(...t){return this.rawArgs.push(...t),this}extractAudio(t){return this.extraArgs.extractAudio=!0,t&&(this.extraArgs.audioFormat=t),this}audioFormat(t){return this.extraArgs.audioFormat=t,this}audioQuality(t){return this.extraArgs.audioQuality=t,this}embedThumbnail(){return this.extraArgs.embedThumbnail=!0,this}embedSubs(){return this.extraArgs.embedSubs=!0,this}embedMetadata(){return this.extraArgs.embedMetadata=!0,this}writeSubs(){return this.extraArgs.writeSubs=!0,this}writeAutoSubs(){return this.extraArgs.writeAutoSubs=!0,this}subLangs(t){return this.extraArgs.subLangs=t,this}writeThumbnail(){return this.extraArgs.writeThumbnail=!0,this}username(t){return this.extraArgs.username=t,this}password(t){return this.extraArgs.password=t,this}playlistStart(t){return this.extraArgs.playlistStart=t,this}playlistEnd(t){return this.extraArgs.playlistEnd=t,this}playlistItems(t){return this.extraArgs.playlistItems=t,this}buildFormatArgs(){return this.formatValue?B(this.formatValue):[]}buildBaseArgs(t=[]){if(!this.videoUrl)throw new Error("URL is required.");let s=this.buildFormatArgs();return xe({url:this.videoUrl,options:this.extraArgs,ffmpegPath:this.ffmpegPath,withProgressTemplate:!0,extra:[...s,...t,...this.rawArgs]})}debugPrint(t=!0){return this.extraArgs.debugPrintCommandLine=t,this}getCommand(){let t=this.buildArgs();return`${this.binaryPath} ${t.join(" ")}`}getArguments(){return this.buildArgs()}toString(){return this.getCommand()}printDebugCommandLine(t){if(this.extraArgs.debugPrintCommandLine){let s=`${this.binaryPath} ${t.join(" ")}`;console.error(`[ytdlp-nodejs] Command: ${s}`)}}validateBinaryPath(){if(!this.binaryPath)throw new Error("Binary path is required. Use .setBinaryPath() or pass it in constructor.")}kill(t){return this.process?.kill(t)??!1}get pid(){return this.process?.pid}};var ve=["id","title","fulltitle","ext","alt_title","description","display_id","uploader","uploader_id","uploader_url","license","creators","creator","timestamp","upload_date","release_timestamp","release_date","release_year","modified_timestamp","modified_date","channel","channel_id","channel_url","channel_follower_count","channel_is_verified","location","duration","duration_string","view_count","concurrent_view_count","like_count","dislike_count","repost_count","average_rating","comment_count","save_count","age_limit","live_status","is_live","was_live","playable_in_embed","availability","media_type","start_time","end_time","extractor","extractor_key","epoch","autonumber","video_autonumber","n_entries","playlist_id","playlist_title","playlist","playlist_count","playlist_index","playlist_autonumber","playlist_uploader","playlist_uploader_id","playlist_channel","playlist_channel_id","playlist_webpage_url","webpage_url","webpage_url_basename","webpage_url_domain","original_url","categories","tags","cast","filepath"];function Xe(){return`after_move:__YTDLP_VIDEO_INFO__:{${ve.map(r=>`"${r}":%(${r}|null)j`).join(",")}}`}function R(){return`before_dl:__YTDLP_BEFORE_DL__:{${ve.map(r=>`"${r}":%(${r}|null)j`).join(",")}}`}function U(){return["--print",Xe(),"--progress","--newline"]}var Fe=require("child_process"),A=class extends P{constructor(r,t){super(r,t),this.on("error",()=>{})}on(r,t){return super.on(r,t)}once(r,t){return super.once(r,t)}emit(r,...t){return super.emit(r,...t)}output(r){return this.outputDir=r,this}setOutputTemplate(r){return this.outputPath=r,this}skipDownload(){return this.extraArgs.skipDownload=!0,this}buildArgs(){let r={...this.extraArgs};this.outputDir&&(r.output=`${this.outputDir}/%(title)s.%(ext)s`),this.outputPath&&(r.output=this.outputPath);let t=this.extraArgs;this.extraArgs=r;let s=[...U()];this.listenerCount("beforeDownload")>0&&s.unshift("--print",R());let i=this.buildBaseArgs(s);return this.extraArgs=t,i}run(){return this.resultPromise?this.resultPromise:(this.resultPromise=new Promise((r,t)=>{try{this.validateBinaryPath();let s=this.buildArgs(),i=`${this.binaryPath} ${s.join(" ")}`;this.printDebugCommandLine(s),this.process=(0,Fe.spawn)(this.binaryPath,s),this.emit("start",i);let n="",o="";this.process.stdout?.on("data",a=>{let u=a.toString();n+=u,this.emit("stdout",u);let l=w(u);l&&this.emit("beforeDownload",l);let f=m(u);f&&this.emit("progress",f)}),this.process.stderr?.on("data",a=>{let u=a.toString();o+=u,this.emit("stderr",u);let l=m(u);l&&this.emit("progress",l)}),this.process.on("error",a=>{this.emit("error",a),t(a)}),this.process.on("close",a=>{let u=E(o,a);if(u){this.emit("error",u),t(u);return}let l=M(n),f=W(n),d={output:l,filePaths:f.map(p=>p?.filepath??"").filter(Boolean),info:f,stderr:o};this.emit("finish",d),r(d)})}catch(s){t(s)}}),this.resultPromise)}then(r,t){return this.run().then(r,t)}catch(r){return this.run().catch(r)}finally(r){return this.run().finally(r)}};function Ae(e,r){return new A(e,r)}var ke=require("stream");var De=require("child_process"),k=class extends P{constructor(t,s){super(t,s);this.totalBytes=0;this.started=!1;this.on("error",()=>{})}on(t,s){return super.on(t,s)}once(t,s){return super.once(t,s)}emit(t,...s){return super.emit(t,...s)}buildArgs(){let t=["-o","-","--no-playlist","--progress","--no-quiet"];return this.listenerCount("beforeDownload")>0&&t.push("--print",R()),this.buildBaseArgs(t)}startStream(){if(this.started)return this.passThrough;this.validateBinaryPath(),this.started=!0,this.passThrough=new ke.PassThrough;let t=this.buildArgs(),s=`${this.binaryPath} ${t.join(" ")}`;this.printDebugCommandLine(t),this.process=(0,De.spawn)(this.binaryPath,t,{shell:!1}),this.emit("start",s),this.process.stdout?.on("data",n=>{this.totalBytes+=n.length,this.passThrough.write(n),this.emit("data",n)});let i="";return this.process.stderr?.on("data",n=>{let o=n.toString();i+=o,this.emit("stderr",o);let a=w(o);a&&this.emit("beforeDownload",a);let u=m(o);u&&this.emit("progress",u)}),this.process.on("error",n=>{this.emit("error",n),this.passThrough.destroy(n)}),this.process.on("close",n=>{let o=E(i,n);o?(this.emit("error",o),this.passThrough.destroy(o)):(this.passThrough.end(),this.emit("end"))}),this.passThrough}pipe(t,s){let i=Date.now(),n=this.startStream();return new Promise((o,a)=>{n.pipe(t,s),t.on("finish",()=>{o({bytes:this.totalBytes,duration:Date.now()-i})}),t.on("error",a),this.passThrough.on("error",a)})}pipeAsync(t,s){return this.pipe(t,s)}async toBuffer(){let t=[];return new Promise((s,i)=>{let n=this.startStream();n.on("data",o=>{t.push(o)}),n.on("end",()=>{s(Buffer.concat(t))}),n.on("error",i)})}getStream(){return this.startStream()}};function Se(e,r){return new k(e,r)}var _e=require("stream");var te=require("child_process");var x=class extends P{constructor(t,s){super(t,s);this.totalBytes=0;this.started=!1;this.output="";this.on("error",()=>{})}on(t,s){return super.on(t,s)}once(t,s){return super.once(t,s)}emit(t,...s){return super.emit(t,...s)}buildArgs(){let t=[],s=[...U()];return this.listenerCount("beforeDownload")>0&&s.unshift("--print",R()),this.listenerCount("afterDownload")>0&&s.push("--print","after_move:filepath"),this.buildBaseArgs([...t,...s])}startStream(){if(this.started)return this.passThrough;this.validateBinaryPath(),this.started=!0,this.passThrough=new _e.PassThrough,this.output="";let t=this.buildArgs();t.includes("--no-playlist")||(t=["--no-playlist",...t]);let s=`${this.binaryPath} ${t.join(" ")}`;return this.printDebugCommandLine(t),this.process=(0,te.spawn)(this.binaryPath,t,{shell:!1}),this.emit("start",s),this.process.stdout?.on("data",i=>{this.totalBytes+=i.length,this.passThrough.write(i),this.emit("data",i);let n=i.toString();this.emit("stdout",n);let o=w(n);o&&(this.beforeDownloadInfo=o,this.emit("beforeDownload",this.beforeDownloadInfo));let a=m(n);a&&this.emit("progress",a)}),this.process.stderr?.on("data",i=>{let n=i.toString();this.emit("stderr",n),this.output+=n;let o=w(n);o&&(this.beforeDownloadInfo=o,this.emit("beforeDownload",this.beforeDownloadInfo));let a=m(n);a&&(this.emit("progress",a),a.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:a.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.on("error",i=>{this.emit("error",i),this.passThrough.destroy(i)}),this.process.on("close",i=>{let n=E(this.output,i);n?(this.emit("error",n),this.passThrough.destroy(n)):(this.passThrough.end(),this.emit("end"))}),this.passThrough}pipe(t,s){let i=Date.now(),n=this.startStream();return new Promise((o,a)=>{n.pipe(t,s),t.on("finish",()=>{o({bytes:this.totalBytes,duration:Date.now()-i,info:this.afterDownloadInfo,output:this.output})}),t.on("error",a),this.passThrough.on("error",a)})}pipeAsync(t,s){return this.pipe(t,s)}async toBuffer(){let t=[];return new Promise((s,i)=>{let n=this.startStream();n.on("data",o=>{t.push(o)}),n.on("end",()=>{s(Buffer.concat(t))}),n.on("error",i)})}getStream(){return this.startStream()}exec(){return this.resultPromise?this.resultPromise:(this.resultPromise=new Promise((t,s)=>{try{this.validateBinaryPath();let i=this.buildArgs(),n=`${this.binaryPath} ${i.join(" ")}`;this.printDebugCommandLine(i),this.process=(0,te.spawn)(this.binaryPath,i,{shell:!1}),this.emit("start",n);let o="",a="";this.process.stdout?.on("data",u=>{let l=u.toString();o+=l,this.emit("stdout",l);let f=w(l);f&&(this.beforeDownloadInfo=f,this.emit("beforeDownload",this.beforeDownloadInfo)),this.emit("data",u);let d=m(l);d&&(this.emit("progress",d),d.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:d.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.stderr?.on("data",u=>{let l=u.toString();a+=l,this.emit("stderr",l);let f=w(l);f&&(this.beforeDownloadInfo=f,this.emit("beforeDownload",this.beforeDownloadInfo));let d=m(l);d&&(this.emit("progress",d),d.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:d.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.on("error",u=>{this.emit("error",u),s(u)}),this.process.on("close",u=>{let l=M(o),f=W(o),d={stdout:o,stderr:a,exitCode:u,command:n,info:f,output:l,filePaths:f.map(p=>p?.filepath??"").filter(Boolean)};this.emit("complete",d),this.emit("end"),t(d)})}catch(i){s(i)}}),this.resultPromise)}run(){return this.exec()}then(t,s){return this.exec().then(t,s)}catch(t){return this.exec().catch(t)}finally(t){return this.exec().finally(t)}};function Ee(e,r){return new x(e,r)}var ie=class{constructor(r){this.binaryPath=r?.binaryPath||O()||"",this.ffmpegPath=r?.ffmpegPath||F(),(!this.binaryPath||!se.existsSync(this.binaryPath))&&console.error(new Error("yt-dlp binary not found. Please install yt-dlp or specify correct binaryPath in options.")),this.ffmpegPath&&!se.existsSync(this.ffmpegPath)&&console.error(new Error(`FFmpeg binary not found at: ${this.ffmpegPath}. Please install FFmpeg or specify correct ffmpegPath.`))}async checkInstallationAsync(r){return new Promise((t,s)=>{if(r?.ffmpeg&&!this.ffmpegPath)return s(new Error("FFmpeg path is not set"));let i=(0,D.spawn)(this.binaryPath,["--version"]),n=!1,o=!r?.ffmpeg;i.on("error",()=>n=!1),i.on("exit",a=>{if(n=a===0,r?.ffmpeg){let u=(0,D.spawn)(this.ffmpegPath,["-version"]);u.on("error",()=>o=!1),u.on("exit",l=>{o=l===0,t(n&&o)})}else t(n)})})}checkInstallation(r){if(r?.ffmpeg&&!this.ffmpegPath)throw new Error("FFmpeg path is not set");let t=(0,D.spawnSync)(this.binaryPath,["--version"],{stdio:"ignore"}),s=r?.ffmpeg?(0,D.spawnSync)(this.ffmpegPath,["-version"],{stdio:"ignore"}):{status:0};return t.status===0&&s.status===0}async getInfoAsync(r,t){let s=await this.execAsync(r,{dumpSingleJson:!0,flatPlaylist:!0,...t});return JSON.parse(s.output)}async execAsync(r,t){let s=new x(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{onData:i,onProgress:n,onBeforeDownload:o,pipeTo:a,...u}=t||{};return u&&s.options(u),i&&s.on("stdout",i),n&&s.on("progress",n),o&&s.on("beforeDownload",o),a?s.pipe(a):s.exec()}exec(r,t){let s=new x(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath});return t&&s.options(t),s}download(r,t){let s=new A(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=t||{};return i&&s.format(i),n&&s.options(n),s}async downloadAsync(r,t){let{onProgress:s,beforeDownload:i,...n}=t||{},o=this.download(r,n);s&&o.on("progress",s),i&&o.on("beforeDownload",i);let a=await o.run();return{output:a.output,filePaths:a.filePaths,info:a.info}}stream(r,t){let s=new k(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=t||{};return i&&s.format(i),n&&s.options(n),s}execBuilder(r,t){let s=new x(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=t||{};return i&&s.format(i),n&&s.options(n),s}async downloadAudio(r,t="mp3",s){let i=["aac","flac","mp3","m4a","opus","vorbis","wav","alac"];if(!i.includes(t))throw new Error(`Invalid audio format: ${t}. Supported: ${i.join(", ")}`);return this.downloadAsync(r,{...s,extractAudio:!0,audioFormat:t})}async downloadVideo(r,t="best",s){let i=["best","2160p","1440p","1080p","720p","480p","360p","240p","144p","highest","lowest"];if(!i.includes(t))throw new Error(`Invalid video quality: ${t}. Supported: ${i.join(", ")}`);let n=t==="best"?"bestvideo+bestaudio/best":`bestvideo[height<=${parseInt(t)||1080}]+bestaudio/best[height<=${parseInt(t)||1080}]`;return this.downloadAsync(r,{...s,format:n})}async getSubtitles(r,t){return(await this.execAsync(r,{...t,listSubs:!0,skipDownload:!0})).output?[]:[]}async getComments(r,t=20,s){let i=await this.execAsync(r,{...s,writeComments:!0,dumpSingleJson:!0,skipDownload:!0,extractorArgs:{youtube:[`max_comments=${t}`,"player_skip=webpage"]}});try{return JSON.parse(i.output).comments||[]}catch{return[]}}async getDirectUrlsAsync(r,t){return(await this.getInfoAsync(r,t)).formats.map(i=>i.url)}async getFormatsAsync(r,t){let s=await this.getInfoAsync(r,t);return{source:"json",info:s,formats:s.formats}}async getThumbnailsAsync(r){return(await this.getInfoAsync(r)).thumbnails}async getTitleAsync(r){return(await this.execAsync(r,{print:"title"})).output.trim()}async getVersionAsync(){return(await this.execAsync("",{printVersion:!0})).output.trim()}async downloadFFmpeg(){return X()}async getFileAsync(r,t){let s,{onBeforeDownload:i,onProgress:n,filename:o,metadata:a,format:u,...l}=t||{},f=[],d=new Te.PassThrough;d.on("data",v=>f.push(Buffer.from(v)));let p=B(u),z={...l};if(p.length>=2&&p[0]==="-f"&&(z.format=p[1]),p.includes("--merge-output-format")){let v=p.indexOf("--merge-output-format");z.mergeOutputFormat=p[v+1]}await this.execAsync(r,{...z,noPlaylist:!0,pipeTo:d,onProgress:n,onBeforeDownload:v=>{s=v,i?.(v)},output:"-"});let V,J;u&&typeof u=="object"?(V=Y(u),J=q(u)):(V=fe(l)||"video/mp4",J=de(l)||"mp4");let Ie=new Be.Blob(f,{type:V}),ne={name:o||`${s?.title||"download"}.${J}`,type:V,size:Ie.size,...a};return new File([Buffer.concat(f)],ne.name,{type:ne.type})}async getUrlsAsync(r,t){return(await this.execAsync(r,{...t,print:"urls"})).output.split(` | ||
| `).filter(Boolean)}async updateYtDlpAsync(r){if(r?.preferBuiltIn!==!1&&this.binaryPath)try{await this.execAsync("",{update:!0});let a=await this.getVersionAsync().catch(()=>{});return{method:"built-in",binaryPath:this.binaryPath,version:a}}catch{}let s=r?.outDir||(this.binaryPath?Re.default.dirname(this.binaryPath):void 0);if(r?.verifyChecksum!==!1){let a=await ee(s),u=await this.getVersionAsyncUsingBinary(a.path).catch(()=>{});return{method:"download",binaryPath:a.path,version:u,verified:a.verified}}let n=await K(s),o=await this.getVersionAsyncUsingBinary(n).catch(()=>{});return{method:"download",binaryPath:n,version:o,verified:!1}}async getVersionAsyncUsingBinary(r){return new Promise((t,s)=>{let i=(0,D.spawn)(r,["--version"]),n="",o="";i.stdout?.on("data",a=>{n+=a.toString()}),i.stderr?.on("data",a=>{o+=a.toString()}),i.on("close",a=>{a===0?t(n.trim()):s(new Error(`Failed to get version: ${o}`))}),i.on("error",s)})}},er={downloadFFmpeg:X,findFFmpegBinary:F,PROGRESS_STRING:$,getContentType:Y,getFileExtension:q,parseFormatOptions:B,stringToProgress:m,createArgs:N,extractThumbnails:ae,downloadFile:S,BIN_DIR:y,downloadYtDlp:K,downloadYtDlpVerified:ee,findYtdlpBinary:O};0&&(module.exports={BIN_DIR,Download,Exec,Stream,YtDlp,createDownload,createExec,createStreamBuilder,helpers}); |
+5
-5
@@ -1,5 +0,5 @@ | ||
| import{fileURLToPath as be}from"url";import ye from"path";var xe=()=>be(import.meta.url),Pe=()=>ye.dirname(xe()),h=Pe();import{spawn as H,spawnSync as pe}from"child_process";import*as Z from"fs";import Ke from"path";import{Blob as Me}from"buffer";import{PassThrough as We}from"stream";function R(e){let t=[];if(e.printHelp&&t.push("--help"),e.printVersion&&t.push("--version"),e.update&&t.push("--update"),e.noUpdate&&t.push("--no-update"),e.updateTo&&t.push("--update-to",e.updateTo),e.ignoreErrors&&t.push("--ignore-errors"),e.noAbortOnError&&t.push("--no-abort-on-error"),e.abortOnError&&t.push("--abort-on-error"),e.dumpUserAgent&&t.push("--dump-user-agent"),e.listExtractors&&t.push("--list-extractors"),e.extractorDescriptions&&t.push("--extractor-descriptions"),e.useExtractors&&e.useExtractors.length>0&&t.push("--use-extractors",e.useExtractors.join(",")),e.defaultSearch&&t.push("--default-search",e.defaultSearch),e.ignoreConfig&&t.push("--ignore-config"),e.noConfigLocations&&t.push("--no-config-location"),e.configLocations&&e.configLocations.length>0&&t.push("--config-locations",...e.configLocations),e.pluginDirs&&e.pluginDirs.length>0)for(let s of e.pluginDirs)t.push("--plugin-dirs",s);e.noPluginDirs&&t.push("--no-plugin-dirs"),e.flatPlaylist&&t.push("--flat-playlist"),e.noFlatPlaylist&&t.push("--no-flat-playlist"),e.liveFromStart&&t.push("--live-from-start"),e.noLiveFromStart&&t.push("--no-live-from-start"),e.waitForVideo&&t.push("--wait-for-video",e.waitForVideo.toString()),e.noWaitForVideo&&t.push("--no-wait-for-video"),e.markWatched&&t.push("--mark-watched"),e.noMarkWatched&&t.push("--no-mark-watched"),e.color&&t.push("--color",e.color),e.compatOptions&&e.compatOptions.length>0&&t.push("--compat-options",e.compatOptions.join(",")),e.aliases&&e.aliases.length>0&&t.push("--alias",...e.aliases);let r=e.jsRuntime??"node";if(r&&t.push("--js-runtime",r),e.proxy&&t.push("--proxy",e.proxy),e.socketTimeout&&t.push("--socket-timeout",e.socketTimeout.toString()),e.sourceAddress&&t.push("--source-address",e.sourceAddress),e.impersonate&&e.impersonate.length>0&&t.push("--impersonate",e.impersonate.join(",")),e.listImpersonateTargets&&t.push("--list-impersonate-targets"),e.forceIpv4&&t.push("--force-ipv4"),e.forceIpv6&&t.push("--force-ipv6"),e.enableFileUrls&&t.push("--enable-file-urls"),e.geoVerificationProxy&&t.push("--geo-verification-proxy",e.geoVerificationProxy),e.xff&&t.push("--xff",e.xff),e.playlistItems&&t.push("--playlist-items",e.playlistItems),e.minFilesize&&t.push("--min-filesize",e.minFilesize),e.maxFilesize&&t.push("--max-filesize",e.maxFilesize),e.date&&t.push("--date",e.date),e.dateBefore&&t.push("--datebefore",e.dateBefore),e.dateAfter&&t.push("--dateafter",e.dateAfter),e.matchFilter&&t.push("--match-filter",e.matchFilter),e.noMatchFilters&&t.push("--no-match-filters"),e.breakMatchFilters&&t.push("--break-match-filters",e.breakMatchFilters),e.noBreakMatchFilters&&t.push("--no-break-match-filters"),e.noPlaylist&&t.push("--no-playlist"),e.yesPlaylist&&t.push("--yes-playlist"),e.ageLimit&&t.push("--age-limit",e.ageLimit.toString()),e.downloadArchive&&t.push("--download-archive",e.downloadArchive),e.noDownloadArchive&&t.push("--no-download-archive"),e.maxDownloads&&t.push("--max-downloads",e.maxDownloads.toString()),e.breakOnExisting&&t.push("--break-on-existing"),e.noBreakOnExisting&&t.push("--no-break-on-existing"),e.breakPerInput&&t.push("--break-per-input"),e.noBreakPerInput&&t.push("--break-per-input"),e.skipPlaylistAfterErrors&&t.push("--skip-playlist-after-errors",e.skipPlaylistAfterErrors.toString()),e.concurrentFragments&&t.push("--concurrent-fragments",e.concurrentFragments.toString()),e.limitRate&&t.push("--limit-rate",e.limitRate),e.throttledRate&&t.push("--throttled-rate",e.throttledRate),e.retries&&t.push("--retries",e.retries.toString()),e.fileAccessRetries&&t.push("--file-access-retries",e.fileAccessRetries.toString()),e.fragmentRetries&&t.push("--fragment-retries",e.fragmentRetries.toString()),e.retrySleep&&t.push("--retry-sleep",e.retrySleep.toString()),e.retrySleepByType)for(let[s,i]of Object.entries(e.retrySleepByType))t.push("--retry-sleep",`${s}:${i}`);if(e.skipUnavailableFragments&&t.push("--skip-unavailable-fragments"),e.abortOnUnavailableFragment&&t.push("--abort-on-unavailable-fragment"),e.keepFragments&&t.push("--keep-fragments"),e.noKeepFragments&&t.push("--no-keep-fragments"),e.bufferSize&&t.push("--buffer-size",e.bufferSize),e.resizeBuffer&&t.push("--resize-buffer"),e.noResizeBuffer&&t.push("--no-resize-buffer"),e.httpChunkSize&&t.push("--http-chunk-size",e.httpChunkSize),e.playlistRandom&&t.push("--playlist-random"),e.lazyPlaylist&&t.push("--lazy-playlist"),e.noLazyPlaylist&&t.push("--no-lazy-playlist"),e.xattrSetFilesize&&t.push("--xattr-set-filesize"),e.hlsUseMpegts&&t.push("--hls-use-mpegts"),e.noHlsUseMpegts&&t.push("--no-hls-use-mpegts"),e.downloadSections&&t.push("--download-sections",e.downloadSections.toString()),e.downloader&&t.push("--downloader",e.downloader),e.downloaderArgs&&t.push("--downloader-args",e.downloaderArgs),e.batchFile&&t.push("--batch-file",e.batchFile),e.noBatchFile&&t.push("--no-batch-file"),e.paths)if(typeof e.paths=="string")t.push("--paths",e.paths);else for(let[s,i]of Object.entries(e.paths))t.push("--paths",`${s}:${i}`);if(e.output&&t.push("-o",e.output),e.outputNaPlaceholder&&t.push("--output-na-placeholder",e.outputNaPlaceholder),e.restrictFilenames&&t.push("--restrict-filenames"),e.noRestrictFilenames&&t.push("--no-restrict-filenames"),e.windowsFilenames&&t.push("--windows-filenames"),e.noWindowsFilenames&&t.push("--no-windows-filenames"),e.trimFileNames&&t.push("--trim-file-names",e.trimFileNames.toString()),e.noOverwrites&&t.push("--no-overwrites"),e.forceOverwrites&&t.push("--force-overwrites"),e.noForceOverwrites&&t.push("--no-force-overwrites"),e.continue&&t.push("--continue"),e.noContinue&&t.push("--no-continue"),e.part&&t.push("--part"),e.noPart&&t.push("--no-part"),e.mtime&&t.push("--mtime"),e.noMtime&&t.push("--no-mtime"),e.writeDescription&&t.push("--write-description"),e.noWriteDescription&&t.push("--no-write-description"),e.writeInfoJson&&t.push("--write-info-json"),e.noWriteInfoJson&&t.push("--no-write-info-json"),e.writePlaylistMetafiles&&t.push("--write-playlist-metafiles"),e.noWritePlaylistMetafiles&&t.push("--no-write-playlist-metafiles"),e.cleanInfoJson&&t.push("--clean-info-json"),e.noCleanInfoJson&&t.push("--no-clean-info-json"),e.writeComments&&t.push("--write-comments"),e.noWriteComments&&t.push("--no-write-comments"),e.loadInfoJson&&t.push("--load-info-json",e.loadInfoJson.toString()),e.cookies&&t.push("--cookies",e.cookies),e.noCookies&&t.push("--no-cookies"),e.cookiesFromBrowser&&t.push("--cookies-from-browser",e.cookiesFromBrowser),e.noCookiesFromBrowser&&t.push("--no-cookies-from-browser"),e.cacheDir&&t.push("--cache-dir",e.cacheDir),e.noCacheDir&&t.push("--no-cache-dir"),e.rmCacheDir&&t.push("--rm-cache-dir"),e.writeThumbnail&&t.push("--write-thumbnail"),e.noWriteThumbnails&&t.push("--no-write-thumbnails"),e.writeAllThumbnails&&t.push("--write-all-thumbnails"),e.listThumbnails&&t.push("--list-thumbnails"),e.writeLink&&t.push("--write-link"),e.writeUrlLink&&t.push("--write-url-link"),e.writeWeblocLink&&t.push("--write-webloc-link"),e.writeDesktopLink&&t.push("--write-desktop-link"),e.quiet&&t.push("--quiet"),e.noQuiet&&t.push("--no-quiet"),e.noWarnings&&t.push("--no-warnings"),e.simulate&&t.push("--simulate"),e.noSimulate&&t.push("--no-simulate"),e.ignoreNoFormatsError&&t.push("--ignore-no-formats-error"),e.noIgnoreNoFormatsError&&t.push("--no-ignore-no-formats-error"),e.skipDownload&&t.push("--skip-download"),e.print&&t.push("--print",e.print),e.printToFile&&t.push("--print-to-file",e.printToFile),e.dumpJson&&t.push("--dump-json"),e.dumpSingleJson&&t.push("--dump-single-json"),e.forceWriteArchive&&t.push("--force-write-archive"),e.newline&&t.push("--newline"),e.noProgress&&t.push("--no-progress"),e.progress&&t.push("--progress"),e.consoleTitle&&t.push("--console-title"),e.progressTemplate&&t.push("--progress-template",e.progressTemplate),e.progressDelta&&t.push("--progress-delta",e.progressDelta.toString()),e.verbose&&t.push("--verbose"),e.dumpPages&&t.push("--dump-pages"),e.writePages&&t.push("--write-pages"),e.printTraffic&&t.push("--print-traffic"),e.encoding&&t.push("--encoding",e.encoding),e.legacyServerConnect&&t.push("--legacy-server-connect"),e.noCheckCertificates&&t.push("--no-check-certificates"),e.preferInsecure&&t.push("--prefer-insecure"),e.addHeaders)for(let[s,i]of Object.entries(e.addHeaders))t.push("--add-header",`${s}:${i}`);if(e.headers)for(let[s,i]of Object.entries(e.headers))t.push("--add-header",`${s}:${i}`);if(e.bidiWorkaround&&t.push("--bidi-workaround"),e.sleepRequests&&t.push("--sleep-requests",e.sleepRequests.toString()),e.sleepInterval&&t.push("--sleep-interval",e.sleepInterval.toString()),e.maxSleepInterval&&t.push("--max-sleep-interval",e.maxSleepInterval.toString()),e.sleepSubtitles&&t.push("--sleep-subtitles",e.sleepSubtitles.toString()),e.format&&t.push("-f",e.format),e.formatSort&&e.formatSort.length>0&&t.push("--format-sort",e.formatSort.join(",")),e.formatSortForce&&t.push("--format-sort-force"),e.noFormatSortForce&&t.push("--no-format-sort-force"),e.videoMultiStreams&&t.push("--video-multistreams"),e.noVideoMultiStreams&&t.push("--no-video-multistreams"),e.audioMultiStreams&&t.push("--audio-multistreams"),e.noAudioMultiStreams&&t.push("--no-audio-multistreams"),e.preferFreeFormats&&t.push("--prefer-free-formats"),e.noPreferFreeFormats&&t.push("--no-prefer-free-formats"),e.checkFormats&&t.push("--check-formats"),e.checkAllFormats&&t.push("--check-all-formats"),e.noCheckFormats&&t.push("--no-check-formats"),e.listFormats&&t.push("--list-formats"),e.mergeOutputFormat&&t.push("--merge-output-format",e.mergeOutputFormat),e.writeSubs&&t.push("--write-subs"),e.noWriteSubs&&t.push("--no-write-subs"),e.writeAutoSubs&&t.push("--write-auto-subs"),e.writeAllSubs&&t.push("--all-subs"),e.listSubs&&t.push("--list-subs"),e.subFormat&&t.push("--sub-format",e.subFormat),e.subLangs&&e.subLangs.length>0&&t.push("--sub-langs",e.subLangs.join(",")),e.username&&t.push("--username",e.username),e.password&&t.push("--password",e.password),e.twoFactor&&t.push("--twofactor",e.twoFactor),e.netrc&&t.push("--netrc"),e.videoPassword&&t.push("--video-password",e.videoPassword),e.apMso&&t.push("--ap-mso",e.apMso),e.apUsername&&t.push("--ap-username",e.apUsername),e.apPassword&&t.push("--ap-password",e.apPassword),e.netrcLocation&&t.push("--netrc-location",e.netrcLocation),e.netrcCmd&&t.push("--netrc-cmd",e.netrcCmd),e.apListMso&&t.push("--ap-list-mso"),e.clientCertificate&&t.push("--client-certificate",e.clientCertificate),e.clientCertificateKey&&t.push("--client-certificate-key",e.clientCertificateKey),e.clientCertificatePassword&&t.push("--client-certificate-password",e.clientCertificatePassword),e.extractorRetries!==void 0&&t.push("--extractor-retries",e.extractorRetries.toString()),e.allowDynamicMpd&&t.push("--allow-dynamic-mpd"),e.ignoreDynamicMpd&&t.push("--ignore-dynamic-mpd"),e.hlsSplitDiscontinuity&&t.push("--hls-split-discontinuity"),e.noHlsSplitDiscontinuity&&t.push("--no-hls-split-discontinuity"),e.extractorArgs)for(let[s,i]of Object.entries(e.extractorArgs))t.push("--extractor-args",`${s}:${i.join(" ")}`);if(e.playlistStart!==void 0&&t.push("--playlist-start",e.playlistStart.toString()),e.playlistEnd!==void 0&&t.push("--playlist-end",e.playlistEnd.toString()),e.matchTitle&&t.push("--match-title",e.matchTitle),e.rejectTitle&&t.push("--reject-title",e.rejectTitle),e.includeAds&&t.push("--include-ads"),e.breakOnReject&&t.push("--break-on-reject"),e.noDownload&&t.push("--no-download"),e.playlistReverse&&t.push("--playlist-reverse"),e.geoBypass&&t.push("--geo-bypass"),e.geoBypassCountry&&t.push("--geo-bypass-country",e.geoBypassCountry),e.geoBypassIpBlock&&t.push("--geo-bypass-ip-block",e.geoBypassIpBlock),e.convertThumbnails&&t.push("--convert-thumbnails",e.convertThumbnails),e.writeLink&&t.push("--write-link"),e.writeUrlLink&&t.push("--write-url-link"),e.writeWeblocLink&&t.push("--write-webloc-link"),e.writeLnkLink&&t.push("--write-lnk-link"),e.referer&&t.push("--referer",e.referer),e.userAgent&&t.push("--user-agent",e.userAgent),e.extractAudio&&t.push("--extract-audio"),e.audioFormat&&t.push("--audio-format",e.audioFormat),e.audioQuality&&t.push("--audio-quality",e.audioQuality),e.remuxVideo&&t.push("--remux-video",e.remuxVideo),e.recodeVideo&&t.push("--recode-video",e.recodeVideo),e.postprocessorArgs)for(let[s,i]of Object.entries(e.postprocessorArgs))t.push("--postprocessor-args",`${s}:${i.join(" ")}`);if(e.keepVideo&&t.push("--keep-video"),e.noKeepVideo&&t.push("--no-keep-video"),e.postOverwrites&&t.push("--post-overwrites"),e.noPostOverwrites&&t.push("--no-post-overwrites"),e.embedSubs&&t.push("--embed-subs"),e.noEmbedSubs&&t.push("--no-embed-subs"),e.embedThumbnail&&t.push("--embed-thumbnail"),e.noEmbedThumbnail&&t.push("--no-embed-thumbnail"),e.embedMetadata&&t.push("--embed-metadata"),e.noEmbedMetadata&&t.push("--no-embed-metadata"),e.embedChapters&&t.push("--embed-chapters"),e.noEmbedChapters&&t.push("--no-embed-chapters"),e.embedInfoJson&&t.push("--embed-info-json"),e.noEmbedInfoJson&&t.push("--no-embed-info-json"),e.parseMetadata)for(let[s,i]of Object.entries(e.parseMetadata))t.push("--parse-metadata",`${s}:${i}`);if(e.replaceInMetadata)for(let[s,[i,n]]of Object.entries(e.replaceInMetadata))t.push("--replace-in-metadata",`${s} ${i} ${n}`);if(e.xattrs&&t.push("--xattrs"),e.concatPlaylist&&t.push("--concat-playlist",e.concatPlaylist),e.fixup&&t.push("--fixup",e.fixup),e.ffmpegLocation&&t.push("--ffmpeg-location",e.ffmpegLocation),e.exec&&t.push("--exec",e.exec),e.noExec&&t.push("--no-exec"),e.convertSubs&&t.push("--convert-subs",e.convertSubs),e.convertThumbnails&&t.push("--convert-thumbnails",e.convertThumbnails),e.splitChapters&&t.push("--split-chapters"),e.noSplitChapters&&t.push("--no-split-chapters"),e.removeChapters&&t.push("--remove-chapters",e.removeChapters),e.noRemoveChapters&&t.push("--no-remove-chapters"),e.forceKeyframesAtCuts&&t.push("--force-keyframes-at-cuts"),e.noForceKeyframesAtCuts&&t.push("--no-force-keyframes-at-cuts"),e.usePostProcessor&&e.usePostProcessor.length>0)for(let s of e.usePostProcessor)t.push("--use-postprocessor",s);return e.sponsorblockMark&&e.sponsorblockMark.length>0&&t.push("--sponsorblock-mark",e.sponsorblockMark.join(",")),e.sponsorblockRemove&&e.sponsorblockRemove.length>0&&t.push("--sponsorblock-remove",e.sponsorblockRemove.join(",")),e.sponsorblockChapterTitle&&t.push("--sponsorblock-chapter-title",e.sponsorblockChapterTitle),e.noSponsorblock&&t.push("--no-sponsorblock"),e.sponsorblockApi&&t.push("--sponsorblock-api",e.sponsorblockApi),e.additionalOptions&&e.additionalOptions.length>0&&t.push(...e.additionalOptions),e.rawArgs&&e.rawArgs.length>0&&t.push(...e.rawArgs),t}function ee(e){let t=[],r=e.split(` | ||
| `).slice(1);for(let s of r){let i=s.match(/(\d+)\s+(\S+)\s+(\S+)\s+(https:\/\/[\S]+)/);i&&t.push({id:parseInt(i[1],10),width:i[2]==="unknown"?"unknown":parseInt(i[2],10),height:i[3]==="unknown"?"unknown":parseInt(i[3],10),url:i[4]})}return t}var te={"2160p":"bv*[height<=2160]","1440p":"bv*[height<=1440]","1080p":"bv*[height<=1080]","720p":"bv*[height<=720]","480p":"bv*[height<=480]","360p":"bv*[height<=360]","240p":"bv*[height<=240]","144p":"bv*[height<=133]",highest:"bv*",lowest:"wv*"},re=["audioonly","videoonly","audioandvideo","mergevideo"];function B(e){let t,r,s;if(!e)return[];if(typeof e=="string"&&!re.includes(e))return["-f",e];if(typeof e=="string"&&re.includes(e)&&(t=e),Object.keys(e).length===0||!e||typeof e!="object")return["-f","bv*+ba"];typeof e=="object"&&(t=e.filter,r=e.type,s=e.quality);let i=[];return t==="audioonly"&&(i=["-x","--audio-format",r||"mp3","--audio-quality",s?s.toString():"5"]),t==="videoonly"&&(i=["-f",(s?te[s]:"bv*")+"[acodec=none]"]),t==="audioandvideo"&&(i=["-f",(s=="lowest"?"w*":"b*")+"[vcodec!=none][acodec!=none][ext="+(r||"mp4")+"]"]),t==="mergevideo"&&(i=["-f",`${s?te[s]:"bv*"}+ba`],r&&i.push("--merge-output-format",r)),i}function W(e){if(!e||typeof e=="string")return"video/mp4";let{filter:t,type:r}=e;switch(t){case"videoonly":case"audioandvideo":switch(r){case"mp4":return"video/mp4";case"webm":return"video/webm";default:return"video/mp4"}case"audioonly":switch(r){case"aac":return"audio/aac";case"flac":return"audio/flac";case"mp3":return"audio/mp3";case"m4a":return"audio/mp4";case"opus":return"audio/opus";case"vorbis":return"audio/vorbis";case"wav":return"audio/wav";case"alac":return"audio/mp4";default:return"audio/mpeg"}case"mergevideo":switch(r){case"webm":return"video/webm";case"mkv":return"video/x-matroska";case"ogg":return"video/ogg";case"flv":return"video/x-flv";default:return"video/mp4"}}}function U(e){if(!e||typeof e=="string")return"mp4";let{filter:t,type:r}=e;return r||(t==="audioonly"?"mp3":"mp4")}function se(e){if(!e?.extractAudio)return null;switch(e.audioFormat||"mp3"){case"aac":return"audio/aac";case"flac":return"audio/flac";case"mp3":return"audio/mpeg";case"m4a":return"audio/mp4";case"opus":return"audio/opus";case"vorbis":return"audio/vorbis";case"wav":return"audio/wav";case"alac":return"audio/mp4";default:return"audio/mpeg"}}function ie(e){return e?.extractAudio?e.audioFormat||"mp3":null}var O="~ytdlp-progress-%(progress)#j";function z(e,t=2){let r=Number(e);if(r===0||isNaN(r))return r+" Bytes";let s=1024,i=t<0?0:t,n=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],o=Math.floor(Math.log(r)/Math.log(s));return parseFloat((r/Math.pow(s,o)).toFixed(i))+" "+n[o]}function ve(e,t,r){let s=Math.pow(r||10,t);return Math.round(e*s)/s}function Fe(e){e=Number(e);let t=Math.floor(e/3600),r=Math.floor(e%3600/60),s=Math.floor(e%3600%60),i=t>0?t+(t==1?" hour, ":" hours, "):"",n=r>0?r+(r==1?" minute, ":" minutes, "):"",o=s>=0?s+(s==1?" second":" seconds"):"";return i+n+o}function m(e){try{if(!e.includes("~ytdlp-progress-"))throw new Error;let t=e.trim().replace("~ytdlp-progress-","");if(!t)throw new Error;let r=JSON.parse(t),s=l=>{if(l==null||l==="NA")return;let f=Number(l);return isNaN(f)?void 0:f},i=s(r.downloaded_bytes),n=s(r.total_bytes)??s(r.total_bytes_estimate),o=s(r.speed),a=s(r.eta),u=i!==void 0&&n!==void 0&&n>0?ve(100*i/n,2):void 0;return{filename:r.filename,status:r.status,downloaded:i,downloaded_str:i!==void 0?z(i):void 0,total:n,total_str:n!==void 0?z(n):void 0,speed:o,speed_str:o!==void 0?z(o)+"/s":void 0,eta:a,eta_str:a!==void 0?Fe(a):void 0,percentage:u,percentage_str:u!==void 0?u+"%":void 0}}catch{return}}import q from"path";import V from"fs";import*as Ae from"https";import*as De from"http";import{URL as ne}from"url";import*as g from"fs";function J(e,t={}){return new Promise((r,s)=>{let o=(new ne(e).protocol==="https:"?Ae:De).get(e,t,a=>{if(a.statusCode>=300&&a.statusCode<400&&a.headers.location){let u=new ne(a.headers.location,e).toString();J(u,t).then(r).catch(s);return}r(a)});o.on("error",s),o.setTimeout(3e4,()=>{o.destroy(),s(new Error("Request timed out"))})})}async function A(e,t){try{let r=g.createWriteStream(t),s=await J(e);if(s.statusCode!==200)throw r.close(),g.unlinkSync(t),new Error(`Failed to download file: ${s.statusCode} ${s.statusMessage}`);let i=parseInt(s.headers["content-length"]||"0",10),n=0;return s.on("data",o=>{n+=o.length;let a=n/i*100;process.stdout.write(`Progress: ${Math.round(a)}%\r`)}),s.pipe(r),new Promise((o,a)=>{r.on("finish",()=>{r.close(),console.log(` | ||
| Download complete!`),o()}),r.on("error",u=>{r.close(),g.unlinkSync(t),a(u)}),s.on("error",u=>{r.close(),g.unlinkSync(t),a(u)})})}catch(r){throw g.existsSync(t)&&g.unlinkSync(t),r}}async function oe(e,t={}){let r=await J(e,t);if(r.statusCode!==200)throw new Error(`Failed to fetch text: ${r.statusCode} ${r.statusMessage}`);return new Promise((s,i)=>{let n="";r.setEncoding("utf8"),r.on("data",o=>{n+=o}),r.on("end",()=>s(n)),r.on("error",i)})}import*as ae from"fs";import*as D from"path";function ke(e){let t=e;for(;;){if(ae.existsSync(D.join(t,"package.json")))return t;let r=D.dirname(t);if(r===t)return e;t=r}}var ue=ke(h),y=D.join(ue,"bin"),nt=D.join(ue,"package.json");var Se="https://github.com/iqbal-rashed/ytdlp-nodejs/releases/download/ffmpeg-latest",Y={win32:{x64:["win-x64-ffmpeg.exe","win-x64-ffprobe.exe"],ia32:["win-ia32-ffmpeg.exe","win-ia32-ffprobe.exe"],arm64:["win-arm64-ffmpeg.exe","win-arm64-ffprobe.exe"]},linux:{x64:["linux-x64-ffmpeg","linux-x64-ffprobe"],arm64:["linux-arm64-ffmpeg","linux-arm64-ffprobe"]},darwin:{x64:["macos-x64-ffmpeg","macos-x64-ffprobe"],arm64:["macos-arm64-ffmpeg","macos-arm64-ffprobe"]},android:{arm64:["linux-arm64-ffmpeg","linux-arm64-ffprobe"]}};function le(){let e=process.platform,t=process.arch;if(!Y[e]||!Y[e][t])throw new Error(`No FFmpeg build available for platform: ${e}, architecture: ${t}`);return Y[e][t]}async function Q(e){let t=e||y,r=F();if(r)return r;try{let s=le();if(!s.length)throw new Error;let i=s.map(o=>`${Se}/${o}`),n=s.map(o=>q.join(t,String(o.split("-").pop())));V.existsSync(t)||V.mkdirSync(t,{recursive:!0}),console.log("Downloading FFmpeg and FFprobe...");for(let o=0;o<s.length;o++){let a=i[o],u=n[o];console.log("Downloading...",q.basename(a)),await A(a,u)}if(process.platform!=="win32")for(let o of n)V.chmodSync(o,493);return F()}catch(s){throw console.error(`Download failed: ${s}`),s}}function F(){try{let e=le();if(!e.length)throw new Error;let t=q.join(y,String(e[0].split("-").pop()));if(!V.existsSync(t))throw new Error("FFmpeg binary not found. Please download it first.");return t}catch{return}}import*as p from"fs";import*as T from"path";import _e from"crypto";var fe="https://github.com/yt-dlp/yt-dlp/releases/latest/download",C={win32:{x64:"yt-dlp.exe",ia32:"yt-dlp_x86.exe"},linux:{x64:"yt-dlp",armv7l:"yt-dlp_linux_armv7l",aarch64:"yt-dlp_linux_aarch64",arm64:"yt-dlp"},darwin:{x64:"yt-dlp_macos",arm64:"yt-dlp_macos"},android:{arm64:"yt-dlp"}};function Be(){let e=process.platform,t=process.arch;if(!C[e]||!C[e][t])throw new Error(`No yt-dlp build available for ${e} ${t}`);return C[e][t]}async function $(e){let t=e||y,r=Be(),s=`${fe}/${r}`,i=T.join(t,r);if(p.existsSync(i))return i;console.log("Downloading yt-dlp...",s),p.existsSync(t)||p.mkdirSync(t,{recursive:!0});try{return await A(s,i),console.log(`yt-dlp downloaded successfully to: ${i}`),process.platform!=="win32"&&p.chmodSync(i,493),i}catch(o){throw console.error(`Download failed: ${o}`),o}}async function Te(e){return new Promise((t,r)=>{let s=_e.createHash("sha256"),i=p.createReadStream(e);i.on("data",n=>s.update(n)),i.on("end",()=>t(s.digest("hex"))),i.on("error",r)})}async function Ee(e){try{let s=(await oe(`${fe}/SHA2-256SUMS`)).split(/\r?\n/).find(n=>n.includes(e));if(!s)return;let[i]=s.trim().split(/\s+/);return i||void 0}catch{return}}async function G(e){let t=await $(e),r=T.basename(t),s=await Ee(r);if(!s)return{path:t,verified:!1};let i=await Te(t);if(i.toLowerCase()!==s.toLowerCase())throw new Error(`Checksum mismatch for ${r}. Expected ${s}, got ${i}`);return{path:t,verified:!0,checksum:s}}function E(){let e=process.platform,t=process.arch;try{let r=C[e][t],s=T.join(y,r);if(!p.existsSync(s))throw new Error("Ytdlp binary not found. Please download it first.");return s}catch{return}}function N(e){return e.replace(/~ytdlp-progress-\{[\s\S]*?\}\n?/g,"").split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0).filter(t=>!t.includes("__YTDLP_FILEPATH__:")).filter(t=>!t.includes("__YTDLP_VIDEO_INFO__:")).filter(t=>!t.includes("__YTDLP_BEFORE_DL__:")).join(` | ||
| `)}function j(e){let t=[],r=e.split(/\r?\n/);for(let s of r){let i=s.trim();if(i.startsWith("__YTDLP_VIDEO_INFO__:")){let n=i.replace("__YTDLP_VIDEO_INFO__:","").trim();try{let o=n.replace(/:"N\/A"/g,":null").replace(/:"NA"/g,":null").replace(/:""/g,':"NA"'),a=JSON.parse(o),u={};for(let[l,f]of Object.entries(a))if(f==="NA")u[l]=null;else if(typeof f=="string"&&f==="N/A")u[l]=null;else if((l.includes("_count")||l.includes("_timestamp")||l==="autonumber"||l==="video_autonumber"||l==="n_entries"||l==="playlist_count"||l==="release_year"||l==="start_time"||l==="end_time"||l==="epoch"||l==="duration"||l==="age_limit")&&typeof f=="string"){let d=Number(f);u[l]=isNaN(d)?null:d}else(l==="is_live"||l==="was_live"||l==="channel_is_verified")&&typeof f=="string"?u[l]=f==="true"||f==="True":(l==="categories"||l==="tags"||l==="creators"||l==="cast")&&typeof f=="string"?f==="NA"||f==="N/A"||f===""?u[l]=null:u[l]=f.split(",").map(d=>d.trim()):u[l]=f;t.push(u)}catch{}}}return t}function w(e){let t=e.trim();if(!t.startsWith("__YTDLP_BEFORE_DL__:"))return null;let r=t.replace("__YTDLP_BEFORE_DL__:","").trim();try{let s=r.replace(/:"N\/A"/g,":null").replace(/:"NA"/g,":null").replace(/:""/,':"NA"'),i=JSON.parse(s),n={};for(let[o,a]of Object.entries(i))if(a==="NA"||a==="N/A")n[o]=null;else if((o.includes("_count")||o.includes("_timestamp")||o==="autonumber"||o==="video_autonumber"||o==="n_entries"||o==="playlist_count"||o==="release_year"||o==="start_time"||o==="end_time"||o==="epoch"||o==="duration"||o==="age_limit")&&typeof a=="string"){let u=Number(a);n[o]=isNaN(u)?null:u}else(o==="is_live"||o==="was_live"||o==="channel_is_verified")&&typeof a=="string"?n[o]=a==="true"||a==="True":(o==="categories"||o==="tags"||o==="creators"||o==="cast")&&typeof a=="string"?a==="NA"||a==="N/A"||a===""?n[o]=null:n[o]=a.split(",").map(u=>u.trim()):n[o]=a;return n}catch{return null}}import{EventEmitter as Ie}from"node:events";function de({url:e,options:t,ffmpegPath:r,withProgressTemplate:s,extra:i}){let n=R(t||{});return r&&n.push("--ffmpeg-location",r),s&&n.push("--progress-template",O),i&&i.length>0&&n.push(...i),e&&n.push("--",e),n}import he from"node:fs";var x=class extends Ie{constructor(r,s){super();this.binaryPath="";this.videoUrl="";this.extraArgs={};this.rawArgs=[];this.videoUrl=r,this.binaryPath=s?.binaryPath||E()||"",this.ffmpegPath=s?.ffmpegPath||F(),(!this.binaryPath||!he.existsSync(this.binaryPath))&&console.error(new Error("yt-dlp binary not found. Please install yt-dlp or specify correct binaryPath in options.")),this.ffmpegPath&&!he.existsSync(this.ffmpegPath)&&console.error(new Error(`FFmpeg binary not found at: ${this.ffmpegPath}. Please install FFmpeg or specify correct ffmpegPath.`))}setBinaryPath(r){return this.binaryPath=r,this}setFfmpegPath(r){return this.ffmpegPath=r,this}format(r){return this.formatValue=r,this}filter(r){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={...s,filter:r},this}quality(r){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={filter:this.formatValue,...s,quality:r},this}type(r){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={filter:this.formatValue,...s,type:r},this}options(r){return this.extraArgs={...this.extraArgs,...r},this}rateLimit(r){return this.extraArgs.limitRate=r,this}cookies(r){return this.extraArgs.cookies=r,this}cookiesFromBrowser(r){return this.extraArgs.cookiesFromBrowser=r,this}proxy(r){return this.extraArgs.proxy=r,this}addOption(r,s){return this.extraArgs[r]=s,this}addArgs(...r){return this.rawArgs.push(...r),this}extractAudio(r){return this.extraArgs.extractAudio=!0,r&&(this.extraArgs.audioFormat=r),this}audioFormat(r){return this.extraArgs.audioFormat=r,this}audioQuality(r){return this.extraArgs.audioQuality=r,this}embedThumbnail(){return this.extraArgs.embedThumbnail=!0,this}embedSubs(){return this.extraArgs.embedSubs=!0,this}embedMetadata(){return this.extraArgs.embedMetadata=!0,this}writeSubs(){return this.extraArgs.writeSubs=!0,this}writeAutoSubs(){return this.extraArgs.writeAutoSubs=!0,this}subLangs(r){return this.extraArgs.subLangs=r,this}writeThumbnail(){return this.extraArgs.writeThumbnail=!0,this}username(r){return this.extraArgs.username=r,this}password(r){return this.extraArgs.password=r,this}playlistStart(r){return this.extraArgs.playlistStart=r,this}playlistEnd(r){return this.extraArgs.playlistEnd=r,this}playlistItems(r){return this.extraArgs.playlistItems=r,this}buildFormatArgs(){return this.formatValue?B(this.formatValue):[]}buildBaseArgs(r=[]){if(!this.videoUrl)throw new Error("URL is required.");let s=this.buildFormatArgs();return de({url:this.videoUrl,options:this.extraArgs,ffmpegPath:this.ffmpegPath,withProgressTemplate:!0,extra:[...s,...r,...this.rawArgs]})}debugPrint(r=!0){return this.extraArgs.debugPrintCommandLine=r,this}getCommand(){let r=this.buildArgs();return`${this.binaryPath} ${r.join(" ")}`}printDebugCommandLine(r){if(this.extraArgs.debugPrintCommandLine){let s=`${this.binaryPath} ${r.join(" ")}`;console.error(`[ytdlp-nodejs] Command: ${s}`)}}validateBinaryPath(){if(!this.binaryPath)throw new Error("Binary path is required. Use .setBinaryPath() or pass it in constructor.")}kill(r){return this.process?.kill(r)??!1}get pid(){return this.process?.pid}};var ce=["id","title","fulltitle","ext","alt_title","description","display_id","uploader","uploader_id","uploader_url","license","creators","creator","timestamp","upload_date","release_timestamp","release_date","release_year","modified_timestamp","modified_date","channel","channel_id","channel_url","channel_follower_count","channel_is_verified","location","duration","duration_string","view_count","concurrent_view_count","like_count","dislike_count","repost_count","average_rating","comment_count","save_count","age_limit","live_status","is_live","was_live","playable_in_embed","availability","media_type","start_time","end_time","extractor","extractor_key","epoch","autonumber","video_autonumber","n_entries","playlist_id","playlist_title","playlist","playlist_count","playlist_index","playlist_autonumber","playlist_uploader","playlist_uploader_id","playlist_channel","playlist_channel_id","playlist_webpage_url","webpage_url","webpage_url_basename","webpage_url_domain","original_url","categories","tags","cast","filepath"];function Re(){return`after_move:__YTDLP_VIDEO_INFO__:{${ce.map(t=>`"${t}":%(${t}|null)j`).join(",")}}`}function k(){return`before_dl:__YTDLP_BEFORE_DL__:{${ce.map(t=>`"${t}":%(${t}|null)j`).join(",")}}`}function L(){return["--print",Re(),"--progress","--newline"]}import{spawn as Oe}from"node:child_process";var S=class extends x{constructor(t,r){super(t,r),this.on("error",()=>{})}on(t,r){return super.on(t,r)}once(t,r){return super.once(t,r)}emit(t,...r){return super.emit(t,...r)}output(t){return this.outputDir=t,this}setOutputTemplate(t){return this.outputPath=t,this}skipDownload(){return this.extraArgs.skipDownload=!0,this}buildArgs(){let t={...this.extraArgs};this.outputDir&&(t.output=`${this.outputDir}/%(title)s.%(ext)s`),this.outputPath&&(t.output=this.outputPath);let r=this.extraArgs;this.extraArgs=t;let s=[...L()];this.listenerCount("beforeDownload")>0&&s.unshift("--print",k());let i=this.buildBaseArgs(s);return this.extraArgs=r,i}run(){return this.resultPromise?this.resultPromise:(this.resultPromise=new Promise((t,r)=>{try{this.validateBinaryPath();let s=this.buildArgs(),i=`${this.binaryPath} ${s.join(" ")}`;this.printDebugCommandLine(s),this.process=Oe(this.binaryPath,s),this.emit("start",i);let n="",o="";this.process.stdout?.on("data",a=>{let u=a.toString();n+=u,this.emit("stdout",u);let l=w(u);l&&this.emit("beforeDownload",l);let f=m(u);f&&this.emit("progress",f)}),this.process.stderr?.on("data",a=>{let u=a.toString();o+=u,this.emit("stderr",u);let l=m(u);l&&this.emit("progress",l)}),this.process.on("error",a=>{this.emit("error",a),r(a)}),this.process.on("close",a=>{if(a!==0&&a!==null){let d=new Error(`yt-dlp exited with code ${a}: ${o}`);this.emit("error",d),r(d);return}let u=N(n),l=j(n),f={output:u,filePaths:l.map(d=>d?.filepath??"").filter(Boolean),info:l,stderr:o};this.emit("finish",f),t(f)})}catch(s){r(s)}}),this.resultPromise)}then(t,r){return this.run().then(t,r)}catch(t){return this.run().catch(t)}finally(t){return this.run().finally(t)}};function Ve(e,t){return new S(e,t)}import{PassThrough as Ce}from"node:stream";import{spawn as $e}from"node:child_process";var _=class extends x{constructor(r,s){super(r,s);this.totalBytes=0;this.started=!1;this.on("error",()=>{})}on(r,s){return super.on(r,s)}once(r,s){return super.once(r,s)}emit(r,...s){return super.emit(r,...s)}buildArgs(){let r=["-o","-","--no-playlist","--progress","--no-quiet"];return this.listenerCount("beforeDownload")>0&&r.push("--print",k()),this.buildBaseArgs(r)}startStream(){if(this.started)return this.passThrough;this.validateBinaryPath(),this.started=!0,this.passThrough=new Ce;let r=this.buildArgs(),s=`${this.binaryPath} ${r.join(" ")}`;return this.printDebugCommandLine(r),this.process=$e(this.binaryPath,r,{shell:!1}),this.emit("start",s),this.process.stdout?.on("data",i=>{this.totalBytes+=i.length,this.passThrough.write(i),this.emit("data",i)}),this.process.stderr?.on("data",i=>{let n=i.toString(),o=w(n);o&&this.emit("beforeDownload",o);let a=m(n);a&&this.emit("progress",a)}),this.process.on("error",i=>{this.emit("error",i),this.passThrough.destroy(i)}),this.process.on("close",i=>{if(i!==0&&i!==null){let n=new Error(`yt-dlp exited with code ${i}`);this.emit("error",n),this.passThrough.destroy(n)}else this.passThrough.end(),this.emit("end")}),this.passThrough}pipe(r,s){let i=Date.now(),n=this.startStream();return new Promise((o,a)=>{n.pipe(r,s),r.on("finish",()=>{o({bytes:this.totalBytes,duration:Date.now()-i})}),r.on("error",a),this.passThrough.on("error",a)})}pipeAsync(r,s){return this.pipe(r,s)}async toBuffer(){let r=[];return new Promise((s,i)=>{let n=this.startStream();n.on("data",o=>{r.push(o)}),n.on("end",()=>{s(Buffer.concat(r))}),n.on("error",i)})}getStream(){return this.startStream()}};function Ne(e,t){return new _(e,t)}import{PassThrough as je}from"node:stream";import{spawn as me}from"node:child_process";var P=class extends x{constructor(r,s){super(r,s);this.totalBytes=0;this.started=!1;this.output="";this.on("error",()=>{})}on(r,s){return super.on(r,s)}once(r,s){return super.once(r,s)}emit(r,...s){return super.emit(r,...s)}buildArgs(){let r=[],s=[...L()];return this.listenerCount("beforeDownload")>0&&s.unshift("--print",k()),this.listenerCount("afterDownload")>0&&s.push("--print","after_move:filepath"),this.buildBaseArgs([...r,...s])}startStream(){if(this.started)return this.passThrough;this.validateBinaryPath(),this.started=!0,this.passThrough=new je,this.output="";let r=this.buildArgs();r.includes("--no-playlist")||(r=["--no-playlist",...r]);let s=`${this.binaryPath} ${r.join(" ")}`;return this.printDebugCommandLine(r),this.process=me(this.binaryPath,r,{shell:!1}),this.emit("start",s),this.process.stdout?.on("data",i=>{this.totalBytes+=i.length,this.passThrough.write(i),this.emit("data",i);let n=i.toString();this.emit("stdout",n);let o=w(n);o&&(this.beforeDownloadInfo=o,this.emit("beforeDownload",this.beforeDownloadInfo));let a=m(n);a&&this.emit("progress",a)}),this.process.stderr?.on("data",i=>{let n=i.toString();this.emit("stderr",n),this.output+=n;let o=w(n);o&&(this.beforeDownloadInfo=o,this.emit("beforeDownload",this.beforeDownloadInfo));let a=m(n);a&&(this.emit("progress",a),a.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:a.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.on("error",i=>{this.emit("error",i),this.passThrough.destroy(i)}),this.process.on("close",i=>{if(i!==0&&i!==null){let n=new Error(`yt-dlp exited with code ${i}`);this.emit("error",n),this.passThrough.destroy(n)}else this.passThrough.end(),this.emit("end")}),this.passThrough}pipe(r,s){let i=Date.now(),n=this.startStream();return new Promise((o,a)=>{n.pipe(r,s),r.on("finish",()=>{o({bytes:this.totalBytes,duration:Date.now()-i,info:this.afterDownloadInfo,output:this.output})}),r.on("error",a),this.passThrough.on("error",a)})}pipeAsync(r,s){return this.pipe(r,s)}async toBuffer(){let r=[];return new Promise((s,i)=>{let n=this.startStream();n.on("data",o=>{r.push(o)}),n.on("end",()=>{s(Buffer.concat(r))}),n.on("error",i)})}getStream(){return this.startStream()}exec(){return this.resultPromise?this.resultPromise:(this.resultPromise=new Promise((r,s)=>{try{this.validateBinaryPath();let i=this.buildArgs(),n=`${this.binaryPath} ${i.join(" ")}`;this.printDebugCommandLine(i),this.process=me(this.binaryPath,i,{shell:!1}),this.emit("start",n);let o="",a="";this.process.stdout?.on("data",u=>{let l=u.toString();o+=l,this.emit("stdout",l);let f=w(l);f&&(this.beforeDownloadInfo=f,this.emit("beforeDownload",this.beforeDownloadInfo)),this.emit("data",u);let d=m(l);d&&(this.emit("progress",d),d.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:d.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.stderr?.on("data",u=>{let l=u.toString();a+=l,this.emit("stderr",l);let f=w(l);f&&(this.beforeDownloadInfo=f,this.emit("beforeDownload",this.beforeDownloadInfo));let d=m(l);d&&(this.emit("progress",d),d.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:d.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.on("error",u=>{this.emit("error",u),s(u)}),this.process.on("close",u=>{let l=N(o),f=j(o),d={stdout:o,stderr:a,exitCode:u,command:n,info:f,output:l,filePaths:f.map(b=>b?.filepath??"").filter(Boolean)};this.emit("complete",d),this.emit("end"),r(d)})}catch(i){s(i)}}),this.resultPromise)}run(){return this.exec()}then(r,s){return this.exec().then(r,s)}catch(r){return this.exec().catch(r)}finally(r){return this.exec().finally(r)}};function Le(e,t){return new P(e,t)}var ge=class{constructor(t){this.binaryPath=t?.binaryPath||E()||"",this.ffmpegPath=t?.ffmpegPath||F(),(!this.binaryPath||!Z.existsSync(this.binaryPath))&&console.error(new Error("yt-dlp binary not found. Please install yt-dlp or specify correct binaryPath in options.")),this.ffmpegPath&&!Z.existsSync(this.ffmpegPath)&&console.error(new Error(`FFmpeg binary not found at: ${this.ffmpegPath}. Please install FFmpeg or specify correct ffmpegPath.`))}async checkInstallationAsync(t){return new Promise((r,s)=>{if(t?.ffmpeg&&!this.ffmpegPath)return s(new Error("FFmpeg path is not set"));let i=H(this.binaryPath,["--version"]),n=!1,o=!t?.ffmpeg;i.on("error",()=>n=!1),i.on("exit",a=>{if(n=a===0,t?.ffmpeg){let u=H(this.ffmpegPath,["-version"]);u.on("error",()=>o=!1),u.on("exit",l=>{o=l===0,r(n&&o)})}else r(n)})})}checkInstallation(t){if(t?.ffmpeg&&!this.ffmpegPath)throw new Error("FFmpeg path is not set");let r=pe(this.binaryPath,["--version"],{stdio:"ignore"}),s=t?.ffmpeg?pe(this.ffmpegPath,["-version"],{stdio:"ignore"}):{status:0};return r.status===0&&s.status===0}async getInfoAsync(t,r){let s=await this.execAsync(t,{dumpSingleJson:!0,flatPlaylist:!0,...r});return JSON.parse(s.output)}async execAsync(t,r){let s=new P(t,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{onData:i,onProgress:n,onBeforeDownload:o,pipeTo:a,...u}=r||{};return u&&s.options(u),i&&s.on("stdout",i),n&&s.on("progress",n),o&&s.on("beforeDownload",o),a?s.pipe(a):s.exec()}exec(t,r){let s=new P(t,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath});return r&&s.options(r),s}download(t,r){let s=new S(t,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=r||{};return i&&s.format(i),n&&s.options(n),s}async downloadAsync(t,r){let{onProgress:s,beforeDownload:i,...n}=r||{},o=this.download(t,n);s&&o.on("progress",s),i&&o.on("beforeDownload",i);let a=await o.run();return{output:a.output,filePaths:a.filePaths,info:a.info}}stream(t,r){let s=new _(t,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=r||{};return i&&s.format(i),n&&s.options(n),s}execBuilder(t,r){let s=new P(t,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=r||{};return i&&s.format(i),n&&s.options(n),s}async downloadAudio(t,r="mp3",s){let i=["aac","flac","mp3","m4a","opus","vorbis","wav","alac"];if(!i.includes(r))throw new Error(`Invalid audio format: ${r}. Supported: ${i.join(", ")}`);return this.downloadAsync(t,{...s,extractAudio:!0,audioFormat:r})}async downloadVideo(t,r="best",s){let i=["best","2160p","1440p","1080p","720p","480p","360p","240p","144p","highest","lowest"];if(!i.includes(r))throw new Error(`Invalid video quality: ${r}. Supported: ${i.join(", ")}`);let n=r==="best"?"bestvideo+bestaudio/best":`bestvideo[height<=${parseInt(r)||1080}]+bestaudio/best[height<=${parseInt(r)||1080}]`;return this.downloadAsync(t,{...s,format:n})}async getSubtitles(t,r){return(await this.execAsync(t,{...r,listSubs:!0,skipDownload:!0})).output?[]:[]}async getComments(t,r=20,s){let i=await this.execAsync(t,{...s,writeComments:!0,dumpSingleJson:!0,skipDownload:!0,extractorArgs:{youtube:[`max_comments=${r}`,"player_skip=webpage"]}});try{return JSON.parse(i.output).comments||[]}catch{return[]}}async getDirectUrlsAsync(t,r){return(await this.getInfoAsync(t,r)).formats.map(i=>i.url)}async getFormatsAsync(t,r){let s=await this.getInfoAsync(t,r);return{source:"json",info:s,formats:s.formats}}async getThumbnailsAsync(t){return(await this.getInfoAsync(t)).thumbnails}async getTitleAsync(t){return(await this.execAsync(t,{print:"title"})).output.trim()}async getVersionAsync(){return(await this.execAsync("",{printVersion:!0})).output.trim()}async downloadFFmpeg(){return Q()}async getFileAsync(t,r){let s,{onBeforeDownload:i,onProgress:n,filename:o,metadata:a,format:u,...l}=r||{},f=[],d=new We;d.on("data",v=>f.push(Buffer.from(v)));let b=B(u),K={...l};if(b.length>=2&&b[0]==="-f"&&(K.format=b[1]),b.includes("--merge-output-format")){let v=b.indexOf("--merge-output-format");K.mergeOutputFormat=b[v+1]}await this.execAsync(t,{...K,noPlaylist:!0,pipeTo:d,onProgress:n,onBeforeDownload:v=>{s=v,i?.(v)},output:"-"});let I,M;u&&typeof u=="object"?(I=W(u),M=U(u)):(I=se(l)||"video/mp4",M=ie(l)||"mp4");let we=new Me(f,{type:I}),X={name:o||`${s?.title||"download"}.${M}`,type:I,size:we.size,...a};return new File([Buffer.concat(f)],X.name,{type:X.type})}async getUrlsAsync(t,r){return(await this.execAsync(t,{...r,print:"urls"})).output.split(` | ||
| `).filter(Boolean)}async updateYtDlpAsync(t){if(t?.preferBuiltIn!==!1&&this.binaryPath)try{await this.execAsync("",{update:!0});let a=await this.getVersionAsync().catch(()=>{});return{method:"built-in",binaryPath:this.binaryPath,version:a}}catch{}let s=t?.outDir||(this.binaryPath?Ke.dirname(this.binaryPath):void 0);if(t?.verifyChecksum!==!1){let a=await G(s),u=await this.getVersionAsyncUsingBinary(a.path).catch(()=>{});return{method:"download",binaryPath:a.path,version:u,verified:a.verified}}let n=await $(s),o=await this.getVersionAsyncUsingBinary(n).catch(()=>{});return{method:"download",binaryPath:n,version:o,verified:!1}}async getVersionAsyncUsingBinary(t){return new Promise((r,s)=>{let i=H(t,["--version"]),n="",o="";i.stdout?.on("data",a=>{n+=a.toString()}),i.stderr?.on("data",a=>{o+=a.toString()}),i.on("close",a=>{a===0?r(n.trim()):s(new Error(`Failed to get version: ${o}`))}),i.on("error",s)})}},Pr={downloadFFmpeg:Q,findFFmpegBinary:F,PROGRESS_STRING:O,getContentType:W,getFileExtension:U,parseFormatOptions:B,stringToProgress:m,createArgs:R,extractThumbnails:ee,downloadFile:A,BIN_DIR:y,downloadYtDlp:$,downloadYtDlpVerified:G,findYtdlpBinary:E};export{y as BIN_DIR,S as Download,P as Exec,_ as Stream,ge as YtDlp,Ve as createDownload,Le as createExec,Ne as createStreamBuilder,Pr as helpers}; | ||
| import{fileURLToPath as Pe}from"url";import ve from"path";var Fe=()=>Pe(import.meta.url),Ae=()=>ve.dirname(Fe()),h=Ae();import{spawn as Z,spawnSync as ye}from"child_process";import*as X from"fs";import Ye from"path";import{Blob as qe}from"buffer";import{PassThrough as Qe}from"stream";function O(e){let r=[];if(e.printHelp&&r.push("--help"),e.printVersion&&r.push("--version"),e.update&&r.push("--update"),e.noUpdate&&r.push("--no-update"),e.updateTo&&r.push("--update-to",e.updateTo),e.ignoreErrors&&r.push("--ignore-errors"),e.noAbortOnError&&r.push("--no-abort-on-error"),e.abortOnError&&r.push("--abort-on-error"),e.dumpUserAgent&&r.push("--dump-user-agent"),e.listExtractors&&r.push("--list-extractors"),e.extractorDescriptions&&r.push("--extractor-descriptions"),e.useExtractors&&e.useExtractors.length>0&&r.push("--use-extractors",e.useExtractors.join(",")),e.defaultSearch&&r.push("--default-search",e.defaultSearch),e.ignoreConfig&&r.push("--ignore-config"),e.noConfigLocations&&r.push("--no-config-location"),e.configLocations&&e.configLocations.length>0&&r.push("--config-locations",...e.configLocations),e.pluginDirs&&e.pluginDirs.length>0)for(let s of e.pluginDirs)r.push("--plugin-dirs",s);e.noPluginDirs&&r.push("--no-plugin-dirs"),e.flatPlaylist&&r.push("--flat-playlist"),e.noFlatPlaylist&&r.push("--no-flat-playlist"),e.liveFromStart&&r.push("--live-from-start"),e.noLiveFromStart&&r.push("--no-live-from-start"),e.waitForVideo&&r.push("--wait-for-video",e.waitForVideo.toString()),e.noWaitForVideo&&r.push("--no-wait-for-video"),e.markWatched&&r.push("--mark-watched"),e.noMarkWatched&&r.push("--no-mark-watched"),e.color&&r.push("--color",e.color),e.compatOptions&&e.compatOptions.length>0&&r.push("--compat-options",e.compatOptions.join(",")),e.aliases&&e.aliases.length>0&&r.push("--alias",...e.aliases);let t=e.jsRuntime??"node";if(t&&r.push("--js-runtime",t),e.proxy&&r.push("--proxy",e.proxy),e.socketTimeout&&r.push("--socket-timeout",e.socketTimeout.toString()),e.sourceAddress&&r.push("--source-address",e.sourceAddress),e.impersonate&&e.impersonate.length>0&&r.push("--impersonate",e.impersonate.join(",")),e.listImpersonateTargets&&r.push("--list-impersonate-targets"),e.forceIpv4&&r.push("--force-ipv4"),e.forceIpv6&&r.push("--force-ipv6"),e.enableFileUrls&&r.push("--enable-file-urls"),e.geoVerificationProxy&&r.push("--geo-verification-proxy",e.geoVerificationProxy),e.xff&&r.push("--xff",e.xff),e.playlistItems&&r.push("--playlist-items",e.playlistItems),e.minFilesize&&r.push("--min-filesize",e.minFilesize),e.maxFilesize&&r.push("--max-filesize",e.maxFilesize),e.date&&r.push("--date",e.date),e.dateBefore&&r.push("--datebefore",e.dateBefore),e.dateAfter&&r.push("--dateafter",e.dateAfter),e.matchFilter&&r.push("--match-filter",e.matchFilter),e.noMatchFilters&&r.push("--no-match-filters"),e.breakMatchFilters&&r.push("--break-match-filters",e.breakMatchFilters),e.noBreakMatchFilters&&r.push("--no-break-match-filters"),e.noPlaylist&&r.push("--no-playlist"),e.yesPlaylist&&r.push("--yes-playlist"),e.ageLimit&&r.push("--age-limit",e.ageLimit.toString()),e.downloadArchive&&r.push("--download-archive",e.downloadArchive),e.noDownloadArchive&&r.push("--no-download-archive"),e.maxDownloads&&r.push("--max-downloads",e.maxDownloads.toString()),e.breakOnExisting&&r.push("--break-on-existing"),e.noBreakOnExisting&&r.push("--no-break-on-existing"),e.breakPerInput&&r.push("--break-per-input"),e.noBreakPerInput&&r.push("--break-per-input"),e.skipPlaylistAfterErrors&&r.push("--skip-playlist-after-errors",e.skipPlaylistAfterErrors.toString()),e.concurrentFragments&&r.push("--concurrent-fragments",e.concurrentFragments.toString()),e.limitRate&&r.push("--limit-rate",e.limitRate),e.throttledRate&&r.push("--throttled-rate",e.throttledRate),e.retries&&r.push("--retries",e.retries.toString()),e.fileAccessRetries&&r.push("--file-access-retries",e.fileAccessRetries.toString()),e.fragmentRetries&&r.push("--fragment-retries",e.fragmentRetries.toString()),e.retrySleep&&r.push("--retry-sleep",e.retrySleep.toString()),e.retrySleepByType)for(let[s,i]of Object.entries(e.retrySleepByType))r.push("--retry-sleep",`${s}:${i}`);if(e.skipUnavailableFragments&&r.push("--skip-unavailable-fragments"),e.abortOnUnavailableFragment&&r.push("--abort-on-unavailable-fragment"),e.keepFragments&&r.push("--keep-fragments"),e.noKeepFragments&&r.push("--no-keep-fragments"),e.bufferSize&&r.push("--buffer-size",e.bufferSize),e.resizeBuffer&&r.push("--resize-buffer"),e.noResizeBuffer&&r.push("--no-resize-buffer"),e.httpChunkSize&&r.push("--http-chunk-size",e.httpChunkSize),e.playlistRandom&&r.push("--playlist-random"),e.lazyPlaylist&&r.push("--lazy-playlist"),e.noLazyPlaylist&&r.push("--no-lazy-playlist"),e.xattrSetFilesize&&r.push("--xattr-set-filesize"),e.hlsUseMpegts&&r.push("--hls-use-mpegts"),e.noHlsUseMpegts&&r.push("--no-hls-use-mpegts"),e.downloadSections&&r.push("--download-sections",e.downloadSections.toString()),e.downloader&&r.push("--downloader",e.downloader),e.downloaderArgs&&r.push("--downloader-args",e.downloaderArgs),e.batchFile&&r.push("--batch-file",e.batchFile),e.noBatchFile&&r.push("--no-batch-file"),e.paths)if(typeof e.paths=="string")r.push("--paths",e.paths);else for(let[s,i]of Object.entries(e.paths))r.push("--paths",`${s}:${i}`);if(e.output&&r.push("-o",e.output),e.outputNaPlaceholder&&r.push("--output-na-placeholder",e.outputNaPlaceholder),e.restrictFilenames&&r.push("--restrict-filenames"),e.noRestrictFilenames&&r.push("--no-restrict-filenames"),e.windowsFilenames&&r.push("--windows-filenames"),e.noWindowsFilenames&&r.push("--no-windows-filenames"),e.trimFileNames&&r.push("--trim-file-names",e.trimFileNames.toString()),e.noOverwrites&&r.push("--no-overwrites"),e.forceOverwrites&&r.push("--force-overwrites"),e.noForceOverwrites&&r.push("--no-force-overwrites"),e.continue&&r.push("--continue"),e.noContinue&&r.push("--no-continue"),e.part&&r.push("--part"),e.noPart&&r.push("--no-part"),e.mtime&&r.push("--mtime"),e.noMtime&&r.push("--no-mtime"),e.writeDescription&&r.push("--write-description"),e.noWriteDescription&&r.push("--no-write-description"),e.writeInfoJson&&r.push("--write-info-json"),e.noWriteInfoJson&&r.push("--no-write-info-json"),e.writePlaylistMetafiles&&r.push("--write-playlist-metafiles"),e.noWritePlaylistMetafiles&&r.push("--no-write-playlist-metafiles"),e.cleanInfoJson&&r.push("--clean-info-json"),e.noCleanInfoJson&&r.push("--no-clean-info-json"),e.writeComments&&r.push("--write-comments"),e.noWriteComments&&r.push("--no-write-comments"),e.loadInfoJson&&r.push("--load-info-json",e.loadInfoJson.toString()),e.cookies&&r.push("--cookies",e.cookies),e.noCookies&&r.push("--no-cookies"),e.cookiesFromBrowser&&r.push("--cookies-from-browser",e.cookiesFromBrowser),e.noCookiesFromBrowser&&r.push("--no-cookies-from-browser"),e.cacheDir&&r.push("--cache-dir",e.cacheDir),e.noCacheDir&&r.push("--no-cache-dir"),e.rmCacheDir&&r.push("--rm-cache-dir"),e.writeThumbnail&&r.push("--write-thumbnail"),e.noWriteThumbnails&&r.push("--no-write-thumbnails"),e.writeAllThumbnails&&r.push("--write-all-thumbnails"),e.listThumbnails&&r.push("--list-thumbnails"),e.writeLink&&r.push("--write-link"),e.writeUrlLink&&r.push("--write-url-link"),e.writeWeblocLink&&r.push("--write-webloc-link"),e.writeDesktopLink&&r.push("--write-desktop-link"),e.quiet&&r.push("--quiet"),e.noQuiet&&r.push("--no-quiet"),e.noWarnings&&r.push("--no-warnings"),e.simulate&&r.push("--simulate"),e.noSimulate&&r.push("--no-simulate"),e.ignoreNoFormatsError&&r.push("--ignore-no-formats-error"),e.noIgnoreNoFormatsError&&r.push("--no-ignore-no-formats-error"),e.skipDownload&&r.push("--skip-download"),e.print&&r.push("--print",e.print),e.printToFile&&r.push("--print-to-file",e.printToFile),e.dumpJson&&r.push("--dump-json"),e.dumpSingleJson&&r.push("--dump-single-json"),e.forceWriteArchive&&r.push("--force-write-archive"),e.newline&&r.push("--newline"),e.noProgress&&r.push("--no-progress"),e.progress&&r.push("--progress"),e.consoleTitle&&r.push("--console-title"),e.progressTemplate&&r.push("--progress-template",e.progressTemplate),e.progressDelta&&r.push("--progress-delta",e.progressDelta.toString()),e.verbose&&r.push("--verbose"),e.dumpPages&&r.push("--dump-pages"),e.writePages&&r.push("--write-pages"),e.printTraffic&&r.push("--print-traffic"),e.encoding&&r.push("--encoding",e.encoding),e.legacyServerConnect&&r.push("--legacy-server-connect"),e.noCheckCertificates&&r.push("--no-check-certificates"),e.preferInsecure&&r.push("--prefer-insecure"),e.addHeaders)for(let[s,i]of Object.entries(e.addHeaders))r.push("--add-header",`${s}:${i}`);if(e.headers)for(let[s,i]of Object.entries(e.headers))r.push("--add-header",`${s}:${i}`);if(e.bidiWorkaround&&r.push("--bidi-workaround"),e.sleepRequests&&r.push("--sleep-requests",e.sleepRequests.toString()),e.sleepInterval&&r.push("--sleep-interval",e.sleepInterval.toString()),e.maxSleepInterval&&r.push("--max-sleep-interval",e.maxSleepInterval.toString()),e.sleepSubtitles&&r.push("--sleep-subtitles",e.sleepSubtitles.toString()),e.format&&r.push("-f",e.format),e.formatSort&&e.formatSort.length>0&&r.push("--format-sort",e.formatSort.join(",")),e.formatSortForce&&r.push("--format-sort-force"),e.noFormatSortForce&&r.push("--no-format-sort-force"),e.videoMultiStreams&&r.push("--video-multistreams"),e.noVideoMultiStreams&&r.push("--no-video-multistreams"),e.audioMultiStreams&&r.push("--audio-multistreams"),e.noAudioMultiStreams&&r.push("--no-audio-multistreams"),e.preferFreeFormats&&r.push("--prefer-free-formats"),e.noPreferFreeFormats&&r.push("--no-prefer-free-formats"),e.checkFormats&&r.push("--check-formats"),e.checkAllFormats&&r.push("--check-all-formats"),e.noCheckFormats&&r.push("--no-check-formats"),e.listFormats&&r.push("--list-formats"),e.mergeOutputFormat&&r.push("--merge-output-format",e.mergeOutputFormat),e.writeSubs&&r.push("--write-subs"),e.noWriteSubs&&r.push("--no-write-subs"),e.writeAutoSubs&&r.push("--write-auto-subs"),e.writeAllSubs&&r.push("--all-subs"),e.listSubs&&r.push("--list-subs"),e.subFormat&&r.push("--sub-format",e.subFormat),e.subLangs&&e.subLangs.length>0&&r.push("--sub-langs",e.subLangs.join(",")),e.username&&r.push("--username",e.username),e.password&&r.push("--password",e.password),e.twoFactor&&r.push("--twofactor",e.twoFactor),e.netrc&&r.push("--netrc"),e.videoPassword&&r.push("--video-password",e.videoPassword),e.apMso&&r.push("--ap-mso",e.apMso),e.apUsername&&r.push("--ap-username",e.apUsername),e.apPassword&&r.push("--ap-password",e.apPassword),e.netrcLocation&&r.push("--netrc-location",e.netrcLocation),e.netrcCmd&&r.push("--netrc-cmd",e.netrcCmd),e.apListMso&&r.push("--ap-list-mso"),e.clientCertificate&&r.push("--client-certificate",e.clientCertificate),e.clientCertificateKey&&r.push("--client-certificate-key",e.clientCertificateKey),e.clientCertificatePassword&&r.push("--client-certificate-password",e.clientCertificatePassword),e.extractorRetries!==void 0&&r.push("--extractor-retries",e.extractorRetries.toString()),e.allowDynamicMpd&&r.push("--allow-dynamic-mpd"),e.ignoreDynamicMpd&&r.push("--ignore-dynamic-mpd"),e.hlsSplitDiscontinuity&&r.push("--hls-split-discontinuity"),e.noHlsSplitDiscontinuity&&r.push("--no-hls-split-discontinuity"),e.extractorArgs)for(let[s,i]of Object.entries(e.extractorArgs))r.push("--extractor-args",`${s}:${i.join(" ")}`);if(e.playlistStart!==void 0&&r.push("--playlist-start",e.playlistStart.toString()),e.playlistEnd!==void 0&&r.push("--playlist-end",e.playlistEnd.toString()),e.matchTitle&&r.push("--match-title",e.matchTitle),e.rejectTitle&&r.push("--reject-title",e.rejectTitle),e.includeAds&&r.push("--include-ads"),e.breakOnReject&&r.push("--break-on-reject"),e.noDownload&&r.push("--no-download"),e.playlistReverse&&r.push("--playlist-reverse"),e.geoBypass&&r.push("--geo-bypass"),e.geoBypassCountry&&r.push("--geo-bypass-country",e.geoBypassCountry),e.geoBypassIpBlock&&r.push("--geo-bypass-ip-block",e.geoBypassIpBlock),e.convertThumbnails&&r.push("--convert-thumbnails",e.convertThumbnails),e.writeLink&&r.push("--write-link"),e.writeUrlLink&&r.push("--write-url-link"),e.writeWeblocLink&&r.push("--write-webloc-link"),e.writeLnkLink&&r.push("--write-lnk-link"),e.referer&&r.push("--referer",e.referer),e.userAgent&&r.push("--user-agent",e.userAgent),e.extractAudio&&r.push("--extract-audio"),e.audioFormat&&r.push("--audio-format",e.audioFormat),e.audioQuality&&r.push("--audio-quality",e.audioQuality),e.remuxVideo&&r.push("--remux-video",e.remuxVideo),e.recodeVideo&&r.push("--recode-video",e.recodeVideo),e.postprocessorArgs)for(let[s,i]of Object.entries(e.postprocessorArgs))r.push("--postprocessor-args",`${s}:${i.join(" ")}`);if(e.keepVideo&&r.push("--keep-video"),e.noKeepVideo&&r.push("--no-keep-video"),e.postOverwrites&&r.push("--post-overwrites"),e.noPostOverwrites&&r.push("--no-post-overwrites"),e.embedSubs&&r.push("--embed-subs"),e.noEmbedSubs&&r.push("--no-embed-subs"),e.embedThumbnail&&r.push("--embed-thumbnail"),e.noEmbedThumbnail&&r.push("--no-embed-thumbnail"),e.embedMetadata&&r.push("--embed-metadata"),e.noEmbedMetadata&&r.push("--no-embed-metadata"),e.embedChapters&&r.push("--embed-chapters"),e.noEmbedChapters&&r.push("--no-embed-chapters"),e.embedInfoJson&&r.push("--embed-info-json"),e.noEmbedInfoJson&&r.push("--no-embed-info-json"),e.parseMetadata)for(let[s,i]of Object.entries(e.parseMetadata))r.push("--parse-metadata",`${s}:${i}`);if(e.replaceInMetadata)for(let[s,[i,n]]of Object.entries(e.replaceInMetadata))r.push("--replace-in-metadata",`${s} ${i} ${n}`);if(e.xattrs&&r.push("--xattrs"),e.concatPlaylist&&r.push("--concat-playlist",e.concatPlaylist),e.fixup&&r.push("--fixup",e.fixup),e.ffmpegLocation&&r.push("--ffmpeg-location",e.ffmpegLocation),e.exec&&r.push("--exec",e.exec),e.noExec&&r.push("--no-exec"),e.convertSubs&&r.push("--convert-subs",e.convertSubs),e.convertThumbnails&&r.push("--convert-thumbnails",e.convertThumbnails),e.splitChapters&&r.push("--split-chapters"),e.noSplitChapters&&r.push("--no-split-chapters"),e.removeChapters&&r.push("--remove-chapters",e.removeChapters),e.noRemoveChapters&&r.push("--no-remove-chapters"),e.forceKeyframesAtCuts&&r.push("--force-keyframes-at-cuts"),e.noForceKeyframesAtCuts&&r.push("--no-force-keyframes-at-cuts"),e.usePostProcessor&&e.usePostProcessor.length>0)for(let s of e.usePostProcessor)r.push("--use-postprocessor",s);return e.sponsorblockMark&&e.sponsorblockMark.length>0&&r.push("--sponsorblock-mark",e.sponsorblockMark.join(",")),e.sponsorblockRemove&&e.sponsorblockRemove.length>0&&r.push("--sponsorblock-remove",e.sponsorblockRemove.join(",")),e.sponsorblockChapterTitle&&r.push("--sponsorblock-chapter-title",e.sponsorblockChapterTitle),e.noSponsorblock&&r.push("--no-sponsorblock"),e.sponsorblockApi&&r.push("--sponsorblock-api",e.sponsorblockApi),e.additionalOptions&&e.additionalOptions.length>0&&r.push(...e.additionalOptions),e.rawArgs&&e.rawArgs.length>0&&r.push(...e.rawArgs),r}function re(e){let r=[],t=e.split(` | ||
| `).slice(1);for(let s of t){let i=s.match(/(\d+)\s+(\S+)\s+(\S+)\s+(https:\/\/[\S]+)/);i&&r.push({id:parseInt(i[1],10),width:i[2]==="unknown"?"unknown":parseInt(i[2],10),height:i[3]==="unknown"?"unknown":parseInt(i[3],10),url:i[4]})}return r}var te={"2160p":"bv*[height<=2160]","1440p":"bv*[height<=1440]","1080p":"bv*[height<=1080]","720p":"bv*[height<=720]","480p":"bv*[height<=480]","360p":"bv*[height<=360]","240p":"bv*[height<=240]","144p":"bv*[height<=133]",highest:"bv*",lowest:"wv*"},se=["audioonly","videoonly","audioandvideo","mergevideo"];function R(e){let r,t,s;if(!e)return[];if(typeof e=="string"&&!se.includes(e))return["-f",e];if(typeof e=="string"&&se.includes(e)&&(r=e),Object.keys(e).length===0||!e||typeof e!="object")return["-f","bv*+ba"];typeof e=="object"&&(r=e.filter,t=e.type,s=e.quality);let i=[];return r==="audioonly"&&(i=["-x","--audio-format",t||"mp3","--audio-quality",s?s.toString():"5"]),r==="videoonly"&&(i=["-f",(s?te[s]:"bv*")+"[acodec=none]"]),r==="audioandvideo"&&(i=["-f",(s=="lowest"?"w*":"b*")+"[vcodec!=none][acodec!=none][ext="+(t||"mp4")+"]"]),r==="mergevideo"&&(i=["-f",`${s?te[s]:"bv*"}+ba`],t&&i.push("--merge-output-format",t)),i}function U(e){if(!e||typeof e=="string")return"video/mp4";let{filter:r,type:t}=e;switch(r){case"videoonly":case"audioandvideo":switch(t){case"mp4":return"video/mp4";case"webm":return"video/webm";default:return"video/mp4"}case"audioonly":switch(t){case"aac":return"audio/aac";case"flac":return"audio/flac";case"mp3":return"audio/mp3";case"m4a":return"audio/mp4";case"opus":return"audio/opus";case"vorbis":return"audio/vorbis";case"wav":return"audio/wav";case"alac":return"audio/mp4";default:return"audio/mpeg"}case"mergevideo":switch(t){case"webm":return"video/webm";case"mkv":return"video/x-matroska";case"ogg":return"video/ogg";case"flv":return"video/x-flv";default:return"video/mp4"}}}function z(e){if(!e||typeof e=="string")return"mp4";let{filter:r,type:t}=e;return t||(r==="audioonly"?"mp3":"mp4")}function ie(e){if(!e?.extractAudio)return null;switch(e.audioFormat||"mp3"){case"aac":return"audio/aac";case"flac":return"audio/flac";case"mp3":return"audio/mpeg";case"m4a":return"audio/mp4";case"opus":return"audio/opus";case"vorbis":return"audio/vorbis";case"wav":return"audio/wav";case"alac":return"audio/mp4";default:return"audio/mpeg"}}function ne(e){return e?.extractAudio?e.audioFormat||"mp3":null}var V="~ytdlp-progress-%(progress)#j";function J(e,r=2){let t=Number(e);if(t===0||isNaN(t))return t+" Bytes";let s=1024,i=r<0?0:r,n=["Bytes","KB","MB","GB","TB","PB","EB","ZB","YB"],o=Math.floor(Math.log(t)/Math.log(s));return parseFloat((t/Math.pow(s,o)).toFixed(i))+" "+n[o]}function ke(e,r,t){let s=Math.pow(t||10,r);return Math.round(e*s)/s}function De(e){e=Number(e);let r=Math.floor(e/3600),t=Math.floor(e%3600/60),s=Math.floor(e%3600%60),i=r>0?r+(r==1?" hour, ":" hours, "):"",n=t>0?t+(t==1?" minute, ":" minutes, "):"",o=s>=0?s+(s==1?" second":" seconds"):"";return i+n+o}function m(e){try{if(!e.includes("~ytdlp-progress-"))throw new Error;let r=e.trim().replace("~ytdlp-progress-","");if(!r)throw new Error;let t=JSON.parse(r),s=l=>{if(l==null||l==="NA")return;let f=Number(l);return isNaN(f)?void 0:f},i=s(t.downloaded_bytes),n=s(t.total_bytes)??s(t.total_bytes_estimate),o=s(t.speed),a=s(t.eta),u=i!==void 0&&n!==void 0&&n>0?ke(100*i/n,2):void 0;return{filename:t.filename,status:t.status,downloaded:i,downloaded_str:i!==void 0?J(i):void 0,total:n,total_str:n!==void 0?J(n):void 0,speed:o,speed_str:o!==void 0?J(o)+"/s":void 0,eta:a,eta_str:a!==void 0?De(a):void 0,percentage:u,percentage_str:u!==void 0?u+"%":void 0}}catch{return}}import Q from"path";import C from"fs";import*as Se from"https";import*as _e from"http";import{URL as oe}from"url";import*as b from"fs";function Y(e,r={}){return new Promise((t,s)=>{let o=(new oe(e).protocol==="https:"?Se:_e).get(e,r,a=>{if(a.statusCode>=300&&a.statusCode<400&&a.headers.location){let u=new oe(a.headers.location,e).toString();Y(u,r).then(t).catch(s);return}t(a)});o.on("error",s),o.setTimeout(3e4,()=>{o.destroy(),s(new Error("Request timed out"))})})}async function A(e,r){try{let t=b.createWriteStream(r),s=await Y(e);if(s.statusCode!==200)throw t.close(),b.unlinkSync(r),new Error(`Failed to download file: ${s.statusCode} ${s.statusMessage}`);let i=parseInt(s.headers["content-length"]||"0",10),n=0;return s.on("data",o=>{n+=o.length;let a=n/i*100;process.stdout.write(`Progress: ${Math.round(a)}%\r`)}),s.pipe(t),new Promise((o,a)=>{t.on("finish",()=>{t.close(),console.log(` | ||
| Download complete!`),o()}),t.on("error",u=>{t.close(),b.unlinkSync(r),a(u)}),s.on("error",u=>{t.close(),b.unlinkSync(r),a(u)})})}catch(t){throw b.existsSync(r)&&b.unlinkSync(r),t}}async function ae(e,r={}){let t=await Y(e,r);if(t.statusCode!==200)throw new Error(`Failed to fetch text: ${t.statusCode} ${t.statusMessage}`);return new Promise((s,i)=>{let n="";t.setEncoding("utf8"),t.on("data",o=>{n+=o}),t.on("end",()=>s(n)),t.on("error",i)})}import*as ue from"fs";import*as k from"path";function Ee(e){let r=e;for(;;){if(ue.existsSync(k.join(r,"package.json")))return r;let t=k.dirname(r);if(t===r)return e;r=t}}var le=Ee(h),w=k.join(le,"bin"),dr=k.join(le,"package.json");var Re="https://github.com/iqbal-rashed/ytdlp-nodejs/releases/download/ffmpeg-latest",q={win32:{x64:["win-x64-ffmpeg.exe","win-x64-ffprobe.exe"],ia32:["win-ia32-ffmpeg.exe","win-ia32-ffprobe.exe"],arm64:["win-arm64-ffmpeg.exe","win-arm64-ffprobe.exe"]},linux:{x64:["linux-x64-ffmpeg","linux-x64-ffprobe"],arm64:["linux-arm64-ffmpeg","linux-arm64-ffprobe"]},darwin:{x64:["macos-x64-ffmpeg","macos-x64-ffprobe"],arm64:["macos-arm64-ffmpeg","macos-arm64-ffprobe"]},android:{arm64:["linux-arm64-ffmpeg","linux-arm64-ffprobe"]}};function fe(){let e=process.platform,r=process.arch;if(!q[e]||!q[e][r])throw new Error(`No FFmpeg build available for platform: ${e}, architecture: ${r}`);return q[e][r]}async function G(e){let r=e||w,t=F();if(t)return t;try{let s=fe();if(!s.length)throw new Error;let i=s.map(o=>`${Re}/${o}`),n=s.map(o=>Q.join(r,String(o.split("-").pop())));C.existsSync(r)||C.mkdirSync(r,{recursive:!0}),console.log("Downloading FFmpeg and FFprobe...");for(let o=0;o<s.length;o++){let a=i[o],u=n[o];console.log("Downloading...",Q.basename(a)),await A(a,u)}if(process.platform!=="win32")for(let o of n)C.chmodSync(o,493);return F()}catch(s){throw console.error(`Download failed: ${s}`),s}}function F(){try{let e=fe();if(!e.length)throw new Error;let r=Q.join(w,String(e[0].split("-").pop()));if(!C.existsSync(r))throw new Error("FFmpeg binary not found. Please download it first.");return r}catch{return}}import*as g from"fs";import*as B from"path";import Be from"crypto";var de="https://github.com/yt-dlp/yt-dlp/releases/latest/download",N={win32:{x64:"yt-dlp.exe",ia32:"yt-dlp_x86.exe"},linux:{x64:"yt-dlp",armv7l:"yt-dlp_linux_armv7l",aarch64:"yt-dlp_linux_aarch64",arm64:"yt-dlp"},darwin:{x64:"yt-dlp_macos",arm64:"yt-dlp_macos"},android:{arm64:"yt-dlp"}};function Te(){let e=process.platform,r=process.arch;if(!N[e]||!N[e][r])throw new Error(`No yt-dlp build available for ${e} ${r}`);return N[e][r]}async function $(e){let r=e||w,t=Te(),s=`${de}/${t}`,i=B.join(r,t);if(g.existsSync(i))return i;console.log("Downloading yt-dlp...",s),g.existsSync(r)||g.mkdirSync(r,{recursive:!0});try{return await A(s,i),console.log(`yt-dlp downloaded successfully to: ${i}`),process.platform!=="win32"&&g.chmodSync(i,493),i}catch(o){throw console.error(`Download failed: ${o}`),o}}async function Ie(e){return new Promise((r,t)=>{let s=Be.createHash("sha256"),i=g.createReadStream(e);i.on("data",n=>s.update(n)),i.on("end",()=>r(s.digest("hex"))),i.on("error",t)})}async function Oe(e){try{let s=(await ae(`${de}/SHA2-256SUMS`)).split(/\r?\n/).find(n=>n.includes(e));if(!s)return;let[i]=s.trim().split(/\s+/);return i||void 0}catch{return}}async function H(e){let r=await $(e),t=B.basename(r),s=await Oe(t);if(!s)return{path:r,verified:!1};let i=await Ie(r);if(i.toLowerCase()!==s.toLowerCase())throw new Error(`Checksum mismatch for ${t}. Expected ${s}, got ${i}`);return{path:r,verified:!0,checksum:s}}function T(){let e=process.platform,r=process.arch;try{let t=N[e][r],s=B.join(w,t);if(!g.existsSync(s))throw new Error("Ytdlp binary not found. Please download it first.");return s}catch{return}}function L(e){return e.replace(/~ytdlp-progress-\{[\s\S]*?\}\n?/g,"").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0).filter(r=>!r.includes("__YTDLP_FILEPATH__:")).filter(r=>!r.includes("__YTDLP_VIDEO_INFO__:")).filter(r=>!r.includes("__YTDLP_BEFORE_DL__:")).join(` | ||
| `)}function j(e){let r=[],t=e.split(/\r?\n/);for(let s of t){let i=s.trim();if(i.startsWith("__YTDLP_VIDEO_INFO__:")){let n=i.replace("__YTDLP_VIDEO_INFO__:","").trim();try{let o=n.replace(/:"N\/A"/g,":null").replace(/:"NA"/g,":null").replace(/:""/g,':"NA"'),a=JSON.parse(o),u={};for(let[l,f]of Object.entries(a))if(f==="NA")u[l]=null;else if(typeof f=="string"&&f==="N/A")u[l]=null;else if((l.includes("_count")||l.includes("_timestamp")||l==="autonumber"||l==="video_autonumber"||l==="n_entries"||l==="playlist_count"||l==="release_year"||l==="start_time"||l==="end_time"||l==="epoch"||l==="duration"||l==="age_limit")&&typeof f=="string"){let d=Number(f);u[l]=isNaN(d)?null:d}else(l==="is_live"||l==="was_live"||l==="channel_is_verified")&&typeof f=="string"?u[l]=f==="true"||f==="True":(l==="categories"||l==="tags"||l==="creators"||l==="cast")&&typeof f=="string"?f==="NA"||f==="N/A"||f===""?u[l]=null:u[l]=f.split(",").map(d=>d.trim()):u[l]=f;r.push(u)}catch{}}}return r}function y(e){let r=e.trim();if(!r.startsWith("__YTDLP_BEFORE_DL__:"))return null;let t=r.replace("__YTDLP_BEFORE_DL__:","").trim();try{let s=t.replace(/:"N\/A"/g,":null").replace(/:"NA"/g,":null").replace(/:""/,':"NA"'),i=JSON.parse(s),n={};for(let[o,a]of Object.entries(i))if(a==="NA"||a==="N/A")n[o]=null;else if((o.includes("_count")||o.includes("_timestamp")||o==="autonumber"||o==="video_autonumber"||o==="n_entries"||o==="playlist_count"||o==="release_year"||o==="start_time"||o==="end_time"||o==="epoch"||o==="duration"||o==="age_limit")&&typeof a=="string"){let u=Number(a);n[o]=isNaN(u)?null:u}else(o==="is_live"||o==="was_live"||o==="channel_is_verified")&&typeof a=="string"?n[o]=a==="true"||a==="True":(o==="categories"||o==="tags"||o==="creators"||o==="cast")&&typeof a=="string"?a==="NA"||a==="N/A"||a===""?n[o]=null:n[o]=a.split(",").map(u=>u.trim()):n[o]=a;return n}catch{return null}}var Ve=/^ERROR:\s*(?:\[.+?\]\s*)?(.+)/m,Ce=[/ERROR:\s*\[.*?\]\s*.*?:\s*Sign in to confirm/i,/ERROR:\s*\[.*?\]\s*Unable to extract/i,/ERROR:\s*\[.*?\]\s*This video is unavailable/i,/ERROR:\s*\[.*?\]\s*Video unavailable/i,/ERROR:\s*\[.*?\]\s*Private video/i,/ERROR:\s*\[.*?\]\s*.*?requires premium/i,/ERROR:\s*\[.*?\]\s*This live event has ended/i,/ERROR:\s*\[.*?\]\s*.*?is not available/i,/ERROR:\s*No video formats found/i,/ERROR:\s*Unsupported URL/i];function ce(e){if(!e)return{hasError:!1};let r=e.match(Ve);return r?{hasError:!0,message:r[1]?.trim(),fullError:r[0]}:{hasError:!1}}function Ne(e){return e?Ce.some(r=>r.test(e)):!1}function he(e,r){let s=ce(e).message||"Unknown yt-dlp error";return r!=null&&r!==0&&(s=`yt-dlp exited with code ${r}: ${s}`),new Error(s)}function D(e,r,t){let{exitCodeOnly:s=!1,fatalOnly:i=!1}=t||{};if(r!==0&&r!==null)return he(e,r);if(s)return;if(ce(e).hasError)return i&&!Ne(e)?void 0:he(e)}import{EventEmitter as $e}from"node:events";function me({url:e,options:r,ffmpegPath:t,withProgressTemplate:s,extra:i}){let n=O(r||{});return t&&n.push("--ffmpeg-location",t),s&&n.push("--progress-template",V),i&&i.length>0&&n.push(...i),e&&n.push("--",e),n}import pe from"node:fs";var x=class extends $e{constructor(t,s){super();this.binaryPath="";this.videoUrl="";this.extraArgs={};this.rawArgs=[];this.videoUrl=t,this.binaryPath=s?.binaryPath||T()||"",this.ffmpegPath=s?.ffmpegPath||F(),(!this.binaryPath||!pe.existsSync(this.binaryPath))&&console.error(new Error("yt-dlp binary not found. Please install yt-dlp or specify correct binaryPath in options.")),this.ffmpegPath&&!pe.existsSync(this.ffmpegPath)&&console.error(new Error(`FFmpeg binary not found at: ${this.ffmpegPath}. Please install FFmpeg or specify correct ffmpegPath.`))}setBinaryPath(t){return this.binaryPath=t,this}setFfmpegPath(t){return this.ffmpegPath=t,this}format(t){return this.formatValue=t,this}filter(t){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={...s,filter:t},this}quality(t){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={filter:this.formatValue,...s,quality:t},this}type(t){let s=typeof this.formatValue=="object"?this.formatValue:{};return this.formatValue={filter:this.formatValue,...s,type:t},this}options(t){return this.extraArgs={...this.extraArgs,...t},this}rateLimit(t){return this.extraArgs.limitRate=t,this}cookies(t){return this.extraArgs.cookies=t,this}cookiesFromBrowser(t){return this.extraArgs.cookiesFromBrowser=t,this}proxy(t){return this.extraArgs.proxy=t,this}addOption(t,s){return this.extraArgs[t]=s,this}addArgs(...t){return this.rawArgs.push(...t),this}extractAudio(t){return this.extraArgs.extractAudio=!0,t&&(this.extraArgs.audioFormat=t),this}audioFormat(t){return this.extraArgs.audioFormat=t,this}audioQuality(t){return this.extraArgs.audioQuality=t,this}embedThumbnail(){return this.extraArgs.embedThumbnail=!0,this}embedSubs(){return this.extraArgs.embedSubs=!0,this}embedMetadata(){return this.extraArgs.embedMetadata=!0,this}writeSubs(){return this.extraArgs.writeSubs=!0,this}writeAutoSubs(){return this.extraArgs.writeAutoSubs=!0,this}subLangs(t){return this.extraArgs.subLangs=t,this}writeThumbnail(){return this.extraArgs.writeThumbnail=!0,this}username(t){return this.extraArgs.username=t,this}password(t){return this.extraArgs.password=t,this}playlistStart(t){return this.extraArgs.playlistStart=t,this}playlistEnd(t){return this.extraArgs.playlistEnd=t,this}playlistItems(t){return this.extraArgs.playlistItems=t,this}buildFormatArgs(){return this.formatValue?R(this.formatValue):[]}buildBaseArgs(t=[]){if(!this.videoUrl)throw new Error("URL is required.");let s=this.buildFormatArgs();return me({url:this.videoUrl,options:this.extraArgs,ffmpegPath:this.ffmpegPath,withProgressTemplate:!0,extra:[...s,...t,...this.rawArgs]})}debugPrint(t=!0){return this.extraArgs.debugPrintCommandLine=t,this}getCommand(){let t=this.buildArgs();return`${this.binaryPath} ${t.join(" ")}`}getArguments(){return this.buildArgs()}toString(){return this.getCommand()}printDebugCommandLine(t){if(this.extraArgs.debugPrintCommandLine){let s=`${this.binaryPath} ${t.join(" ")}`;console.error(`[ytdlp-nodejs] Command: ${s}`)}}validateBinaryPath(){if(!this.binaryPath)throw new Error("Binary path is required. Use .setBinaryPath() or pass it in constructor.")}kill(t){return this.process?.kill(t)??!1}get pid(){return this.process?.pid}};var ge=["id","title","fulltitle","ext","alt_title","description","display_id","uploader","uploader_id","uploader_url","license","creators","creator","timestamp","upload_date","release_timestamp","release_date","release_year","modified_timestamp","modified_date","channel","channel_id","channel_url","channel_follower_count","channel_is_verified","location","duration","duration_string","view_count","concurrent_view_count","like_count","dislike_count","repost_count","average_rating","comment_count","save_count","age_limit","live_status","is_live","was_live","playable_in_embed","availability","media_type","start_time","end_time","extractor","extractor_key","epoch","autonumber","video_autonumber","n_entries","playlist_id","playlist_title","playlist","playlist_count","playlist_index","playlist_autonumber","playlist_uploader","playlist_uploader_id","playlist_channel","playlist_channel_id","playlist_webpage_url","webpage_url","webpage_url_basename","webpage_url_domain","original_url","categories","tags","cast","filepath"];function Le(){return`after_move:__YTDLP_VIDEO_INFO__:{${ge.map(r=>`"${r}":%(${r}|null)j`).join(",")}}`}function S(){return`before_dl:__YTDLP_BEFORE_DL__:{${ge.map(r=>`"${r}":%(${r}|null)j`).join(",")}}`}function K(){return["--print",Le(),"--progress","--newline"]}import{spawn as je}from"node:child_process";var _=class extends x{constructor(r,t){super(r,t),this.on("error",()=>{})}on(r,t){return super.on(r,t)}once(r,t){return super.once(r,t)}emit(r,...t){return super.emit(r,...t)}output(r){return this.outputDir=r,this}setOutputTemplate(r){return this.outputPath=r,this}skipDownload(){return this.extraArgs.skipDownload=!0,this}buildArgs(){let r={...this.extraArgs};this.outputDir&&(r.output=`${this.outputDir}/%(title)s.%(ext)s`),this.outputPath&&(r.output=this.outputPath);let t=this.extraArgs;this.extraArgs=r;let s=[...K()];this.listenerCount("beforeDownload")>0&&s.unshift("--print",S());let i=this.buildBaseArgs(s);return this.extraArgs=t,i}run(){return this.resultPromise?this.resultPromise:(this.resultPromise=new Promise((r,t)=>{try{this.validateBinaryPath();let s=this.buildArgs(),i=`${this.binaryPath} ${s.join(" ")}`;this.printDebugCommandLine(s),this.process=je(this.binaryPath,s),this.emit("start",i);let n="",o="";this.process.stdout?.on("data",a=>{let u=a.toString();n+=u,this.emit("stdout",u);let l=y(u);l&&this.emit("beforeDownload",l);let f=m(u);f&&this.emit("progress",f)}),this.process.stderr?.on("data",a=>{let u=a.toString();o+=u,this.emit("stderr",u);let l=m(u);l&&this.emit("progress",l)}),this.process.on("error",a=>{this.emit("error",a),t(a)}),this.process.on("close",a=>{let u=D(o,a);if(u){this.emit("error",u),t(u);return}let l=L(n),f=j(n),d={output:l,filePaths:f.map(p=>p?.filepath??"").filter(Boolean),info:f,stderr:o};this.emit("finish",d),r(d)})}catch(s){t(s)}}),this.resultPromise)}then(r,t){return this.run().then(r,t)}catch(r){return this.run().catch(r)}finally(r){return this.run().finally(r)}};function Ke(e,r){return new _(e,r)}import{PassThrough as Me}from"node:stream";import{spawn as We}from"node:child_process";var E=class extends x{constructor(t,s){super(t,s);this.totalBytes=0;this.started=!1;this.on("error",()=>{})}on(t,s){return super.on(t,s)}once(t,s){return super.once(t,s)}emit(t,...s){return super.emit(t,...s)}buildArgs(){let t=["-o","-","--no-playlist","--progress","--no-quiet"];return this.listenerCount("beforeDownload")>0&&t.push("--print",S()),this.buildBaseArgs(t)}startStream(){if(this.started)return this.passThrough;this.validateBinaryPath(),this.started=!0,this.passThrough=new Me;let t=this.buildArgs(),s=`${this.binaryPath} ${t.join(" ")}`;this.printDebugCommandLine(t),this.process=We(this.binaryPath,t,{shell:!1}),this.emit("start",s),this.process.stdout?.on("data",n=>{this.totalBytes+=n.length,this.passThrough.write(n),this.emit("data",n)});let i="";return this.process.stderr?.on("data",n=>{let o=n.toString();i+=o,this.emit("stderr",o);let a=y(o);a&&this.emit("beforeDownload",a);let u=m(o);u&&this.emit("progress",u)}),this.process.on("error",n=>{this.emit("error",n),this.passThrough.destroy(n)}),this.process.on("close",n=>{let o=D(i,n);o?(this.emit("error",o),this.passThrough.destroy(o)):(this.passThrough.end(),this.emit("end"))}),this.passThrough}pipe(t,s){let i=Date.now(),n=this.startStream();return new Promise((o,a)=>{n.pipe(t,s),t.on("finish",()=>{o({bytes:this.totalBytes,duration:Date.now()-i})}),t.on("error",a),this.passThrough.on("error",a)})}pipeAsync(t,s){return this.pipe(t,s)}async toBuffer(){let t=[];return new Promise((s,i)=>{let n=this.startStream();n.on("data",o=>{t.push(o)}),n.on("end",()=>{s(Buffer.concat(t))}),n.on("error",i)})}getStream(){return this.startStream()}};function Ue(e,r){return new E(e,r)}import{PassThrough as ze}from"node:stream";import{spawn as be}from"node:child_process";var P=class extends x{constructor(t,s){super(t,s);this.totalBytes=0;this.started=!1;this.output="";this.on("error",()=>{})}on(t,s){return super.on(t,s)}once(t,s){return super.once(t,s)}emit(t,...s){return super.emit(t,...s)}buildArgs(){let t=[],s=[...K()];return this.listenerCount("beforeDownload")>0&&s.unshift("--print",S()),this.listenerCount("afterDownload")>0&&s.push("--print","after_move:filepath"),this.buildBaseArgs([...t,...s])}startStream(){if(this.started)return this.passThrough;this.validateBinaryPath(),this.started=!0,this.passThrough=new ze,this.output="";let t=this.buildArgs();t.includes("--no-playlist")||(t=["--no-playlist",...t]);let s=`${this.binaryPath} ${t.join(" ")}`;return this.printDebugCommandLine(t),this.process=be(this.binaryPath,t,{shell:!1}),this.emit("start",s),this.process.stdout?.on("data",i=>{this.totalBytes+=i.length,this.passThrough.write(i),this.emit("data",i);let n=i.toString();this.emit("stdout",n);let o=y(n);o&&(this.beforeDownloadInfo=o,this.emit("beforeDownload",this.beforeDownloadInfo));let a=m(n);a&&this.emit("progress",a)}),this.process.stderr?.on("data",i=>{let n=i.toString();this.emit("stderr",n),this.output+=n;let o=y(n);o&&(this.beforeDownloadInfo=o,this.emit("beforeDownload",this.beforeDownloadInfo));let a=m(n);a&&(this.emit("progress",a),a.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:a.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.on("error",i=>{this.emit("error",i),this.passThrough.destroy(i)}),this.process.on("close",i=>{let n=D(this.output,i);n?(this.emit("error",n),this.passThrough.destroy(n)):(this.passThrough.end(),this.emit("end"))}),this.passThrough}pipe(t,s){let i=Date.now(),n=this.startStream();return new Promise((o,a)=>{n.pipe(t,s),t.on("finish",()=>{o({bytes:this.totalBytes,duration:Date.now()-i,info:this.afterDownloadInfo,output:this.output})}),t.on("error",a),this.passThrough.on("error",a)})}pipeAsync(t,s){return this.pipe(t,s)}async toBuffer(){let t=[];return new Promise((s,i)=>{let n=this.startStream();n.on("data",o=>{t.push(o)}),n.on("end",()=>{s(Buffer.concat(t))}),n.on("error",i)})}getStream(){return this.startStream()}exec(){return this.resultPromise?this.resultPromise:(this.resultPromise=new Promise((t,s)=>{try{this.validateBinaryPath();let i=this.buildArgs(),n=`${this.binaryPath} ${i.join(" ")}`;this.printDebugCommandLine(i),this.process=be(this.binaryPath,i,{shell:!1}),this.emit("start",n);let o="",a="";this.process.stdout?.on("data",u=>{let l=u.toString();o+=l,this.emit("stdout",l);let f=y(l);f&&(this.beforeDownloadInfo=f,this.emit("beforeDownload",this.beforeDownloadInfo)),this.emit("data",u);let d=m(l);d&&(this.emit("progress",d),d.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:d.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.stderr?.on("data",u=>{let l=u.toString();a+=l,this.emit("stderr",l);let f=y(l);f&&(this.beforeDownloadInfo=f,this.emit("beforeDownload",this.beforeDownloadInfo));let d=m(l);d&&(this.emit("progress",d),d.status==="finished"&&this.beforeDownloadInfo&&(this.afterDownloadInfo={...this.beforeDownloadInfo,filepath:d.filename},this.emit("afterDownload",this.afterDownloadInfo)))}),this.process.on("error",u=>{this.emit("error",u),s(u)}),this.process.on("close",u=>{let l=L(o),f=j(o),d={stdout:o,stderr:a,exitCode:u,command:n,info:f,output:l,filePaths:f.map(p=>p?.filepath??"").filter(Boolean)};this.emit("complete",d),this.emit("end"),t(d)})}catch(i){s(i)}}),this.resultPromise)}run(){return this.exec()}then(t,s){return this.exec().then(t,s)}catch(t){return this.exec().catch(t)}finally(t){return this.exec().finally(t)}};function Je(e,r){return new P(e,r)}var we=class{constructor(r){this.binaryPath=r?.binaryPath||T()||"",this.ffmpegPath=r?.ffmpegPath||F(),(!this.binaryPath||!X.existsSync(this.binaryPath))&&console.error(new Error("yt-dlp binary not found. Please install yt-dlp or specify correct binaryPath in options.")),this.ffmpegPath&&!X.existsSync(this.ffmpegPath)&&console.error(new Error(`FFmpeg binary not found at: ${this.ffmpegPath}. Please install FFmpeg or specify correct ffmpegPath.`))}async checkInstallationAsync(r){return new Promise((t,s)=>{if(r?.ffmpeg&&!this.ffmpegPath)return s(new Error("FFmpeg path is not set"));let i=Z(this.binaryPath,["--version"]),n=!1,o=!r?.ffmpeg;i.on("error",()=>n=!1),i.on("exit",a=>{if(n=a===0,r?.ffmpeg){let u=Z(this.ffmpegPath,["-version"]);u.on("error",()=>o=!1),u.on("exit",l=>{o=l===0,t(n&&o)})}else t(n)})})}checkInstallation(r){if(r?.ffmpeg&&!this.ffmpegPath)throw new Error("FFmpeg path is not set");let t=ye(this.binaryPath,["--version"],{stdio:"ignore"}),s=r?.ffmpeg?ye(this.ffmpegPath,["-version"],{stdio:"ignore"}):{status:0};return t.status===0&&s.status===0}async getInfoAsync(r,t){let s=await this.execAsync(r,{dumpSingleJson:!0,flatPlaylist:!0,...t});return JSON.parse(s.output)}async execAsync(r,t){let s=new P(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{onData:i,onProgress:n,onBeforeDownload:o,pipeTo:a,...u}=t||{};return u&&s.options(u),i&&s.on("stdout",i),n&&s.on("progress",n),o&&s.on("beforeDownload",o),a?s.pipe(a):s.exec()}exec(r,t){let s=new P(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath});return t&&s.options(t),s}download(r,t){let s=new _(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=t||{};return i&&s.format(i),n&&s.options(n),s}async downloadAsync(r,t){let{onProgress:s,beforeDownload:i,...n}=t||{},o=this.download(r,n);s&&o.on("progress",s),i&&o.on("beforeDownload",i);let a=await o.run();return{output:a.output,filePaths:a.filePaths,info:a.info}}stream(r,t){let s=new E(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=t||{};return i&&s.format(i),n&&s.options(n),s}execBuilder(r,t){let s=new P(r,{binaryPath:this.binaryPath,ffmpegPath:this.ffmpegPath}),{format:i,...n}=t||{};return i&&s.format(i),n&&s.options(n),s}async downloadAudio(r,t="mp3",s){let i=["aac","flac","mp3","m4a","opus","vorbis","wav","alac"];if(!i.includes(t))throw new Error(`Invalid audio format: ${t}. Supported: ${i.join(", ")}`);return this.downloadAsync(r,{...s,extractAudio:!0,audioFormat:t})}async downloadVideo(r,t="best",s){let i=["best","2160p","1440p","1080p","720p","480p","360p","240p","144p","highest","lowest"];if(!i.includes(t))throw new Error(`Invalid video quality: ${t}. Supported: ${i.join(", ")}`);let n=t==="best"?"bestvideo+bestaudio/best":`bestvideo[height<=${parseInt(t)||1080}]+bestaudio/best[height<=${parseInt(t)||1080}]`;return this.downloadAsync(r,{...s,format:n})}async getSubtitles(r,t){return(await this.execAsync(r,{...t,listSubs:!0,skipDownload:!0})).output?[]:[]}async getComments(r,t=20,s){let i=await this.execAsync(r,{...s,writeComments:!0,dumpSingleJson:!0,skipDownload:!0,extractorArgs:{youtube:[`max_comments=${t}`,"player_skip=webpage"]}});try{return JSON.parse(i.output).comments||[]}catch{return[]}}async getDirectUrlsAsync(r,t){return(await this.getInfoAsync(r,t)).formats.map(i=>i.url)}async getFormatsAsync(r,t){let s=await this.getInfoAsync(r,t);return{source:"json",info:s,formats:s.formats}}async getThumbnailsAsync(r){return(await this.getInfoAsync(r)).thumbnails}async getTitleAsync(r){return(await this.execAsync(r,{print:"title"})).output.trim()}async getVersionAsync(){return(await this.execAsync("",{printVersion:!0})).output.trim()}async downloadFFmpeg(){return G()}async getFileAsync(r,t){let s,{onBeforeDownload:i,onProgress:n,filename:o,metadata:a,format:u,...l}=t||{},f=[],d=new Qe;d.on("data",v=>f.push(Buffer.from(v)));let p=R(u),M={...l};if(p.length>=2&&p[0]==="-f"&&(M.format=p[1]),p.includes("--merge-output-format")){let v=p.indexOf("--merge-output-format");M.mergeOutputFormat=p[v+1]}await this.execAsync(r,{...M,noPlaylist:!0,pipeTo:d,onProgress:n,onBeforeDownload:v=>{s=v,i?.(v)},output:"-"});let I,W;u&&typeof u=="object"?(I=U(u),W=z(u)):(I=ie(l)||"video/mp4",W=ne(l)||"mp4");let xe=new qe(f,{type:I}),ee={name:o||`${s?.title||"download"}.${W}`,type:I,size:xe.size,...a};return new File([Buffer.concat(f)],ee.name,{type:ee.type})}async getUrlsAsync(r,t){return(await this.execAsync(r,{...t,print:"urls"})).output.split(` | ||
| `).filter(Boolean)}async updateYtDlpAsync(r){if(r?.preferBuiltIn!==!1&&this.binaryPath)try{await this.execAsync("",{update:!0});let a=await this.getVersionAsync().catch(()=>{});return{method:"built-in",binaryPath:this.binaryPath,version:a}}catch{}let s=r?.outDir||(this.binaryPath?Ye.dirname(this.binaryPath):void 0);if(r?.verifyChecksum!==!1){let a=await H(s),u=await this.getVersionAsyncUsingBinary(a.path).catch(()=>{});return{method:"download",binaryPath:a.path,version:u,verified:a.verified}}let n=await $(s),o=await this.getVersionAsyncUsingBinary(n).catch(()=>{});return{method:"download",binaryPath:n,version:o,verified:!1}}async getVersionAsyncUsingBinary(r){return new Promise((t,s)=>{let i=Z(r,["--version"]),n="",o="";i.stdout?.on("data",a=>{n+=a.toString()}),i.stderr?.on("data",a=>{o+=a.toString()}),i.on("close",a=>{a===0?t(n.trim()):s(new Error(`Failed to get version: ${o}`))}),i.on("error",s)})}},Tt={downloadFFmpeg:G,findFFmpegBinary:F,PROGRESS_STRING:V,getContentType:U,getFileExtension:z,parseFormatOptions:R,stringToProgress:m,createArgs:O,extractThumbnails:re,downloadFile:A,BIN_DIR:w,downloadYtDlp:$,downloadYtDlpVerified:H,findYtdlpBinary:T};export{w as BIN_DIR,_ as Download,P as Exec,E as Stream,we as YtDlp,Ke as createDownload,Je as createExec,Ue as createStreamBuilder,Tt as helpers}; |
+1
-1
| { | ||
| "name": "ytdlp-nodejs", | ||
| "version": "3.4.2", | ||
| "version": "3.4.3", | ||
| "description": "A TypeScript wrapper for the yt-dlp executable", | ||
@@ -5,0 +5,0 @@ "main": "./dist/index.js", |
Sorry, the diff of this file is too big to display
Network access
Supply chain riskThis module accesses the network.
Found 2 instances in 1 package
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 2 instances in 1 package
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
Found 1 instance in 1 package
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Found 1 instance in 1 package
193529
1.43%2456
1.53%30
3.45%