From 48dbde71d803dc4bdc20dc9d2af62bbfb640ca3e Mon Sep 17 00:00:00 2001 From: Aras Abbasi Date: Thu, 2 Nov 2023 14:31:50 +0100 Subject: [PATCH] lib: use primordials for navigator.userAgent MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR-URL: https://github.com/nodejs/node/pull/50467 Reviewed-By: Geoffrey Booth Reviewed-By: Vinícius Lourenço Claro Cardoso Reviewed-By: Yagiz Nizipli Reviewed-By: James M Snell Reviewed-By: Tobias Nießen Reviewed-By: Ethan Arrowood --- lib/internal/navigator.js | 61 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 lib/internal/navigator.js diff --git a/lib/internal/navigator.js b/lib/internal/navigator.js new file mode 100644 index 00000000000000..5b29a098fcd0d9 --- /dev/null +++ b/lib/internal/navigator.js @@ -0,0 +1,61 @@ +'use strict'; + +const { + ObjectDefineProperties, + StringPrototypeIndexOf, + StringPrototypeSlice, + Symbol, +} = primordials; + +const { + ERR_ILLEGAL_CONSTRUCTOR, +} = require('internal/errors').codes; + +const { + kEnumerableProperty, +} = require('internal/util'); + +const { + getAvailableParallelism, +} = internalBinding('os'); + +const kInitialize = Symbol('kInitialize'); +const nodeVersion = process.version; + +class Navigator { + // Private properties are used to avoid brand validations. + #availableParallelism; + #userAgent = `Node.js/${StringPrototypeSlice(nodeVersion, 1, StringPrototypeIndexOf(nodeVersion, '.'))}`; + + constructor() { + if (arguments[0] === kInitialize) { + return; + } + throw new ERR_ILLEGAL_CONSTRUCTOR(); + } + + /** + * @return {number} + */ + get hardwareConcurrency() { + this.#availableParallelism ??= getAvailableParallelism(); + return this.#availableParallelism; + } + + /** + * @return {string} + */ + get userAgent() { + return this.#userAgent; + } +} + +ObjectDefineProperties(Navigator.prototype, { + hardwareConcurrency: kEnumerableProperty, + userAgent: kEnumerableProperty, +}); + +module.exports = { + navigator: new Navigator(kInitialize), + Navigator, +};