utils.js 983 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. 'use strict';
  2. /* global window */
  3. /**
  4. * Normalizes our expected stringified form of a function across versions of node
  5. * @param {Function} fn The function to stringify
  6. */
  7. function normalizedFunctionString(fn) {
  8. return fn.toString().replace('function(', 'function (');
  9. }
  10. function insecureRandomBytes(size) {
  11. const result = new Uint8Array(size);
  12. for (let i = 0; i < size; ++i) result[i] = Math.floor(Math.random() * 256);
  13. return result;
  14. }
  15. let randomBytes = insecureRandomBytes;
  16. if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
  17. randomBytes = size => window.crypto.getRandomValues(new Uint8Array(size));
  18. } else {
  19. try {
  20. randomBytes = require('crypto').randomBytes;
  21. } catch (e) {
  22. // keep the fallback
  23. }
  24. // NOTE: in transpiled cases the above require might return null/undefined
  25. if (randomBytes == null) {
  26. randomBytes = insecureRandomBytes;
  27. }
  28. }
  29. module.exports = {
  30. normalizedFunctionString,
  31. randomBytes
  32. };