@lazy-random/cross-crypto
Version:
1 lines • 2.55 kB
Source Map (JSON)
{"version":3,"file":"index.umd.production.min.cjs","sources":["../src/index.ts"],"sourcesContent":["/**\n * Created by user on 2018/11/25/025.\n */\n\nexport interface ICryptoLike\n{\n\trandomBytes(size: number, callback?: (err: Error | null, buf: Buffer) => void): Buffer;\n\n\tgetRandomValues?<T extends Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null>(array: T): T;\n}\n\nexport const crossCrypto = (() =>\n{\n\tlet crypto: ICryptoLike;\n\n\treturn (): ICryptoLike =>\n\t{\n\t\tif (typeof crypto === 'undefined')\n\t\t{\n\t\t\tlet _crypto: ICryptoLike;\n\t\t\ttry\n\t\t\t{\n\t\t\t\t_crypto = crypto = require('crypto')\n\t\t\t}\n\t\t\tcatch (e)\n\t\t\t{\n\t\t\t\t// @ts-ignore\n\t\t\t\t_crypto = global.crypto || global.msCrypto;\n\n\t\t\t\tif (_crypto?.getRandomValues)\n\t\t\t\t{\n\t\t\t\t\tcrypto = _crypto\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!crypto?.randomBytes)\n\t\t\t{\n\t\t\t\tcrypto.randomBytes = crypto.randomBytes || function randomBytes(size: number, cb?: (err: Error | null, buf: Buffer) => void)\n\t\t\t\t{\n\t\t\t\t\tif (size > 65536) throw new Error('requested too many random bytes');\n\t\t\t\t\tlet rawBytes = new Uint8Array(size);\n\n\t\t\t\t\tif (size > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\t_crypto.getRandomValues(rawBytes)\n\t\t\t\t\t}\n\n\t\t\t\t\t// XXX: phantomjs doesn't like a buffer being passed here\n\t\t\t\t\tlet bytes = Buffer.from(rawBytes.buffer);\n\n\t\t\t\t\tif (typeof cb === 'function')\n\t\t\t\t\t{\n\t\t\t\t\t\tcb(null, bytes)\n\t\t\t\t\t}\n\n\t\t\t\t\treturn bytes\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!crypto)\n\t\t{\n\t\t\tcrypto = null;\n\t\t\tthrow new Error(`not support crypto`)\n\t\t}\n\n\t\treturn crypto\n\t};\n})();\n\nexport function randomBytes(size: number, callback?: (err: Error | null, buf: Buffer) => void): Buffer\n{\n\treturn crossCrypto().randomBytes(size, callback)\n}\n\nexport default crossCrypto\n"],"names":["crossCrypto","crypto","_crypto3","_crypto","require","e","_crypto2","global","msCrypto","randomBytes","size","cb","Error","rawBytes","Uint8Array","getRandomValues","bytes","Buffer","from","buffer"],"mappings":";;;;EAEGA,MAAAA,IAAA;;;MAsBO,SACN,MAAAC,GAAA;QAAA,IAAAC;YAEOC;;cAMPF,IAAAG,QAED;AAEC,iBAEmBC;UAAA,IAAAC;UAGlBH,IAAAI,OAAAN,UAAAM,OAAAC,oBAECF,IAAAH,WAAAG,WAAAA;;QAWDJ,+BAAAA,OAAAO,gBACDR,EAAAQ,cAAAR,EAAAQ,eAAAA,SAAAA,YAAAC,GAAAC;yBAIS,MAAAC,IAAAA,MAAA;UAGV,IAAAC,IAAU,IAAAC,WAAMJ;UAGjBA,SAAaP,EAAAY,gBAAAF;UAOdG,IAAAA,IAAAC,OAAAC,KAAAL,EAAAM;iBAED,qBAAAR;;;;;;IAzEG;;;;;;"}