yanki
Version:
A CLI tool and TypeScript library for syncing Markdown to Anki flashcards.
3 lines (2 loc) • 7.62 kB
JavaScript
var _=Object.defineProperty;var n=(e,r)=>_(e,"name",{value:r,configurable:!0});import c from"node:process";import{Buffer as I}from"node:buffer";import F from"node:path";import{fileURLToPath as W}from"node:url";import H,{execFile as w}from"node:child_process";import v,{constants as B}from"node:fs/promises";import R from"node:os";import g from"node:fs";import{promisify as h}from"node:util";let E;function U(){try{return g.statSync("/.dockerenv"),!0}catch{return!1}}n(U,"hasDockerEnv");function z(){try{return g.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}n(z,"hasDockerCGroup");function N(){return E===void 0&&(E=U()||z()),E}n(N,"isDocker");let S;const D=n(()=>{try{return g.statSync("/run/.containerenv"),!0}catch{return!1}},"hasContainerEnv");function P(){return S===void 0&&(S=D()||N()),S}n(P,"isInsideContainer");const $=n(()=>{if(c.platform!=="linux")return!1;if(R.release().toLowerCase().includes("microsoft"))return!P();try{return g.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!P():!1}catch{return!1}},"isWsl");var y=c.env.__IS_WSL_TEST__?$:$();function p(e,r,t){const i=n(o=>Object.defineProperty(e,r,{value:o,enumerable:!0,writable:!0}),"define");return Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get(){const o=t();return i(o),o},set(o){i(o)}}),e}n(p,"defineLazyProperty");const X=h(w);async function G(){if(c.platform!=="darwin")throw new Error("macOS only");const{stdout:e}=await X("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari"}n(G,"defaultBrowserId");const q=h(w);async function K(e,{humanReadableOutput:r=!0}={}){if(c.platform!=="darwin")throw new Error("macOS only");const t=r?[]:["-ss"],{stdout:i}=await q("osascript",["-e",e,t]);return i.trim()}n(K,"runAppleScript");async function Y(e){return K(`tell application "Finder" to set app_path to application file id "${e}" as string
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}n(Y,"bundleName");const j=h(w),J={AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},MSEdgeDHTML:{name:"Edge",id:"com.microsoft.edge"},MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"}};class L extends Error{static{n(this,"UnknownBrowserError")}}async function Q(e=j){const{stdout:r}=await e("reg",["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),t=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(r);if(!t)throw new L(`Cannot find Windows browser in stdout: ${JSON.stringify(r)}`);const{id:i}=t.groups,o=J[i];if(!o)throw new L(`Unknown browser ID: ${i}`);return o}n(Q,"defaultBrowser$1");const V=h(w),Z=n(e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,r=>r.toUpperCase()),"titleize");async function ee(){if(c.platform==="darwin"){const e=await G();return{name:await Y(e),id:e}}if(c.platform==="linux"){const{stdout:e}=await V("xdg-mime",["query","default","x-scheme-handler/http"]),r=e.trim();return{name:Z(r.replace(/.desktop$/,"").replace("-"," ")),id:r}}if(c.platform==="win32")return Q();throw new Error("Only macOS, Linux, and Windows are supported")}n(ee,"defaultBrowser");const A=F.dirname(W(import.meta.url)),O=F.join(A,"xdg-open"),{platform:m,arch:T}=c,re=(()=>{const e="/mnt/";let r;return async function(){if(r)return r;const t="/etc/wsl.conf";let i=!1;try{await v.access(t,B.F_OK),i=!0}catch{}if(!i)return e;const o=await v.readFile(t,{encoding:"utf8"}),f=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(o);return f?(r=f.groups.mountPoint.trim(),r=r.endsWith("/")?r:`${r}/`,r):e}})(),k=n(async(e,r)=>{let t;for(const i of e)try{return await r(i)}catch(o){t=o}throw t},"pTryEach"),x=n(async e=>{if(e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e},Array.isArray(e.app))return k(e.app,a=>x({...e,app:a}));let{name:r,arguments:t=[]}=e.app??{};if(t=[...t],Array.isArray(r))return k(r,a=>x({...e,app:{name:a,arguments:t}}));if(r==="browser"||r==="browserPrivate"){const a={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","microsoft-edge.desktop":"edge"},s={chrome:"--incognito",firefox:"--private-window",edge:"--inPrivate"},l=await ee();if(l.id in a){const C=a[l.id];return r==="browserPrivate"&&t.push(s[C]),x({...e,app:{name:u[C],arguments:t}})}throw new Error(`${l.name} is not supported as a default browser`)}let i;const o=[],f={};if(m==="darwin")i="open",e.wait&&o.push("--wait-apps"),e.background&&o.push("--background"),e.newInstance&&o.push("--new"),r&&o.push("-a",r);else if(m==="win32"||y&&!P()&&!r){const a=await re();i=y?`${a}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`:`${c.env.SYSTEMROOT||c.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell`,o.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),y||(f.windowsVerbatimArguments=!0);const s=["Start"];e.wait&&s.push("-Wait"),r?(s.push(`"\`"${r}\`""`),e.target&&t.push(e.target)):e.target&&s.push(`"${e.target}"`),t.length>0&&(t=t.map(l=>`"\`"${l}\`""`),s.push("-ArgumentList",t.join(","))),e.target=I.from(s.join(" "),"utf16le").toString("base64")}else{if(r)i=r;else{const a=!A||A==="/";let s=!1;try{await v.access(O,B.X_OK),s=!0}catch{}i=c.versions.electron??(m==="android"||a||!s)?"xdg-open":O}t.length>0&&o.push(...t),e.wait||(f.stdio="ignore",f.detached=!0)}m==="darwin"&&t.length>0&&o.push("--args",...t),e.target&&o.push(e.target);const d=H.spawn(i,o,f);return e.wait?new Promise((a,s)=>{d.once("error",s),d.once("close",l=>{if(!e.allowNonzeroExitCode&&l>0){s(new Error(`Exited with code ${l}`));return}a(d)})}):(d.unref(),d)},"baseOpen"),te=n((e,r)=>{if(typeof e!="string"&&!Array.isArray(e))throw new TypeError("Expected a valid `name`");const{arguments:t=[]}=r??{};if(t!=null&&!Array.isArray(t))throw new TypeError("Expected `appArguments` as Array type");return x({...r,app:{name:e,arguments:t}})},"openApp");function M(e){if(typeof e=="string"||Array.isArray(e))return e;const{[T]:r}=e;if(!r)throw new Error(`${T} is not supported`);return r}n(M,"detectArchBinary");function b({[m]:e},{wsl:r}){if(r&&y)return M(r);if(!e)throw new Error(`${m} is not supported`);return M(e)}n(b,"detectPlatformBinary");const u={};p(u,"chrome",()=>b({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}})),p(u,"firefox",()=>b({darwin:"firefox",win32:"C:\\Program Files\\Mozilla Firefox\\firefox.exe",linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"})),p(u,"edge",()=>b({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"})),p(u,"browser",()=>"browser"),p(u,"browserPrivate",()=>"browserPrivate");export{u as apps,te as openApp};