implementation.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const semver = require('semver');
  3. const flags = require('./flags.json');
  4. const getDescriptors = require('object.getownpropertydescriptors');
  5. const replaceUnderscoresRegex = /_/g;
  6. const leadingDashesRegex = /^--?/;
  7. const trailingValuesRegex = /=.*$/;
  8. const replace = Function.call.bind(String.prototype.replace);
  9. const has = Function.call.bind(Set.prototype.has);
  10. const test = Function.call.bind(RegExp.prototype.test);
  11. const [allowedNodeEnvironmentFlags, detectedSemverRange] = Object.keys(
  12. flags
  13. ).reduce(
  14. (acc, range) =>
  15. acc ||
  16. (semver.satisfies(process.version, range) ? [flags[range], range] : acc),
  17. null
  18. );
  19. const trimLeadingDashes = flag => replace(flag, leadingDashesRegex, '');
  20. class NodeEnvironmentFlagsSet extends Set {
  21. constructor(...args) {
  22. super(...args);
  23. this.add = () => this;
  24. }
  25. delete() {
  26. return false;
  27. }
  28. clear() {}
  29. has(key) {
  30. if (typeof key === 'string') {
  31. key = replace(key, replaceUnderscoresRegex, '-');
  32. if (test(leadingDashesRegex, key)) {
  33. key = replace(key, trailingValuesRegex, '');
  34. return has(this, key);
  35. }
  36. return has(nodeFlags, key);
  37. }
  38. return false;
  39. }
  40. }
  41. const nodeFlags = Object.defineProperties(
  42. new Set(allowedNodeEnvironmentFlags.map(trimLeadingDashes)),
  43. getDescriptors(Set.prototype)
  44. );
  45. Object.freeze(NodeEnvironmentFlagsSet.prototype.constructor);
  46. Object.freeze(NodeEnvironmentFlagsSet.prototype);
  47. exports.allowedNodeEnvironmentFlags = Object.freeze(
  48. new NodeEnvironmentFlagsSet(allowedNodeEnvironmentFlags)
  49. );
  50. exports.detectedSemverRange = detectedSemverRange;