-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshim.js
47 lines (41 loc) · 1.81 KB
/
shim.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const SEA = require('./root')
const api = {Buffer: require('./buffer')}
var o = {}, u;
// ideally we can move away from JSON entirely? unlikely due to compatibility issues... oh well.
JSON.parseAsync = JSON.parseAsync || function(t,cb,r){ var u; try{ cb(u, JSON.parse(t,r)) }catch(e){ cb(e) } }
JSON.stringifyAsync = JSON.stringifyAsync || function(v,cb,r,s){ var u; try{ cb(u, JSON.stringify(v,r,s)) }catch(e){ cb(e) } }
api.parse = function(t,r){ return new Promise(function(res, rej){
JSON.parseAsync(t,function(err, raw){ err? rej(err) : res(raw) },r);
})}
api.stringify = function(v,r,s){ return new Promise(function(res, rej){
JSON.stringifyAsync(v,function(err, raw){ err? rej(err) : res(raw) },r,s);
})}
if(SEA.window){
api.crypto = window.crypto || window.msCrypto
api.subtle = (api.crypto||o).subtle || (api.crypto||o).webkitSubtle;
api.TextEncoder = window.TextEncoder;
api.TextDecoder = window.TextDecoder;
api.random = (len) => api.Buffer.from(api.crypto.getRandomValues(new Uint8Array(api.Buffer.alloc(len))));
}
if(!api.TextDecoder)
{
const { TextEncoder, TextDecoder } = require((u+'' == typeof MODULE?'.':'')+'./lib/text-encoding', 1);
api.TextDecoder = TextDecoder;
api.TextEncoder = TextEncoder;
}
if(!api.crypto)
{
try
{
var crypto = require('crypto', 1);
Object.assign(api, {
crypto,
random: (len) => api.Buffer.from(crypto.randomBytes(len))
});
const { Crypto: WebCrypto } = require('@peculiar/webcrypto', 1);
api.ossl = api.subtle = new WebCrypto({directory: 'ossl'}).subtle // ECDH
}
catch(e){
console.log("Please `npm install @peculiar/webcrypto` or add it to your package.json !");
}}
module.exports = api