velocid
Version:
Revolutionary high-performance distributed ID generator with military-grade security
3 lines (2 loc) • 8.77 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).Velocid={})}(this,function(t){"use strict";class e{static getInfo(){if(this._info)return this._info;const t={type:this.detectPlatformType(),hasCrypto:this.hasCryptoSupport(),hasSharedArrayBuffer:this.hasSharedArrayBufferSupport(),hardwareConcurrency:this.getHardwareConcurrency()};return this._info=t,t}static detectPlatformType(){return"undefined"!=typeof window?"undefined"!=typeof self&&"function"==typeof self.importScripts?"webworker":"browser":"undefined"!=typeof process&&process.versions?.node?"node":"unknown"}static hasCryptoSupport(){try{const t="undefined"!=typeof globalThis&&globalThis.crypto?globalThis.crypto:"undefined"!=typeof window&&window.crypto?window.crypto:void 0;if(t&&"function"==typeof t.getRandomValues)return!0;if("undefined"!=typeof require){return!!require("crypto").randomBytes}return!1}catch{return!1}}static hasSharedArrayBufferSupport(){try{return"undefined"!=typeof SharedArrayBuffer}catch{return!1}}static getHardwareConcurrency(){if("undefined"!=typeof navigator&&navigator.hardwareConcurrency)return navigator.hardwareConcurrency;try{if("undefined"!=typeof require){return require("os").cpus().length}}catch{}return 4}}function r(t){const e=new Uint8Array(t),r="undefined"!=typeof globalThis&&globalThis.crypto?globalThis.crypto:"undefined"!=typeof window&&window.crypto?window.crypto:void 0;if(r&&"function"==typeof r.getRandomValues)return r.getRandomValues(e),e;try{if("undefined"!=typeof require){const e=require("crypto").randomBytes(t);return new Uint8Array(e)}}catch{console.warn("velocid: Using insecure fallback random number generation");for(let r=0;r<t;r++)e[r]=Math.floor(256*Math.random())}return e}e._info=null;class n{constructor(){this.hasSharedArrayBuffer=e.getInfo().hasSharedArrayBuffer,this.hasSharedArrayBuffer?this.buffer=new SharedArrayBuffer(16):this.buffer=new ArrayBuffer(16),this.counter=new BigUint64Array(this.buffer),this.initialize()}initialize(){const t=r(3);let e=0n;for(let r=0;r<3;r++)e=e<<8n|BigInt(t[r]);this.counter[0]=1n|e,this.counter[1]=0n}getNext(){if(this.hasSharedArrayBuffer){const t=Atomics.add(this.counter,0,1n);return Number(0xffffffn&t)}{const t=this.counter[0];return this.counter[0]=t+1n,Number(0xffffffn&t)}}getCurrent(){return this.counter[0]}reset(){this.initialize()}}class i{constructor(t){if(void 0!==t)this._id=65535&t;else{const t=i.getOrGenerateNodeId(),e=i._instanceCounter++;this._id=t+e&65535}}get id(){return this._id}static getOrGenerateNodeId(){return null!==this._nodeId||(this._nodeId=this.generateStableNodeId()),this._nodeId}static generateStableNodeId(){try{const t=function(){const t=[];try{if("undefined"!=typeof require){const e=require("os"),r=e.networkInterfaces();for(const[e,n]of Object.entries(r))if(n&&Array.isArray(n))for(const e of n)e.mac&&"00:00:00:00:00:00"!==e.mac&&t.push(`mac:${e.mac}`);const n=e.hostname();n&&t.push(`hostname:${n}`),t.push(`platform:${e.platform()}`),t.push(`arch:${e.arch()}`)}"undefined"!=typeof navigator&&(navigator.hardwareConcurrency&&t.push(`hw:${navigator.hardwareConcurrency}`),navigator.language&&t.push(`lang:${navigator.language}`),navigator.platform&&t.push(`platform:${navigator.platform}`)),"undefined"!=typeof screen&&t.push(`screen:${screen.width}x${screen.height}`),"undefined"!=typeof process&&process.pid&&t.push(`pid:${process.pid}`);const e=Intl.DateTimeFormat().resolvedOptions().timeZone;e&&t.push(`tz:${e}`)}catch(t){console.warn("velocid: Error gathering node identifiers:",t)}return t.push(`ts:${Date.now()}`),t.push(`rnd:${Math.random()}`),t}().join("|");return 65535&this.simpleHash(t)}catch(t){console.warn("velocid: Error generating node ID, using random fallback:",t);const e=r(2);return e[0]<<8|e[1]}}static simpleHash(t){let e=0;for(let r=0;r<t.length;r++){e=(e<<5)-e+t.charCodeAt(r),e&=e}return Math.abs(e)}toHex(){return this._id.toString(16).padStart(4,"0")}static getGlobalNodeId(){return this.getOrGenerateNodeId()}}i._nodeId=null,i._instanceCounter=0;class a{constructor(t){const e=t||this.seedFromSystemEntropy();this.prng=new o(e)}seedFromSystemEntropy(){return r(32)}getNext(){return 1048575&this.prng.next()}getBatch(t){const e=new Array(t);for(let r=0;r<t;r++)e[r]=this.getNext();return e}reseed(t){const e=t||this.seedFromSystemEntropy();this.prng=new o(e)}}class o{constructor(t){if(32!==t.length)throw new Error("ChaCha20 seed must be exactly 32 bytes");this.state=new Uint32Array(16),this.initializeState(t)}initializeState(t){this.state[0]=1634760805,this.state[1]=857760878,this.state[2]=2036477234,this.state[3]=1797285236;for(let e=0;e<8;e++)this.state[4+e]=t[4*e]|t[4*e+1]<<8|t[4*e+2]<<16|t[4*e+3]<<24;this.state[12]=0,this.state[13]=0,this.state[14]=0,this.state[15]=0}next(){this.state[12]++,0===this.state[12]&&this.state[13]++;const t=new Uint32Array(this.state);for(let e=0;e<10;e++)this.quarterRound(t,0,4,8,12),this.quarterRound(t,1,5,9,13),this.quarterRound(t,2,6,10,14),this.quarterRound(t,3,7,11,15),this.quarterRound(t,0,5,10,15),this.quarterRound(t,1,6,11,12),this.quarterRound(t,2,7,8,13),this.quarterRound(t,3,4,9,14);for(let e=0;e<16;e++)t[e]=t[e]+this.state[e]>>>0;return t[0]}quarterRound(t,e,r,n,i){t[e]=t[e]+t[r]>>>0,t[i]^=t[e],t[i]=this.rotateLeft(t[i],16),t[n]=t[n]+t[i]>>>0,t[r]^=t[n],t[r]=this.rotateLeft(t[r],12),t[e]=t[e]+t[r]>>>0,t[i]^=t[e],t[i]=this.rotateLeft(t[i],8),t[n]=t[n]+t[i]>>>0,t[r]^=t[n],t[r]=this.rotateLeft(t[r],7)}rotateLeft(t,e){return(t<<e|t>>>32-e)>>>0}}class s{constructor(){this.table=s.getTable()}static getTable(){if(this._table)return this._table;this._table=new Uint8Array(16);for(let t=0;t<16;t++){let e=t;for(let t=0;t<4;t++)1&e?e=e>>1^this.POLYNOMIAL:e>>=1;this._table[t]=15&e}return this._table}calculate(t){let e=15;for(let r=0;r<8;r++){const n=Number(t>>BigInt(56-8*r)&0xffn);e=this.table[15&(e^n)]^e>>4,e=this.table[15&(e^n>>4)]^e>>4}return 15&e}verify(t){const e=Number(0xfn&t);let r=15;const n=t>>4n;for(let t=0;t<8;t++){const e=Number(n>>BigInt(56-8*t)&0xffn);r=this.table[15&(r^e)]^r>>4,r=this.table[15&(r^e>>4)]^r>>4}return e===(15&r)}attach(t){const e=this.calculate(t);return t<<4n|BigInt(e)}}s.POLYNOMIAL=3,s._table=null;class c{constructor(t={}){this.createdAt=new Date,this.enableStats=t.enableStats??!0,this.counter=new n,this.nodeId=new i(t.nodeId).id,this.entropy=new a(t.customSeed),this.crc=new s}generate(){const t=this.counter.getNext(),e=this.nodeId,r=this.entropy.getNext(),n=BigInt(t)<<36n|BigInt(e)<<20n|BigInt(r),i=this.crc.attach(n);return this.enableStats&&(this.lastGenerated=new Date),i}generateWithMetadata(){const t=new Date;return{id:this.generate(),timestamp:t,nodeId:this.nodeId,counter:this.counter.getCurrent()-1n<0n?0:Number(this.counter.getCurrent()-1n)}}generateBatch(t){if(t<=0)throw new Error("Batch count must be positive");const e=new Array(t),r=this.entropy.getBatch(t);for(let n=0;n<t;n++){const t=this.counter.getNext(),i=this.nodeId,a=r[n],o=BigInt(t)<<36n|BigInt(i)<<20n|BigInt(a);e[n]=this.crc.attach(o)}return this.enableStats&&(this.lastGenerated=new Date),e}generateBatchWithMetrics(t){const e=new Date,r=this.generateBatch(t),n=new Date,i=n.getTime()-e.getTime();return{ids:r,startTime:e,endTime:n,duration:i,throughput:i>0?t/i*1e3:1/0}}verify(t){try{return this.crc.verify(t)}catch{return!1}}validate(t){try{if(!this.crc.verify(t))return{valid:!1,error:"Invalid CRC checksum"};const e=t>>4n,r=Number(0xfn&t),n=Number(e>>36n&0xffffffn),i=Number(e>>20n&0xffffn);return{valid:!0,components:{counter:n,nodeId:i,entropy:Number(0xfffffn&e),crc:r}}}catch(t){return{valid:!1,error:t instanceof Error?t.message:"Unknown validation error"}}}getStats(){return{generatedCount:this.counter.getCurrent(),nodeId:this.nodeId.toString(16).padStart(4,"0"),memoryUsage:this.getMemoryUsage(),createdAt:this.createdAt,lastGenerated:this.lastGenerated}}reset(){this.counter.reset(),this.entropy.reseed(),this.lastGenerated=void 0}getMemoryUsage(){return 512}static toString(t,e="hex"){switch(e){case"hex":return t.toString(16).padStart(16,"0");case"decimal":return t.toString(10);case"binary":return t.toString(2).padStart(64,"0");default:throw new Error(`Unsupported format: ${e}`)}}static fromString(t,e="hex"){try{switch(e){case"hex":return BigInt("0x"+t);case"decimal":return BigInt(t);case"binary":return BigInt("0b"+t);default:throw new Error(`Unsupported format: ${e}`)}}catch(r){throw new Error(`Invalid ${e} format: ${t}`)}}static getPlatformInfo(){return e.getInfo()}}t.CryptoEntropy=a,t.FastCRC4=s,t.GlobalCounter=n,t.PlatformDetector=e,t.StaticNodeID=i,t.VelocidGenerator=c,t.default=c,Object.defineProperty(t,"__esModule",{value:!0})});
//# sourceMappingURL=index.umd.js.map