UNPKG

yanki

Version:

A CLI tool and TypeScript library for syncing Markdown to Anki flashcards.

3 lines (2 loc) 8.24 kB
var _=Object.defineProperty;var n=(e,r)=>_(e,"name",{value:r,configurable:!0});import a from"node:process";import{Buffer as F}from"node:buffer";import B from"node:path";import{fileURLToPath as H}from"node:url";import R,{promisify as g}from"node:util";import L,{execFile as h}from"node:child_process";import P,{constants as M}from"node:fs/promises";import N from"node:os";import y from"node:fs";let S;function z(){try{return y.statSync("/.dockerenv"),!0}catch{return!1}}n(z,"hasDockerEnv");function D(){try{return y.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}n(D,"hasDockerCGroup");function G(){return S===void 0&&(S=z()||D()),S}n(G,"isDocker");let v;const X=n(()=>{try{return y.statSync("/run/.containerenv"),!0}catch{return!1}},"hasContainerEnv");function E(){return v===void 0&&(v=X()||G()),v}n(E,"isInsideContainer");const $=n(()=>{if(a.platform!=="linux")return!1;if(N.release().toLowerCase().includes("microsoft"))return!E();try{return y.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!E():!1}catch{return!1}},"isWsl");var p=a.env.__IS_WSL_TEST__?$:$();function w(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(w,"defineLazyProperty");const K=g(h);async function q(){if(a.platform!=="darwin")throw new Error("macOS only");const{stdout:e}=await K("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(q,"defaultBrowserId");const Y=g(h);async function j(e,{humanReadableOutput:r=!0}={}){if(a.platform!=="darwin")throw new Error("macOS only");const t=r?[]:["-ss"],{stdout:i}=await Y("osascript",["-e",e,t]);return i.trim()}n(j,"runAppleScript");async function J(e){return j(`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(J,"bundleName");const Q=g(h),V={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 T extends Error{static{n(this,"UnknownBrowserError")}}async function Z(e=Q){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 T(`Cannot find Windows browser in stdout: ${JSON.stringify(r)}`);const{id:i}=t.groups,o=V[i];if(!o)throw new T(`Unknown browser ID: ${i}`);return o}n(Z,"defaultBrowser$1");const ee=g(h),re=n(e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,r=>r.toUpperCase()),"titleize");async function te(){if(a.platform==="darwin"){const e=await q();return{name:await J(e),id:e}}if(a.platform==="linux"){const{stdout:e}=await ee("xdg-mime",["query","default","x-scheme-handler/http"]),r=e.trim();return{name:re(r.replace(/.desktop$/,"").replace("-"," ")),id:r}}if(a.platform==="win32")return Z();throw new Error("Only macOS, Linux, and Windows are supported")}n(te,"defaultBrowser");const oe=R.promisify(L.execFile),A=B.dirname(H(import.meta.url)),I=B.join(A,"xdg-open"),{platform:d,arch:O}=a,ne=(()=>{const e="/mnt/";let r;return async function(){if(r)return r;const t="/etc/wsl.conf";let i=!1;try{await P.access(t,M.F_OK),i=!0}catch{}if(!i)return e;const o=await P.readFile(t,{encoding:"utf8"}),c=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(o);return c?(r=c.groups.mountPoint.trim(),r=r.endsWith("/")?r:`${r}/`,r):e}})(),W=n(async()=>`${await ne()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,"getPowershellPathFromWsl");async function ie(){const e=await W(),t=F.from('(Get-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice").ProgId',"utf16le").toString("base64"),{stdout:i}=await oe(e,["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",t],{encoding:"utf8"}),o=i.trim(),c={ChromeHTML:"com.google.chrome",MSEdgeHTM:"com.microsoft.edge",FirefoxURL:"org.mozilla.firefox"};return c[o]?{id:c[o]}:{}}n(ie,"getWindowsDefaultBrowserFromWsl");const 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,s=>x({...e,app:s}));let{name:r,arguments:t=[]}=e.app??{};if(t=[...t],Array.isArray(r))return k(r,s=>x({...e,app:{name:s,arguments:t}}));if(r==="browser"||r==="browserPrivate"){const s={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge"},l={chrome:"--incognito",firefox:"--private-window",edge:"--inPrivate"},f=p?await ie():await te();if(f.id in s){const b=s[f.id];return r==="browserPrivate"&&t.push(l[b]),x({...e,app:{name:m[b],arguments:t}})}throw new Error(`${f.name} is not supported as a default browser`)}let i;const o=[],c={};if(d==="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(d==="win32"||p&&!E()&&!r){i=p?await W():`${a.env.SYSTEMROOT||a.env.windir||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell`,o.push("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"),p||(c.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=F.from(s.join(" "),"utf16le").toString("base64")}else{if(r)i=r;else{const s=!A||A==="/";let l=!1;try{await P.access(I,M.X_OK),l=!0}catch{}i=a.versions.electron??(d==="android"||s||!l)?"xdg-open":I}t.length>0&&o.push(...t),e.wait||(c.stdio="ignore",c.detached=!0)}d==="darwin"&&t.length>0&&o.push("--args",...t),e.target&&o.push(e.target);const u=L.spawn(i,o,c);return e.wait?new Promise((s,l)=>{u.once("error",l),u.once("close",f=>{if(!e.allowNonzeroExitCode&&f>0){l(new Error(`Exited with code ${f}`));return}s(u)})}):(u.unref(),u)},"baseOpen"),se=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 U(e){if(typeof e=="string"||Array.isArray(e))return e;const{[O]:r}=e;if(!r)throw new Error(`${O} is not supported`);return r}n(U,"detectArchBinary");function C({[d]:e},{wsl:r}){if(r&&p)return U(r);if(!e)throw new Error(`${d} is not supported`);return U(e)}n(C,"detectPlatformBinary");const m={};w(m,"chrome",()=>C({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"]}})),w(m,"firefox",()=>C({darwin:"firefox",win32:"C:\\Program Files\\Mozilla Firefox\\firefox.exe",linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"})),w(m,"edge",()=>C({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"})),w(m,"browser",()=>"browser"),w(m,"browserPrivate",()=>"browserPrivate");export{m as apps,se as openApp};