UNPKG

@adamlui/geolocate

Version:

Fetch IP geolocation data from the CLI.

16 lines 5.19 kB
#!/usr/bin/env node /** * © 2024–2025 Adam Lui under the MIT license. * Source: https://code.geolocatejs.org * Documentation: https://docs.geolocatejs.org */ const pkgName="@adamlui/geolocate",copyright="© 2024–2025 Adam Lui under the MIT license.",cmdFormat="geolocate [ip1] [ip2] [...] [options|commands]",srcURL="https://code.geolocatejs.org",docURL="https://docs.geolocatejs.org/#-command-line-usage",latestLocaleCommitHash="3560750";(async()=>{const e=require(__dirname.match(/src/)?"./geolocate":"./geolocate.min"),n=require("fs"),s=require("path"),{execSync:i,execFileSync:o}=require("child_process"),t="",r="";let p="en";if("win32"==process.platform)try{p=i("(Get-Culture).TwoLetterISOLanguageName",{shell:"powershell",encoding:"utf-8"}).trim()}catch(e){_("Error loading system language: "+e)}else{var a=process.env;p=(a.LANG||a.LANGUAGE||a.LC_ALL||a.LC_MESSAGES||a.LC_NAME||"en").split(".")[0]}let c={};var l,g,a=new Promise((t,r)=>{const a=`https://cdn.jsdelivr.net/gh/adamlui/js-utils@fd79febbc6decf19f52d94e720d3b135fb4a625b/geolocate/_locales/`,e=(p?p.replace("-","_"):"en")+"/";let c=a+e+"messages.json",l=0;v(c).then(async function o(e){try{const n=await e.json(),s={};for(const i in n)"object"==typeof n[i]&&"message"in n[i]&&(s[i]=n[i].message);t(s)}catch(e){if(3==++l)return t({});v(c=p.includes("-")&&1==l?c.replace(/([^_]*)_[^/]*(\/.*)/,"$1$2"):a+"en/messages.json").then(o).catch(r)}}).catch(r)});try{c=await a}catch(e){_("Error fetching messages: "+e)}const m={},f={flags:{quietMode:/^--?q(?:uiet)?(?:-?mode)?$/},infoCmds:{help:/^--?h(?:elp)?$/,version:/^--?ve?r?s?i?o?n?$/}};if(process.argv.forEach(o=>{var e,n;o.startsWith("-")&&(e=Object.keys(f.flags).find(e=>f.flags[e].test(o)),n=Object.keys(f.infoCmds).find(e=>f.infoCmds[e].test(o)),e?m[e]=!0:n||(console.error(` ${""+(c.prefix_error||"ERROR")}: `+`Arg [${o}] ${c.error_notRecognized||"not recognized"}.`),console.info(` ${""+(c.info_validArgs||"Valid arguments are below")}.`),$(["configOptions","infoCmds"]),process.exit(1)))}),process.argv.some(e=>f.infoCmds.help.test(e)))$();else if(process.argv.some(e=>f.infoCmds.version.test(e))){a=i(`npm view ${pkgName} version`).toString().trim()||"none";let e,o=process.cwd();for(;"/"!=o;){var d=s.join(o,"package.json");if(n.existsSync(d)){d=require(d);e=(d.dependencies?.[pkgName]||d.devDependencies?.[pkgName])?.match(/^\d+\.\d+\.\d+$/)?.[0]||"none";break}o=s.dirname(o)}console.info(` ${c.prefix_globalVer||"Global version"}: `+a),console.info(`${c.prefix_localVer||"Local version"}: `+e)}else{var h,u=[];for(const L of process.argv.slice(2))L.startsWith("-")||(h=L.replace(/[[\]]/g,""),u.push(h));a=await e.locate(u,{verbose:!m.quietMode});a||process.exit(1),m.quietMode||1!=a.length||(console.info(` IP: `+r+a[0].ip+t),console.info(`${c.geoLabel_country||"Country"}: `+r+a[0].country+t),console.info(`${c.geoLabel_region||"Region"}: `+r+a[0].regionName+t),console.info(`${c.geoLabel_city||"City"}: `+r+a[0].city+t),console.info(`${c.geoLabel_zip||"Zip"}: `+r+a[0].zip+t),console.info(`${c.geoLabel_lat||"Latitude"}: `+r+a[0].lat+t),console.info(`${c.geoLabel_lon||"Longitude"}: `+r+a[0].lon+t),console.info(`${c.geoLabel_timeZone||"Time zone"}: `+r+a[0].timezone.replace(/_/g," ").replace(/\//g," / ")+t),console.info("ISP: "+r+a[0].isp+t)),_(` ${c.info_copying||"Copying to clipboard"}...`),l=(l=JSON.stringify(a,null,2)).replace(/"/g,'""'),g={darwin:{binPath:"/usr/bin/pbcopy",args:[]},linux:{binPath:"/usr/bin/xclip",args:["-selection","clipboard"]},win32:{binPath:s.join(process.env.SYSTEMROOT,"System32","WindowsPowerShell","v1.0","powershell.exe"),args:["-Command","Set-Clipboard -Value $input"]}},o(...Object.values(g[process.platform]),{input:l})}function v(s){return new Promise((n,e)=>{var o=s.match(/^([^:]+):\/\//)[1];/^https?$/.test(o)||e(new Error(`${c.error_invalidURL||"Invalid URL"}.`)),require(o).get(s,e=>{let o="";e.on("data",e=>o+=e),e.on("end",()=>n({json:()=>JSON.parse(o)}))}).on("error",e)})}function $(e=["header","usage","configOptions","infoCmds"]){var o=` ${pkgName.replace(/^@[^/]+\//,"")}  `;const n={header:["\n├ "+o+(c.appCopyright||copyright),o+(c.prefix_source||"Source")+": "+srcURL],usage:[` ${r}o ${c.helpSection_usage||"Usage"}:`," » "+cmdFormat+t],configOptions:[` ${r}o ${c.helpSection_configOptions||"Config options"}:`,` -q, --quiet ${c.optionDesc_quiet||"Suppress all logging except errors"}.`],infoCmds:[` ${r}o ${c.helpSection_infoCmds||"Info commands"}:`," -h, --help "+(c.optionDesc_help||"Display help screen."),` -v, --version ${c.optionDesc_version||"Show version number"}.`]};e.forEach(r=>n[r]?.forEach(e=>{{var s=/header|usage/.test(r)?1:29;const i=process.stdout.columns||80,t=[],o=e.match(/\S+|\s+/g);let n="";o.forEach(e=>{var o=i-(t.length?s:0);n.length+"| ".length+e.length>o&&(t.push(t.length?n.trimStart():n),n=""),n+=e}),t.push(t.length?n.trimStart():n),t.forEach((e,o)=>console.info("| "+(0==o?e:" ".repeat(s)+e)))}})),console.info(` ${c.info_moreHelp||"For more help"}, ${c.info_visit||"visit"}: `+r+docURL+t)}function _(e){m.quietMode||console.info(e)}})();