import{resolve as m}from"path";import{BrowserWindow as y,session as I,utilityProcess as L,app as W}from"electron/main";import{WebSocketClose as g}from"@spacingbat3/disconnection";import l from"@spacingbat3/kolor";import T from"../../common/modules/l10n.js";import{initWindow as _}from"./parent.js";let r;function E(){const c=y.getAllWindows().find(i=>i.webContents.session===I.defaultSession&&i.getParentWindow()===null);if(c===void 0)throw console.debug("[WSS] Closed connection due to lack of main window."),new Error("Server couldn't connect to main window, try again later.");return c}function b(){const c=new T.default;let i=!1;const w=l.cyan("")!=="";r=L.fork(m(W.getAppPath(),"app/code/utility/ws.js"),[w?"--color=always":"--color=never"],{stdio:"pipe"}),r.stdout?.pipe(process.stdout),r.stderr?.pipe(process.stderr),r.once("spawn",()=>{r.postMessage(c.client.log.listenPort.replace("%s",l.underline(l.blueBright("%s"))));const k=(...e)=>{const[o,d,t]=e,s=E();if(i)return console.debug('[WSS] Blocked request "'+o.cmd+'" (WSS locked).'),g.TryAgainLater;if(i=!0,t===void 0)return;const a=o.cmd==="GUILD_TEMPLATE_BROWSER"?{width:960}:{},n=_("invite",s,{...a,webPreferences:{nodeIntegration:!1,contextIsolation:!0,sandbox:!0,disableDialogs:!0}});if(n===void 0)return;const S=o.cmd==="INVITE_BROWSER"?"/invite/":"/template/",u=new URL(s.webContents.getURL()).origin,f=/^https?:\/\/(?:[a-z]+\.)?discord\.com$/,R=d===null||f.test(d)&&f.test(u)?u:d;n.loadURL(R+S+o.args.code),n.webContents.once("did-finish-load",()=>{n.show()}),n.webContents.once("will-navigate",()=>n.close()),n.once("closed",()=>i=!1),n.webContents.session.webRequest.onBeforeRequest({urls:["ws://127.0.0.1:"+t.toString()+"/*"]},(P,h)=>h({cancel:!0}))},p=Object.freeze(["INVITE_BROWSER","GUILD_TEMPLATE_BROWSER","DEEP_LINK_CHANNEL"]);p.forEach(e=>r.postMessage({evt:"hook-set",hook:e})),r.on("message",e=>{if(typeof e=="string"){console.log(e);return}if(e.evt!=="hook-trigger")return;const{hook:o,nonce:d}=e;let t;const s=e.data[0];switch(o){case"INVITE_BROWSER":case"GUILD_TEMPLATE_BROWSER":t=void 0;try{t=k(...e.data,e.port)}catch(a){a instanceof Error&&(t=a)}r.postMessage({evt:"hook-return",hook:o,data:t,nonce:d});break;case"DEEP_LINK_CHANNEL":t=void 0;try{if(s.cmd!=="DEEP_LINK")throw TypeError("Invalid parsedData.cmd != DEEP_LINK condition");const a=E(),n=s.args.params.channelId!==void 0?"/channels/"+s.args.params.guildId+"/"+s.args.params.channelId:"/channels/"+s.args.params.guildId;a.webContents.send("navigate",n),a.show()}catch{t=g.TryAgainLater}r.postMessage({evt:"hook-return",hook:o,data:t,nonce:d});break;default:if(p.includes(o))throw Error(`Unhandled hook: "${String(o)}"`)}})})}export{b as default};
