js-randomness-predictor
Version:
Predict Math.random output in Node, Deno, Bun, Chrome, Firefox, and Safari
2 lines (1 loc) • 12.3 kB
JavaScript
;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class m extends Error{constructor(t){t=t===void 0?"Cannot solve state. Unable to make accurate predictions.":t,super(t),this.name="UnsatError",Object.setPrototypeOf(this,new.target.prototype)}}class U extends Error{constructor(t){super(t),this.name="InsufficientSequenceLengthError",Object.setPrototypeOf(this,new.target.prototype)}}class g extends Error{constructor(t){super(t),this.name="UnexpectedRuntimeError",Object.setPrototypeOf(this,new.target.prototype)}}class u{constructor(){}static isDeno(){return typeof globalThis.Deno<"u"&&typeof Deno.version<"u"&&typeof Deno.version.deno=="string"}static isBun(){return typeof globalThis.Bun<"u"&&typeof Bun.version<"u"&&typeof process.versions.bun=="string"}static isNode(){return!this.isDeno()&&!this.isBun()&&typeof process.versions.node<"u"&&typeof process.versions.node=="string"}static isFirefox(){return typeof window<"u"&&navigator.userAgent.indexOf("Firefox")>-1}static isChrome(){return typeof window<"u"&&navigator.userAgent.indexOf("Chrome")>-1}static isSafari(){return typeof window<"u"&&navigator.userAgent.indexOf("Safari")>-1}static type(){if(this.isNode())return"node";if(this.isDeno())return"deno";if(this.isBun())return"bun";if(this.isChrome())return"chrome";if(this.isSafari())return"safari";if(this.isFirefox())return"firefox";throw new g}}function G(){if(u.isChrome())return"chrome";if(u.isSafari())return"safari";if(u.isFirefox())return"firefox"}async function Z(){const e="https://z3-tawny.vercel.app/z3-built.js",t="https://z3-tawny.vercel.app/z3-built.wasm";try{const[r,o]=await Promise.all([fetch(e),fetch(t)]);(!r.ok||!o.ok)&&console.error("js-randomness-predictor Failed to fetch z3 files",{jsResponse:r.ok,wasmResponse:o.ok});const i=await r.text(),h=new Blob([i],{type:"text/javascript"}),l=URL.createObjectURL(h);var n={locateFile:(f,d)=>f.endsWith(".wasm")?t:d+f,onRuntimeInitialized:()=>{console.log("js-randomness-predictor initialized.")},wasmBinaryFile:t,mainScriptUrlOrBlob:l};window.Module=n;const a=document.createElement("script");a.src=l,a.id="z3-built-jsrp",document.body.appendChild(a),(function f(){try{if(typeof initZ3>"u")setTimeout(()=>f(),300);else if(window.initZ3){window.initZ3=initZ3;return}}catch(d){console.error("js-randomness-predictor something went wrong during initialize()",d)}})()}catch(r){console.error("js-randomness-predictor an error occurred during loading:",r)}}function c(e){return e&0xffffffffffffffffn}class s{constructor(){}static symbolic(t){let n=t[0];n=n.xor(n.shl(23)),n=n.xor(n.lshr(17)),n=n.xor(t[1]),n=n.xor(t[1].lshr(26)),t[0]=t[1],t[1]=n}static symbolicArithmeticShiftRight(t){let n=t[0];n=n.xor(n.shl(23)),n=n.xor(n.shr(17)),n=n.xor(t[1]),n=n.xor(t[1].shr(26)),t[0]=t[1],t[1]=n}static concreteBackwards(t){let n=t[1]^t[0]>>26n^t[0];n=c(n^n>>17n^n>>34n^n>>51n),n=c(n^n<<23n^n<<46n),t[1]=t[0],t[0]=n}static concrete(t){let n=t[0];n^=c(n<<23n),n^=c(n>>17n),n^=t[1],n^=c(t[1]>>26n),t[0]=t[1],t[1]=n}static concreteArithmeticShiftRight(t){let n=c(t[0]);n^=c(n<<23n),n^=this.#e(n,17n),n^=t[1],n^=this.#e(t[1],26n),t[0]=t[1],t[1]=c(n)}static#e(t,n){const r=c(t>>n);if((t&1n<<63n)===0n)return r;const i=(1n<<n)-1n<<64n-n;return r|i}}let b;async function B(){if(b)return{...b};if(!window.initZ3||!window.Module)throw new Error("Z3 not initialized properly! window.initZ3 and window.Module should be set via IIFE in entry!");const e=window.initZ3,t=async()=>await e(window.Module),n=await(await Promise.resolve().then(()=>require("./index-X417yGod.cjs")).then(i=>i.index)).init(t),{createApi:r}=await Promise.resolve().then(()=>require("./index-BJxWVkn6.cjs")).then(i=>i.index),o={...n,...r(n.Z3)};return b={...o},o}class M{#e=[0n,0n];#n;#t;constructor(t,n){if(n.length<=0)throw new Error("V8EnginePredictor requires at least one solvingStrategy in solvingStrategies");this.sequence=t,this.#n=n,this.#t=this.#n[0]}async predictNext(){this.#e[0]===0n&&this.#e[1]===0n&&await this.#o();const t=this.#t.toDouble(this.#e);return this.#t.concreteXorShift(this.#e),t}async#r(){try{const{Context:t}=await B(),n=t("main"),r=new n.Solver,o=n.BitVec.const("ss0",64),i=n.BitVec.const("ss1",64),h=[o,i],l=[...this.sequence].reverse();for(const f of l){this.#t.symbolicXorShift(h);const d=this.#t.recoverMantissa(f);this.#t.constrainMantissa(d,h,r,n)}if(await r.check()!=="sat")throw new m;const a=r.model();this.#e=[a.get(o).value(),a.get(i).value()]}catch(t){return Promise.reject(t)}}async#o(){let t;for(const n of this.#n)try{return this.#t=n,await this.#r()}catch(r){if(!(r instanceof m))throw r;t=r}throw t??new Error("V8EnginePredictor : no strategies attempted")}}const w=Math.pow(2,53),z=[{recoverMantissa:e=>{const t=Math.floor(e*w);return BigInt(t)},toDouble:e=>Number(e[0]>>11n)/w,constrainMantissa:(e,t,n,r)=>{n.add(t[0].lshr(11).eq(r.BitVec.val(e,64)))},symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concreteBackwards(e)},{recoverMantissa:e=>{const t=Math.floor(e*w);return BigInt(t)},toDouble:e=>{const t=c(e[0]+e[1]);return Number(t>>11n)/w},constrainMantissa:(e,t,n,r)=>{const o=t[0].add(t[1]);n.add(o.lshr(11).eq(r.BitVec.val(e,64)))},symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concreteBackwards(e)}];class O extends M{constructor(t){super(t,z)}}class W{#e=[0n,0n];#n;#t;constructor(t,n){if(n.length<=0)throw new Error("SpiderMonkeyPredictor requires at least one solvingStrategy in solvingStrategies");this.sequence=t,this.#n=n,this.#t=this.#n[0]}async predictNext(){return this.#e[0]===0n&&this.#e[1]===0n&&await this.#o(),this.#t.concreteXorShift(this.#e),this.#t.toDouble(this.#e)}async#r(){try{const{Context:t}=await B(),n=t("main"),r=new n.Solver,o=n.BitVec.const("ss0",64),i=n.BitVec.const("ss1",64),h=[o,i];for(const f of this.sequence){this.#t.symbolicXorShift(h);const d=this.#t.recoverMantissa(f);this.#t.constrainMantissa(d,h,r,n)}if(await r.check()!=="sat")throw new m;const l=r.model(),a=[l.get(o).value(),l.get(i).value()];for(const f of this.sequence)this.#t.concreteXorShift(a);this.#e=a}catch(t){return Promise.reject(t)}}async#o(){let t;for(const n of this.#n)try{return this.#t=n,await this.#r()}catch(r){if(!(r instanceof m))throw r;t=r}throw t??new Error("SpiderMonkeyPredictor : no strategies attempted")}}const I=0x1fffffffffffffn,_=Math.pow(2,53),J=[{recoverMantissa:e=>BigInt(Math.floor(e*_)),toDouble:e=>{const t=c(e[0]+e[1]);return Number(t&I)/_},constrainMantissa:(e,t,n,r)=>{const o=t[0].add(t[1]).and(r.BitVec.val(I,64));n.add(o.eq(r.BitVec.val(e,64)))},symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concrete(e)}];class L extends W{constructor(t){super(t,J)}}const V=["node","bun","deno","chrome","firefox","safari"],K=["node","bun","deno"],H=["chrome","safari","firefox"];Object.fromEntries(V.map(e=>[e,K.includes(e)]));Object.fromEntries(V.map(e=>[e,H.includes(e)]));const Q={node:"v8",bun:"javascriptcore",deno:"v8",chrome:"v8",firefox:"spidermonkey",safari:"javascriptcore"};Object.entries(Q).reduce((e,[t,n])=>((e[n]||=[]).push(t),e),{});const y={node:5},T=64,S=0x000fffffffffffffn,N=0x3ff0000000000000n,p=Math.pow(2,53),Y=[{recoverMantissa:e=>{const t=Math.floor(e*p);return BigInt(t)},toDouble:e=>{const t=c(e[0]+e[1]);return Number(t>>11n)/p},constrainMantissa:(e,t,n,r)=>{const o=t[0].add(t[1]);n.add(o.lshr(11).eq(r.BitVec.val(e,64)))},symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concreteBackwards(e)},{recoverMantissa:e=>{const t=Math.floor(e*p);return BigInt(t)},toDouble:e=>Number(e[0]>>11n)/p,constrainMantissa:(e,t,n,r)=>{n.add(t[0].lshr(11).eq(r.BitVec.val(e,64)))},symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concreteBackwards(e)},{recoverMantissa:e=>{const t=Buffer.alloc(8);return t.writeDoubleLE(e+1,0),t.readBigUInt64LE(0)&S},toDouble:e=>{const t=Buffer.alloc(8);return t.writeBigUInt64LE(e[0]>>12n|N,0),t.readDoubleLE(0)-1},constrainMantissa:(e,t,n,r)=>{n.add(t[0].lshr(12).eq(r.BitVec.val(e,64)))},symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concreteBackwards(e)},{recoverMantissa:e=>{const t=Buffer.alloc(8);return t.writeDoubleLE(e+1,0),t.readBigUInt64LE(0)&S},toDouble:e=>{const t=e[0]+e[1],n=Buffer.alloc(8);return n.writeBigUInt64LE(t&S|N,0),n.readDoubleLE(0)-1},constrainMantissa:(e,t,n,r)=>{const o=t[0].add(t[1]).and(r.BitVec.val(S,64));n.add(o.eq(r.BitVec.val(e,64)))},symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concreteBackwards(e)}];class j extends M{constructor(t){if(t){if(t.length>=T)throw new Error(`sequence.length must be less than '${T}', got '${t.length}'`);if(t.length<y.node)throw new Error(`sequence.length must be at least '${y.node}', got '${t.length}'`)}if(!t){if(!u.isNode())throw new g("Expected NodeJS runtime! Unable to auto-generate sequence, please provide one.");t=Array.from({length:y.node},Math.random)}super(t,Y)}}class k{#e=[0n,0n];#n;#t;constructor(t,n){if(n.length<=0)throw new Error("JavaScriptCorePredictor requires at least one solvingStrategy in solvingStrategies");this.sequence=t,this.#n=n,this.#t=this.#n[0]}async predictNext(){return this.#e[0]===0n&&this.#e[1]===0n&&await this.#o(),this.#t.concreteXorShift(this.#e),this.#t.toDouble(this.#e)}async#r(){try{const{Context:t}=await B(),n=t("main"),r=new n.Solver,o=n.BitVec.const("ss0",64),i=n.BitVec.const("ss1",64),h=[o,i];for(const f of this.sequence){this.#t.symbolicXorShift(h);const d=this.#t.recoverMantissa(f);this.#t.constrainMantissa(d,h,r,n)}if(await r.check()!=="sat")throw new m;const l=r.model(),a=[l.get(o).value(),l.get(i).value()];for(const f of this.sequence)this.#t.concreteXorShift(a);this.#e=a}catch(t){return Promise.reject(t)}}async#o(){let t;for(const n of this.#n)try{return this.#t=n,await this.#r()}catch(r){if(!(r instanceof m))throw r;t=r}throw t??new Error("JavaScriptCorePredictor : no strategies attempted")}}const x=6,R=0x1fffffffffffffn,A=Math.pow(2,53),P={recoverMantissa:e=>BigInt(Math.floor(e*A)),toDouble:e=>{const t=c(e[0]+e[1]);return Number(t&R)/A},constrainMantissa:(e,t,n,r)=>{const o=t[0].add(t[1]).and(r.BitVec.val(R,64));n.add(o.eq(r.BitVec.val(e,64)))}},tt=[{...P,symbolicXorShift:e=>s.symbolicArithmeticShiftRight(e),concreteXorShift:e=>s.concreteArithmeticShiftRight(e)},{...P,symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concrete(e)}];class F extends k{constructor(t){if(t.length<x)throw new U(`sequence length must be >= ${x} : got ${t.length}`);super(t,tt)}}function et(e=1){const t=[];for(let n=0;n<e;n++)t.push(Math.random());return t}const v=6,X=0x1fffffffffffffn,C=Math.pow(2,53),D={recoverMantissa:e=>BigInt(Math.floor(e*C)),toDouble:e=>{const t=c(e[0]+e[1]);return Number(t&X)/C},constrainMantissa:(e,t,n,r)=>{const o=t[0].add(t[1]).and(r.BitVec.val(X,64));n.add(o.eq(r.BitVec.val(e,64)))}},nt=[{...D,symbolicXorShift:e=>s.symbolicArithmeticShiftRight(e),concreteXorShift:e=>s.concreteArithmeticShiftRight(e)},{...D,symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concrete(e)}];class q extends k{constructor(t){if(t&&t.length<v)throw new U(`sequence length must be >= ${v} : got ${t.length}`);if(!t){if(!u.isBun())throw new g("Expected Bun runtime! Unable to auto-generate sequence, please provide one.");t=et(v)}super(t,nt)}}const E=Math.pow(2,53),rt=[{recoverMantissa:e=>{const t=Math.floor(e*E);return BigInt(t)},toDouble:e=>Number(e[0]>>11n)/E,constrainMantissa:(e,t,n,r)=>{n.add(t[0].lshr(11).eq(r.BitVec.val(e,64)))},symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concreteBackwards(e)},{recoverMantissa:e=>{const t=Math.floor(e*E);return BigInt(t)},toDouble:e=>{const t=c(e[0]+e[1]);return Number(t>>11n)/E},constrainMantissa:(e,t,n,r)=>{const o=t[0].add(t[1]);n.add(o.lshr(11).eq(r.BitVec.val(e,64)))},symbolicXorShift:e=>s.symbolic(e),concreteXorShift:e=>s.concreteBackwards(e)}];class $ extends M{constructor(t){if(!t){if(!u.isDeno())throw new g("Expected Deno runtime! Unable to auto-generate sequence, please provide one.");t=Array.from({length:4},Math.random)}super(t,rt)}}Z();const ot=e=>new j(e),st=e=>new L(e),it=e=>new O(e),ct=e=>new F(e),at=e=>new q(e),ft=e=>new $(e);exports.BunRandomnessPredictor=q;exports.ChromeRandomnessPredictor=O;exports.DenoRandomnessPredictor=$;exports.FirefoxRandomnessPredictor=L;exports.NodeRandomnessPredictor=j;exports.SafariRandomnessPredictor=F;exports.bun=at;exports.chrome=it;exports.deno=ft;exports.firefox=st;exports.getCurrentBrowser=G;exports.node=ot;exports.safari=ct;