@iplookup/country
Version:
Browser api to lookup country from IP address
2 lines (1 loc) • 1.67 kB
JavaScript
var IpLookup=function(){"use strict";const n=n=>((n=n.split(/\./))[0]<<24|n[1]<<16|n[2]<<8|n[3])>>>0,r=document.currentScript.src.split("/").slice(0,-1).join("/")+"/",t=async(n,r=3)=>fetch(n,{cache:"no-cache"}).then((async e=>{return e.ok?e.arrayBuffer():404===e.status?null:r?(await(i=100*(4-r)*(4-r),new Promise((n=>setTimeout(n,i)))),t(n,r-1)):null;var i})),e=t,i={},l={4:r,6:r},s={4:e(r+"4.idx").then((n=>{if(n)return i[4]=new Uint32Array(n)})),6:e(r+"4.idx").then((n=>{if(n)return i[6]=new BigUint64Array(n)}))};return async r=>{var e,c,u=!0;r.includes(":")?6===(c=(e=(r=>{if(r.includes("."))return n(r.split(":").pop());var t,e=0n;if((r=r.split(/:/)).length-1<7){const n=r.indexOf("");if(n<4){const e=8-r.length,i=n+e;for(t=7;t>=n;t--)r[t]=t>i?r[t-e]:0}}for(t=0;t<4;t++)r[t]&&(e+=BigInt(parseInt(r[t],16))<<BigInt(16*(3-t)));return e})(r)).constructor===BigInt?6:4)&&(u=!1):(e=n(r),c=4);const a=i[c]||await s[c];if(!a)return null;if(!(e>=a[0]))return null;for(var o,f=0,g=a.length-1;;)if(e<a[o=f+g>>1]){if(g-f<2)return null;g=o-1}else{if(f===o){g>o&&e>=a[g]&&(o=g);break}f=o}const h=((n,r)=>n.length>r?n:"_".repeat(r-n.length)+n)(o.toString(36),2);const y=await t(l[c]+c+"/"+h);if(!y)return null;const p=2*(c-2),w=2+2*p,d=y.byteLength/w,A=u?new Uint32Array(y.slice(0,4*d)):new BigUint64Array(y.slice(0,8*d));for(f=0,g=d-1;;)if(e<A[o=f+g>>1]){if(g-f<2)return null;g=o-1}else{if(f===o){g>o&&e>=A[g]&&(o=g);break}f=o}const B=u?new Uint32Array(y.slice((d+o)*p,(d+o+1)*p))[0]:new BigUint64Array(y.slice((d+o)*p,(d+o+1)*p))[0];if(e>=A[o]&&e<=B){const n=new Uint16Array(y.slice(d*p*2+2*o,d*p*2+2*(o+1)))[0];return{country:String.fromCharCode(255&n,n>>8)}}return null}}();