var C=Object.create;var M=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var T=Object.getOwnPropertyNames;var H=Object.getPrototypeOf,F=Object.prototype.hasOwnProperty;var _=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of T(e))!F.call(t,o)&&o!==r&&M(t,o,{get:()=>e[o],enumerable:!(s=D(e,o))||s.enumerable});return t};var w=(t,e,r)=>(r=t!=null?C(H(t)):{},_(e||!t||!t.__esModule?M(r,"default",{value:t,enumerable:!0}):r,t));var B=require("source-map-support"),p=w(require("../main/modules/error")),n=require("electron/main"),P=require("electron/common"),E=require("fs"),h=require("./global"),U=require("../main/modules/update"),x=w(require("./modules/l10n")),O=w(require("../main/windows/main")),k=require("../main/modules/config"),i=w(require("@spacingbat3/kolor")),m=require("path"),R=require("./modules/agent"),L=require("./modules/client"),A=require("../main/modules/optimize"),W=require("../main/modules/extensions"),v=require("util");process.platform==="win32"&&(process.argv[1]?.startsWith("--squirrel-")??!1)&&(console.log("Detected --squirrel-* option, possibly application's being run during installation, aborting..."),process.exit());(0,B.install)();(0,p.default)();const j=Object.freeze({options:Object.freeze({color:{type:"string"},help:{type:"boolean",short:"h"},info:{type:"boolean",short:"?"},version:{type:"boolean",short:"V"},"start-minimized":{type:"boolean",short:"m"},"export-l10n":{type:"string"},verbose:{type:"boolean",short:"v"},"user-agent-mobile":{type:"boolean"},"user-agent-version":{type:"string"},"user-agent-device":{type:"string"},"user-agent-platform":{type:"string"},"user-agent-arch":{type:"string"},"add-css-theme":{type:"boolean"},"gpu-info":{type:"string"},"safe-mode":{type:"boolean"}}),strict:!1,args:Object.freeze(process.argv).slice(1).filter(t=>(0,m.resolve)(t)!==(0,m.resolve)(n.app.getAppPath()))}),a=Object.freeze((0,v.parseArgs)(j));{const t=console.warn,e=console.error,r=console.debug;console.error=(s,...o)=>{e(typeof s=="string"?i.default.red(s):s,...o)},console.warn=(s,...o)=>{t(typeof s=="string"?i.default.yellow(s):s,...o)},console.debug=(s,...o)=>{(__filename.startsWith(n.app.getAppPath())&&(0,v.debug)("webcord").enabled||a.values.verbose===!0)&&r(typeof s=="string"?i.default.gray(s):s,...o)}}{const t=()=>console.log=console.debug=()=>{},e=()=>console.error=console.warn=()=>{};process.stdout.once("error",t).once("close",t),process.stderr.once("error",e).once("close",e)}{const{AppUserModelId:t}=(0,L.getBuildInfo)();process.platform==="win32"&&t!==void 0&&n.app.setAppUserModelId(t)}let z=!1,g=!1;const S={};let b;{const t=(e,r,s,o=32)=>{const l=j.options[e],f=["--"+e,s!==void 0?"="+i.default.yellow(s):l.type==="string"?"="+i.default.yellow("{string}"):"","short"in l?`   -${l.short}`:""].join(""),c=o-(0,v.stripVTControlCharacters)(f).length,d=r.replaceAll(s??/^$/g,s!==void 0?i.default.yellow(s):"").replaceAll(/(--?[a-zA-Z-]+)/g,i.default.green("$1"));return"  "+i.default.green(f)+" ".repeat(c>0?c:0)+i.default.gray(d)};if((0,L.getBuildInfo)().type!=="devel")for(const e of["inspect-brk","inspect-port","inspect","inspect-publish-uid"])n.app.commandLine.hasSwitch(e)&&(console.info("Unsafe switch detected: '--"+e+"'! It will be removed from Chromium's cmdline\u2026"),n.app.commandLine.removeSwitch(e));if(a.values.help===!0||a.values.info===!0){const e=process.argv0.endsWith("electron")&&process.argv.length>2?(process.argv[0]??"")+' "'+(process.argv[1]??"")+'"':process.argv0;console.log([`
 `+i.default.bold(i.default.blue(n.app.getName()))+" \u2013 Privacy focused Discord client made with "+i.default.bold(i.default.whiteBright(i.default.bgBlue("TypeScript")))+" and "+i.default.bold(i.default.bgBlack(i.default.cyanBright("Electron")))+`.
`," "+i.default.underline("Usage:")," "+i.default.red(e)+i.default.green(` [options]
`)," "+i.default.underline("Options:")].join(`
`)+`
`+[t("color","Whenever colorize console font.","always|auto|never"),t("help","Show this help message."),t("info","An alias for --help."),t("version","Show current application version."),t("start-minimized","Hide application at first run."),t("export-l10n","Export localization files to {dir} directory","{dir}."),t("verbose","Show debug messages."),t("gpu-info","Shows GPU information as JS object.","basic|complete"),t("user-agent-mobile","Whenever use 'mobile' variant of user agent."),t("user-agent-platform","Platform to replace in the user agent."),t("user-agent-version","Version of platform in user agent."),t("user-agent-device","Device identifier in the user agent (Android)."),t("user-agent-arch","Architecture to replace in the user agent."),t("add-css-theme","Adds theme to WebCord using file picker."),t("safe-mode","Starts WebCord in 'Safe Mode'.")].sort().join(`
`)+`
`),n.app.exit()}if(a.values.version===!0){const e=(0,L.getBuildInfo)();console.log(n.app.getName()+" v"+n.app.getVersion()+", "+(e.type==="release"?"stable":"development")+" build"+(e.commit!==void 0?", commit hash "+e.commit:"")),n.app.exit()}if(a.values["user-agent-mobile"]===!0&&(S.mobile=!0),("user-agent-device"in a.values||"user-agent-version"in a.values||"user-agent-platform"in a.values||"user-agent-arch"in a.values)&&(S.replace={platform:typeof a.values["user-agent-platform"]=="string"?a.values["user-agent-platform"]:process.platform,version:typeof a.values["user-agent-version"]=="string"?a.values["user-agent-version"]:process.getSystemVersion(),device:typeof a.values["user-agent-device"]=="string"?a.values["user-agent-device"]:void 0,arch:typeof a.values["user-agent-arch"]=="string"?a.values["user-agent-arch"]:process.arch}),a.values["start-minimized"]===!0&&(z=!0),a.values["safe-mode"]===!0&&(g=!0),a.values.verbose===!0?(process.env.NODE_DEBUG="*",process.env.DEBUG="*",n.app.commandLine.appendSwitch("enable-logging"),n.app.commandLine.appendSwitch("log-level","-1"),n.app.commandLine.appendSwitch("v","-1")):n.app.commandLine.appendSwitch("log-level","3"),"export-l10n"in a.values&&(b=()=>{const e=new x.default,r=a.values["export-l10n"];if(r!=="string")throw new TypeError("Parameter 'export-l10n' should contain a string value!");const s=[];for(const o of Object.keys(e))s.push(E.promises.writeFile((0,m.resolve)(r,o+".json"),JSON.stringify(e[o],null,2)));Promise.all(s).then(()=>{console.log([`
\u{1F389}\uFE0F `+i.default.green(i.default.bold("Successfully"))+" exported localization files to","   '"+i.default.blue(i.default.underline(r))+`'!
`].join(`
`)),n.app.quit()}).catch(o=>{if(!(o instanceof Error))return;const l="path"in o&&typeof o.path=="string"?{relative:(0,m.relative)(process.cwd(),o.path),absolute:(0,m.resolve)(process.cwd(),o.path),original:o.path}:{original:""},f=l.absolute!==void 0?l.absolute.length>l.relative.length?l.relative:l.absolute:null,c="syscall"in o&&typeof o.syscall=="string"?o.syscall:"",d="code"in o&&typeof o.code=="string"?o.code:"";console.error([`
\u26D4\uFE0F `+i.default.red(i.default.bold("code"in o&&typeof o.code=="string"?o.code:o.name))+" "+c+": ",f!==null?i.default.blue(i.default.underline(f))+": ":"",o.message.replace(d+": ","").replace(", "+c+" '"+l.original+"'","")+`.
`].join("")),n.app.exit(("errno"in o&&typeof o.errno=="number"?o.errno:0)*-1)})}),"gpu-info"in a.values){const e=a.values["gpu-info"];switch(e){case"basic":case"complete":n.app.getGPUInfo(e).then(r=>{console.log("GPU information object:"),console.dir(r)}).then(()=>n.app.exit()).catch(p.commonCatches.throw);break;default:throw new Error(`Flag 'gpu-info' should include a value of type '"basic"|"complete"'.`)}}"add-css-theme"in a.values&&(b=()=>{W.styles.add().then(()=>process.exit(0)).catch(()=>process.exit(1))})}{const t=(e,r)=>{if(r!==void 0&&n.app.commandLine.getSwitchValue(e)!=="")switch(e){case"enable-features":case"enable-blink-features":r=n.app.commandLine.getSwitchValue(e)+","+r}n.app.commandLine.appendSwitch(e,r),console.debug("[OPTIMIZE] Applying flag: %s...","--"+e+(r!==void 0?"="+r:""))};if(g)n.app.commandLine.appendSwitch("use-gl","angle"),n.app.commandLine.appendSwitch("use-angle","swiftshader");else if(k.appConfig.value.settings.advanced.optimize.gpu)for(const e of(0,A.getRecommendedGPUFlags)())t(e[0],e[1]);if(process.platform!=="win32"&&k.appConfig.value.settings.advanced.unix.autoscroll&&!g&&t("enable-blink-features","MiddleClickAutoscroll"),!g)for(const e of(0,A.getRecommendedOSFlags)())t(e[0],e[1]);if(process.platform!=="win32"&&process.platform!=="darwin"&&!g){const e=n.app.commandLine.getSwitchValue("enable-features");for(const r of["MediaSessionService","HardwareMediaKeyHandling","WebRtcAllowInputVolumeAdjustment"])if(!e.includes(r)){const s=n.app.commandLine.getSwitchValue("disable-features");console.debug("[FEATURE] Disabling '%s'...",r),s===""?n.app.commandLine.appendSwitch("disable-features",r):n.app.commandLine.appendSwitch("disable-features",s+","+r)}}}g&&n.app.disableHardwareAcceleration(),n.app.userAgentFallback=(0,R.getUserAgent)(process.versions.chrome,S.mobile,S.replace);const q=n.app.requestSingleInstanceLock();function G(){if(b)b();else{const t=setInterval(()=>{(0,U.checkVersion)(t).catch(p.commonCatches.print)},18e5);(0,U.checkVersion)(t).catch(p.commonCatches.print);const e=(0,O.default)(z);import("../main/modules/socket.mjs").then(r=>r.default()).catch(p.commonCatches.print),n.app.on("second-instance",()=>{e.isVisible()||e.show(),e.isMinimized()&&e.restore(),e.focus()})}}!q&&!b?n.app.on("ready",()=>{console.log(new x.default().client.log.singleInstance),n.app.quit()}):n.app.on("ready",G);let N=0;n.app.on("web-contents-created",(t,e)=>{const r=e.session===n.session.defaultSession;r||(e.session.setPermissionCheckHandler(()=>!1),e.session.setPermissionRequestHandler((s,o,l)=>l(!1))),e.session.setDevicePermissionHandler(()=>!1),e.session.setSSLConfig({minVersion:"tls1.2"}),e.on("will-navigate",(s,o)=>{const l=e.getURL();l!==""&&new URL(l).origin!==new URL(o).origin&&s.preventDefault()}),e.on("render-process-gone",(s,o)=>{if(console.error(i.default.bold("[WC_%s:%d]")+" %s",e.getProcessId(),o.exitCode,o.reason),e.reloadIgnoringCache(),!g&&++N>10){console.warn("Crash count exceeded (>10), relaunching in safe mode...");const l=[...process.argv];l.shift(),l.push("--safe-mode"),n.app.relaunch({args:l}),n.app.quit()}}),e.setWindowOpenHandler(s=>{const o=k.appConfig.value.settings;if(!n.app.isReady())return{action:"deny"};const l=new URL(s.url),f=new URL(e.getURL()).origin===l.origin,c={trust:!1,allow:!1};if(h.protocols.secure.includes(l.protocol)&&(c.trust=!0),h.protocols.allowed.includes(l.protocol)&&(c.allow=!0),(c.trust||c.allow)&&!f&&(o.advanced.redirection.warn||c.allow||!r)){const d=n.BrowserWindow.fromWebContents(e),{dialog:u,context:V}=new x.default().client,I={type:"warning",title:u.common.warning+": "+u.externalApp.title,message:u.externalApp.message,buttons:[u.common.no,V.copyURL,u.common.yes],defaultId:0,cancelId:0,detail:u.common.source+`:
`+(0,h.wordWrap)(s.url,Math.round(n.screen.getPrimaryDisplay().bounds.width/16),16),textWidth:320,normalizeAccessKeys:!0};let y;if(d instanceof n.BrowserWindow?y=n.dialog.showMessageBoxSync(d,I):y=n.dialog.showMessageBoxSync(I),y===1&&P.clipboard.writeText(s.url),y<(I.buttons?.length??0)-1)return{action:"deny"}}if(c.trust||c.allow){const d=new URL(s.url),u=n.BrowserWindow.fromWebContents(e);if(d.host===h.knownInstancesList[o.advanced.currentInstance.radio][1].host&&d.pathname==="/popout")return{action:"allow",overrideBrowserWindowOptions:{autoHideMenuBar:!0,...u?{BrowserWindow:u}:{},fullscreenable:!1,webPreferences:{nodeIntegration:!1,sandbox:!0,contextIsolation:!0,webSecurity:!0,enableWebSQL:!1}}};P.shell.openExternal(s.url).catch(p.commonCatches.print)}return{action:"deny"}}),e.once("did-create-window",s=>s.removeMenu()),e.on("did-create-window",s=>{W.styles.load(s.webContents)})}),n.app.on("child-process-gone",(t,e)=>{const r=(e.name??e.type).replace(" ","");let s,o=null;switch(e.reason){case"oom":s="Computer memory seem to be at poor condition.",o="Just let it forget some stuff, I guess?";break;case"launch-failed":s="Process is too lazy to start working!",o="Try to motivate it a little... :/.";break;case"abnormal-exit":s="Process left us unexpectedly!",o=`Rest in peace, ${r}... :(`;break;case"integrity-failure":s="Process was an impostor!";break;default:s=e.reason}e.reason!=="killed"&&e.reason!=="clean-exit"&&a.values.verbose!==!0&&(console.error(i.default.bold("[%s:%d]")+" %s",r,e.exitCode,s),o!==null&&setImmediate(()=>console.error(i.default.bold("[%s:TIP]")+" %s",r,o)))});
