diff --git a/js/webtorrent-global.js b/js/webtorrent-global.js
new file mode 100644
index 00000000..0a58bfa1
--- /dev/null
+++ b/js/webtorrent-global.js
@@ -0,0 +1,16 @@
+import WebTorrent from "./webtorrent.min.js";
+
+const globalScope =
+ (typeof window !== "undefined" && window) ||
+ (typeof globalThis !== "undefined" && globalThis) ||
+ null;
+
+if (
+ globalScope &&
+ typeof globalScope.WebTorrent !== "function" &&
+ typeof WebTorrent === "function"
+) {
+ globalScope.WebTorrent = WebTorrent;
+}
+
+export {};
diff --git a/torrent/beacon.html b/torrent/beacon.html
index 77178107..ed01d346 100644
--- a/torrent/beacon.html
+++ b/torrent/beacon.html
@@ -16,7 +16,7 @@
-
+
diff --git a/torrent/dist/beacon.js b/torrent/dist/beacon.js
index 7a36c52d..8686d644 100644
--- a/torrent/dist/beacon.js
+++ b/torrent/dist/beacon.js
@@ -1 +1 @@
-var O={info:"torrent-toast torrent-toast--info",success:"torrent-toast torrent-toast--success",error:"torrent-toast torrent-toast--error",warn:"torrent-toast torrent-toast--warn"},V="transition duration-200 ease-out",Y="beacon-toast-motion",q="data-beacon-motion";function J(e,t){let a=e?.defaultView;if(a&&typeof a.requestAnimationFrame=="function"){a.requestAnimationFrame(t);return}setTimeout(t,16)}function Q(e){let t=e||(typeof document<"u"?document:null);if(!t)return null;let a=t.getElementById("beacon-toast-container");if(!a){a=t.createElement("div"),a.id="beacon-toast-container",a.setAttribute("role","region"),a.setAttribute("aria-live","polite"),a.className=["pointer-events-none","fixed","inset-x-0","top-4","z-[70]","flex","flex-col","items-center","gap-3","px-4"].join(" ");let i=t.body||t.getElementsByTagName?.("body")?.[0];i&&i.appendChild(a)}return a}function X(e,t,a){let i=e.createElement("div");i.className=[V,a].join(" "),i.setAttribute("role","status"),i.setAttribute("tabindex","0"),i.textContent=t;let o=e.createElement("button");o.type="button",o.className=["absolute","right-3","top-3","rounded","p-1","text-current/70","hover:text-current","focus-visible:outline","focus-visible:outline-2","focus-visible:outline-offset-2","focus-visible:outline-info"].join(" "),o.setAttribute("aria-label","Dismiss notification"),o.innerHTML='';let d=e.createElement("div");return d.className=["relative","w-full",V,Y].join(" "),d.setAttribute(q,"exit"),d.appendChild(i),i.appendChild(o),{wrapper:d,toast:i,closeButton:o}}function Z(e,t=setTimeout,a=clearTimeout){return{show(i,o={}){if(!i)return;let d=o.type&&O[o.type]?o.type:"info",n=Q(e);if(!n)return;let{wrapper:m,toast:c,closeButton:T}=X(e,i,O[d]);n.appendChild(m),J(e,()=>{m.setAttribute(q,"enter")});let w=typeof o.duration=="number"?o.duration:3500,p=()=>{m.setAttribute(q,"exit");let S=t(()=>{m.parentNode&&m.parentNode.removeChild(m)},200);return T.removeEventListener("click",E),c.removeEventListener("keydown",h),T.removeEventListener("keydown",h),S},E=()=>p(),h=S=>{S.key==="Escape"&&(S.stopPropagation(),p())};T.addEventListener("click",E),c.addEventListener("keydown",h),T.addEventListener("keydown",h);let N=null;return o.sticky||(N=t(()=>{p()},w)),{dismiss(){N&&a(N),p()}}},set(i,o){return typeof o=="string"?this.show(i,{type:o}):this.show(i,o)},info(i,o={}){return this.show(i,{...o,type:"info"})},success(i,o={}){return this.show(i,{...o,type:"success"})},error(i,o={}){return this.show(i,{...o,type:"error"})},warn(i,o={}){return this.show(i,{...o,type:"warn"})}}}function R(e,t=setTimeout,a=clearTimeout){return Z(e,t,a)}var $=[{key:"name",label:"Name",headerClass:"w-full sm:w-1/3 text-left",cellClass:"font-medium text-text truncate"},{key:"progress",label:"Progress",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"progress"},{key:"downloadSpeed",label:"\u2193 Speed",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"bytesPerSecond"},{key:"uploadSpeed",label:"\u2191 Speed",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"bytesPerSecond"},{key:"numPeers",label:"Peers",headerClass:"w-20 text-right",cellClass:"tabular-nums text-right",formatter:"integer"},{key:"ratio",label:"Ratio",headerClass:"w-20 text-right",cellClass:"tabular-nums text-right",formatter:"ratio"}];function ee(e){return e?e.infoHash||e.magnetURI||e.name||String(Math.random()):""}function te(e,t){return!e||!t?!1:e===t||e.magnetURI&&e.magnetURI===t.magnetURI||e.infoHash&&e.infoHash===t.infoHash}function ne(e){return typeof e!="number"||Number.isNaN(e)?"":`${(e*100).toFixed(1)}%`}function re(e){return typeof e!="number"||!Number.isFinite(e)?"0.00":e.toFixed(2)}function oe(e){return typeof e!="number"||!Number.isFinite(e)?"0":Math.max(0,Math.floor(e)).toString()}function ae(e,t){if(typeof t=="function")return t(e,!0)||"";if(typeof e!="number"||Number.isNaN(e)||e<1)return"";let a=["B","kB","MB","GB","TB"],i=Math.min(Math.floor(Math.log(e)/Math.log(1e3)),a.length-1);return`${(e/Math.pow(1e3,i)).toFixed(1)} ${a[i]}/s`}function se(e,t){let a=e.formatter;if(typeof a=="function")return a;let i=t?.[a];if(typeof i=="function")return i;switch(a){case"progress":return ne;case"ratio":return re;case"integer":return oe;case"bytesPerSecond":return o=>ae(o,t?.bytes);default:return o=>o}}function W({documentRef:e=typeof document<"u"?document:null,root:t,onSelect:a,formatters:i={}}={}){if(!e)throw new Error("createTorrentTable requires a document reference");if(!(t instanceof e.defaultView.HTMLElement))throw new Error("createTorrentTable requires a valid root element");let o=e;t.innerHTML="";let d=o.createElement("div");d.className="overflow-hidden rounded-xl border border-border-translucent bg-surface shadow-sm";let n=o.createElement("div");n.className="overflow-x-auto",d.appendChild(n);let m=o.createElement("table");m.className="min-w-full divide-y divide-border-translucent text-sm",n.appendChild(m);let c=o.createElement("thead");c.className="bg-surface-alt text-muted-strong";let T=o.createElement("tr");$.forEach(y=>{let x=o.createElement("th");x.setAttribute("scope","col"),x.className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide",y.headerClass&&(x.className+=` ${y.headerClass}`),x.textContent=y.label,T.appendChild(x)}),c.appendChild(T),m.appendChild(c);let w=o.createElement("tbody");w.className="divide-y divide-border-translucent",m.appendChild(w);let p=o.createElement("tbody"),E=o.createElement("tr"),h=o.createElement("td");h.className="px-4 py-8 text-center text-sm text-muted",h.colSpan=$.length,h.textContent="No active torrents yet. Add a magnet link to get started.",E.appendChild(h),p.appendChild(E),m.appendChild(p),t.appendChild(d);function N(y=[],x=null){let k=Array.isArray(y)?y:[];if(w.innerHTML="",!k.length){w.hidden=!0,p.hidden=!1;return}w.hidden=!1,p.hidden=!0;for(let B of k){let v=o.createElement("tr");v.className=["group","align-middle","cursor-pointer","transition","hover:bg-panel-hover","focus-visible:outline","focus-visible:outline-2","focus-visible:outline-offset-2","focus-visible:outline-info"].join(" "),v.setAttribute("role","button"),v.setAttribute("tabindex","0"),v.dataset.torrentId=ee(B),te(x,B)?(v.classList.add("bg-info/10","text-text"),v.setAttribute("aria-pressed","true")):v.setAttribute("aria-pressed","false"),v.addEventListener("click",()=>{typeof a=="function"&&a(B)}),v.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),typeof a=="function"&&a(B))}),$.forEach(C=>{let A=o.createElement("td");A.className="px-4 py-3",C.cellClass&&(A.className+=` ${C.cellClass}`);let H=B?B[C.key]:void 0,r=se(C,i)(H,B,C),s=o.createElement("span");s.textContent=r==null?"":String(r),A.appendChild(s),v.appendChild(A)}),w.appendChild(v)}}function S(){t.innerHTML=""}return{render:N,destroy:S}}var ie="2.0",z=["wss://tracker.btorrent.xyz","wss://tracker.openwebtorrent.com"],j={announce:z},le={announce:z};function M(e,t=!1){if(typeof e!="number"||Number.isNaN(e))return"";if(e<1)return t?"":"0 B";let a=["B","kB","MB","GB","TB"],i=Math.min(Math.floor(Math.log(e)/Math.log(1e3)),a.length-1);return`${(e/Math.pow(1e3,i)).toFixed(1)} ${a[i]}${t?"/s":""}`}function ce(e){return typeof e!="number"||Number.isNaN(e)?"":`${(e*100).toFixed(1)}%`}function _(e){return typeof e!="number"||!Number.isFinite(e)?"0.00":e.toFixed(2)}function de(e,t){return!e||!t?!1:!!(e===t||e.infoHash&&t.infoHash&&e.infoHash===t.infoHash||e.magnetURI&&t.magnetURI&&e.magnetURI===t.magnetURI)}function ue(e){if(!(!e||!Array.isArray(e.files))&&(e.files.forEach(t=>{typeof t.priority!="string"&&(t.priority="0"),typeof t.getBlobURL=="function"&&t.getBlobURL((a,i)=>{a||!i||(t.url=i)})}),e.torrentFile&&typeof Blob=="function"&&typeof URL<"u"))try{let t=new Blob([e.torrentFile],{type:"application/x-bittorrent"});if(e.torrentFileBlobURL=URL.createObjectURL(t),!e.fileName){let a=e.name||"download";e.fileName=`${a}.torrent`}}catch(t){console.warn("[beacon] Failed to create torrent blob URL",t)}}function fe(e,t){if(!e)return;let a=typeof t=="string"?t:String(t??"0");if(e.priority=a,a==="-1"){typeof e.deselect=="function"&&e.deselect();return}let i=Number.parseInt(a,10);Number.isFinite(i)&&typeof e.select=="function"&&e.select(i)}function D(e,t){if(!Array.isArray(t)||t.length===0)return null;if(!e)return t[0];let a=t.find(i=>de(i,e));return a||t[0]}function G({documentRef:e=typeof document<"u"?document:null,WebTorrentCtor:t}={}){if(!e)throw new Error("createBeaconApp requires a document reference");let a=e.defaultView||globalThis,i=typeof t=="function"?t:typeof a?.WebTorrent=="function"?a.WebTorrent:null;if(!i)throw new Error("createBeaconApp requires a WebTorrent constructor");let o=R(e),d=new i({tracker:le}),n={form:e.querySelector('[data-beacon="magnet-form"]'),magnetInput:e.querySelector('[data-beacon="magnet-input"]'),seedButton:e.querySelector('[data-beacon="seed-button"]'),seedInput:e.querySelector('[data-beacon="seed-input"]'),tableRoot:e.querySelector('[data-beacon="torrent-table"]'),selectedSection:e.querySelector('[data-beacon="selected"]'),selectedName:e.querySelector('[data-beacon="selected-name"]'),pauseButton:e.querySelector('[data-beacon-action="pause"]'),resumeButton:e.querySelector('[data-beacon-action="resume"]'),downloadAllButton:e.querySelector('[data-beacon-action="download-all"]'),removeButton:e.querySelector('[data-beacon-action="remove"]'),copyMagnetButton:e.querySelector('[data-beacon-action="copy-magnet"]'),infoHashValue:e.querySelector('[data-beacon="info-hash"]'),fileList:e.querySelector('[data-beacon="file-list"]'),stats:e.querySelector('[data-beacon="client-stats"]'),overlay:e.querySelector('[data-beacon="processing-overlay"]')},m=n.tableRoot?W({documentRef:e,root:n.tableRoot,formatters:{bytes:(r,s=!1)=>M(r,s),progress:r=>ce(r),ratio:r=>_(r),integer:r=>typeof r=="number"&&Number.isFinite(r)?Math.floor(r).toString():"0",bytesPerSecond:r=>M(r,!0)},onSelect(r){c.selectedTorrent=r,y()}}):null,c={selectedTorrent:null,processing:!1},T=[],w=[];function p(r){T.push(r)}function E(r){c.processing=!!r,n.overlay&&(n.overlay.hidden=!c.processing)}function h(){return Array.isArray(d.torrents)?[...d.torrents]:[]}function N(){if(!n.stats)return;let r=M(d.downloadSpeed,!0)||"0 B/s",s=M(d.uploadSpeed,!0)||"0 B/s",f=_(d.ratio);n.stats.textContent=`Client stats: \u2193 ${r} \xB7 \u2191 ${s} \xB7 Ratio: ${f}`}function S(r){n.fileList&&(n.fileList.innerHTML="",!(!r||!Array.isArray(r.files)||!r.files.length)&&r.files.forEach((s,f)=>{let u=e.createElement("tr");u.className="align-top";let l=e.createElement("td");if(l.className="px-3 py-2",s.done&&s.url){let g=e.createElement("a");g.className="text-info hover:text-info-strong",g.href=s.url,g.download=s.name||`file-${f+1}`,g.textContent=s.name||`File ${f+1}`,l.appendChild(g)}else{let g=e.createElement("span");g.textContent=s.name||`File ${f+1}`,l.appendChild(g)}u.appendChild(l);let b=e.createElement("td");b.className="px-3 py-2 text-muted-strong",b.textContent=M(s.length)||"0 B",u.appendChild(b);let I=e.createElement("td");I.className="px-3 py-2";let L=e.createElement("select");L.className="select",L.name=`${s.name||`file-${f+1}`}-priority`,L.setAttribute("aria-label",`Set priority for ${s.name||`file ${f+1}`}`),[{value:"1",label:"High priority"},{value:"0",label:"Low priority"},{value:"-1",label:"Don't download"}].forEach(g=>{let U=e.createElement("option");U.value=g.value,U.textContent=g.label,g.value===s.priority&&(U.selected=!0),L.appendChild(U)}),L.value=s.priority??"0",L.addEventListener("change",g=>{fe(s,g.target.value)}),I.appendChild(L),u.appendChild(I),n.fileList.appendChild(u)}))}function y(){if(!n.selectedSection)return;let r=h();c.selectedTorrent=D(c.selectedTorrent,r);let s=c.selectedTorrent;n.selectedSection.hidden=!s,s&&(n.selectedName&&(n.selectedName.textContent=s.name||"Untitled torrent"),n.pauseButton&&(n.pauseButton.hidden=s.paused===!0,n.pauseButton.disabled=s.paused===!0),n.resumeButton&&(n.resumeButton.hidden=s.paused!==!0,n.resumeButton.disabled=s.paused!==!0),n.downloadAllButton&&(n.downloadAllButton.disabled=!(s.progress>=1)),n.infoHashValue&&(n.infoHashValue.textContent=s.infoHash||""),S(s))}function x(r,{isSeed:s=!1}={}){E(!1),ue(r),s||o.info(`Received ${r.name||"torrent"} metadata`),c.selectedTorrent||(c.selectedTorrent=r),y(),m?.render(h(),c.selectedTorrent)}function k(r){let s=typeof r=="string"?r.trim():"";s&&(E(!0),d.add(s,j,f=>{x(f,{isSeed:!1})}))}function B(r){!Array.isArray(r)||r.length===0||(E(!0),d.seed(r,j,s=>{x(s,{isSeed:!0}),o.success(`Seeding ${s.files.length} file(s)`)}))}function v(r){if(r){if(r.progress<1){o.warn("Torrent is not finished downloading yet.");return}r.files.forEach(s=>{typeof s.getBlob=="function"&&s.getBlob((f,u)=>{if(f||!u){console.error("[beacon] Failed to get blob for file",s?.name,f),o.error("Failed to prepare file for download.");return}let l=URL.createObjectURL(u),b=e.createElement("a");b.className="beacon-hidden-download",b.setAttribute("data-beacon-hidden-download","true"),b.href=l,b.download=s.name||"download",e.body.appendChild(b),b.click(),e.body.removeChild(b),URL.revokeObjectURL(l)})})}}function C(r){if(!r?.magnetURI)return;let s=r.magnetURI,f=a?.navigator?.clipboard;if(f&&typeof f.writeText=="function"){f.writeText(s).then(()=>{o.success("Magnet URI copied to clipboard!")}).catch(u=>{console.error("[beacon] Clipboard error",u),o.error("Failed to copy magnet URI")});return}try{let u=e.createElement("textarea");u.value=s,u.className="beacon-clipboard-offscreen",u.setAttribute("data-beacon-clipboard-state","offscreen"),e.body.appendChild(u),u.select(),e.execCommand?.("copy"),e.body.removeChild(u),o.success("Magnet URI copied (fallback)!")}catch(u){console.error("[beacon] Clipboard fallback error",u),o.error("Failed to copy magnet URI")}}function A(r){r&&r.destroy(s=>{s&&(console.error("[beacon] Failed to destroy torrent",s),o.error("Failed to remove torrent"));let f=h();c.selectedTorrent=D(null,f),m?.render(f,c.selectedTorrent),y()})}function H(){if(console.log(`[beacon] Starting beacon runtime v${ie}`),o||console.warn("[beacon] Toast service unavailable"),i.WEBRTC_SUPPORT||o?.error("Please use a browser with WebRTC support.",{sticky:!0}),n.form){let l=b=>{b.preventDefault(),k(n.magnetInput?.value||""),n.magnetInput&&(n.magnetInput.value="")};n.form.addEventListener("submit",l),p(()=>n.form.removeEventListener("submit",l))}if(n.seedButton&&n.seedInput){let l=()=>{n.seedInput.click()},b=()=>{let I=Array.from(n.seedInput.files||[]);n.seedInput.value="",B(I)};n.seedButton.addEventListener("click",l),n.seedInput.addEventListener("change",b),p(()=>{n.seedButton.removeEventListener("click",l),n.seedInput.removeEventListener("change",b)})}if(n.pauseButton){let l=()=>{c.selectedTorrent&&typeof c.selectedTorrent.pause=="function"&&(c.selectedTorrent.pause(),y())};n.pauseButton.addEventListener("click",l),p(()=>n.pauseButton.removeEventListener("click",l))}if(n.resumeButton){let l=()=>{c.selectedTorrent&&typeof c.selectedTorrent.resume=="function"&&(c.selectedTorrent.resume(),y())};n.resumeButton.addEventListener("click",l),p(()=>n.resumeButton.removeEventListener("click",l))}if(n.downloadAllButton){let l=()=>v(c.selectedTorrent);n.downloadAllButton.addEventListener("click",l),p(()=>n.downloadAllButton.removeEventListener("click",l))}if(n.removeButton){let l=()=>A(c.selectedTorrent);n.removeButton.addEventListener("click",l),p(()=>n.removeButton.removeEventListener("click",l))}if(n.copyMagnetButton){let l=()=>C(c.selectedTorrent);n.copyMagnetButton.addEventListener("click",l),p(()=>n.copyMagnetButton.removeEventListener("click",l))}let r=l=>{console.error("[beacon] Torrent client error",l),o?.error(l?.message||String(l)),E(!1)};d.on("error",r),p(()=>d.removeListener("error",r));let s=l=>{if(d.torrents&&d.torrents.length>0)return l.preventDefault(),l.returnValue="Transfers are in progress. Are you sure you want to leave or refresh?",l.returnValue};a&&typeof a.addEventListener=="function"&&(a.addEventListener("beforeunload",s),p(()=>a.removeEventListener("beforeunload",s))),m?.render(h(),c.selectedTorrent),y(),N(),E(!1);let f=a.setInterval(()=>{m?.render(h(),c.selectedTorrent),y(),N()},1e3);w.push(f);let u=a?.location?.hash;typeof u=="string"&&u.length>1&&k(u.slice(1))}function P(){w.forEach(r=>a.clearInterval(r)),w.length=0,T.forEach(r=>{try{r()}catch(s){console.warn("[beacon] Cleanup task failed",s)}}),T.length=0,m?.destroy();try{d.destroy()}catch(r){console.warn("[beacon] Failed to destroy client",r)}}return{mount:H,destroy:P}}function pe(){let e=typeof window<"u"&&window||typeof globalThis<"u"&&globalThis||null;if(e&&typeof e.WebTorrent=="function")return e.WebTorrent;throw new Error("WebTorrent runtime is not available on the global scope")}var F=null;function K(){if(F)return F;if(typeof document>"u")throw new Error("Beacon runtime requires a document environment");let e=pe();return F=G({documentRef:document,WebTorrentCtor:e}),F.mount(),F}if(typeof document<"u")if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>{try{K()}catch(e){console.error("[beacon] Failed to mount app",e)}});else try{K()}catch(e){console.error("[beacon] Failed to mount app",e)}export{G as createBeaconApp,K as mountBeaconApp};
+var O={info:"torrent-toast torrent-toast--info",success:"torrent-toast torrent-toast--success",error:"torrent-toast torrent-toast--error",warn:"torrent-toast torrent-toast--warn"},V="transition duration-200 ease-out",Y="beacon-toast-motion",q="data-beacon-motion";function J(e,t){let a=e?.defaultView;if(a&&typeof a.requestAnimationFrame=="function"){a.requestAnimationFrame(t);return}setTimeout(t,16)}function Q(e){let t=e||(typeof document<"u"?document:null);if(!t)return null;let a=t.getElementById("beacon-toast-container");if(!a){a=t.createElement("div"),a.id="beacon-toast-container",a.setAttribute("role","region"),a.setAttribute("aria-live","polite"),a.className=["pointer-events-none","fixed","inset-x-0","top-0","z-overlay-toast","flex","w-full","flex-col","items-center","gap-3","px-4","pt-6","sm:items-end","sm:px-6","sm:pt-8"].join(" ");let i=t.body||t.getElementsByTagName?.("body")?.[0];i&&i.appendChild(a)}return a}function X(e,t,a){let i=e.createElement("div");i.className=[V,a].join(" "),i.setAttribute("role","status"),i.setAttribute("tabindex","0"),i.textContent=t;let o=e.createElement("button");o.type="button",o.className=["notification-dismiss","focus-ring","absolute","right-3","top-3"].join(" "),o.setAttribute("aria-label","Dismiss notification"),o.innerHTML='';let d=e.createElement("div");return d.className=["relative","w-full",V,Y].join(" "),d.setAttribute(q,"exit"),d.appendChild(i),i.appendChild(o),{wrapper:d,toast:i,closeButton:o}}function Z(e,t=setTimeout,a=clearTimeout){return{show(i,o={}){if(!i)return;let d=o.type&&O[o.type]?o.type:"info",n=Q(e);if(!n)return;let{wrapper:m,toast:c,closeButton:T}=X(e,i,O[d]);n.appendChild(m),J(e,()=>{m.setAttribute(q,"enter")});let v=typeof o.duration=="number"?o.duration:3500,p=()=>{m.setAttribute(q,"exit");let N=t(()=>{m.parentNode&&m.parentNode.removeChild(m)},200);return T.removeEventListener("click",E),c.removeEventListener("keydown",h),T.removeEventListener("keydown",h),N},E=()=>p(),h=N=>{N.key==="Escape"&&(N.stopPropagation(),p())};T.addEventListener("click",E),c.addEventListener("keydown",h),T.addEventListener("keydown",h);let S=null;return o.sticky||(S=t(()=>{p()},v)),{dismiss(){S&&a(S),p()}}},set(i,o){return typeof o=="string"?this.show(i,{type:o}):this.show(i,o)},info(i,o={}){return this.show(i,{...o,type:"info"})},success(i,o={}){return this.show(i,{...o,type:"success"})},error(i,o={}){return this.show(i,{...o,type:"error"})},warn(i,o={}){return this.show(i,{...o,type:"warn"})}}}function R(e,t=setTimeout,a=clearTimeout){return Z(e,t,a)}var $=[{key:"name",label:"Name",headerClass:"w-full sm:w-1/3 text-left",cellClass:"font-medium text-text truncate"},{key:"progress",label:"Progress",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"progress"},{key:"downloadSpeed",label:"\u2193 Speed",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"bytesPerSecond"},{key:"uploadSpeed",label:"\u2191 Speed",headerClass:"w-24 text-right",cellClass:"tabular-nums text-right",formatter:"bytesPerSecond"},{key:"numPeers",label:"Peers",headerClass:"w-20 text-right",cellClass:"tabular-nums text-right",formatter:"integer"},{key:"ratio",label:"Ratio",headerClass:"w-20 text-right",cellClass:"tabular-nums text-right",formatter:"ratio"}];function ee(e){return e?e.infoHash||e.magnetURI||e.name||String(Math.random()):""}function te(e,t){return!e||!t?!1:e===t||e.magnetURI&&e.magnetURI===t.magnetURI||e.infoHash&&e.infoHash===t.infoHash}function ne(e){return typeof e!="number"||Number.isNaN(e)?"":`${(e*100).toFixed(1)}%`}function re(e){return typeof e!="number"||!Number.isFinite(e)?"0.00":e.toFixed(2)}function oe(e){return typeof e!="number"||!Number.isFinite(e)?"0":Math.max(0,Math.floor(e)).toString()}function ae(e,t){if(typeof t=="function")return t(e,!0)||"";if(typeof e!="number"||Number.isNaN(e)||e<1)return"";let a=["B","kB","MB","GB","TB"],i=Math.min(Math.floor(Math.log(e)/Math.log(1e3)),a.length-1);return`${(e/Math.pow(1e3,i)).toFixed(1)} ${a[i]}/s`}function se(e,t){let a=e.formatter;if(typeof a=="function")return a;let i=t?.[a];if(typeof i=="function")return i;switch(a){case"progress":return ne;case"ratio":return re;case"integer":return oe;case"bytesPerSecond":return o=>ae(o,t?.bytes);default:return o=>o}}function W({documentRef:e=typeof document<"u"?document:null,root:t,onSelect:a,formatters:i={}}={}){if(!e)throw new Error("createTorrentTable requires a document reference");if(!(t instanceof e.defaultView.HTMLElement))throw new Error("createTorrentTable requires a valid root element");let o=e;t.innerHTML="";let d=o.createElement("div");d.className="overflow-hidden rounded-xl border border-border-translucent bg-surface shadow-sm";let n=o.createElement("div");n.className="overflow-x-auto",d.appendChild(n);let m=o.createElement("table");m.className="min-w-full divide-y divide-border-translucent text-sm",n.appendChild(m);let c=o.createElement("thead");c.className="bg-surface-alt text-muted-strong";let T=o.createElement("tr");$.forEach(y=>{let x=o.createElement("th");x.setAttribute("scope","col"),x.className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide",y.headerClass&&(x.className+=` ${y.headerClass}`),x.textContent=y.label,T.appendChild(x)}),c.appendChild(T),m.appendChild(c);let v=o.createElement("tbody");v.className="divide-y divide-border-translucent",m.appendChild(v);let p=o.createElement("tbody"),E=o.createElement("tr"),h=o.createElement("td");h.className="px-4 py-8 text-center text-sm text-muted",h.colSpan=$.length,h.textContent="No active torrents yet. Add a magnet link to get started.",E.appendChild(h),p.appendChild(E),m.appendChild(p),t.appendChild(d);function S(y=[],x=null){let k=Array.isArray(y)?y:[];if(v.innerHTML="",!k.length){v.hidden=!0,p.hidden=!1;return}v.hidden=!1,p.hidden=!0;for(let B of k){let w=o.createElement("tr");w.className=["group","align-middle","cursor-pointer","transition","hover:bg-panel-hover","focus-visible:outline","focus-visible:outline-2","focus-visible:outline-offset-2","focus-visible:outline-info"].join(" "),w.setAttribute("role","button"),w.setAttribute("tabindex","0"),w.dataset.torrentId=ee(B),te(x,B)?(w.classList.add("bg-info/10","text-text"),w.setAttribute("aria-pressed","true")):w.setAttribute("aria-pressed","false"),w.addEventListener("click",()=>{typeof a=="function"&&a(B)}),w.addEventListener("keydown",C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),typeof a=="function"&&a(B))}),$.forEach(C=>{let A=o.createElement("td");A.className="px-4 py-3",C.cellClass&&(A.className+=` ${C.cellClass}`);let H=B?B[C.key]:void 0,r=se(C,i)(H,B,C),s=o.createElement("span");s.textContent=r==null?"":String(r),A.appendChild(s),w.appendChild(A)}),v.appendChild(w)}}function N(){t.innerHTML=""}return{render:S,destroy:N}}var ie="2.0",z=["wss://tracker.btorrent.xyz","wss://tracker.openwebtorrent.com"],j={announce:z},le={announce:z};function M(e,t=!1){if(typeof e!="number"||Number.isNaN(e))return"";if(e<1)return t?"":"0 B";let a=["B","kB","MB","GB","TB"],i=Math.min(Math.floor(Math.log(e)/Math.log(1e3)),a.length-1);return`${(e/Math.pow(1e3,i)).toFixed(1)} ${a[i]}${t?"/s":""}`}function ce(e){return typeof e!="number"||Number.isNaN(e)?"":`${(e*100).toFixed(1)}%`}function _(e){return typeof e!="number"||!Number.isFinite(e)?"0.00":e.toFixed(2)}function de(e,t){return!e||!t?!1:!!(e===t||e.infoHash&&t.infoHash&&e.infoHash===t.infoHash||e.magnetURI&&t.magnetURI&&e.magnetURI===t.magnetURI)}function ue(e){if(!(!e||!Array.isArray(e.files))&&(e.files.forEach(t=>{typeof t.priority!="string"&&(t.priority="0"),typeof t.getBlobURL=="function"&&t.getBlobURL((a,i)=>{a||!i||(t.url=i)})}),e.torrentFile&&typeof Blob=="function"&&typeof URL<"u"))try{let t=new Blob([e.torrentFile],{type:"application/x-bittorrent"});if(e.torrentFileBlobURL=URL.createObjectURL(t),!e.fileName){let a=e.name||"download";e.fileName=`${a}.torrent`}}catch(t){console.warn("[beacon] Failed to create torrent blob URL",t)}}function fe(e,t){if(!e)return;let a=typeof t=="string"?t:String(t??"0");if(e.priority=a,a==="-1"){typeof e.deselect=="function"&&e.deselect();return}let i=Number.parseInt(a,10);Number.isFinite(i)&&typeof e.select=="function"&&e.select(i)}function D(e,t){if(!Array.isArray(t)||t.length===0)return null;if(!e)return t[0];let a=t.find(i=>de(i,e));return a||t[0]}function G({documentRef:e=typeof document<"u"?document:null,WebTorrentCtor:t}={}){if(!e)throw new Error("createBeaconApp requires a document reference");let a=e.defaultView||globalThis,i=typeof t=="function"?t:typeof a?.WebTorrent=="function"?a.WebTorrent:null;if(!i)throw new Error("createBeaconApp requires a WebTorrent constructor");let o=R(e),d=new i({tracker:le}),n={form:e.querySelector('[data-beacon="magnet-form"]'),magnetInput:e.querySelector('[data-beacon="magnet-input"]'),seedButton:e.querySelector('[data-beacon="seed-button"]'),seedInput:e.querySelector('[data-beacon="seed-input"]'),tableRoot:e.querySelector('[data-beacon="torrent-table"]'),selectedSection:e.querySelector('[data-beacon="selected"]'),selectedName:e.querySelector('[data-beacon="selected-name"]'),pauseButton:e.querySelector('[data-beacon-action="pause"]'),resumeButton:e.querySelector('[data-beacon-action="resume"]'),downloadAllButton:e.querySelector('[data-beacon-action="download-all"]'),removeButton:e.querySelector('[data-beacon-action="remove"]'),copyMagnetButton:e.querySelector('[data-beacon-action="copy-magnet"]'),infoHashValue:e.querySelector('[data-beacon="info-hash"]'),fileList:e.querySelector('[data-beacon="file-list"]'),stats:e.querySelector('[data-beacon="client-stats"]'),overlay:e.querySelector('[data-beacon="processing-overlay"]')},m=n.tableRoot?W({documentRef:e,root:n.tableRoot,formatters:{bytes:(r,s=!1)=>M(r,s),progress:r=>ce(r),ratio:r=>_(r),integer:r=>typeof r=="number"&&Number.isFinite(r)?Math.floor(r).toString():"0",bytesPerSecond:r=>M(r,!0)},onSelect(r){c.selectedTorrent=r,y()}}):null,c={selectedTorrent:null,processing:!1},T=[],v=[];function p(r){T.push(r)}function E(r){c.processing=!!r,n.overlay&&(n.overlay.hidden=!c.processing)}function h(){return Array.isArray(d.torrents)?[...d.torrents]:[]}function S(){if(!n.stats)return;let r=M(d.downloadSpeed,!0)||"0 B/s",s=M(d.uploadSpeed,!0)||"0 B/s",f=_(d.ratio);n.stats.textContent=`Client stats: \u2193 ${r} \xB7 \u2191 ${s} \xB7 Ratio: ${f}`}function N(r){n.fileList&&(n.fileList.innerHTML="",!(!r||!Array.isArray(r.files)||!r.files.length)&&r.files.forEach((s,f)=>{let u=e.createElement("tr");u.className="align-top";let l=e.createElement("td");if(l.className="px-3 py-2",s.done&&s.url){let g=e.createElement("a");g.className="text-info hover:text-info-strong",g.href=s.url,g.download=s.name||`file-${f+1}`,g.textContent=s.name||`File ${f+1}`,l.appendChild(g)}else{let g=e.createElement("span");g.textContent=s.name||`File ${f+1}`,l.appendChild(g)}u.appendChild(l);let b=e.createElement("td");b.className="px-3 py-2 text-muted-strong",b.textContent=M(s.length)||"0 B",u.appendChild(b);let I=e.createElement("td");I.className="px-3 py-2";let L=e.createElement("select");L.className="select",L.name=`${s.name||`file-${f+1}`}-priority`,L.setAttribute("aria-label",`Set priority for ${s.name||`file ${f+1}`}`),[{value:"1",label:"High priority"},{value:"0",label:"Low priority"},{value:"-1",label:"Don't download"}].forEach(g=>{let U=e.createElement("option");U.value=g.value,U.textContent=g.label,g.value===s.priority&&(U.selected=!0),L.appendChild(U)}),L.value=s.priority??"0",L.addEventListener("change",g=>{fe(s,g.target.value)}),I.appendChild(L),u.appendChild(I),n.fileList.appendChild(u)}))}function y(){if(!n.selectedSection)return;let r=h();c.selectedTorrent=D(c.selectedTorrent,r);let s=c.selectedTorrent;n.selectedSection.hidden=!s,s&&(n.selectedName&&(n.selectedName.textContent=s.name||"Untitled torrent"),n.pauseButton&&(n.pauseButton.hidden=s.paused===!0,n.pauseButton.disabled=s.paused===!0),n.resumeButton&&(n.resumeButton.hidden=s.paused!==!0,n.resumeButton.disabled=s.paused!==!0),n.downloadAllButton&&(n.downloadAllButton.disabled=!(s.progress>=1)),n.infoHashValue&&(n.infoHashValue.textContent=s.infoHash||""),N(s))}function x(r,{isSeed:s=!1}={}){E(!1),ue(r),s||o.info(`Received ${r.name||"torrent"} metadata`),c.selectedTorrent||(c.selectedTorrent=r),y(),m?.render(h(),c.selectedTorrent)}function k(r){let s=typeof r=="string"?r.trim():"";s&&(E(!0),d.add(s,j,f=>{x(f,{isSeed:!1})}))}function B(r){!Array.isArray(r)||r.length===0||(E(!0),d.seed(r,j,s=>{x(s,{isSeed:!0}),o.success(`Seeding ${s.files.length} file(s)`)}))}function w(r){if(r){if(r.progress<1){o.warn("Torrent is not finished downloading yet.");return}r.files.forEach(s=>{typeof s.getBlob=="function"&&s.getBlob((f,u)=>{if(f||!u){console.error("[beacon] Failed to get blob for file",s?.name,f),o.error("Failed to prepare file for download.");return}let l=URL.createObjectURL(u),b=e.createElement("a");b.className="beacon-hidden-download",b.setAttribute("data-beacon-hidden-download","true"),b.href=l,b.download=s.name||"download",e.body.appendChild(b),b.click(),e.body.removeChild(b),URL.revokeObjectURL(l)})})}}function C(r){if(!r?.magnetURI)return;let s=r.magnetURI,f=a?.navigator?.clipboard;if(f&&typeof f.writeText=="function"){f.writeText(s).then(()=>{o.success("Magnet URI copied to clipboard!")}).catch(u=>{console.error("[beacon] Clipboard error",u),o.error("Failed to copy magnet URI")});return}try{let u=e.createElement("textarea");u.value=s,u.className="beacon-clipboard-offscreen",u.setAttribute("data-beacon-clipboard-state","offscreen"),e.body.appendChild(u),u.select(),e.execCommand?.("copy"),e.body.removeChild(u),o.success("Magnet URI copied (fallback)!")}catch(u){console.error("[beacon] Clipboard fallback error",u),o.error("Failed to copy magnet URI")}}function A(r){r&&r.destroy(s=>{s&&(console.error("[beacon] Failed to destroy torrent",s),o.error("Failed to remove torrent"));let f=h();c.selectedTorrent=D(null,f),m?.render(f,c.selectedTorrent),y()})}function H(){if(console.log(`[beacon] Starting beacon runtime v${ie}`),o||console.warn("[beacon] Toast service unavailable"),i.WEBRTC_SUPPORT||o?.error("Please use a browser with WebRTC support.",{sticky:!0}),n.form){let l=b=>{b.preventDefault(),k(n.magnetInput?.value||""),n.magnetInput&&(n.magnetInput.value="")};n.form.addEventListener("submit",l),p(()=>n.form.removeEventListener("submit",l))}if(n.seedButton&&n.seedInput){let l=()=>{n.seedInput.click()},b=()=>{let I=Array.from(n.seedInput.files||[]);n.seedInput.value="",B(I)};n.seedButton.addEventListener("click",l),n.seedInput.addEventListener("change",b),p(()=>{n.seedButton.removeEventListener("click",l),n.seedInput.removeEventListener("change",b)})}if(n.pauseButton){let l=()=>{c.selectedTorrent&&typeof c.selectedTorrent.pause=="function"&&(c.selectedTorrent.pause(),y())};n.pauseButton.addEventListener("click",l),p(()=>n.pauseButton.removeEventListener("click",l))}if(n.resumeButton){let l=()=>{c.selectedTorrent&&typeof c.selectedTorrent.resume=="function"&&(c.selectedTorrent.resume(),y())};n.resumeButton.addEventListener("click",l),p(()=>n.resumeButton.removeEventListener("click",l))}if(n.downloadAllButton){let l=()=>w(c.selectedTorrent);n.downloadAllButton.addEventListener("click",l),p(()=>n.downloadAllButton.removeEventListener("click",l))}if(n.removeButton){let l=()=>A(c.selectedTorrent);n.removeButton.addEventListener("click",l),p(()=>n.removeButton.removeEventListener("click",l))}if(n.copyMagnetButton){let l=()=>C(c.selectedTorrent);n.copyMagnetButton.addEventListener("click",l),p(()=>n.copyMagnetButton.removeEventListener("click",l))}let r=l=>{console.error("[beacon] Torrent client error",l),o?.error(l?.message||String(l)),E(!1)};d.on("error",r),p(()=>d.removeListener("error",r));let s=l=>{if(d.torrents&&d.torrents.length>0)return l.preventDefault(),l.returnValue="Transfers are in progress. Are you sure you want to leave or refresh?",l.returnValue};a&&typeof a.addEventListener=="function"&&(a.addEventListener("beforeunload",s),p(()=>a.removeEventListener("beforeunload",s))),m?.render(h(),c.selectedTorrent),y(),S(),E(!1);let f=a.setInterval(()=>{m?.render(h(),c.selectedTorrent),y(),S()},1e3);v.push(f);let u=a?.location?.hash;typeof u=="string"&&u.length>1&&k(u.slice(1))}function P(){v.forEach(r=>a.clearInterval(r)),v.length=0,T.forEach(r=>{try{r()}catch(s){console.warn("[beacon] Cleanup task failed",s)}}),T.length=0,m?.destroy();try{d.destroy()}catch(r){console.warn("[beacon] Failed to destroy client",r)}}return{mount:H,destroy:P}}function pe(){return typeof window<"u"&&window||typeof globalThis<"u"&&globalThis||null}function me(){let e=pe();if(e&&typeof e.WebTorrent=="function")return e.WebTorrent;throw new Error("WebTorrent runtime is not available on the global scope")}var F=null;function K(){if(F)return F;if(typeof document>"u")throw new Error("Beacon runtime requires a document environment");let e=me();return F=G({documentRef:document,WebTorrentCtor:e}),F.mount(),F}if(typeof document<"u")if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>{try{K()}catch(e){console.error("[beacon] Failed to mount app",e)}});else try{K()}catch(e){console.error("[beacon] Failed to mount app",e)}export{G as createBeaconApp,K as mountBeaconApp};
diff --git a/torrent/src/beacon-vendor.js b/torrent/src/beacon-vendor.js
index 9f61b3a7..51e31443 100644
--- a/torrent/src/beacon-vendor.js
+++ b/torrent/src/beacon-vendor.js
@@ -1,10 +1,15 @@
import { createBeaconApp } from "../app.js";
-function resolveWebTorrent() {
- const globalScope =
+function resolveGlobalScope() {
+ return (
(typeof window !== "undefined" && window) ||
(typeof globalThis !== "undefined" && globalThis) ||
- null;
+ null
+ );
+}
+
+function resolveWebTorrent() {
+ const globalScope = resolveGlobalScope();
if (globalScope && typeof globalScope.WebTorrent === "function") {
return globalScope.WebTorrent;