diff --git a/dist/LICENSE.txt b/dist/LICENSE.txt
index 9a52c742..00ad9230 100644
--- a/dist/LICENSE.txt
+++ b/dist/LICENSE.txt
@@ -1802,7 +1802,7 @@ systeminformation
MIT
The MIT License (MIT)
-Copyright (c) 2014-2024 Sebastian Hildebrandt
+Copyright (c) 2014-2025 Sebastian Hildebrandt
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
diff --git a/dist/index.js b/dist/index.js
index f1388ada..974b36b9 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -86814,53953 +86814,54026 @@ module.exports = toNumber
/***/ }),
-/***/ 47411:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// audio.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 16. audio
-// ----------------------------------------------------------------------------------
-
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-function parseAudioType(str, input, output) {
- str = str.toLowerCase();
- let result = '';
+/***/ 94176:
+/***/ ((module) => {
- if (str.indexOf('input') >= 0) { result = 'Microphone'; }
- if (str.indexOf('display audio') >= 0) { result = 'Speaker'; }
- if (str.indexOf('speak') >= 0) { result = 'Speaker'; }
- if (str.indexOf('laut') >= 0) { result = 'Speaker'; }
- if (str.indexOf('loud') >= 0) { result = 'Speaker'; }
- if (str.indexOf('head') >= 0) { result = 'Headset'; }
- if (str.indexOf('mic') >= 0) { result = 'Microphone'; }
- if (str.indexOf('mikr') >= 0) { result = 'Microphone'; }
- if (str.indexOf('phone') >= 0) { result = 'Phone'; }
- if (str.indexOf('controll') >= 0) { result = 'Controller'; }
- if (str.indexOf('line o') >= 0) { result = 'Line Out'; }
- if (str.indexOf('digital o') >= 0) { result = 'Digital Out'; }
- if (str.indexOf('smart sound technology') >= 0) { result = 'Digital Signal Processor'; }
- if (str.indexOf('high definition audio') >= 0) { result = 'Sound Driver'; }
+/******************************************************************************
+Copyright (c) Microsoft Corporation.
- if (!result && output) {
- result = 'Speaker';
- } else if (!result && input) {
- result = 'Microphone';
- }
- return result;
-}
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */
+var __extends;
+var __assign;
+var __rest;
+var __decorate;
+var __param;
+var __esDecorate;
+var __runInitializers;
+var __propKey;
+var __setFunctionName;
+var __metadata;
+var __awaiter;
+var __generator;
+var __exportStar;
+var __values;
+var __read;
+var __spread;
+var __spreadArrays;
+var __spreadArray;
+var __await;
+var __asyncGenerator;
+var __asyncDelegator;
+var __asyncValues;
+var __makeTemplateObject;
+var __importStar;
+var __importDefault;
+var __classPrivateFieldGet;
+var __classPrivateFieldSet;
+var __classPrivateFieldIn;
+var __createBinding;
+var __addDisposableResource;
+var __disposeResources;
+var __rewriteRelativeImportExtension;
+(function (factory) {
+ var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
+ if (typeof define === "function" && define.amd) {
+ define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
+ }
+ else if ( true && typeof module.exports === "object") {
+ factory(createExporter(root, createExporter(module.exports)));
+ }
+ else {
+ factory(createExporter(root));
+ }
+ function createExporter(exports, previous) {
+ if (exports !== root) {
+ if (typeof Object.create === "function") {
+ Object.defineProperty(exports, "__esModule", { value: true });
+ }
+ else {
+ exports.__esModule = true;
+ }
+ }
+ return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
+ }
+})
+(function (exporter) {
+ var extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
-function getLinuxAudioPci() {
- let cmd = 'lspci -v 2>/dev/null';
- let result = [];
- try {
- const parts = execSync(cmd, util.execOptsLinux).toString().split('\n\n');
- parts.forEach(element => {
- const lines = element.split('\n');
- if (lines && lines.length && lines[0].toLowerCase().indexOf('audio') >= 0) {
- const audio = {};
- audio.slotId = lines[0].split(' ')[0];
- audio.driver = util.getValue(lines, 'Kernel driver in use', ':', true) || util.getValue(lines, 'Kernel modules', ':', true);
- result.push(audio);
- }
- });
- return result;
- } catch (e) {
- return result;
- }
-}
+ __extends = function (d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
-function parseLinuxAudioPciMM(lines, audioPCI) {
- const result = {};
- const slotId = util.getValue(lines, 'Slot');
+ __assign = Object.assign || function (t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ };
- const pciMatch = audioPCI.filter(function (item) { return item.slotId === slotId; });
+ __rest = function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+ };
- result.id = slotId;
- result.name = util.getValue(lines, 'SDevice');
- result.manufacturer = util.getValue(lines, 'SVendor');
- result.revision = util.getValue(lines, 'Rev');
- result.driver = pciMatch && pciMatch.length === 1 && pciMatch[0].driver ? pciMatch[0].driver : '';
- result.default = null;
- result.channel = 'PCIe';
- result.type = parseAudioType(result.name, null, null);
- result.in = null;
- result.out = null;
- result.status = 'online';
+ __decorate = function (decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+ };
- return result;
-}
+ __param = function (paramIndex, decorator) {
+ return function (target, key) { decorator(target, key, paramIndex); }
+ };
-function parseDarwinChannel(str) {
- let result = '';
+ __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
+ var _, done = false;
+ for (var i = decorators.length - 1; i >= 0; i--) {
+ var context = {};
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
+ if (kind === "accessor") {
+ if (result === void 0) continue;
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
+ if (_ = accept(result.get)) descriptor.get = _;
+ if (_ = accept(result.set)) descriptor.set = _;
+ if (_ = accept(result.init)) initializers.unshift(_);
+ }
+ else if (_ = accept(result)) {
+ if (kind === "field") initializers.unshift(_);
+ else descriptor[key] = _;
+ }
+ }
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
+ done = true;
+ };
- if (str.indexOf('builtin') >= 0) { result = 'Built-In'; }
- if (str.indexOf('extern') >= 0) { result = 'Audio-Jack'; }
- if (str.indexOf('hdmi') >= 0) { result = 'HDMI'; }
- if (str.indexOf('displayport') >= 0) { result = 'Display-Port'; }
- if (str.indexOf('usb') >= 0) { result = 'USB'; }
- if (str.indexOf('pci') >= 0) { result = 'PCIe'; }
+ __runInitializers = function (thisArg, initializers, value) {
+ var useValue = arguments.length > 2;
+ for (var i = 0; i < initializers.length; i++) {
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
+ }
+ return useValue ? value : void 0;
+ };
- return result;
-}
+ __propKey = function (x) {
+ return typeof x === "symbol" ? x : "".concat(x);
+ };
-function parseDarwinAudio(audioObject, id) {
- const result = {};
- const channelStr = ((audioObject.coreaudio_device_transport || '') + ' ' + (audioObject._name || '')).toLowerCase();
+ __setFunctionName = function (f, name, prefix) {
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
+ };
- result.id = id;
- result.name = audioObject._name;
- result.manufacturer = audioObject.coreaudio_device_manufacturer;
- result.revision = null;
- result.driver = null;
- result.default = !!(audioObject.coreaudio_default_audio_input_device || '') || !!(audioObject.coreaudio_default_audio_output_device || '');
- result.channel = parseDarwinChannel(channelStr);
- result.type = parseAudioType(result.name, !!(audioObject.coreaudio_device_input || ''), !!(audioObject.coreaudio_device_output || ''));
- result.in = !!(audioObject.coreaudio_device_input || '');
- result.out = !!(audioObject.coreaudio_device_output || '');
- result.status = 'online';
+ __metadata = function (metadataKey, metadataValue) {
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
+ };
- return result;
-}
+ __awaiter = function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ };
-function parseWindowsAudio(lines) {
- const result = {};
- const status = util.getValue(lines, 'StatusInfo', ':');
+ __generator = function (thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+ };
- result.id = util.getValue(lines, 'DeviceID', ':'); // PNPDeviceID??
- result.name = util.getValue(lines, 'name', ':');
- result.manufacturer = util.getValue(lines, 'manufacturer', ':');
- result.revision = null;
- result.driver = null;
- result.default = null;
- result.channel = null;
- result.type = parseAudioType(result.name, null, null);
- result.in = null;
- result.out = null;
- result.status = status;
+ __exportStar = function(m, o) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
+ };
- return result;
-}
+ __createBinding = Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+ }) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+ });
-function audio(callback) {
+ __values = function (o) {
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+ if (m) return m.call(o);
+ if (o && typeof o.length === "number") return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+ };
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux || _freebsd || _openbsd || _netbsd) {
- let cmd = 'lspci -vmm 2>/dev/null';
- exec(cmd, function (error, stdout) {
- // PCI
- if (!error) {
- const audioPCI = getLinuxAudioPci();
- const parts = stdout.toString().split('\n\n');
- parts.forEach(element => {
- const lines = element.split('\n');
- if (util.getValue(lines, 'class', ':', true).toLowerCase().indexOf('audio') >= 0) {
- const audio = parseLinuxAudioPciMM(lines, audioPCI);
- result.push(audio);
- }
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_darwin) {
- let cmd = 'system_profiler SPAudioDataType -json';
- exec(cmd, function (error, stdout) {
- if (!error) {
+ __read = function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
try {
- const outObj = JSON.parse(stdout.toString());
- if (outObj.SPAudioDataType && outObj.SPAudioDataType.length && outObj.SPAudioDataType[0] && outObj.SPAudioDataType[0]['_items'] && outObj.SPAudioDataType[0]['_items'].length) {
- for (let i = 0; i < outObj.SPAudioDataType[0]['_items'].length; i++) {
- const audio = parseDarwinAudio(outObj.SPAudioDataType[0]['_items'][i], i);
- result.push(audio);
- }
- }
- } catch (e) {
- util.noop();
+ if (r && !r.done && (m = i["return"])) m.call(i);
}
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_windows) {
- util.powerShell('Get-CimInstance Win32_SoundDevice | select DeviceID,StatusInfo,Name,Manufacturer | fl').then((stdout, error) => {
- if (!error) {
- const parts = stdout.toString().split(/\n\s*\n/);
- parts.forEach(element => {
- const lines = element.split('\n');
- if (util.getValue(lines, 'name', ':')) {
- result.push(parseWindowsAudio(lines));
- }
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_sunos) {
- resolve(null);
- }
- });
- });
-}
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+ };
-exports.audio = audio;
+ /** @deprecated */
+ __spread = function () {
+ for (var ar = [], i = 0; i < arguments.length; i++)
+ ar = ar.concat(__read(arguments[i]));
+ return ar;
+ };
+ /** @deprecated */
+ __spreadArrays = function () {
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+ r[k] = a[j];
+ return r;
+ };
-/***/ }),
+ __spreadArray = function (to, from, pack) {
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
+ if (ar || !(i in from)) {
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
+ ar[i] = from[i];
+ }
+ }
+ return to.concat(ar || Array.prototype.slice.call(from));
+ };
-/***/ 35552:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ __await = function (v) {
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
+ };
+ __asyncGenerator = function (thisArg, _arguments, generator) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
+ function fulfill(value) { resume("next", value); }
+ function reject(value) { resume("throw", value); }
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
+ };
-// @ts-check;
-// ==================================================================================
-// battery.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 6. Battery
-// ----------------------------------------------------------------------------------
+ __asyncDelegator = function (o) {
+ var i, p;
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
+ };
-const exec = (__nccwpck_require__(35317).exec);
-const fs = __nccwpck_require__(79896);
-const util = __nccwpck_require__(33225);
+ __asyncValues = function (o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+ };
-let _platform = process.platform;
+ __makeTemplateObject = function (cooked, raw) {
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
+ return cooked;
+ };
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
+ var __setModuleDefault = Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+ }) : function(o, v) {
+ o["default"] = v;
+ };
-function parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity) {
- const result = {};
- let status = util.getValue(lines, 'BatteryStatus', ':').trim();
- // 1 = "Discharging"
- // 2 = "On A/C"
- // 3 = "Fully Charged"
- // 4 = "Low"
- // 5 = "Critical"
- // 6 = "Charging"
- // 7 = "Charging High"
- // 8 = "Charging Low"
- // 9 = "Charging Critical"
- // 10 = "Undefined"
- // 11 = "Partially Charged"
- if (status >= 0) {
- const statusValue = status ? parseInt(status) : 0;
- result.status = statusValue;
- result.hasBattery = true;
- result.maxCapacity = fullChargeCapacity || parseInt(util.getValue(lines, 'DesignCapacity', ':') || 0);
- result.designedCapacity = parseInt(util.getValue(lines, 'DesignCapacity', ':') || designedCapacity);
- result.voltage = parseInt(util.getValue(lines, 'DesignVoltage', ':') || 0) / 1000.0;
- result.capacityUnit = 'mWh';
- result.percent = parseInt(util.getValue(lines, 'EstimatedChargeRemaining', ':') || 0);
- result.currentCapacity = parseInt(result.maxCapacity * result.percent / 100);
- result.isCharging = (statusValue >= 6 && statusValue <= 9) || statusValue === 11 || ((statusValue !== 3) && (statusValue !== 1) && result.percent < 100);
- result.acConnected = result.isCharging || statusValue === 2;
- result.model = util.getValue(lines, 'DeviceID', ':');
- } else {
- result.status = -1;
- }
+ var ownKeys = function(o) {
+ ownKeys = Object.getOwnPropertyNames || function (o) {
+ var ar = [];
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+ return ar;
+ };
+ return ownKeys(o);
+ };
- return result;
-}
+ __importStar = function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+ __setModuleDefault(result, mod);
+ return result;
+ };
-module.exports = function (callback) {
+ __importDefault = function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+ };
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
- hasBattery: false,
- cycleCount: 0,
- isCharging: false,
- designedCapacity: 0,
- maxCapacity: 0,
- currentCapacity: 0,
- voltage: 0,
- capacityUnit: '',
- percent: 0,
- timeRemaining: null,
- acConnected: true,
- type: '',
- model: '',
- manufacturer: '',
- serial: ''
- };
+ __classPrivateFieldGet = function (receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+ };
- if (_linux) {
- let battery_path = '';
- if (fs.existsSync('/sys/class/power_supply/BAT1/uevent')) {
- battery_path = '/sys/class/power_supply/BAT1/';
- } else if (fs.existsSync('/sys/class/power_supply/BAT0/uevent')) {
- battery_path = '/sys/class/power_supply/BAT0/';
- }
+ __classPrivateFieldSet = function (receiver, state, value, kind, f) {
+ if (kind === "m") throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+ };
- let acConnected = false;
- let acPath = '';
- if (fs.existsSync('/sys/class/power_supply/AC/online')) {
- acPath = '/sys/class/power_supply/AC/online';
- } else if (fs.existsSync('/sys/class/power_supply/AC0/online')) {
- acPath = '/sys/class/power_supply/AC0/online';
- }
+ __classPrivateFieldIn = function (state, receiver) {
+ if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
+ return typeof state === "function" ? receiver === state : state.has(receiver);
+ };
- if (acPath) {
- const file = fs.readFileSync(acPath);
- acConnected = file.toString().trim() === '1';
+ __addDisposableResource = function (env, value, async) {
+ if (value !== null && value !== void 0) {
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
+ var dispose, inner;
+ if (async) {
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
+ dispose = value[Symbol.asyncDispose];
+ }
+ if (dispose === void 0) {
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
+ dispose = value[Symbol.dispose];
+ if (async) inner = dispose;
+ }
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
+ env.stack.push({ value: value, dispose: dispose, async: async });
}
+ else if (async) {
+ env.stack.push({ async: true });
+ }
+ return value;
+ };
- if (battery_path) {
- fs.readFile(battery_path + 'uevent', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
-
- result.isCharging = (util.getValue(lines, 'POWER_SUPPLY_STATUS', '=').toLowerCase() === 'charging');
- result.acConnected = acConnected || result.isCharging;
- result.voltage = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_VOLTAGE_NOW', '='), 10) / 1000000.0;
- result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
- result.cycleCount = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CYCLE_COUNT', '='), 10);
- result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL', '=', true, true), 10) / 1000.0 * (result.voltage || 1));
- const desingedMinVoltage = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_VOLTAGE_MIN_DESIGN', '='), 10) / 1000000.0;
- result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL_DESIGN', '=', true, true), 10) / 1000.0 * (desingedMinVoltage || result.voltage || 1));
- result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10) / 1000.0 * (result.voltage || 1));
- if (!result.maxCapacity) {
- result.maxCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL', '=', true, true), 10) / 1000.0;
- result.designedCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL_DESIGN', '=', true, true), 10) / 1000.0 | result.maxCapacity;
- result.currentCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10) / 1000.0;
- }
- const percent = util.getValue(lines, 'POWER_SUPPLY_CAPACITY', '=');
- const energy = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10);
- const power = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_POWER_NOW', '='), 10);
- const current = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CURRENT_NOW', '='), 10);
- const charge = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10);
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
+ var e = new Error(message);
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
+ };
- result.percent = parseInt('0' + percent, 10);
- if (result.maxCapacity && result.currentCapacity) {
- result.hasBattery = true;
- if (!percent) {
- result.percent = 100.0 * result.currentCapacity / result.maxCapacity;
- }
- }
- if (result.isCharging) {
- result.hasBattery = true;
- }
- if (energy && power) {
- result.timeRemaining = Math.floor(energy / power * 60);
- } else if (current && charge) {
- result.timeRemaining = Math.floor(charge / current * 60);
- } else if (current && result.currentCapacity) {
- result.timeRemaining = Math.floor(result.currentCapacity / current * 60);
- }
- result.type = util.getValue(lines, 'POWER_SUPPLY_TECHNOLOGY', '=');
- result.model = util.getValue(lines, 'POWER_SUPPLY_MODEL_NAME', '=');
- result.manufacturer = util.getValue(lines, 'POWER_SUPPLY_MANUFACTURER', '=');
- result.serial = util.getValue(lines, 'POWER_SUPPLY_SERIAL_NUMBER', '=');
- if (callback) { callback(result); }
- resolve(result);
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
+ __disposeResources = function (env) {
+ function fail(e) {
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
+ env.hasError = true;
}
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('sysctl -i hw.acpi.battery hw.acpi.acline', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- const batteries = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.units'), 10);
- const percent = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.life'), 10);
- result.hasBattery = (batteries > 0);
- result.cycleCount = null;
- result.isCharging = util.getValue(lines, 'hw.acpi.acline') !== '1';
- result.acConnected = result.isCharging;
- result.maxCapacity = null;
- result.currentCapacity = null;
- result.capacityUnit = 'unknown';
- result.percent = batteries ? percent : null;
- if (callback) { callback(result); }
- resolve(result);
- });
- }
-
- if (_darwin) {
- exec('ioreg -n AppleSmartBattery -r | egrep "CycleCount|IsCharging|DesignCapacity|MaxCapacity|CurrentCapacity|BatterySerialNumber|TimeRemaining|Voltage"; pmset -g batt | grep %', function (error, stdout) {
- if (stdout) {
- let lines = stdout.toString().replace(/ +/g, '').replace(/"+/g, '').replace(/-/g, '').split('\n');
- result.cycleCount = parseInt('0' + util.getValue(lines, 'cyclecount', '='), 10);
- result.voltage = parseInt('0' + util.getValue(lines, 'voltage', '='), 10) / 1000.0;
- result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
- result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'applerawmaxcapacity', '='), 10) * (result.voltage || 1));
- result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'applerawcurrentcapacity', '='), 10) * (result.voltage || 1));
- result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'DesignCapacity', '='), 10) * (result.voltage || 1));
- result.manufacturer = 'Apple';
- result.serial = util.getValue(lines, 'BatterySerialNumber', '=');
- let percent = null;
- const line = util.getValue(lines, 'internal', 'Battery');
- let parts = line.split(';');
- if (parts && parts[0]) {
- let parts2 = parts[0].split('\t');
- if (parts2 && parts2[1]) {
- percent = parseFloat(parts2[1].trim().replace(/%/g, ''));
- }
- }
- if (parts && parts[1]) {
- result.isCharging = (parts[1].trim() === 'charging');
- result.acConnected = (parts[1].trim() !== 'discharging');
- } else {
- result.isCharging = util.getValue(lines, 'ischarging', '=').toLowerCase() === 'yes';
- result.acConnected = result.isCharging;
- }
- if (result.maxCapacity && result.currentCapacity) {
- result.hasBattery = true;
- result.type = 'Li-ion';
- result.percent = percent !== null ? percent : Math.round(100.0 * result.currentCapacity / result.maxCapacity);
- if (!result.isCharging) {
- result.timeRemaining = parseInt('0' + util.getValue(lines, 'TimeRemaining', '='), 10);
- }
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance Win32_Battery | select BatteryStatus, DesignCapacity, DesignVoltage, EstimatedChargeRemaining, DeviceID | fl'));
- workload.push(util.powerShell('(Get-WmiObject -Class BatteryStaticData -Namespace ROOT/WMI).DesignedCapacity'));
- workload.push(util.powerShell('(Get-CimInstance -Class BatteryFullChargedCapacity -Namespace ROOT/WMI).FullChargedCapacity'));
- util.promiseAll(
- workload
- ).then((data) => {
- if (data) {
- let parts = data.results[0].split(/\n\s*\n/);
- let batteries = [];
- const hasValue = value => /\S/.test(value);
- for (let i = 0; i < parts.length; i++) {
- if (hasValue(parts[i]) && (!batteries.length || !hasValue(parts[i - 1]))) {
- batteries.push([]);
- }
- if (hasValue(parts[i])) {
- batteries[batteries.length - 1].push(parts[i]);
- }
- }
- let designCapacities = data.results[1].split('\r\n').filter(e => e);
- let fullChargeCapacities = data.results[2].split('\r\n').filter(e => e);
- if (batteries.length) {
- let first = false;
- let additionalBatteries = [];
- for (let i = 0; i < batteries.length; i++) {
- let lines = batteries[i][0].split('\r\n');
- const designedCapacity = designCapacities && designCapacities.length >= (i + 1) && designCapacities[i] ? util.toInt(designCapacities[i]) : 0;
- const fullChargeCapacity = fullChargeCapacities && fullChargeCapacities.length >= (i + 1) && fullChargeCapacities[i] ? util.toInt(fullChargeCapacities[i]) : 0;
- const parsed = parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity);
- if (!first && parsed.status > 0 && parsed.status !== 10) {
- result.hasBattery = parsed.hasBattery;
- result.maxCapacity = parsed.maxCapacity;
- result.designedCapacity = parsed.designedCapacity;
- result.voltage = parsed.voltage;
- result.capacityUnit = parsed.capacityUnit;
- result.percent = parsed.percent;
- result.currentCapacity = parsed.currentCapacity;
- result.isCharging = parsed.isCharging;
- result.acConnected = parsed.acConnected;
- result.model = parsed.model;
- first = true;
- } else if (parsed.status !== -1) {
- additionalBatteries.push(
- {
- hasBattery: parsed.hasBattery,
- maxCapacity: parsed.maxCapacity,
- designedCapacity: parsed.designedCapacity,
- voltage: parsed.voltage,
- capacityUnit: parsed.capacityUnit,
- percent: parsed.percent,
- currentCapacity: parsed.currentCapacity,
- isCharging: parsed.isCharging,
- timeRemaining: null,
- acConnected: parsed.acConnected,
- model: parsed.model,
- type: '',
- manufacturer: '',
- serial: ''
- }
- );
- }
- }
- if (!first && additionalBatteries.length) {
- result = additionalBatteries[0];
- additionalBatteries.shift();
+ var r, s = 0;
+ function next() {
+ while (r = env.stack.pop()) {
+ try {
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
+ if (r.dispose) {
+ var result = r.dispose.call(r.value);
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
+ }
+ else s |= 1;
}
- if (additionalBatteries.length) {
- result.additionalBatteries = additionalBatteries;
+ catch (e) {
+ fail(e);
}
- }
}
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
+ if (env.hasError) throw env.error;
}
- }
- });
- });
-};
+ return next();
+ };
+ __rewriteRelativeImportExtension = function (path, preserveJsx) {
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
+ });
+ }
+ return path;
+ };
-/***/ }),
+ exporter("__extends", __extends);
+ exporter("__assign", __assign);
+ exporter("__rest", __rest);
+ exporter("__decorate", __decorate);
+ exporter("__param", __param);
+ exporter("__esDecorate", __esDecorate);
+ exporter("__runInitializers", __runInitializers);
+ exporter("__propKey", __propKey);
+ exporter("__setFunctionName", __setFunctionName);
+ exporter("__metadata", __metadata);
+ exporter("__awaiter", __awaiter);
+ exporter("__generator", __generator);
+ exporter("__exportStar", __exportStar);
+ exporter("__createBinding", __createBinding);
+ exporter("__values", __values);
+ exporter("__read", __read);
+ exporter("__spread", __spread);
+ exporter("__spreadArrays", __spreadArrays);
+ exporter("__spreadArray", __spreadArray);
+ exporter("__await", __await);
+ exporter("__asyncGenerator", __asyncGenerator);
+ exporter("__asyncDelegator", __asyncDelegator);
+ exporter("__asyncValues", __asyncValues);
+ exporter("__makeTemplateObject", __makeTemplateObject);
+ exporter("__importStar", __importStar);
+ exporter("__importDefault", __importDefault);
+ exporter("__classPrivateFieldGet", __classPrivateFieldGet);
+ exporter("__classPrivateFieldSet", __classPrivateFieldSet);
+ exporter("__classPrivateFieldIn", __classPrivateFieldIn);
+ exporter("__addDisposableResource", __addDisposableResource);
+ exporter("__disposeResources", __disposeResources);
+ exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
+});
-/***/ 45595:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+0 && (0);
-// @ts-check
-// ==================================================================================
-// audio.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 17. bluetooth
-// ----------------------------------------------------------------------------------
+/***/ }),
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const path = __nccwpck_require__(16928);
-const util = __nccwpck_require__(33225);
-const bluetoothVendors = __nccwpck_require__(55848);
-const fs = __nccwpck_require__(79896);
+/***/ 5070:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-let _platform = process.platform;
+module.exports = __nccwpck_require__(35862);
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-function parseBluetoothType(str) {
- let result = '';
+/***/ }),
- if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
- if (str.indexOf('mouse') >= 0) { result = 'Mouse'; }
- if (str.indexOf('trackpad') >= 0) { result = 'Trackpad'; }
- if (str.indexOf('speaker') >= 0) { result = 'Speaker'; }
- if (str.indexOf('headset') >= 0) { result = 'Headset'; }
- if (str.indexOf('phone') >= 0) { result = 'Phone'; }
- if (str.indexOf('macbook') >= 0) { result = 'Computer'; }
- if (str.indexOf('imac') >= 0) { result = 'Computer'; }
- if (str.indexOf('ipad') >= 0) { result = 'Tablet'; }
- if (str.indexOf('watch') >= 0) { result = 'Watch'; }
- if (str.indexOf('headphone') >= 0) { result = 'Headset'; }
- // to be continued ...
+/***/ 35862:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return result;
-}
-function parseBluetoothManufacturer(str) {
- let result = str.split(' ')[0];
- str = str.toLowerCase();
- if (str.indexOf('apple') >= 0) { result = 'Apple'; }
- if (str.indexOf('ipad') >= 0) { result = 'Apple'; }
- if (str.indexOf('imac') >= 0) { result = 'Apple'; }
- if (str.indexOf('iphone') >= 0) { result = 'Apple'; }
- if (str.indexOf('magic mouse') >= 0) { result = 'Apple'; }
- if (str.indexOf('magic track') >= 0) { result = 'Apple'; }
- if (str.indexOf('macbook') >= 0) { result = 'Apple'; }
- // to be continued ...
- return result;
-}
+var net = __nccwpck_require__(69278);
+var tls = __nccwpck_require__(64756);
+var http = __nccwpck_require__(58611);
+var https = __nccwpck_require__(65692);
+var events = __nccwpck_require__(24434);
+var assert = __nccwpck_require__(42613);
+var util = __nccwpck_require__(39023);
-function parseBluetoothVendor(str) {
- const id = parseInt(str);
- if (!isNaN(id)) return bluetoothVendors[id];
-}
-function parseLinuxBluetoothInfo(lines, macAddr1, macAddr2) {
- const result = {};
+exports.httpOverHttp = httpOverHttp;
+exports.httpsOverHttp = httpsOverHttp;
+exports.httpOverHttps = httpOverHttps;
+exports.httpsOverHttps = httpsOverHttps;
- result.device = null;
- result.name = util.getValue(lines, 'name', '=');
- result.manufacturer = null;
- result.macDevice = macAddr1;
- result.macHost = macAddr2;
- result.batteryPercent = null;
- result.type = parseBluetoothType(result.name.toLowerCase());
- result.connected = false;
- return result;
+function httpOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ return agent;
}
-function parseDarwinBluetoothDevices(bluetoothObject, macAddr2) {
- const result = {};
- const typeStr = ((bluetoothObject.device_minorClassOfDevice_string || bluetoothObject.device_majorClassOfDevice_string || bluetoothObject.device_minorType || '') + (bluetoothObject.device_name || '')).toLowerCase();
+function httpsOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
+}
- result.device = bluetoothObject.device_services || '';
- result.name = bluetoothObject.device_name || '';
- result.manufacturer = bluetoothObject.device_manufacturer || parseBluetoothVendor(bluetoothObject.device_vendorID) || parseBluetoothManufacturer(bluetoothObject.device_name || '') || '';
- result.macDevice = (bluetoothObject.device_addr || bluetoothObject.device_address || '').toLowerCase().replace(/-/g, ':');
- result.macHost = macAddr2;
- result.batteryPercent = bluetoothObject.device_batteryPercent || null;
- result.type = parseBluetoothType(typeStr);
- result.connected = bluetoothObject.device_isconnected === 'attrib_Yes' || false;
+function httpOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ return agent;
+}
- return result;
+function httpsOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
}
-function parseWindowsBluetooth(lines) {
- const result = {};
- result.device = null;
- result.name = util.getValue(lines, 'name', ':');
- result.manufacturer = util.getValue(lines, 'manufacturer', ':');
- result.macDevice = null;
- result.macHost = null;
- result.batteryPercent = null;
- result.type = parseBluetoothType(result.name.toLowerCase());
- result.connected = null;
+function TunnelingAgent(options) {
+ var self = this;
+ self.options = options || {};
+ self.proxyOptions = self.options.proxy || {};
+ self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
+ self.requests = [];
+ self.sockets = [];
- return result;
+ self.on('free', function onFree(socket, host, port, localAddress) {
+ var options = toOptions(host, port, localAddress);
+ for (var i = 0, len = self.requests.length; i < len; ++i) {
+ var pending = self.requests[i];
+ if (pending.host === options.host && pending.port === options.port) {
+ // Detect the request to connect same origin server,
+ // reuse the connection.
+ self.requests.splice(i, 1);
+ pending.request.onSocket(socket);
+ return;
+ }
+ }
+ socket.destroy();
+ self.removeSocket(socket);
+ });
}
+util.inherits(TunnelingAgent, events.EventEmitter);
-function bluetoothDevices(callback) {
+TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
+ var self = this;
+ var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux) {
- // get files in /var/lib/bluetooth/ recursive
- const btFiles = util.getFilesInPath('/var/lib/bluetooth/');
- btFiles.forEach((element) => {
- const filename = path.basename(element);
- const pathParts = element.split('/');
- const macAddr1 = pathParts.length >= 6 ? pathParts[pathParts.length - 2] : null;
- const macAddr2 = pathParts.length >= 7 ? pathParts[pathParts.length - 3] : null;
- if (filename === 'info') {
- const infoFile = fs.readFileSync(element, { encoding: 'utf8' }).split('\n');
- result.push(parseLinuxBluetoothInfo(infoFile, macAddr1, macAddr2));
- }
- });
- // determine "connected" with hcitool con
- try {
- const hdicon = execSync('hcitool con', util.execOptsLinux).toString().toLowerCase();
- for (let i = 0; i < result.length; i++) {
- if (result[i].macDevice && result[i].macDevice.length > 10 && hdicon.indexOf(result[i].macDevice.toLowerCase()) >= 0) {
- result[i].connected = true;
- }
- }
- } catch (e) {
- util.noop();
- }
+ if (self.sockets.length >= this.maxSockets) {
+ // We are over limit so we'll add it to the queue.
+ self.requests.push(options);
+ return;
+ }
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- if (_darwin) {
- let cmd = 'system_profiler SPBluetoothDataType -json';
- exec(cmd, function (error, stdout) {
- if (!error) {
- try {
- const outObj = JSON.parse(stdout.toString());
- if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_title'] && outObj.SPBluetoothDataType[0]['device_title'].length) {
- // missing: host BT Adapter macAddr ()
- let macAddr2 = null;
- if (outObj.SPBluetoothDataType[0]['local_device_title'] && outObj.SPBluetoothDataType[0].local_device_title.general_address) {
- macAddr2 = outObj.SPBluetoothDataType[0].local_device_title.general_address.toLowerCase().replace(/-/g, ':');
- }
- outObj.SPBluetoothDataType[0]['device_title'].forEach((element) => {
- const obj = element;
- const objKey = Object.keys(obj);
- if (objKey && objKey.length === 1) {
- const innerObject = obj[objKey[0]];
- innerObject.device_name = objKey[0];
- const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
- result.push(bluetoothDevice);
- }
- });
- }
- if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_connected'] && outObj.SPBluetoothDataType[0]['device_connected'].length) {
- const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null;
- outObj.SPBluetoothDataType[0]['device_connected'].forEach((element) => {
- const obj = element;
- const objKey = Object.keys(obj);
- if (objKey && objKey.length === 1) {
- const innerObject = obj[objKey[0]];
- innerObject.device_name = objKey[0];
- innerObject.device_isconnected = 'attrib_Yes';
- const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
- result.push(bluetoothDevice);
- }
- });
- }
- if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_not_connected'] && outObj.SPBluetoothDataType[0]['device_not_connected'].length) {
- const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null;
- outObj.SPBluetoothDataType[0]['device_not_connected'].forEach((element) => {
- const obj = element;
- const objKey = Object.keys(obj);
- if (objKey && objKey.length === 1) {
- const innerObject = obj[objKey[0]];
- innerObject.device_name = objKey[0];
- innerObject.device_isconnected = 'attrib_No';
- const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
- result.push(bluetoothDevice);
- }
- });
- }
- } catch (e) {
- util.noop();
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_windows) {
- util.powerShell('Get-CimInstance Win32_PNPEntity | select PNPClass, Name, Manufacturer | fl').then((stdout, error) => {
- if (!error) {
- const parts = stdout.toString().split(/\n\s*\n/);
- parts.forEach((part) => {
- if (util.getValue(part.split('\n'), 'PNPClass', ':') === 'Bluetooth') {
- result.push(parseWindowsBluetooth(part.split('\n')));
- }
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_freebsd || _netbsd || _openbsd || _sunos) {
- resolve(null);
- }
+ // If we are under maxSockets create a new one.
+ self.createSocket(options, function(socket) {
+ socket.on('free', onFree);
+ socket.on('close', onCloseOrRemove);
+ socket.on('agentRemove', onCloseOrRemove);
+ req.onSocket(socket);
+
+ function onFree() {
+ self.emit('free', socket, options);
+ }
+
+ function onCloseOrRemove(err) {
+ self.removeSocket(socket);
+ socket.removeListener('free', onFree);
+ socket.removeListener('close', onCloseOrRemove);
+ socket.removeListener('agentRemove', onCloseOrRemove);
+ }
+ });
+};
+
+TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
+ var self = this;
+ var placeholder = {};
+ self.sockets.push(placeholder);
+
+ var connectOptions = mergeOptions({}, self.proxyOptions, {
+ method: 'CONNECT',
+ path: options.host + ':' + options.port,
+ agent: false,
+ headers: {
+ host: options.host + ':' + options.port
+ }
+ });
+ if (options.localAddress) {
+ connectOptions.localAddress = options.localAddress;
+ }
+ if (connectOptions.proxyAuth) {
+ connectOptions.headers = connectOptions.headers || {};
+ connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
+ new Buffer(connectOptions.proxyAuth).toString('base64');
+ }
+
+ debug('making CONNECT request');
+ var connectReq = self.request(connectOptions);
+ connectReq.useChunkedEncodingByDefault = false; // for v0.6
+ connectReq.once('response', onResponse); // for v0.6
+ connectReq.once('upgrade', onUpgrade); // for v0.6
+ connectReq.once('connect', onConnect); // for v0.7 or later
+ connectReq.once('error', onError);
+ connectReq.end();
+
+ function onResponse(res) {
+ // Very hacky. This is necessary to avoid http-parser leaks.
+ res.upgrade = true;
+ }
+
+ function onUpgrade(res, socket, head) {
+ // Hacky.
+ process.nextTick(function() {
+ onConnect(res, socket, head);
+ });
+ }
+
+ function onConnect(res, socket, head) {
+ connectReq.removeAllListeners();
+ socket.removeAllListeners();
+
+ if (res.statusCode !== 200) {
+ debug('tunneling socket could not be established, statusCode=%d',
+ res.statusCode);
+ socket.destroy();
+ var error = new Error('tunneling socket could not be established, ' +
+ 'statusCode=' + res.statusCode);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ if (head.length > 0) {
+ debug('got illegal response body from proxy');
+ socket.destroy();
+ var error = new Error('got illegal response body from proxy');
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ debug('tunneling connection has established');
+ self.sockets[self.sockets.indexOf(placeholder)] = socket;
+ return cb(socket);
+ }
+
+ function onError(cause) {
+ connectReq.removeAllListeners();
+
+ debug('tunneling socket could not be established, cause=%s\n',
+ cause.message, cause.stack);
+ var error = new Error('tunneling socket could not be established, ' +
+ 'cause=' + cause.message);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ }
+};
+
+TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
+ var pos = this.sockets.indexOf(socket)
+ if (pos === -1) {
+ return;
+ }
+ this.sockets.splice(pos, 1);
+
+ var pending = this.requests.shift();
+ if (pending) {
+ // If we have pending requests and a socket gets closed a new one
+ // needs to be created to take over in the pool for the one that closed.
+ this.createSocket(pending, function(socket) {
+ pending.request.onSocket(socket);
+ });
+ }
+};
+
+function createSecureSocket(options, cb) {
+ var self = this;
+ TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
+ var hostHeader = options.request.getHeader('host');
+ var tlsOptions = mergeOptions({}, self.options, {
+ socket: socket,
+ servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
});
+
+ // 0 is dummy port for v0.6
+ var secureSocket = tls.connect(0, tlsOptions);
+ self.sockets[self.sockets.indexOf(socket)] = secureSocket;
+ cb(secureSocket);
});
}
-exports.bluetoothDevices = bluetoothDevices;
+
+function toOptions(host, port, localAddress) {
+ if (typeof host === 'string') { // since v0.10
+ return {
+ host: host,
+ port: port,
+ localAddress: localAddress
+ };
+ }
+ return host; // for v0.11 or later
+}
+
+function mergeOptions(target) {
+ for (var i = 1, len = arguments.length; i < len; ++i) {
+ var overrides = arguments[i];
+ if (typeof overrides === 'object') {
+ var keys = Object.keys(overrides);
+ for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
+ var k = keys[j];
+ if (overrides[k] !== undefined) {
+ target[k] = overrides[k];
+ }
+ }
+ }
+ }
+ return target;
+}
+
+
+var debug;
+if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
+ debug = function() {
+ var args = Array.prototype.slice.call(arguments);
+ if (typeof args[0] === 'string') {
+ args[0] = 'TUNNEL: ' + args[0];
+ } else {
+ args.unshift('TUNNEL:');
+ }
+ console.error.apply(console, args);
+ }
+} else {
+ debug = function() {};
+}
+exports.debug = debug; // for test
/***/ }),
-/***/ 55848:
-/***/ ((module) => {
+/***/ 99069:
+/***/ ((__unused_webpack_module, exports) => {
-// @ts-check
-module.exports = {
- 0x0000: 'Ericsson Technology Licensing',
- 0x0001: 'Nokia Mobile Phones',
- 0x0002: 'Intel Corp.',
- 0x0003: 'IBM Corp.',
- 0x0004: 'Toshiba Corp.',
- 0x0005: '3Com',
- 0x0006: 'Microsoft',
- 0x0007: 'Lucent',
- 0x0008: 'Motorola',
- 0x0009: 'Infineon Technologies AG',
- 0x000a: 'Cambridge Silicon Radio',
- 0x000b: 'Silicon Wave',
- 0x000c: 'Digianswer A/S',
- 0x000d: 'Texas Instruments Inc.',
- 0x000e: 'Ceva, Inc. (formerly Parthus Technologies, Inc.)',
- 0x000f: 'Broadcom Corporation',
- 0x0010: 'Mitel Semiconductor',
- 0x0011: 'Widcomm, Inc',
- 0x0012: 'Zeevo, Inc.',
- 0x0013: 'Atmel Corporation',
- 0x0014: 'Mitsubishi Electric Corporation',
- 0x0015: 'RTX Telecom A/S',
- 0x0016: 'KC Technology Inc.',
- 0x0017: 'NewLogic',
- 0x0018: 'Transilica, Inc.',
- 0x0019: 'Rohde & Schwarz GmbH & Co. KG',
- 0x001a: 'TTPCom Limited',
- 0x001b: 'Signia Technologies, Inc.',
- 0x001c: 'Conexant Systems Inc.',
- 0x001d: 'Qualcomm',
- 0x001e: 'Inventel',
- 0x001f: 'AVM Berlin',
- 0x0020: 'BandSpeed, Inc.',
- 0x0021: 'Mansella Ltd',
- 0x0022: 'NEC Corporation',
- 0x0023: 'WavePlus Technology Co., Ltd.',
- 0x0024: 'Alcatel',
- 0x0025: 'NXP Semiconductors (formerly Philips Semiconductors)',
- 0x0026: 'C Technologies',
- 0x0027: 'Open Interface',
- 0x0028: 'R F Micro Devices',
- 0x0029: 'Hitachi Ltd',
- 0x002a: 'Symbol Technologies, Inc.',
- 0x002b: 'Tenovis',
- 0x002c: 'Macronix International Co. Ltd.',
- 0x002d: 'GCT Semiconductor',
- 0x002e: 'Norwood Systems',
- 0x002f: 'MewTel Technology Inc.',
- 0x0030: 'ST Microelectronics',
- 0x0031: 'Synopsis',
- 0x0032: 'Red-M (Communications) Ltd',
- 0x0033: 'Commil Ltd',
- 0x0034: 'Computer Access Technology Corporation (CATC)',
- 0x0035: 'Eclipse (HQ Espana) S.L.',
- 0x0036: 'Renesas Electronics Corporation',
- 0x0037: 'Mobilian Corporation',
- 0x0038: 'Terax',
- 0x0039: 'Integrated System Solution Corp.',
- 0x003a: 'Matsushita Electric Industrial Co., Ltd.',
- 0x003b: 'Gennum Corporation',
- 0x003c: 'BlackBerry Limited (formerly Research In Motion)',
- 0x003d: 'IPextreme, Inc.',
- 0x003e: 'Systems and Chips, Inc.',
- 0x003f: 'Bluetooth SIG, Inc.',
- 0x0040: 'Seiko Epson Corporation',
- 0x0041: 'Integrated Silicon Solution Taiwan, Inc.',
- 0x0042: 'CONWISE Technology Corporation Ltd',
- 0x0043: 'PARROT SA',
- 0x0044: 'Socket Mobile',
- 0x0045: 'Atheros Communications, Inc.',
- 0x0046: 'MediaTek, Inc.',
- 0x0047: 'Bluegiga',
- 0x0048: 'Marvell Technology Group Ltd.',
- 0x0049: '3DSP Corporation',
- 0x004a: 'Accel Semiconductor Ltd.',
- 0x004b: 'Continental Automotive Systems',
- 0x004c: 'Apple, Inc.',
- 0x004d: 'Staccato Communications, Inc.',
- 0x004e: 'Avago Technologies',
- 0x004f: 'APT Licensing Ltd.',
- 0x0050: 'SiRF Technology',
- 0x0051: 'Tzero Technologies, Inc.',
- 0x0052: 'J&M Corporation',
- 0x0053: 'Free2move AB',
- 0x0054: '3DiJoy Corporation',
- 0x0055: 'Plantronics, Inc.',
- 0x0056: 'Sony Ericsson Mobile Communications',
- 0x0057: 'Harman International Industries, Inc.',
- 0x0058: 'Vizio, Inc.',
- 0x0059: 'Nordic Semiconductor ASA',
- 0x005a: 'EM Microelectronic-Marin SA',
- 0x005b: 'Ralink Technology Corporation',
- 0x005c: 'Belkin International, Inc.',
- 0x005d: 'Realtek Semiconductor Corporation',
- 0x005e: 'Stonestreet One, LLC',
- 0x005f: 'Wicentric, Inc.',
- 0x0060: 'RivieraWaves S.A.S',
- 0x0061: 'RDA Microelectronics',
- 0x0062: 'Gibson Guitars',
- 0x0063: 'MiCommand Inc.',
- 0x0064: 'Band XI International, LLC',
- 0x0065: 'Hewlett-Packard Company',
- 0x0066: '9Solutions Oy',
- 0x0067: 'GN Netcom A/S',
- 0x0068: 'General Motors',
- 0x0069: 'A&D Engineering, Inc.',
- 0x006a: 'MindTree Ltd.',
- 0x006b: 'Polar Electro OY',
- 0x006c: 'Beautiful Enterprise Co., Ltd.',
- 0x006d: 'BriarTek, Inc.',
- 0x006e: 'Summit Data Communications, Inc.',
- 0x006f: 'Sound ID',
- 0x0070: 'Monster, LLC',
- 0x0071: 'connectBlue AB',
- 0x0072: 'ShangHai Super Smart Electronics Co. Ltd.',
- 0x0073: 'Group Sense Ltd.',
- 0x0074: 'Zomm, LLC',
- 0x0075: 'Samsung Electronics Co. Ltd.',
- 0x0076: 'Creative Technology Ltd.',
- 0x0077: 'Laird Technologies',
- 0x0078: 'Nike, Inc.',
- 0x0079: 'lesswire AG',
- 0x007a: 'MStar Semiconductor, Inc.',
- 0x007b: 'Hanlynn Technologies',
- 0x007c: 'A & R Cambridge',
- 0x007d: 'Seers Technology Co. Ltd',
- 0x007e: 'Sports Tracking Technologies Ltd.',
- 0x007f: 'Autonet Mobile',
- 0x0080: 'DeLorme Publishing Company, Inc.',
- 0x0081: 'WuXi Vimicro',
- 0x0082: 'Sennheiser Communications A/S',
- 0x0083: 'TimeKeeping Systems, Inc.',
- 0x0084: 'Ludus Helsinki Ltd.',
- 0x0085: 'BlueRadios, Inc.',
- 0x0086: 'equinox AG',
- 0x0087: 'Garmin International, Inc.',
- 0x0088: 'Ecotest',
- 0x0089: 'GN ReSound A/S',
- 0x008a: 'Jawbone',
- 0x008b: 'Topcorn Positioning Systems, LLC',
- 0x008c: 'Gimbal Inc. (formerly Qualcomm Labs, Inc. and Qualcomm Retail Solutions, Inc.)',
- 0x008d: 'Zscan Software',
- 0x008e: 'Quintic Corp.',
- 0x008f: 'Stollman E+V GmbH',
- 0x0090: 'Funai Electric Co., Ltd.',
- 0x0091: 'Advanced PANMOBIL Systems GmbH & Co. KG',
- 0x0092: 'ThinkOptics, Inc.',
- 0x0093: 'Universal Electronics, Inc.',
- 0x0094: 'Airoha Technology Corp.',
- 0x0095: 'NEC Lighting, Ltd.',
- 0x0096: 'ODM Technology, Inc.',
- 0x0097: 'ConnecteDevice Ltd.',
- 0x0098: 'zer01.tv GmbH',
- 0x0099: 'i.Tech Dynamic Global Distribution Ltd.',
- 0x009a: 'Alpwise',
- 0x009b: 'Jiangsu Toppower Automotive Electronics Co., Ltd.',
- 0x009c: 'Colorfy, Inc.',
- 0x009d: 'Geoforce Inc.',
- 0x009e: 'Bose Corporation',
- 0x009f: 'Suunto Oy',
- 0x00a0: 'Kensington Computer Products Group',
- 0x00a1: 'SR-Medizinelektronik',
- 0x00a2: 'Vertu Corporation Limited',
- 0x00a3: 'Meta Watch Ltd.',
- 0x00a4: 'LINAK A/S',
- 0x00a5: 'OTL Dynamics LLC',
- 0x00a6: 'Panda Ocean Inc.',
- 0x00a7: 'Visteon Corporation',
- 0x00a8: 'ARP Devices Limited',
- 0x00a9: 'Magneti Marelli S.p.A',
- 0x00aa: 'CAEN RFID srl',
- 0x00ab: 'Ingenieur-Systemgruppe Zahn GmbH',
- 0x00ac: 'Green Throttle Games',
- 0x00ad: 'Peter Systemtechnik GmbH',
- 0x00ae: 'Omegawave Oy',
- 0x00af: 'Cinetix',
- 0x00b0: 'Passif Semiconductor Corp',
- 0x00b1: 'Saris Cycling Group, Inc',
- 0x00b2: 'Bekey A/S',
- 0x00b3: 'Clarinox Technologies Pty. Ltd.',
- 0x00b4: 'BDE Technology Co., Ltd.',
- 0x00b5: 'Swirl Networks',
- 0x00b6: 'Meso international',
- 0x00b7: 'TreLab Ltd',
- 0x00b8: 'Qualcomm Innovation Center, Inc. (QuIC)',
- 0x00b9: 'Johnson Controls, Inc.',
- 0x00ba: 'Starkey Laboratories Inc.',
- 0x00bb: 'S-Power Electronics Limited',
- 0x00bc: 'Ace Sensor Inc',
- 0x00bd: 'Aplix Corporation',
- 0x00be: 'AAMP of America',
- 0x00bf: 'Stalmart Technology Limited',
- 0x00c0: 'AMICCOM Electronics Corporation',
- 0x00c1: 'Shenzhen Excelsecu Data Technology Co.,Ltd',
- 0x00c2: 'Geneq Inc.',
- 0x00c3: 'adidas AG',
- 0x00c4: 'LG Electronics',
- 0x00c5: 'Onset Computer Corporation',
- 0x00c6: 'Selfly BV',
- 0x00C7: 'Quuppa Oy.',
- 0x00C8: 'GeLo Inc',
- 0x00C9: 'Evluma',
- 0x00CA: 'MC10',
- 0x00CB: 'Binauric SE',
- 0x00CC: 'Beats Electronics',
- 0x00CD: 'Microchip Technology Inc.',
- 0x00CE: 'Elgato Systems GmbH',
- 0x00CF: 'ARCHOS SA',
- 0x00D0: 'Dexcom, Inc.',
- 0x00D1: 'Polar Electro Europe B.V.',
- 0x00D2: 'Dialog Semiconductor B.V.',
- 0x00D3: 'Taixingbang Technology (HK) Co,. LTD.',
- 0x00D4: 'Kawantech',
- 0x00D5: 'Austco Communication Systems',
- 0x00D6: 'Timex Group USA, Inc.',
- 0x00D7: 'Qualcomm Technologies, Inc.',
- 0x00D8: 'Qualcomm Connected Experiences, Inc.',
- 0x00D9: 'Voyetra Turtle Beach',
- 0x00DA: 'txtr GmbH',
- 0x00DB: 'Biosentronics',
- 0x00DC: 'Procter & Gamble',
- 0x00DD: 'Hosiden Corporation',
- 0x00DE: 'Muzik LLC',
- 0x00DF: 'Misfit Wearables Corp',
- 0x00E0: 'Google',
- 0x00E1: 'Danlers Ltd',
- 0x00E2: 'Semilink Inc',
- 0x00E3: 'inMusic Brands, Inc',
- 0x00E4: 'L.S. Research Inc.',
- 0x00E5: 'Eden Software Consultants Ltd.',
- 0x00E6: 'Freshtemp',
- 0x00e7: 'KS Technologies',
- 0x00e8: 'ACTS Technologies',
- 0x00e9: 'Vtrack Systems',
- 0x00ea: 'Nielsen-Kellerman Company',
- 0x00eb: 'Server Technology, Inc.',
- 0x00ec: 'BioResearch Associates',
- 0x00ed: 'Jolly Logic, LLC',
- 0x00ee: 'Above Average Outcomes, Inc.',
- 0x00ef: 'Bitsplitters GmbH',
- 0x00f0: 'PayPal, Inc.',
- 0x00f1: 'Witron Technology Limited',
- 0x00f2: 'Aether Things Inc. (formerly Morse Project Inc.)',
- 0x00f3: 'Kent Displays Inc.',
- 0x00f4: 'Nautilus Inc.',
- 0x00f5: 'Smartifier Oy',
- 0x00f6: 'Elcometer Limited',
- 0x00f7: 'VSN Technologies Inc.',
- 0x00f8: 'AceUni Corp., Ltd.',
- 0x00f9: 'StickNFind',
- 0x00fa: 'Crystal Code AB',
- 0x00fb: 'KOUKAAM a.s.',
- 0x00fc: 'Delphi Corporation',
- 0x00fd: 'ValenceTech Limited',
- 0x00fe: 'Reserved',
- 0x00ff: 'Typo Products, LLC',
- 0x0100: 'TomTom International BV',
- 0x0101: 'Fugoo, Inc',
- 0x0102: 'Keiser Corporation',
- 0x0103: 'Bang & Olufsen A/S',
- 0x0104: 'PLUS Locations Systems Pty Ltd',
- 0x0105: 'Ubiquitous Computing Technology Corporation',
- 0x0106: 'Innovative Yachtter Solutions',
- 0x0107: 'William Demant Holding A/S',
- 0x0108: 'Chicony Electronics Co., Ltd.',
- 0x0109: 'Atus BV',
- 0x010a: 'Codegate Ltd.',
- 0x010b: 'ERi, Inc.',
- 0x010c: 'Transducers Direct, LLC',
- 0x010d: 'Fujitsu Ten Limited',
- 0x010e: 'Audi AG',
- 0x010f: 'HiSilicon Technologies Co., Ltd.',
- 0x0110: 'Nippon Seiki Co., Ltd.',
- 0x0111: 'Steelseries ApS',
- 0x0112: 'vyzybl Inc.',
- 0x0113: 'Openbrain Technologies, Co., Ltd.',
- 0x0114: 'Xensr',
- 0x0115: 'e.solutions',
- 0x0116: '1OAK Technologies',
- 0x0117: 'Wimoto Technologies Inc',
- 0x0118: 'Radius Networks, Inc.',
- 0x0119: 'Wize Technology Co., Ltd.',
- 0x011a: 'Qualcomm Labs, Inc.',
- 0x011b: 'Aruba Networks',
- 0x011c: 'Baidu',
- 0x011d: 'Arendi AG',
- 0x011e: 'Skoda Auto a.s.',
- 0x011f: 'Volkswagon AG',
- 0x0120: 'Porsche AG',
- 0x0121: 'Sino Wealth Electronic Ltd.',
- 0x0122: 'AirTurn, Inc.',
- 0x0123: 'Kinsa, Inc.',
- 0x0124: 'HID Global',
- 0x0125: 'SEAT es',
- 0x0126: 'Promethean Ltd.',
- 0x0127: 'Salutica Allied Solutions',
- 0x0128: 'GPSI Group Pty Ltd',
- 0x0129: 'Nimble Devices Oy',
- 0x012a: 'Changzhou Yongse Infotech Co., Ltd',
- 0x012b: 'SportIQ',
- 0x012c: 'TEMEC Instruments B.V.',
- 0x012d: 'Sony Corporation',
- 0x012e: 'ASSA ABLOY',
- 0x012f: 'Clarion Co., Ltd.',
- 0x0130: 'Warehouse Innovations',
- 0x0131: 'Cypress Semiconductor Corporation',
- 0x0132: 'MADS Inc',
- 0x0133: 'Blue Maestro Limited',
- 0x0134: 'Resolution Products, Inc.',
- 0x0135: 'Airewear LLC',
- 0x0136: 'Seed Labs, Inc. (formerly ETC sp. z.o.o.)',
- 0x0137: 'Prestigio Plaza Ltd.',
- 0x0138: 'NTEO Inc.',
- 0x0139: 'Focus Systems Corporation',
- 0x013a: 'Tencent Holdings Limited',
- 0x013b: 'Allegion',
- 0x013c: 'Murata Manufacuring Co., Ltd.',
- 0x013e: 'Nod, Inc.',
- 0x013f: 'B&B Manufacturing Company',
- 0x0140: 'Alpine Electronics (China) Co., Ltd',
- 0x0141: 'FedEx Services',
- 0x0142: 'Grape Systems Inc.',
- 0x0143: 'Bkon Connect',
- 0x0144: 'Lintech GmbH',
- 0x0145: 'Novatel Wireless',
- 0x0146: 'Ciright',
- 0x0147: 'Mighty Cast, Inc.',
- 0x0148: 'Ambimat Electronics',
- 0x0149: 'Perytons Ltd.',
- 0x014a: 'Tivoli Audio, LLC',
- 0x014b: 'Master Lock',
- 0x014c: 'Mesh-Net Ltd',
- 0x014d: 'Huizhou Desay SV Automotive CO., LTD.',
- 0x014e: 'Tangerine, Inc.',
- 0x014f: 'B&W Group Ltd.',
- 0x0150: 'Pioneer Corporation',
- 0x0151: 'OnBeep',
- 0x0152: 'Vernier Software & Technology',
- 0x0153: 'ROL Ergo',
- 0x0154: 'Pebble Technology',
- 0x0155: 'NETATMO',
- 0x0156: 'Accumulate AB',
- 0x0157: 'Anhui Huami Information Technology Co., Ltd.',
- 0x0158: 'Inmite s.r.o.',
- 0x0159: 'ChefSteps, Inc.',
- 0x015a: 'micas AG',
- 0x015b: 'Biomedical Research Ltd.',
- 0x015c: 'Pitius Tec S.L.',
- 0x015d: 'Estimote, Inc.',
- 0x015e: 'Unikey Technologies, Inc.',
- 0x015f: 'Timer Cap Co.',
- 0x0160: 'AwoX',
- 0x0161: 'yikes',
- 0x0162: 'MADSGlobal NZ Ltd.',
- 0x0163: 'PCH International',
- 0x0164: 'Qingdao Yeelink Information Technology Co., Ltd.',
- 0x0165: 'Milwaukee Tool (formerly Milwaukee Electric Tools)',
- 0x0166: 'MISHIK Pte Ltd',
- 0x0167: 'Bayer HealthCare',
- 0x0168: 'Spicebox LLC',
- 0x0169: 'emberlight',
- 0x016a: 'Cooper-Atkins Corporation',
- 0x016b: 'Qblinks',
- 0x016c: 'MYSPHERA',
- 0x016d: 'LifeScan Inc',
- 0x016e: 'Volantic AB',
- 0x016f: 'Podo Labs, Inc',
- 0x0170: 'Roche Diabetes Care AG',
- 0x0171: 'Amazon Fulfillment Service',
- 0x0172: 'Connovate Technology Private Limited',
- 0x0173: 'Kocomojo, LLC',
- 0x0174: 'Everykey LLC',
- 0x0175: 'Dynamic Controls',
- 0x0176: 'SentriLock',
- 0x0177: 'I-SYST inc.',
- 0x0178: 'CASIO COMPUTER CO., LTD.',
- 0x0179: 'LAPIS Semiconductor Co., Ltd.',
- 0x017a: 'Telemonitor, Inc.',
- 0x017b: 'taskit GmbH',
- 0x017c: 'Daimler AG',
- 0x017d: 'BatAndCat',
- 0x017e: 'BluDotz Ltd',
- 0x017f: 'XTel ApS',
- 0x0180: 'Gigaset Communications GmbH',
- 0x0181: 'Gecko Health Innovations, Inc.',
- 0x0182: 'HOP Ubiquitous',
- 0x0183: 'To Be Assigned',
- 0x0184: 'Nectar',
- 0x0185: 'bel’apps LLC',
- 0x0186: 'CORE Lighting Ltd',
- 0x0187: 'Seraphim Sense Ltd',
- 0x0188: 'Unico RBC',
- 0x0189: 'Physical Enterprises Inc.',
- 0x018a: 'Able Trend Technology Limited',
- 0x018b: 'Konica Minolta, Inc.',
- 0x018c: 'Wilo SE',
- 0x018d: 'Extron Design Services',
- 0x018e: 'Fitbit, Inc.',
- 0x018f: 'Fireflies Systems',
- 0x0190: 'Intelletto Technologies Inc.',
- 0x0191: 'FDK CORPORATION',
- 0x0192: 'Cloudleaf, Inc',
- 0x0193: 'Maveric Automation LLC',
- 0x0194: 'Acoustic Stream Corporation',
- 0x0195: 'Zuli',
- 0x0196: 'Paxton Access Ltd',
- 0x0197: 'WiSilica Inc',
- 0x0198: 'Vengit Limited',
- 0x0199: 'SALTO SYSTEMS S.L.',
- 0x019a: 'TRON Forum (formerly T-Engine Forum)',
- 0x019b: 'CUBETECH s.r.o.',
- 0x019c: 'Cokiya Incorporated',
- 0x019d: 'CVS Health',
- 0x019e: 'Ceruus',
- 0x019f: 'Strainstall Ltd',
- 0x01a0: 'Channel Enterprises (HK) Ltd.',
- 0x01a1: 'FIAMM',
- 0x01a2: 'GIGALANE.CO.,LTD',
- 0x01a3: 'EROAD',
- 0x01a4: 'Mine Safety Appliances',
- 0x01a5: 'Icon Health and Fitness',
- 0x01a6: 'Asandoo GmbH',
- 0x01a7: 'ENERGOUS CORPORATION',
- 0x01a8: 'Taobao',
- 0x01a9: 'Canon Inc.',
- 0x01aa: 'Geophysical Technology Inc.',
- 0x01ab: 'Facebook, Inc.',
- 0x01ac: 'Nipro Diagnostics, Inc.',
- 0x01ad: 'FlightSafety International',
- 0x01ae: 'Earlens Corporation',
- 0x01af: 'Sunrise Micro Devices, Inc.',
- 0x01b0: 'Star Micronics Co., Ltd.',
- 0x01b1: 'Netizens Sp. z o.o.',
- 0x01b2: 'Nymi Inc.',
- 0x01b3: 'Nytec, Inc.',
- 0x01b4: 'Trineo Sp. z o.o.',
- 0x01b5: 'Nest Labs Inc.',
- 0x01b6: 'LM Technologies Ltd',
- 0x01b7: 'General Electric Company',
- 0x01b8: 'i+D3 S.L.',
- 0x01b9: 'HANA Micron',
- 0x01ba: 'Stages Cycling LLC',
- 0x01bb: 'Cochlear Bone Anchored Solutions AB',
- 0x01bc: 'SenionLab AB',
- 0x01bd: 'Syszone Co., Ltd',
- 0x01be: 'Pulsate Mobile Ltd.',
- 0x01bf: 'Hong Kong HunterSun Electronic Limited',
- 0x01c0: 'pironex GmbH',
- 0x01c1: 'BRADATECH Corp.',
- 0x01c2: 'Transenergooil AG',
- 0x01c3: 'Bunch',
- 0x01c4: 'DME Microelectronics',
- 0x01c5: 'Bitcraze AB',
- 0x01c6: 'HASWARE Inc.',
- 0x01c7: 'Abiogenix Inc.',
- 0x01c8: 'Poly-Control ApS',
- 0x01c9: 'Avi-on',
- 0x01ca: 'Laerdal Medical AS',
- 0x01cb: 'Fetch My Pet',
- 0x01cc: 'Sam Labs Ltd.',
- 0x01cd: 'Chengdu Synwing Technology Ltd',
- 0x01ce: 'HOUWA SYSTEM DESIGN, k.k.',
- 0x01cf: 'BSH',
- 0x01d0: 'Primus Inter Pares Ltd',
- 0x01d1: 'August',
- 0x01d2: 'Gill Electronics',
- 0x01d3: 'Sky Wave Design',
- 0x01d4: 'Newlab S.r.l.',
- 0x01d5: 'ELAD srl',
- 0x01d6: 'G-wearables inc.',
- 0x01d7: 'Squadrone Systems Inc.',
- 0x01d8: 'Code Corporation',
- 0x01d9: 'Savant Systems LLC',
- 0x01da: 'Logitech International SA',
- 0x01db: 'Innblue Consulting',
- 0x01dc: 'iParking Ltd.',
- 0x01dd: 'Koninklijke Philips Electronics N.V.',
- 0x01de: 'Minelab Electronics Pty Limited',
- 0x01df: 'Bison Group Ltd.',
- 0x01e0: 'Widex A/S',
- 0x01e1: 'Jolla Ltd',
- 0x01e2: 'Lectronix, Inc.',
- 0x01e3: 'Caterpillar Inc',
- 0x01e4: 'Freedom Innovations',
- 0x01e5: 'Dynamic Devices Ltd',
- 0x01e6: 'Technology Solutions (UK) Ltd',
- 0x01e7: 'IPS Group Inc.',
- 0x01e8: 'STIR',
- 0x01e9: 'Sano, Inc',
- 0x01ea: 'Advanced Application Design, Inc.',
- 0x01eb: 'AutoMap LLC',
- 0x01ec: 'Spreadtrum Communications Shanghai Ltd',
- 0x01ed: 'CuteCircuit LTD',
- 0x01ee: 'Valeo Service',
- 0x01ef: 'Fullpower Technologies, Inc.',
- 0x01f0: 'KloudNation',
- 0x01f1: 'Zebra Technologies Corporation',
- 0x01f2: 'Itron, Inc.',
- 0x01f3: 'The University of Tokyo',
- 0x01f4: 'UTC Fire and Security',
- 0x01f5: 'Cool Webthings Limited',
- 0x01f6: 'DJO Global',
- 0x01f7: 'Gelliner Limited',
- 0x01f8: 'Anyka (Guangzhou) Microelectronics Technology Co, LTD',
- 0x01f9: 'Medtronic, Inc.',
- 0x01fa: 'Gozio, Inc.',
- 0x01fb: 'Form Lifting, LLC',
- 0x01fc: 'Wahoo Fitness, LLC',
- 0x01fd: 'Kontakt Micro-Location Sp. z o.o.',
- 0x01fe: 'Radio System Corporation',
- 0x01ff: 'Freescale Semiconductor, Inc.',
- 0x0200: 'Verifone Systems PTe Ltd. Taiwan Branch',
- 0x0201: 'AR Timing',
- 0x0202: 'Rigado LLC',
- 0x0203: 'Kemppi Oy',
- 0x0204: 'Tapcentive Inc.',
- 0x0205: 'Smartbotics Inc.',
- 0x0206: 'Otter Products, LLC',
- 0x0207: 'STEMP Inc.',
- 0x0208: 'LumiGeek LLC',
- 0x0209: 'InvisionHeart Inc.',
- 0x020A: 'Macnica Inc. ',
- 0x020b: 'Jaguar Land Rover Limited',
- 0x020c: 'CoroWare Technologies, Inc',
- 0x020d: 'Simplo Technology Co., LTD',
- 0x020e: 'Omron Healthcare Co., LTD',
- 0x020f: 'Comodule GMBH',
- 0x0210: 'ikeGPS',
- 0x0211: 'Telink Semiconductor Co. Ltd',
- 0x0212: 'Interplan Co., Ltd',
- 0x0213: 'Wyler AG',
- 0x0214: 'IK Multimedia Production srl',
- 0x0215: 'Lukoton Experience Oy',
- 0x0216: 'MTI Ltd',
- 0x0217: 'Tech4home, Lda',
- 0x0218: 'Hiotech AB',
- 0x0219: 'DOTT Limited',
- 0x021A: 'Blue Speck Labs, LLC',
- 0x021B: 'Cisco Systems, Inc',
- 0x021C: 'Mobicomm Inc',
- 0x021D: 'Edamic',
- 0x021E: 'Goodnet, Ltd',
- 0x021F: 'Luster Leaf Products Inc',
- 0x0220: 'Manus Machina BV',
- 0x0221: 'Mobiquity Networks Inc',
- 0x0222: 'Praxis Dynamics',
- 0x0223: 'Philip Morris Products S.A.',
- 0x0224: 'Comarch SA',
- 0x0225: 'Nestl Nespresso S.A.',
- 0x0226: 'Merlinia A/S',
- 0x0227: 'LifeBEAM Technologies',
- 0x0228: 'Twocanoes Labs, LLC',
- 0x0229: 'Muoverti Limited',
- 0x022A: 'Stamer Musikanlagen GMBH',
- 0x022B: 'Tesla Motors',
- 0x022C: 'Pharynks Corporation',
- 0x022D: 'Lupine',
- 0x022E: 'Siemens AG',
- 0x022F: 'Huami (Shanghai) Culture Communication CO., LTD',
- 0x0230: 'Foster Electric Company, Ltd',
- 0x0231: 'ETA SA',
- 0x0232: 'x-Senso Solutions Kft',
- 0x0233: 'Shenzhen SuLong Communication Ltd',
- 0x0234: 'FengFan (BeiJing) Technology Co, Ltd',
- 0x0235: 'Qrio Inc',
- 0x0236: 'Pitpatpet Ltd',
- 0x0237: 'MSHeli s.r.l.',
- 0x0238: 'Trakm8 Ltd',
- 0x0239: 'JIN CO, Ltd',
- 0x023A: 'Alatech Tehnology',
- 0x023B: 'Beijing CarePulse Electronic Technology Co, Ltd',
- 0x023C: 'Awarepoint',
- 0x023D: 'ViCentra B.V.',
- 0x023E: 'Raven Industries',
- 0x023F: 'WaveWare Technologies Inc.',
- 0x0240: 'Argenox Technologies',
- 0x0241: 'Bragi GmbH',
- 0x0242: '16Lab Inc',
- 0x0243: 'Masimo Corp',
- 0x0244: 'Iotera Inc',
- 0x0245: 'Endress+Hauser',
- 0x0246: 'ACKme Networks, Inc.',
- 0x0247: 'FiftyThree Inc.',
- 0x0248: 'Parker Hannifin Corp',
- 0x0249: 'Transcranial Ltd',
- 0x024A: 'Uwatec AG',
- 0x024B: 'Orlan LLC',
- 0x024C: 'Blue Clover Devices',
- 0x024D: 'M-Way Solutions GmbH',
- 0x024E: 'Microtronics Engineering GmbH',
- 0x024F: 'Schneider Schreibgerte GmbH',
- 0x0250: 'Sapphire Circuits LLC',
- 0x0251: 'Lumo Bodytech Inc.',
- 0x0252: 'UKC Technosolution',
- 0x0253: 'Xicato Inc.',
- 0x0254: 'Playbrush',
- 0x0255: 'Dai Nippon Printing Co., Ltd.',
- 0x0256: 'G24 Power Limited',
- 0x0257: 'AdBabble Local Commerce Inc.',
- 0x0258: 'Devialet SA',
- 0x0259: 'ALTYOR',
- 0x025A: 'University of Applied Sciences Valais/Haute Ecole Valaisanne',
- 0x025B: 'Five Interactive, LLC dba Zendo',
- 0x025C: 'NetEaseHangzhouNetwork co.Ltd.',
- 0x025D: 'Lexmark International Inc.',
- 0x025E: 'Fluke Corporation',
- 0x025F: 'Yardarm Technologies',
- 0x0260: 'SensaRx',
- 0x0261: 'SECVRE GmbH',
- 0x0262: 'Glacial Ridge Technologies',
- 0x0263: 'Identiv, Inc.',
- 0x0264: 'DDS, Inc.',
- 0x0265: 'SMK Corporation',
- 0x0266: 'Schawbel Technologies LLC',
- 0x0267: 'XMI Systems SA',
- 0x0268: 'Cerevo',
- 0x0269: 'Torrox GmbH & Co KG',
- 0x026A: 'Gemalto',
- 0x026B: 'DEKA Research & Development Corp.',
- 0x026C: 'Domster Tadeusz Szydlowski',
- 0x026D: 'Technogym SPA',
- 0x026E: 'FLEURBAEY BVBA',
- 0x026F: 'Aptcode Solutions',
- 0x0270: 'LSI ADL Technology',
- 0x0271: 'Animas Corp',
- 0x0272: 'Alps Electric Co., Ltd.',
- 0x0273: 'OCEASOFT',
- 0x0274: 'Motsai Research',
- 0x0275: 'Geotab',
- 0x0276: 'E.G.O. Elektro-Gertebau GmbH',
- 0x0277: 'bewhere inc',
- 0x0278: 'Johnson Outdoors Inc',
- 0x0279: 'steute Schaltgerate GmbH & Co. KG',
- 0x027A: 'Ekomini inc.',
- 0x027B: 'DEFA AS',
- 0x027C: 'Aseptika Ltd',
- 0x027D: 'HUAWEI Technologies Co., Ltd. ( )',
- 0x027E: 'HabitAware, LLC',
- 0x027F: 'ruwido austria gmbh',
- 0x0280: 'ITEC corporation',
- 0x0281: 'StoneL',
- 0x0282: 'Sonova AG',
- 0x0283: 'Maven Machines, Inc.',
- 0x0284: 'Synapse Electronics',
- 0x0285: 'Standard Innovation Inc.',
- 0x0286: 'RF Code, Inc.',
- 0x0287: 'Wally Ventures S.L.',
- 0x0288: 'Willowbank Electronics Ltd',
- 0x0289: 'SK Telecom',
- 0x028A: 'Jetro AS',
- 0x028B: 'Code Gears LTD',
- 0x028C: 'NANOLINK APS',
- 0x028D: 'IF, LLC',
- 0x028E: 'RF Digital Corp',
- 0x028F: 'Church & Dwight Co., Inc',
- 0x0290: 'Multibit Oy',
- 0x0291: 'CliniCloud Inc',
- 0x0292: 'SwiftSensors',
- 0x0293: 'Blue Bite',
- 0x0294: 'ELIAS GmbH',
- 0x0295: 'Sivantos GmbH',
- 0x0296: 'Petzl',
- 0x0297: 'storm power ltd',
- 0x0298: 'EISST Ltd',
- 0x0299: 'Inexess Technology Simma KG',
- 0x029A: 'Currant, Inc.',
- 0x029B: 'C2 Development, Inc.',
- 0x029C: 'Blue Sky Scientific, LLC',
- 0x029D: 'ALOTTAZS LABS, LLC',
- 0x029E: 'Kupson spol. s r.o.',
- 0x029F: 'Areus Engineering GmbH',
- 0x02A0: 'Impossible Camera GmbH',
- 0x02A1: 'InventureTrack Systems',
- 0x02A2: 'LockedUp',
- 0x02A3: 'Itude',
- 0x02A4: 'Pacific Lock Company',
- 0x02A5: 'Tendyron Corporation ( )',
- 0x02A6: 'Robert Bosch GmbH',
- 0x02A7: 'Illuxtron international B.V.',
- 0x02A8: 'miSport Ltd.',
- 0x02A9: 'Chargelib',
- 0x02AA: 'Doppler Lab',
- 0x02AB: 'BBPOS Limited',
- 0x02AC: 'RTB Elektronik GmbH & Co. KG',
- 0x02AD: 'Rx Networks, Inc.',
- 0x02AE: 'WeatherFlow, Inc.',
- 0x02AF: 'Technicolor USA Inc.',
- 0x02B0: 'Bestechnic(Shanghai),Ltd',
- 0x02B1: 'Raden Inc',
- 0x02B2: 'JouZen Oy',
- 0x02B3: 'CLABER S.P.A.',
- 0x02B4: 'Hyginex, Inc.',
- 0x02B5: 'HANSHIN ELECTRIC RAILWAY CO.,LTD.',
- 0x02B6: 'Schneider Electric',
- 0x02B7: 'Oort Technologies LLC',
- 0x02B8: 'Chrono Therapeutics',
- 0x02B9: 'Rinnai Corporation',
- 0x02BA: 'Swissprime Technologies AG',
- 0x02BB: 'Koha.,Co.Ltd',
- 0x02BC: 'Genevac Ltd',
- 0x02BD: 'Chemtronics',
- 0x02BE: 'Seguro Technology Sp. z o.o.',
- 0x02BF: 'Redbird Flight Simulations',
- 0x02C0: 'Dash Robotics',
- 0x02C1: 'LINE Corporation',
- 0x02C2: 'Guillemot Corporation',
- 0x02C3: 'Techtronic Power Tools Technology Limited',
- 0x02C4: 'Wilson Sporting Goods',
- 0x02C5: 'Lenovo (Singapore) Pte Ltd. ( )',
- 0x02C6: 'Ayatan Sensors',
- 0x02C7: 'Electronics Tomorrow Limited',
- 0x02C8: 'VASCO Data Security International, Inc.',
- 0x02C9: 'PayRange Inc.',
- 0x02CA: 'ABOV Semiconductor',
- 0x02CB: 'AINA-Wireless Inc.',
- 0x02CC: 'Eijkelkamp Soil & Water',
- 0x02CD: 'BMA ergonomics b.v.',
- 0x02CE: 'Teva Branded Pharmaceutical Products R&D, Inc.',
- 0x02CF: 'Anima',
- 0x02D0: '3M',
- 0x02D1: 'Empatica Srl',
- 0x02D2: 'Afero, Inc.',
- 0x02D3: 'Powercast Corporation',
- 0x02D4: 'Secuyou ApS',
- 0x02D5: 'OMRON Corporation',
- 0x02D6: 'Send Solutions',
- 0x02D7: 'NIPPON SYSTEMWARE CO.,LTD.',
- 0x02D8: 'Neosfar',
- 0x02D9: 'Fliegl Agrartechnik GmbH',
- 0x02DA: 'Gilvader',
- 0x02DB: 'Digi International Inc (R)',
- 0x02DC: 'DeWalch Technologies, Inc.',
- 0x02DD: 'Flint Rehabilitation Devices, LLC',
- 0x02DE: 'Samsung SDS Co., Ltd.',
- 0x02DF: 'Blur Product Development',
- 0x02E0: 'University of Michigan',
- 0x02E1: 'Victron Energy BV',
- 0x02E2: 'NTT docomo',
- 0x02E3: 'Carmanah Technologies Corp.',
- 0x02E4: 'Bytestorm Ltd.',
- 0x02E5: 'Espressif Incorporated ( () )',
- 0x02E6: 'Unwire',
- 0x02E7: 'Connected Yard, Inc.',
- 0x02E8: 'American Music Environments',
- 0x02E9: 'Sensogram Technologies, Inc.',
- 0x02EA: 'Fujitsu Limited',
- 0x02EB: 'Ardic Technology',
- 0x02EC: 'Delta Systems, Inc',
- 0x02ED: 'HTC Corporation',
- 0x02EE: 'Citizen Holdings Co., Ltd.',
- 0x02EF: 'SMART-INNOVATION.inc',
- 0x02F0: 'Blackrat Software',
- 0x02F1: 'The Idea Cave, LLC',
- 0x02F2: 'GoPro, Inc.',
- 0x02F3: 'AuthAir, Inc',
- 0x02F4: 'Vensi, Inc.',
- 0x02F5: 'Indagem Tech LLC',
- 0x02F6: 'Intemo Technologies',
- 0x02F7: 'DreamVisions co., Ltd.',
- 0x02F8: 'Runteq Oy Ltd',
- 0x02F9: 'IMAGINATION TECHNOLOGIES LTD',
- 0x02FA: 'CoSTAR TEchnologies',
- 0x02FB: 'Clarius Mobile Health Corp.',
- 0x02FC: 'Shanghai Frequen Microelectronics Co., Ltd.',
- 0x02FD: 'Uwanna, Inc.',
- 0x02FE: 'Lierda Science & Technology Group Co., Ltd.',
- 0x02FF: 'Silicon Laboratories',
- 0x0300: 'World Moto Inc.',
- 0x0301: 'Giatec Scientific Inc.',
- 0x0302: 'Loop Devices, Inc',
- 0x0303: 'IACA electronique',
- 0x0304: 'Martians Inc',
- 0x0305: 'Swipp ApS',
- 0x0306: 'Life Laboratory Inc.',
- 0x0307: 'FUJI INDUSTRIAL CO.,LTD.',
- 0x0308: 'Surefire, LLC',
- 0x0309: 'Dolby Labs',
- 0x030A: 'Ellisys',
- 0x030B: 'Magnitude Lighting Converters',
- 0x030C: 'Hilti AG',
- 0x030D: 'Devdata S.r.l.',
- 0x030E: 'Deviceworx',
- 0x030F: 'Shortcut Labs',
- 0x0310: 'SGL Italia S.r.l.',
- 0x0311: 'PEEQ DATA',
- 0x0312: 'Ducere Technologies Pvt Ltd',
- 0x0313: 'DiveNav, Inc.',
- 0x0314: 'RIIG AI Sp. z o.o.',
- 0x0315: 'Thermo Fisher Scientific',
- 0x0316: 'AG Measurematics Pvt. Ltd.',
- 0x0317: 'CHUO Electronics CO., LTD.',
- 0x0318: 'Aspenta International',
- 0x0319: 'Eugster Frismag AG',
- 0x031A: 'Amber wireless GmbH',
- 0x031B: 'HQ Inc',
- 0x031C: 'Lab Sensor Solutions',
- 0x031D: 'Enterlab ApS',
- 0x031E: 'Eyefi, Inc.',
- 0x031F: 'MetaSystem S.p.A.',
- 0x0320: 'SONO ELECTRONICS. CO., LTD',
- 0x0321: 'Jewelbots',
- 0x0322: 'Compumedics Limited',
- 0x0323: 'Rotor Bike Components',
- 0x0324: 'Astro, Inc.',
- 0x0325: 'Amotus Solutions',
- 0x0326: 'Healthwear Technologies (Changzhou)Ltd',
- 0x0327: 'Essex Electronics',
- 0x0328: 'Grundfos A/S',
- 0x0329: 'Eargo, Inc.',
- 0x032A: 'Electronic Design Lab',
- 0x032B: 'ESYLUX',
- 0x032C: 'NIPPON SMT.CO.,Ltd',
- 0x032D: 'BM innovations GmbH',
- 0x032E: 'indoormap',
- 0x032F: 'OttoQ Inc',
- 0x0330: 'North Pole Engineering',
- 0x0331: '3flares Technologies Inc.',
- 0x0332: 'Electrocompaniet A.S.',
- 0x0333: 'Mul-T-Lock',
- 0x0334: 'Corentium AS',
- 0x0335: 'Enlighted Inc',
- 0x0336: 'GISTIC',
- 0x0337: 'AJP2 Holdings, LLC',
- 0x0338: 'COBI GmbH',
- 0x0339: 'Blue Sky Scientific, LLC',
- 0x033A: 'Appception, Inc.',
- 0x033B: 'Courtney Thorne Limited',
- 0x033C: 'Virtuosys',
- 0x033D: 'TPV Technology Limited',
- 0x033E: 'Monitra SA',
- 0x033F: 'Automation Components, Inc.',
- 0x0340: 'Letsense s.r.l.',
- 0x0341: 'Etesian Technologies LLC',
- 0x0342: 'GERTEC BRASIL LTDA.',
- 0x0343: 'Drekker Development Pty. Ltd.',
- 0x0344: 'Whirl Inc',
- 0x0345: 'Locus Positioning',
- 0x0346: 'Acuity Brands Lighting, Inc',
- 0x0347: 'Prevent Biometrics',
- 0x0348: 'Arioneo',
- 0x0349: 'VersaMe',
- 0x034A: 'Vaddio',
- 0x034B: 'Libratone A/S',
- 0x034C: 'HM Electronics, Inc.',
- 0x034D: 'TASER International, Inc.',
- 0x034E: 'SafeTrust Inc.',
- 0x034F: 'Heartland Payment Systems',
- 0x0350: 'Bitstrata Systems Inc.',
- 0x0351: 'Pieps GmbH',
- 0x0352: 'iRiding(Xiamen)Technology Co.,Ltd.',
- 0x0353: 'Alpha Audiotronics, Inc.',
- 0x0354: 'TOPPAN FORMS CO.,LTD.',
- 0x0355: 'Sigma Designs, Inc.',
- 0x0356: 'Spectrum Brands, Inc.',
- 0x0357: 'Polymap Wireless',
- 0x0358: 'MagniWare Ltd.',
- 0x0359: 'Novotec Medical GmbH',
- 0x035A: 'Medicom Innovation Partner a/s',
- 0x035B: 'Matrix Inc.',
- 0x035C: 'Eaton Corporation',
- 0x035D: 'KYS',
- 0x035E: 'Naya Health, Inc.',
- 0x035F: 'Acromag',
- 0x0360: 'Insulet Corporation',
- 0x0361: 'Wellinks Inc.',
- 0x0362: 'ON Semiconductor',
- 0x0363: 'FREELAP SA',
- 0x0364: 'Favero Electronics Srl',
- 0x0365: 'BioMech Sensor LLC',
- 0x0366: 'BOLTT Sports technologies Private limited',
- 0x0367: 'Saphe International',
- 0x0368: 'Metormote AB',
- 0x0369: 'littleBits',
- 0x036A: 'SetPoint Medical',
- 0x036B: 'BRControls Products BV',
- 0x036C: 'Zipcar',
- 0x036D: 'AirBolt Pty Ltd',
- 0x036E: 'KeepTruckin Inc',
- 0x036F: 'Motiv, Inc.',
- 0x0370: 'Wazombi Labs O',
- 0x0371: 'ORBCOMM',
- 0x0372: 'Nixie Labs, Inc.',
- 0x0373: 'AppNearMe Ltd',
- 0x0374: 'Holman Industries',
- 0x0375: 'Expain AS',
- 0x0376: 'Electronic Temperature Instruments Ltd',
- 0x0377: 'Plejd AB',
- 0x0378: 'Propeller Health',
- 0x0379: 'Shenzhen iMCO Electronic Technology Co.,Ltd',
- 0x037A: 'Algoria',
- 0x037B: 'Apption Labs Inc.',
- 0x037C: 'Cronologics Corporation',
- 0x037D: 'MICRODIA Ltd.',
- 0x037E: 'lulabytes S.L.',
- 0x037F: 'Nestec S.A.',
- 0x0380: 'LLC MEGA - F service',
- 0x0381: 'Sharp Corporation',
- 0x0382: 'Precision Outcomes Ltd',
- 0x0383: 'Kronos Incorporated',
- 0x0384: 'OCOSMOS Co., Ltd.',
- 0x0385: 'Embedded Electronic Solutions Ltd. dba e2Solutions',
- 0x0386: 'Aterica Inc.',
- 0x0387: 'BluStor PMC, Inc.',
- 0x0388: 'Kapsch TrafficCom AB',
- 0x0389: 'ActiveBlu Corporation',
- 0x038A: 'Kohler Mira Limited',
- 0x038B: 'Noke',
- 0x038C: 'Appion Inc.',
- 0x038D: 'Resmed Ltd',
- 0x038E: 'Crownstone B.V.',
- 0x038F: 'Xiaomi Inc.',
- 0x0390: 'INFOTECH s.r.o.',
- 0x0391: 'Thingsquare AB',
- 0x0392: 'T&D',
- 0x0393: 'LAVAZZA S.p.A.',
- 0x0394: 'Netclearance Systems, Inc.',
- 0x0395: 'SDATAWAY',
- 0x0396: 'BLOKS GmbH',
- 0x0397: 'LEGO System A/S',
- 0x0398: 'Thetatronics Ltd',
- 0x0399: 'Nikon Corporation',
- 0x039A: 'NeST',
- 0x039B: 'South Silicon Valley Microelectronics',
- 0x039C: 'ALE International',
- 0x039D: 'CareView Communications, Inc.',
- 0x039E: 'SchoolBoard Limited',
- 0x039F: 'Molex Corporation',
- 0x03A0: 'IVT Wireless Limited',
- 0x03A1: 'Alpine Labs LLC',
- 0x03A2: 'Candura Instruments',
- 0x03A3: 'SmartMovt Technology Co., Ltd',
- 0x03A4: 'Token Zero Ltd',
- 0x03A5: 'ACE CAD Enterprise Co., Ltd. (ACECAD)',
- 0x03A6: 'Medela, Inc',
- 0x03A7: 'AeroScout',
- 0x03A8: 'Esrille Inc.',
- 0x03A9: 'THINKERLY SRL',
- 0x03AA: 'Exon Sp. z o.o.',
- 0x03AB: 'Meizu Technology Co., Ltd.',
- 0x03AC: 'Smablo LTD',
- 0x03AD: 'XiQ',
- 0x03AE: 'Allswell Inc.',
- 0x03AF: 'Comm-N-Sense Corp DBA Verigo',
- 0x03B0: 'VIBRADORM GmbH',
- 0x03B1: 'Otodata Wireless Network Inc.',
- 0x03B2: 'Propagation Systems Limited',
- 0x03B3: 'Midwest Instruments & Controls',
- 0x03B4: 'Alpha Nodus, inc.',
- 0x03B5: 'petPOMM, Inc',
- 0x03B6: 'Mattel',
- 0x03B7: 'Airbly Inc.',
- 0x03B8: 'A-Safe Limited',
- 0x03B9: 'FREDERIQUE CONSTANT SA',
- 0x03BA: 'Maxscend Microelectronics Company Limited',
- 0x03BB: 'Abbott Diabetes Care',
- 0x03BC: 'ASB Bank Ltd',
- 0x03BD: 'amadas',
- 0x03BE: 'Applied Science, Inc.',
- 0x03BF: 'iLumi Solutions Inc.',
- 0x03C0: 'Arch Systems Inc.',
- 0x03C1: 'Ember Technologies, Inc.',
- 0x03C2: 'Snapchat Inc',
- 0x03C3: 'Casambi Technologies Oy',
- 0x03C4: 'Pico Technology Inc.',
- 0x03C5: 'St. Jude Medical, Inc.',
- 0x03C6: 'Intricon',
- 0x03C7: 'Structural Health Systems, Inc.',
- 0x03C8: 'Avvel International',
- 0x03C9: 'Gallagher Group',
- 0x03CA: 'In2things Automation Pvt. Ltd.',
- 0x03CB: 'SYSDEV Srl',
- 0x03CC: 'Vonkil Technologies Ltd',
- 0x03CD: 'Wynd Technologies, Inc.',
- 0x03CE: 'CONTRINEX S.A.',
- 0x03CF: 'MIRA, Inc.',
- 0x03D0: 'Watteam Ltd',
- 0x03D1: 'Density Inc.',
- 0x03D2: 'IOT Pot India Private Limited',
- 0x03D3: 'Sigma Connectivity AB',
- 0x03D4: 'PEG PEREGO SPA',
- 0x03D5: 'Wyzelink Systems Inc.',
- 0x03D6: 'Yota Devices LTD',
- 0x03D7: 'FINSECUR',
- 0x03D8: 'Zen-Me Labs Ltd',
- 0x03D9: '3IWare Co., Ltd.',
- 0x03DA: 'EnOcean GmbH',
- 0x03DB: 'Instabeat, Inc',
- 0x03DC: 'Nima Labs',
- 0x03DD: 'Andreas Stihl AG & Co. KG',
- 0x03DE: 'Nathan Rhoades LLC',
- 0x03DF: 'Grob Technologies, LLC',
- 0x03E0: 'Actions (Zhuhai) Technology Co., Limited',
- 0x03E1: 'SPD Development Company Ltd',
- 0x03E2: 'Sensoan Oy',
- 0x03E3: 'Qualcomm Life Inc',
- 0x03E4: 'Chip-ing AG',
- 0x03E5: 'ffly4u',
- 0x03E6: 'IoT Instruments Oy',
- 0x03E7: 'TRUE Fitness Technology',
- 0x03E8: 'Reiner Kartengeraete GmbH & Co. KG.',
- 0x03E9: 'SHENZHEN LEMONJOY TECHNOLOGY CO., LTD.',
- 0x03EA: 'Hello Inc.',
- 0x03EB: 'Evollve Inc.',
- 0x03EC: 'Jigowatts Inc.',
- 0x03ED: 'BASIC MICRO.COM,INC.',
- 0x03EE: 'CUBE TECHNOLOGIES',
- 0x03EF: 'foolography GmbH',
- 0x03F0: 'CLINK',
- 0x03F1: 'Hestan Smart Cooking Inc.',
- 0x03F2: 'WindowMaster A/S',
- 0x03F3: 'Flowscape AB',
- 0x03F4: 'PAL Technologies Ltd',
- 0x03F5: 'WHERE, Inc.',
- 0x03F6: 'Iton Technology Corp.',
- 0x03F7: 'Owl Labs Inc.',
- 0x03F8: 'Rockford Corp.',
- 0x03F9: 'Becon Technologies Co.,Ltd.',
- 0x03FA: 'Vyassoft Technologies Inc',
- 0x03FB: 'Nox Medical',
- 0x03FC: 'Kimberly-Clark',
- 0x03FD: 'Trimble Navigation Ltd.',
- 0x03FE: 'Littelfuse',
- 0x03FF: 'Withings',
- 0x0400: 'i-developer IT Beratung UG',
- 0x0402: 'Sears Holdings Corporation',
- 0x0403: 'Gantner Electronic GmbH',
- 0x0404: 'Authomate Inc',
- 0x0405: 'Vertex International, Inc.',
- 0x0406: 'Airtago',
- 0x0407: 'Swiss Audio SA',
- 0x0408: 'ToGetHome Inc.',
- 0x0409: 'AXIS',
- 0x040A: 'Openmatics',
- 0x040B: 'Jana Care Inc.',
- 0x040C: 'Senix Corporation',
- 0x040D: 'NorthStar Battery Company, LLC',
- 0x040E: 'SKF (U.K.) Limited',
- 0x040F: 'CO-AX Technology, Inc.',
- 0x0410: 'Fender Musical Instruments',
- 0x0411: 'Luidia Inc',
- 0x0412: 'SEFAM',
- 0x0413: 'Wireless Cables Inc',
- 0x0414: 'Lightning Protection International Pty Ltd',
- 0x0415: 'Uber Technologies Inc',
- 0x0416: 'SODA GmbH',
- 0x0417: 'Fatigue Science',
- 0x0418: 'Alpine Electronics Inc.',
- 0x0419: 'Novalogy LTD',
- 0x041A: 'Friday Labs Limited',
- 0x041B: 'OrthoAccel Technologies',
- 0x041C: 'WaterGuru, Inc.',
- 0x041D: 'Benning Elektrotechnik und Elektronik GmbH & Co. KG',
- 0x041E: 'Dell Computer Corporation',
- 0x041F: 'Kopin Corporation',
- 0x0420: 'TecBakery GmbH',
- 0x0421: 'Backbone Labs, Inc.',
- 0x0422: 'DELSEY SA',
- 0x0423: 'Chargifi Limited',
- 0x0424: 'Trainesense Ltd.',
- 0x0425: 'Unify Software and Solutions GmbH & Co. KG',
- 0x0426: 'Husqvarna AB',
- 0x0427: 'Focus fleet and fuel management inc',
- 0x0428: 'SmallLoop, LLC',
- 0x0429: 'Prolon Inc.',
- 0x042A: 'BD Medical',
- 0x042B: 'iMicroMed Incorporated',
- 0x042C: 'Ticto N.V.',
- 0x042D: 'Meshtech AS',
- 0x042E: 'MemCachier Inc.',
- 0x042F: 'Danfoss A/S',
- 0x0430: 'SnapStyk Inc.',
- 0x0431: 'Amyway Corporation',
- 0x0432: 'Silk Labs, Inc.',
- 0x0433: 'Pillsy Inc.',
- 0x0434: 'Hatch Baby, Inc.',
- 0x0435: 'Blocks Wearables Ltd.',
- 0x0436: 'Drayson Technologies (Europe) Limited',
- 0x0437: 'eBest IOT Inc.',
- 0x0438: 'Helvar Ltd',
- 0x0439: 'Radiance Technologies',
- 0x043A: 'Nuheara Limited',
- 0x043B: 'Appside co., ltd.',
- 0x043C: 'DeLaval',
- 0x043D: 'Coiler Corporation',
- 0x043E: 'Thermomedics, Inc.',
- 0x043F: 'Tentacle Sync GmbH',
- 0x0440: 'Valencell, Inc.',
- 0x0441: 'iProtoXi Oy',
- 0x0442: 'SECOM CO., LTD.',
- 0x0443: 'Tucker International LLC',
- 0x0444: 'Metanate Limited',
- 0x0445: 'Kobian Canada Inc.',
- 0x0446: 'NETGEAR, Inc.',
- 0x0447: 'Fabtronics Australia Pty Ltd',
- 0x0448: 'Grand Centrix GmbH',
- 0x0449: '1UP USA.com llc',
- 0x044A: 'SHIMANO INC.',
- 0x044B: 'Nain Inc.',
- 0x044C: 'LifeStyle Lock, LLC',
- 0x044D: 'VEGA Grieshaber KG',
- 0x044E: 'Xtrava Inc.',
- 0x044F: 'TTS Tooltechnic Systems AG & Co. KG',
- 0x0450: 'Teenage Engineering AB',
- 0x0451: 'Tunstall Nordic AB',
- 0x0452: 'Svep Design Center AB',
- 0x0453: 'GreenPeak Technologies BV',
- 0x0454: 'Sphinx Electronics GmbH & Co KG',
- 0x0455: 'Atomation',
- 0x0456: 'Nemik Consulting Inc',
- 0x0457: 'RF INNOVATION',
- 0x0458: 'Mini Solution Co., Ltd.',
- 0x0459: 'Lumenetix, Inc',
- 0x045A: '2048450 Ontario Inc',
- 0x045B: 'SPACEEK LTD',
- 0x045C: 'Delta T Corporation',
- 0x045D: 'Boston Scientific Corporation',
- 0x045E: 'Nuviz, Inc.',
- 0x045F: 'Real Time Automation, Inc.',
- 0x0460: 'Kolibree',
- 0x0461: 'vhf elektronik GmbH',
- 0x0462: 'Bonsai Systems GmbH',
- 0x0463: 'Fathom Systems Inc.',
- 0x0464: 'Bellman & Symfon',
- 0x0465: 'International Forte Group LLC',
- 0x0466: 'CycleLabs Solutions inc.',
- 0x0467: 'Codenex Oy',
- 0x0468: 'Kynesim Ltd',
- 0x0469: 'Palago AB',
- 0x046A: 'INSIGMA INC.',
- 0x046B: 'PMD Solutions',
- 0x046C: 'Qingdao Realtime Technology Co., Ltd.',
- 0x046D: 'BEGA Gantenbrink-Leuchten KG',
- 0x046E: 'Pambor Ltd.',
- 0xFFFF: 'SPECIAL USE/DEFAULT'
-};
-
-
-/***/ }),
-
-/***/ 93739:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// cpu.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 4. CPU
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const fs = __nccwpck_require__(79896);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-let _cpu_speed = 0;
-let _current_cpu = {
- user: 0,
- nice: 0,
- system: 0,
- idle: 0,
- irq: 0,
- steal: 0,
- guest: 0,
- load: 0,
- tick: 0,
- ms: 0,
- currentLoad: 0,
- currentLoadUser: 0,
- currentLoadSystem: 0,
- currentLoadNice: 0,
- currentLoadIdle: 0,
- currentLoadIrq: 0,
- currentLoadSteal: 0,
- currentLoadGuest: 0,
- rawCurrentLoad: 0,
- rawCurrentLoadUser: 0,
- rawCurrentLoadSystem: 0,
- rawCurrentLoadNice: 0,
- rawCurrentLoadIdle: 0,
- rawCurrentLoadIrq: 0,
- rawCurrentLoadSteal: 0,
- rawCurrentLoadGuest: 0
-};
-let _cpus = [];
-let _corecount = 0;
-
-const AMDBaseFrequencies = {
- '8346': '1.8',
- '8347': '1.9',
- '8350': '2.0',
- '8354': '2.2',
- '8356|SE': '2.4',
- '8356': '2.3',
- '8360': '2.5',
- '2372': '2.1',
- '2373': '2.1',
- '2374': '2.2',
- '2376': '2.3',
- '2377': '2.3',
- '2378': '2.4',
- '2379': '2.4',
- '2380': '2.5',
- '2381': '2.5',
- '2382': '2.6',
- '2384': '2.7',
- '2386': '2.8',
- '2387': '2.8',
- '2389': '2.9',
- '2393': '3.1',
- '8374': '2.2',
- '8376': '2.3',
- '8378': '2.4',
- '8379': '2.4',
- '8380': '2.5',
- '8381': '2.5',
- '8382': '2.6',
- '8384': '2.7',
- '8386': '2.8',
- '8387': '2.8',
- '8389': '2.9',
- '8393': '3.1',
- '2419EE': '1.8',
- '2423HE': '2.0',
- '2425HE': '2.1',
- '2427': '2.2',
- '2431': '2.4',
- '2435': '2.6',
- '2439SE': '2.8',
- '8425HE': '2.1',
- '8431': '2.4',
- '8435': '2.6',
- '8439SE': '2.8',
- '4122': '2.2',
- '4130': '2.6',
- '4162EE': '1.7',
- '4164EE': '1.8',
- '4170HE': '2.1',
- '4174HE': '2.3',
- '4176HE': '2.4',
- '4180': '2.6',
- '4184': '2.8',
- '6124HE': '1.8',
- '6128HE': '2.0',
- '6132HE': '2.2',
- '6128': '2.0',
- '6134': '2.3',
- '6136': '2.4',
- '6140': '2.6',
- '6164HE': '1.7',
- '6166HE': '1.8',
- '6168': '1.9',
- '6172': '2.1',
- '6174': '2.2',
- '6176': '2.3',
- '6176SE': '2.3',
- '6180SE': '2.5',
- '3250': '2.5',
- '3260': '2.7',
- '3280': '2.4',
- '4226': '2.7',
- '4228': '2.8',
- '4230': '2.9',
- '4234': '3.1',
- '4238': '3.3',
- '4240': '3.4',
- '4256': '1.6',
- '4274': '2.5',
- '4276': '2.6',
- '4280': '2.8',
- '4284': '3.0',
- '6204': '3.3',
- '6212': '2.6',
- '6220': '3.0',
- '6234': '2.4',
- '6238': '2.6',
- '6262HE': '1.6',
- '6272': '2.1',
- '6274': '2.2',
- '6276': '2.3',
- '6278': '2.4',
- '6282SE': '2.6',
- '6284SE': '2.7',
- '6308': '3.5',
- '6320': '2.8',
- '6328': '3.2',
- '6338P': '2.3',
- '6344': '2.6',
- '6348': '2.8',
- '6366': '1.8',
- '6370P': '2.0',
- '6376': '2.3',
- '6378': '2.4',
- '6380': '2.5',
- '6386': '2.8',
- 'FX|4100': '3.6',
- 'FX|4120': '3.9',
- 'FX|4130': '3.8',
- 'FX|4150': '3.8',
- 'FX|4170': '4.2',
- 'FX|6100': '3.3',
- 'FX|6120': '3.6',
- 'FX|6130': '3.6',
- 'FX|6200': '3.8',
- 'FX|8100': '2.8',
- 'FX|8120': '3.1',
- 'FX|8140': '3.2',
- 'FX|8150': '3.6',
- 'FX|8170': '3.9',
- 'FX|4300': '3.8',
- 'FX|4320': '4.0',
- 'FX|4350': '4.2',
- 'FX|6300': '3.5',
- 'FX|6350': '3.9',
- 'FX|8300': '3.3',
- 'FX|8310': '3.4',
- 'FX|8320': '3.5',
- 'FX|8350': '4.0',
- 'FX|8370': '4.0',
- 'FX|9370': '4.4',
- 'FX|9590': '4.7',
- 'FX|8320E': '3.2',
- 'FX|8370E': '3.3',
-
- // ZEN Desktop CPUs
- '1200': '3.1',
- 'Pro 1200': '3.1',
- '1300X': '3.5',
- 'Pro 1300': '3.5',
- '1400': '3.2',
- '1500X': '3.5',
- 'Pro 1500': '3.5',
- '1600': '3.2',
- '1600X': '3.6',
- 'Pro 1600': '3.2',
- '1700': '3.0',
- 'Pro 1700': '3.0',
- '1700X': '3.4',
- 'Pro 1700X': '3.4',
- '1800X': '3.6',
- '1900X': '3.8',
- '1920': '3.2',
- '1920X': '3.5',
- '1950X': '3.4',
-
- // ZEN Desktop APUs
- '200GE': '3.2',
- 'Pro 200GE': '3.2',
- '220GE': '3.4',
- '240GE': '3.5',
- '3000G': '3.5',
- '300GE': '3.4',
- '3050GE': '3.4',
- '2200G': '3.5',
- 'Pro 2200G': '3.5',
- '2200GE': '3.2',
- 'Pro 2200GE': '3.2',
- '2400G': '3.6',
- 'Pro 2400G': '3.6',
- '2400GE': '3.2',
- 'Pro 2400GE': '3.2',
-
- // ZEN Mobile APUs
- 'Pro 200U': '2.3',
- '300U': '2.4',
- '2200U': '2.5',
- '3200U': '2.6',
- '2300U': '2.0',
- 'Pro 2300U': '2.0',
- '2500U': '2.0',
- 'Pro 2500U': '2.2',
- '2600H': '3.2',
- '2700U': '2.0',
- 'Pro 2700U': '2.2',
- '2800H': '3.3',
-
- // ZEN Server Processors
- '7351': '2.4',
- '7351P': '2.4',
- '7401': '2.0',
- '7401P': '2.0',
- '7551P': '2.0',
- '7551': '2.0',
- '7251': '2.1',
- '7261': '2.5',
- '7281': '2.1',
- '7301': '2.2',
- '7371': '3.1',
- '7451': '2.3',
- '7501': '2.0',
- '7571': '2.2',
- '7601': '2.2',
-
- // ZEN Embedded Processors
- 'V1500B': '2.2',
- 'V1780B': '3.35',
- 'V1202B': '2.3',
- 'V1404I': '2.0',
- 'V1605B': '2.0',
- 'V1756B': '3.25',
- 'V1807B': '3.35',
-
- '3101': '2.1',
- '3151': '2.7',
- '3201': '1.5',
- '3251': '2.5',
- '3255': '2.5',
- '3301': '2.0',
- '3351': '1.9',
- '3401': '1.85',
- '3451': '2.15',
-
- // ZEN+ Desktop
- '1200|AF': '3.1',
- '2300X': '3.5',
- '2500X': '3.6',
- '2600': '3.4',
- '2600E': '3.1',
- '1600|AF': '3.2',
- '2600X': '3.6',
- '2700': '3.2',
- '2700E': '2.8',
- 'Pro 2700': '3.2',
- '2700X': '3.7',
- 'Pro 2700X': '3.6',
- '2920X': '3.5',
- '2950X': '3.5',
- '2970WX': '3.0',
- '2990WX': '3.0',
-
- // ZEN+ Desktop APU
- 'Pro 300GE': '3.4',
- 'Pro 3125GE': '3.4',
- '3150G': '3.5',
- 'Pro 3150G': '3.5',
- '3150GE': '3.3',
- 'Pro 3150GE': '3.3',
- '3200G': '3.6',
- 'Pro 3200G': '3.6',
- '3200GE': '3.3',
- 'Pro 3200GE': '3.3',
- '3350G': '3.6',
- 'Pro 3350G': '3.6',
- '3350GE': '3.3',
- 'Pro 3350GE': '3.3',
- '3400G': '3.7',
- 'Pro 3400G': '3.7',
- '3400GE': '3.3',
- 'Pro 3400GE': '3.3',
-
- // ZEN+ Mobile
- '3300U': '2.1',
- 'PRO 3300U': '2.1',
- '3450U': '2.1',
- '3500U': '2.1',
- 'PRO 3500U': '2.1',
- '3500C': '2.1',
- '3550H': '2.1',
- '3580U': '2.1',
- '3700U': '2.3',
- 'PRO 3700U': '2.3',
- '3700C': '2.3',
- '3750H': '2.3',
- '3780U': '2.3',
-
- // ZEN2 Desktop CPUS
- '3100': '3.6',
- '3300X': '3.8',
- '3500': '3.6',
- '3500X': '3.6',
- '3600': '3.6',
- 'Pro 3600': '3.6',
- '3600X': '3.8',
- '3600XT': '3.8',
- 'Pro 3700': '3.6',
- '3700X': '3.6',
- '3800X': '3.9',
- '3800XT': '3.9',
- '3900': '3.1',
- 'Pro 3900': '3.1',
- '3900X': '3.8',
- '3900XT': '3.8',
- '3950X': '3.5',
- '3960X': '3.8',
- '3970X': '3.7',
- '3990X': '2.9',
- '3945WX': '4.0',
- '3955WX': '3.9',
- '3975WX': '3.5',
- '3995WX': '2.7',
-
- // ZEN2 Desktop APUs
- '4300GE': '3.5',
- 'Pro 4300GE': '3.5',
- '4300G': '3.8',
- 'Pro 4300G': '3.8',
- '4600GE': '3.3',
- 'Pro 4650GE': '3.3',
- '4600G': '3.7',
- 'Pro 4650G': '3.7',
- '4700GE': '3.1',
- 'Pro 4750GE': '3.1',
- '4700G': '3.6',
- 'Pro 4750G': '3.6',
- '4300U': '2.7',
- '4450U': '2.5',
- 'Pro 4450U': '2.5',
- '4500U': '2.3',
- '4600U': '2.1',
- 'PRO 4650U': '2.1',
- '4680U': '2.1',
- '4600HS': '3.0',
- '4600H': '3.0',
- '4700U': '2.0',
- 'PRO 4750U': '1.7',
- '4800U': '1.8',
- '4800HS': '2.9',
- '4800H': '2.9',
- '4900HS': '3.0',
- '4900H': '3.3',
- '5300U': '2.6',
- '5500U': '2.1',
- '5700U': '1.8',
-
- // ZEN2 - EPYC
- '7232P': '3.1',
- '7302P': '3.0',
- '7402P': '2.8',
- '7502P': '2.5',
- '7702P': '2.0',
- '7252': '3.1',
- '7262': '3.2',
- '7272': '2.9',
- '7282': '2.8',
- '7302': '3.0',
- '7352': '2.3',
- '7402': '2.8',
- '7452': '2.35',
- '7502': '2.5',
- '7532': '2.4',
- '7542': '2.9',
- '7552': '2.2',
- '7642': '2.3',
- '7662': '2.0',
- '7702': '2.0',
- '7742': '2.25',
- '7H12': '2.6',
- '7F32': '3.7',
- '7F52': '3.5',
- '7F72': '3.2',
-
- // Epyc (Milan)
-
- '7773X': '2.2',
- '7763': '2.45',
- '7713': '2.0',
- '7713P': '2.0',
- '7663': '2.0',
- '7643': '2.3',
- '7573X': '2.8',
- '75F3': '2.95',
- '7543': '2.8',
- '7543P': '2.8',
- '7513': '2.6',
- '7473X': '2.8',
- '7453': '2.75',
- '74F3': '3.2',
- '7443': '2.85',
- '7443P': '2.85',
- '7413': '2.65',
- '7373X': '3.05',
- '73F3': '3.5',
- '7343': '3.2',
- '7313': '3.0',
- '7313P': '3.0',
- '72F3': '3.7',
-
- // ZEN3
- '5600X': '3.7',
- '5800X': '3.8',
- '5900X': '3.7',
- '5950X': '3.4',
- '5945WX': '4.1',
- '5955WX': '4.0',
- '5965WX': '3.8',
- '5975WX': '3.6',
- '5995WX': '2.7',
-
- '7960X': '4.2',
- '7970X': '4.0',
- '7980X': '3.2',
-
- '7965WX': '4.2',
- '7975WX': '4.0',
- '7985WX': '3.2',
- '7995WX': '2.5',
-
- // ZEN4
- '9754': '2.25',
- '9754S': '2.25',
- '9734': '2.2',
- '9684X': '2.55',
- '9384X': '3.1',
- '9184X': '3.55',
- '9654P': '2.4',
- '9654': '2.4',
- '9634': '2.25',
- '9554P': '3.1',
- '9554': '3.1',
- '9534': '2.45',
- '9474F': '3.6',
- '9454P': '2.75',
- '9454': '2.75',
- '9374F': '3.85',
- '9354P': '3.25',
- '9354': '3.25',
- '9334': '2.7',
- '9274F': '4.05',
- '9254': '2.9',
- '9224': '2.5',
- '9174F': '4.1',
- '9124': '3.0'
-};
-
-const socketTypes = {
- 1: 'Other',
- 2: 'Unknown',
- 3: 'Daughter Board',
- 4: 'ZIF Socket',
- 5: 'Replacement/Piggy Back',
- 6: 'None',
- 7: 'LIF Socket',
- 8: 'Slot 1',
- 9: 'Slot 2',
- 10: '370 Pin Socket',
- 11: 'Slot A',
- 12: 'Slot M',
- 13: '423',
- 14: 'A (Socket 462)',
- 15: '478',
- 16: '754',
- 17: '940',
- 18: '939',
- 19: 'mPGA604',
- 20: 'LGA771',
- 21: 'LGA775',
- 22: 'S1',
- 23: 'AM2',
- 24: 'F (1207)',
- 25: 'LGA1366',
- 26: 'G34',
- 27: 'AM3',
- 28: 'C32',
- 29: 'LGA1156',
- 30: 'LGA1567',
- 31: 'PGA988A',
- 32: 'BGA1288',
- 33: 'rPGA988B',
- 34: 'BGA1023',
- 35: 'BGA1224',
- 36: 'LGA1155',
- 37: 'LGA1356',
- 38: 'LGA2011',
- 39: 'FS1',
- 40: 'FS2',
- 41: 'FM1',
- 42: 'FM2',
- 43: 'LGA2011-3',
- 44: 'LGA1356-3',
- 45: 'LGA1150',
- 46: 'BGA1168',
- 47: 'BGA1234',
- 48: 'BGA1364',
- 49: 'AM4',
- 50: 'LGA1151',
- 51: 'BGA1356',
- 52: 'BGA1440',
- 53: 'BGA1515',
- 54: 'LGA3647-1',
- 55: 'SP3',
- 56: 'SP3r2',
- 57: 'LGA2066',
- 58: 'BGA1392',
- 59: 'BGA1510',
- 60: 'BGA1528',
- 61: 'LGA4189',
- 62: 'LGA1200',
- 63: 'LGA4677',
- 64: 'LGA1700',
- 65: 'BGA1744',
- 66: 'BGA1781',
- 67: 'BGA1211',
- 68: 'BGA2422',
- 69: 'LGA1211',
- 70: 'LGA2422',
- 71: 'LGA5773',
- 72: 'BGA5773',
-};
-
-const socketTypesByName = {
- 'LGA1150': 'i7-5775C i3-4340 i3-4170 G3250 i3-4160T i3-4160 E3-1231 G3258 G3240 i7-4790S i7-4790K i7-4790 i5-4690K i5-4690 i5-4590T i5-4590S i5-4590 i5-4460 i3-4360 i3-4150 G1820 G3420 G3220 i7-4771 i5-4440 i3-4330 i3-4130T i3-4130 E3-1230 i7-4770S i7-4770K i7-4770 i5-4670K i5-4670 i5-4570T i5-4570S i5-4570 i5-4430',
- 'LGA1151': 'i9-9900KS E-2288G E-2224 G5420 i9-9900T i9-9900 i7-9700T i7-9700F i7-9700E i7-9700 i5-9600 i5-9500T i5-9500F i5-9500 i5-9400T i3-9350K i3-9300 i3-9100T i3-9100F i3-9100 G4930 i9-9900KF i7-9700KF i5-9600KF i5-9400F i5-9400 i3-9350KF i9-9900K i7-9700K i5-9600K G5500 G5400 i7-8700T i7-8086K i5-8600 i5-8500T i5-8500 i5-8400T i3-8300 i3-8100T G4900 i7-8700K i7-8700 i5-8600K i5-8400 i3-8350K i3-8100 E3-1270 G4600 G4560 i7-7700T i7-7700K i7-7700 i5-7600K i5-7600 i5-7500T i5-7500 i5-7400 i3-7350K i3-7300 i3-7100T i3-7100 G3930 G3900 G4400 i7-6700T i7-6700K i7-6700 i5-6600K i5-6600 i5-6500T i5-6500 i5-6400T i5-6400 i3-6300 i3-6100T i3-6100 E3-1270 E3-1270 T4500 T4400',
- '1155': 'G440 G460 G465 G470 G530T G540T G550T G1610T G1620T G530 G540 G1610 G550 G1620 G555 G1630 i3-2100T i3-2120T i3-3220T i3-3240T i3-3250T i3-2100 i3-2105 i3-2102 i3-3210 i3-3220 i3-2125 i3-2120 i3-3225 i3-2130 i3-3245 i3-3240 i3-3250 i5-3570T i5-2500T i5-2400S i5-2405S i5-2390T i5-3330S i5-2500S i5-3335S i5-2300 i5-3450S i5-3340S i5-3470S i5-3475S i5-3470T i5-2310 i5-3550S i5-2320 i5-3330 i5-3350P i5-3450 i5-2400 i5-3340 i5-3570S i5-2380P i5-2450P i5-3470 i5-2500K i5-3550 i5-2500 i5-3570 i5-3570K i5-2550K i7-3770T i7-2600S i7-3770S i7-2600K i7-2600 i7-3770 i7-3770K i7-2700K G620T G630T G640T G2020T G645T G2100T G2030T G622 G860T G620 G632 G2120T G630 G640 G2010 G840 G2020 G850 G645 G2030 G860 G2120 G870 G2130 G2140 E3-1220L E3-1220L E3-1260L E3-1265L E3-1220 E3-1225 E3-1220 E3-1235 E3-1225 E3-1230 E3-1230 E3-1240 E3-1245 E3-1270 E3-1275 E3-1240 E3-1245 E3-1270 E3-1280 E3-1275 E3-1290 E3-1280 E3-1290'
-};
-
-function getSocketTypesByName(str) {
- let result = '';
- for (const key in socketTypesByName) {
- const names = socketTypesByName[key].split(' ');
- names.forEach(element => {
- if (str.indexOf(element) >= 0) {
- result = key;
- }
- });
- }
- return result;
-}
-
-function cpuManufacturer(str) {
- let result = str;
- str = str.toLowerCase();
-
- if (str.indexOf('intel') >= 0) { result = 'Intel'; }
- if (str.indexOf('amd') >= 0) { result = 'AMD'; }
- if (str.indexOf('qemu') >= 0) { result = 'QEMU'; }
- if (str.indexOf('hygon') >= 0) { result = 'Hygon'; }
- if (str.indexOf('centaur') >= 0) { result = 'WinChip/Via'; }
- if (str.indexOf('vmware') >= 0) { result = 'VMware'; }
- if (str.indexOf('Xen') >= 0) { result = 'Xen Hypervisor'; }
- if (str.indexOf('tcg') >= 0) { result = 'QEMU'; }
- if (str.indexOf('apple') >= 0) { result = 'Apple'; }
- if (str.indexOf('sifive') >= 0) { result = 'SiFive'; }
- if (str.indexOf('thead') >= 0) { result = 'T-Head'; }
- if (str.indexOf('andestech') >= 0) { result = 'Andes Technology'; }
-
- return result;
-}
-
-function cpuBrandManufacturer(res) {
- res.brand = res.brand.replace(/\(R\)+/g, '®').replace(/\s+/g, ' ').trim();
- res.brand = res.brand.replace(/\(TM\)+/g, '™').replace(/\s+/g, ' ').trim();
- res.brand = res.brand.replace(/\(C\)+/g, '©').replace(/\s+/g, ' ').trim();
- res.brand = res.brand.replace(/CPU+/g, '').replace(/\s+/g, ' ').trim();
- res.manufacturer = cpuManufacturer(res.brand);
-
- let parts = res.brand.split(' ');
- parts.shift();
- res.brand = parts.join(' ');
- return res;
-}
-
-function getAMDSpeed(brand) {
- let result = '0';
- for (let key in AMDBaseFrequencies) {
- if ({}.hasOwnProperty.call(AMDBaseFrequencies, key)) {
- let parts = key.split('|');
- let found = 0;
- parts.forEach(item => {
- if (brand.indexOf(item) > -1) {
- found++;
- }
- });
- if (found === parts.length) {
- result = AMDBaseFrequencies[key];
- }
- }
- }
- return parseFloat(result);
-}
-
-// --------------------------
-// CPU - brand, speed
-
-function getCpu() {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- const UNKNOWN = 'unknown';
- let result = {
- manufacturer: UNKNOWN,
- brand: UNKNOWN,
- vendor: '',
- family: '',
- model: '',
- stepping: '',
- revision: '',
- voltage: '',
- speed: 0,
- speedMin: 0,
- speedMax: 0,
- governor: '',
- cores: util.cores(),
- physicalCores: util.cores(),
- performanceCores: util.cores(),
- efficiencyCores: 0,
- processors: 1,
- socket: '',
- flags: '',
- virtualization: false,
- cache: {}
- };
- cpuFlags().then(flags => {
- result.flags = flags;
- result.virtualization = flags.indexOf('vmx') > -1 || flags.indexOf('svm') > -1;
- if (_darwin) {
- exec('sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min hw.packages hw.physicalcpu_max hw.ncpu hw.tbfrequency hw.cpufamily hw.cpusubfamily', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- const modelline = util.getValue(lines, 'machdep.cpu.brand_string');
- const modellineParts = modelline.split('@');
- result.brand = modellineParts[0].trim();
- const speed = modellineParts[1] ? modellineParts[1].trim() : '0';
- result.speed = parseFloat(speed.replace(/GHz+/g, ''));
- let tbFrequency = util.getValue(lines, 'hw.tbfrequency') / 1000000000.0;
- tbFrequency = tbFrequency < 0.1 ? tbFrequency * 100 : tbFrequency;
- result.speed = result.speed === 0 ? tbFrequency : result.speed;
-
- _cpu_speed = result.speed;
- result = cpuBrandManufacturer(result);
- result.speedMin = util.getValue(lines, 'hw.cpufrequency_min') ? (util.getValue(lines, 'hw.cpufrequency_min') / 1000000000.0) : result.speed;
- result.speedMax = util.getValue(lines, 'hw.cpufrequency_max') ? (util.getValue(lines, 'hw.cpufrequency_max') / 1000000000.0) : result.speed;
- result.vendor = util.getValue(lines, 'machdep.cpu.vendor') || 'Apple';
- result.family = util.getValue(lines, 'machdep.cpu.family') || util.getValue(lines, 'hw.cpufamily');
- result.model = util.getValue(lines, 'machdep.cpu.model');
- result.stepping = util.getValue(lines, 'machdep.cpu.stepping') || util.getValue(lines, 'hw.cpusubfamily');
- result.virtualization = true;
- const countProcessors = util.getValue(lines, 'hw.packages');
- const countCores = util.getValue(lines, 'hw.physicalcpu_max');
- const countThreads = util.getValue(lines, 'hw.ncpu');
- if (os.arch() === 'arm64') {
- result.socket = 'SOC';
- try {
- const clusters = execSync('ioreg -c IOPlatformDevice -d 3 -r | grep cluster-type').toString().split('\n');
- const efficiencyCores = clusters.filter(line => line.indexOf('"E"') >= 0).length;
- const performanceCores = clusters.filter(line => line.indexOf('"P"') >= 0).length;
- result.efficiencyCores = efficiencyCores;
- result.performanceCores = performanceCores;
- } catch (e) {
- util.noop();
- }
- }
- if (countProcessors) {
- result.processors = parseInt(countProcessors) || 1;
- }
- if (countCores && countThreads) {
- result.cores = parseInt(countThreads) || util.cores();
- result.physicalCores = parseInt(countCores) || util.cores();
- }
- cpuCache().then((res) => {
- result.cache = res;
- resolve(result);
- });
- });
- }
- if (_linux) {
- let modelline = '';
- let lines = [];
- if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; }
- exec('export LC_ALL=C; lscpu; echo -n "Governor: "; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null; echo; unset LC_ALL', function (error, stdout) {
- if (!error) {
- lines = stdout.toString().split('\n');
- }
- modelline = util.getValue(lines, 'model name') || modelline;
- modelline = util.getValue(lines, 'bios model name') || modelline;
- const modellineParts = modelline.split('@');
- result.brand = modellineParts[0].trim();
- result.speed = modellineParts[1] ? parseFloat(modellineParts[1].trim()) : 0;
- if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
- result.speed = getAMDSpeed(result.brand);
- }
- if (result.speed === 0) {
- const current = getCpuCurrentSpeedSync();
- if (current.avg !== 0) { result.speed = current.avg; }
- }
- _cpu_speed = result.speed;
- result.speedMin = Math.round(parseFloat(util.getValue(lines, 'cpu min mhz').replace(/,/g, '.')) / 10.0) / 100;
- result.speedMax = Math.round(parseFloat(util.getValue(lines, 'cpu max mhz').replace(/,/g, '.')) / 10.0) / 100;
-
- result = cpuBrandManufacturer(result);
- result.vendor = cpuManufacturer(util.getValue(lines, 'vendor id'));
-
- result.family = util.getValue(lines, 'cpu family');
- result.model = util.getValue(lines, 'model:');
- result.stepping = util.getValue(lines, 'stepping');
- result.revision = util.getValue(lines, 'cpu revision');
- result.cache.l1d = util.getValue(lines, 'l1d cache');
- if (result.cache.l1d) { result.cache.l1d = parseInt(result.cache.l1d) * (result.cache.l1d.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1d.indexOf('K') !== -1 ? 1024 : 1)); }
- result.cache.l1i = util.getValue(lines, 'l1i cache');
- if (result.cache.l1i) { result.cache.l1i = parseInt(result.cache.l1i) * (result.cache.l1i.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1i.indexOf('K') !== -1 ? 1024 : 1)); }
- result.cache.l2 = util.getValue(lines, 'l2 cache');
- if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2) * (result.cache.l2.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l2.indexOf('K') !== -1 ? 1024 : 1)); }
- result.cache.l3 = util.getValue(lines, 'l3 cache');
- if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3) * (result.cache.l3.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l3.indexOf('K') !== -1 ? 1024 : 1)); }
-
- const threadsPerCore = util.getValue(lines, 'thread(s) per core') || '1';
- const processors = util.getValue(lines, 'socket(s)') || '1';
- const threadsPerCoreInt = parseInt(threadsPerCore, 10); // threads per code (normally only for performance cores)
- const processorsInt = parseInt(processors, 10) || 1; // number of sockets / processor units in machine (normally 1)
- const coresPerSocket = parseInt(util.getValue(lines, 'core(s) per socket'), 10); // number of cores (e.g. 16 on i12900)
- result.physicalCores = coresPerSocket ? coresPerSocket * processorsInt : result.cores / threadsPerCoreInt;
- result.performanceCores = threadsPerCoreInt > 1 ? result.cores - result.physicalCores : result.cores;
- result.efficiencyCores = threadsPerCoreInt > 1 ? result.cores - (threadsPerCoreInt * result.performanceCores) : 0;
- result.processors = processorsInt;
- result.governor = util.getValue(lines, 'governor') || '';
-
- // Test Raspberry
- if (result.vendor === 'ARM') {
- const linesRpi = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
- const rPIRevision = util.decodePiCpuinfo(linesRpi);
- if (rPIRevision.model.toLowerCase().indexOf('raspberry') >= 0) {
- result.family = result.manufacturer;
- result.manufacturer = rPIRevision.manufacturer;
- result.brand = rPIRevision.processor;
- result.revision = rPIRevision.revisionCode;
- result.socket = 'SOC';
- }
- }
-
- // Test RISC-V
- if (util.getValue(lines, 'architecture') === 'riscv64') {
- const linesRiscV = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
- const uarch = util.getValue(linesRiscV, 'uarch') || '';
- if (uarch.indexOf(',') > -1) {
- const split = uarch.split(',');
- result.manufacturer = cpuManufacturer(split[0]);
- result.brand = split[1];
- }
- }
-
- // socket type
- let lines2 = [];
- exec('export LC_ALL=C; dmidecode –t 4 2>/dev/null | grep "Upgrade: Socket"; unset LC_ALL', function (error2, stdout2) {
- lines2 = stdout2.toString().split('\n');
- if (lines2 && lines2.length) {
- result.socket = util.getValue(lines2, 'Upgrade').replace('Socket', '').trim() || result.socket;
- }
- resolve(result);
- });
- });
- }
- if (_freebsd || _openbsd || _netbsd) {
- let modelline = '';
- let lines = [];
- if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; }
- exec('export LC_ALL=C; dmidecode -t 4; dmidecode -t 7 unset LC_ALL', function (error, stdout) {
- let cache = [];
- if (!error) {
- const data = stdout.toString().split('# dmidecode');
- const processor = data.length > 1 ? data[1] : '';
- cache = data.length > 2 ? data[2].split('Cache Information') : [];
-
- lines = processor.split('\n');
- }
- result.brand = modelline.split('@')[0].trim();
- result.speed = modelline.split('@')[1] ? parseFloat(modelline.split('@')[1].trim()) : 0;
- if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
- result.speed = getAMDSpeed(result.brand);
- }
- if (result.speed === 0) {
- const current = getCpuCurrentSpeedSync();
- if (current.avg !== 0) { result.speed = current.avg; }
- }
- _cpu_speed = result.speed;
- result.speedMin = result.speed;
- result.speedMax = Math.round(parseFloat(util.getValue(lines, 'max speed').replace(/Mhz/g, '')) / 10.0) / 100;
-
- result = cpuBrandManufacturer(result);
- result.vendor = cpuManufacturer(util.getValue(lines, 'manufacturer'));
- let sig = util.getValue(lines, 'signature');
- sig = sig.split(',');
- for (let i = 0; i < sig.length; i++) {
- sig[i] = sig[i].trim();
- }
- result.family = util.getValue(sig, 'Family', ' ', true);
- result.model = util.getValue(sig, 'Model', ' ', true);
- result.stepping = util.getValue(sig, 'Stepping', ' ', true);
- result.revision = '';
- const voltage = parseFloat(util.getValue(lines, 'voltage'));
- result.voltage = isNaN(voltage) ? '' : voltage.toFixed(2);
- for (let i = 0; i < cache.length; i++) {
- lines = cache[i].split('\n');
- let cacheType = util.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-');
- cacheType = cacheType.length ? cacheType[0] : '';
- const sizeParts = util.getValue(lines, 'Installed Size').split(' ');
- let size = parseInt(sizeParts[0], 10);
- const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb';
- size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1)));
- if (cacheType) {
- if (cacheType === 'l1') {
- result.cache[cacheType + 'd'] = size / 2;
- result.cache[cacheType + 'i'] = size / 2;
- } else {
- result.cache[cacheType] = size;
- }
- }
- }
- // socket type
- result.socket = util.getValue(lines, 'Upgrade').replace('Socket', '').trim();
- // # threads / # cores
- const threadCount = util.getValue(lines, 'thread count').trim();
- const coreCount = util.getValue(lines, 'core count').trim();
- if (coreCount && threadCount) {
- result.cores = parseInt(threadCount, 10);
- result.physicalCores = parseInt(coreCount, 10);
- }
- resolve(result);
- });
- }
- if (_sunos) {
- resolve(result);
- }
- if (_windows) {
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance Win32_processor | select Name, Revision, L2CacheSize, L3CacheSize, Manufacturer, MaxClockSpeed, Description, UpgradeMethod, Caption, NumberOfLogicalProcessors, NumberOfCores | fl'));
- workload.push(util.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl'));
- workload.push(util.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent'));
-
- Promise.all(
- workload
- ).then((data) => {
- let lines = data[0].split('\r\n');
- let name = util.getValue(lines, 'name', ':') || '';
- if (name.indexOf('@') >= 0) {
- result.brand = name.split('@')[0].trim();
- result.speed = name.split('@')[1] ? parseFloat(name.split('@')[1].trim()) : 0;
- _cpu_speed = result.speed;
- } else {
- result.brand = name.trim();
- result.speed = 0;
- }
- result = cpuBrandManufacturer(result);
- result.revision = util.getValue(lines, 'revision', ':');
- result.vendor = util.getValue(lines, 'manufacturer', ':');
- result.speedMax = Math.round(parseFloat(util.getValue(lines, 'maxclockspeed', ':').replace(/,/g, '.')) / 10.0) / 100;
- if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
- result.speed = getAMDSpeed(result.brand);
- }
- if (result.speed === 0) {
- result.speed = result.speedMax;
- }
- result.speedMin = result.speed;
-
- let description = util.getValue(lines, 'description', ':').split(' ');
- for (let i = 0; i < description.length; i++) {
- if (description[i].toLowerCase().startsWith('family') && (i + 1) < description.length && description[i + 1]) {
- result.family = description[i + 1];
- }
- if (description[i].toLowerCase().startsWith('model') && (i + 1) < description.length && description[i + 1]) {
- result.model = description[i + 1];
- }
- if (description[i].toLowerCase().startsWith('stepping') && (i + 1) < description.length && description[i + 1]) {
- result.stepping = description[i + 1];
- }
- }
- // socket type
- const socketId = util.getValue(lines, 'UpgradeMethod', ':');
- if (socketTypes[socketId]) {
- result.socket = socketTypes[socketId];
- }
- const socketByName = getSocketTypesByName(name);
- if (socketByName) {
- result.socket = socketByName;
- }
- // # threads / # cores
- const countProcessors = util.countLines(lines, 'Caption');
- const countThreads = util.getValue(lines, 'NumberOfLogicalProcessors', ':');
- const countCores = util.getValue(lines, 'NumberOfCores', ':');
- if (countProcessors) {
- result.processors = parseInt(countProcessors) || 1;
- }
- if (countCores && countThreads) {
- result.cores = parseInt(countThreads) || util.cores();
- result.physicalCores = parseInt(countCores) || util.cores();
- }
- if (countProcessors > 1) {
- result.cores = result.cores * countProcessors;
- result.physicalCores = result.physicalCores * countProcessors;
- }
- result.cache = parseWinCache(data[0], data[1]);
- const hyperv = data[2] ? data[2].toString().toLowerCase() : '';
- result.virtualization = hyperv.indexOf('true') !== -1;
-
- resolve(result);
- });
- } catch (e) {
- resolve(result);
- }
- }
- });
- });
- });
-}
-
-// --------------------------
-// CPU - Processor Data
-
-function cpu(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- getCpu().then(result => {
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- });
-}
-
-exports.cpu = cpu;
-
-// --------------------------
-// CPU - current speed - in GHz
-
-function getCpuCurrentSpeedSync() {
-
- let cpus = os.cpus();
- let minFreq = 999999999;
- let maxFreq = 0;
- let avgFreq = 0;
- let cores = [];
-
- if (cpus && cpus.length) {
- for (let i in cpus) {
- if ({}.hasOwnProperty.call(cpus, i)) {
- let freq = cpus[i].speed > 100 ? (cpus[i].speed + 1) / 1000 : cpus[i].speed / 10;
- avgFreq = avgFreq + freq;
- if (freq > maxFreq) { maxFreq = freq; }
- if (freq < minFreq) { minFreq = freq; }
- cores.push(parseFloat(freq.toFixed(2)));
- }
- }
- avgFreq = avgFreq / cpus.length;
- return {
- min: parseFloat(minFreq.toFixed(2)),
- max: parseFloat(maxFreq.toFixed(2)),
- avg: parseFloat((avgFreq).toFixed(2)),
- cores: cores
- };
- } else {
- return {
- min: 0,
- max: 0,
- avg: 0,
- cores: cores
- };
- }
-}
-
-function cpuCurrentSpeed(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = getCpuCurrentSpeedSync();
- if (result.avg === 0 && _cpu_speed !== 0) {
- const currCpuSpeed = parseFloat(_cpu_speed);
- result = {
- min: currCpuSpeed,
- max: currCpuSpeed,
- avg: currCpuSpeed,
- cores: []
- };
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- });
-}
-
-exports.cpuCurrentSpeed = cpuCurrentSpeed;
-
-// --------------------------
-// CPU - temperature
-// if sensors are installed
-
-function cpuTemperature(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
- main: null,
- cores: [],
- max: null,
- socket: [],
- chipset: null
- };
- if (_linux) {
- // CPU Chipset, Socket
- try {
- const cmd = 'cat /sys/class/thermal/thermal_zone*/type 2>/dev/null; echo "-----"; cat /sys/class/thermal/thermal_zone*/temp 2>/dev/null;';
- const parts = execSync(cmd, util.execOptsLinux).toString().split('-----\n');
- if (parts.length === 2) {
- const lines = parts[0].split('\n');
- const lines2 = parts[1].split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim();
- if (line.startsWith('acpi') && lines2[i]) {
- result.socket.push(Math.round(parseInt(lines2[i], 10) / 100) / 10);
- }
- if (line.startsWith('pch') && lines2[i]) {
- result.chipset = Math.round(parseInt(lines2[i], 10) / 100) / 10;
- }
- }
- }
- } catch (e) {
- util.noop();
- }
-
- const cmd = 'for mon in /sys/class/hwmon/hwmon*; do for label in "$mon"/temp*_label; do if [ -f $label ]; then value=${label%_*}_input; echo $(cat "$label")___$(cat "$value"); fi; done; done;';
- try {
- exec(cmd, function (error, stdout) {
- stdout = stdout.toString();
- const tdiePos = stdout.toLowerCase().indexOf('tdie');
- if (tdiePos !== -1) {
- stdout = stdout.substring(tdiePos);
- }
- let lines = stdout.split('\n');
- let tctl = 0;
- lines.forEach(line => {
- const parts = line.split('___');
- const label = parts[0];
- const value = parts.length > 1 && parts[1] ? parts[1] : '0';
- if (value && label && label.toLowerCase() === 'tctl') {
- tctl = result.main = Math.round(parseInt(value, 10) / 100) / 10;
- }
- if (value && (label === undefined || (label && label.toLowerCase().startsWith('core')))) {
- result.cores.push(Math.round(parseInt(value, 10) / 100) / 10);
- } else if (value && label && result.main === null && (label.toLowerCase().indexOf('package') >= 0 || label.toLowerCase().indexOf('physical') >= 0 || label.toLowerCase() === 'tccd1')) {
- result.main = Math.round(parseInt(value, 10) / 100) / 10;
- }
- });
- if (tctl && result.main === null) {
- result.main = tctl;
- }
-
- if (result.cores.length > 0) {
- if (result.main === null) {
- result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length);
- }
- let maxtmp = Math.max.apply(Math, result.cores);
- result.max = (maxtmp > result.main) ? maxtmp : result.main;
- }
- if (result.main !== null) {
- if (result.max === null) {
- result.max = result.main;
- }
- if (callback) { callback(result); }
- resolve(result);
- return;
- }
- exec('sensors', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- let tdieTemp = null;
- let newSectionStarts = true;
- let section = '';
- lines.forEach(function (line) {
- // determine section
- if (line.trim() === '') {
- newSectionStarts = true;
- } else if (newSectionStarts) {
- if (line.trim().toLowerCase().startsWith('acpi')) { section = 'acpi'; }
- if (line.trim().toLowerCase().startsWith('pch')) { section = 'pch'; }
- if (line.trim().toLowerCase().startsWith('core')) { section = 'core'; }
- newSectionStarts = false;
- }
- let regex = /[+-]([^°]*)/g;
- let temps = line.match(regex);
- let firstPart = line.split(':')[0].toUpperCase();
- if (section === 'acpi') {
- // socket temp
- if (firstPart.indexOf('TEMP') !== -1) {
- result.socket.push(parseFloat(temps));
- }
- } else if (section === 'pch') {
- // chipset temp
- if (firstPart.indexOf('TEMP') !== -1 && !result.chipset) {
- result.chipset = parseFloat(temps);
- }
- }
- // cpu temp
- if (firstPart.indexOf('PHYSICAL') !== -1 || firstPart.indexOf('PACKAGE') !== -1) {
- result.main = parseFloat(temps);
- }
- if (firstPart.indexOf('CORE ') !== -1) {
- result.cores.push(parseFloat(temps));
- }
- if (firstPart.indexOf('TDIE') !== -1 && tdieTemp === null) {
- tdieTemp = parseFloat(temps);
- }
- });
- if (result.cores.length > 0) {
- result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length);
- let maxtmp = Math.max.apply(Math, result.cores);
- result.max = (maxtmp > result.main) ? maxtmp : result.main;
- } else {
- if (result.main === null && tdieTemp !== null) {
- result.main = tdieTemp;
- result.max = tdieTemp;
- }
- }
- if (result.main !== null || result.max !== null) {
- if (callback) { callback(result); }
- resolve(result);
- return;
- }
- }
- fs.stat('/sys/class/thermal/thermal_zone0/temp', function (err) {
- if (err === null) {
- fs.readFile('/sys/class/thermal/thermal_zone0/temp', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines.length > 0) {
- result.main = parseFloat(lines[0]) / 1000.0;
- result.max = result.main;
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- exec('/opt/vc/bin/vcgencmd measure_temp', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines.length > 0 && lines[0].indexOf('=')) {
- result.main = parseFloat(lines[0].split('=')[1]);
- result.max = result.main;
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- });
- });
- });
- } catch (er) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('sysctl dev.cpu | grep temp', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- let sum = 0;
- lines.forEach(function (line) {
- const parts = line.split(':');
- if (parts.length > 1) {
- const temp = parseFloat(parts[1].replace(',', '.'));
- if (temp > result.max) { result.max = temp; }
- sum = sum + temp;
- result.cores.push(temp);
- }
- });
- if (result.cores.length) {
- result.main = Math.round(sum / result.cores.length * 100) / 100;
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- let osxTemp = null;
- try {
- osxTemp = __nccwpck_require__(73700);
- } catch (er) {
- osxTemp = null;
- }
- if (osxTemp) {
- result = osxTemp.cpuTemperature();
- // round to 2 digits
- if (result.main) {
- result.main = Math.round(result.main * 100) / 100;
- }
- if (result.max) {
- result.max = Math.round(result.max * 100) / 100;
- }
- if (result.cores && result.cores.length) {
- for (let i = 0; i < result.cores.length; i++) {
- result.cores[i] = Math.round(result.cores[i] * 100) / 100;
- }
- }
- }
-
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- util.powerShell('Get-CimInstance MSAcpi_ThermalZoneTemperature -Namespace "root/wmi" | Select CurrentTemperature').then((stdout, error) => {
- if (!error) {
- let sum = 0;
- let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
- lines.forEach(function (line) {
- let value = (parseInt(line, 10) - 2732) / 10;
- if (!isNaN(value)) {
- sum = sum + value;
- if (value > result.max) { result.max = value; }
- result.cores.push(value);
- }
- });
- if (result.cores.length) {
- result.main = sum / result.cores.length;
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.cpuTemperature = cpuTemperature;
-
-// --------------------------
-// CPU Flags
-
-function cpuFlags(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = '';
- if (_windows) {
- try {
- exec('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', util.execOptsWin, function (error, stdout) {
- if (!error) {
- let flag_hex = stdout.split('0x').pop().trim();
- let flag_bin_unpadded = parseInt(flag_hex, 16).toString(2);
- let flag_bin = '0'.repeat(32 - flag_bin_unpadded.length) + flag_bin_unpadded;
- // empty flags are the reserved fields in the CPUID feature bit list
- // as found on wikipedia:
- // https://en.wikipedia.org/wiki/CPUID
- let all_flags = [
- 'fpu', 'vme', 'de', 'pse', 'tsc', 'msr', 'pae', 'mce', 'cx8', 'apic',
- '', 'sep', 'mtrr', 'pge', 'mca', 'cmov', 'pat', 'pse-36', 'psn', 'clfsh',
- '', 'ds', 'acpi', 'mmx', 'fxsr', 'sse', 'sse2', 'ss', 'htt', 'tm', 'ia64', 'pbe'
- ];
- for (let f = 0; f < all_flags.length; f++) {
- if (flag_bin[f] === '1' && all_flags[f] !== '') {
- result += ' ' + all_flags[f];
- }
- }
- result = result.trim().toLowerCase();
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_linux) {
- try {
-
- exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- if (line.split(':')[0].toUpperCase().indexOf('FLAGS') !== -1) {
- result = line.split(':')[1].trim().toLowerCase();
- }
- });
- }
- if (!result) {
- fs.readFile('/proc/cpuinfo', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result = util.getValue(lines, 'features', ':', true).toLowerCase();
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('export LC_ALL=C; dmidecode -t 4 2>/dev/null; unset LC_ALL', function (error, stdout) {
- let flags = [];
- if (!error) {
- let parts = stdout.toString().split('\tFlags:');
- const lines = parts.length > 1 ? parts[1].split('\tVersion:')[0].split('\n') : [];
- lines.forEach(function (line) {
- let flag = (line.indexOf('(') ? line.split('(')[0].toLowerCase() : '').trim().replace(/\t/g, '');
- if (flag) {
- flags.push(flag);
- }
- });
- }
- result = flags.join(' ').trim().toLowerCase();
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- exec('sysctl machdep.cpu.features', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines.length > 0 && lines[0].indexOf('machdep.cpu.features:') !== -1) {
- result = lines[0].split(':')[1].trim().toLowerCase();
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
-}
-
-exports.cpuFlags = cpuFlags;
-
-// --------------------------
-// CPU Cache
-
-function cpuCache(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- l1d: null,
- l1i: null,
- l2: null,
- l3: null,
- };
- if (_linux) {
- try {
- exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- let parts = line.split(':');
- if (parts[0].toUpperCase().indexOf('L1D CACHE') !== -1) {
- result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
- }
- if (parts[0].toUpperCase().indexOf('L1I CACHE') !== -1) {
- result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
- }
- if (parts[0].toUpperCase().indexOf('L2 CACHE') !== -1) {
- result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
- }
- if (parts[0].toUpperCase().indexOf('L3 CACHE') !== -1) {
- result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
- }
- });
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('export LC_ALL=C; dmidecode -t 7 2>/dev/null; unset LC_ALL', function (error, stdout) {
- let cache = [];
- if (!error) {
- const data = stdout.toString();
- cache = data.split('Cache Information');
- cache.shift();
- }
- for (let i = 0; i < cache.length; i++) {
- const lines = cache[i].split('\n');
- let cacheType = util.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-');
- cacheType = cacheType.length ? cacheType[0] : '';
- const sizeParts = util.getValue(lines, 'Installed Size').split(' ');
- let size = parseInt(sizeParts[0], 10);
- const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb';
- size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1)));
- if (cacheType) {
- if (cacheType === 'l1') {
- result.cache[cacheType + 'd'] = size / 2;
- result.cache[cacheType + 'i'] = size / 2;
- } else {
- result.cache[cacheType] = size;
- }
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- exec('sysctl hw.l1icachesize hw.l1dcachesize hw.l2cachesize hw.l3cachesize', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- let parts = line.split(':');
- if (parts[0].toLowerCase().indexOf('hw.l1icachesize') !== -1) {
- result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
- }
- if (parts[0].toLowerCase().indexOf('hw.l1dcachesize') !== -1) {
- result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
- }
- if (parts[0].toLowerCase().indexOf('hw.l2cachesize') !== -1) {
- result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
- }
- if (parts[0].toLowerCase().indexOf('hw.l3cachesize') !== -1) {
- result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
- }
- });
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance Win32_processor | select L2CacheSize, L3CacheSize | fl'));
- workload.push(util.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl'));
-
- Promise.all(
- workload
- ).then((data) => {
- result = parseWinCache(data[0], data[1]);
-
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-function parseWinCache(linesProc, linesCache) {
- let result = {
- l1d: null,
- l1i: null,
- l2: null,
- l3: null,
- };
-
- // Win32_processor
- let lines = linesProc.split('\r\n');
- result.l1d = 0;
- result.l1i = 0;
- result.l2 = util.getValue(lines, 'l2cachesize', ':');
- result.l3 = util.getValue(lines, 'l3cachesize', ':');
- if (result.l2) { result.l2 = parseInt(result.l2, 10) * 1024; } else { result.l2 = 0; }
- if (result.l3) { result.l3 = parseInt(result.l3, 10) * 1024; } else { result.l3 = 0; }
-
- // Win32_CacheMemory
- const parts = linesCache.split(/\n\s*\n/);
- let l1i = 0;
- let l1d = 0;
- let l2 = 0;
- parts.forEach(function (part) {
- const lines = part.split('\r\n');
- const cacheType = util.getValue(lines, 'CacheType');
- const level = util.getValue(lines, 'Level');
- const installedSize = util.getValue(lines, 'InstalledSize');
- // L1 Instructions
- if (level === '3' && cacheType === '3') {
- result.l1i = result.l1i + parseInt(installedSize, 10) * 1024;
- }
- // L1 Data
- if (level === '3' && cacheType === '4') {
- result.l1d = result.l1d + parseInt(installedSize, 10) * 1024;
- }
- // L1 all
- if (level === '3' && cacheType === '5') {
- l1i = parseInt(installedSize, 10) / 2;
- l1d = parseInt(installedSize, 10) / 2;
- }
- // L2
- if (level === '4' && cacheType === '5') {
- l2 = l2 + parseInt(installedSize, 10) * 1024;
- }
- });
- if (!result.l1i && !result.l1d) {
- result.l1i = l1i;
- result.l1d = l1d;
- }
- if (l2) {
- result.l2 = l2;
- }
- return result;
-}
-
-exports.cpuCache = cpuCache;
-
-// --------------------------
-// CPU - current load - in %
-
-function getLoad() {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let loads = os.loadavg().map(function (x) { return x / util.cores(); });
- let avgLoad = parseFloat((Math.max.apply(Math, loads)).toFixed(2));
- let result = {};
-
- let now = Date.now() - _current_cpu.ms;
- if (now >= 200) {
- _current_cpu.ms = Date.now();
- const cpus = os.cpus().map(function (cpu) {
- cpu.times.steal = 0;
- cpu.times.guest = 0;
- return cpu;
- });
- let totalUser = 0;
- let totalSystem = 0;
- let totalNice = 0;
- let totalIrq = 0;
- let totalIdle = 0;
- let totalSteal = 0;
- let totalGuest = 0;
- let cores = [];
- _corecount = (cpus && cpus.length) ? cpus.length : 0;
-
- // linux: try to get other cpu stats
- if (_linux) {
- try {
- const lines = execSync('cat /proc/stat 2>/dev/null | grep cpu', util.execOptsLinux).toString().split('\n');
- if (lines.length > 1) {
- lines.shift();
- if (lines.length === cpus.length) {
- for (let i = 0; i < lines.length; i++) {
- let parts = lines[i].split(' ');
- if (parts.length >= 10) {
- const steal = parseFloat(parts[8]) || 0;
- const guest = parseFloat(parts[9]) || 0;
- cpus[i].times.steal = steal;
- cpus[i].times.guest = guest;
- }
- }
- }
- }
- } catch (e) {
- util.noop();
- }
- }
-
- for (let i = 0; i < _corecount; i++) {
- const cpu = cpus[i].times;
- totalUser += cpu.user;
- totalSystem += cpu.sys;
- totalNice += cpu.nice;
- totalIdle += cpu.idle;
- totalIrq += cpu.irq;
- totalSteal += cpu.steal || 0;
- totalGuest += cpu.guest || 0;
- let tmpTick = (_cpus && _cpus[i] && _cpus[i].totalTick ? _cpus[i].totalTick : 0);
- let tmpLoad = (_cpus && _cpus[i] && _cpus[i].totalLoad ? _cpus[i].totalLoad : 0);
- let tmpUser = (_cpus && _cpus[i] && _cpus[i].user ? _cpus[i].user : 0);
- let tmpSystem = (_cpus && _cpus[i] && _cpus[i].sys ? _cpus[i].sys : 0);
- let tmpNice = (_cpus && _cpus[i] && _cpus[i].nice ? _cpus[i].nice : 0);
- let tmpIdle = (_cpus && _cpus[i] && _cpus[i].idle ? _cpus[i].idle : 0);
- let tmpIrq = (_cpus && _cpus[i] && _cpus[i].irq ? _cpus[i].irq : 0);
- let tmpSteal = (_cpus && _cpus[i] && _cpus[i].steal ? _cpus[i].steal : 0);
- let tmpGuest = (_cpus && _cpus[i] && _cpus[i].guest ? _cpus[i].guest : 0);
- _cpus[i] = cpu;
- _cpus[i].totalTick = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest + _cpus[i].idle;
- _cpus[i].totalLoad = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest;
- _cpus[i].currentTick = _cpus[i].totalTick - tmpTick;
- _cpus[i].load = (_cpus[i].totalLoad - tmpLoad);
- _cpus[i].loadUser = (_cpus[i].user - tmpUser);
- _cpus[i].loadSystem = (_cpus[i].sys - tmpSystem);
- _cpus[i].loadNice = (_cpus[i].nice - tmpNice);
- _cpus[i].loadIdle = (_cpus[i].idle - tmpIdle);
- _cpus[i].loadIrq = (_cpus[i].irq - tmpIrq);
- _cpus[i].loadSteal = (_cpus[i].steal - tmpSteal);
- _cpus[i].loadGuest = (_cpus[i].guest - tmpGuest);
- cores[i] = {};
- cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
- cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100;
- cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100;
- cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100;
- cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100;
- cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100;
- cores[i].loadSteal = _cpus[i].loadSteal / _cpus[i].currentTick * 100;
- cores[i].loadGuest = _cpus[i].loadGuest / _cpus[i].currentTick * 100;
- cores[i].rawLoad = _cpus[i].load;
- cores[i].rawLoadUser = _cpus[i].loadUser;
- cores[i].rawLoadSystem = _cpus[i].loadSystem;
- cores[i].rawLoadNice = _cpus[i].loadNice;
- cores[i].rawLoadIdle = _cpus[i].loadIdle;
- cores[i].rawLoadIrq = _cpus[i].loadIrq;
- cores[i].rawLoadSteal = _cpus[i].loadSteal;
- cores[i].rawLoadGuest = _cpus[i].loadGuest;
- }
- let totalTick = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest + totalIdle;
- let totalLoad = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest;
- let currentTick = totalTick - _current_cpu.tick;
- result = {
- avgLoad: avgLoad,
- currentLoad: (totalLoad - _current_cpu.load) / currentTick * 100,
- currentLoadUser: (totalUser - _current_cpu.user) / currentTick * 100,
- currentLoadSystem: (totalSystem - _current_cpu.system) / currentTick * 100,
- currentLoadNice: (totalNice - _current_cpu.nice) / currentTick * 100,
- currentLoadIdle: (totalIdle - _current_cpu.idle) / currentTick * 100,
- currentLoadIrq: (totalIrq - _current_cpu.irq) / currentTick * 100,
- currentLoadSteal: (totalSteal - _current_cpu.steal) / currentTick * 100,
- currentLoadGuest: (totalGuest - _current_cpu.guest) / currentTick * 100,
- rawCurrentLoad: (totalLoad - _current_cpu.load),
- rawCurrentLoadUser: (totalUser - _current_cpu.user),
- rawCurrentLoadSystem: (totalSystem - _current_cpu.system),
- rawCurrentLoadNice: (totalNice - _current_cpu.nice),
- rawCurrentLoadIdle: (totalIdle - _current_cpu.idle),
- rawCurrentLoadIrq: (totalIrq - _current_cpu.irq),
- rawCurrentLoadSteal: (totalSteal - _current_cpu.steal),
- rawCurrentLoadGuest: (totalGuest - _current_cpu.guest),
- cpus: cores
- };
- _current_cpu = {
- user: totalUser,
- nice: totalNice,
- system: totalSystem,
- idle: totalIdle,
- irq: totalIrq,
- steal: totalSteal,
- guest: totalGuest,
- tick: totalTick,
- load: totalLoad,
- ms: _current_cpu.ms,
- currentLoad: result.currentLoad,
- currentLoadUser: result.currentLoadUser,
- currentLoadSystem: result.currentLoadSystem,
- currentLoadNice: result.currentLoadNice,
- currentLoadIdle: result.currentLoadIdle,
- currentLoadIrq: result.currentLoadIrq,
- currentLoadSteal: result.currentLoadSteal,
- currentLoadGuest: result.currentLoadGuest,
- rawCurrentLoad: result.rawCurrentLoad,
- rawCurrentLoadUser: result.rawCurrentLoadUser,
- rawCurrentLoadSystem: result.rawCurrentLoadSystem,
- rawCurrentLoadNice: result.rawCurrentLoadNice,
- rawCurrentLoadIdle: result.rawCurrentLoadIdle,
- rawCurrentLoadIrq: result.rawCurrentLoadIrq,
- rawCurrentLoadSteal: result.rawCurrentLoadSteal,
- rawCurrentLoadGuest: result.rawCurrentLoadGuest,
- };
- } else {
- let cores = [];
- for (let i = 0; i < _corecount; i++) {
- cores[i] = {};
- cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
- cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100;
- cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100;
- cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100;
- cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100;
- cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100;
- cores[i].rawLoad = _cpus[i].load;
- cores[i].rawLoadUser = _cpus[i].loadUser;
- cores[i].rawLoadSystem = _cpus[i].loadSystem;
- cores[i].rawLoadNice = _cpus[i].loadNice;
- cores[i].rawLoadIdle = _cpus[i].loadIdle;
- cores[i].rawLoadIrq = _cpus[i].loadIrq;
- cores[i].rawLoadSteal = _cpus[i].loadSteal;
- cores[i].rawLoadGuest = _cpus[i].loadGuest;
- }
- result = {
- avgLoad: avgLoad,
- currentLoad: _current_cpu.currentLoad,
- currentLoadUser: _current_cpu.currentLoadUser,
- currentLoadSystem: _current_cpu.currentLoadSystem,
- currentLoadNice: _current_cpu.currentLoadNice,
- currentLoadIdle: _current_cpu.currentLoadIdle,
- currentLoadIrq: _current_cpu.currentLoadIrq,
- currentLoadSteal: _current_cpu.currentLoadSteal,
- currentLoadGuest: _current_cpu.currentLoadGuest,
- rawCurrentLoad: _current_cpu.rawCurrentLoad,
- rawCurrentLoadUser: _current_cpu.rawCurrentLoadUser,
- rawCurrentLoadSystem: _current_cpu.rawCurrentLoadSystem,
- rawCurrentLoadNice: _current_cpu.rawCurrentLoadNice,
- rawCurrentLoadIdle: _current_cpu.rawCurrentLoadIdle,
- rawCurrentLoadIrq: _current_cpu.rawCurrentLoadIrq,
- rawCurrentLoadSteal: _current_cpu.rawCurrentLoadSteal,
- rawCurrentLoadGuest: _current_cpu.rawCurrentLoadGuest,
- cpus: cores
- };
- }
- resolve(result);
- });
- });
-}
-
-function currentLoad(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- getLoad().then(result => {
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- });
-}
-
-exports.currentLoad = currentLoad;
-
-// --------------------------
-// PS - full load
-// since bootup
-
-function getFullLoad() {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- const cpus = os.cpus();
- let totalUser = 0;
- let totalSystem = 0;
- let totalNice = 0;
- let totalIrq = 0;
- let totalIdle = 0;
-
- let result = 0;
-
- if (cpus && cpus.length) {
- for (let i = 0, len = cpus.length; i < len; i++) {
- const cpu = cpus[i].times;
- totalUser += cpu.user;
- totalSystem += cpu.sys;
- totalNice += cpu.nice;
- totalIrq += cpu.irq;
- totalIdle += cpu.idle;
- }
- let totalTicks = totalIdle + totalIrq + totalNice + totalSystem + totalUser;
- result = (totalTicks - totalIdle) / totalTicks * 100.0;
-
- }
- resolve(result);
- });
- });
-}
-
-function fullLoad(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- getFullLoad().then(result => {
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- });
-}
-
-exports.fullLoad = fullLoad;
-
-
-/***/ }),
-
-/***/ 31865:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// docker.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 13. Docker
-// ----------------------------------------------------------------------------------
-
-const util = __nccwpck_require__(33225);
-const DockerSocket = __nccwpck_require__(89364);
-
-let _platform = process.platform;
-const _windows = (_platform === 'win32');
-
-let _docker_container_stats = {};
-let _docker_socket;
-let _docker_last_read = 0;
-
-
-// --------------------------
-// get containers (parameter all: get also inactive/exited containers)
-
-function dockerInfo(callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
- const result = {};
-
- _docker_socket.getInfo((data) => {
- result.id = data.ID;
- result.containers = data.Containers;
- result.containersRunning = data.ContainersRunning;
- result.containersPaused = data.ContainersPaused;
- result.containersStopped = data.ContainersStopped;
- result.images = data.Images;
- result.driver = data.Driver;
- result.memoryLimit = data.MemoryLimit;
- result.swapLimit = data.SwapLimit;
- result.kernelMemory = data.KernelMemory;
- result.cpuCfsPeriod = data.CpuCfsPeriod;
- result.cpuCfsQuota = data.CpuCfsQuota;
- result.cpuShares = data.CPUShares;
- result.cpuSet = data.CPUSet;
- result.ipv4Forwarding = data.IPv4Forwarding;
- result.bridgeNfIptables = data.BridgeNfIptables;
- result.bridgeNfIp6tables = data.BridgeNfIp6tables;
- result.debug = data.Debug;
- result.nfd = data.NFd;
- result.oomKillDisable = data.OomKillDisable;
- result.ngoroutines = data.NGoroutines;
- result.systemTime = data.SystemTime;
- result.loggingDriver = data.LoggingDriver;
- result.cgroupDriver = data.CgroupDriver;
- result.nEventsListener = data.NEventsListener;
- result.kernelVersion = data.KernelVersion;
- result.operatingSystem = data.OperatingSystem;
- result.osType = data.OSType;
- result.architecture = data.Architecture;
- result.ncpu = data.NCPU;
- result.memTotal = data.MemTotal;
- result.dockerRootDir = data.DockerRootDir;
- result.httpProxy = data.HttpProxy;
- result.httpsProxy = data.HttpsProxy;
- result.noProxy = data.NoProxy;
- result.name = data.Name;
- result.labels = data.Labels;
- result.experimentalBuild = data.ExperimentalBuild;
- result.serverVersion = data.ServerVersion;
- result.clusterStore = data.ClusterStore;
- result.clusterAdvertise = data.ClusterAdvertise;
- result.defaultRuntime = data.DefaultRuntime;
- result.liveRestoreEnabled = data.LiveRestoreEnabled;
- result.isolation = data.Isolation;
- result.initBinary = data.InitBinary;
- result.productLicense = data.ProductLicense;
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- });
-}
-
-exports.dockerInfo = dockerInfo;
-
-function dockerImages(all, callback) {
-
- // fallback - if only callback is given
- if (util.isFunction(all) && !callback) {
- callback = all;
- all = false;
- }
- if (typeof all === 'string' && all === 'true') {
- all = true;
- }
- if (typeof all !== 'boolean' && all !== undefined) {
- all = false;
- }
-
- all = all || false;
- let result = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
- const workload = [];
-
- _docker_socket.listImages(all, data => {
- let dockerImages = {};
- try {
- dockerImages = data;
- if (dockerImages && Object.prototype.toString.call(dockerImages) === '[object Array]' && dockerImages.length > 0) {
-
- dockerImages.forEach(function (element) {
-
- if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) {
- element.Name = element.Names[0].replace(/^\/|\/$/g, '');
- }
- workload.push(dockerImagesInspect(element.Id.trim(), element));
- });
- if (workload.length) {
- Promise.all(
- workload
- ).then((data) => {
- if (callback) { callback(data); }
- resolve(data);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } catch (err) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
- });
-}
-
-// --------------------------
-// container inspect (for one container)
-
-function dockerImagesInspect(imageID, payload) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- imageID = imageID || '';
- if (typeof imageID !== 'string') {
- return resolve();
- }
- const imageIDSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(imageID, true)).trim();
- if (imageIDSanitized) {
-
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
-
- _docker_socket.inspectImage(imageIDSanitized.trim(), data => {
- try {
- resolve({
- id: payload.Id,
- container: data.Container,
- comment: data.Comment,
- os: data.Os,
- architecture: data.Architecture,
- parent: data.Parent,
- dockerVersion: data.DockerVersion,
- size: data.Size,
- sharedSize: payload.SharedSize,
- virtualSize: data.VirtualSize,
- author: data.Author,
- created: data.Created ? Math.round(new Date(data.Created).getTime() / 1000) : 0,
- containerConfig: data.ContainerConfig ? data.ContainerConfig : {},
- graphDriver: data.GraphDriver ? data.GraphDriver : {},
- repoDigests: data.RepoDigests ? data.RepoDigests : {},
- repoTags: data.RepoTags ? data.RepoTags : {},
- config: data.Config ? data.Config : {},
- rootFS: data.RootFS ? data.RootFS : {},
- });
- } catch (err) {
- resolve();
- }
- });
- } else {
- resolve();
- }
- });
- });
-}
-
-exports.dockerImages = dockerImages;
-
-function dockerContainers(all, callback) {
-
- function inContainers(containers, id) {
- let filtered = containers.filter(obj => {
- /**
- * @namespace
- * @property {string} Id
- */
- return (obj.Id && (obj.Id === id));
- });
- return (filtered.length > 0);
- }
-
- // fallback - if only callback is given
- if (util.isFunction(all) && !callback) {
- callback = all;
- all = false;
- }
- if (typeof all === 'string' && all === 'true') {
- all = true;
- }
- if (typeof all !== 'boolean' && all !== undefined) {
- all = false;
- }
-
- all = all || false;
- let result = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
- const workload = [];
-
- _docker_socket.listContainers(all, data => {
- let docker_containers = {};
- try {
- docker_containers = data;
- if (docker_containers && Object.prototype.toString.call(docker_containers) === '[object Array]' && docker_containers.length > 0) {
- // GC in _docker_container_stats
- for (let key in _docker_container_stats) {
- if ({}.hasOwnProperty.call(_docker_container_stats, key)) {
- if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; }
- }
- }
-
- docker_containers.forEach(function (element) {
-
- if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) {
- element.Name = element.Names[0].replace(/^\/|\/$/g, '');
- }
- workload.push(dockerContainerInspect(element.Id.trim(), element));
- });
- if (workload.length) {
- Promise.all(
- workload
- ).then((data) => {
- if (callback) { callback(data); }
- resolve(data);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } catch (err) {
- // GC in _docker_container_stats
- for (let key in _docker_container_stats) {
- if ({}.hasOwnProperty.call(_docker_container_stats, key)) {
- if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; }
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
- });
-}
-
-// --------------------------
-// container inspect (for one container)
-
-function dockerContainerInspect(containerID, payload) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- containerID = containerID || '';
- if (typeof containerID !== 'string') {
- return resolve();
- }
- const containerIdSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerID, true)).trim();
- if (containerIdSanitized) {
-
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
-
- _docker_socket.getInspect(containerIdSanitized.trim(), data => {
- try {
- resolve({
- id: payload.Id,
- name: payload.Name,
- image: payload.Image,
- imageID: payload.ImageID,
- command: payload.Command,
- created: payload.Created,
- started: data.State && data.State.StartedAt ? Math.round(new Date(data.State.StartedAt).getTime() / 1000) : 0,
- finished: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? Math.round(new Date(data.State.FinishedAt).getTime() / 1000) : 0,
- createdAt: data.Created ? data.Created : '',
- startedAt: data.State && data.State.StartedAt ? data.State.StartedAt : '',
- finishedAt: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? data.State.FinishedAt : '',
- state: payload.State,
- restartCount: data.RestartCount || 0,
- platform: data.Platform || '',
- driver: data.Driver || '',
- ports: payload.Ports,
- mounts: payload.Mounts,
- // hostconfig: payload.HostConfig,
- // network: payload.NetworkSettings
- });
- } catch (err) {
- resolve();
- }
- });
- } else {
- resolve();
- }
- });
- });
-}
-
-exports.dockerContainers = dockerContainers;
-
-// --------------------------
-// helper functions for calculation of docker stats
-
-function docker_calcCPUPercent(cpu_stats, precpu_stats) {
- /**
- * @namespace
- * @property {object} cpu_usage
- * @property {number} cpu_usage.total_usage
- * @property {number} system_cpu_usage
- * @property {object} cpu_usage
- * @property {Array} cpu_usage.percpu_usage
- */
-
- if (!_windows) {
- let cpuPercent = 0.0;
- // calculate the change for the cpu usage of the container in between readings
- let cpuDelta = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
- // calculate the change for the entire system between readings
- let systemDelta = cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage;
-
- if (systemDelta > 0.0 && cpuDelta > 0.0) {
- // calculate the change for the cpu usage of the container in between readings
- if (precpu_stats.online_cpus) {
- cpuPercent = (cpuDelta / systemDelta) * precpu_stats.online_cpus * 100.0;
- }
- else {
- cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0;
- }
- }
-
- return cpuPercent;
- } else {
- let nanoSecNow = util.nanoSeconds();
- let cpuPercent = 0.0;
- if (_docker_last_read > 0) {
- let possIntervals = (nanoSecNow - _docker_last_read); // / 100 * os.cpus().length;
- let intervalsUsed = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
- if (possIntervals > 0) {
- cpuPercent = 100.0 * intervalsUsed / possIntervals;
- }
- }
- _docker_last_read = nanoSecNow;
- return cpuPercent;
- }
-}
-
-function docker_calcNetworkIO(networks) {
- let rx;
- let wx;
- for (let key in networks) {
- // skip loop if the property is from prototype
- if (!{}.hasOwnProperty.call(networks, key)) { continue; }
-
- /**
- * @namespace
- * @property {number} rx_bytes
- * @property {number} tx_bytes
- */
- let obj = networks[key];
- rx = +obj.rx_bytes;
- wx = +obj.tx_bytes;
- }
- return {
- rx,
- wx
- };
-}
-
-function docker_calcBlockIO(blkio_stats) {
- let result = {
- r: 0,
- w: 0
- };
-
- /**
- * @namespace
- * @property {Array} io_service_bytes_recursive
- */
- if (blkio_stats && blkio_stats.io_service_bytes_recursive && Object.prototype.toString.call(blkio_stats.io_service_bytes_recursive) === '[object Array]' && blkio_stats.io_service_bytes_recursive.length > 0) {
- blkio_stats.io_service_bytes_recursive.forEach(function (element) {
- /**
- * @namespace
- * @property {string} op
- * @property {number} value
- */
-
- if (element.op && element.op.toLowerCase() === 'read' && element.value) {
- result.r += element.value;
- }
- if (element.op && element.op.toLowerCase() === 'write' && element.value) {
- result.w += element.value;
- }
- });
- }
- return result;
-}
-
-function dockerContainerStats(containerIDs, callback) {
-
- let containerArray = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- // fallback - if only callback is given
- if (util.isFunction(containerIDs) && !callback) {
- callback = containerIDs;
- containerArray = ['*'];
- } else {
- containerIDs = containerIDs || '*';
- if (typeof containerIDs !== 'string') {
- if (callback) { callback([]); }
- return resolve([]);
- }
- let containerIDsSanitized = '';
- try {
- containerIDsSanitized.__proto__.toLowerCase = util.stringToLower;
- containerIDsSanitized.__proto__.replace = util.stringReplace;
- containerIDsSanitized.__proto__.trim = util.stringTrim;
- } catch (e) {
- Object.setPrototypeOf(containerIDsSanitized, util.stringObj);
- }
-
- containerIDsSanitized = containerIDs;
- containerIDsSanitized = containerIDsSanitized.trim();
- if (containerIDsSanitized !== '*') {
- containerIDsSanitized = '';
- const s = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerIDs, true)).trim();
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- s[i].__proto__.toLowerCase = util.stringToLower;
- const sl = s[i].toLowerCase();
- if (sl && sl[0] && !sl[1]) {
- containerIDsSanitized = containerIDsSanitized + sl[0];
- }
- }
- }
- }
-
- containerIDsSanitized = containerIDsSanitized.trim().toLowerCase().replace(/,+/g, '|');
- containerArray = containerIDsSanitized.split('|');
- }
-
- const result = [];
-
- const workload = [];
- if (containerArray.length && containerArray[0].trim() === '*') {
- containerArray = [];
- dockerContainers().then(allContainers => {
- for (let container of allContainers) {
- containerArray.push(container.id.substring(0, 12));
- }
- if (containerArray.length) {
- dockerContainerStats(containerArray.join(',')).then(result => {
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } else {
- for (let containerID of containerArray) {
- workload.push(dockerContainerStatsSingle(containerID.trim()));
- }
- if (workload.length) {
- Promise.all(
- workload
- ).then((data) => {
- if (callback) { callback(data); }
- resolve(data);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-// --------------------------
-// container stats (for one container)
-
-function dockerContainerStatsSingle(containerID) {
- containerID = containerID || '';
- let result = {
- id: containerID,
- memUsage: 0,
- memLimit: 0,
- memPercent: 0,
- cpuPercent: 0,
- pids: 0,
- netIO: {
- rx: 0,
- wx: 0
- },
- blockIO: {
- r: 0,
- w: 0
- },
- restartCount: 0,
- cpuStats: {},
- precpuStats: {},
- memoryStats: {},
- networks: {},
- };
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (containerID) {
-
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
-
- _docker_socket.getInspect(containerID, dataInspect => {
- try {
- _docker_socket.getStats(containerID, data => {
- try {
- let stats = data;
- if (!stats.message) {
- if (data.id) { result.id = data.id; }
- result.memUsage = (stats.memory_stats && stats.memory_stats.usage ? stats.memory_stats.usage : 0);
- result.memLimit = (stats.memory_stats && stats.memory_stats.limit ? stats.memory_stats.limit : 0);
- result.memPercent = (stats.memory_stats && stats.memory_stats.usage && stats.memory_stats.limit ? stats.memory_stats.usage / stats.memory_stats.limit * 100.0 : 0);
- result.cpuPercent = (stats.cpu_stats && stats.precpu_stats ? docker_calcCPUPercent(stats.cpu_stats, stats.precpu_stats) : 0);
- result.pids = (stats.pids_stats && stats.pids_stats.current ? stats.pids_stats.current : 0);
- result.restartCount = (dataInspect.RestartCount ? dataInspect.RestartCount : 0);
- if (stats.networks) { result.netIO = docker_calcNetworkIO(stats.networks); }
- if (stats.blkio_stats) { result.blockIO = docker_calcBlockIO(stats.blkio_stats); }
- result.cpuStats = (stats.cpu_stats ? stats.cpu_stats : {});
- result.precpuStats = (stats.precpu_stats ? stats.precpu_stats : {});
- result.memoryStats = (stats.memory_stats ? stats.memory_stats : {});
- result.networks = (stats.networks ? stats.networks : {});
- }
- } catch (err) {
- util.noop();
- }
- // }
- resolve(result);
- });
- } catch (err) {
- util.noop();
- }
- });
- } else {
- resolve(result);
- }
- });
- });
-}
-
-exports.dockerContainerStats = dockerContainerStats;
-
-// --------------------------
-// container processes (for one container)
-
-function dockerContainerProcesses(containerID, callback) {
- let result = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
- containerID = containerID || '';
- if (typeof containerID !== 'string') {
- return resolve(result);
- }
- const containerIdSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerID, true)).trim();
-
- if (containerIdSanitized) {
-
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
-
- _docker_socket.getProcesses(containerIdSanitized, data => {
- /**
- * @namespace
- * @property {Array} Titles
- * @property {Array} Processes
- **/
- try {
- if (data && data.Titles && data.Processes) {
- let titles = data.Titles.map(function (value) {
- return value.toUpperCase();
- });
- let pos_pid = titles.indexOf('PID');
- let pos_ppid = titles.indexOf('PPID');
- let pos_pgid = titles.indexOf('PGID');
- let pos_vsz = titles.indexOf('VSZ');
- let pos_time = titles.indexOf('TIME');
- let pos_elapsed = titles.indexOf('ELAPSED');
- let pos_ni = titles.indexOf('NI');
- let pos_ruser = titles.indexOf('RUSER');
- let pos_user = titles.indexOf('USER');
- let pos_rgroup = titles.indexOf('RGROUP');
- let pos_group = titles.indexOf('GROUP');
- let pos_stat = titles.indexOf('STAT');
- let pos_rss = titles.indexOf('RSS');
- let pos_command = titles.indexOf('COMMAND');
-
- data.Processes.forEach(process => {
- result.push({
- pidHost: (pos_pid >= 0 ? process[pos_pid] : ''),
- ppid: (pos_ppid >= 0 ? process[pos_ppid] : ''),
- pgid: (pos_pgid >= 0 ? process[pos_pgid] : ''),
- user: (pos_user >= 0 ? process[pos_user] : ''),
- ruser: (pos_ruser >= 0 ? process[pos_ruser] : ''),
- group: (pos_group >= 0 ? process[pos_group] : ''),
- rgroup: (pos_rgroup >= 0 ? process[pos_rgroup] : ''),
- stat: (pos_stat >= 0 ? process[pos_stat] : ''),
- time: (pos_time >= 0 ? process[pos_time] : ''),
- elapsed: (pos_elapsed >= 0 ? process[pos_elapsed] : ''),
- nice: (pos_ni >= 0 ? process[pos_ni] : ''),
- rss: (pos_rss >= 0 ? process[pos_rss] : ''),
- vsz: (pos_vsz >= 0 ? process[pos_vsz] : ''),
- command: (pos_command >= 0 ? process[pos_command] : '')
- });
- });
- }
- } catch (err) {
- util.noop();
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
-}
-
-exports.dockerContainerProcesses = dockerContainerProcesses;
-
-function dockerVolumes(callback) {
-
- let result = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
- _docker_socket.listVolumes((data) => {
- let dockerVolumes = {};
- try {
- dockerVolumes = data;
- if (dockerVolumes && dockerVolumes.Volumes && Object.prototype.toString.call(dockerVolumes.Volumes) === '[object Array]' && dockerVolumes.Volumes.length > 0) {
-
- dockerVolumes.Volumes.forEach(function (element) {
-
- result.push({
- name: element.Name,
- driver: element.Driver,
- labels: element.Labels,
- mountpoint: element.Mountpoint,
- options: element.Options,
- scope: element.Scope,
- created: element.CreatedAt ? Math.round(new Date(element.CreatedAt).getTime() / 1000) : 0,
- });
- });
- if (callback) { callback(result); }
- resolve(result);
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } catch (err) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
- });
-}
-
-exports.dockerVolumes = dockerVolumes;
-
-function dockerAll(callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- dockerContainers(true).then(result => {
- if (result && Object.prototype.toString.call(result) === '[object Array]' && result.length > 0) {
- let l = result.length;
- result.forEach(function (element) {
- dockerContainerStats(element.id).then((res) => {
- // include stats in array
- element.memUsage = res[0].memUsage;
- element.memLimit = res[0].memLimit;
- element.memPercent = res[0].memPercent;
- element.cpuPercent = res[0].cpuPercent;
- element.pids = res[0].pids;
- element.netIO = res[0].netIO;
- element.blockIO = res[0].blockIO;
- element.cpuStats = res[0].cpuStats;
- element.precpuStats = res[0].precpuStats;
- element.memoryStats = res[0].memoryStats;
- element.networks = res[0].networks;
-
- dockerContainerProcesses(element.id).then(processes => {
- element.processes = processes;
-
- l -= 1;
- if (l === 0) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- // all done??
- });
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
- });
-}
-
-exports.dockerAll = dockerAll;
-
-
-/***/ }),
-
-/***/ 89364:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// dockerSockets.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 13. DockerSockets
-// ----------------------------------------------------------------------------------
-
-const net = __nccwpck_require__(69278);
-const isWin = (__nccwpck_require__(70857).type)() === 'Windows_NT';
-const socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock';
-
-class DockerSocket {
-
- getInfo(callback) {
- try {
-
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/info HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- }
-
- listImages(all, callback) {
- try {
-
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/images/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- }
-
- inspectImage(id, callback) {
- id = id || '';
- if (id) {
- try {
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/images/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- } else {
- callback({});
- }
- }
-
- listContainers(all, callback) {
- try {
-
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/containers/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- }
-
- getStats(id, callback) {
- id = id || '';
- if (id) {
- try {
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/containers/' + id + '/stats?stream=0 HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- } else {
- callback({});
- }
- }
-
- getInspect(id, callback) {
- id = id || '';
- if (id) {
- try {
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/containers/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- } else {
- callback({});
- }
- }
-
- getProcesses(id, callback) {
- id = id || '';
- if (id) {
- try {
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/containers/' + id + '/top?ps_args=-opid,ppid,pgid,vsz,time,etime,nice,ruser,user,rgroup,group,stat,rss,args HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- } else {
- callback({});
- }
- }
-
- listVolumes(callback) {
- try {
-
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/volumes HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- }
-}
-
-module.exports = DockerSocket;
-
-
-/***/ }),
-
-/***/ 43022:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// filesystem.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 8. File System
-// ----------------------------------------------------------------------------------
-
-const util = __nccwpck_require__(33225);
-const fs = __nccwpck_require__(79896);
-
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const execPromiseSave = util.promisifySave((__nccwpck_require__(35317).exec));
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-let _fs_speed = {};
-let _disk_io = {};
-
-// --------------------------
-// FS - mounted file systems
-
-function fsSize(drive, callback) {
-
- if (util.isFunction(drive)) {
- callback = drive;
- drive = '';
- }
-
- let macOsDisks = [];
- let osMounts = [];
-
- function getmacOsFsType(fs) {
- if (!fs.startsWith('/')) { return 'NFS'; }
- const parts = fs.split('/');
- const fsShort = parts[parts.length - 1];
- const macOsDisksSingle = macOsDisks.filter(item => item.indexOf(fsShort) >= 0);
- if (macOsDisksSingle.length === 1 && macOsDisksSingle[0].indexOf('APFS') >= 0) { return 'APFS'; }
- return 'HFS';
- }
-
- function isLinuxTmpFs(fs) {
- const linuxTmpFileSystems = ['rootfs', 'unionfs', 'squashfs', 'cramfs', 'initrd', 'initramfs', 'devtmpfs', 'tmpfs', 'udev', 'devfs', 'specfs', 'type', 'appimaged'];
- let result = false;
- linuxTmpFileSystems.forEach(linuxFs => {
- if (fs.toLowerCase().indexOf(linuxFs) >= 0) { result = true; }
- });
- return result;
- }
-
- function filterLines(stdout) {
- let lines = stdout.toString().split('\n');
- lines.shift();
- if (stdout.toString().toLowerCase().indexOf('filesystem')) {
- let removeLines = 0;
- for (let i = 0; i < lines.length; i++) {
- if (lines[i] && lines[i].toLowerCase().startsWith('filesystem')) {
- removeLines = i;
- }
- }
- for (let i = 0; i < removeLines; i++) {
- lines.shift();
- }
- }
- return lines;
- }
-
- function parseDf(lines) {
- let data = [];
- lines.forEach(function (line) {
- if (line !== '') {
- line = line.replace(/ +/g, ' ').split(' ');
- if (line && ((line[0].startsWith('/')) || (line[6] && line[6] === '/') || (line[0].indexOf('/') > 0) || (line[0].indexOf(':') === 1) || !_darwin && !isLinuxTmpFs(line[1]))) {
- const fs = line[0];
- const fsType = ((_linux || _freebsd || _openbsd || _netbsd) ? line[1] : getmacOsFsType(line[0]));
- const size = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[2] : line[1])) * 1024;
- const used = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[3] : line[2])) * 1024;
- const available = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[4] : line[3])) * 1024;
- const use = parseFloat((100.0 * (used / (used + available))).toFixed(2));
- let rw = osMounts && Object.keys(osMounts).length > 0 ? osMounts[fs] || false : null;
- line.splice(0, (_linux || _freebsd || _openbsd || _netbsd) ? 6 : 5);
- const mount = line.join(' ');
- if (!data.find(el => (el.fs === fs && el.type === fsType))) {
- data.push({
- fs,
- type: fsType,
- size,
- used,
- available,
- use,
- mount,
- rw
- });
- }
- }
- }
- });
- return data;
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let data = [];
- if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
- let cmd = '';
- macOsDisks = [];
- osMounts = {};
- if (_darwin) {
- cmd = 'df -kP';
- try {
- macOsDisks = execSync('diskutil list').toString().split('\n').filter(line => {
- return !line.startsWith('/') && line.indexOf(':') > 0;
- });
- execSync('mount').toString().split('\n').filter(line => {
- return line.startsWith('/');
- }).forEach((line) => {
- osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1;
- });
- } catch (e) {
- util.noop();
- }
- }
- if (_linux) {
- try {
- cmd = 'export LC_ALL=C; df -lkPTx squashfs; unset LC_ALL';
- execSync('cat /proc/mounts 2>/dev/null', util.execOptsLinux).toString().split('\n').filter(line => {
- return line.startsWith('/');
- }).forEach((line) => {
- osMounts[line.split(' ')[0]] = osMounts[line.split(' ')[0]] || false;
- if (line.toLowerCase().indexOf('/snap/') === -1) {
- osMounts[line.split(' ')[0]] = ((line.toLowerCase().indexOf('rw,') >= 0 || line.toLowerCase().indexOf(' rw ') >= 0));
- }
- });
- } catch (e) {
- util.noop();
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- try {
- cmd = 'df -lkPT';
- execSync('mount').toString().split('\n').forEach((line) => {
- osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1;
- });
- } catch (e) {
- util.noop();
- }
- }
- exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- let lines = filterLines(stdout);
- data = parseDf(lines);
- if (drive) {
- data = data.filter(item => {
- return item.fs.toLowerCase().indexOf(drive.toLowerCase()) >= 0 || item.mount.toLowerCase().indexOf(drive.toLowerCase()) >= 0;
- });
- }
- if ((!error || data.length) && stdout.toString().trim() !== '') {
- if (callback) {
- callback(data);
- }
- resolve(data);
- } else {
- exec('df -kPT', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = filterLines(stdout);
- data = parseDf(lines);
- }
- if (callback) {
- callback(data);
- }
- resolve(data);
- });
- }
- });
- }
- if (_sunos) {
- if (callback) { callback(data); }
- resolve(data);
- }
- if (_windows) {
- try {
- const cmd = `Get-WmiObject Win32_logicaldisk | select Access,Caption,FileSystem,FreeSpace,Size ${drive ? '| where -property Caption -eq ' + drive : ''} | fl`;
- util.powerShell(cmd).then((stdout, error) => {
- if (!error) {
- let devices = stdout.toString().split(/\n\s*\n/);
- devices.forEach(function (device) {
- let lines = device.split('\r\n');
- const size = util.toInt(util.getValue(lines, 'size', ':'));
- const free = util.toInt(util.getValue(lines, 'freespace', ':'));
- const caption = util.getValue(lines, 'caption', ':');
- const rwValue = util.getValue(lines, 'access', ':');
- const rw = rwValue ? (util.toInt(rwValue) !== 1) : null;
- if (size) {
- data.push({
- fs: caption,
- type: util.getValue(lines, 'filesystem', ':'),
- size,
- used: size - free,
- available: free,
- use: parseFloat(((100.0 * (size - free)) / size).toFixed(2)),
- mount: caption,
- rw
- });
- }
- });
- }
- if (callback) {
- callback(data);
- }
- resolve(data);
- });
- } catch (e) {
- if (callback) { callback(data); }
- resolve(data);
- }
- }
- });
- });
-}
-
-exports.fsSize = fsSize;
-
-// --------------------------
-// FS - open files count
-
-function fsOpenFiles(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- const result = {
- max: null,
- allocated: null,
- available: null
- };
- if (_freebsd || _openbsd || _netbsd || _darwin) {
- let cmd = 'sysctl -i kern.maxfiles kern.num_files kern.open_files';
- exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result.max = parseInt(util.getValue(lines, 'kern.maxfiles', ':'), 10);
- result.allocated = parseInt(util.getValue(lines, 'kern.num_files', ':'), 10) || parseInt(util.getValue(lines, 'kern.open_files', ':'), 10);
- result.available = result.max - result.allocated;
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_linux) {
- fs.readFile('/proc/sys/fs/file-nr', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines[0]) {
- const parts = lines[0].replace(/\s+/g, ' ').split(' ');
- if (parts.length === 3) {
- result.allocated = parseInt(parts[0], 10);
- result.available = parseInt(parts[1], 10);
- result.max = parseInt(parts[2], 10);
- if (!result.available) { result.available = result.max - result.allocated; }
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else {
- fs.readFile('/proc/sys/fs/file-max', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines[0]) {
- result.max = parseInt(lines[0], 10);
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- });
- }
- if (_sunos) {
- if (callback) { callback(null); }
- resolve(null);
- }
- if (_windows) {
- if (callback) { callback(null); }
- resolve(null);
- }
- });
- });
-}
-
-exports.fsOpenFiles = fsOpenFiles;
-
-// --------------------------
-// disks
-
-function parseBytes(s) {
- return parseInt(s.substr(s.indexOf(' (') + 2, s.indexOf(' Bytes)') - 10));
-}
-
-function parseDevices(lines) {
- let devices = [];
- let i = 0;
- lines.forEach(line => {
- if (line.length > 0) {
- if (line[0] === '*') {
- i++;
- } else {
- let parts = line.split(':');
- if (parts.length > 1) {
- if (!devices[i]) {
- devices[i] = {
- name: '',
- identifier: '',
- type: 'disk',
- fsType: '',
- mount: '',
- size: 0,
- physical: 'HDD',
- uuid: '',
- label: '',
- model: '',
- serial: '',
- removable: false,
- protocol: '',
- group: '',
- device: ''
- };
- }
- parts[0] = parts[0].trim().toUpperCase().replace(/ +/g, '');
- parts[1] = parts[1].trim();
- if ('DEVICEIDENTIFIER' === parts[0]) { devices[i].identifier = parts[1]; }
- if ('DEVICENODE' === parts[0]) { devices[i].name = parts[1]; }
- if ('VOLUMENAME' === parts[0]) {
- if (parts[1].indexOf('Not applicable') === -1) { devices[i].label = parts[1]; }
- }
- if ('PROTOCOL' === parts[0]) { devices[i].protocol = parts[1]; }
- if ('DISKSIZE' === parts[0]) { devices[i].size = parseBytes(parts[1]); }
- if ('FILESYSTEMPERSONALITY' === parts[0]) { devices[i].fsType = parts[1]; }
- if ('MOUNTPOINT' === parts[0]) { devices[i].mount = parts[1]; }
- if ('VOLUMEUUID' === parts[0]) { devices[i].uuid = parts[1]; }
- if ('READ-ONLYMEDIA' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'CD/DVD'; }
- if ('SOLIDSTATE' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'SSD'; }
- if ('VIRTUAL' === parts[0]) { devices[i].type = 'virtual'; }
- if ('REMOVABLEMEDIA' === parts[0]) { devices[i].removable = (parts[1] === 'Removable'); }
- if ('PARTITIONTYPE' === parts[0]) { devices[i].type = 'part'; }
- if ('DEVICE/MEDIANAME' === parts[0]) { devices[i].model = parts[1]; }
- }
- }
- }
- });
- return devices;
-}
-
-function parseBlk(lines) {
- let data = [];
-
- lines.filter(line => line !== '').forEach((line) => {
- try {
- line = decodeURIComponent(line.replace(/\\x/g, '%'));
- line = line.replace(/\\/g, '\\\\');
- let disk = JSON.parse(line);
- data.push({
- 'name': disk.name,
- 'type': disk.type,
- 'fsType': disk.fsType,
- 'mount': disk.mountpoint,
- 'size': parseInt(disk.size),
- 'physical': (disk.type === 'disk' ? (disk.rota === '0' ? 'SSD' : 'HDD') : (disk.type === 'rom' ? 'CD/DVD' : '')),
- 'uuid': disk.uuid,
- 'label': disk.label,
- 'model': (disk.model || '').trim(),
- 'serial': disk.serial,
- 'removable': disk.rm === '1',
- 'protocol': disk.tran,
- 'group': disk.group || '',
- });
- } catch (e) {
- util.noop();
- }
- });
- data = util.unique(data);
- data = util.sortByKey(data, ['type', 'name']);
- return data;
-}
-
-function decodeMdabmData(lines) {
- const raid = util.getValue(lines, 'md_level', '=');
- const label = util.getValue(lines, 'md_name', '='); // <- get label info
- const uuid = util.getValue(lines, 'md_uuid', '='); // <- get uuid info
- const members = [];
- lines.forEach(line => {
- if (line.toLowerCase().startsWith('md_device_dev') && line.toLowerCase().indexOf('/dev/') > 0) {
- members.push(line.split('/dev/')[1]);
- }
- });
- return {
- raid,
- label,
- uuid,
- members
- };
-}
-
-function raidMatchLinux(data) {
- // for all block devices of type "raid%"
- let result = data;
- try {
- data.forEach(element => {
- if (element.type.startsWith('raid')) {
- const lines = execSync(`mdadm --export --detail /dev/${element.name}`, util.execOptsLinux).toString().split('\n');
- const mdData = decodeMdabmData(lines);
-
- element.label = mdData.label; // <- assign label info
- element.uuid = mdData.uuid; // <- assign uuid info
-
- if (mdData.members && mdData.members.length && mdData.raid === element.type) {
- result = result.map(blockdevice => {
- if (blockdevice.fsType === 'linux_raid_member' && mdData.members.indexOf(blockdevice.name) >= 0) {
- blockdevice.group = element.name;
- }
- return blockdevice;
- });
- }
- }
- });
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function getDevicesLinux(data) {
- const result = [];
- data.forEach(element => {
- if (element.type.startsWith('disk')) {
- result.push(element.name);
- }
- });
- return result;
-}
-
-function matchDevicesLinux(data) {
- let result = data;
- try {
- const devices = getDevicesLinux(data);
- result = result.map(blockdevice => {
- if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk')) {
- devices.forEach(element => {
- if (blockdevice.name.startsWith(element)) {
- blockdevice.device = '/dev/' + element;
- }
- });
- }
- return blockdevice;
- });
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function getDevicesMac(data) {
- const result = [];
- data.forEach(element => {
- if (element.type.startsWith('disk')) {
- result.push({ name: element.name, model: element.model, device: element.name });
- }
- if (element.type.startsWith('virtual')) {
- let device = '';
- result.forEach(e => {
- if (e.model === element.model) {
- device = e.device;
- }
- });
- if (device) {
- result.push({ name: element.name, model: element.model, device });
- }
- }
- });
- return result;
-}
-
-function matchDevicesMac(data) {
- let result = data;
- try {
- const devices = getDevicesMac(data);
- result = result.map(blockdevice => {
- if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk') || blockdevice.type.startsWith('virtual')) {
- devices.forEach(element => {
- if (blockdevice.name.startsWith(element.name)) {
- blockdevice.device = element.device;
- }
- });
- }
- return blockdevice;
- });
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function getDevicesWin(diskDrives) {
- const result = [];
- diskDrives.forEach(element => {
- const lines = element.split('\r\n');
- const device = util.getValue(lines, 'DeviceID', ':');
- let partitions = element.split('@{DeviceID=');
- if (partitions.length > 1) {
- partitions = partitions.slice(1);
- partitions.forEach(partition => {
- result.push({ name: partition.split(';')[0].toUpperCase(), device });
- });
- }
- });
- return result;
-}
-
-function matchDevicesWin(data, diskDrives) {
- const devices = getDevicesWin(diskDrives);
- data.map(element => {
- const filteresDevices = devices.filter((e) => { return e.name === element.name.toUpperCase(); });
- if (filteresDevices.length > 0) {
- element.device = filteresDevices[0].device;
- }
- return element;
- });
- return data;
-}
-
-function blkStdoutToObject(stdout) {
- return stdout.toString()
- .replace(/NAME=/g, '{"name":')
- .replace(/FSTYPE=/g, ',"fsType":')
- .replace(/TYPE=/g, ',"type":')
- .replace(/SIZE=/g, ',"size":')
- .replace(/MOUNTPOINT=/g, ',"mountpoint":')
- .replace(/UUID=/g, ',"uuid":')
- .replace(/ROTA=/g, ',"rota":')
- .replace(/RO=/g, ',"ro":')
- .replace(/RM=/g, ',"rm":')
- .replace(/TRAN=/g, ',"tran":')
- .replace(/SERIAL=/g, ',"serial":')
- .replace(/LABEL=/g, ',"label":')
- .replace(/MODEL=/g, ',"model":')
- .replace(/OWNER=/g, ',"owner":')
- .replace(/GROUP=/g, ',"group":')
- .replace(/\n/g, '}\n');
-}
-
-function blockDevices(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let data = [];
- if (_linux) {
- // see https://wiki.ubuntuusers.de/lsblk/
- // exec("lsblk -bo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,TRAN,SERIAL,LABEL,MODEL,OWNER,GROUP,MODE,ALIGNMENT,MIN-IO,OPT-IO,PHY-SEC,LOG-SEC,SCHED,RQ-SIZE,RA,WSAME", function (error, stdout) {
- exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,TRAN,SERIAL,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = blkStdoutToObject(stdout).split('\n');
- data = parseBlk(lines);
- data = raidMatchLinux(data);
- data = matchDevicesLinux(data);
- if (callback) {
- callback(data);
- }
- resolve(data);
- } else {
- exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = blkStdoutToObject(stdout).split('\n');
- data = parseBlk(lines);
- data = raidMatchLinux(data);
- }
- if (callback) {
- callback(data);
- }
- resolve(data);
- });
- }
- });
- }
- if (_darwin) {
- exec('diskutil info -all', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- // parse lines into temp array of devices
- data = parseDevices(lines);
- data = matchDevicesMac(data);
- }
- if (callback) {
- callback(data);
- }
- resolve(data);
- });
- }
- if (_sunos) {
- if (callback) { callback(data); }
- resolve(data);
- }
- if (_windows) {
- let drivetypes = ['Unknown', 'NoRoot', 'Removable', 'Local', 'Network', 'CD/DVD', 'RAM'];
- try {
- // util.wmic('logicaldisk get Caption,Description,DeviceID,DriveType,FileSystem,FreeSpace,Name,Size,VolumeName,VolumeSerialNumber /value').then((stdout, error) => {
- // util.powerShell('Get-CimInstance Win32_logicaldisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl').then((stdout, error) => {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance -ClassName Win32_LogicalDisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl'));
- workload.push(util.powerShell('Get-WmiObject -Class Win32_diskdrive | Select-Object -Property PNPDeviceId,DeviceID, Model, Size, @{L=\'Partitions\'; E={$_.GetRelated(\'Win32_DiskPartition\').GetRelated(\'Win32_LogicalDisk\') | Select-Object -Property DeviceID, VolumeName, Size, FreeSpace}} | fl'));
- util.promiseAll(
- workload
- ).then((res) => {
- let logicalDisks = res.results[0].toString().split(/\n\s*\n/);
- let diskDrives = res.results[1].toString().split(/\n\s*\n/);
- logicalDisks.forEach(function (device) {
- let lines = device.split('\r\n');
- let drivetype = util.getValue(lines, 'drivetype', ':');
- if (drivetype) {
- data.push({
- name: util.getValue(lines, 'name', ':'),
- identifier: util.getValue(lines, 'caption', ':'),
- type: 'disk',
- fsType: util.getValue(lines, 'filesystem', ':').toLowerCase(),
- mount: util.getValue(lines, 'caption', ':'),
- size: util.getValue(lines, 'size', ':'),
- physical: (drivetype >= 0 && drivetype <= 6) ? drivetypes[drivetype] : drivetypes[0],
- uuid: util.getValue(lines, 'volumeserialnumber', ':'),
- label: util.getValue(lines, 'volumename', ':'),
- model: '',
- serial: util.getValue(lines, 'volumeserialnumber', ':'),
- removable: drivetype === '2',
- protocol: '',
- group: '',
- device: ''
- });
- }
- });
- // match devices
- data = matchDevicesWin(data, diskDrives);
- if (callback) {
- callback(data);
- }
- resolve(data);
- });
- } catch (e) {
- if (callback) { callback(data); }
- resolve(data);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- // will follow
- if (callback) { callback(null); }
- resolve(null);
- }
-
- });
- });
-}
-
-exports.blockDevices = blockDevices;
-
-// --------------------------
-// FS - speed
-
-function calcFsSpeed(rx, wx) {
- let result = {
- rx: 0,
- wx: 0,
- tx: 0,
- rx_sec: null,
- wx_sec: null,
- tx_sec: null,
- ms: 0
- };
-
- if (_fs_speed && _fs_speed.ms) {
- result.rx = rx;
- result.wx = wx;
- result.tx = result.rx + result.wx;
- result.ms = Date.now() - _fs_speed.ms;
- result.rx_sec = (result.rx - _fs_speed.bytes_read) / (result.ms / 1000);
- result.wx_sec = (result.wx - _fs_speed.bytes_write) / (result.ms / 1000);
- result.tx_sec = result.rx_sec + result.wx_sec;
- _fs_speed.rx_sec = result.rx_sec;
- _fs_speed.wx_sec = result.wx_sec;
- _fs_speed.tx_sec = result.tx_sec;
- _fs_speed.bytes_read = result.rx;
- _fs_speed.bytes_write = result.wx;
- _fs_speed.bytes_overall = result.rx + result.wx;
- _fs_speed.ms = Date.now();
- _fs_speed.last_ms = result.ms;
- } else {
- result.rx = rx;
- result.wx = wx;
- result.tx = result.rx + result.wx;
- _fs_speed.rx_sec = null;
- _fs_speed.wx_sec = null;
- _fs_speed.tx_sec = null;
- _fs_speed.bytes_read = result.rx;
- _fs_speed.bytes_write = result.wx;
- _fs_speed.bytes_overall = result.rx + result.wx;
- _fs_speed.ms = Date.now();
- _fs_speed.last_ms = 0;
- }
- return result;
-}
-
-function fsStats(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (_windows || _freebsd || _openbsd || _netbsd || _sunos) {
- return resolve(null);
- }
-
- let result = {
- rx: 0,
- wx: 0,
- tx: 0,
- rx_sec: null,
- wx_sec: null,
- tx_sec: null,
- ms: 0
- };
-
- let rx = 0;
- let wx = 0;
- if ((_fs_speed && !_fs_speed.ms) || (_fs_speed && _fs_speed.ms && Date.now() - _fs_speed.ms >= 500)) {
- if (_linux) {
- // exec("df -k | grep /dev/", function(error, stdout) {
- exec('lsblk -r 2>/dev/null | grep /', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- let fs_filter = [];
- lines.forEach(function (line) {
- if (line !== '') {
- line = line.trim().split(' ');
- if (fs_filter.indexOf(line[0]) === -1) { fs_filter.push(line[0]); }
- }
- });
-
- let output = fs_filter.join('|');
- exec('cat /proc/diskstats | egrep "' + output + '"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- line = line.trim();
- if (line !== '') {
- line = line.replace(/ +/g, ' ').split(' ');
-
- rx += parseInt(line[5]) * 512;
- wx += parseInt(line[9]) * 512;
- }
- });
- result = calcFsSpeed(rx, wx);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- }
- if (_darwin) {
- exec('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- line = line.trim();
- if (line !== '') {
- line = line.split(',');
-
- rx += parseInt(line[2]);
- wx += parseInt(line[9]);
- }
- });
- result = calcFsSpeed(rx, wx);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- } else {
- result.ms = _fs_speed.last_ms;
- result.rx = _fs_speed.bytes_read;
- result.wx = _fs_speed.bytes_write;
- result.tx = _fs_speed.bytes_read + _fs_speed.bytes_write;
- result.rx_sec = _fs_speed.rx_sec;
- result.wx_sec = _fs_speed.wx_sec;
- result.tx_sec = _fs_speed.tx_sec;
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- });
-}
-
-exports.fsStats = fsStats;
-
-function calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime) {
- let result = {
- rIO: 0,
- wIO: 0,
- tIO: 0,
- rIO_sec: null,
- wIO_sec: null,
- tIO_sec: null,
- rWaitTime: 0,
- wWaitTime: 0,
- tWaitTime: 0,
- rWaitPercent: null,
- wWaitPercent: null,
- tWaitPercent: null,
- ms: 0
- };
- if (_disk_io && _disk_io.ms) {
- result.rIO = rIO;
- result.wIO = wIO;
- result.tIO = rIO + wIO;
- result.ms = Date.now() - _disk_io.ms;
- result.rIO_sec = (result.rIO - _disk_io.rIO) / (result.ms / 1000);
- result.wIO_sec = (result.wIO - _disk_io.wIO) / (result.ms / 1000);
- result.tIO_sec = result.rIO_sec + result.wIO_sec;
- result.rWaitTime = rWaitTime;
- result.wWaitTime = wWaitTime;
- result.tWaitTime = tWaitTime;
- result.rWaitPercent = (result.rWaitTime - _disk_io.rWaitTime) * 100 / (result.ms);
- result.wWaitPercent = (result.wWaitTime - _disk_io.wWaitTime) * 100 / (result.ms);
- result.tWaitPercent = (result.tWaitTime - _disk_io.tWaitTime) * 100 / (result.ms);
- _disk_io.rIO = rIO;
- _disk_io.wIO = wIO;
- _disk_io.rIO_sec = result.rIO_sec;
- _disk_io.wIO_sec = result.wIO_sec;
- _disk_io.tIO_sec = result.tIO_sec;
- _disk_io.rWaitTime = rWaitTime;
- _disk_io.wWaitTime = wWaitTime;
- _disk_io.tWaitTime = tWaitTime;
- _disk_io.rWaitPercent = result.rWaitPercent;
- _disk_io.wWaitPercent = result.wWaitPercent;
- _disk_io.tWaitPercent = result.tWaitPercent;
- _disk_io.last_ms = result.ms;
- _disk_io.ms = Date.now();
- } else {
- result.rIO = rIO;
- result.wIO = wIO;
- result.tIO = rIO + wIO;
- result.rWaitTime = rWaitTime;
- result.wWaitTime = wWaitTime;
- result.tWaitTime = tWaitTime;
- _disk_io.rIO = rIO;
- _disk_io.wIO = wIO;
- _disk_io.rIO_sec = null;
- _disk_io.wIO_sec = null;
- _disk_io.tIO_sec = null;
- _disk_io.rWaitTime = rWaitTime;
- _disk_io.wWaitTime = wWaitTime;
- _disk_io.tWaitTime = tWaitTime;
- _disk_io.rWaitPercent = null;
- _disk_io.wWaitPercent = null;
- _disk_io.tWaitPercent = null;
- _disk_io.last_ms = 0;
- _disk_io.ms = Date.now();
- }
- return result;
-}
-
-function disksIO(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (_windows) {
- return resolve(null);
- }
- if (_sunos) {
- return resolve(null);
- }
-
- let result = {
- rIO: 0,
- wIO: 0,
- tIO: 0,
- rIO_sec: null,
- wIO_sec: null,
- tIO_sec: null,
- rWaitTime: 0,
- wWaitTime: 0,
- tWaitTime: 0,
- rWaitPercent: null,
- wWaitPercent: null,
- tWaitPercent: null,
- ms: 0
- };
- let rIO = 0;
- let wIO = 0;
- let rWaitTime = 0;
- let wWaitTime = 0;
- let tWaitTime = 0;
-
- if ((_disk_io && !_disk_io.ms) || (_disk_io && _disk_io.ms && Date.now() - _disk_io.ms >= 500)) {
- if (_linux || _freebsd || _openbsd || _netbsd) {
- // prints Block layer statistics for all mounted volumes
- // var cmd = "for mount in `lsblk | grep / | sed -r 's/│ └─//' | cut -d ' ' -f 1`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done";
- // var cmd = "for mount in `lsblk | grep / | sed 's/[│└─├]//g' | awk '{$1=$1};1' | cut -d ' ' -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done";
- let cmd = 'for mount in `lsblk 2>/dev/null | grep " disk " | sed "s/[│└─├]//g" | awk \'{$1=$1};1\' | cut -d " " -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r "s/ +/;/g" | sed -r "s/^;//"; done';
-
- exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.split('\n');
- lines.forEach(function (line) {
- // ignore empty lines
- if (!line) { return; }
-
- // sum r/wIO of all disks to compute all disks IO
- let stats = line.split(';');
- rIO += parseInt(stats[0]);
- wIO += parseInt(stats[4]);
- rWaitTime += parseInt(stats[3]);
- wWaitTime += parseInt(stats[7]);
- tWaitTime += parseInt(stats[10]);
- });
- result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime);
-
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- }
- if (_darwin) {
- exec('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- line = line.trim();
- if (line !== '') {
- line = line.split(',');
-
- rIO += parseInt(line[10]);
- wIO += parseInt(line[0]);
- }
- });
- result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- } else {
- result.rIO = _disk_io.rIO;
- result.wIO = _disk_io.wIO;
- result.tIO = _disk_io.rIO + _disk_io.wIO;
- result.ms = _disk_io.last_ms;
- result.rIO_sec = _disk_io.rIO_sec;
- result.wIO_sec = _disk_io.wIO_sec;
- result.tIO_sec = _disk_io.tIO_sec;
- result.rWaitTime = _disk_io.rWaitTime;
- result.wWaitTime = _disk_io.wWaitTime;
- result.tWaitTime = _disk_io.tWaitTime;
- result.rWaitPercent = _disk_io.rWaitPercent;
- result.wWaitPercent = _disk_io.wWaitPercent;
- result.tWaitPercent = _disk_io.tWaitPercent;
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- });
-}
-
-exports.disksIO = disksIO;
-
-function diskLayout(callback) {
-
- function getVendorFromModel(model) {
- const diskManufacturers = [
- { pattern: 'WESTERN.*', manufacturer: 'Western Digital' },
- { pattern: '^WDC.*', manufacturer: 'Western Digital' },
- { pattern: 'WD.*', manufacturer: 'Western Digital' },
- { pattern: 'TOSHIBA.*', manufacturer: 'Toshiba' },
- { pattern: 'HITACHI.*', manufacturer: 'Hitachi' },
- { pattern: '^IC.*', manufacturer: 'Hitachi' },
- { pattern: '^HTS.*', manufacturer: 'Hitachi' },
- { pattern: 'SANDISK.*', manufacturer: 'SanDisk' },
- { pattern: 'KINGSTON.*', manufacturer: 'Kingston Technology' },
- { pattern: '^SONY.*', manufacturer: 'Sony' },
- { pattern: 'TRANSCEND.*', manufacturer: 'Transcend' },
- { pattern: 'SAMSUNG.*', manufacturer: 'Samsung' },
- { pattern: '^ST(?!I\\ ).*', manufacturer: 'Seagate' },
- { pattern: '^STI\\ .*', manufacturer: 'SimpleTech' },
- { pattern: '^D...-.*', manufacturer: 'IBM' },
- { pattern: '^IBM.*', manufacturer: 'IBM' },
- { pattern: '^FUJITSU.*', manufacturer: 'Fujitsu' },
- { pattern: '^MP.*', manufacturer: 'Fujitsu' },
- { pattern: '^MK.*', manufacturer: 'Toshiba' },
- { pattern: 'MAXTO.*', manufacturer: 'Maxtor' },
- { pattern: 'PIONEER.*', manufacturer: 'Pioneer' },
- { pattern: 'PHILIPS.*', manufacturer: 'Philips' },
- { pattern: 'QUANTUM.*', manufacturer: 'Quantum Technology' },
- { pattern: 'FIREBALL.*', manufacturer: 'Quantum Technology' },
- { pattern: '^VBOX.*', manufacturer: 'VirtualBox' },
- { pattern: 'CORSAIR.*', manufacturer: 'Corsair Components' },
- { pattern: 'CRUCIAL.*', manufacturer: 'Crucial' },
- { pattern: 'ECM.*', manufacturer: 'ECM' },
- { pattern: 'INTEL.*', manufacturer: 'INTEL' },
- { pattern: 'EVO.*', manufacturer: 'Samsung' },
- { pattern: 'APPLE.*', manufacturer: 'Apple' },
- ];
-
- let result = '';
- if (model) {
- model = model.toUpperCase();
- diskManufacturers.forEach((manufacturer) => {
- const re = RegExp(manufacturer.pattern);
- if (re.test(model)) { result = manufacturer.manufacturer; }
- });
- }
- return result;
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- const commitResult = res => {
- for (let i = 0; i < res.length; i++) {
- delete res[i].BSDName;
- }
- if (callback) {
- callback(res);
- }
- resolve(res);
- };
-
- let result = [];
- let cmd = '';
-
- if (_linux) {
- let cmdFullSmart = '';
-
- exec('export LC_ALL=C; lsblk -ablJO 2>/dev/null; unset LC_ALL', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- try {
- const out = stdout.toString().trim();
- let devices = [];
- try {
- const outJSON = JSON.parse(out);
- if (outJSON && {}.hasOwnProperty.call(outJSON, 'blockdevices')) {
- devices = outJSON.blockdevices.filter(item => { return (item.type === 'disk') && item.size > 0 && (item.model !== null || (item.mountpoint === null && item.label === null && item.fstype === null && item.parttype === null && item.path && item.path.indexOf('/ram') !== 0 && item.path.indexOf('/loop') !== 0 && item['disc-max'] && item['disc-max'] !== 0)); });
- }
- } catch (e) {
- // fallback to older version of lsblk
- try {
- const out2 = execSync('export LC_ALL=C; lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER,GROUP 2>/dev/null; unset LC_ALL', util.execOptsLinux).toString();
- let lines = blkStdoutToObject(out2).split('\n');
- const data = parseBlk(lines);
- devices = data.filter(item => { return (item.type === 'disk') && item.size > 0 && ((item.model !== null && item.model !== '') || (item.mount === '' && item.label === '' && item.fsType === '')); });
- } catch (e) {
- util.noop();
- }
- }
- devices.forEach((device) => {
- let mediumType = '';
- const BSDName = '/dev/' + device.name;
- const logical = device.name;
- try {
- mediumType = execSync('cat /sys/block/' + logical + '/queue/rotational 2>/dev/null', util.execOptsLinux).toString().split('\n')[0];
- } catch (e) {
- util.noop();
- }
- let interfaceType = device.tran ? device.tran.toUpperCase().trim() : '';
- if (interfaceType === 'NVME') {
- mediumType = '2';
- interfaceType = 'PCIe';
- }
- result.push({
- device: BSDName,
- type: (mediumType === '0' ? 'SSD' : (mediumType === '1' ? 'HD' : (mediumType === '2' ? 'NVMe' : (device.model && device.model.indexOf('SSD') > -1 ? 'SSD' : (device.model && device.model.indexOf('NVM') > -1 ? 'NVMe' : 'HD'))))),
- name: device.model || '',
- vendor: getVendorFromModel(device.model) || (device.vendor ? device.vendor.trim() : ''),
- size: device.size || 0,
- bytesPerSector: null,
- totalCylinders: null,
- totalHeads: null,
- totalSectors: null,
- totalTracks: null,
- tracksPerCylinder: null,
- sectorsPerTrack: null,
- firmwareRevision: device.rev ? device.rev.trim() : '',
- serialNum: device.serial ? device.serial.trim() : '',
- interfaceType: interfaceType,
- smartStatus: 'unknown',
- temperature: null,
- BSDName: BSDName
- });
- cmd += `printf "\n${BSDName}|"; smartctl -H ${BSDName} | grep overall;`;
- cmdFullSmart += `${cmdFullSmart ? 'printf ",";' : ''}smartctl -a -j ${BSDName};`;
- });
- } catch (e) {
- util.noop();
- }
- }
- // check S.M.A.R.T. status
- if (cmdFullSmart) {
- exec(cmdFullSmart, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- try {
- const data = JSON.parse(`[${stdout}]`);
- data.forEach(disk => {
- const diskBSDName = disk.smartctl.argv[disk.smartctl.argv.length - 1];
-
- for (let i = 0; i < result.length; i++) {
- if (result[i].BSDName === diskBSDName) {
- result[i].smartStatus = (disk.smart_status.passed ? 'Ok' : (disk.smart_status.passed === false ? 'Predicted Failure' : 'unknown'));
- if (disk.temperature && disk.temperature.current) {
- result[i].temperature = disk.temperature.current;
- }
- result[i].smartData = disk;
- }
- }
- });
- commitResult(result);
- } catch (e) {
- if (cmd) {
- cmd = cmd + 'printf "\n"';
- exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- lines.forEach(line => {
- if (line) {
- let parts = line.split('|');
- if (parts.length === 2) {
- let BSDName = parts[0];
- parts[1] = parts[1].trim();
- let parts2 = parts[1].split(':');
- if (parts2.length === 2) {
- parts2[1] = parts2[1].trim();
- let status = parts2[1].toLowerCase();
- for (let i = 0; i < result.length; i++) {
- if (result[i].BSDName === BSDName) {
- result[i].smartStatus = (status === 'passed' ? 'Ok' : (status === 'failed!' ? 'Predicted Failure' : 'unknown'));
- }
- }
- }
- }
- }
- });
- commitResult(result);
- });
- } else {
- commitResult(result);
- }
- }
- });
- } else {
- commitResult(result);
- }
- });
- }
- if (_freebsd || _openbsd || _netbsd) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_darwin) {
- exec('system_profiler SPSerialATADataType SPNVMeDataType SPUSBDataType', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- // split by type:
- let lines = stdout.toString().split('\n');
- let linesSATA = [];
- let linesNVMe = [];
- let linesUSB = [];
- let dataType = 'SATA';
- lines.forEach(line => {
- if (line === 'NVMExpress:') { dataType = 'NVMe'; }
- else if (line === 'USB:') { dataType = 'USB'; }
- else if (line === 'SATA/SATA Express:') { dataType = 'SATA'; }
- else if (dataType === 'SATA') { linesSATA.push(line); }
- else if (dataType === 'NVMe') { linesNVMe.push(line); }
- else if (dataType === 'USB') { linesUSB.push(line); }
- });
- try {
- // Serial ATA Drives
- let devices = linesSATA.join('\n').split(' Physical Interconnect: ');
- devices.shift();
- devices.forEach(function (device) {
- device = 'InterfaceType: ' + device;
- let lines = device.split('\n');
- const mediumType = util.getValue(lines, 'Medium Type', ':', true).trim();
- const sizeStr = util.getValue(lines, 'capacity', ':', true).trim();
- const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
- if (sizeStr) {
- let sizeValue = 0;
- if (sizeStr.indexOf('(') >= 0) {
- sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
- }
- if (!sizeValue) {
- sizeValue = parseInt(sizeStr);
- }
- if (sizeValue) {
- const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
- result.push({
- device: BSDName,
- type: mediumType.startsWith('Solid') ? 'SSD' : 'HD',
- name: util.getValue(lines, 'Model', ':', true).trim(),
- vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()) || util.getValue(lines, 'Manufacturer', ':', true),
- size: sizeValue,
- bytesPerSector: null,
- totalCylinders: null,
- totalHeads: null,
- totalSectors: null,
- totalTracks: null,
- tracksPerCylinder: null,
- sectorsPerTrack: null,
- firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
- serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
- interfaceType: util.getValue(lines, 'InterfaceType', ':', true).trim(),
- smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
- temperature: null,
- BSDName: BSDName
- });
- cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
- }
- }
- });
- } catch (e) {
- util.noop();
- }
-
- // NVME Drives
- try {
- let devices = linesNVMe.join('\n').split('\n\n Capacity:');
- devices.shift();
- devices.forEach(function (device) {
- device = '!Capacity: ' + device;
- let lines = device.split('\n');
- const linkWidth = util.getValue(lines, 'link width', ':', true).trim();
- const sizeStr = util.getValue(lines, '!capacity', ':', true).trim();
- const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
- if (sizeStr) {
- let sizeValue = 0;
- if (sizeStr.indexOf('(') >= 0) {
- sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
- }
- if (!sizeValue) {
- sizeValue = parseInt(sizeStr);
- }
- if (sizeValue) {
- const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
- result.push({
- device: BSDName,
- type: 'NVMe',
- name: util.getValue(lines, 'Model', ':', true).trim(),
- vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()),
- size: sizeValue,
- bytesPerSector: null,
- totalCylinders: null,
- totalHeads: null,
- totalSectors: null,
- totalTracks: null,
- tracksPerCylinder: null,
- sectorsPerTrack: null,
- firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
- serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
- interfaceType: ('PCIe ' + linkWidth).trim(),
- smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
- temperature: null,
- BSDName: BSDName
- });
- cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
- }
- }
- });
- } catch (e) {
- util.noop();
- }
- // USB Drives
- try {
- let devices = linesUSB.join('\n').replaceAll('Media:\n ', 'Model:').split('\n\n Product ID:');
- devices.shift();
- devices.forEach(function (device) {
- let lines = device.split('\n');
- const sizeStr = util.getValue(lines, 'Capacity', ':', true).trim();
- const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
- if (sizeStr) {
- let sizeValue = 0;
- if (sizeStr.indexOf('(') >= 0) {
- sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
- }
- if (!sizeValue) {
- sizeValue = parseInt(sizeStr);
- }
- if (sizeValue) {
- const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
- result.push({
- device: BSDName,
- type: 'USB',
- name: util.getValue(lines, 'Model', ':', true).trim().replaceAll(':', ''),
- vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()),
- size: sizeValue,
- bytesPerSector: null,
- totalCylinders: null,
- totalHeads: null,
- totalSectors: null,
- totalTracks: null,
- tracksPerCylinder: null,
- sectorsPerTrack: null,
- firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
- serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
- interfaceType: 'USB',
- smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
- temperature: null,
- BSDName: BSDName
- });
- cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
- }
- }
- });
- } catch (e) {
- util.noop();
- }
- if (cmd) {
- cmd = cmd + 'printf "\n"';
- exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- lines.forEach(line => {
- if (line) {
- let parts = line.split('|');
- if (parts.length === 2) {
- let BSDName = parts[0];
- parts[1] = parts[1].trim();
- let parts2 = parts[1].split(':');
- if (parts2.length === 2) {
- parts2[1] = parts2[1].trim();
- let status = parts2[1].toLowerCase();
- for (let i = 0; i < result.length; i++) {
- if (result[i].BSDName === BSDName) {
- result[i].smartStatus = (status === 'not supported' ? 'not supported' : (status === 'verified' ? 'Ok' : (status === 'failing' ? 'Predicted Failure' : 'unknown')));
- }
- }
- }
- }
- }
- });
- for (let i = 0; i < result.length; i++) {
- delete result[i].BSDName;
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- for (let i = 0; i < result.length; i++) {
- delete result[i].BSDName;
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- }
- });
- }
- if (_windows) {
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance Win32_DiskDrive | select Caption,Size,Status,PNPDeviceId,DeviceId,BytesPerSector,TotalCylinders,TotalHeads,TotalSectors,TotalTracks,TracksPerCylinder,SectorsPerTrack,FirmwareRevision,SerialNumber,InterfaceType | fl'));
- workload.push(util.powerShell('Get-PhysicalDisk | select BusType,MediaType,FriendlyName,Model,SerialNumber,Size | fl'));
- if (util.smartMonToolsInstalled()) {
- try {
- const smartDev = JSON.parse(execSync('smartctl --scan -j').toString());
- if (smartDev && smartDev.devices && smartDev.devices.length > 0) {
- smartDev.devices.forEach((dev) => {
- workload.push(execPromiseSave(`smartctl -j -a ${dev.name}`, util.execOptsWin));
- });
- }
- } catch (e) {
- util.noop();
- }
- }
- util.promiseAll(
- workload
- ).then((data) => {
- let devices = data.results[0].toString().split(/\n\s*\n/);
- devices.forEach(function (device) {
- let lines = device.split('\r\n');
- const size = util.getValue(lines, 'Size', ':').trim();
- const status = util.getValue(lines, 'Status', ':').trim().toLowerCase();
- if (size) {
- result.push({
- device: util.getValue(lines, 'DeviceId', ':'), // changed from PNPDeviceId to DeviceID (be be able to match devices)
- type: device.indexOf('SSD') > -1 ? 'SSD' : 'HD', // just a starting point ... better: MSFT_PhysicalDisk - Media Type ... see below
- name: util.getValue(lines, 'Caption', ':'),
- vendor: getVendorFromModel(util.getValue(lines, 'Caption', ':', true).trim()),
- size: parseInt(size),
- bytesPerSector: parseInt(util.getValue(lines, 'BytesPerSector', ':')),
- totalCylinders: parseInt(util.getValue(lines, 'TotalCylinders', ':')),
- totalHeads: parseInt(util.getValue(lines, 'TotalHeads', ':')),
- totalSectors: parseInt(util.getValue(lines, 'TotalSectors', ':')),
- totalTracks: parseInt(util.getValue(lines, 'TotalTracks', ':')),
- tracksPerCylinder: parseInt(util.getValue(lines, 'TracksPerCylinder', ':')),
- sectorsPerTrack: parseInt(util.getValue(lines, 'SectorsPerTrack', ':')),
- firmwareRevision: util.getValue(lines, 'FirmwareRevision', ':').trim(),
- serialNum: util.getValue(lines, 'SerialNumber', ':').trim(),
- interfaceType: util.getValue(lines, 'InterfaceType', ':').trim(),
- smartStatus: (status === 'ok' ? 'Ok' : (status === 'degraded' ? 'Degraded' : (status === 'pred fail' ? 'Predicted Failure' : 'Unknown'))),
- temperature: null,
- });
- }
- });
- devices = data.results[1].split(/\n\s*\n/);
- devices.forEach(function (device) {
- let lines = device.split('\r\n');
- const serialNum = util.getValue(lines, 'SerialNumber', ':').trim();
- const name = util.getValue(lines, 'FriendlyName', ':').trim().replace('Msft ', 'Microsoft');
- const size = util.getValue(lines, 'Size', ':').trim();
- const model = util.getValue(lines, 'Model', ':').trim();
- const interfaceType = util.getValue(lines, 'BusType', ':').trim();
- let mediaType = util.getValue(lines, 'MediaType', ':').trim();
- if (mediaType === '3' || mediaType === 'HDD') { mediaType = 'HD'; }
- if (mediaType === '4') { mediaType = 'SSD'; }
- if (mediaType === '5') { mediaType = 'SCM'; }
- if (mediaType === 'Unspecified' && (model.toLowerCase().indexOf('virtual') > -1 || model.toLowerCase().indexOf('vbox') > -1)) { mediaType = 'Virtual'; }
- if (size) {
- let i = util.findObjectByKey(result, 'serialNum', serialNum);
- if (i === -1 || serialNum === '') {
- i = util.findObjectByKey(result, 'name', name);
- }
- if (i != -1) {
- result[i].type = mediaType;
- result[i].interfaceType = interfaceType;
- }
- }
- });
- // S.M.A.R.T
- data.results.shift();
- data.results.shift();
- if (data.results.length) {
- data.results.forEach((smartStr) => {
- try {
- const smartData = JSON.parse(smartStr);
- if (smartData.serial_number) {
- const serialNum = smartData.serial_number;
- let i = util.findObjectByKey(result, 'serialNum', serialNum);
- if (i != -1) {
- result[i].smartStatus = (smartData.smart_status && smartData.smart_status.passed ? 'Ok' : (smartData.smart_status && smartData.smart_status.passed === false ? 'Predicted Failure' : 'unknown'));
- if (smartData.temperature && smartData.temperature.current) {
- result[i].temperature = smartData.temperature.current;
- }
- result[i].smartData = smartData;
- }
- }
- } catch (e) {
- util.noop();
- }
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.diskLayout = diskLayout;
-
-
-/***/ }),
-
-/***/ 49404:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// graphics.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 7. Graphics (controller, display)
-// ----------------------------------------------------------------------------------
-
-const fs = __nccwpck_require__(79896);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-let _nvidiaSmiPath = '';
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-let _resolutionX = 0;
-let _resolutionY = 0;
-let _pixelDepth = 0;
-let _refreshRate = 0;
-
-const videoTypes = {
- '-2': 'UNINITIALIZED',
- '-1': 'OTHER',
- '0': 'HD15',
- '1': 'SVIDEO',
- '2': 'Composite video',
- '3': 'Component video',
- '4': 'DVI',
- '5': 'HDMI',
- '6': 'LVDS',
- '8': 'D_JPN',
- '9': 'SDI',
- '10': 'DP',
- '11': 'DP embedded',
- '12': 'UDI',
- '13': 'UDI embedded',
- '14': 'SDTVDONGLE',
- '15': 'MIRACAST',
- '2147483648': 'INTERNAL'
-};
-
-function getVendorFromModel(model) {
- const manufacturers = [
- { pattern: '^LG.+', manufacturer: 'LG' },
- { pattern: '^BENQ.+', manufacturer: 'BenQ' },
- { pattern: '^ASUS.+', manufacturer: 'Asus' },
- { pattern: '^DELL.+', manufacturer: 'Dell' },
- { pattern: '^SAMSUNG.+', manufacturer: 'Samsung' },
- { pattern: '^VIEWSON.+', manufacturer: 'ViewSonic' },
- { pattern: '^SONY.+', manufacturer: 'Sony' },
- { pattern: '^ACER.+', manufacturer: 'Acer' },
- { pattern: '^AOC.+', manufacturer: 'AOC Monitors' },
- { pattern: '^HP.+', manufacturer: 'HP' },
- { pattern: '^EIZO.?', manufacturer: 'Eizo' },
- { pattern: '^PHILIPS.?', manufacturer: 'Philips' },
- { pattern: '^IIYAMA.?', manufacturer: 'Iiyama' },
- { pattern: '^SHARP.?', manufacturer: 'Sharp' },
- { pattern: '^NEC.?', manufacturer: 'NEC' },
- { pattern: '^LENOVO.?', manufacturer: 'Lenovo' },
- { pattern: 'COMPAQ.?', manufacturer: 'Compaq' },
- { pattern: 'APPLE.?', manufacturer: 'Apple' },
- { pattern: 'INTEL.?', manufacturer: 'Intel' },
- { pattern: 'AMD.?', manufacturer: 'AMD' },
- { pattern: 'NVIDIA.?', manufacturer: 'NVDIA' },
- ];
-
- let result = '';
- if (model) {
- model = model.toUpperCase();
- manufacturers.forEach((manufacturer) => {
- const re = RegExp(manufacturer.pattern);
- if (re.test(model)) { result = manufacturer.manufacturer; }
- });
- }
- return result;
-}
-
-function getVendorFromId(id) {
- const vendors = {
- '610': 'Apple',
- '1e6d': 'LG',
- '10ac': 'DELL',
- '4dd9': 'Sony',
- '38a3': 'NEC',
- };
- return vendors[id] || '';
-}
-
-function vendorToId(str) {
- let result = '';
- str = (str || '').toLowerCase();
- if (str.indexOf('apple') >= 0) { result = '0x05ac'; }
- else if (str.indexOf('nvidia') >= 0) { result = '0x10de'; }
- else if (str.indexOf('intel') >= 0) { result = '0x8086'; }
- else if (str.indexOf('ati') >= 0 || str.indexOf('amd') >= 0) { result = '0x1002'; }
-
- return result;
-}
-
-function getMetalVersion(id) {
- const families = {
- 'spdisplays_mtlgpufamilymac1': 'mac1',
- 'spdisplays_mtlgpufamilymac2': 'mac2',
- 'spdisplays_mtlgpufamilyapple1': 'apple1',
- 'spdisplays_mtlgpufamilyapple2': 'apple2',
- 'spdisplays_mtlgpufamilyapple3': 'apple3',
- 'spdisplays_mtlgpufamilyapple4': 'apple4',
- 'spdisplays_mtlgpufamilyapple5': 'apple5',
- 'spdisplays_mtlgpufamilyapple6': 'apple6',
- 'spdisplays_mtlgpufamilyapple7': 'apple7',
- 'spdisplays_metalfeaturesetfamily11': 'family1_v1',
- 'spdisplays_metalfeaturesetfamily12': 'family1_v2',
- 'spdisplays_metalfeaturesetfamily13': 'family1_v3',
- 'spdisplays_metalfeaturesetfamily14': 'family1_v4',
- 'spdisplays_metalfeaturesetfamily21': 'family2_v1'
- };
- return families[id] || '';
-}
-
-function graphics(callback) {
-
- function parseLinesDarwin(graphicsArr) {
- const res = {
- controllers: [],
- displays: []
- };
- try {
- graphicsArr.forEach(function (item) {
- // controllers
- const bus = ((item.sppci_bus || '').indexOf('builtin') > -1 ? 'Built-In' : ((item.sppci_bus || '').indexOf('pcie') > -1 ? 'PCIe' : ''));
- const vram = (parseInt((item.spdisplays_vram || ''), 10) || 0) * (((item.spdisplays_vram || '').indexOf('GB') > -1) ? 1024 : 1);
- const vramDyn = (parseInt((item.spdisplays_vram_shared || ''), 10) || 0) * (((item.spdisplays_vram_shared || '').indexOf('GB') > -1) ? 1024 : 1);
- let metalVersion = getMetalVersion(item.spdisplays_metal || item.spdisplays_metalfamily || '');
- res.controllers.push({
- vendor: getVendorFromModel(item.spdisplays_vendor || '') || item.spdisplays_vendor || '',
- model: item.sppci_model || '',
- bus,
- vramDynamic: bus === 'Built-In',
- vram: vram || vramDyn || null,
- deviceId: item['spdisplays_device-id'] || '',
- vendorId: item['spdisplays_vendor-id'] || vendorToId((item['spdisplays_vendor'] || '') + (item.sppci_model || '')),
- external: (item.sppci_device_type === 'spdisplays_egpu'),
- cores: item['sppci_cores'] || null,
- metalVersion
- });
-
- // displays
- if (item.spdisplays_ndrvs && item.spdisplays_ndrvs.length) {
- item.spdisplays_ndrvs.forEach(function (displayItem) {
- const connectionType = displayItem['spdisplays_connection_type'] || '';
- const currentResolutionParts = (displayItem['_spdisplays_resolution'] || '').split('@');
- const currentResolution = currentResolutionParts[0].split('x');
- const pixelParts = (displayItem['_spdisplays_pixels'] || '').split('x');
- const pixelDepthString = displayItem['spdisplays_depth'] || '';
- const serial = displayItem['_spdisplays_display-serial-number'] || displayItem['_spdisplays_display-serial-number2'] || null;
- res.displays.push({
- vendor: getVendorFromId(displayItem['_spdisplays_display-vendor-id'] || '') || getVendorFromModel(displayItem['_name'] || ''),
- vendorId: displayItem['_spdisplays_display-vendor-id'] || '',
- model: displayItem['_name'] || '',
- productionYear: displayItem['_spdisplays_display-year'] || null,
- serial: serial !== '0' ? serial : null,
- displayId: displayItem['_spdisplays_displayID'] || null,
- main: displayItem['spdisplays_main'] ? displayItem['spdisplays_main'] === 'spdisplays_yes' : false,
- builtin: (displayItem['spdisplays_display_type'] || '').indexOf('built-in') > -1,
- connection: ((connectionType.indexOf('_internal') > -1) ? 'Internal' : ((connectionType.indexOf('_displayport') > -1) ? 'Display Port' : ((connectionType.indexOf('_hdmi') > -1) ? 'HDMI' : null))),
- sizeX: null,
- sizeY: null,
- pixelDepth: (pixelDepthString === 'CGSThirtyBitColor' ? 30 : (pixelDepthString === 'CGSThirtytwoBitColor' ? 32 : (pixelDepthString === 'CGSTwentyfourBitColor' ? 24 : null))),
- resolutionX: pixelParts.length > 1 ? parseInt(pixelParts[0], 10) : null,
- resolutionY: pixelParts.length > 1 ? parseInt(pixelParts[1], 10) : null,
- currentResX: currentResolution.length > 1 ? parseInt(currentResolution[0], 10) : null,
- currentResY: currentResolution.length > 1 ? parseInt(currentResolution[1], 10) : null,
- positionX: 0,
- positionY: 0,
- currentRefreshRate: currentResolutionParts.length > 1 ? parseInt(currentResolutionParts[1], 10) : null,
-
- });
- });
- }
- });
- return res;
- } catch (e) {
- return res;
- }
- }
-
- function parseLinesLinuxControllers(lines) {
- let controllers = [];
- let currentController = {
- vendor: '',
- subVendor: '',
- model: '',
- bus: '',
- busAddress: '',
- vram: null,
- vramDynamic: false,
- pciID: ''
- };
- let isGraphicsController = false;
- // PCI bus IDs
- let pciIDs = [];
- try {
- pciIDs = execSync('export LC_ALL=C; dmidecode -t 9 2>/dev/null; unset LC_ALL | grep "Bus Address: "', util.execOptsLinux).toString().split('\n');
- for (let i = 0; i < pciIDs.length; i++) {
- pciIDs[i] = pciIDs[i].replace('Bus Address:', '').replace('0000:', '').trim();
- }
- pciIDs = pciIDs.filter(function (el) {
- return el != null && el;
- });
- } catch (e) {
- util.noop();
- }
- let i = 1;
- lines.forEach((line) => {
- let subsystem = '';
- if (i < lines.length && lines[i]) { // get next line;
- subsystem = lines[i];
- if (subsystem.indexOf(':') > 0) {
- subsystem = subsystem.split(':')[1];
- }
- }
- if ('' !== line.trim()) {
- if (' ' !== line[0] && '\t' !== line[0]) { // first line of new entry
- let isExternal = (pciIDs.indexOf(line.split(' ')[0]) >= 0);
- let vgapos = line.toLowerCase().indexOf(' vga ');
- let _3dcontrollerpos = line.toLowerCase().indexOf('3d controller');
- if (vgapos !== -1 || _3dcontrollerpos !== -1) { // VGA
- if (_3dcontrollerpos !== -1 && vgapos === -1) {
- vgapos = _3dcontrollerpos;
- }
- if (currentController.vendor || currentController.model || currentController.bus || currentController.vram !== null || currentController.vramDynamic) { // already a controller found
- controllers.push(currentController);
- currentController = {
- vendor: '',
- model: '',
- bus: '',
- busAddress: '',
- vram: null,
- vramDynamic: false,
- };
- }
-
- const pciIDCandidate = line.split(' ')[0];
- if (/[\da-fA-F]{2}:[\da-fA-F]{2}\.[\da-fA-F]/.test(pciIDCandidate)) {
- currentController.busAddress = pciIDCandidate;
- }
- isGraphicsController = true;
- let endpos = line.search(/\[[0-9a-f]{4}:[0-9a-f]{4}]|$/);
- let parts = line.substr(vgapos, endpos - vgapos).split(':');
- currentController.busAddress = line.substr(0, vgapos).trim();
- if (parts.length > 1) {
- parts[1] = parts[1].trim();
- if (parts[1].toLowerCase().indexOf('corporation') >= 0) {
- currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf('corporation') + 11).trim();
- currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf('corporation') + 11, 200).split('(')[0].trim();
- currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard';
- currentController.vram = null;
- currentController.vramDynamic = false;
- } else if (parts[1].toLowerCase().indexOf(' inc.') >= 0) {
- if ((parts[1].match(/]/g) || []).length > 1) {
- currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim();
- currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim();
- } else {
- currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' inc.') + 5).trim();
- currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' inc.') + 5, 200).trim().split('(')[0].trim();
- }
- currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard';
- currentController.vram = null;
- currentController.vramDynamic = false;
- } else if (parts[1].toLowerCase().indexOf(' ltd.') >= 0) {
- if ((parts[1].match(/]/g) || []).length > 1) {
- currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim();
- currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim();
- } else {
- currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' ltd.') + 5).trim();
- currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' ltd.') + 5, 200).trim().split('(')[0].trim();
- }
- }
- if (currentController.model && subsystem.indexOf(currentController.model) !== -1) {
- const subVendor = subsystem.split(currentController.model)[0].trim();
- if (subVendor) {
- currentController.subVendor = subVendor;
- }
- }
- }
-
- } else {
- isGraphicsController = false;
- }
- }
- if (isGraphicsController) { // within VGA details
- let parts = line.split(':');
- if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('devicename') !== -1 && parts[1].toLowerCase().indexOf('onboard') !== -1) { currentController.bus = 'Onboard'; }
- if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('region') !== -1 && parts[1].toLowerCase().indexOf('memory') !== -1) {
- let memparts = parts[1].split('=');
- if (memparts.length > 1) {
- currentController.vram = parseInt(memparts[1]);
- }
- }
- }
- }
- i++;
- });
-
- if (currentController.vendor || currentController.model || currentController.bus || currentController.busAddress || currentController.vram !== null || currentController.vramDynamic) { // already a controller found
- controllers.push(currentController);
- }
- return (controllers);
- }
-
- function parseLinesLinuxClinfo(controllers, lines) {
- const fieldPattern = /\[([^\]]+)\]\s+(\w+)\s+(.*)/;
- const devices = lines.reduce((devices, line) => {
- const field = fieldPattern.exec(line.trim());
- if (field) {
- if (!devices[field[1]]) {
- devices[field[1]] = {};
- }
- devices[field[1]][field[2]] = field[3];
- }
- return devices;
- }, {});
- for (let deviceId in devices) {
- const device = devices[deviceId];
- if (device['CL_DEVICE_TYPE'] === 'CL_DEVICE_TYPE_GPU') {
- let busAddress;
- if (device['CL_DEVICE_TOPOLOGY_AMD']) {
- const bdf = device['CL_DEVICE_TOPOLOGY_AMD'].match(/[a-zA-Z0-9]+:\d+\.\d+/);
- if (bdf) {
- busAddress = bdf[0];
- }
- } else if (device['CL_DEVICE_PCI_BUS_ID_NV'] && device['CL_DEVICE_PCI_SLOT_ID_NV']) {
- const bus = parseInt(device['CL_DEVICE_PCI_BUS_ID_NV']);
- const slot = parseInt(device['CL_DEVICE_PCI_SLOT_ID_NV']);
- if (!isNaN(bus) && !isNaN(slot)) {
- const b = bus & 0xff;
- const d = (slot >> 3) & 0xff;
- const f = slot & 0x07;
- busAddress = `${b.toString().padStart(2, '0')}:${d.toString().padStart(2, '0')}.${f}`;
- }
- }
- if (busAddress) {
- let controller = controllers.find(controller => controller.busAddress === busAddress);
- if (!controller) {
- controller = {
- vendor: '',
- model: '',
- bus: '',
- busAddress,
- vram: null,
- vramDynamic: false
- };
- controllers.push(controller);
- }
- controller.vendor = device['CL_DEVICE_VENDOR'];
- if (device['CL_DEVICE_BOARD_NAME_AMD']) {
- controller.model = device['CL_DEVICE_BOARD_NAME_AMD'];
- } else {
- controller.model = device['CL_DEVICE_NAME'];
- }
- const memory = parseInt(device['CL_DEVICE_GLOBAL_MEM_SIZE']);
- if (!isNaN(memory)) {
- controller.vram = Math.round(memory / 1024 / 1024);
- }
- }
- }
- }
- return controllers;
- }
-
- function getNvidiaSmi() {
- if (_nvidiaSmiPath) {
- return _nvidiaSmiPath;
- }
-
- if (_windows) {
- try {
- const basePath = util.WINDIR + '\\System32\\DriverStore\\FileRepository';
- // find all directories that have an nvidia-smi.exe file
- const candidateDirs = fs.readdirSync(basePath).filter(dir => {
- return fs.readdirSync([basePath, dir].join('/')).includes('nvidia-smi.exe');
- });
- // use the directory with the most recently created nvidia-smi.exe file
- const targetDir = candidateDirs.reduce((prevDir, currentDir) => {
- const previousNvidiaSmi = fs.statSync([basePath, prevDir, 'nvidia-smi.exe'].join('/'));
- const currentNvidiaSmi = fs.statSync([basePath, currentDir, 'nvidia-smi.exe'].join('/'));
- return (previousNvidiaSmi.ctimeMs > currentNvidiaSmi.ctimeMs) ? prevDir : currentDir;
- });
-
- if (targetDir) {
- _nvidiaSmiPath = [basePath, targetDir, 'nvidia-smi.exe'].join('/');
- }
- } catch (e) {
- util.noop();
- }
- } else if (_linux) {
- _nvidiaSmiPath = 'nvidia-smi';
- }
- return _nvidiaSmiPath;
- }
-
- function nvidiaSmi(options) {
- const nvidiaSmiExe = getNvidiaSmi();
- options = options || util.execOptsWin;
- if (nvidiaSmiExe) {
- const nvidiaSmiOpts = '--query-gpu=driver_version,pci.sub_device_id,name,pci.bus_id,fan.speed,memory.total,memory.used,memory.free,utilization.gpu,utilization.memory,temperature.gpu,temperature.memory,power.draw,power.limit,clocks.gr,clocks.mem --format=csv,noheader,nounits';
- const cmd = nvidiaSmiExe + ' ' + nvidiaSmiOpts + (_linux ? ' 2>/dev/null' : '');
- if (_linux) {
- options.stdio = ['pipe', 'pipe', 'ignore'];
- }
- try {
- const res = execSync(cmd, options).toString();
- return res;
- } catch (e) {
- util.noop();
- }
- }
- return '';
- }
-
- function nvidiaDevices() {
-
- function safeParseNumber(value) {
- if ([null, undefined].includes(value)) {
- return value;
- }
- return parseFloat(value);
- }
-
- const stdout = nvidiaSmi();
- if (!stdout) {
- return [];
- }
-
- const gpus = stdout.split('\n').filter(Boolean);
- let results = gpus.map(gpu => {
- const splittedData = gpu.split(', ').map(value => value.includes('N/A') ? undefined : value);
- if (splittedData.length === 16) {
- return {
- driverVersion: splittedData[0],
- subDeviceId: splittedData[1],
- name: splittedData[2],
- pciBus: splittedData[3],
- fanSpeed: safeParseNumber(splittedData[4]),
- memoryTotal: safeParseNumber(splittedData[5]),
- memoryUsed: safeParseNumber(splittedData[6]),
- memoryFree: safeParseNumber(splittedData[7]),
- utilizationGpu: safeParseNumber(splittedData[8]),
- utilizationMemory: safeParseNumber(splittedData[9]),
- temperatureGpu: safeParseNumber(splittedData[10]),
- temperatureMemory: safeParseNumber(splittedData[11]),
- powerDraw: safeParseNumber(splittedData[12]),
- powerLimit: safeParseNumber(splittedData[13]),
- clockCore: safeParseNumber(splittedData[14]),
- clockMemory: safeParseNumber(splittedData[15]),
- };
- } else {
- return {};
- }
- });
- results = results.filter((item) => {
- return ('pciBus' in item);
- });
- return results;
- }
-
- function mergeControllerNvidia(controller, nvidia) {
- if (nvidia.driverVersion) { controller.driverVersion = nvidia.driverVersion; }
- if (nvidia.subDeviceId) { controller.subDeviceId = nvidia.subDeviceId; }
- if (nvidia.name) { controller.name = nvidia.name; }
- if (nvidia.pciBus) { controller.pciBus = nvidia.pciBus; }
- if (nvidia.fanSpeed) { controller.fanSpeed = nvidia.fanSpeed; }
- if (nvidia.memoryTotal) {
- controller.memoryTotal = nvidia.memoryTotal;
- controller.vram = nvidia.memoryTotal;
- controller.vramDynamic = false;
- }
- if (nvidia.memoryUsed) { controller.memoryUsed = nvidia.memoryUsed; }
- if (nvidia.memoryFree) { controller.memoryFree = nvidia.memoryFree; }
- if (nvidia.utilizationGpu) { controller.utilizationGpu = nvidia.utilizationGpu; }
- if (nvidia.utilizationMemory) { controller.utilizationMemory = nvidia.utilizationMemory; }
- if (nvidia.temperatureGpu) { controller.temperatureGpu = nvidia.temperatureGpu; }
- if (nvidia.temperatureMemory) { controller.temperatureMemory = nvidia.temperatureMemory; }
- if (nvidia.powerDraw) { controller.powerDraw = nvidia.powerDraw; }
- if (nvidia.powerLimit) { controller.powerLimit = nvidia.powerLimit; }
- if (nvidia.clockCore) { controller.clockCore = nvidia.clockCore; }
- if (nvidia.clockMemory) { controller.clockMemory = nvidia.clockMemory; }
- return controller;
- }
-
- function parseLinesLinuxEdid(edid) {
- // parsen EDID
- // --> model
- // --> resolutionx
- // --> resolutiony
- // --> builtin = false
- // --> pixeldepth (?)
- // --> sizex
- // --> sizey
- let result = {
- vendor: '',
- model: '',
- deviceName: '',
- main: false,
- builtin: false,
- connection: '',
- sizeX: null,
- sizeY: null,
- pixelDepth: null,
- resolutionX: null,
- resolutionY: null,
- currentResX: null,
- currentResY: null,
- positionX: 0,
- positionY: 0,
- currentRefreshRate: null
- };
- // find first "Detailed Timing Description"
- let start = 108;
- if (edid.substr(start, 6) === '000000') {
- start += 36;
- }
- if (edid.substr(start, 6) === '000000') {
- start += 36;
- }
- if (edid.substr(start, 6) === '000000') {
- start += 36;
- }
- if (edid.substr(start, 6) === '000000') {
- start += 36;
- }
- result.resolutionX = parseInt('0x0' + edid.substr(start + 8, 1) + edid.substr(start + 4, 2));
- result.resolutionY = parseInt('0x0' + edid.substr(start + 14, 1) + edid.substr(start + 10, 2));
- result.sizeX = parseInt('0x0' + edid.substr(start + 28, 1) + edid.substr(start + 24, 2));
- result.sizeY = parseInt('0x0' + edid.substr(start + 29, 1) + edid.substr(start + 26, 2));
- // monitor name
- start = edid.indexOf('000000fc00'); // find first "Monitor Description Data"
- if (start >= 0) {
- let model_raw = edid.substr(start + 10, 26);
- if (model_raw.indexOf('0a') !== -1) {
- model_raw = model_raw.substr(0, model_raw.indexOf('0a'));
- }
- try {
- if (model_raw.length > 2) {
- result.model = model_raw.match(/.{1,2}/g).map(function (v) {
- return String.fromCharCode(parseInt(v, 16));
- }).join('');
- }
- } catch (e) {
- util.noop();
- }
- } else {
- result.model = '';
- }
- return result;
- }
-
- function parseLinesLinuxDisplays(lines, depth) {
- let displays = [];
- let currentDisplay = {
- vendor: '',
- model: '',
- deviceName: '',
- main: false,
- builtin: false,
- connection: '',
- sizeX: null,
- sizeY: null,
- pixelDepth: null,
- resolutionX: null,
- resolutionY: null,
- currentResX: null,
- currentResY: null,
- positionX: 0,
- positionY: 0,
- currentRefreshRate: null
- };
- let is_edid = false;
- let is_current = false;
- let edid_raw = '';
- let start = 0;
- for (let i = 1; i < lines.length; i++) { // start with second line
- if ('' !== lines[i].trim()) {
- if (' ' !== lines[i][0] && '\t' !== lines[i][0] && lines[i].toLowerCase().indexOf(' connected ') !== -1) { // first line of new entry
- if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // push last display to array
- displays.push(currentDisplay);
- currentDisplay = {
- vendor: '',
- model: '',
- main: false,
- builtin: false,
- connection: '',
- sizeX: null,
- sizeY: null,
- pixelDepth: null,
- resolutionX: null,
- resolutionY: null,
- currentResX: null,
- currentResY: null,
- positionX: 0,
- positionY: 0,
- currentRefreshRate: null
- };
- }
- let parts = lines[i].split(' ');
- currentDisplay.connection = parts[0];
- currentDisplay.main = lines[i].toLowerCase().indexOf(' primary ') >= 0;
- currentDisplay.builtin = (parts[0].toLowerCase().indexOf('edp') >= 0);
- }
-
- // try to read EDID information
- if (is_edid) {
- if (lines[i].search(/\S|$/) > start) {
- edid_raw += lines[i].toLowerCase().trim();
- } else {
- // parsen EDID
- let edid_decoded = parseLinesLinuxEdid(edid_raw);
- currentDisplay.vendor = edid_decoded.vendor;
- currentDisplay.model = edid_decoded.model;
- currentDisplay.resolutionX = edid_decoded.resolutionX;
- currentDisplay.resolutionY = edid_decoded.resolutionY;
- currentDisplay.sizeX = edid_decoded.sizeX;
- currentDisplay.sizeY = edid_decoded.sizeY;
- currentDisplay.pixelDepth = depth;
- is_edid = false;
- }
- }
- if (lines[i].toLowerCase().indexOf('edid:') >= 0) {
- is_edid = true;
- start = lines[i].search(/\S|$/);
- }
- if (lines[i].toLowerCase().indexOf('*current') >= 0) {
- const parts1 = lines[i].split('(');
- if (parts1 && parts1.length > 1 && parts1[0].indexOf('x') >= 0) {
- const resParts = parts1[0].trim().split('x');
- currentDisplay.currentResX = util.toInt(resParts[0]);
- currentDisplay.currentResY = util.toInt(resParts[1]);
- }
- is_current = true;
- }
- if (is_current && lines[i].toLowerCase().indexOf('clock') >= 0 && lines[i].toLowerCase().indexOf('hz') >= 0 && lines[i].toLowerCase().indexOf('v: height') >= 0) {
- const parts1 = lines[i].split('clock');
- if (parts1 && parts1.length > 1 && parts1[1].toLowerCase().indexOf('hz') >= 0) {
- currentDisplay.currentRefreshRate = util.toInt(parts1[1]);
- }
- is_current = false;
- }
- }
- }
-
- // pushen displays
- if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // still information there
- displays.push(currentDisplay);
- }
- return displays;
- }
-
- // function starts here
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
- controllers: [],
- displays: []
- };
- if (_darwin) {
- let cmd = 'system_profiler -xml -detailLevel full SPDisplaysDataType';
- exec(cmd, function (error, stdout) {
- if (!error) {
- try {
- const output = stdout.toString();
- result = parseLinesDarwin(util.plistParser(output)[0]._items);
- } catch (e) {
- util.noop();
- }
- try {
- stdout = execSync('defaults read /Library/Preferences/com.apple.windowserver.plist 2>/dev/null;defaults read /Library/Preferences/com.apple.windowserver.displays.plist 2>/dev/null; echo ""', { maxBuffer: 1024 * 20000 });
- const output = (stdout || '').toString();
- const obj = util.plistReader(output);
- if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets']['Configs'] && obj['DisplayAnyUserSets']['Configs'][0] && obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig']) {
- const current = obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig'];
- let i = 0;
- current.forEach((o) => {
- if (o['CurrentInfo'] && o['CurrentInfo']['OriginX'] !== undefined && result.displays && result.displays[i]) {
- result.displays[i].positionX = o['CurrentInfo']['OriginX'];
- }
- if (o['CurrentInfo'] && o['CurrentInfo']['OriginY'] !== undefined && result.displays && result.displays[i]) {
- result.displays[i].positionY = o['CurrentInfo']['OriginY'];
- }
- i++;
- });
- }
- if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets'].length > 0 && obj['DisplayAnyUserSets'][0].length > 0 && obj['DisplayAnyUserSets'][0][0]['DisplayID']) {
- const current = obj['DisplayAnyUserSets'][0];
- let i = 0;
- current.forEach((o) => {
- if ('OriginX' in o && result.displays && result.displays[i]) {
- result.displays[i].positionX = o['OriginX'];
- }
- if ('OriginY' in o && result.displays && result.displays[i]) {
- result.displays[i].positionY = o['OriginY'];
- }
- if (o['Mode'] && o['Mode']['BitsPerPixel'] !== undefined && result.displays && result.displays[i]) {
- result.displays[i].pixelDepth = o['Mode']['BitsPerPixel'];
- }
- i++;
- });
- }
- } catch (e) {
- util.noop();
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_linux) {
- // Raspberry: https://elinux.org/RPI_vcgencmd_usage
- if (util.isRaspberry() && util.isRaspbian()) {
- let cmd = 'fbset -s | grep \'mode "\'; vcgencmd get_mem gpu; tvservice -s; tvservice -n;';
- exec(cmd, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- if (lines.length > 3 && lines[0].indexOf('mode "') >= -1 && lines[2].indexOf('0x12000a') > -1) {
- const parts = lines[0].replace('mode', '').replace(/"/g, '').trim().split('x');
- if (parts.length === 2) {
- result.displays.push({
- vendor: '',
- model: util.getValue(lines, 'device_name', '='),
- main: true,
- builtin: false,
- connection: 'HDMI',
- sizeX: null,
- sizeY: null,
- pixelDepth: null,
- resolutionX: parseInt(parts[0], 10),
- resolutionY: parseInt(parts[1], 10),
- currentResX: null,
- currentResY: null,
- positionX: 0,
- positionY: 0,
- currentRefreshRate: null
- });
- }
- }
- if (lines.length > 1 && stdout.toString().indexOf('gpu=') >= -1) {
- result.controllers.push({
- vendor: 'Broadcom',
- model: util.getRpiGpu(),
- bus: '',
- vram: util.getValue(lines, 'gpu', '=').replace('M', ''),
- vramDynamic: true
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- let cmd = 'lspci -vvv 2>/dev/null';
- exec(cmd, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result.controllers = parseLinesLinuxControllers(lines);
- const nvidiaData = nvidiaDevices();
- // needs to be rewritten ... using no spread operators
- result.controllers = result.controllers.map((controller) => { // match by busAddress
- return mergeControllerNvidia(controller, nvidiaData.find((contr) => contr.pciBus.toLowerCase().endsWith(controller.busAddress.toLowerCase())) || {});
- });
- }
- let cmd = 'clinfo --raw';
- exec(cmd, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result.controllers = parseLinesLinuxClinfo(result.controllers, lines);
- }
- let cmd = 'xdpyinfo 2>/dev/null | grep \'depth of root window\' | awk \'{ print $5 }\'';
- exec(cmd, function (error, stdout) {
- let depth = 0;
- if (!error) {
- let lines = stdout.toString().split('\n');
- depth = parseInt(lines[0]) || 0;
- }
- let cmd = 'xrandr --verbose 2>/dev/null';
- exec(cmd, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result.displays = parseLinesLinuxDisplays(lines, depth);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- });
- });
- });
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- if (callback) { callback(null); }
- resolve(null);
- }
- if (_sunos) {
- if (callback) { callback(null); }
- resolve(null);
- }
- if (_windows) {
-
- // https://blogs.technet.microsoft.com/heyscriptingguy/2013/10/03/use-powershell-to-discover-multi-monitor-information/
- // https://devblogs.microsoft.com/scripting/use-powershell-to-discover-multi-monitor-information/
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance win32_VideoController | fl *'));
- workload.push(util.powerShell('gp "HKLM:\\SYSTEM\\ControlSet001\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}\\*" -ErrorAction SilentlyContinue | where MatchingDeviceId $null -NE | select MatchingDeviceId,HardwareInformation.qwMemorySize | fl'));
- workload.push(util.powerShell('Get-CimInstance win32_desktopmonitor | fl *'));
- workload.push(util.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorBasicDisplayParams | fl'));
- workload.push(util.powerShell('Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Screen]::AllScreens'));
- workload.push(util.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorConnectionParams | fl'));
- workload.push(util.powerShell('gwmi WmiMonitorID -Namespace root\\wmi | ForEach-Object {(($_.ManufacturerName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.ProductCodeID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.UserFriendlyName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.SerialNumberID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + $_.InstanceName}'));
-
- const nvidiaData = nvidiaDevices();
-
- Promise.all(
- workload
- ).then((data) => {
- // controller + vram
- let csections = data[0].replace(/\r/g, '').split(/\n\s*\n/);
- let vsections = data[1].replace(/\r/g, '').split(/\n\s*\n/);
- result.controllers = parseLinesWindowsControllers(csections, vsections);
- result.controllers = result.controllers.map((controller) => { // match by subDeviceId
- if (controller.vendor.toLowerCase() === 'nvidia') {
- return mergeControllerNvidia(controller, nvidiaData.find(device => {
- let windowsSubDeviceId = (controller.subDeviceId || '').toLowerCase();
- const nvidiaSubDeviceIdParts = device.subDeviceId.split('x');
- let nvidiaSubDeviceId = nvidiaSubDeviceIdParts.length > 1 ? nvidiaSubDeviceIdParts[1].toLowerCase() : nvidiaSubDeviceIdParts[0].toLowerCase();
- const lengthDifference = Math.abs(windowsSubDeviceId.length - nvidiaSubDeviceId.length);
- if (windowsSubDeviceId.length > nvidiaSubDeviceId.length) {
- for (let i = 0; i < lengthDifference; i++) {
- nvidiaSubDeviceId = '0' + nvidiaSubDeviceId;
- }
- } else if (windowsSubDeviceId.length < nvidiaSubDeviceId.length) {
- for (let i = 0; i < lengthDifference; i++) {
- windowsSubDeviceId = '0' + windowsSubDeviceId;
- }
- }
- return windowsSubDeviceId === nvidiaSubDeviceId;
- }) || {});
- } else {
- return controller;
- }
- });
-
- // displays
- let dsections = data[2].replace(/\r/g, '').split(/\n\s*\n/);
- // result.displays = parseLinesWindowsDisplays(dsections);
- if (dsections[0].trim() === '') { dsections.shift(); }
- if (dsections.length && dsections[dsections.length - 1].trim() === '') { dsections.pop(); }
-
- // monitor (powershell)
- let msections = data[3].replace(/\r/g, '').split('Active ');
- msections.shift();
-
- // forms.screens (powershell)
- let ssections = data[4].replace(/\r/g, '').split('BitsPerPixel ');
- ssections.shift();
-
- // connection params (powershell) - video type
- let tsections = data[5].replace(/\r/g, '').split(/\n\s*\n/);
- tsections.shift();
-
- // monitor ID (powershell) - model / vendor
- const res = data[6].replace(/\r/g, '').split(/\n/);
- let isections = [];
- res.forEach(element => {
- const parts = element.split('|');
- if (parts.length === 5) {
- isections.push({
- vendor: parts[0],
- code: parts[1],
- model: parts[2],
- serial: parts[3],
- instanceId: parts[4]
- });
- }
- });
-
- result.displays = parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections);
-
- if (result.displays.length === 1) {
- if (_resolutionX) {
- result.displays[0].resolutionX = _resolutionX;
- if (!result.displays[0].currentResX) {
- result.displays[0].currentResX = _resolutionX;
- }
- }
- if (_resolutionY) {
- result.displays[0].resolutionY = _resolutionY;
- if (result.displays[0].currentResY === 0) {
- result.displays[0].currentResY = _resolutionY;
- }
- }
- if (_pixelDepth) {
- result.displays[0].pixelDepth = _pixelDepth;
- }
- }
- result.displays = result.displays.map(element => {
- if (_refreshRate && !element.currentRefreshRate) {
- element.currentRefreshRate = _refreshRate;
- }
- return element;
- });
-
- if (callback) {
- callback(result);
- }
- resolve(result);
- })
- .catch(() => {
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-
- function parseLinesWindowsControllers(sections, vections) {
- const memorySizes = {};
- for (const i in vections) {
- if ({}.hasOwnProperty.call(vections, i)) {
- if (vections[i].trim() !== '') {
- const lines = vections[i].trim().split('\n');
- const matchingDeviceId = util.getValue(lines, 'MatchingDeviceId').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i);
- if (matchingDeviceId) {
- const quadWordmemorySize = parseInt(util.getValue(lines, 'HardwareInformation.qwMemorySize'));
- if (!isNaN(quadWordmemorySize)) {
- let deviceId = matchingDeviceId[1].toUpperCase() + '&' + matchingDeviceId[2].toUpperCase();
- if (matchingDeviceId[3]) {
- deviceId += '&' + matchingDeviceId[3].toUpperCase();
- }
- if (matchingDeviceId[4]) {
- deviceId += '&' + matchingDeviceId[4].toUpperCase();
- }
- memorySizes[deviceId] = quadWordmemorySize;
- }
- }
- }
- }
- }
-
- let controllers = [];
- for (let i in sections) {
- if ({}.hasOwnProperty.call(sections, i)) {
- if (sections[i].trim() !== '') {
- let lines = sections[i].trim().split('\n');
- let pnpDeviceId = util.getValue(lines, 'PNPDeviceID', ':').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i);
- let subDeviceId = null;
- let memorySize = null;
- if (pnpDeviceId) {
- subDeviceId = pnpDeviceId[3] || '';
- if (subDeviceId) {
- subDeviceId = subDeviceId.split('_')[1];
- }
-
- // Match PCI device identifier (there's an order of increasing generality):
- // https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
-
- // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4)&REV_r(2)
- if (memorySize == null && pnpDeviceId[3] && pnpDeviceId[4]) {
- const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase();
- if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
- memorySize = memorySizes[deviceId];
- }
- }
-
- // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4)
- if (memorySize == null && pnpDeviceId[3]) {
- const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase();
- if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
- memorySize = memorySizes[deviceId];
- }
- }
-
- // PCI\VEN_v(4)&DEV_d(4)&REV_r(2)
- if (memorySize == null && pnpDeviceId[4]) {
- const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase();
- if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
- memorySize = memorySizes[deviceId];
- }
- }
-
- // PCI\VEN_v(4)&DEV_d(4)
- if (memorySize == null) {
- const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase();
- if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
- memorySize = memorySizes[deviceId];
- }
- }
- }
-
- controllers.push({
- vendor: util.getValue(lines, 'AdapterCompatibility', ':'),
- model: util.getValue(lines, 'name', ':'),
- bus: util.getValue(lines, 'PNPDeviceID', ':').startsWith('PCI') ? 'PCI' : '',
- vram: (memorySize == null ? util.toInt(util.getValue(lines, 'AdapterRAM', ':')) : memorySize) / 1024 / 1024,
- vramDynamic: (util.getValue(lines, 'VideoMemoryType', ':') === '2'),
- subDeviceId
- });
- _resolutionX = util.toInt(util.getValue(lines, 'CurrentHorizontalResolution', ':')) || _resolutionX;
- _resolutionY = util.toInt(util.getValue(lines, 'CurrentVerticalResolution', ':')) || _resolutionY;
- _refreshRate = util.toInt(util.getValue(lines, 'CurrentRefreshRate', ':')) || _refreshRate;
- _pixelDepth = util.toInt(util.getValue(lines, 'CurrentBitsPerPixel', ':')) || _pixelDepth;
- }
- }
- }
- return controllers;
- }
-
- function parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections) {
- let displays = [];
- let vendor = '';
- let model = '';
- let deviceID = '';
- let resolutionX = 0;
- let resolutionY = 0;
- if (dsections && dsections.length) {
- let linesDisplay = dsections[0].split('\n');
- vendor = util.getValue(linesDisplay, 'MonitorManufacturer', ':');
- model = util.getValue(linesDisplay, 'Name', ':');
- deviceID = util.getValue(linesDisplay, 'PNPDeviceID', ':').replace(/&/g, '&').toLowerCase();
- resolutionX = util.toInt(util.getValue(linesDisplay, 'ScreenWidth', ':'));
- resolutionY = util.toInt(util.getValue(linesDisplay, 'ScreenHeight', ':'));
- }
- for (let i = 0; i < ssections.length; i++) {
- if (ssections[i].trim() !== '') {
- ssections[i] = 'BitsPerPixel ' + ssections[i];
- msections[i] = 'Active ' + msections[i];
- // tsections can be empty OR undefined on earlier versions of powershell (<=2.0)
- // Tag connection type as UNKNOWN by default if this information is missing
- if (tsections.length === 0 || tsections[i] === undefined) {
- tsections[i] = 'Unknown';
- }
- let linesScreen = ssections[i].split('\n');
- let linesMonitor = msections[i].split('\n');
-
- let linesConnection = tsections[i].split('\n');
- const bitsPerPixel = util.getValue(linesScreen, 'BitsPerPixel');
- const bounds = util.getValue(linesScreen, 'Bounds').replace('{', '').replace('}', '').replace(/=/g, ':').split(',');
- const primary = util.getValue(linesScreen, 'Primary');
- const sizeX = util.getValue(linesMonitor, 'MaxHorizontalImageSize');
- const sizeY = util.getValue(linesMonitor, 'MaxVerticalImageSize');
- const instanceName = util.getValue(linesMonitor, 'InstanceName').toLowerCase();
- const videoOutputTechnology = util.getValue(linesConnection, 'VideoOutputTechnology');
- const deviceName = util.getValue(linesScreen, 'DeviceName');
- let displayVendor = '';
- let displayModel = '';
- isections.forEach(element => {
- if (element.instanceId.toLowerCase().startsWith(instanceName) && vendor.startsWith('(') && model.startsWith('PnP')) {
- displayVendor = element.vendor;
- displayModel = element.model;
- }
- });
- displays.push({
- vendor: instanceName.startsWith(deviceID) && displayVendor === '' ? vendor : displayVendor,
- model: instanceName.startsWith(deviceID) && displayModel === '' ? model : displayModel,
- deviceName,
- main: primary.toLowerCase() === 'true',
- builtin: videoOutputTechnology === '2147483648',
- connection: videoOutputTechnology && videoTypes[videoOutputTechnology] ? videoTypes[videoOutputTechnology] : '',
- resolutionX: util.toInt(util.getValue(bounds, 'Width', ':')),
- resolutionY: util.toInt(util.getValue(bounds, 'Height', ':')),
- sizeX: sizeX ? parseInt(sizeX, 10) : null,
- sizeY: sizeY ? parseInt(sizeY, 10) : null,
- pixelDepth: bitsPerPixel,
- currentResX: util.toInt(util.getValue(bounds, 'Width', ':')),
- currentResY: util.toInt(util.getValue(bounds, 'Height', ':')),
- positionX: util.toInt(util.getValue(bounds, 'X', ':')),
- positionY: util.toInt(util.getValue(bounds, 'Y', ':')),
- });
- }
- }
- if (ssections.length === 0) {
- displays.push({
- vendor,
- model,
- main: true,
- sizeX: null,
- sizeY: null,
- resolutionX,
- resolutionY,
- pixelDepth: null,
- currentResX: resolutionX,
- currentResY: resolutionY,
- positionX: 0,
- positionY: 0
- });
- }
- return displays;
- }
-}
-
-exports.graphics = graphics;
-
-
-/***/ }),
-
-/***/ 70657:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// index.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// Contributors: Guillaume Legrain (https://github.com/glegrain)
-// Riccardo Novaglia (https://github.com/richy24)
-// Quentin Busuttil (https://github.com/Buzut)
-// Lapsio (https://github.com/lapsio)
-// csy (https://github.com/csy1983)
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-
-// ----------------------------------------------------------------------------------
-// Dependencies
-// ----------------------------------------------------------------------------------
-
-const lib_version = (__nccwpck_require__(15460)/* .version */ .rE);
-const util = __nccwpck_require__(33225);
-const system = __nccwpck_require__(50936);
-const osInfo = __nccwpck_require__(70255);
-const cpu = __nccwpck_require__(93739);
-const memory = __nccwpck_require__(30958);
-const battery = __nccwpck_require__(35552);
-const graphics = __nccwpck_require__(49404);
-const filesystem = __nccwpck_require__(43022);
-const network = __nccwpck_require__(20287);
-const wifi = __nccwpck_require__(81180);
-const processes = __nccwpck_require__(76340);
-const users = __nccwpck_require__(93069);
-const internet = __nccwpck_require__(27336);
-const docker = __nccwpck_require__(31865);
-const vbox = __nccwpck_require__(3881);
-const printer = __nccwpck_require__(14497);
-const usb = __nccwpck_require__(66223);
-const audio = __nccwpck_require__(47411);
-const bluetooth = __nccwpck_require__(45595);
-
-let _platform = process.platform;
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-// ----------------------------------------------------------------------------------
-// init
-// ----------------------------------------------------------------------------------
-
-if (_windows) {
- util.getCodepage();
-}
-
-// ----------------------------------------------------------------------------------
-// General
-// ----------------------------------------------------------------------------------
-
-function version() {
- return lib_version;
-}
-
-// ----------------------------------------------------------------------------------
-// Get static and dynamic data (all)
-// ----------------------------------------------------------------------------------
-
-// --------------------------
-// get static data - they should not change until restarted
-
-function getStaticData(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let data = {};
-
- data.version = version();
-
- Promise.all([
- system.system(),
- system.bios(),
- system.baseboard(),
- system.chassis(),
- osInfo.osInfo(),
- osInfo.uuid(),
- osInfo.versions(),
- cpu.cpu(),
- cpu.cpuFlags(),
- graphics.graphics(),
- network.networkInterfaces(),
- memory.memLayout(),
- filesystem.diskLayout()
- ]).then((res) => {
- data.system = res[0];
- data.bios = res[1];
- data.baseboard = res[2];
- data.chassis = res[3];
- data.os = res[4];
- data.uuid = res[5];
- data.versions = res[6];
- data.cpu = res[7];
- data.cpu.flags = res[8];
- data.graphics = res[9];
- data.net = res[10];
- data.memLayout = res[11];
- data.diskLayout = res[12];
- if (callback) { callback(data); }
- resolve(data);
- });
- });
- });
-}
-
-
-// --------------------------
-// get all dynamic data - e.g. for monitoring agents
-// may take some seconds to get all data
-// --------------------------
-// 2 additional parameters needed
-// - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql"
-// - iface: define network interface for which you like to monitor network speed e.g. "eth0"
-
-function getDynamicData(srv, iface, callback) {
-
- if (util.isFunction(iface)) {
- callback = iface;
- iface = '';
- }
- if (util.isFunction(srv)) {
- callback = srv;
- srv = '';
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- iface = iface || network.getDefaultNetworkInterface();
- srv = srv || '';
-
- // use closure to track ƒ completion
- let functionProcessed = (function () {
- let totalFunctions = 15;
- if (_windows) { totalFunctions = 13; }
- if (_freebsd || _openbsd || _netbsd) { totalFunctions = 11; }
- if (_sunos) { totalFunctions = 6; }
-
- return function () {
- if (--totalFunctions === 0) {
- if (callback) {
- callback(data);
- }
- resolve(data);
- }
- };
- })();
-
- let data = {};
-
- // get time
- data.time = osInfo.time();
-
- /**
- * @namespace
- * @property {Object} versions
- * @property {string} versions.node
- * @property {string} versions.v8
- */
- data.node = process.versions.node;
- data.v8 = process.versions.v8;
-
- cpu.cpuCurrentSpeed().then((res) => {
- data.cpuCurrentSpeed = res;
- functionProcessed();
- });
-
- users.users().then((res) => {
- data.users = res;
- functionProcessed();
- });
-
- processes.processes().then((res) => {
- data.processes = res;
- functionProcessed();
- });
-
- cpu.currentLoad().then((res) => {
- data.currentLoad = res;
- functionProcessed();
- });
-
- if (!_sunos) {
- cpu.cpuTemperature().then((res) => {
- data.temp = res;
- functionProcessed();
- });
- }
-
- if (!_openbsd && !_freebsd && !_netbsd && !_sunos) {
- network.networkStats(iface).then((res) => {
- data.networkStats = res;
- functionProcessed();
- });
- }
-
- if (!_sunos) {
- network.networkConnections().then((res) => {
- data.networkConnections = res;
- functionProcessed();
- });
- }
-
- memory.mem().then((res) => {
- data.mem = res;
- functionProcessed();
- });
-
- if (!_sunos) {
- battery().then((res) => {
- data.battery = res;
- functionProcessed();
- });
- }
-
- if (!_sunos) {
- processes.services(srv).then((res) => {
- data.services = res;
- functionProcessed();
- });
- }
-
- if (!_sunos) {
- filesystem.fsSize().then((res) => {
- data.fsSize = res;
- functionProcessed();
- });
- }
-
- if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) {
- filesystem.fsStats().then((res) => {
- data.fsStats = res;
- functionProcessed();
- });
- }
-
- if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) {
- filesystem.disksIO().then((res) => {
- data.disksIO = res;
- functionProcessed();
- });
- }
-
- if (!_openbsd && !_freebsd && !_netbsd && !_sunos) {
- wifi.wifiNetworks().then((res) => {
- data.wifiNetworks = res;
- functionProcessed();
- });
- }
-
- internet.inetLatency().then((res) => {
- data.inetLatency = res;
- functionProcessed();
- });
- });
- });
-}
-
-// --------------------------
-// get all data at once
-// --------------------------
-// 2 additional parameters needed
-// - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql"
-// - iface: define network interface for which you like to monitor network speed e.g. "eth0"
-
-function getAllData(srv, iface, callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let data = {};
-
- if (iface && util.isFunction(iface) && !callback) {
- callback = iface;
- iface = '';
- }
-
- if (srv && util.isFunction(srv) && !iface && !callback) {
- callback = srv;
- srv = '';
- iface = '';
- }
-
- getStaticData().then((res) => {
- data = res;
- getDynamicData(srv, iface).then((res) => {
- for (let key in res) {
- if ({}.hasOwnProperty.call(res, key)) {
- data[key] = res[key];
- }
- }
- if (callback) { callback(data); }
- resolve(data);
- });
- });
- });
- });
-}
-
-function get(valueObject, callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- const allPromises = Object.keys(valueObject)
- .filter(func => ({}.hasOwnProperty.call(exports, func)))
- .map(func => {
- const params = valueObject[func].substring(valueObject[func].lastIndexOf('(') + 1, valueObject[func].lastIndexOf(')'));
- let funcWithoutParams = func.indexOf(')') >= 0 ? func.split(')')[1].trim() : func;
- funcWithoutParams = func.indexOf('|') >= 0 ? func.split('|')[0].trim() : funcWithoutParams;
- if (params) {
- return exports[funcWithoutParams](params);
- } else {
- return exports[funcWithoutParams]('');
- }
- });
-
- Promise.all(allPromises).then((data) => {
- const result = {};
- let i = 0;
- for (let key in valueObject) {
- if ({}.hasOwnProperty.call(valueObject, key) && {}.hasOwnProperty.call(exports, key) && data.length > i) {
- if (valueObject[key] === '*' || valueObject[key] === 'all') {
- result[key] = data[i];
- } else {
- let keys = valueObject[key];
- let filter = '';
- let filterParts = [];
- // remove params
- if (keys.indexOf(')') >= 0) {
- keys = keys.split(')')[1].trim();
- }
- // extract filter and remove it from keys
- if (keys.indexOf('|') >= 0) {
- filter = keys.split('|')[1].trim();
- filterParts = filter.split(':');
-
- keys = keys.split('|')[0].trim();
- }
- keys = keys.replace(/,/g, ' ').replace(/ +/g, ' ').split(' ');
- if (data[i]) {
- if (Array.isArray(data[i])) {
- // result is in an array, go through all elements of array and pick only the right ones
- const partialArray = [];
- data[i].forEach(element => {
- let partialRes = {};
- if (keys.length === 1 && (keys[0] === '*' || keys[0] === 'all')) {
- partialRes = element;
- } else {
- keys.forEach(k => {
- if ({}.hasOwnProperty.call(element, k)) {
- partialRes[k] = element[k];
- }
- });
- }
- // if there is a filter, then just take those elements
- if (filter && filterParts.length === 2) {
- if ({}.hasOwnProperty.call(partialRes, filterParts[0].trim())) {
- const val = partialRes[filterParts[0].trim()];
- if (typeof val == 'number') {
- if (val === parseFloat(filterParts[1].trim())) {
- partialArray.push(partialRes);
- }
- } else if (typeof val == 'string') {
- if (val.toLowerCase() === filterParts[1].trim().toLowerCase()) {
- partialArray.push(partialRes);
- }
- }
- }
- } else {
- partialArray.push(partialRes);
- }
-
- });
- result[key] = partialArray;
- } else {
- const partialRes = {};
- keys.forEach(k => {
- if ({}.hasOwnProperty.call(data[i], k)) {
- partialRes[k] = data[i][k];
- }
- });
- result[key] = partialRes;
- }
- } else {
- result[key] = {};
- }
- }
- i++;
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- });
-}
-
-function observe(valueObject, interval, callback) {
- let _data = null;
-
- const result = setInterval(() => {
- get(valueObject).then((data) => {
- if (JSON.stringify(_data) !== JSON.stringify(data)) {
- _data = Object.assign({}, data);
- callback(data);
- }
- });
- }, interval);
- return result;
-}
-
-// ----------------------------------------------------------------------------------
-// export all libs
-// ----------------------------------------------------------------------------------
-
-exports.version = version;
-exports.system = system.system;
-exports.bios = system.bios;
-exports.baseboard = system.baseboard;
-exports.chassis = system.chassis;
-
-exports.time = osInfo.time;
-exports.osInfo = osInfo.osInfo;
-exports.versions = osInfo.versions;
-exports.shell = osInfo.shell;
-exports.uuid = osInfo.uuid;
-
-exports.cpu = cpu.cpu;
-exports.cpuFlags = cpu.cpuFlags;
-exports.cpuCache = cpu.cpuCache;
-exports.cpuCurrentSpeed = cpu.cpuCurrentSpeed;
-exports.cpuTemperature = cpu.cpuTemperature;
-exports.currentLoad = cpu.currentLoad;
-exports.fullLoad = cpu.fullLoad;
-
-exports.mem = memory.mem;
-exports.memLayout = memory.memLayout;
-
-exports.battery = battery;
-
-exports.graphics = graphics.graphics;
-
-exports.fsSize = filesystem.fsSize;
-exports.fsOpenFiles = filesystem.fsOpenFiles;
-exports.blockDevices = filesystem.blockDevices;
-exports.fsStats = filesystem.fsStats;
-exports.disksIO = filesystem.disksIO;
-exports.diskLayout = filesystem.diskLayout;
-
-exports.networkInterfaceDefault = network.networkInterfaceDefault;
-exports.networkGatewayDefault = network.networkGatewayDefault;
-exports.networkInterfaces = network.networkInterfaces;
-exports.networkStats = network.networkStats;
-exports.networkConnections = network.networkConnections;
-
-exports.wifiNetworks = wifi.wifiNetworks;
-exports.wifiInterfaces = wifi.wifiInterfaces;
-exports.wifiConnections = wifi.wifiConnections;
-
-exports.services = processes.services;
-exports.processes = processes.processes;
-exports.processLoad = processes.processLoad;
-
-exports.users = users.users;
-
-exports.inetChecksite = internet.inetChecksite;
-exports.inetLatency = internet.inetLatency;
-
-exports.dockerInfo = docker.dockerInfo;
-exports.dockerImages = docker.dockerImages;
-exports.dockerContainers = docker.dockerContainers;
-exports.dockerContainerStats = docker.dockerContainerStats;
-exports.dockerContainerProcesses = docker.dockerContainerProcesses;
-exports.dockerVolumes = docker.dockerVolumes;
-exports.dockerAll = docker.dockerAll;
-
-exports.vboxInfo = vbox.vboxInfo;
-
-exports.printer = printer.printer;
-
-exports.usb = usb.usb;
-
-exports.audio = audio.audio;
-exports.bluetoothDevices = bluetooth.bluetoothDevices;
-
-exports.getStaticData = getStaticData;
-exports.getDynamicData = getDynamicData;
-exports.getAllData = getAllData;
-exports.get = get;
-exports.observe = observe;
-
-exports.powerShellStart = util.powerShellStart;
-exports.powerShellRelease = util.powerShellRelease;
-
-
-/***/ }),
-
-/***/ 27336:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// internet.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 12. Internet
-// ----------------------------------------------------------------------------------
-
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-// --------------------------
-// check if external site is available
-
-function inetChecksite(url, callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
- url: url,
- ok: false,
- status: 404,
- ms: null
- };
- if (typeof url !== 'string') {
- if (callback) { callback(result); }
- return resolve(result);
- }
- let urlSanitized = '';
- const s = util.sanitizeShellString(url, true);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- try {
- s[i].__proto__.toLowerCase = util.stringToLower;
- } catch (e) {
- Object.setPrototypeOf(s[i], util.stringObj);
- }
-
- const sl = s[i].toLowerCase();
- if (sl && sl[0] && !sl[1] && sl[0].length === 1) {
- urlSanitized = urlSanitized + sl[0];
- }
- }
- }
- result.url = urlSanitized;
- try {
- if (urlSanitized && !util.isPrototypePolluted()) {
- try {
- urlSanitized.__proto__.startsWith = util.stringStartWith;
- } catch (e) {
- Object.setPrototypeOf(urlSanitized, util.stringObj);
- }
-
- if (urlSanitized.startsWith('file:') || urlSanitized.startsWith('gopher:') || urlSanitized.startsWith('telnet:') || urlSanitized.startsWith('mailto:') || urlSanitized.startsWith('news:') || urlSanitized.startsWith('nntp:')) {
- if (callback) { callback(result); }
- return resolve(result);
- }
-
- util.checkWebsite(urlSanitized).then((res) => {
- result.status = res.statusCode;
- result.ok = res.statusCode >= 200 && res.statusCode <= 399;;
- result.ms = (result.ok ? res.time : null);
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } catch (err) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
-}
-
-exports.inetChecksite = inetChecksite;
-
-// --------------------------
-// check inet latency
-
-function inetLatency(host, callback) {
-
- // fallback - if only callback is given
- if (util.isFunction(host) && !callback) {
- callback = host;
- host = '';
- }
-
- host = host || '8.8.8.8';
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (typeof host !== 'string') {
- if (callback) { callback(null); }
- return resolve(null);
- }
- let hostSanitized = '';
- const s = (util.isPrototypePolluted() ? '8.8.8.8' : util.sanitizeShellString(host, true)).trim();
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (!(s[i] === undefined)) {
- try {
- s[i].__proto__.toLowerCase = util.stringToLower;
- } catch (e) {
- Object.setPrototypeOf(s[i], util.stringObj);
- }
-
- const sl = s[i].toLowerCase();
- if (sl && sl[0] && !sl[1]) {
- hostSanitized = hostSanitized + sl[0];
- }
- }
- }
- try {
- hostSanitized.__proto__.startsWith = util.stringStartWith;
- } catch (e) {
- Object.setPrototypeOf(hostSanitized, util.stringObj);
- }
-
- if (hostSanitized.startsWith('file:') || hostSanitized.startsWith('gopher:') || hostSanitized.startsWith('telnet:') || hostSanitized.startsWith('mailto:') || hostSanitized.startsWith('news:') || hostSanitized.startsWith('nntp:')) {
- if (callback) { callback(null); }
- return resolve(null);
- }
- let params;
- if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
- if (_linux) {
- params = ['-c', '2', '-w', '3', hostSanitized];
- }
- if (_freebsd || _openbsd || _netbsd) {
- params = ['-c', '2', '-t', '3', hostSanitized];
- }
- if (_darwin) {
- params = ['-c2', '-t3', hostSanitized];
- }
- util.execSafe('ping', params).then((stdout) => {
- let result = null;
- if (stdout) {
- const lines = stdout.split('\n').filter((line) => (line.indexOf('rtt') >= 0 || line.indexOf('round-trip') >= 0 || line.indexOf('avg') >= 0)).join('\n');
-
- const line = lines.split('=');
- if (line.length > 1) {
- const parts = line[1].split('/');
- if (parts.length > 1) {
- result = parseFloat(parts[1]);
- }
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- const params = ['-s', '-a', hostSanitized, '56', '2'];
- const filt = 'avg';
- util.execSafe('ping', params, { timeout: 3000 }).then((stdout) => {
- let result = null;
- if (stdout) {
- const lines = stdout.split('\n').filter(line => line.indexOf(filt) >= 0).join('\n');
- const line = lines.split('=');
- if (line.length > 1) {
- const parts = line[1].split('/');
- if (parts.length > 1) {
- result = parseFloat(parts[1].replace(',', '.'));
- }
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_windows) {
- let result = null;
- try {
- const params = [hostSanitized, '-n', '1'];
- util.execSafe('ping', params, util.execOptsWin).then((stdout) => {
- if (stdout) {
- let lines = stdout.split('\r\n');
- lines.shift();
- lines.forEach(function (line) {
- if ((line.toLowerCase().match(/ms/g) || []).length === 3) {
- let l = line.replace(/ +/g, ' ').split(' ');
- if (l.length > 6) {
- result = parseFloat(l[l.length - 1]);
- }
- }
- });
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.inetLatency = inetLatency;
-
-
-/***/ }),
-
-/***/ 30958:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// memory.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 5. Memory
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const util = __nccwpck_require__(33225);
-const fs = __nccwpck_require__(79896);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-const OSX_RAM_manufacturers = {
- '0x014F': 'Transcend Information',
- '0x2C00': 'Micron Technology Inc.',
- '0x802C': 'Micron Technology Inc.',
- '0x80AD': 'Hynix Semiconductor Inc.',
- '0x80CE': 'Samsung Electronics Inc.',
- '0xAD00': 'Hynix Semiconductor Inc.',
- '0xCE00': 'Samsung Electronics Inc.',
- '0x02FE': 'Elpida',
- '0x5105': 'Qimonda AG i. In.',
- '0x8551': 'Qimonda AG i. In.',
- '0x859B': 'Crucial',
- '0x04CD': 'G-Skill'
-};
-
-const LINUX_RAM_manufacturers = {
- '017A': 'Apacer',
- '0198': 'HyperX',
- '029E': 'Corsair',
- '04CB': 'A-DATA',
- '04CD': 'G-Skill',
- '059B': 'Crucial',
- '00CE': 'Samsung',
- '1315': 'Crucial',
- '014F': 'Transcend Information',
- '2C00': 'Micron Technology Inc.',
- '802C': 'Micron Technology Inc.',
- '80AD': 'Hynix Semiconductor Inc.',
- '80CE': 'Samsung Electronics Inc.',
- 'AD00': 'Hynix Semiconductor Inc.',
- 'CE00': 'Samsung Electronics Inc.',
- '02FE': 'Elpida',
- '5105': 'Qimonda AG i. In.',
- '8551': 'Qimonda AG i. In.',
- '859B': 'Crucial'
-};
-
-// _______________________________________________________________________________________
-// | R A M | H D |
-// |______________________|_________________________| | |
-// | active buffers/cache | | |
-// |________________________________________________|___________|_________|______________|
-// | used free | used free |
-// |____________________________________________________________|________________________|
-// | total | swap |
-// |____________________________________________________________|________________________|
-
-// free (older versions)
-// ----------------------------------
-// # free
-// total used free shared buffers cached
-// Mem: 16038 (1) 15653 (2) 384 (3) 0 (4) 236 (5) 14788 (6)
-// -/+ buffers/cache: 628 (7) 15409 (8)
-// Swap: 16371 83 16288
-//
-// |------------------------------------------------------------|
-// | R A M |
-// |______________________|_____________________________________|
-// | active (2-(5+6) = 7) | available (3+5+6 = 8) |
-// |______________________|_________________________|___________|
-// | active | buffers/cache (5+6) | |
-// |________________________________________________|___________|
-// | used (2) | free (3) |
-// |____________________________________________________________|
-// | total (1) |
-// |____________________________________________________________|
-
-//
-// free (since free von procps-ng 3.3.10)
-// ----------------------------------
-// # free
-// total used free shared buffers/cache available
-// Mem: 16038 (1) 628 (2) 386 (3) 0 (4) 15024 (5) 14788 (6)
-// Swap: 16371 83 16288
-//
-// |------------------------------------------------------------|
-// | R A M |
-// |______________________|_____________________________________|
-// | | available (6) estimated |
-// |______________________|_________________________|___________|
-// | active (2) | buffers/cache (5) | free (3) |
-// |________________________________________________|___________|
-// | total (1) |
-// |____________________________________________________________|
-//
-// Reference: http://www.software-architect.net/blog/article/date/2015/06/12/-826c6e5052.html
-
-// /procs/meminfo - sample (all in kB)
-//
-// MemTotal: 32806380 kB
-// MemFree: 17977744 kB
-// MemAvailable: 19768972 kB
-// Buffers: 517028 kB
-// Cached: 2161876 kB
-// SwapCached: 456 kB
-// Active: 12081176 kB
-// Inactive: 2164616 kB
-// Active(anon): 10832884 kB
-// Inactive(anon): 1477272 kB
-// Active(file): 1248292 kB
-// Inactive(file): 687344 kB
-// Unevictable: 0 kB
-// Mlocked: 0 kB
-// SwapTotal: 16768892 kB
-// SwapFree: 16768304 kB
-// Dirty: 268 kB
-// Writeback: 0 kB
-// AnonPages: 11568832 kB
-// Mapped: 719992 kB
-// Shmem: 743272 kB
-// Slab: 335716 kB
-// SReclaimable: 256364 kB
-// SUnreclaim: 79352 kB
-
-function mem(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- total: os.totalmem(),
- free: os.freemem(),
- used: os.totalmem() - os.freemem(),
-
- active: os.totalmem() - os.freemem(), // temporarily (fallback)
- available: os.freemem(), // temporarily (fallback)
- buffers: 0,
- cached: 0,
- slab: 0,
- buffcache: 0,
-
- swaptotal: 0,
- swapused: 0,
- swapfree: 0,
- writeback: null,
- dirty: null
- };
-
- if (_linux) {
- try {
- fs.readFile('/proc/meminfo', function (error, stdout) {
- if (!error) {
- const lines = stdout.toString().split('\n');
- result.total = parseInt(util.getValue(lines, 'memtotal'), 10);
- result.total = result.total ? result.total * 1024 : os.totalmem();
- result.free = parseInt(util.getValue(lines, 'memfree'), 10);
- result.free = result.free ? result.free * 1024 : os.freemem();
- result.used = result.total - result.free;
-
- result.buffers = parseInt(util.getValue(lines, 'buffers'), 10);
- result.buffers = result.buffers ? result.buffers * 1024 : 0;
- result.cached = parseInt(util.getValue(lines, 'cached'), 10);
- result.cached = result.cached ? result.cached * 1024 : 0;
- result.slab = parseInt(util.getValue(lines, 'slab'), 10);
- result.slab = result.slab ? result.slab * 1024 : 0;
- result.buffcache = result.buffers + result.cached + result.slab;
-
- let available = parseInt(util.getValue(lines, 'memavailable'), 10);
- result.available = available ? available * 1024 : result.free + result.buffcache;
- result.active = result.total - result.available;
-
- result.swaptotal = parseInt(util.getValue(lines, 'swaptotal'), 10);
- result.swaptotal = result.swaptotal ? result.swaptotal * 1024 : 0;
- result.swapfree = parseInt(util.getValue(lines, 'swapfree'), 10);
- result.swapfree = result.swapfree ? result.swapfree * 1024 : 0;
- result.swapused = result.swaptotal - result.swapfree;
- result.writeback = parseInt(util.getValue(lines, 'writeback'), 10);
- result.writeback = result.writeback ? result.writeback * 1024 : 0;
- result.dirty = parseInt(util.getValue(lines, 'dirty'), 10);
- result.dirty = result.dirty ? result.dirty * 1024 : 0;
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- try {
- exec('/sbin/sysctl hw.realmem hw.physmem vm.stats.vm.v_page_count vm.stats.vm.v_wire_count vm.stats.vm.v_active_count vm.stats.vm.v_inactive_count vm.stats.vm.v_cache_count vm.stats.vm.v_free_count vm.stats.vm.v_page_size', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- const pagesize = parseInt(util.getValue(lines, 'vm.stats.vm.v_page_size'), 10);
- const inactive = parseInt(util.getValue(lines, 'vm.stats.vm.v_inactive_count'), 10) * pagesize;
- const cache = parseInt(util.getValue(lines, 'vm.stats.vm.v_cache_count'), 10) * pagesize;
-
- result.total = parseInt(util.getValue(lines, 'hw.realmem'), 10);
- if (isNaN(result.total)) { result.total = parseInt(util.getValue(lines, 'hw.physmem'), 10); }
- result.free = parseInt(util.getValue(lines, 'vm.stats.vm.v_free_count'), 10) * pagesize;
- result.buffcache = inactive + cache;
- result.available = result.buffcache + result.free;
- result.active = result.total - result.free - result.buffcache;
-
- result.swaptotal = 0;
- result.swapfree = 0;
- result.swapused = 0;
-
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_darwin) {
- let pageSize = 4096;
- try {
- let sysPpageSize = util.toInt(execSync('sysctl -n vm.pagesize').toString());
- pageSize = sysPpageSize || pageSize;
- } catch (e) {
- util.noop();
- }
- try {
- exec('vm_stat 2>/dev/null | grep "Pages active"', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
-
- result.active = parseInt(lines[0].split(':')[1], 10) * pageSize;
- result.buffcache = result.used - result.active;
- result.available = result.free + result.buffcache;
- }
- exec('sysctl -n vm.swapusage 2>/dev/null', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines.length > 0) {
- let firstline = lines[0].replace(/,/g, '.').replace(/M/g, '');
- let lineArray = firstline.trim().split(' ');
- lineArray.forEach(line => {
- if (line.toLowerCase().indexOf('total') !== -1) { result.swaptotal = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
- if (line.toLowerCase().indexOf('used') !== -1) { result.swapused = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
- if (line.toLowerCase().indexOf('free') !== -1) { result.swapfree = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
- });
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_windows) {
- let swaptotal = 0;
- let swapused = 0;
- try {
- util.powerShell('Get-CimInstance Win32_PageFileUsage | Select AllocatedBaseSize, CurrentUsage').then((stdout, error) => {
- if (!error) {
- let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
- lines.forEach(function (line) {
- if (line !== '') {
- line = line.trim().split(/\s\s+/);
- swaptotal = swaptotal + (parseInt(line[0], 10) || 0);
- swapused = swapused + (parseInt(line[1], 10) || 0);
- }
- });
- }
- result.swaptotal = swaptotal * 1024 * 1024;
- result.swapused = swapused * 1024 * 1024;
- result.swapfree = result.swaptotal - result.swapused;
-
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.mem = mem;
-
-function memLayout(callback) {
-
- function getManufacturerDarwin(manId) {
- if ({}.hasOwnProperty.call(OSX_RAM_manufacturers, manId)) {
- return (OSX_RAM_manufacturers[manId]);
- }
- return manId;
- }
-
- function getManufacturerLinux(manId) {
- const manIdSearch = manId.replace('0x', '').toUpperCase();
- if (manIdSearch.length === 4 && {}.hasOwnProperty.call(LINUX_RAM_manufacturers, manIdSearch)) {
- return (LINUX_RAM_manufacturers[manIdSearch]);
- }
- return manId;
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = [];
-
- if (_linux || _freebsd || _openbsd || _netbsd) {
- exec('export LC_ALL=C; dmidecode -t memory 2>/dev/null | grep -iE "Size:|Type|Speed|Manufacturer|Form Factor|Locator|Memory Device|Serial Number|Voltage|Part Number"; unset LC_ALL', function (error, stdout) {
- if (!error) {
- let devices = stdout.toString().split('Memory Device');
- devices.shift();
- devices.forEach(function (device) {
- let lines = device.split('\n');
- const sizeString = util.getValue(lines, 'Size');
- const size = sizeString.indexOf('GB') >= 0 ? parseInt(sizeString, 10) * 1024 * 1024 * 1024 : parseInt(sizeString, 10) * 1024 * 1024;
- let bank = util.getValue(lines, 'Bank Locator');
- if (bank.toLowerCase().indexOf('bad') >= 0) {
- bank = '';
- }
- if (parseInt(util.getValue(lines, 'Size'), 10) > 0) {
- const totalWidth = util.toInt(util.getValue(lines, 'Total Width'));
- const dataWidth = util.toInt(util.getValue(lines, 'Data Width'));
- result.push({
- size,
- bank,
- type: util.getValue(lines, 'Type:'),
- ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false,
- clockSpeed: (util.getValue(lines, 'Configured Clock Speed:') ? parseInt(util.getValue(lines, 'Configured Clock Speed:'), 10) : (util.getValue(lines, 'Speed:') ? parseInt(util.getValue(lines, 'Speed:'), 10) : null)),
- formFactor: util.getValue(lines, 'Form Factor:'),
- manufacturer: getManufacturerLinux(util.getValue(lines, 'Manufacturer:')),
- partNum: util.getValue(lines, 'Part Number:'),
- serialNum: util.getValue(lines, 'Serial Number:'),
- voltageConfigured: parseFloat(util.getValue(lines, 'Configured Voltage:')) || null,
- voltageMin: parseFloat(util.getValue(lines, 'Minimum Voltage:')) || null,
- voltageMax: parseFloat(util.getValue(lines, 'Maximum Voltage:')) || null,
- });
- } else {
- result.push({
- size: 0,
- bank,
- type: 'Empty',
- ecc: null,
- clockSpeed: 0,
- formFactor: util.getValue(lines, 'Form Factor:'),
- partNum: '',
- serialNum: '',
- voltageConfigured: null,
- voltageMin: null,
- voltageMax: null,
- });
- }
- });
- }
- if (!result.length) {
- result.push({
- size: os.totalmem(),
- bank: '',
- type: '',
- ecc: null,
- clockSpeed: 0,
- formFactor: '',
- partNum: '',
- serialNum: '',
- voltageConfigured: null,
- voltageMin: null,
- voltageMax: null,
- });
-
- // Try Raspberry PI
- try {
- let stdout = execSync('cat /proc/cpuinfo 2>/dev/null', util.execOptsLinux);
- let lines = stdout.toString().split('\n');
- let model = util.getValue(lines, 'hardware', ':', true).toUpperCase();
- let version = util.getValue(lines, 'revision', ':', true).toLowerCase();
-
- if (model === 'BCM2835' || model === 'BCM2708' || model === 'BCM2709' || model === 'BCM2835' || model === 'BCM2837') {
-
- const clockSpeed = {
- '0': 400,
- '1': 450,
- '2': 450,
- '3': 3200
- };
- result[0].type = 'LPDDR2';
- result[0].type = version && version[2] && version[2] === '3' ? 'LPDDR4' : result[0].type;
- result[0].ecc = false;
- result[0].clockSpeed = version && version[2] && clockSpeed[version[2]] || 400;
- result[0].clockSpeed = version && version[4] && version[4] === 'd' ? 500 : result[0].clockSpeed;
- result[0].formFactor = 'SoC';
-
- stdout = execSync('vcgencmd get_config sdram_freq 2>/dev/null', util.execOptsLinux);
- lines = stdout.toString().split('\n');
- let freq = parseInt(util.getValue(lines, 'sdram_freq', '=', true), 10) || 0;
- if (freq) {
- result[0].clockSpeed = freq;
- }
-
- stdout = execSync('vcgencmd measure_volts sdram_p 2>/dev/null', util.execOptsLinux);
- lines = stdout.toString().split('\n');
- let voltage = parseFloat(util.getValue(lines, 'volt', '=', true)) || 0;
- if (voltage) {
- result[0].voltageConfigured = voltage;
- result[0].voltageMin = voltage;
- result[0].voltageMax = voltage;
- }
- }
- } catch (e) {
- util.noop();
- }
-
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
-
- if (_darwin) {
- exec('system_profiler SPMemoryDataType', function (error, stdout) {
- if (!error) {
- const allLines = stdout.toString().split('\n');
- const eccStatus = util.getValue(allLines, 'ecc', ':', true).toLowerCase();
- let devices = stdout.toString().split(' BANK ');
- let hasBank = true;
- if (devices.length === 1) {
- devices = stdout.toString().split(' DIMM');
- hasBank = false;
- }
- devices.shift();
- devices.forEach(function (device) {
- let lines = device.split('\n');
- const bank = (hasBank ? 'BANK ' : 'DIMM') + lines[0].trim().split('/')[0];
- const size = parseInt(util.getValue(lines, ' Size'));
- if (size) {
- result.push({
- size: size * 1024 * 1024 * 1024,
- bank: bank,
- type: util.getValue(lines, ' Type:'),
- ecc: eccStatus ? eccStatus === 'enabled' : null,
- clockSpeed: parseInt(util.getValue(lines, ' Speed:'), 10),
- formFactor: '',
- manufacturer: getManufacturerDarwin(util.getValue(lines, ' Manufacturer:')),
- partNum: util.getValue(lines, ' Part Number:'),
- serialNum: util.getValue(lines, ' Serial Number:'),
- voltageConfigured: null,
- voltageMin: null,
- voltageMax: null,
- });
- } else {
- result.push({
- size: 0,
- bank: bank,
- type: 'Empty',
- ecc: null,
- clockSpeed: 0,
- formFactor: '',
- manufacturer: '',
- partNum: '',
- serialNum: '',
- voltageConfigured: null,
- voltageMin: null,
- voltageMax: null,
- });
- }
- });
- }
- if (!result.length) {
- const lines = stdout.toString().split('\n');
- const size = parseInt(util.getValue(lines, ' Memory:'));
- const type = util.getValue(lines, ' Type:');
- const manufacturerId = util.getValue(lines, ' Manufacturer:');
- if (size && type) {
- result.push({
- size: size * 1024 * 1024 * 1024,
- bank: '0',
- type,
- ecc: false,
- clockSpeed: null,
- formFactor: 'SOC',
- manufacturer: getManufacturerDarwin(manufacturerId),
- partNum: '',
- serialNum: '',
- voltageConfigured: null,
- voltageMin: null,
- voltageMax: null,
- });
-
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- // https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0a.pdf
- const memoryTypes = 'Unknown|Other|DRAM|Synchronous DRAM|Cache DRAM|EDO|EDRAM|VRAM|SRAM|RAM|ROM|FLASH|EEPROM|FEPROM|EPROM|CDRAM|3DRAM|SDRAM|SGRAM|RDRAM|DDR|DDR2|DDR2 FB-DIMM|Reserved|DDR3|FBD2|DDR4|LPDDR|LPDDR2|LPDDR3|LPDDR4|Logical non-volatile device|HBM|HBM2|DDR5|LPDDR5'.split('|');
- const FormFactors = 'Unknown|Other|SIP|DIP|ZIP|SOJ|Proprietary|SIMM|DIMM|TSOP|PGA|RIMM|SODIMM|SRIMM|SMD|SSMP|QFP|TQFP|SOIC|LCC|PLCC|BGA|FPBGA|LGA'.split('|');
-
- try {
- util.powerShell('Get-CimInstance Win32_PhysicalMemory | select DataWidth,TotalWidth,Capacity,BankLabel,MemoryType,SMBIOSMemoryType,ConfiguredClockSpeed,FormFactor,Manufacturer,PartNumber,SerialNumber,ConfiguredVoltage,MinVoltage,MaxVoltage,Tag | fl').then((stdout, error) => {
- if (!error) {
- let devices = stdout.toString().split(/\n\s*\n/);
- devices.shift();
- devices.forEach(function (device) {
- let lines = device.split('\r\n');
- const dataWidth = util.toInt(util.getValue(lines, 'DataWidth', ':'));
- const totalWidth = util.toInt(util.getValue(lines, 'TotalWidth', ':'));
- const size = parseInt(util.getValue(lines, 'Capacity', ':'), 10) || 0;
- const tag = util.getValue(lines, 'Tag', ':');
- const tagInt = util.splitByNumber(tag);
- if (size) {
- result.push({
- size,
- bank: util.getValue(lines, 'BankLabel', ':') + (tagInt[1] ? '/' + tagInt[1] : ''), // BankLabel
- type: memoryTypes[parseInt(util.getValue(lines, 'MemoryType', ':'), 10) || parseInt(util.getValue(lines, 'SMBIOSMemoryType', ':'), 10)],
- ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false,
- clockSpeed: parseInt(util.getValue(lines, 'ConfiguredClockSpeed', ':'), 10) || parseInt(util.getValue(lines, 'Speed', ':'), 10) || 0,
- formFactor: FormFactors[parseInt(util.getValue(lines, 'FormFactor', ':'), 10) || 0],
- manufacturer: util.getValue(lines, 'Manufacturer', ':'),
- partNum: util.getValue(lines, 'PartNumber', ':'),
- serialNum: util.getValue(lines, 'SerialNumber', ':'),
- voltageConfigured: (parseInt(util.getValue(lines, 'ConfiguredVoltage', ':'), 10) || 0) / 1000.0,
- voltageMin: (parseInt(util.getValue(lines, 'MinVoltage', ':'), 10) || 0) / 1000.0,
- voltageMax: (parseInt(util.getValue(lines, 'MaxVoltage', ':'), 10) || 0) / 1000.0,
- });
- }
- });
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.memLayout = memLayout;
-
-
-
-/***/ }),
-
-/***/ 20287:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// network.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 9. Network
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const fs = __nccwpck_require__(79896);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-let _network = {};
-let _default_iface = '';
-let _ifaces = {};
-let _dhcpNics = [];
-let _networkInterfaces = [];
-let _mac = {};
-let pathToIp;
-
-function getDefaultNetworkInterface() {
-
- let ifacename = '';
- let ifacenameFirst = '';
- try {
- let ifaces = os.networkInterfaces();
-
- let scopeid = 9999;
-
- // fallback - "first" external interface (sorted by scopeid)
- for (let dev in ifaces) {
- if ({}.hasOwnProperty.call(ifaces, dev)) {
- ifaces[dev].forEach(function (details) {
- if (details && details.internal === false) {
- ifacenameFirst = ifacenameFirst || dev; // fallback if no scopeid
- if (details.scopeid && details.scopeid < scopeid) {
- ifacename = dev;
- scopeid = details.scopeid;
- }
- }
- });
- }
- }
- ifacename = ifacename || ifacenameFirst || '';
-
- if (_windows) {
- // https://www.inetdaemon.com/tutorials/internet/ip/routing/default_route.shtml
- let defaultIp = '';
- const cmd = 'netstat -r';
- const result = execSync(cmd, util.execOptsWin);
- const lines = result.toString().split(os.EOL);
- lines.forEach(line => {
- line = line.replace(/\s+/g, ' ').trim();
- if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) {
- const parts = line.split(' ');
- if (parts.length >= 5) {
- defaultIp = parts[parts.length - 2];
- }
- }
- });
- if (defaultIp) {
- for (let dev in ifaces) {
- if ({}.hasOwnProperty.call(ifaces, dev)) {
- ifaces[dev].forEach(function (details) {
- if (details && details.address && details.address === defaultIp) {
- ifacename = dev;
- }
- });
- }
- }
- }
- }
- if (_linux) {
- let cmd = 'ip route 2> /dev/null | grep default';
- let result = execSync(cmd, util.execOptsLinux);
- let parts = result.toString().split('\n')[0].split(/\s+/);
- if (parts[0] === 'none' && parts[5]) {
- ifacename = parts[5];
- } else if (parts[4]) {
- ifacename = parts[4];
- }
-
- if (ifacename.indexOf(':') > -1) {
- ifacename = ifacename.split(':')[1].trim();
- }
- }
- if (_darwin || _freebsd || _openbsd || _netbsd || _sunos) {
- let cmd = '';
- if (_linux) { cmd = 'ip route 2> /dev/null | grep default | awk \'{print $5}\''; }
- if (_darwin) { cmd = 'route -n get default 2>/dev/null | grep interface: | awk \'{print $2}\''; }
- if (_freebsd || _openbsd || _netbsd || _sunos) { cmd = 'route get 0.0.0.0 | grep interface:'; }
- let result = execSync(cmd);
- ifacename = result.toString().split('\n')[0];
- if (ifacename.indexOf(':') > -1) {
- ifacename = ifacename.split(':')[1].trim();
- }
- }
- } catch (e) {
- util.noop();
- }
- if (ifacename) { _default_iface = ifacename; }
- return _default_iface;
-}
-
-exports.getDefaultNetworkInterface = getDefaultNetworkInterface;
-
-function getMacAddresses() {
- let iface = '';
- let mac = '';
- let result = {};
- if (_linux || _freebsd || _openbsd || _netbsd) {
- if (typeof pathToIp === 'undefined') {
- try {
- const lines = execSync('which ip', util.execOptsLinux).toString().split('\n');
- if (lines.length && lines[0].indexOf(':') === -1 && lines[0].indexOf('/') === 0) {
- pathToIp = lines[0];
- } else {
- pathToIp = '';
- }
- } catch (e) {
- pathToIp = '';
- }
- }
- try {
- const cmd = 'export LC_ALL=C; ' + ((pathToIp) ? pathToIp + ' link show up' : '/sbin/ifconfig') + '; unset LC_ALL';
- let res = execSync(cmd, util.execOptsLinux);
- const lines = res.toString().split('\n');
- for (let i = 0; i < lines.length; i++) {
- if (lines[i] && lines[i][0] !== ' ') {
- if (pathToIp) {
- let nextline = lines[i + 1].trim().split(' ');
- if (nextline[0] === 'link/ether') {
- iface = lines[i].split(' ')[1];
- iface = iface.slice(0, iface.length - 1);
- mac = nextline[1];
- }
- } else {
- iface = lines[i].split(' ')[0];
- mac = lines[i].split('HWaddr ')[1];
- }
-
- if (iface && mac) {
- result[iface] = mac.trim();
- iface = '';
- mac = '';
- }
- }
- }
- } catch (e) {
- util.noop();
- }
- }
- if (_darwin) {
- try {
- const cmd = '/sbin/ifconfig';
- let res = execSync(cmd);
- const lines = res.toString().split('\n');
- for (let i = 0; i < lines.length; i++) {
- if (lines[i] && lines[i][0] !== '\t' && lines[i].indexOf(':') > 0) {
- iface = lines[i].split(':')[0];
- } else if (lines[i].indexOf('\tether ') === 0) {
- mac = lines[i].split('\tether ')[1];
- if (iface && mac) {
- result[iface] = mac.trim();
- iface = '';
- mac = '';
- }
- }
- }
- } catch (e) {
- util.noop();
- }
- }
- return result;
-}
-
-function networkInterfaceDefault(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = getDefaultNetworkInterface();
- if (callback) { callback(result); }
- resolve(result);
- });
- });
-}
-
-exports.networkInterfaceDefault = networkInterfaceDefault;
-
-// --------------------------
-// NET - interfaces
-
-function parseLinesWindowsNics(sections, nconfigsections) {
- let nics = [];
- for (let i in sections) {
- try {
- if ({}.hasOwnProperty.call(sections, i)) {
-
- if (sections[i].trim() !== '') {
-
- let lines = sections[i].trim().split('\r\n');
- let linesNicConfig = null;
- try {
- linesNicConfig = nconfigsections && nconfigsections[i] ? nconfigsections[i].trim().split('\r\n') : [];
- } catch (e) {
- util.noop();
- }
- let netEnabled = util.getValue(lines, 'NetEnabled', ':');
- let adapterType = util.getValue(lines, 'AdapterTypeID', ':') === '9' ? 'wireless' : 'wired';
- let ifacename = util.getValue(lines, 'Name', ':').replace(/\]/g, ')').replace(/\[/g, '(');
- let iface = util.getValue(lines, 'NetConnectionID', ':').replace(/\]/g, ')').replace(/\[/g, '(');
- if (ifacename.toLowerCase().indexOf('wi-fi') >= 0 || ifacename.toLowerCase().indexOf('wireless') >= 0) {
- adapterType = 'wireless';
- }
- if (netEnabled !== '') {
- const speed = parseInt(util.getValue(lines, 'speed', ':').trim(), 10) / 1000000;
- nics.push({
- mac: util.getValue(lines, 'MACAddress', ':').toLowerCase(),
- dhcp: util.getValue(linesNicConfig, 'dhcpEnabled', ':').toLowerCase() === 'true',
- name: ifacename,
- iface,
- netEnabled: netEnabled === 'TRUE',
- speed: isNaN(speed) ? null : speed,
- operstate: util.getValue(lines, 'NetConnectionStatus', ':') === '2' ? 'up' : 'down',
- type: adapterType
- });
- }
- }
- }
- } catch (e) {
- util.noop();
- }
- }
- return nics;
-}
-
-function getWindowsNics() {
- return new Promise((resolve) => {
- process.nextTick(() => {
- let cmd = 'Get-CimInstance Win32_NetworkAdapter | fl *' + '; echo \'#-#-#-#\';';
- cmd += 'Get-CimInstance Win32_NetworkAdapterConfiguration | fl DHCPEnabled' + '';
- try {
- util.powerShell(cmd).then((data) => {
- data = data.split('#-#-#-#');
- const nsections = (data[0] || '').split(/\n\s*\n/);
- const nconfigsections = (data[1] || '').split(/\n\s*\n/);
- resolve(parseLinesWindowsNics(nsections, nconfigsections));
- });
- } catch (e) {
- resolve([]);
- }
- });
- });
-}
-
-function getWindowsDNSsuffixes() {
-
- let iface = {};
-
- let dnsSuffixes = {
- primaryDNS: '',
- exitCode: 0,
- ifaces: [],
- };
-
- try {
- const ipconfig = execSync('ipconfig /all', util.execOptsWin);
- const ipconfigArray = ipconfig.split('\r\n\r\n');
-
- ipconfigArray.forEach((element, index) => {
-
- if (index == 1) {
- const longPrimaryDNS = element.split('\r\n').filter((element) => {
- return element.toUpperCase().includes('DNS');
- });
- const primaryDNS = longPrimaryDNS[0].substring(longPrimaryDNS[0].lastIndexOf(':') + 1);
- dnsSuffixes.primaryDNS = primaryDNS.trim();
- if (!dnsSuffixes.primaryDNS) { dnsSuffixes.primaryDNS = 'Not defined'; }
- }
- if (index > 1) {
- if (index % 2 == 0) {
- const name = element.substring(element.lastIndexOf(' ') + 1).replace(':', '');
- iface.name = name;
- } else {
- const connectionSpecificDNS = element.split('\r\n').filter((element) => {
- return element.toUpperCase().includes('DNS');
- });
- const dnsSuffix = connectionSpecificDNS[0].substring(connectionSpecificDNS[0].lastIndexOf(':') + 1);
- iface.dnsSuffix = dnsSuffix.trim();
- dnsSuffixes.ifaces.push(iface);
- iface = {};
- }
- }
- });
-
- return dnsSuffixes;
- } catch (error) {
- return {
- primaryDNS: '',
- exitCode: 0,
- ifaces: [],
- };
- }
-}
-
-function getWindowsIfaceDNSsuffix(ifaces, ifacename) {
- let dnsSuffix = '';
- // Adding (.) to ensure ifacename compatibility when duplicated iface-names
- const interfaceName = ifacename + '.';
- try {
- const connectionDnsSuffix = ifaces.filter((iface) => {
- return interfaceName.includes(iface.name + '.');
- }).map((iface) => iface.dnsSuffix);
- if (connectionDnsSuffix[0]) {
- dnsSuffix = connectionDnsSuffix[0];
- }
- if (!dnsSuffix) { dnsSuffix = ''; }
- return dnsSuffix;
- } catch (error) {
- return 'Unknown';
- }
-}
-
-function getWindowsWiredProfilesInformation() {
- try {
- const result = execSync('netsh lan show profiles', util.execOptsWin);
- const profileList = result.split('\r\nProfile on interface');
- return profileList;
- } catch (error) {
- if (error.status === 1 && error.stdout.includes('AutoConfig')) {
- return 'Disabled';
- }
- return [];
- }
-}
-
-function getWindowsWirelessIfaceSSID(interfaceName) {
- try {
- const result = execSync(`netsh wlan show interface name="${interfaceName}" | findstr "SSID"`, util.execOptsWin);
- const SSID = result.split('\r\n').shift();
- const parseSSID = SSID.split(':').pop().trim();
- return parseSSID;
- } catch (error) {
- return 'Unknown';
- }
-}
-function getWindowsIEEE8021x(connectionType, iface, ifaces) {
- let i8021x = {
- state: 'Unknown',
- protocol: 'Unknown',
- };
-
- if (ifaces === 'Disabled') {
- i8021x.state = 'Disabled';
- i8021x.protocol = 'Not defined';
- return i8021x;
- }
-
- if (connectionType == 'wired' && ifaces.length > 0) {
- try {
- // Get 802.1x information by interface name
- const iface8021xInfo = ifaces.find((element) => {
- return element.includes(iface + '\r\n');
- });
- const arrayIface8021xInfo = iface8021xInfo.split('\r\n');
- const state8021x = arrayIface8021xInfo.find((element) => {
- return element.includes('802.1x');
- });
-
- if (state8021x.includes('Disabled')) {
- i8021x.state = 'Disabled';
- i8021x.protocol = 'Not defined';
- } else if (state8021x.includes('Enabled')) {
- const protocol8021x = arrayIface8021xInfo.find((element) => {
- return element.includes('EAP');
- });
- i8021x.protocol = protocol8021x.split(':').pop();
- i8021x.state = 'Enabled';
- }
- } catch (error) {
- return i8021x;
- }
- } else if (connectionType == 'wireless') {
-
- let i8021xState = '';
- let i8021xProtocol = '';
-
-
-
- try {
- const SSID = getWindowsWirelessIfaceSSID(iface);
- if (SSID !== 'Unknown') {
-
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(SSID);
- const l = util.mathMin(s.length, 32);
-
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
- i8021xState = execSync(`netsh wlan show profiles "${ifaceSanitized}" | findstr "802.1X"`, util.execOptsWin);
- i8021xProtocol = execSync(`netsh wlan show profiles "${ifaceSanitized}" | findstr "EAP"`, util.execOptsWin);
- }
-
- if (i8021xState.includes(':') && i8021xProtocol.includes(':')) {
- i8021x.state = i8021xState.split(':').pop();
- i8021x.protocol = i8021xProtocol.split(':').pop();
- }
- } catch (error) {
- if (error.status === 1 && error.stdout.includes('AutoConfig')) {
- i8021x.state = 'Disabled';
- i8021x.protocol = 'Not defined';
- }
- return i8021x;
- }
- }
-
- return i8021x;
-}
-
-function splitSectionsNics(lines) {
- const result = [];
- let section = [];
- lines.forEach(function (line) {
- if (!line.startsWith('\t') && !line.startsWith(' ')) {
- if (section.length) {
- result.push(section);
- section = [];
- }
- }
- section.push(line);
- });
- if (section.length) {
- result.push(section);
- }
- return result;
-}
-
-function parseLinesDarwinNics(sections) {
- let nics = [];
- sections.forEach(section => {
- let nic = {
- iface: '',
- mtu: null,
- mac: '',
- ip6: '',
- ip4: '',
- speed: null,
- type: '',
- operstate: '',
- duplex: '',
- internal: false
- };
- const first = section[0];
- nic.iface = first.split(':')[0].trim();
- let parts = first.split('> mtu');
- nic.mtu = parts.length > 1 ? parseInt(parts[1], 10) : null;
- if (isNaN(nic.mtu)) {
- nic.mtu = null;
- }
- nic.internal = parts[0].toLowerCase().indexOf('loopback') > -1;
- section.forEach(line => {
- if (line.trim().startsWith('ether ')) {
- nic.mac = line.split('ether ')[1].toLowerCase().trim();
- }
- if (line.trim().startsWith('inet6 ') && !nic.ip6) {
- nic.ip6 = line.split('inet6 ')[1].toLowerCase().split('%')[0].split(' ')[0];
- }
- if (line.trim().startsWith('inet ') && !nic.ip4) {
- nic.ip4 = line.split('inet ')[1].toLowerCase().split(' ')[0];
- }
- });
- let speed = util.getValue(section, 'link rate');
- nic.speed = speed ? parseFloat(speed) : null;
- if (nic.speed === null) {
- speed = util.getValue(section, 'uplink rate');
- nic.speed = speed ? parseFloat(speed) : null;
- if (nic.speed !== null && speed.toLowerCase().indexOf('gbps') >= 0) {
- nic.speed = nic.speed * 1000;
- }
- } else {
- if (speed.toLowerCase().indexOf('gbps') >= 0) {
- nic.speed = nic.speed * 1000;
- }
- }
- nic.type = util.getValue(section, 'type').toLowerCase().indexOf('wi-fi') > -1 ? 'wireless' : 'wired';
- const operstate = util.getValue(section, 'status').toLowerCase();
- nic.operstate = (operstate === 'active' ? 'up' : (operstate === 'inactive' ? 'down' : 'unknown'));
- nic.duplex = util.getValue(section, 'media').toLowerCase().indexOf('half-duplex') > -1 ? 'half' : 'full';
- if (nic.ip6 || nic.ip4 || nic.mac) {
- nics.push(nic);
- }
- });
- return nics;
-}
-
-function getDarwinNics() {
- const cmd = '/sbin/ifconfig -v';
- try {
- const lines = execSync(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n');
- const nsections = splitSectionsNics(lines);
- return (parseLinesDarwinNics(nsections));
- } catch (e) {
- return [];
- }
-}
-
-function getLinuxIfaceConnectionName(interfaceName) {
- const cmd = `nmcli device status 2>/dev/null | grep ${interfaceName}`;
-
- try {
- const result = execSync(cmd, util.execOptsLinux).toString();
- const resultFormat = result.replace(/\s+/g, ' ').trim();
- const connectionNameLines = resultFormat.split(' ').slice(3);
- const connectionName = connectionNameLines.join(' ');
- return connectionName != '--' ? connectionName : '';
- } catch (e) {
- return '';
- }
-}
-
-function checkLinuxDCHPInterfaces(file) {
- let result = [];
- try {
- let cmd = `cat ${file} 2> /dev/null | grep 'iface\\|source'`;
- const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
-
- lines.forEach(line => {
- const parts = line.replace(/\s+/g, ' ').trim().split(' ');
- if (parts.length >= 4) {
- if (line.toLowerCase().indexOf(' inet ') >= 0 && line.toLowerCase().indexOf('dhcp') >= 0) {
- result.push(parts[1]);
- }
- }
- if (line.toLowerCase().includes('source')) {
- let file = line.split(' ')[1];
- result = result.concat(checkLinuxDCHPInterfaces(file));
- }
- });
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function getLinuxDHCPNics() {
- // alternate methods getting interfaces using DHCP
- let cmd = 'ip a 2> /dev/null';
- let result = [];
- try {
- const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- const nsections = splitSectionsNics(lines);
- result = (parseLinuxDHCPNics(nsections));
- } catch (e) {
- util.noop();
- }
- try {
- result = checkLinuxDCHPInterfaces('/etc/network/interfaces');
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function parseLinuxDHCPNics(sections) {
- const result = [];
- if (sections && sections.length) {
- sections.forEach(lines => {
- if (lines && lines.length) {
- const parts = lines[0].split(':');
- if (parts.length > 2) {
- for (let line of lines) {
- if (line.indexOf(' inet ') >= 0 && line.indexOf(' dynamic ') >= 0) {
- const parts2 = line.split(' ');
- const nic = parts2[parts2.length - 1].trim();
- result.push(nic);
- break;
- }
- }
- }
- }
- });
- }
- return result;
-}
-
-function getLinuxIfaceDHCPstatus(iface, connectionName, DHCPNics) {
- let result = false;
- if (connectionName) {
- const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.method;`;
- try {
- const lines = execSync(cmd, util.execOptsLinux).toString();
- const resultFormat = lines.replace(/\s+/g, ' ').trim();
-
- let dhcStatus = resultFormat.split(' ').slice(1).toString();
- switch (dhcStatus) {
- case 'auto':
- result = true;
- break;
-
- default:
- result = false;
- break;
- }
- return result;
- } catch (e) {
- return (DHCPNics.indexOf(iface) >= 0);
- }
- } else {
- return (DHCPNics.indexOf(iface) >= 0);
- }
-}
-
-function getDarwinIfaceDHCPstatus(iface) {
- let result = false;
- const cmd = `ipconfig getpacket "${iface}" 2>/dev/null | grep lease_time;`;
- try {
- const lines = execSync(cmd).toString().split('\n');
- if (lines.length && lines[0].startsWith('lease_time')) {
- result = true;
- }
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function getLinuxIfaceDNSsuffix(connectionName) {
- if (connectionName) {
- const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.dns-search;`;
- try {
- const result = execSync(cmd, util.execOptsLinux).toString();
- const resultFormat = result.replace(/\s+/g, ' ').trim();
- const dnsSuffix = resultFormat.split(' ').slice(1).toString();
- return dnsSuffix == '--' ? 'Not defined' : dnsSuffix;
- } catch (e) {
- return 'Unknown';
- }
- } else {
- return 'Unknown';
- }
-}
-
-function getLinuxIfaceIEEE8021xAuth(connectionName) {
- if (connectionName) {
- const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep 802-1x.eap;`;
- try {
- const result = execSync(cmd, util.execOptsLinux).toString();
- const resultFormat = result.replace(/\s+/g, ' ').trim();
- const authenticationProtocol = resultFormat.split(' ').slice(1).toString();
-
-
- return authenticationProtocol == '--' ? '' : authenticationProtocol;
- } catch (e) {
- return 'Not defined';
- }
- } else {
- return 'Not defined';
- }
-}
-
-function getLinuxIfaceIEEE8021xState(authenticationProtocol) {
- if (authenticationProtocol) {
- if (authenticationProtocol == 'Not defined') {
- return 'Disabled';
- }
- return 'Enabled';
- } else {
- return 'Unknown';
- }
-}
-
-function testVirtualNic(iface, ifaceName, mac) {
- const virtualMacs = ['00:00:00:00:00:00', '00:03:FF', '00:05:69', '00:0C:29', '00:0F:4B', '00:13:07', '00:13:BE', '00:15:5d', '00:16:3E', '00:1C:42', '00:21:F6', '00:24:0B', '00:50:56', '00:A0:B1', '00:E0:C8', '08:00:27', '0A:00:27', '18:92:2C', '16:DF:49', '3C:F3:92', '54:52:00', 'FC:15:97'];
- if (mac) {
- return virtualMacs.filter(item => { return mac.toUpperCase().toUpperCase().startsWith(item.substring(0, mac.length)); }).length > 0 ||
- iface.toLowerCase().indexOf(' virtual ') > -1 ||
- ifaceName.toLowerCase().indexOf(' virtual ') > -1 ||
- iface.toLowerCase().indexOf('vethernet ') > -1 ||
- ifaceName.toLowerCase().indexOf('vethernet ') > -1 ||
- iface.toLowerCase().startsWith('veth') ||
- ifaceName.toLowerCase().startsWith('veth') ||
- iface.toLowerCase().startsWith('vboxnet') ||
- ifaceName.toLowerCase().startsWith('vboxnet');
- } else { return false; }
-}
-
-function networkInterfaces(callback, rescan, defaultString) {
-
- if (typeof callback === 'string') {
- defaultString = callback;
- rescan = true;
- callback = null;
- }
-
- if (typeof callback === 'boolean') {
- rescan = callback;
- callback = null;
- defaultString = '';
- }
- if (typeof rescan === 'undefined') {
- rescan = true;
- }
- defaultString = defaultString || '';
- defaultString = '' + defaultString;
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let ifaces = os.networkInterfaces();
-
- let result = [];
- let nics = [];
- let dnsSuffixes = [];
- let nics8021xInfo = [];
- // seperate handling in OSX
- if (_darwin || _freebsd || _openbsd || _netbsd) {
- if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
- // no changes - just return object
- result = _networkInterfaces;
-
- if (callback) { callback(result); }
- resolve(result);
- } else {
- const defaultInterface = getDefaultNetworkInterface();
- _ifaces = JSON.parse(JSON.stringify(ifaces));
-
- nics = getDarwinNics();
-
-
- nics.forEach(nic => {
-
- if ({}.hasOwnProperty.call(ifaces, nic.iface)) {
- ifaces[nic.iface].forEach(function (details) {
- if (details.family === 'IPv4' || details.family === 4) {
- nic.ip4subnet = details.netmask;
- }
- if (details.family === 'IPv6' || details.family === 6) {
- nic.ip6subnet = details.netmask;
- }
- });
- }
-
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(nic.iface);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
-
- result.push({
- iface: nic.iface,
- ifaceName: nic.iface,
- default: nic.iface === defaultInterface,
- ip4: nic.ip4,
- ip4subnet: nic.ip4subnet || '',
- ip6: nic.ip6,
- ip6subnet: nic.ip6subnet || '',
- mac: nic.mac,
- internal: nic.internal,
- virtual: nic.internal ? false : testVirtualNic(nic.iface, nic.iface, nic.mac),
- operstate: nic.operstate,
- type: nic.type,
- duplex: nic.duplex,
- mtu: nic.mtu,
- speed: nic.speed,
- dhcp: getDarwinIfaceDHCPstatus(ifaceSanitized),
- dnsSuffix: '',
- ieee8021xAuth: '',
- ieee8021xState: '',
- carrierChanges: 0
- });
- });
- _networkInterfaces = result;
- if (defaultString.toLowerCase().indexOf('default') >= 0) {
- result = result.filter(item => item.default);
- if (result.length > 0) {
- result = result[0];
- } else {
- result = [];
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_linux) {
- if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
- // no changes - just return object
- result = _networkInterfaces;
-
- if (callback) { callback(result); }
- resolve(result);
- } else {
- _ifaces = JSON.parse(JSON.stringify(ifaces));
- _dhcpNics = getLinuxDHCPNics();
- const defaultInterface = getDefaultNetworkInterface();
- for (let dev in ifaces) {
- let ip4 = '';
- let ip4subnet = '';
- let ip6 = '';
- let ip6subnet = '';
- let mac = '';
- let duplex = '';
- let mtu = '';
- let speed = null;
- let carrierChanges = 0;
- let dhcp = false;
- let dnsSuffix = '';
- let ieee8021xAuth = '';
- let ieee8021xState = '';
- let type = '';
-
- if ({}.hasOwnProperty.call(ifaces, dev)) {
- let ifaceName = dev;
- ifaces[dev].forEach(function (details) {
- if (details.family === 'IPv4' || details.family === 4) {
- ip4 = details.address;
- ip4subnet = details.netmask;
- }
- if (details.family === 'IPv6' || details.family === 6) {
- if (!ip6 || ip6.match(/^fe80::/i)) {
- ip6 = details.address;
- ip6subnet = details.netmask;
- }
- }
- mac = details.mac;
- // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2)
- const nodeMainVersion = parseInt(process.versions.node.split('.'), 10);
- if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) {
- if (Object.keys(_mac).length === 0) {
- _mac = getMacAddresses();
- }
- mac = _mac[dev] || '';
- }
- });
- let iface = dev.split(':')[0].trim().toLowerCase();
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
- const cmd = `echo -n "addr_assign_type: "; cat /sys/class/net/${ifaceSanitized}/addr_assign_type 2>/dev/null; echo;
- echo -n "address: "; cat /sys/class/net/${ifaceSanitized}/address 2>/dev/null; echo;
- echo -n "addr_len: "; cat /sys/class/net/${ifaceSanitized}/addr_len 2>/dev/null; echo;
- echo -n "broadcast: "; cat /sys/class/net/${ifaceSanitized}/broadcast 2>/dev/null; echo;
- echo -n "carrier: "; cat /sys/class/net/${ifaceSanitized}/carrier 2>/dev/null; echo;
- echo -n "carrier_changes: "; cat /sys/class/net/${ifaceSanitized}/carrier_changes 2>/dev/null; echo;
- echo -n "dev_id: "; cat /sys/class/net/${ifaceSanitized}/dev_id 2>/dev/null; echo;
- echo -n "dev_port: "; cat /sys/class/net/${ifaceSanitized}/dev_port 2>/dev/null; echo;
- echo -n "dormant: "; cat /sys/class/net/${ifaceSanitized}/dormant 2>/dev/null; echo;
- echo -n "duplex: "; cat /sys/class/net/${ifaceSanitized}/duplex 2>/dev/null; echo;
- echo -n "flags: "; cat /sys/class/net/${ifaceSanitized}/flags 2>/dev/null; echo;
- echo -n "gro_flush_timeout: "; cat /sys/class/net/${ifaceSanitized}/gro_flush_timeout 2>/dev/null; echo;
- echo -n "ifalias: "; cat /sys/class/net/${ifaceSanitized}/ifalias 2>/dev/null; echo;
- echo -n "ifindex: "; cat /sys/class/net/${ifaceSanitized}/ifindex 2>/dev/null; echo;
- echo -n "iflink: "; cat /sys/class/net/${ifaceSanitized}/iflink 2>/dev/null; echo;
- echo -n "link_mode: "; cat /sys/class/net/${ifaceSanitized}/link_mode 2>/dev/null; echo;
- echo -n "mtu: "; cat /sys/class/net/${ifaceSanitized}/mtu 2>/dev/null; echo;
- echo -n "netdev_group: "; cat /sys/class/net/${ifaceSanitized}/netdev_group 2>/dev/null; echo;
- echo -n "operstate: "; cat /sys/class/net/${ifaceSanitized}/operstate 2>/dev/null; echo;
- echo -n "proto_down: "; cat /sys/class/net/${ifaceSanitized}/proto_down 2>/dev/null; echo;
- echo -n "speed: "; cat /sys/class/net/${ifaceSanitized}/speed 2>/dev/null; echo;
- echo -n "tx_queue_len: "; cat /sys/class/net/${ifaceSanitized}/tx_queue_len 2>/dev/null; echo;
- echo -n "type: "; cat /sys/class/net/${ifaceSanitized}/type 2>/dev/null; echo;
- echo -n "wireless: "; cat /proc/net/wireless 2>/dev/null | grep ${ifaceSanitized}; echo;
- echo -n "wirelessspeed: "; iw dev ${ifaceSanitized} link 2>&1 | grep bitrate; echo;`;
-
- let lines = [];
- try {
- lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- const connectionName = getLinuxIfaceConnectionName(ifaceSanitized);
- dhcp = getLinuxIfaceDHCPstatus(ifaceSanitized, connectionName, _dhcpNics);
- dnsSuffix = getLinuxIfaceDNSsuffix(connectionName);
- ieee8021xAuth = getLinuxIfaceIEEE8021xAuth(connectionName);
- ieee8021xState = getLinuxIfaceIEEE8021xState(ieee8021xAuth);
- } catch (e) {
- util.noop();
- }
- duplex = util.getValue(lines, 'duplex');
- duplex = duplex.startsWith('cat') ? '' : duplex;
- mtu = parseInt(util.getValue(lines, 'mtu'), 10);
- let myspeed = parseInt(util.getValue(lines, 'speed'), 10);
- speed = isNaN(myspeed) ? null : myspeed;
- let wirelessspeed = util.getValue(lines, 'wirelessspeed').split('tx bitrate: ');
- if (speed === null && wirelessspeed.length === 2) {
- myspeed = parseFloat(wirelessspeed[1]);
- speed = isNaN(myspeed) ? null : myspeed;
- }
- carrierChanges = parseInt(util.getValue(lines, 'carrier_changes'), 10);
- const operstate = util.getValue(lines, 'operstate');
- type = operstate === 'up' ? (util.getValue(lines, 'wireless').trim() ? 'wireless' : 'wired') : 'unknown';
- if (ifaceSanitized === 'lo' || ifaceSanitized.startsWith('bond')) { type = 'virtual'; }
-
- let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false;
- if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) {
- internal = true;
- }
- const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac);
- result.push({
- iface: ifaceSanitized,
- ifaceName,
- default: iface === defaultInterface,
- ip4,
- ip4subnet,
- ip6,
- ip6subnet,
- mac,
- internal,
- virtual,
- operstate,
- type,
- duplex,
- mtu,
- speed,
- dhcp,
- dnsSuffix,
- ieee8021xAuth,
- ieee8021xState,
- carrierChanges,
- });
- }
- }
- _networkInterfaces = result;
- if (defaultString.toLowerCase().indexOf('default') >= 0) {
- result = result.filter(item => item.default);
- if (result.length > 0) {
- result = result[0];
- } else {
- result = [];
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_windows) {
- if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
- // no changes - just return object
- result = _networkInterfaces;
-
- if (callback) { callback(result); }
- resolve(result);
- } else {
- _ifaces = JSON.parse(JSON.stringify(ifaces));
- const defaultInterface = getDefaultNetworkInterface();
-
- getWindowsNics().then(function (nics) {
- nics.forEach(nic => {
- let found = false;
- Object.keys(ifaces).forEach(key => {
- if (!found) {
- ifaces[key].forEach(value => {
- if (Object.keys(value).indexOf('mac') >= 0) {
- found = value['mac'] === nic.mac;
- }
- });
- }
- });
-
- if (!found) {
- ifaces[nic.name] = [{ mac: nic.mac }];
- }
- });
- nics8021xInfo = getWindowsWiredProfilesInformation();
- dnsSuffixes = getWindowsDNSsuffixes();
- for (let dev in ifaces) {
-
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(dev);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
-
- let iface = dev;
- let ip4 = '';
- let ip4subnet = '';
- let ip6 = '';
- let ip6subnet = '';
- let mac = '';
- let duplex = '';
- let mtu = '';
- let speed = null;
- let carrierChanges = 0;
- let operstate = 'down';
- let dhcp = false;
- let dnsSuffix = '';
- let ieee8021xAuth = '';
- let ieee8021xState = '';
- let type = '';
-
- if ({}.hasOwnProperty.call(ifaces, dev)) {
- let ifaceName = dev;
- ifaces[dev].forEach(function (details) {
- if (details.family === 'IPv4' || details.family === 4) {
- ip4 = details.address;
- ip4subnet = details.netmask;
- }
- if (details.family === 'IPv6' || details.family === 6) {
- if (!ip6 || ip6.match(/^fe80::/i)) {
- ip6 = details.address;
- ip6subnet = details.netmask;
- }
- }
- mac = details.mac;
- // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2)
- const nodeMainVersion = parseInt(process.versions.node.split('.'), 10);
- if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) {
- if (Object.keys(_mac).length === 0) {
- _mac = getMacAddresses();
- }
- mac = _mac[dev] || '';
- }
- });
-
-
-
- dnsSuffix = getWindowsIfaceDNSsuffix(dnsSuffixes.ifaces, ifaceSanitized);
- let foundFirst = false;
- nics.forEach(detail => {
- if (detail.mac === mac && !foundFirst) {
- iface = detail.iface || iface;
- ifaceName = detail.name;
- dhcp = detail.dhcp;
- operstate = detail.operstate;
- speed = operstate === 'up' ? detail.speed : 0;
- type = detail.type;
- foundFirst = true;
- }
- });
-
- if (dev.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('802.11n') >= 0 || ifaceName.toLowerCase().indexOf('wireless') >= 0 || ifaceName.toLowerCase().indexOf('wi-fi') >= 0 || ifaceName.toLowerCase().indexOf('wifi') >= 0) {
- type = 'wireless';
- }
-
- const IEEE8021x = getWindowsIEEE8021x(type, ifaceSanitized, nics8021xInfo);
- ieee8021xAuth = IEEE8021x.protocol;
- ieee8021xState = IEEE8021x.state;
- let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false;
- if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) {
- internal = true;
- }
- const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac);
- result.push({
- iface,
- ifaceName,
- default: iface === defaultInterface,
- ip4,
- ip4subnet,
- ip6,
- ip6subnet,
- mac,
- internal,
- virtual,
- operstate,
- type,
- duplex,
- mtu,
- speed,
- dhcp,
- dnsSuffix,
- ieee8021xAuth,
- ieee8021xState,
- carrierChanges,
- });
- }
- }
- _networkInterfaces = result;
- if (defaultString.toLowerCase().indexOf('default') >= 0) {
- result = result.filter(item => item.default);
- if (result.length > 0) {
- result = result[0];
- } else {
- result = [];
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- }
- });
- });
-}
-
-exports.networkInterfaces = networkInterfaces;
-
-// --------------------------
-// NET - Speed
-
-function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors) {
- let result = {
- iface,
- operstate,
- rx_bytes,
- rx_dropped,
- rx_errors,
- tx_bytes,
- tx_dropped,
- tx_errors,
- rx_sec: null,
- tx_sec: null,
- ms: 0
- };
-
- if (_network[iface] && _network[iface].ms) {
- result.ms = Date.now() - _network[iface].ms;
- result.rx_sec = (rx_bytes - _network[iface].rx_bytes) >= 0 ? (rx_bytes - _network[iface].rx_bytes) / (result.ms / 1000) : 0;
- result.tx_sec = (tx_bytes - _network[iface].tx_bytes) >= 0 ? (tx_bytes - _network[iface].tx_bytes) / (result.ms / 1000) : 0;
- _network[iface].rx_bytes = rx_bytes;
- _network[iface].tx_bytes = tx_bytes;
- _network[iface].rx_sec = result.rx_sec;
- _network[iface].tx_sec = result.tx_sec;
- _network[iface].ms = Date.now();
- _network[iface].last_ms = result.ms;
- _network[iface].operstate = operstate;
- } else {
- if (!_network[iface]) { _network[iface] = {}; }
- _network[iface].rx_bytes = rx_bytes;
- _network[iface].tx_bytes = tx_bytes;
- _network[iface].rx_sec = null;
- _network[iface].tx_sec = null;
- _network[iface].ms = Date.now();
- _network[iface].last_ms = 0;
- _network[iface].operstate = operstate;
- }
- return result;
-}
-
-function networkStats(ifaces, callback) {
-
- let ifacesArray = [];
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- // fallback - if only callback is given
- if (util.isFunction(ifaces) && !callback) {
- callback = ifaces;
- ifacesArray = [getDefaultNetworkInterface()];
- } else {
- if (typeof ifaces !== 'string' && ifaces !== undefined) {
- if (callback) { callback([]); }
- return resolve([]);
- }
- ifaces = ifaces || getDefaultNetworkInterface();
-
- try {
- ifaces.__proto__.toLowerCase = util.stringToLower;
- ifaces.__proto__.replace = util.stringReplace;
- ifaces.__proto__.trim = util.stringTrim;
- } catch (e) {
- Object.setPrototypeOf(ifaces, util.stringObj);
- }
-
- ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|');
- ifacesArray = ifaces.split('|');
- }
-
- const result = [];
-
- const workload = [];
- if (ifacesArray.length && ifacesArray[0].trim() === '*') {
- ifacesArray = [];
- networkInterfaces(false).then(allIFaces => {
- for (let iface of allIFaces) {
- ifacesArray.push(iface.iface);
- }
- networkStats(ifacesArray.join(',')).then(result => {
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- } else {
- for (let iface of ifacesArray) {
- workload.push(networkStatsSingle(iface.trim()));
- }
- if (workload.length) {
- Promise.all(
- workload
- ).then((data) => {
- if (callback) { callback(data); }
- resolve(data);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-function networkStatsSingle(iface) {
-
- function parseLinesWindowsPerfData(sections) {
- let perfData = [];
- for (let i in sections) {
- if ({}.hasOwnProperty.call(sections, i)) {
- if (sections[i].trim() !== '') {
- let lines = sections[i].trim().split('\r\n');
- perfData.push({
- name: util.getValue(lines, 'Name', ':').replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase(),
- rx_bytes: parseInt(util.getValue(lines, 'BytesReceivedPersec', ':'), 10),
- rx_errors: parseInt(util.getValue(lines, 'PacketsReceivedErrors', ':'), 10),
- rx_dropped: parseInt(util.getValue(lines, 'PacketsReceivedDiscarded', ':'), 10),
- tx_bytes: parseInt(util.getValue(lines, 'BytesSentPersec', ':'), 10),
- tx_errors: parseInt(util.getValue(lines, 'PacketsOutboundErrors', ':'), 10),
- tx_dropped: parseInt(util.getValue(lines, 'PacketsOutboundDiscarded', ':'), 10)
- });
- }
- }
- }
- return perfData;
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
-
- let result = {
- iface: ifaceSanitized,
- operstate: 'unknown',
- rx_bytes: 0,
- rx_dropped: 0,
- rx_errors: 0,
- tx_bytes: 0,
- tx_dropped: 0,
- tx_errors: 0,
- rx_sec: null,
- tx_sec: null,
- ms: 0
- };
-
- let operstate = 'unknown';
- let rx_bytes = 0;
- let tx_bytes = 0;
- let rx_dropped = 0;
- let rx_errors = 0;
- let tx_dropped = 0;
- let tx_errors = 0;
-
- let cmd, lines, stats;
- if (!_network[ifaceSanitized] || (_network[ifaceSanitized] && !_network[ifaceSanitized].ms) || (_network[ifaceSanitized] && _network[ifaceSanitized].ms && Date.now() - _network[ifaceSanitized].ms >= 500)) {
- if (_linux) {
- if (fs.existsSync('/sys/class/net/' + ifaceSanitized)) {
- cmd =
- 'cat /sys/class/net/' + ifaceSanitized + '/operstate; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_bytes; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_bytes; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_dropped; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_errors; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_dropped; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_errors; ';
- exec(cmd, function (error, stdout) {
- if (!error) {
- lines = stdout.toString().split('\n');
- operstate = lines[0].trim();
- rx_bytes = parseInt(lines[1], 10);
- tx_bytes = parseInt(lines[2], 10);
- rx_dropped = parseInt(lines[3], 10);
- rx_errors = parseInt(lines[4], 10);
- tx_dropped = parseInt(lines[5], 10);
- tx_errors = parseInt(lines[6], 10);
-
- result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
-
- }
- resolve(result);
- });
- } else {
- resolve(result);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- cmd = 'netstat -ibndI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input]
- exec(cmd, function (error, stdout) {
- if (!error) {
- lines = stdout.toString().split('\n');
- for (let i = 1; i < lines.length; i++) {
- const line = lines[i].replace(/ +/g, ' ').split(' ');
- if (line && line[0] && line[7] && line[10]) {
- rx_bytes = rx_bytes + parseInt(line[7]);
- if (line[6].trim() !== '-') { rx_dropped = rx_dropped + parseInt(line[6]); }
- if (line[5].trim() !== '-') { rx_errors = rx_errors + parseInt(line[5]); }
- tx_bytes = tx_bytes + parseInt(line[10]);
- if (line[12].trim() !== '-') { tx_dropped = tx_dropped + parseInt(line[12]); }
- if (line[9].trim() !== '-') { tx_errors = tx_errors + parseInt(line[9]); }
- operstate = 'up';
- }
- }
- result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
- }
- resolve(result);
- });
- }
- if (_darwin) {
- cmd = 'ifconfig ' + ifaceSanitized + ' | grep "status"'; // lgtm [js/shell-command-constructed-from-input]
- exec(cmd, function (error, stdout) {
- result.operstate = (stdout.toString().split(':')[1] || '').trim();
- result.operstate = (result.operstate || '').toLowerCase();
- result.operstate = (result.operstate === 'active' ? 'up' : (result.operstate === 'inactive' ? 'down' : 'unknown'));
- cmd = 'netstat -bdI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input]
- exec(cmd, function (error, stdout) {
- if (!error) {
- lines = stdout.toString().split('\n');
- // if there is less than 2 lines, no information for this interface was found
- if (lines.length > 1 && lines[1].trim() !== '') {
- // skip header line
- // use the second line because it is tied to the NIC instead of the ipv4 or ipv6 address
- stats = lines[1].replace(/ +/g, ' ').split(' ');
- const offset = stats.length > 11 ? 1 : 0;
- rx_bytes = parseInt(stats[offset + 5]);
- rx_dropped = parseInt(stats[offset + 10]);
- rx_errors = parseInt(stats[offset + 4]);
- tx_bytes = parseInt(stats[offset + 8]);
- tx_dropped = parseInt(stats[offset + 10]);
- tx_errors = parseInt(stats[offset + 7]);
- result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, result.operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
- }
- }
- resolve(result);
- });
- });
- }
- if (_windows) {
- let perfData = [];
- let ifaceName = ifaceSanitized;
-
- // Performance Data
- util.powerShell('Get-CimInstance Win32_PerfRawData_Tcpip_NetworkInterface | select Name,BytesReceivedPersec,PacketsReceivedErrors,PacketsReceivedDiscarded,BytesSentPersec,PacketsOutboundErrors,PacketsOutboundDiscarded | fl').then((stdout, error) => {
- if (!error) {
- const psections = stdout.toString().split(/\n\s*\n/);
- perfData = parseLinesWindowsPerfData(psections);
- }
-
- // Network Interfaces
- networkInterfaces(false).then(interfaces => {
- // get bytes sent, received from perfData by name
- rx_bytes = 0;
- tx_bytes = 0;
- perfData.forEach(detail => {
- interfaces.forEach(det => {
- if ((det.iface.toLowerCase() === ifaceSanitized.toLowerCase() ||
- det.mac.toLowerCase() === ifaceSanitized.toLowerCase() ||
- det.ip4.toLowerCase() === ifaceSanitized.toLowerCase() ||
- det.ip6.toLowerCase() === ifaceSanitized.toLowerCase() ||
- det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === ifaceSanitized.replace(/[()[\] ]+/g, '').replace('#', '_').toLowerCase()) &&
- (det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === detail.name)) {
- ifaceName = det.iface;
- rx_bytes = detail.rx_bytes;
- rx_dropped = detail.rx_dropped;
- rx_errors = detail.rx_errors;
- tx_bytes = detail.tx_bytes;
- tx_dropped = detail.tx_dropped;
- tx_errors = detail.tx_errors;
- operstate = det.operstate;
- }
- });
- });
- if (rx_bytes && tx_bytes) {
- result = calcNetworkSpeed(ifaceName, parseInt(rx_bytes), parseInt(tx_bytes), operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
- }
- resolve(result);
- });
- });
- }
- } else {
- result.rx_bytes = _network[ifaceSanitized].rx_bytes;
- result.tx_bytes = _network[ifaceSanitized].tx_bytes;
- result.rx_sec = _network[ifaceSanitized].rx_sec;
- result.tx_sec = _network[ifaceSanitized].tx_sec;
- result.ms = _network[ifaceSanitized].last_ms;
- result.operstate = _network[ifaceSanitized].operstate;
- resolve(result);
- }
- });
- });
-}
-
-exports.networkStats = networkStats;
-
-// --------------------------
-// NET - connections (sockets)
-
-function getProcessName(processes, pid) {
- let cmd = '';
- processes.forEach(line => {
- const parts = line.split(' ');
- const id = parseInt(parts[0], 10) || -1;
- if (id === pid) {
- parts.shift();
- cmd = parts.join(' ').split(':')[0];
- }
- });
- cmd = cmd.split(' -')[0];
- cmd = cmd.split(' /')[0];
- return cmd;
- // const cmdParts = cmd.split('/');
- // return cmdParts[cmdParts.length - 1];
-}
-
-function networkConnections(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux || _freebsd || _openbsd || _netbsd) {
- let cmd = 'export LC_ALL=C; netstat -tunap | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL';
- if (_freebsd || _openbsd || _netbsd) { cmd = 'export LC_ALL=C; netstat -na | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; }
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- if (!error && (lines.length > 1 || lines[0] != '')) {
- lines.forEach(function (line) {
- line = line.replace(/ +/g, ' ').split(' ');
- if (line.length >= 7) {
- let localip = line[3];
- let localport = '';
- let localaddress = line[3].split(':');
- if (localaddress.length > 1) {
- localport = localaddress[localaddress.length - 1];
- localaddress.pop();
- localip = localaddress.join(':');
- }
- let peerip = line[4];
- let peerport = '';
- let peeraddress = line[4].split(':');
- if (peeraddress.length > 1) {
- peerport = peeraddress[peeraddress.length - 1];
- peeraddress.pop();
- peerip = peeraddress.join(':');
- }
- let connstate = line[5];
- let proc = line[6].split('/');
-
- if (connstate) {
- result.push({
- protocol: line[0],
- localAddress: localip,
- localPort: localport,
- peerAddress: peerip,
- peerPort: peerport,
- state: connstate,
- pid: proc[0] && proc[0] !== '-' ? parseInt(proc[0], 10) : null,
- process: proc[1] ? proc[1].split(' ')[0].split(':')[0] : ''
- });
- }
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else {
- cmd = 'ss -tunap | grep "ESTAB\\|SYN-SENT\\|SYN-RECV\\|FIN-WAIT1\\|FIN-WAIT2\\|TIME-WAIT\\|CLOSE\\|CLOSE-WAIT\\|LAST-ACK\\|LISTEN\\|CLOSING"';
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
-
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- line = line.replace(/ +/g, ' ').split(' ');
- if (line.length >= 6) {
- let localip = line[4];
- let localport = '';
- let localaddress = line[4].split(':');
- if (localaddress.length > 1) {
- localport = localaddress[localaddress.length - 1];
- localaddress.pop();
- localip = localaddress.join(':');
- }
- let peerip = line[5];
- let peerport = '';
- let peeraddress = line[5].split(':');
- if (peeraddress.length > 1) {
- peerport = peeraddress[peeraddress.length - 1];
- peeraddress.pop();
- peerip = peeraddress.join(':');
- }
- let connstate = line[1];
- if (connstate === 'ESTAB') { connstate = 'ESTABLISHED'; }
- if (connstate === 'TIME-WAIT') { connstate = 'TIME_WAIT'; }
- let pid = null;
- let process = '';
- if (line.length >= 7 && line[6].indexOf('users:') > -1) {
- let proc = line[6].replace('users:(("', '').replace(/"/g, '').split(',');
- if (proc.length > 2) {
- process = proc[0].split(' ')[0].split(':')[0];
- pid = parseInt(proc[1], 10);
- }
- }
- if (connstate) {
- result.push({
- protocol: line[0],
- localAddress: localip,
- localPort: localport,
- peerAddress: peerip,
- peerPort: peerport,
- state: connstate,
- pid,
- process
- });
- }
- }
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- });
- }
- if (_darwin) {
- let cmd = 'netstat -natvln | head -n2; netstat -natvln | grep "tcp4\\|tcp6\\|udp4\\|udp6"';
- const states = 'ESTABLISHED|SYN_SENT|SYN_RECV|FIN_WAIT1|FIN_WAIT_1|FIN_WAIT2|FIN_WAIT_2|TIME_WAIT|CLOSE|CLOSE_WAIT|LAST_ACK|LISTEN|CLOSING|UNKNOWN'.split('|');
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- if (!error) {
- exec('ps -axo pid,command', { maxBuffer: 1024 * 20000 }, function (err2, stdout2) {
- let processes = stdout2.toString().split('\n');
- processes = processes.map((line => { return line.trim().replace(/ +/g, ' '); }));
- let lines = stdout.toString().split('\n');
- lines.shift();
- let pidPos = 8;
- if (lines.length > 1 && lines[0].indexOf('pid') > 0) {
- const header = (lines.shift() || '').replace(/ Address/g, '_Address').replace(/ +/g, ' ').split(' ');
- pidPos = header.indexOf('pid');
- }
- lines.forEach(function (line) {
- line = line.replace(/ +/g, ' ').split(' ');
- if (line.length >= 8) {
- let localip = line[3];
- let localport = '';
- let localaddress = line[3].split('.');
- if (localaddress.length > 1) {
- localport = localaddress[localaddress.length - 1];
- localaddress.pop();
- localip = localaddress.join('.');
- }
- let peerip = line[4];
- let peerport = '';
- let peeraddress = line[4].split('.');
- if (peeraddress.length > 1) {
- peerport = peeraddress[peeraddress.length - 1];
- peeraddress.pop();
- peerip = peeraddress.join('.');
- }
- const hasState = states.indexOf(line[5]) >= 0;
- let connstate = hasState ? line[5] : 'UNKNOWN';
- let pid = parseInt(line[pidPos + (hasState ? 0 : -1)], 10);
- if (connstate) {
- result.push({
- protocol: line[0],
- localAddress: localip,
- localPort: localport,
- peerAddress: peerip,
- peerPort: peerport,
- state: connstate,
- pid: pid,
- process: getProcessName(processes, pid)
- });
- }
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
-
- }
- });
- }
- if (_windows) {
- let cmd = 'netstat -nao';
- try {
- exec(cmd, util.execOptsWin, function (error, stdout) {
- if (!error) {
-
- let lines = stdout.toString().split('\r\n');
-
- lines.forEach(function (line) {
- line = line.trim().replace(/ +/g, ' ').split(' ');
- if (line.length >= 4) {
- let localip = line[1];
- let localport = '';
- let localaddress = line[1].split(':');
- if (localaddress.length > 1) {
- localport = localaddress[localaddress.length - 1];
- localaddress.pop();
- localip = localaddress.join(':');
- }
- localip = localip.replace(/\[/g, '').replace(/\]/g, '');
- let peerip = line[2];
- let peerport = '';
- let peeraddress = line[2].split(':');
- if (peeraddress.length > 1) {
- peerport = peeraddress[peeraddress.length - 1];
- peeraddress.pop();
- peerip = peeraddress.join(':');
- }
- peerip = peerip.replace(/\[/g, '').replace(/\]/g, '');
- let pid = util.toInt(line[4]);
- let connstate = line[3];
- if (connstate === 'HERGESTELLT') { connstate = 'ESTABLISHED'; }
- if (connstate.startsWith('ABH')) { connstate = 'LISTEN'; }
- if (connstate === 'SCHLIESSEN_WARTEN') { connstate = 'CLOSE_WAIT'; }
- if (connstate === 'WARTEND') { connstate = 'TIME_WAIT'; }
- if (connstate === 'SYN_GESENDET') { connstate = 'SYN_SENT'; }
-
- if (connstate === 'LISTENING') { connstate = 'LISTEN'; }
- if (connstate === 'SYN_RECEIVED') { connstate = 'SYN_RECV'; }
- if (connstate === 'FIN_WAIT_1') { connstate = 'FIN_WAIT1'; }
- if (connstate === 'FIN_WAIT_2') { connstate = 'FIN_WAIT2'; }
- if (line[0].toLowerCase() !== 'udp' && connstate) {
- result.push({
- protocol: line[0].toLowerCase(),
- localAddress: localip,
- localPort: localport,
- peerAddress: peerip,
- peerPort: peerport,
- state: connstate,
- pid,
- process: ''
- });
- } else if (line[0].toLowerCase() === 'udp') {
- result.push({
- protocol: line[0].toLowerCase(),
- localAddress: localip,
- localPort: localport,
- peerAddress: peerip,
- peerPort: peerport,
- state: '',
- pid: parseInt(line[3], 10),
- process: ''
- });
- }
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.networkConnections = networkConnections;
-
-function networkGatewayDefault(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = '';
- if (_linux || _freebsd || _openbsd || _netbsd) {
- let cmd = 'ip route get 1';
- try {
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- const line = lines && lines[0] ? lines[0] : '';
- let parts = line.split(' via ');
- if (parts && parts[1]) {
- parts = parts[1].split(' ');
- result = parts[0];
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_darwin) {
- let cmd = 'route -n get default';
- try {
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- if (!error) {
- const lines = stdout.toString().split('\n').map(line => line.trim());
- result = util.getValue(lines, 'gateway');
- }
- if (!result) {
- cmd = 'netstat -rn | awk \'/default/ {print $2}\'';
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- const lines = stdout.toString().split('\n').map(line => line.trim());
- result = lines.find(line => (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(line)));
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_windows) {
- try {
- exec('netstat -r', util.execOptsWin, function (error, stdout) {
- const lines = stdout.toString().split(os.EOL);
- lines.forEach(line => {
- line = line.replace(/\s+/g, ' ').trim();
- if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) {
- const parts = line.split(' ');
- if (parts.length >= 5 && (parts[parts.length - 3]).indexOf('.') > -1) {
- result = parts[parts.length - 3];
- }
- }
- });
- if (!result) {
- util.powerShell('Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq \'0.0.0.0\' -and $_.Mask -eq \'0.0.0.0\' }')
- .then((data) => {
- let lines = data.toString().split('\r\n');
- if (lines.length > 1 && !result) {
- result = util.getValue(lines, 'NextHop');
- if (callback) {
- callback(result);
- }
- resolve(result);
- // } else {
- // exec('ipconfig', util.execOptsWin, function (error, stdout) {
- // let lines = stdout.toString().split('\r\n');
- // lines.forEach(function (line) {
- // line = line.trim().replace(/\. /g, '');
- // line = line.trim().replace(/ +/g, '');
- // const parts = line.split(':');
- // if ((parts[0].toLowerCase().startsWith('standardgate') || parts[0].toLowerCase().indexOf('gateway') > -1 || parts[0].toLowerCase().indexOf('enlace') > -1) && parts[1]) {
- // result = parts[1];
- // }
- // });
- // if (callback) { callback(result); }
- // resolve(result);
- // });
- }
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.networkGatewayDefault = networkGatewayDefault;
-
-
-/***/ }),
-
-/***/ 70255:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// osinfo.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 3. Operating System
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const fs = __nccwpck_require__(79896);
-const util = __nccwpck_require__(33225);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-// --------------------------
-// Get current time and OS uptime
-
-function time() {
- let t = new Date().toString().split(' ');
- const result = {
- current: Date.now(),
- uptime: os.uptime(),
- timezone: (t.length >= 7) ? t[5] : '',
- timezoneName: Intl ? Intl.DateTimeFormat().resolvedOptions().timeZone : (t.length >= 7) ? t.slice(6).join(' ').replace(/\(/g, '').replace(/\)/g, '') : ''
- };
- if (_darwin || _linux) {
- try {
- const stdout = execSync('date +%Z && date +%z && ls -l /etc/localtime 2>/dev/null', util.execOptsLinux);
- const lines = stdout.toString().split(os.EOL);
- if (lines.length > 3 && !lines[0]) {
- lines.shift();
- }
- let timezone = lines[0] || '';
- if (timezone.startsWith('+') || timezone.startsWith('-')) {
- timezone = 'GMT';
- }
- return {
- current: Date.now(),
- uptime: os.uptime(),
- timezone: lines[1] ? timezone + lines[1] : timezone,
- timezoneName: lines[2] && lines[2].indexOf('/zoneinfo/') > 0 ? (lines[2].split('/zoneinfo/')[1] || '') : ''
- };
- } catch (e) {
- util.noop();
- }
- }
- return result;
-}
-
-exports.time = time;
-
-// --------------------------
-// Get logo filename of OS distribution
-
-function getLogoFile(distro) {
- distro = distro || '';
- distro = distro.toLowerCase();
- let result = _platform;
- if (_windows) {
- result = 'windows';
- }
- else if (distro.indexOf('mac os') !== -1 || distro.indexOf('macos') !== -1) {
- result = 'apple';
- }
- else if (distro.indexOf('arch') !== -1) {
- result = 'arch';
- }
- else if (distro.indexOf('cachy') !== -1) {
- result = 'cachy';
- }
- else if (distro.indexOf('centos') !== -1) {
- result = 'centos';
- }
- else if (distro.indexOf('coreos') !== -1) {
- result = 'coreos';
- }
- else if (distro.indexOf('debian') !== -1) {
- result = 'debian';
- }
- else if (distro.indexOf('deepin') !== -1) {
- result = 'deepin';
- }
- else if (distro.indexOf('elementary') !== -1) {
- result = 'elementary';
- }
- else if (distro.indexOf('endeavour') !== -1) {
- result = 'endeavour';
- }
- else if (distro.indexOf('fedora') !== -1) {
- result = 'fedora';
- }
- else if (distro.indexOf('gentoo') !== -1) {
- result = 'gentoo';
- }
- else if (distro.indexOf('mageia') !== -1) {
- result = 'mageia';
- }
- else if (distro.indexOf('mandriva') !== -1) {
- result = 'mandriva';
- }
- else if (distro.indexOf('manjaro') !== -1) {
- result = 'manjaro';
- }
- else if (distro.indexOf('mint') !== -1) {
- result = 'mint';
- }
- else if (distro.indexOf('mx') !== -1) {
- result = 'mx';
- }
- else if (distro.indexOf('openbsd') !== -1) {
- result = 'openbsd';
- }
- else if (distro.indexOf('freebsd') !== -1) {
- result = 'freebsd';
- }
- else if (distro.indexOf('opensuse') !== -1) {
- result = 'opensuse';
- }
- else if (distro.indexOf('pclinuxos') !== -1) {
- result = 'pclinuxos';
- }
- else if (distro.indexOf('puppy') !== -1) {
- result = 'puppy';
- }
- else if (distro.indexOf('popos') !== -1) {
- result = 'popos';
- }
- else if (distro.indexOf('raspbian') !== -1) {
- result = 'raspbian';
- }
- else if (distro.indexOf('reactos') !== -1) {
- result = 'reactos';
- }
- else if (distro.indexOf('redhat') !== -1) {
- result = 'redhat';
- }
- else if (distro.indexOf('slackware') !== -1) {
- result = 'slackware';
- }
- else if (distro.indexOf('sugar') !== -1) {
- result = 'sugar';
- }
- else if (distro.indexOf('steam') !== -1) {
- result = 'steam';
- }
- else if (distro.indexOf('suse') !== -1) {
- result = 'suse';
- }
- else if (distro.indexOf('mate') !== -1) {
- result = 'ubuntu-mate';
- }
- else if (distro.indexOf('lubuntu') !== -1) {
- result = 'lubuntu';
- }
- else if (distro.indexOf('xubuntu') !== -1) {
- result = 'xubuntu';
- }
- else if (distro.indexOf('ubuntu') !== -1) {
- result = 'ubuntu';
- }
- else if (distro.indexOf('solaris') !== -1) {
- result = 'solaris';
- }
- else if (distro.indexOf('tails') !== -1) {
- result = 'tails';
- }
- else if (distro.indexOf('feren') !== -1) {
- result = 'ferenos';
- }
- else if (distro.indexOf('robolinux') !== -1) {
- result = 'robolinux';
- } else if (_linux && distro) {
- result = distro.toLowerCase().trim().replace(/\s+/g, '-');
- }
- return result;
-}
-
-// --------------------------
-// FQDN
-
-function getFQDN() {
- let fqdn = os.hostname;
- if (_linux || _darwin) {
- try {
- const stdout = execSync('hostname -f 2>/dev/null', util.execOptsLinux);
- fqdn = stdout.toString().split(os.EOL)[0];
- } catch (e) {
- util.noop();
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- try {
- const stdout = execSync('hostname 2>/dev/null');
- fqdn = stdout.toString().split(os.EOL)[0];
- } catch (e) {
- util.noop();
- }
- }
- if (_windows) {
- try {
- const stdout = execSync('echo %COMPUTERNAME%.%USERDNSDOMAIN%', util.execOptsWin);
- fqdn = stdout.toString().replace('.%USERDNSDOMAIN%', '').split(os.EOL)[0];
- } catch (e) {
- util.noop();
- }
- }
- return fqdn;
-}
-
-// --------------------------
-// OS Information
-
-function osInfo(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
-
- platform: (_platform === 'win32' ? 'Windows' : _platform),
- distro: 'unknown',
- release: 'unknown',
- codename: '',
- kernel: os.release(),
- arch: os.arch(),
- hostname: os.hostname(),
- fqdn: getFQDN(),
- codepage: '',
- logofile: '',
- serial: '',
- build: '',
- servicepack: '',
- uefi: false
- };
-
- if (_linux) {
-
- exec('cat /etc/*-release; cat /usr/lib/os-release; cat /etc/openwrt_release', function (error, stdout) {
- /**
- * @namespace
- * @property {string} DISTRIB_ID
- * @property {string} NAME
- * @property {string} DISTRIB_RELEASE
- * @property {string} VERSION_ID
- * @property {string} DISTRIB_CODENAME
- */
- let release = {};
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- if (line.indexOf('=') !== -1) {
- release[line.split('=')[0].trim().toUpperCase()] = line.split('=')[1].trim();
- }
- });
- result.distro = (release.DISTRIB_ID || release.NAME || 'unknown').replace(/"/g, '');
- result.logofile = getLogoFile(result.distro);
- let releaseVersion = (release.VERSION || '').replace(/"/g, '');
- let codename = (release.DISTRIB_CODENAME || release.VERSION_CODENAME || '').replace(/"/g, '');
- const prettyName = (release.PRETTY_NAME || '').replace(/"/g, '');
- if (prettyName.indexOf(result.distro + ' ') === 0) {
- releaseVersion = prettyName.replace(result.distro + ' ', '').trim();
- }
- if (releaseVersion.indexOf('(') >= 0) {
- codename = releaseVersion.split('(')[1].replace(/[()]/g, '').trim();
- releaseVersion = releaseVersion.split('(')[0].trim();
- }
- result.release = (releaseVersion || release.DISTRIB_RELEASE || release.VERSION_ID || 'unknown').replace(/"/g, '');
- result.codename = codename;
- result.codepage = util.getCodepage();
- result.build = (release.BUILD_ID || '').replace(/"/g, '').trim();
- isUefiLinux().then(uefi => {
- result.uefi = uefi;
- uuid().then((data) => {
- result.serial = data.os;
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- });
- });
- }
- if (_freebsd || _openbsd || _netbsd) {
-
- exec('sysctl kern.ostype kern.osrelease kern.osrevision kern.hostuuid machdep.bootmethod kern.geom.confxml', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- const distro = util.getValue(lines, 'kern.ostype');
- const logofile = getLogoFile(distro);
- const release = util.getValue(lines, 'kern.osrelease').split('-')[0];
- const serial = util.getValue(lines, 'kern.uuid');
- const bootmethod = util.getValue(lines, 'machdep.bootmethod');
- const uefiConf = stdout.toString().indexOf('efi') >= 0;
- const uefi = bootmethod ? bootmethod.toLowerCase().indexOf('uefi') >= 0 : (uefiConf ? uefiConf : null);
- result.distro = distro || result.distro;
- result.logofile = logofile || result.logofile;
- result.release = release || result.release;
- result.serial = serial || result.serial;
- result.codename = '';
- result.codepage = util.getCodepage();
- result.uefi = uefi || null;
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_darwin) {
- exec('sw_vers; sysctl kern.ostype kern.osrelease kern.osrevision kern.uuid', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- result.serial = util.getValue(lines, 'kern.uuid');
- result.distro = util.getValue(lines, 'ProductName');
- result.release = (util.getValue(lines, 'ProductVersion', ':', true, true) + ' ' + util.getValue(lines, 'ProductVersionExtra', ':', true, true)).trim();
- result.build = util.getValue(lines, 'BuildVersion');
- result.logofile = getLogoFile(result.distro);
- result.codename = 'macOS';
- result.codename = (result.release.indexOf('10.4') > -1 ? 'OS X Tiger' : result.codename);
- result.codename = (result.release.indexOf('10.5') > -1 ? 'OS X Leopard' : result.codename);
- result.codename = (result.release.indexOf('10.6') > -1 ? 'OS X Snow Leopard' : result.codename);
- result.codename = (result.release.indexOf('10.7') > -1 ? 'OS X Lion' : result.codename);
- result.codename = (result.release.indexOf('10.8') > -1 ? 'OS X Mountain Lion' : result.codename);
- result.codename = (result.release.indexOf('10.9') > -1 ? 'OS X Mavericks' : result.codename);
- result.codename = (result.release.indexOf('10.10') > -1 ? 'OS X Yosemite' : result.codename);
- result.codename = (result.release.indexOf('10.11') > -1 ? 'OS X El Capitan' : result.codename);
- result.codename = (result.release.indexOf('10.12') > -1 ? 'Sierra' : result.codename);
- result.codename = (result.release.indexOf('10.13') > -1 ? 'High Sierra' : result.codename);
- result.codename = (result.release.indexOf('10.14') > -1 ? 'Mojave' : result.codename);
- result.codename = (result.release.indexOf('10.15') > -1 ? 'Catalina' : result.codename);
- result.codename = (result.release.startsWith('11.') ? 'Big Sur' : result.codename);
- result.codename = (result.release.startsWith('12.') ? 'Monterey' : result.codename);
- result.codename = (result.release.startsWith('13.') ? 'Ventura' : result.codename);
- result.codename = (result.release.startsWith('14.') ? 'Sonoma' : result.codename);
- result.codename = (result.release.startsWith('15.') ? 'Sequoia' : result.codename);
- result.uefi = true;
- result.codepage = util.getCodepage();
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_sunos) {
- result.release = result.kernel;
- exec('uname -o', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- result.distro = lines[0];
- result.logofile = getLogoFile(result.distro);
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_windows) {
- result.logofile = getLogoFile();
- result.release = result.kernel;
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance Win32_OperatingSystem | select Caption,SerialNumber,BuildNumber,ServicePackMajorVersion,ServicePackMinorVersion | fl'));
- workload.push(util.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent'));
- workload.push(util.powerShell('Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SystemInformation]::TerminalServerSession'));
- util.promiseAll(
- workload
- ).then((data) => {
- let lines = data.results[0] ? data.results[0].toString().split('\r\n') : [''];
- result.distro = util.getValue(lines, 'Caption', ':').trim();
- result.serial = util.getValue(lines, 'SerialNumber', ':').trim();
- result.build = util.getValue(lines, 'BuildNumber', ':').trim();
- result.servicepack = util.getValue(lines, 'ServicePackMajorVersion', ':').trim() + '.' + util.getValue(lines, 'ServicePackMinorVersion', ':').trim();
- result.codepage = util.getCodepage();
- const hyperv = data.results[1] ? data.results[1].toString().toLowerCase() : '';
- result.hypervisor = hyperv.indexOf('true') !== -1;
- const term = data.results[2] ? data.results[2].toString() : '';
- result.remoteSession = (term.toString().toLowerCase().indexOf('true') >= 0);
- isUefiWindows().then(uefi => {
- result.uefi = uefi;
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.osInfo = osInfo;
-
-function isUefiLinux() {
- return new Promise((resolve) => {
- process.nextTick(() => {
- fs.stat('/sys/firmware/efi', function (err) {
- if (!err) {
- return resolve(true);
- } else {
- exec('dmesg | grep -E "EFI v"', function (error, stdout) {
- if (!error) {
- const lines = stdout.toString().split('\n');
- return resolve(lines.length > 0);
- }
- return resolve(false);
- });
- }
- });
- });
- });
-}
-
-function isUefiWindows() {
- return new Promise((resolve) => {
- process.nextTick(() => {
- try {
- exec('findstr /C:"Detected boot environment" "%windir%\\Panther\\setupact.log"', util.execOptsWin, function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n\r')[0];
- return resolve(line.toLowerCase().indexOf('efi') >= 0);
- } else {
- exec('echo %firmware_type%', util.execOptsWin, function (error, stdout) {
- if (!error) {
- const line = stdout.toString() || '';
- return resolve(line.toLowerCase().indexOf('efi') >= 0);
- } else {
- return resolve(false);
- }
- });
- }
- });
- } catch (e) {
- return resolve(false);
- }
- });
- });
-}
-
-function versions(apps, callback) {
- let versionObject = {
- kernel: os.release(),
- apache: '',
- bash: '',
- bun: '',
- deno: '',
- docker: '',
- dotnet: '',
- fish: '',
- gcc: '',
- git: '',
- grunt: '',
- gulp: '',
- java: '',
- mongodb: '',
- mysql: '',
- nginx: '',
- node: '', //process.versions.node,
- npm: '',
- openssl: '',
- perl: '',
- php: '',
- pip3: '',
- pip: '',
- pm2: '',
- postfix: '',
- postgresql: '',
- powershell: '',
- python3: '',
- python: '',
- redis: '',
- systemOpenssl: '',
- systemOpensslLib: '',
- tsc: '',
- v8: process.versions.v8,
- virtualbox: '',
- yarn: '',
- zsh: ''
- };
-
- function checkVersionParam(apps) {
- if (apps === '*') {
- return {
- versions: versionObject,
- counter: 32
- };
- }
- if (!Array.isArray(apps)) {
- apps = apps.trim().toLowerCase().replace(/,+/g, '|').replace(/ /g, '|');
- apps = apps.split('|');
- const result = {
- versions: {},
- counter: 0
- };
- apps.forEach(el => {
- if (el) {
- for (let key in versionObject) {
- if ({}.hasOwnProperty.call(versionObject, key)) {
- if (key.toLowerCase() === el.toLowerCase() && !{}.hasOwnProperty.call(result.versions, key)) {
- result.versions[key] = versionObject[key];
- if (key === 'openssl') {
- result.versions.systemOpenssl = '';
- result.versions.systemOpensslLib = '';
- }
-
- if (!result.versions[key]) { result.counter++; }
- }
- }
- }
- }
- });
- return result;
- }
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (util.isFunction(apps) && !callback) {
- callback = apps;
- apps = '*';
- } else {
- apps = apps || '*';
- if (typeof apps !== 'string') {
- if (callback) { callback({}); }
- return resolve({});
- }
- }
- const appsObj = checkVersionParam(apps);
- let totalFunctions = appsObj.counter;
-
- let functionProcessed = (function () {
- return function () {
- if (--totalFunctions === 0) {
- if (callback) {
- callback(appsObj.versions);
- }
- resolve(appsObj.versions);
- }
- };
- })();
-
- let cmd = '';
- try {
- if ({}.hasOwnProperty.call(appsObj.versions, 'openssl')) {
- appsObj.versions.openssl = process.versions.openssl;
- exec('openssl version', function (error, stdout) {
- if (!error) {
- let openssl_string = stdout.toString().split('\n')[0].trim();
- let openssl = openssl_string.split(' ');
- appsObj.versions.systemOpenssl = openssl.length > 0 ? openssl[1] : openssl[0];
- appsObj.versions.systemOpensslLib = openssl.length > 0 ? openssl[0] : 'openssl';
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'npm')) {
- exec('npm -v', function (error, stdout) {
- if (!error) {
- appsObj.versions.npm = stdout.toString().split('\n')[0];
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'pm2')) {
- cmd = 'pm2';
- if (_windows) {
- cmd += '.cmd';
- }
- exec(`${cmd} -v`, function (error, stdout) {
- if (!error) {
- let pm2 = stdout.toString().split('\n')[0].trim();
- if (!pm2.startsWith('[PM2]')) {
- appsObj.versions.pm2 = pm2;
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'yarn')) {
- exec('yarn --version', function (error, stdout) {
- if (!error) {
- appsObj.versions.yarn = stdout.toString().split('\n')[0];
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'gulp')) {
- cmd = 'gulp';
- if (_windows) {
- cmd += '.cmd';
- }
- exec(`${cmd} --version`, function (error, stdout) {
- if (!error) {
- const gulp = stdout.toString().split('\n')[0] || '';
- appsObj.versions.gulp = (gulp.toLowerCase().split('version')[1] || '').trim();
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'tsc')) {
- cmd = 'tsc';
- if (_windows) {
- cmd += '.cmd';
- }
- exec(`${cmd} --version`, function (error, stdout) {
- if (!error) {
- const tsc = stdout.toString().split('\n')[0] || '';
- appsObj.versions.tsc = (tsc.toLowerCase().split('version')[1] || '').trim();
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'grunt')) {
- cmd = 'grunt';
- if (_windows) {
- cmd += '.cmd';
- }
- exec(`${cmd} --version`, function (error, stdout) {
- if (!error) {
- const grunt = stdout.toString().split('\n')[0] || '';
- appsObj.versions.grunt = (grunt.toLowerCase().split('cli v')[1] || '').trim();
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'git')) {
- if (_darwin) {
- const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/git') || fs.existsSync('/opt/homebrew/bin/git');
- if (util.darwinXcodeExists() || gitHomebrewExists) {
- exec('git --version', function (error, stdout) {
- if (!error) {
- let git = stdout.toString().split('\n')[0] || '';
- git = (git.toLowerCase().split('version')[1] || '').trim();
- appsObj.versions.git = (git.split(' ')[0] || '').trim();
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } else {
- exec('git --version', function (error, stdout) {
- if (!error) {
- let git = stdout.toString().split('\n')[0] || '';
- git = (git.toLowerCase().split('version')[1] || '').trim();
- appsObj.versions.git = (git.split(' ')[0] || '').trim();
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'apache')) {
- exec('apachectl -v 2>&1', function (error, stdout) {
- if (!error) {
- const apache = (stdout.toString().split('\n')[0] || '').split(':');
- appsObj.versions.apache = (apache.length > 1 ? apache[1].replace('Apache', '').replace('/', '').split('(')[0].trim() : '');
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'nginx')) {
- exec('nginx -v 2>&1', function (error, stdout) {
- if (!error) {
- const nginx = stdout.toString().split('\n')[0] || '';
- appsObj.versions.nginx = (nginx.toLowerCase().split('/')[1] || '').trim();
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'mysql')) {
- exec('mysql -V', function (error, stdout) {
- if (!error) {
- let mysql = stdout.toString().split('\n')[0] || '';
- mysql = mysql.toLowerCase();
- if (mysql.indexOf(',') > -1) {
- mysql = (mysql.split(',')[0] || '').trim();
- const parts = mysql.split(' ');
- appsObj.versions.mysql = (parts[parts.length - 1] || '').trim();
- } else {
- if (mysql.indexOf(' ver ') > -1) {
- mysql = mysql.split(' ver ')[1];
- appsObj.versions.mysql = mysql.split(' ')[0];
- }
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'php')) {
- exec('php -v', function (error, stdout) {
- if (!error) {
- const php = stdout.toString().split('\n')[0] || '';
- let parts = php.split('(');
- if (parts[0].indexOf('-')) {
- parts = parts[0].split('-');
- }
- appsObj.versions.php = parts[0].replace(/[^0-9.]/g, '');
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'redis')) {
- exec('redis-server --version', function (error, stdout) {
- if (!error) {
- const redis = stdout.toString().split('\n')[0] || '';
- const parts = redis.split(' ');
- appsObj.versions.redis = util.getValue(parts, 'v', '=', true);
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'docker')) {
- exec('docker --version', function (error, stdout) {
- if (!error) {
- const docker = stdout.toString().split('\n')[0] || '';
- const parts = docker.split(' ');
- appsObj.versions.docker = parts.length > 2 && parts[2].endsWith(',') ? parts[2].slice(0, -1) : '';
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'postfix')) {
- exec('postconf -d | grep mail_version', function (error, stdout) {
- if (!error) {
- const postfix = stdout.toString().split('\n') || [];
- appsObj.versions.postfix = util.getValue(postfix, 'mail_version', '=', true);
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'mongodb')) {
- exec('mongod --version', function (error, stdout) {
- if (!error) {
- const mongodb = stdout.toString().split('\n')[0] || '';
- appsObj.versions.mongodb = (mongodb.toLowerCase().split(',')[0] || '').replace(/[^0-9.]/g, '');
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'postgresql')) {
- if (_linux) {
- exec('locate bin/postgres', function (error, stdout) {
- if (!error) {
- const postgresqlBin = stdout.toString().split('\n').sort();
- if (postgresqlBin.length) {
- exec(postgresqlBin[postgresqlBin.length - 1] + ' -V', function (error, stdout) {
- if (!error) {
- const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
- appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } else {
- exec('psql -V', function (error, stdout) {
- if (!error) {
- const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
- appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
- appsObj.versions.postgresql = appsObj.versions.postgresql.split('-')[0];
- }
- functionProcessed();
- });
- }
- });
- } else {
- if (_windows) {
- util.powerShell('Get-CimInstance Win32_Service | select caption | fl').then((stdout) => {
- let serviceSections = stdout.split(/\n\s*\n/);
- serviceSections.forEach((item) => {
- if (item.trim() !== '') {
- let lines = item.trim().split('\r\n');
- let srvCaption = util.getValue(lines, 'caption', ':', true).toLowerCase();
- if (srvCaption.indexOf('postgresql') > -1) {
- const parts = srvCaption.split(' server ');
- if (parts.length > 1) {
- appsObj.versions.postgresql = parts[1];
- }
- }
- }
- });
- functionProcessed();
- });
- } else {
- exec('postgres -V', function (error, stdout) {
- if (!error) {
- const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
- appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
- } else {
- exec('pg_config --version', function (error, stdout) {
- if (!error) {
- const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
- appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
- }
- });
- }
- functionProcessed();
- });
- }
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'perl')) {
- exec('perl -v', function (error, stdout) {
- if (!error) {
- const perl = stdout.toString().split('\n') || '';
- while (perl.length > 0 && perl[0].trim() === '') {
- perl.shift();
- }
- if (perl.length > 0) {
- appsObj.versions.perl = perl[0].split('(').pop().split(')')[0].replace('v', '');
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'python')) {
- if (_darwin) {
- try {
- const stdout = execSync('sw_vers');
- const lines = stdout.toString().split('\n');
- const osVersion = util.getValue(lines, 'ProductVersion', ':');
- const gitHomebrewExists1 = fs.existsSync('/usr/local/Cellar/python');
- const gitHomebrewExists2 = fs.existsSync('/opt/homebrew/bin/python');
- if ((util.darwinXcodeExists() && util.semverCompare('12.0.1', osVersion) < 0) || gitHomebrewExists1 || gitHomebrewExists2) {
- const cmd = gitHomebrewExists1 ? '/usr/local/Cellar/python -V 2>&1' : (gitHomebrewExists2 ? '/opt/homebrew/bin/python -V 2>&1' : 'python -V 2>&1');
- exec(cmd, function (error, stdout) {
- if (!error) {
- const python = stdout.toString().split('\n')[0] || '';
- appsObj.versions.python = python.toLowerCase().replace('python', '').trim();
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } catch (e) {
- functionProcessed();
- }
-
- } else {
- exec('python -V 2>&1', function (error, stdout) {
- if (!error) {
- const python = stdout.toString().split('\n')[0] || '';
- appsObj.versions.python = python.toLowerCase().replace('python', '').trim();
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'python3')) {
- if (_darwin) {
- const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/python3') || fs.existsSync('/opt/homebrew/bin/python3');
- if (util.darwinXcodeExists() || gitHomebrewExists) {
- exec('python3 -V 2>&1', function (error, stdout) {
- if (!error) {
- const python = stdout.toString().split('\n')[0] || '';
- appsObj.versions.python3 = python.toLowerCase().replace('python', '').trim();
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } else {
- exec('python3 -V 2>&1', function (error, stdout) {
- if (!error) {
- const python = stdout.toString().split('\n')[0] || '';
- appsObj.versions.python3 = python.toLowerCase().replace('python', '').trim();
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'pip')) {
- if (_darwin) {
- const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/pip') || fs.existsSync('/opt/homebrew/bin/pip');
- if (util.darwinXcodeExists() || gitHomebrewExists) {
- exec('pip -V 2>&1', function (error, stdout) {
- if (!error) {
- const pip = stdout.toString().split('\n')[0] || '';
- const parts = pip.split(' ');
- appsObj.versions.pip = parts.length >= 2 ? parts[1] : '';
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } else {
- exec('pip -V 2>&1', function (error, stdout) {
- if (!error) {
- const pip = stdout.toString().split('\n')[0] || '';
- const parts = pip.split(' ');
- appsObj.versions.pip = parts.length >= 2 ? parts[1] : '';
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'pip3')) {
- if (_darwin) {
- const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/pip3') || fs.existsSync('/opt/homebrew/bin/pip3');
- if (util.darwinXcodeExists() || gitHomebrewExists) {
- exec('pip3 -V 2>&1', function (error, stdout) {
- if (!error) {
- const pip = stdout.toString().split('\n')[0] || '';
- const parts = pip.split(' ');
- appsObj.versions.pip3 = parts.length >= 2 ? parts[1] : '';
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } else {
- exec('pip3 -V 2>&1', function (error, stdout) {
- if (!error) {
- const pip = stdout.toString().split('\n')[0] || '';
- const parts = pip.split(' ');
- appsObj.versions.pip3 = parts.length >= 2 ? parts[1] : '';
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'java')) {
- if (_darwin) {
- // check if any JVM is installed but avoid dialog box that Java needs to be installed
- exec('/usr/libexec/java_home -V 2>&1', function (error, stdout) {
- if (!error && stdout.toString().toLowerCase().indexOf('no java runtime') === -1) {
- // now this can be done savely
- exec('java -version 2>&1', function (error, stdout) {
- if (!error) {
- const java = stdout.toString().split('\n')[0] || '';
- const parts = java.split('"');
- appsObj.versions.java = parts.length === 3 ? parts[1].trim() : '';
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- });
- } else {
- exec('java -version 2>&1', function (error, stdout) {
- if (!error) {
- const java = stdout.toString().split('\n')[0] || '';
- const parts = java.split('"');
- appsObj.versions.java = parts.length === 3 ? parts[1].trim() : '';
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'gcc')) {
- if ((_darwin && util.darwinXcodeExists()) || !_darwin) {
- exec('gcc -dumpversion', function (error, stdout) {
- if (!error) {
- appsObj.versions.gcc = stdout.toString().split('\n')[0].trim() || '';
- }
- if (appsObj.versions.gcc.indexOf('.') > -1) {
- functionProcessed();
- } else {
- exec('gcc --version', function (error, stdout) {
- if (!error) {
- const gcc = stdout.toString().split('\n')[0].trim();
- if (gcc.indexOf('gcc') > -1 && gcc.indexOf(')') > -1) {
- const parts = gcc.split(')');
- appsObj.versions.gcc = parts[1].trim() || appsObj.versions.gcc;
- }
- }
- functionProcessed();
- });
- }
- });
- } else {
- functionProcessed();
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'virtualbox')) {
- exec(util.getVboxmanage() + ' -v 2>&1', function (error, stdout) {
- if (!error) {
- const vbox = stdout.toString().split('\n')[0] || '';
- const parts = vbox.split('r');
- appsObj.versions.virtualbox = parts[0];
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'bash')) {
- exec('bash --version', function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n')[0];
- const parts = line.split(' version ');
- if (parts.length > 1) {
- appsObj.versions.bash = parts[1].split(' ')[0].split('(')[0];
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'zsh')) {
- exec('zsh --version', function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n')[0];
- const parts = line.split('zsh ');
- if (parts.length > 1) {
- appsObj.versions.zsh = parts[1].split(' ')[0];
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'fish')) {
- exec('fish --version', function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n')[0];
- const parts = line.split(' version ');
- if (parts.length > 1) {
- appsObj.versions.fish = parts[1].split(' ')[0];
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'bun')) {
- exec('bun -v', function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n')[0].trim();
- appsObj.versions.bun = line;
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'deno')) {
- exec('deno -v', function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n')[0].trim();
- const parts = line.split(' ');
- if (parts.length > 1) {
- appsObj.versions.deno = parts[1];
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'node')) {
- exec('node -v', function (error, stdout) {
- if (!error) {
- let line = stdout.toString().split('\n')[0].trim();
- if (line.startsWith('v')) { line = line.slice(1); }
- appsObj.versions.node = line;
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'powershell')) {
- if (_windows) {
- util.powerShell('$PSVersionTable').then(stdout => {
- const lines = stdout.toString().split('\n').map(line => line.replace(/ +/g, ' ').replace(/ +/g, ':'));
- appsObj.versions.powershell = util.getValue(lines, 'psversion');
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'dotnet')) {
- if (_windows) {
- util.powerShell('gci "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP" -recurse | gp -name Version,Release -EA 0 | where { $_.PSChildName -match "^(?!S)\\p{L}"} | select PSChildName, Version, Release').then(stdout => {
- const lines = stdout.toString().split('\r\n');
- let dotnet = '';
- lines.forEach(line => {
- line = line.replace(/ +/g, ' ');
- const parts = line.split(' ');
- dotnet = dotnet || (parts[0].toLowerCase().startsWith('client') && parts.length > 2 ? parts[1].trim() : (parts[0].toLowerCase().startsWith('full') && parts.length > 2 ? parts[1].trim() : ''));
- });
- appsObj.versions.dotnet = dotnet.trim();
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- }
- } catch (e) {
- if (callback) { callback(appsObj.versions); }
- resolve(appsObj.versions);
- }
- });
- });
-}
-
-exports.versions = versions;
-
-function shell(callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (_windows) {
- resolve('cmd');
- } else {
- let result = '';
- exec('echo $SHELL', function (error, stdout) {
- if (!error) {
- result = stdout.toString().split('\n')[0];
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- });
- });
-}
-
-exports.shell = shell;
-
-function getUniqueMacAdresses() {
- let macs = [];
- try {
- const ifaces = os.networkInterfaces();
- for (let dev in ifaces) {
- if ({}.hasOwnProperty.call(ifaces, dev)) {
- ifaces[dev].forEach(function (details) {
- if (details && details.mac && details.mac !== '00:00:00:00:00:00') {
- const mac = details.mac.toLowerCase();
- if (macs.indexOf(mac) === -1) {
- macs.push(mac);
- }
- }
- });
- }
- }
- macs = macs.sort(function (a, b) {
- if (a < b) { return -1; }
- if (a > b) { return 1; }
- return 0;
- });
- } catch (e) {
- macs.push('00:00:00:00:00:00');
- }
- return macs;
-}
-
-function uuid(callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- os: '',
- hardware: '',
- macs: getUniqueMacAdresses()
- };
- let parts;
-
- if (_darwin) {
- exec('system_profiler SPHardwareDataType -json', function (error, stdout) {
- if (!error) {
- try {
- const jsonObj = JSON.parse(stdout.toString());
- if (jsonObj.SPHardwareDataType && jsonObj.SPHardwareDataType.length > 0) {
- const spHardware = jsonObj.SPHardwareDataType[0];
- result.os = spHardware.platform_UUID.toLowerCase();
- result.hardware = spHardware.serial_number;
- }
- } catch (e) {
- util.noop();
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_linux) {
- const cmd = `echo -n "os: "; cat /var/lib/dbus/machine-id 2> /dev/null ||
-cat /etc/machine-id 2> /dev/null; echo;
-echo -n "hardware: "; cat /sys/class/dmi/id/product_uuid 2> /dev/null; echo;`;
- exec(cmd, function (error, stdout) {
- const lines = stdout.toString().split('\n');
- result.os = util.getValue(lines, 'os').toLowerCase();
- result.hardware = util.getValue(lines, 'hardware').toLowerCase();
- if (!result.hardware) {
- const lines = fs.readFileSync('/proc/cpuinfo', { encoding: 'utf8' }).toString().split('\n');
- const serial = util.getValue(lines, 'serial');
- result.hardware = serial || '';
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('sysctl -i kern.hostid kern.hostuuid', function (error, stdout) {
- const lines = stdout.toString().split('\n');
- result.os = util.getValue(lines, 'kern.hostid', ':').toLowerCase();
- result.hardware = util.getValue(lines, 'kern.hostuuid', ':').toLowerCase();
- if (result.os.indexOf('unknown') >= 0) { result.os = ''; }
- if (result.hardware.indexOf('unknown') >= 0) { result.hardware = ''; }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_windows) {
- let sysdir = '%windir%\\System32';
- if (process.arch === 'ia32' && Object.prototype.hasOwnProperty.call(process.env, 'PROCESSOR_ARCHITEW6432')) {
- sysdir = '%windir%\\sysnative\\cmd.exe /c %windir%\\System32';
- }
- util.powerShell('Get-CimInstance Win32_ComputerSystemProduct | select UUID | fl').then((stdout) => {
- let lines = stdout.split('\r\n');
- result.hardware = util.getValue(lines, 'uuid', ':').toLowerCase();
- exec(`${sysdir}\\reg query "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid`, util.execOptsWin, function (error, stdout) {
- parts = stdout.toString().split('\n\r')[0].split('REG_SZ');
- result.os = parts.length > 1 ? parts[1].replace(/\r+|\n+|\s+/ig, '').toLowerCase() : '';
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- });
- }
- });
- });
-}
-
-exports.uuid = uuid;
-
-
-/***/ }),
-
-/***/ 14497:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// printers.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 15. printers
-// ----------------------------------------------------------------------------------
-
-const exec = (__nccwpck_require__(35317).exec);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-const winPrinterStatus = {
- 1: 'Other',
- 2: 'Unknown',
- 3: 'Idle',
- 4: 'Printing',
- 5: 'Warmup',
- 6: 'Stopped Printing',
- 7: 'Offline',
-};
-
-function parseLinuxCupsHeader(lines) {
- const result = {};
- if (lines && lines.length) {
- if (lines[0].indexOf(' CUPS v') > 0) {
- const parts = lines[0].split(' CUPS v');
- result.cupsVersion = parts[1];
- }
- }
- return result;
-}
-
-function parseLinuxCupsPrinter(lines) {
- const result = {};
- const printerId = util.getValue(lines, 'PrinterId', ' ');
- result.id = printerId ? parseInt(printerId, 10) : null;
- result.name = util.getValue(lines, 'Info', ' ');
- result.model = lines.length > 0 && lines[0] ? lines[0].split(' ')[0] : '';
- result.uri = util.getValue(lines, 'DeviceURI', ' ');
- result.uuid = util.getValue(lines, 'UUID', ' ');
- result.status = util.getValue(lines, 'State', ' ');
- result.local = util.getValue(lines, 'Location', ' ').toLowerCase().startsWith('local');
- result.default = null;
- result.shared = util.getValue(lines, 'Shared', ' ').toLowerCase().startsWith('yes');
-
- return result;
-}
-
-function parseLinuxLpstatPrinter(lines, id) {
- const result = {};
- result.id = id;
- result.name = util.getValue(lines, 'Description', ':', true);
- result.model = lines.length > 0 && lines[0] ? lines[0].split(' ')[0] : '';
- result.uri = null;
- result.uuid = null;
- result.status = lines.length > 0 && lines[0] ? (lines[0].indexOf(' idle') > 0 ? 'idle' : (lines[0].indexOf(' printing') > 0 ? 'printing' : 'unknown')) : null;
- result.local = util.getValue(lines, 'Location', ':', true).toLowerCase().startsWith('local');
- result.default = null;
- result.shared = util.getValue(lines, 'Shared', ' ').toLowerCase().startsWith('yes');
-
- return result;
-}
-
-function parseDarwinPrinters(printerObject, id) {
- const result = {};
- const uriParts = printerObject.uri.split('/');
- result.id = id;
- result.name = printerObject._name;
- result.model = uriParts.length ? uriParts[uriParts.length - 1] : '';
- result.uri = printerObject.uri;
- result.uuid = null;
- result.status = printerObject.status;
- result.local = printerObject.printserver === 'local';
- result.default = printerObject.default === 'yes';
- result.shared = printerObject.shared === 'yes';
-
- return result;
-}
-
-function parseWindowsPrinters(lines, id) {
- const result = {};
- const status = parseInt(util.getValue(lines, 'PrinterStatus', ':'), 10);
-
- result.id = id;
- result.name = util.getValue(lines, 'name', ':');
- result.model = util.getValue(lines, 'DriverName', ':');
- result.uri = null;
- result.uuid = null;
- result.status = winPrinterStatus[status] ? winPrinterStatus[status] : null;
- result.local = util.getValue(lines, 'Local', ':').toUpperCase() === 'TRUE';
- result.default = util.getValue(lines, 'Default', ':').toUpperCase() === 'TRUE';
- result.shared = util.getValue(lines, 'Shared', ':').toUpperCase() === 'TRUE';
-
- return result;
-}
-
-function printer(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux || _freebsd || _openbsd || _netbsd) {
- let cmd = 'cat /etc/cups/printers.conf 2>/dev/null';
- exec(cmd, function (error, stdout) {
- // printers.conf
- if (!error) {
- const parts = stdout.toString().split(' {
- if (!error) {
- const parts = stdout.toString().split(/\n\s*\n/);
- for (let i = 0; i < parts.length; i++) {
- const printer = parseWindowsPrinters(parts[i].split('\n'), i);
- if (printer.name || printer.model) {
- result.push(printer);
- }
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_sunos) {
- resolve(null);
- }
- });
- });
-}
-
-exports.printer = printer;
-
-
-/***/ }),
-
-/***/ 76340:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// processes.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 10. Processes
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const fs = __nccwpck_require__(79896);
-const path = __nccwpck_require__(16928);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-const _processes_cpu = {
- all: 0,
- all_utime: 0,
- all_stime: 0,
- list: {},
- ms: 0,
- result: {}
-};
-const _services_cpu = {
- all: 0,
- all_utime: 0,
- all_stime: 0,
- list: {},
- ms: 0,
- result: {}
-};
-const _process_cpu = {
- all: 0,
- all_utime: 0,
- all_stime: 0,
- list: {},
- ms: 0,
- result: {}
-};
-
-const _winStatusValues = {
- '0': 'unknown',
- '1': 'other',
- '2': 'ready',
- '3': 'running',
- '4': 'blocked',
- '5': 'suspended blocked',
- '6': 'suspended ready',
- '7': 'terminated',
- '8': 'stopped',
- '9': 'growing',
-};
-
-function parseTimeUnix(time) {
- let result = time;
- let parts = time.replace(/ +/g, ' ').split(' ');
- if (parts.length === 5) {
- result = parts[4] + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(parts[1].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + parts[2]).slice(-2) + ' ' + parts[3];
- }
- return result;
-}
-
-function parseElapsedTime(etime) {
- let current = new Date();
- current = new Date(current.getTime() - current.getTimezoneOffset() * 60000);
-
- const elapsed = etime.split('-');
-
- const timeIndex = elapsed.length - 1;
- const days = timeIndex > 0 ? parseInt(elapsed[timeIndex - 1]) : 0;
-
- const timeStr = elapsed[timeIndex].split(':');
- const hours = timeStr.length === 3 ? parseInt(timeStr[0] || 0) : 0;
- const mins = parseInt(timeStr[timeStr.length === 3 ? 1 : 0] || 0);
- const secs = parseInt(timeStr[timeStr.length === 3 ? 2 : 1] || 0);
- const ms = (((((days * 24 + hours) * 60) + mins) * 60 + secs) * 1000);
-
- let res = new Date(current.getTime());
- let result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19);
- try {
- res = new Date(current.getTime() - ms);
- result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19);
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-// --------------------------
-// PS - services
-// pass a comma separated string with services to check (mysql, apache, postgresql, ...)
-// this function gives an array back, if the services are running.
-
-function services(srv, callback) {
-
- // fallback - if only callback is given
- if (util.isFunction(srv) && !callback) {
- callback = srv;
- srv = '';
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (typeof srv !== 'string') {
- if (callback) { callback([]); }
- return resolve([]);
- }
-
- if (srv) {
- let srvString = '';
- try {
- srvString.__proto__.toLowerCase = util.stringToLower;
- srvString.__proto__.replace = util.stringReplace;
- srvString.__proto__.trim = util.stringTrim;
- } catch (e) {
- Object.setPrototypeOf(srvString, util.stringObj);
- }
-
- const s = util.sanitizeShellString(srv);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- srvString = srvString + s[i];
- }
- }
-
- srvString = srvString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|');
- if (srvString === '') {
- srvString = '*';
- }
- if (util.isPrototypePolluted() && srvString !== '*') {
- srvString = '------';
- }
- let srvs = srvString.split('|');
- let result = [];
- let dataSrv = [];
-
- if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
- if ((_linux || _freebsd || _openbsd || _netbsd) && srvString === '*') {
- try {
- const tmpsrv = execSync('systemctl --all --type=service --no-legend 2> /dev/null', util.execOptsLinux).toString().split('\n');
- srvs = [];
- for (const s of tmpsrv) {
- const name = s.split('.service')[0];
- if (name && s.indexOf(' not-found ') === -1) {
- srvs.push(name.trim());
- }
- }
- srvString = srvs.join('|');
- } catch (d) {
- try {
- srvString = '';
- const tmpsrv = execSync('service --status-all 2> /dev/null', util.execOptsLinux).toString().split('\n');
- for (const s of tmpsrv) {
- const parts = s.split(']');
- if (parts.length === 2) {
- srvString += (srvString !== '' ? '|' : '') + parts[1].trim();
- }
- }
- srvs = srvString.split('|');
- } catch (e) {
- try {
- const srvStr = execSync('ls /etc/init.d/ -m 2> /dev/null', util.execOptsLinux).toString().split('\n').join('');
- srvString = '';
- if (srvStr) {
- const tmpsrv = srvStr.split(',');
- for (const s of tmpsrv) {
- const name = s.trim();
- if (name) {
- srvString += (srvString !== '' ? '|' : '') + name;
- }
- }
- srvs = srvString.split('|');
- }
- } catch (f) {
- srvString = '';
- srvs = [];
- }
- }
- }
- }
- if ((_darwin) && srvString === '*') { // service enumeration not yet suported on mac OS
- if (callback) { callback(result); }
- resolve(result);
- }
- let args = (_darwin) ? ['-caxo', 'pcpu,pmem,pid,command'] : ['-axo', 'pcpu,pmem,pid,command'];
- if (srvString !== '' && srvs.length > 0) {
- util.execSafe('ps', args).then((stdout) => {
- if (stdout) {
- let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n');
- srvs.forEach(function (srv) {
- let ps;
- if (_darwin) {
- ps = lines.filter(function (e) {
- return (e.toLowerCase().indexOf(srv) !== -1);
- });
-
- } else {
- ps = lines.filter(function (e) {
- return (e.toLowerCase().indexOf(' ' + srv.toLowerCase() + ':') !== -1) || (e.toLowerCase().indexOf('/' + srv.toLowerCase()) !== -1);
- });
- }
- const pids = [];
- for (const p of ps) {
- const pid = p.trim().split(' ')[2];
- if (pid) {
- pids.push(parseInt(pid, 10));
- }
- }
- result.push({
- name: srv,
- running: ps.length > 0,
- startmode: '',
- pids: pids,
- cpu: parseFloat((ps.reduce(function (pv, cv) {
- return pv + parseFloat(cv.trim().split(' ')[0]);
- }, 0)).toFixed(2)),
- mem: parseFloat((ps.reduce(function (pv, cv) {
- return pv + parseFloat(cv.trim().split(' ')[1]);
- }, 0)).toFixed(2))
- });
- });
- if (_linux) {
- // calc process_cpu - ps is not accurate in linux!
- let cmd = 'cat /proc/stat | grep "cpu "';
- for (let i in result) {
- for (let j in result[i].pids) {
- cmd += (';cat /proc/' + result[i].pids[j] + '/stat');
- }
- }
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- let curr_processes = stdout.toString().split('\n');
-
- // first line (all - /proc/stat)
- let all = parseProcStat(curr_processes.shift());
-
- // process
- let list_new = {};
- let resultProcess = {};
- curr_processes.forEach((element) => {
- resultProcess = calcProcStatLinux(element, all, _services_cpu);
-
- if (resultProcess.pid) {
- let listPos = -1;
- for (let i in result) {
- for (let j in result[i].pids) {
- if (parseInt(result[i].pids[j]) === parseInt(resultProcess.pid)) {
- listPos = i;
- }
- }
- }
- if (listPos >= 0) {
- result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus;
- }
-
- // save new values
- list_new[resultProcess.pid] = {
- cpuu: resultProcess.cpuu,
- cpus: resultProcess.cpus,
- utime: resultProcess.utime,
- stime: resultProcess.stime,
- cutime: resultProcess.cutime,
- cstime: resultProcess.cstime
- };
- }
- });
-
- // store old values
- _services_cpu.all = all;
- _services_cpu.list = Object.assign({}, list_new);
- _services_cpu.ms = Date.now() - _services_cpu.ms;
- _services_cpu.result = Object.assign({}, result);
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- args = ['-o', 'comm'];
- util.execSafe('ps', args).then((stdout) => {
- if (stdout) {
- let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n');
- srvs.forEach(function (srv) {
- let ps = lines.filter(function (e) {
- return e.indexOf(srv) !== -1;
- });
- result.push({
- name: srv,
- running: ps.length > 0,
- startmode: '',
- cpu: 0,
- mem: 0
- });
- });
- if (callback) { callback(result); }
- resolve(result);
- } else {
- srvs.forEach(function (srv) {
- result.push({
- name: srv,
- running: false,
- startmode: '',
- cpu: 0,
- mem: 0
- });
- });
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- }
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_windows) {
- try {
- let wincommand = 'Get-CimInstance Win32_Service';
- if (srvs[0] !== '*') {
- wincommand += ' -Filter "';
- srvs.forEach((srv) => {
- wincommand += `Name='${srv}' or `;
- });
- wincommand = `${wincommand.slice(0, -4)}"`;
- }
- wincommand += ' | select Name,Caption,Started,StartMode,ProcessId | fl';
- util.powerShell(wincommand).then((stdout, error) => {
- if (!error) {
- let serviceSections = stdout.split(/\n\s*\n/);
- serviceSections.forEach((element) => {
- if (element.trim() !== '') {
- let lines = element.trim().split('\r\n');
- let srvName = util.getValue(lines, 'Name', ':', true).toLowerCase();
- let srvCaption = util.getValue(lines, 'Caption', ':', true).toLowerCase();
- let started = util.getValue(lines, 'Started', ':', true);
- let startMode = util.getValue(lines, 'StartMode', ':', true);
- let pid = util.getValue(lines, 'ProcessId', ':', true);
- if (srvString === '*' || srvs.indexOf(srvName) >= 0 || srvs.indexOf(srvCaption) >= 0) {
- result.push({
- name: srvName,
- running: (started.toLowerCase() === 'true'),
- startmode: startMode,
- pids: [pid],
- cpu: 0,
- mem: 0
- });
- dataSrv.push(srvName);
- dataSrv.push(srvCaption);
- }
- }
-
- });
-
- if (srvString !== '*') {
- let srvsMissing = srvs.filter(function (e) {
- return dataSrv.indexOf(e) === -1;
- });
- srvsMissing.forEach(function (srvName) {
- result.push({
- name: srvName,
- running: false,
- startmode: '',
- pids: [],
- cpu: 0,
- mem: 0
- });
- });
- }
- if (callback) { callback(result); }
- resolve(result);
- } else {
- srvs.forEach(function (srvName) {
- result.push({
- name: srvName,
- running: false,
- startmode: '',
- cpu: 0,
- mem: 0
- });
- });
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- } else {
- if (callback) { callback([]); }
- resolve([]);
- }
- });
- });
-}
-
-exports.services = services;
-
-function parseProcStat(line) {
- let parts = line.replace(/ +/g, ' ').split(' ');
- let user = (parts.length >= 2 ? parseInt(parts[1]) : 0);
- let nice = (parts.length >= 3 ? parseInt(parts[2]) : 0);
- let system = (parts.length >= 4 ? parseInt(parts[3]) : 0);
- let idle = (parts.length >= 5 ? parseInt(parts[4]) : 0);
- let iowait = (parts.length >= 6 ? parseInt(parts[5]) : 0);
- let irq = (parts.length >= 7 ? parseInt(parts[6]) : 0);
- let softirq = (parts.length >= 8 ? parseInt(parts[7]) : 0);
- let steal = (parts.length >= 9 ? parseInt(parts[8]) : 0);
- let guest = (parts.length >= 10 ? parseInt(parts[9]) : 0);
- let guest_nice = (parts.length >= 11 ? parseInt(parts[10]) : 0);
- return user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice;
-}
-
-function calcProcStatLinux(line, all, _cpu_old) {
- let statparts = line.replace(/ +/g, ' ').split(')');
- if (statparts.length >= 2) {
- let parts = statparts[1].split(' ');
- if (parts.length >= 16) {
- let pid = parseInt(statparts[0].split(' ')[0]);
- let utime = parseInt(parts[12]);
- let stime = parseInt(parts[13]);
- let cutime = parseInt(parts[14]);
- let cstime = parseInt(parts[15]);
-
- // calc
- let cpuu = 0;
- let cpus = 0;
- if (_cpu_old.all > 0 && _cpu_old.list[pid]) {
- cpuu = (utime + cutime - _cpu_old.list[pid].utime - _cpu_old.list[pid].cutime) / (all - _cpu_old.all) * 100; // user
- cpus = (stime + cstime - _cpu_old.list[pid].stime - _cpu_old.list[pid].cstime) / (all - _cpu_old.all) * 100; // system
- } else {
- cpuu = (utime + cutime) / (all) * 100; // user
- cpus = (stime + cstime) / (all) * 100; // system
- }
- return {
- pid: pid,
- utime: utime,
- stime: stime,
- cutime: cutime,
- cstime: cstime,
- cpuu: cpuu,
- cpus: cpus
- };
- } else {
- return {
- pid: 0,
- utime: 0,
- stime: 0,
- cutime: 0,
- cstime: 0,
- cpuu: 0,
- cpus: 0
- };
- }
- } else {
- return {
- pid: 0,
- utime: 0,
- stime: 0,
- cutime: 0,
- cstime: 0,
- cpuu: 0,
- cpus: 0
- };
- }
-}
-
-function calcProcStatWin(procStat, all, _cpu_old) {
- // calc
- let cpuu = 0;
- let cpus = 0;
- if (_cpu_old.all > 0 && _cpu_old.list[procStat.pid]) {
- cpuu = (procStat.utime - _cpu_old.list[procStat.pid].utime) / (all - _cpu_old.all) * 100; // user
- cpus = (procStat.stime - _cpu_old.list[procStat.pid].stime) / (all - _cpu_old.all) * 100; // system
- } else {
- cpuu = (procStat.utime) / (all) * 100; // user
- cpus = (procStat.stime) / (all) * 100; // system
- }
- return {
- pid: procStat.pid,
- utime: procStat.utime,
- stime: procStat.stime,
- cpuu: cpuu > 0 ? cpuu : 0,
- cpus: cpus > 0 ? cpus : 0
- };
-}
-
-
-
-// --------------------------
-// running processes
-
-function processes(callback) {
-
- let parsedhead = [];
-
- function getName(command) {
- command = command || '';
- let result = command.split(' ')[0];
- if (result.substr(-1) === ':') {
- result = result.substr(0, result.length - 1);
- }
- if (result.substr(0, 1) !== '[') {
- let parts = result.split('/');
- if (isNaN(parseInt(parts[parts.length - 1]))) {
- result = parts[parts.length - 1];
- } else {
- result = parts[0];
- }
- }
- return result;
- }
-
- function parseLine(line) {
-
- let offset = 0;
- let offset2 = 0;
-
- function checkColumn(i) {
- offset = offset2;
- if (parsedhead[i]) {
- offset2 = line.substring(parsedhead[i].to + offset, 10000).indexOf(' ');
- } else {
- offset2 = 10000;
- }
- }
-
- checkColumn(0);
- const pid = parseInt(line.substring(parsedhead[0].from + offset, parsedhead[0].to + offset2));
- checkColumn(1);
- const ppid = parseInt(line.substring(parsedhead[1].from + offset, parsedhead[1].to + offset2));
- checkColumn(2);
- const cpu = parseFloat(line.substring(parsedhead[2].from + offset, parsedhead[2].to + offset2).replace(/,/g, '.'));
- checkColumn(3);
- const mem = parseFloat(line.substring(parsedhead[3].from + offset, parsedhead[3].to + offset2).replace(/,/g, '.'));
- checkColumn(4);
- const priority = parseInt(line.substring(parsedhead[4].from + offset, parsedhead[4].to + offset2));
- checkColumn(5);
- const vsz = parseInt(line.substring(parsedhead[5].from + offset, parsedhead[5].to + offset2));
- checkColumn(6);
- const rss = parseInt(line.substring(parsedhead[6].from + offset, parsedhead[6].to + offset2));
- checkColumn(7);
- const nice = parseInt(line.substring(parsedhead[7].from + offset, parsedhead[7].to + offset2)) || 0;
- checkColumn(8);
- const started = !_sunos ? parseElapsedTime(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()) : parseTimeUnix(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim());
- checkColumn(9);
- let state = line.substring(parsedhead[9].from + offset, parsedhead[9].to + offset2).trim();
- state = (state[0] === 'R' ? 'running' : (state[0] === 'S' ? 'sleeping' : (state[0] === 'T' ? 'stopped' : (state[0] === 'W' ? 'paging' : (state[0] === 'X' ? 'dead' : (state[0] === 'Z' ? 'zombie' : ((state[0] === 'D' || state[0] === 'U') ? 'blocked' : 'unknown')))))));
- checkColumn(10);
- let tty = line.substring(parsedhead[10].from + offset, parsedhead[10].to + offset2).trim();
- if (tty === '?' || tty === '??') { tty = ''; }
- checkColumn(11);
- const user = line.substring(parsedhead[11].from + offset, parsedhead[11].to + offset2).trim();
- checkColumn(12);
- let cmdPath = '';
- let command = '';
- let params = '';
- let fullcommand = line.substring(parsedhead[12].from + offset, parsedhead[12].to + offset2).trim();
- if (fullcommand.substr(fullcommand.length - 1) === ']') { fullcommand = fullcommand.slice(0, -1); }
- if (fullcommand.substr(0, 1) === '[') { command = fullcommand.substring(1); }
- else {
- const p1 = fullcommand.indexOf('(');
- const p2 = fullcommand.indexOf(')');
- const p3 = fullcommand.indexOf('/');
- const p4 = fullcommand.indexOf(':');
- if (p1 < p2 && p1 < p3 && p3 < p2) {
- command = fullcommand.split(' ')[0];
- command = command.replace(/:/g, '');
- } else {
- if (p4 > 0 && (p3 === -1 || p3 > 3)) {
- command = fullcommand.split(' ')[0];
- command = command.replace(/:/g, '');
- } else {
- // try to figure out where parameter starts
- let firstParamPos = fullcommand.indexOf(' -');
- let firstParamPathPos = fullcommand.indexOf(' /');
- firstParamPos = (firstParamPos >= 0 ? firstParamPos : 10000);
- firstParamPathPos = (firstParamPathPos >= 0 ? firstParamPathPos : 10000);
- const firstPos = Math.min(firstParamPos, firstParamPathPos);
- let tmpCommand = fullcommand.substr(0, firstPos);
- const tmpParams = fullcommand.substr(firstPos);
- const lastSlashPos = tmpCommand.lastIndexOf('/');
- if (lastSlashPos >= 0) {
- cmdPath = tmpCommand.substr(0, lastSlashPos);
- tmpCommand = tmpCommand.substr(lastSlashPos + 1);
- }
-
- if (firstPos === 10000 && tmpCommand.indexOf(' ') > -1) {
- const parts = tmpCommand.split(' ');
- if (fs.existsSync(path.join(cmdPath, parts[0]))) {
- command = parts.shift();
- params = (parts.join(' ') + ' ' + tmpParams).trim();
- } else {
- command = tmpCommand.trim();
- params = tmpParams.trim();
- }
- } else {
- command = tmpCommand.trim();
- params = tmpParams.trim();
- }
- }
- }
-
- }
-
- return ({
- pid: pid,
- parentPid: ppid,
- name: _linux ? getName(command) : command,
- cpu: cpu,
- cpuu: 0,
- cpus: 0,
- mem: mem,
- priority: priority,
- memVsz: vsz,
- memRss: rss,
- nice: nice,
- started: started,
- state: state,
- tty: tty,
- user: user,
- command: command,
- params: params,
- path: cmdPath
- });
- }
-
- function parseProcesses(lines) {
- let result = [];
- if (lines.length > 1) {
- let head = lines[0];
- parsedhead = util.parseHead(head, 8);
- lines.shift();
- lines.forEach(function (line) {
- if (line.trim() !== '') {
- result.push(parseLine(line));
- }
- });
- }
- return result;
- }
- function parseProcesses2(lines) {
-
- function formatDateTime(time) {
- const month = ('0' + (time.getMonth() + 1).toString()).slice(-2);
- const year = time.getFullYear().toString();
- const day = ('0' + time.getDate().toString()).slice(-2);
- const hours = ('0' + time.getHours().toString()).slice(-2);
- const mins = ('0' + time.getMinutes().toString()).slice(-2);
- const secs = ('0' + time.getSeconds().toString()).slice(-2);
-
- return (year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + secs);
- }
-
- function parseElapsed(etime) {
- let started = '';
- if (etime.indexOf('d') >= 0) {
- const elapsed_parts = etime.split('d');
- started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 24 + elapsed_parts[1] * 1) * 60 * 60 * 1000));
- } else if (etime.indexOf('h') >= 0) {
- const elapsed_parts = etime.split('h');
- started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 60 + elapsed_parts[1] * 1) * 60 * 1000));
- } else if (etime.indexOf(':') >= 0) {
- const elapsed_parts = etime.split(':');
- started = formatDateTime(new Date(Date.now() - (elapsed_parts.length > 1 ? (elapsed_parts[0] * 60 + elapsed_parts[1]) * 1000 : elapsed_parts[0] * 1000)));
- }
- return started;
- }
-
- let result = [];
- lines.forEach(function (line) {
- if (line.trim() !== '') {
- line = line.trim().replace(/ +/g, ' ').replace(/,+/g, '.');
- const parts = line.split(' ');
- const command = parts.slice(9).join(' ');
- const pmem = parseFloat((1.0 * parseInt(parts[3]) * 1024 / os.totalmem()).toFixed(1));
- const started = parseElapsed(parts[5]);
-
- result.push({
- pid: parseInt(parts[0]),
- parentPid: parseInt(parts[1]),
- name: getName(command),
- cpu: 0,
- cpuu: 0,
- cpus: 0,
- mem: pmem,
- priority: 0,
- memVsz: parseInt(parts[2]),
- memRss: parseInt(parts[3]),
- nice: parseInt(parts[4]),
- started: started,
- state: (parts[6] === 'R' ? 'running' : (parts[6] === 'S' ? 'sleeping' : (parts[6] === 'T' ? 'stopped' : (parts[6] === 'W' ? 'paging' : (parts[6] === 'X' ? 'dead' : (parts[6] === 'Z' ? 'zombie' : ((parts[6] === 'D' || parts[6] === 'U') ? 'blocked' : 'unknown'))))))),
- tty: parts[7],
- user: parts[8],
- command: command
- });
- }
- });
- return result;
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
- all: 0,
- running: 0,
- blocked: 0,
- sleeping: 0,
- unknown: 0,
- list: []
- };
-
- let cmd = '';
-
- if ((_processes_cpu.ms && Date.now() - _processes_cpu.ms >= 500) || _processes_cpu.ms === 0) {
- if (_linux || _freebsd || _openbsd || _netbsd || _darwin || _sunos) {
- if (_linux) { cmd = 'export LC_ALL=C; ps -axo pid:11,ppid:11,pcpu:6,pmem:6,pri:5,vsz:11,rss:11,ni:5,etime:30,state:5,tty:15,user:20,command; unset LC_ALL'; }
- if (_freebsd || _openbsd || _netbsd) { cmd = 'export LC_ALL=C; ps -axo pid,ppid,pcpu,pmem,pri,vsz,rss,ni,etime,state,tty,user,command; unset LC_ALL'; }
- if (_darwin) { cmd = 'ps -axo pid,ppid,pcpu,pmem,pri,vsz=temp_title_1,rss=temp_title_2,nice,etime=temp_title_3,state,tty,user,command -r'; }
- if (_sunos) { cmd = 'ps -Ao pid,ppid,pcpu,pmem,pri,vsz,rss,nice,stime,s,tty,user,comm'; }
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- if (!error && stdout.toString().trim()) {
- result.list = (parseProcesses(stdout.toString().split('\n'))).slice();
- result.all = result.list.length;
- result.running = result.list.filter(function (e) {
- return e.state === 'running';
- }).length;
- result.blocked = result.list.filter(function (e) {
- return e.state === 'blocked';
- }).length;
- result.sleeping = result.list.filter(function (e) {
- return e.state === 'sleeping';
- }).length;
-
- if (_linux) {
- // calc process_cpu - ps is not accurate in linux!
- cmd = 'cat /proc/stat | grep "cpu "';
- result.list.forEach((element) => {
- cmd += (';cat /proc/' + element.pid + '/stat');
- });
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- let curr_processes = stdout.toString().split('\n');
-
- // first line (all - /proc/stat)
- let all = parseProcStat(curr_processes.shift());
-
- // process
- let list_new = {};
- let resultProcess = {};
- curr_processes.forEach((element) => {
- resultProcess = calcProcStatLinux(element, all, _processes_cpu);
-
- if (resultProcess.pid) {
-
- // store pcpu in outer array
- let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid);
- if (listPos >= 0) {
- result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus;
- result.list[listPos].cpuu = resultProcess.cpuu;
- result.list[listPos].cpus = resultProcess.cpus;
- }
-
- // save new values
- list_new[resultProcess.pid] = {
- cpuu: resultProcess.cpuu,
- cpus: resultProcess.cpus,
- utime: resultProcess.utime,
- stime: resultProcess.stime,
- cutime: resultProcess.cutime,
- cstime: resultProcess.cstime
- };
- }
- });
-
- // store old values
- _processes_cpu.all = all;
- _processes_cpu.list = Object.assign({}, list_new);
- _processes_cpu.ms = Date.now() - _processes_cpu.ms;
- _processes_cpu.result = Object.assign({}, result);
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,stat,tty,user,comm';
- if (_sunos) {
- cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,s,tty,user,comm';
- }
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.shift();
-
- result.list = parseProcesses2(lines).slice();
- result.all = result.list.length;
- result.running = result.list.filter(function (e) {
- return e.state === 'running';
- }).length;
- result.blocked = result.list.filter(function (e) {
- return e.state === 'blocked';
- }).length;
- result.sleeping = result.list.filter(function (e) {
- return e.state === 'sleeping';
- }).length;
- if (callback) { callback(result); }
- resolve(result);
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- }
- });
- } else if (_windows) {
- try {
- util.powerShell('Get-CimInstance Win32_Process | select-Object ProcessId,ParentProcessId,ExecutionState,Caption,CommandLine,ExecutablePath,UserModeTime,KernelModeTime,WorkingSetSize,Priority,PageFileUsage, @{n="CreationDate";e={$_.CreationDate.ToString("yyyy-MM-dd HH:mm:ss")}} | fl').then((stdout, error) => {
- if (!error) {
- let processSections = stdout.split(/\n\s*\n/);
- let procs = [];
- let procStats = [];
- let list_new = {};
- let allcpuu = 0;
- let allcpus = 0;
- processSections.forEach((element) => {
- if (element.trim() !== '') {
- let lines = element.trim().split('\r\n');
- let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10);
- let parentPid = parseInt(util.getValue(lines, 'ParentProcessId', ':', true), 10);
- let statusValue = util.getValue(lines, 'ExecutionState', ':');
- let name = util.getValue(lines, 'Caption', ':', true);
- let commandLine = util.getValue(lines, 'CommandLine', ':', true);
- // get additional command line data
- let additionalCommand = false;
- lines.forEach((line) => {
- if (additionalCommand && line.toLowerCase().startsWith(' ')) {
- commandLine += ' ' + line.trim();
- } else {
- additionalCommand = false;
- }
- if (line.toLowerCase().startsWith('commandline')) {
- additionalCommand = true;
- }
- });
- let commandPath = util.getValue(lines, 'ExecutablePath', ':', true);
- let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10);
- let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10);
- let memw = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10);
- allcpuu = allcpuu + utime;
- allcpus = allcpus + stime;
- result.all++;
- if (!statusValue) { result.unknown++; }
- if (statusValue === '3') { result.running++; }
- if (statusValue === '4' || statusValue === '5') { result.blocked++; }
-
- procStats.push({
- pid: pid,
- utime: utime,
- stime: stime,
- cpu: 0,
- cpuu: 0,
- cpus: 0,
- });
- procs.push({
- pid: pid,
- parentPid: parentPid,
- name: name,
- cpu: 0,
- cpuu: 0,
- cpus: 0,
- mem: memw / os.totalmem() * 100,
- priority: parseInt(util.getValue(lines, 'Priority', ':', true), 10),
- memVsz: parseInt(util.getValue(lines, 'PageFileUsage', ':', true), 10),
- memRss: Math.floor(parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10) / 1024),
- nice: 0,
- started: util.getValue(lines, 'CreationDate', ':', true),
- state: (!statusValue ? _winStatusValues[0] : _winStatusValues[statusValue]),
- tty: '',
- user: '',
- command: commandLine || name,
- path: commandPath,
- params: ''
- });
- }
- });
-
- result.sleeping = result.all - result.running - result.blocked - result.unknown;
- result.list = procs;
- procStats.forEach((element) => {
- let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _processes_cpu);
-
- // store pcpu in outer array
- let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid);
- if (listPos >= 0) {
- result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus;
- result.list[listPos].cpuu = resultProcess.cpuu;
- result.list[listPos].cpus = resultProcess.cpus;
- }
-
- // save new values
- list_new[resultProcess.pid] = {
- cpuu: resultProcess.cpuu,
- cpus: resultProcess.cpus,
- utime: resultProcess.utime,
- stime: resultProcess.stime
- };
- });
-
- // store old values
- _processes_cpu.all = allcpuu + allcpus;
- _processes_cpu.all_utime = allcpuu;
- _processes_cpu.all_stime = allcpus;
- _processes_cpu.list = Object.assign({}, list_new);
- _processes_cpu.ms = Date.now() - _processes_cpu.ms;
- _processes_cpu.result = Object.assign({}, result);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(_processes_cpu.result); }
- resolve(_processes_cpu.result);
- }
- });
- });
-}
-
-exports.processes = processes;
-
-// --------------------------
-// PS - process load
-// get detailed information about a certain process
-// (PID, CPU-Usage %, Mem-Usage %)
-
-function processLoad(proc, callback) {
-
- // fallback - if only callback is given
- if (util.isFunction(proc) && !callback) {
- callback = proc;
- proc = '';
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- proc = proc || '';
-
- if (typeof proc !== 'string') {
- if (callback) { callback([]); }
- return resolve([]);
- }
-
- let processesString = '';
- try {
- processesString.__proto__.toLowerCase = util.stringToLower;
- processesString.__proto__.replace = util.stringReplace;
- processesString.__proto__.trim = util.stringTrim;
- } catch (e) {
- Object.setPrototypeOf(processesString, util.stringObj);
- }
-
- const s = util.sanitizeShellString(proc);
- const l = util.mathMin(s.length, 2000);
-
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- processesString = processesString + s[i];
- }
- }
-
- processesString = processesString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|');
- if (processesString === '') {
- processesString = '*';
- }
- if (util.isPrototypePolluted() && processesString !== '*') {
- processesString = '------';
- }
- let processes = processesString.split('|');
- let result = [];
-
- const procSanitized = util.isPrototypePolluted() ? '' : (util.sanitizeShellString(proc) || '*');
-
- // from here new
- // let result = {
- // 'proc': procSanitized,
- // 'pid': null,
- // 'cpu': 0,
- // 'mem': 0
- // };
- if (procSanitized && processes.length && processes[0] !== '------') {
- if (_windows) {
- try {
- util.powerShell('Get-CimInstance Win32_Process | select ProcessId,Caption,UserModeTime,KernelModeTime,WorkingSetSize | fl').then((stdout, error) => {
- if (!error) {
- let processSections = stdout.split(/\n\s*\n/);
- let procStats = [];
- let list_new = {};
- let allcpuu = 0;
- let allcpus = 0;
-
- // go through all processes
- processSections.forEach((element) => {
- if (element.trim() !== '') {
- let lines = element.trim().split('\r\n');
- let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10);
- let name = util.getValue(lines, 'Caption', ':', true);
- let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10);
- let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10);
- let mem = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10);
- allcpuu = allcpuu + utime;
- allcpus = allcpus + stime;
-
- procStats.push({
- pid: pid,
- name,
- utime: utime,
- stime: stime,
- cpu: 0,
- cpuu: 0,
- cpus: 0,
- mem
- });
- let pname = '';
- let inList = false;
- processes.forEach(function (proc) {
- if (name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) {
- inList = true;
- pname = proc;
- }
- });
-
- if (processesString === '*' || inList) {
- let processFound = false;
- result.forEach(function (item) {
- if (item.proc.toLowerCase() === pname.toLowerCase()) {
- item.pids.push(pid);
- item.mem += mem / os.totalmem() * 100;
- processFound = true;
- }
- });
- if (!processFound) {
- result.push({
- proc: pname,
- pid: pid,
- pids: [pid],
- cpu: 0,
- mem: mem / os.totalmem() * 100
- });
- }
- }
- }
- });
-
- // add missing processes
- if (processesString !== '*') {
- let processesMissing = processes.filter(function (name) {
- return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0;
-
- });
- processesMissing.forEach(function (procName) {
- result.push({
- proc: procName,
- pid: null,
- pids: [],
- cpu: 0,
- mem: 0
- });
- });
- }
-
- // calculate proc stats for each proc
- procStats.forEach((element) => {
- let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _process_cpu);
-
- let listPos = -1;
- for (let j = 0; j < result.length; j++) {
- if (result[j].pid === resultProcess.pid || result[j].pids.indexOf(resultProcess.pid) >= 0) { listPos = j; }
- }
- if (listPos >= 0) {
- result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus;
- }
-
- // save new values
- list_new[resultProcess.pid] = {
- cpuu: resultProcess.cpuu,
- cpus: resultProcess.cpus,
- utime: resultProcess.utime,
- stime: resultProcess.stime
- };
- });
-
- // store old values
- _process_cpu.all = allcpuu + allcpus;
- _process_cpu.all_utime = allcpuu;
- _process_cpu.all_stime = allcpus;
- _process_cpu.list = Object.assign({}, list_new);
- _process_cpu.ms = Date.now() - _process_cpu.ms;
- _process_cpu.result = JSON.parse(JSON.stringify(result));
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
-
- if (_darwin || _linux || _freebsd || _openbsd || _netbsd) {
- const params = ['-axo', 'pid,ppid,pcpu,pmem,comm'];
- util.execSafe('ps', params).then((stdout) => {
- if (stdout) {
- let procStats = [];
- let lines = stdout.toString().split('\n').filter(function (line) {
- if (processesString === '*') { return true; }
- if (line.toLowerCase().indexOf('grep') !== -1) { return false; } // remove this??
- let found = false;
- processes.forEach(function (item) {
- found = found || (line.toLowerCase().indexOf(item.toLowerCase()) >= 0);
- });
- return found;
- });
- lines.shift();
- lines.forEach(function (line) {
- let data = line.trim().replace(/ +/g, ' ').split(' ');
- if (data.length > 4) {
- const linuxName = data[4].indexOf('/') >= 0 ? data[4].substring(0, data[4].indexOf('/')) : data[4];
- const name = _linux ? (linuxName) : data[4].substring(data[4].lastIndexOf('/') + 1);
- procStats.push({
- name,
- pid: parseInt(data[0]) || 0,
- ppid: parseInt(data[1]) || 0,
- cpu: parseFloat(data[2].replace(',', '.')),
- mem: parseFloat(data[3].replace(',', '.'))
- });
- }
- });
-
- procStats.forEach(function (item) {
- let listPos = -1;
- let inList = false;
- let name = item.name;
- for (let j = 0; j < result.length; j++) {
- if (item.name.toLowerCase().indexOf(result[j].proc.toLowerCase()) >= 0) {
- listPos = j;
- }
- }
- processes.forEach(function (proc) {
-
- if (item.name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) {
- inList = true;
- name = proc;
- }
- });
- if ((processesString === '*') || inList) {
- if (listPos < 0) {
- if (name) {
- result.push({
- proc: name,
- pid: item.pid,
- pids: [item.pid],
- cpu: item.cpu,
- mem: item.mem
- });
- }
- } else {
- if (item.ppid < 10) {
- result[listPos].pid = item.pid;
- }
- result[listPos].pids.push(item.pid);
- result[listPos].cpu += item.cpu;
- result[listPos].mem += item.mem;
- }
- }
- });
-
- if (processesString !== '*') {
- // add missing processes
- let processesMissing = processes.filter(function (name) {
- return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0;
- });
- processesMissing.forEach(function (procName) {
- result.push({
- proc: procName,
- pid: null,
- pids: [],
- cpu: 0,
- mem: 0
- });
- });
- }
- if (_linux) {
- // calc process_cpu - ps is not accurate in linux!
- result.forEach(function (item) {
- item.cpu = 0;
- });
- let cmd = 'cat /proc/stat | grep "cpu "';
- for (let i in result) {
- for (let j in result[i].pids) {
- cmd += (';cat /proc/' + result[i].pids[j] + '/stat');
- }
- }
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- let curr_processes = stdout.toString().split('\n');
-
- // first line (all - /proc/stat)
- let all = parseProcStat(curr_processes.shift());
-
- // process
- let list_new = {};
- let resultProcess = {};
- curr_processes.forEach((element) => {
- resultProcess = calcProcStatLinux(element, all, _process_cpu);
-
- if (resultProcess.pid) {
-
- // find result item
- let resultItemId = -1;
- for (let i in result) {
- if (result[i].pids.indexOf(resultProcess.pid) >= 0) {
- resultItemId = i;
- }
- }
- // store pcpu in outer result
- if (resultItemId >= 0) {
- result[resultItemId].cpu += resultProcess.cpuu + resultProcess.cpus;
- }
-
- // save new values
- list_new[resultProcess.pid] = {
- cpuu: resultProcess.cpuu,
- cpus: resultProcess.cpus,
- utime: resultProcess.utime,
- stime: resultProcess.stime,
- cutime: resultProcess.cutime,
- cstime: resultProcess.cstime
- };
- }
- });
-
- result.forEach(function (item) {
- item.cpu = Math.round(item.cpu * 100) / 100;
- });
-
- _process_cpu.all = all;
- _process_cpu.list = Object.assign({}, list_new);
- _process_cpu.ms = Date.now() - _process_cpu.ms;
- _process_cpu.result = Object.assign({}, result);
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- }
- }
- });
- });
-}
-
-exports.processLoad = processLoad;
-
-
-/***/ }),
-
-/***/ 50936:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// system.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 2. System (Hardware, BIOS, Base Board)
-// ----------------------------------------------------------------------------------
-
-const fs = __nccwpck_require__(79896);
-const os = __nccwpck_require__(70857);
-const util = __nccwpck_require__(33225);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const execPromise = util.promisify((__nccwpck_require__(35317).exec));
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-function system(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- manufacturer: '',
- model: 'Computer',
- version: '',
- serial: '-',
- uuid: '-',
- sku: '-',
- virtual: false
- };
-
- if (_linux || _freebsd || _openbsd || _netbsd) {
- exec('export LC_ALL=C; dmidecode -t system 2>/dev/null; unset LC_ALL', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- result.manufacturer = util.getValue(lines, 'manufacturer');
- result.model = util.getValue(lines, 'product name');
- result.version = cleanDefaults(util.getValue(lines, 'version'));
- result.serial = cleanDefaults(util.getValue(lines, 'serial number'));
- result.uuid = cleanDefaults((util.getValue(lines, 'uuid').toLowerCase()));
- result.sku = cleanDefaults(util.getValue(lines, 'sku number'));
- // Non-Root values
- const cmd = `echo -n "product_name: "; cat /sys/devices/virtual/dmi/id/product_name 2>/dev/null; echo;
- echo -n "product_serial: "; cat /sys/devices/virtual/dmi/id/product_serial 2>/dev/null; echo;
- echo -n "product_uuid: "; cat /sys/devices/virtual/dmi/id/product_uuid 2>/dev/null; echo;
- echo -n "product_version: "; cat /sys/devices/virtual/dmi/id/product_version 2>/dev/null; echo;
- echo -n "sys_vendor: "; cat /sys/devices/virtual/dmi/id/sys_vendor 2>/dev/null; echo;`;
- try {
- lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- result.manufacturer = result.manufacturer === '' ? util.getValue(lines, 'sys_vendor') : result.manufacturer;
- result.model = result.model === '' ? util.getValue(lines, 'product_name') : result.model;
- result.version = cleanDefaults(result.version === '' ? util.getValue(lines, 'product_version') : result.version);
- result.serial = cleanDefaults(result.serial === '' ? util.getValue(lines, 'product_serial') : result.serial);
- result.uuid = cleanDefaults(result.uuid === '' ? util.getValue(lines, 'product_uuid').toLowerCase() : result.uuid);
- } catch (e) {
- util.noop();
- }
- if (!result.serial) { result.serial = '-'; }
- if (!result.manufacturer) { result.manufacturer = ''; }
- if (!result.model) { result.model = 'Computer'; }
- if (!result.version) { result.version = ''; }
- if (!result.sku) { result.sku = '-'; }
-
- // detect virtual (1)
- if (result.model.toLowerCase() === 'virtualbox' || result.model.toLowerCase() === 'kvm' || result.model.toLowerCase() === 'virtual machine' || result.model.toLowerCase() === 'bochs' || result.model.toLowerCase().startsWith('vmware') || result.model.toLowerCase().startsWith('droplet')) {
- result.virtual = true;
- switch (result.model.toLowerCase()) {
- case 'virtualbox':
- result.virtualHost = 'VirtualBox';
- break;
- case 'vmware':
- result.virtualHost = 'VMware';
- break;
- case 'kvm':
- result.virtualHost = 'KVM';
- break;
- case 'bochs':
- result.virtualHost = 'bochs';
- break;
- }
- }
- if (result.manufacturer.toLowerCase().startsWith('vmware') || result.manufacturer.toLowerCase() === 'xen') {
- result.virtual = true;
- switch (result.manufacturer.toLowerCase()) {
- case 'vmware':
- result.virtualHost = 'VMware';
- break;
- case 'xen':
- result.virtualHost = 'Xen';
- break;
- }
- }
- if (!result.virtual) {
- try {
- const disksById = execSync('ls -1 /dev/disk/by-id/ 2>/dev/null', util.execOptsLinux).toString();
- if (disksById.indexOf('_QEMU_') >= 0) {
- result.virtual = true;
- result.virtualHost = 'QEMU';
- }
- if (disksById.indexOf('_VBOX_') >= 0) {
- result.virtual = true;
- result.virtualHost = 'VirtualBox';
- }
- } catch (e) {
- util.noop();
- }
- }
- if (!result.virtual && (os.release().toLowerCase().indexOf('microsoft') >= 0 || os.release().toLowerCase().endsWith('wsl2'))) {
- const kernelVersion = parseFloat(os.release().toLowerCase());
- result.virtual = true;
- result.manufacturer = 'Microsoft';
- result.model = 'WSL';
- result.version = kernelVersion < 4.19 ? '1' : '2';
- }
- if ((_freebsd || _openbsd || _netbsd) && !result.virtualHost) {
- try {
- const procInfo = execSync('dmidecode -t 4', util.execOptsLinux);
- const procLines = procInfo.toString().split('\n');
- const procManufacturer = util.getValue(procLines, 'manufacturer', ':', true);
- switch (procManufacturer.toLowerCase()) {
- case 'virtualbox':
- result.virtualHost = 'VirtualBox';
- break;
- case 'vmware':
- result.virtualHost = 'VMware';
- break;
- case 'kvm':
- result.virtualHost = 'KVM';
- break;
- case 'bochs':
- result.virtualHost = 'bochs';
- break;
- }
- } catch (e) {
- util.noop();
- }
- }
- // detect docker
- if (fs.existsSync('/.dockerenv') || fs.existsSync('/.dockerinit')) {
- result.model = 'Docker Container';
- }
- try {
- const stdout = execSync('dmesg 2>/dev/null | grep -iE "virtual|hypervisor" | grep -iE "vmware|qemu|kvm|xen" | grep -viE "Nested Virtualization|/virtual/"');
- // detect virtual machines
- let lines = stdout.toString().split('\n');
- if (lines.length > 0) {
- if (result.model === 'Computer') { result.model = 'Virtual machine'; }
- result.virtual = true;
- if (stdout.toString().toLowerCase().indexOf('vmware') >= 0 && !result.virtualHost) {
- result.virtualHost = 'VMware';
- }
- if (stdout.toString().toLowerCase().indexOf('qemu') >= 0 && !result.virtualHost) {
- result.virtualHost = 'QEMU';
- }
- if (stdout.toString().toLowerCase().indexOf('xen') >= 0 && !result.virtualHost) {
- result.virtualHost = 'Xen';
- }
- if (stdout.toString().toLowerCase().indexOf('kvm') >= 0 && !result.virtualHost) {
- result.virtualHost = 'KVM';
- }
- }
- } catch (e) {
- util.noop();
- }
-
- if (result.manufacturer === '' && result.model === 'Computer' && result.version === '') {
- // Check Raspberry Pi
- fs.readFile('/proc/cpuinfo', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result.model = util.getValue(lines, 'hardware', ':', true).toUpperCase();
- result.version = util.getValue(lines, 'revision', ':', true).toLowerCase();
- result.serial = util.getValue(lines, 'serial', ':', true);
- const model = util.getValue(lines, 'model:', ':', true);
- // reference values: https://elinux.org/RPi_HardwareHistory
- // https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
- if ((result.model === 'BCM2835' || result.model === 'BCM2708' || result.model === 'BCM2709' || result.model === 'BCM2710' || result.model === 'BCM2711' || result.model === 'BCM2836' || result.model === 'BCM2837') && model.toLowerCase().indexOf('raspberry') >= 0) {
- const rPIRevision = util.decodePiCpuinfo(lines);
- result.model = rPIRevision.model;
- result.version = rPIRevision.revisionCode;
- result.manufacturer = 'Raspberry Pi Foundation';
- result.raspberry = {
- manufacturer: rPIRevision.manufacturer,
- processor: rPIRevision.processor,
- type: rPIRevision.type,
- revision: rPIRevision.revision
- };
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- }
- if (_darwin) {
- exec('ioreg -c IOPlatformExpertDevice -d 2', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().replace(/[<>"]/g, '').split('\n');
-
- const model = util.getAppleModel(util.getValue(lines, 'model', '=', true));
- // const modelParts = util.splitByNumber(model);
- // const version = util.getValue(lines, 'version', '=', true);
- result.manufacturer = util.getValue(lines, 'manufacturer', '=', true);
- result.model = model.key;
- result.type = macOsChassisType(model.model);
- result.version = model.version;
- result.serial = util.getValue(lines, 'ioplatformserialnumber', '=', true);
- result.uuid = util.getValue(lines, 'ioplatformuuid', '=', true).toLowerCase();
- result.sku = util.getValue(lines, 'board-id', '=', true) || util.getValue(lines, 'target-sub-type', '=', true);
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- util.powerShell('Get-CimInstance Win32_ComputerSystemProduct | select Name,Vendor,Version,IdentifyingNumber,UUID | fl').then((stdout, error) => {
- if (!error) {
- let lines = stdout.split('\r\n');
- result.manufacturer = util.getValue(lines, 'vendor', ':');
- result.model = util.getValue(lines, 'name', ':');
- result.version = util.getValue(lines, 'version', ':');
- result.serial = util.getValue(lines, 'identifyingnumber', ':');
- result.uuid = util.getValue(lines, 'uuid', ':').toLowerCase();
- // detect virtual (1)
- const model = result.model.toLowerCase();
- if (model === 'virtualbox' || model === 'kvm' || model === 'virtual machine' || model === 'bochs' || model.startsWith('vmware') || model.startsWith('qemu') || model.startsWith('parallels')) {
- result.virtual = true;
- if (model.startsWith('virtualbox')) { result.virtualHost = 'VirtualBox'; }
- if (model.startsWith('vmware')) { result.virtualHost = 'VMware'; }
- if (model.startsWith('kvm')) { result.virtualHost = 'KVM'; }
- if (model.startsWith('bochs')) { result.virtualHost = 'bochs'; }
- if (model.startsWith('qemu')) { result.virtualHost = 'KVM'; }
- if (model.startsWith('parallels')) { result.virtualHost = 'Parallels'; }
- }
- const manufacturer = result.manufacturer.toLowerCase();
- if (manufacturer.startsWith('vmware') || manufacturer.startsWith('qemu') || manufacturer === 'xen' || manufacturer.startsWith('parallels')) {
- result.virtual = true;
- if (manufacturer.startsWith('vmware')) { result.virtualHost = 'VMware'; }
- if (manufacturer.startsWith('xen')) { result.virtualHost = 'Xen'; }
- if (manufacturer.startsWith('qemu')) { result.virtualHost = 'KVM'; }
- if (manufacturer.startsWith('parallels')) { result.virtualHost = 'Parallels'; }
- }
- util.powerShell('Get-CimInstance MS_Systeminformation -Namespace "root/wmi" | select systemsku | fl ').then((stdout, error) => {
- if (!error) {
- let lines = stdout.split('\r\n');
- result.sku = util.getValue(lines, 'systemsku', ':');
- }
- if (!result.virtual) {
- util.powerShell('Get-CimInstance Win32_bios | select Version, SerialNumber, SMBIOSBIOSVersion').then((stdout, error) => {
- if (!error) {
- let lines = stdout.toString();
- if (lines.indexOf('VRTUAL') >= 0 || lines.indexOf('A M I ') >= 0 || lines.indexOf('VirtualBox') >= 0 || lines.indexOf('VMWare') >= 0 || lines.indexOf('Xen') >= 0 || lines.indexOf('Parallels') >= 0) {
- result.virtual = true;
- if (lines.indexOf('VirtualBox') >= 0 && !result.virtualHost) {
- result.virtualHost = 'VirtualBox';
- }
- if (lines.indexOf('VMware') >= 0 && !result.virtualHost) {
- result.virtualHost = 'VMware';
- }
- if (lines.indexOf('Xen') >= 0 && !result.virtualHost) {
- result.virtualHost = 'Xen';
- }
- if (lines.indexOf('VRTUAL') >= 0 && !result.virtualHost) {
- result.virtualHost = 'Hyper-V';
- }
- if (lines.indexOf('A M I') >= 0 && !result.virtualHost) {
- result.virtualHost = 'Virtual PC';
- }
- if (lines.indexOf('Parallels') >= 0 && !result.virtualHost) {
- result.virtualHost = 'Parallels';
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.system = system;
-
-function cleanDefaults(s) {
- const cmpStr = s.toLowerCase();
- if (cmpStr.indexOf('o.e.m.') === -1 && cmpStr.indexOf('default string') === -1 && cmpStr !== 'default') {
- return s || '';
- }
- return '';
-}
-function bios(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- vendor: '',
- version: '',
- releaseDate: '',
- revision: '',
- };
- let cmd = '';
- if (_linux || _freebsd || _openbsd || _netbsd) {
- if (process.arch === 'arm') {
- cmd = 'cat /proc/cpuinfo | grep Serial';
- } else {
- cmd = 'export LC_ALL=C; dmidecode -t bios 2>/dev/null; unset LC_ALL';
- }
- exec(cmd, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- result.vendor = util.getValue(lines, 'Vendor');
- result.version = util.getValue(lines, 'Version');
- let datetime = util.getValue(lines, 'Release Date');
- result.releaseDate = util.parseDateTime(datetime).date;
- result.revision = util.getValue(lines, 'BIOS Revision');
- result.serial = util.getValue(lines, 'SerialNumber');
- let language = util.getValue(lines, 'Currently Installed Language').split('|')[0];
- if (language) {
- result.language = language;
- }
- if (lines.length && stdout.toString().indexOf('Characteristics:') >= 0) {
- const features = [];
- lines.forEach(line => {
- if (line.indexOf(' is supported') >= 0) {
- const feature = line.split(' is supported')[0].trim();
- features.push(feature);
- }
- });
- result.features = features;
- }
- // Non-Root values
- const cmd = `echo -n "bios_date: "; cat /sys/devices/virtual/dmi/id/bios_date 2>/dev/null; echo;
- echo -n "bios_vendor: "; cat /sys/devices/virtual/dmi/id/bios_vendor 2>/dev/null; echo;
- echo -n "bios_version: "; cat /sys/devices/virtual/dmi/id/bios_version 2>/dev/null; echo;`;
- try {
- lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- result.vendor = !result.vendor ? util.getValue(lines, 'bios_vendor') : result.vendor;
- result.version = !result.version ? util.getValue(lines, 'bios_version') : result.version;
- datetime = util.getValue(lines, 'bios_date');
- result.releaseDate = !result.releaseDate ? util.parseDateTime(datetime).date : result.releaseDate;
- } catch (e) {
- util.noop();
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- result.vendor = 'Apple Inc.';
- exec(
- 'system_profiler SPHardwareDataType -json', function (error, stdout) {
- try {
- const hardwareData = JSON.parse(stdout.toString());
- if (hardwareData && hardwareData.SPHardwareDataType && hardwareData.SPHardwareDataType.length) {
- let bootRomVersion = hardwareData.SPHardwareDataType[0].boot_rom_version;
- bootRomVersion = bootRomVersion ? bootRomVersion.split('(')[0].trim() : null;
- result.version = bootRomVersion;
- }
- } catch (e) {
- util.noop();
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- result.vendor = 'Sun Microsystems';
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- util.powerShell('Get-CimInstance Win32_bios | select Description,Version,Manufacturer,@{n="ReleaseDate";e={$_.ReleaseDate.ToString("yyyy-MM-dd")}},BuildNumber,SerialNumber,SMBIOSBIOSVersion | fl').then((stdout, error) => {
- if (!error) {
- let lines = stdout.toString().split('\r\n');
- const description = util.getValue(lines, 'description', ':');
- const version = util.getValue(lines, 'SMBIOSBIOSVersion', ':');
- if (description.indexOf(' Version ') !== -1) {
- // ... Phoenix ROM BIOS PLUS Version 1.10 A04
- result.vendor = description.split(' Version ')[0].trim();
- result.version = description.split(' Version ')[1].trim();
- } else if (description.indexOf(' Ver: ') !== -1) {
- // ... BIOS Date: 06/27/16 17:50:16 Ver: 1.4.5
- result.vendor = util.getValue(lines, 'manufacturer', ':');
- result.version = description.split(' Ver: ')[1].trim();
- } else {
- result.vendor = util.getValue(lines, 'manufacturer', ':');
- result.version = version || util.getValue(lines, 'version', ':');
- }
- result.releaseDate = util.getValue(lines, 'releasedate', ':');
- result.revision = util.getValue(lines, 'buildnumber', ':');
- result.serial = cleanDefaults(util.getValue(lines, 'serialnumber', ':'));
- }
-
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.bios = bios;
-
-function baseboard(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- manufacturer: '',
- model: '',
- version: '',
- serial: '-',
- assetTag: '-',
- memMax: null,
- memSlots: null
- };
- let cmd = '';
- if (_linux || _freebsd || _openbsd || _netbsd) {
- if (process.arch === 'arm') {
- cmd = 'cat /proc/cpuinfo | grep Serial';
- // 'BCM2709', 'BCM2835', 'BCM2708' -->
- } else {
- cmd = 'export LC_ALL=C; dmidecode -t 2 2>/dev/null; unset LC_ALL';
- }
- const workload = [];
- workload.push(execPromise(cmd));
- workload.push(execPromise('export LC_ALL=C; dmidecode -t memory 2>/dev/null'));
- util.promiseAll(
- workload
- ).then((data) => {
- let lines = data.results[0] ? data.results[0].toString().split('\n') : [''];
- result.manufacturer = cleanDefaults(util.getValue(lines, 'Manufacturer'));
- result.model = cleanDefaults(util.getValue(lines, 'Product Name'));
- result.version = cleanDefaults(util.getValue(lines, 'Version'));
- result.serial = cleanDefaults(util.getValue(lines, 'Serial Number'));
- result.assetTag = cleanDefaults(util.getValue(lines, 'Asset Tag'));
- // Non-Root values
- const cmd = `echo -n "board_asset_tag: "; cat /sys/devices/virtual/dmi/id/board_asset_tag 2>/dev/null; echo;
- echo -n "board_name: "; cat /sys/devices/virtual/dmi/id/board_name 2>/dev/null; echo;
- echo -n "board_serial: "; cat /sys/devices/virtual/dmi/id/board_serial 2>/dev/null; echo;
- echo -n "board_vendor: "; cat /sys/devices/virtual/dmi/id/board_vendor 2>/dev/null; echo;
- echo -n "board_version: "; cat /sys/devices/virtual/dmi/id/board_version 2>/dev/null; echo;`;
- try {
- lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- result.manufacturer = cleanDefaults(!result.manufacturer ? util.getValue(lines, 'board_vendor') : result.manufacturer);
- result.model = cleanDefaults(!result.model ? util.getValue(lines, 'board_name') : result.model);
- result.version = cleanDefaults(!result.version ? util.getValue(lines, 'board_version') : result.version);
- result.serial = cleanDefaults(!result.serial ? util.getValue(lines, 'board_serial') : result.serial);
- result.assetTag = cleanDefaults(!result.assetTag ? util.getValue(lines, 'board_asset_tag') : result.assetTag);
- } catch (e) {
- util.noop();
- }
-
- // mem
- lines = data.results[1] ? data.results[1].toString().split('\n') : [''];
- result.memMax = util.toInt(util.getValue(lines, 'Maximum Capacity')) * 1024 * 1024 * 1024 || null;
- result.memSlots = util.toInt(util.getValue(lines, 'Number Of Devices')) || null;
-
- // raspberry
- let linesRpi = '';
- try {
- linesRpi = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
- } catch (e) {
- util.noop();
- }
- if (linesRpi) {
- const hardware = util.getValue(linesRpi, 'hardware');
- if (hardware.startsWith('BCM')) {
- const rpi = util.decodePiCpuinfo(linesRpi);
- result.manufacturer = rpi.manufacturer;
- result.model = 'Raspberry Pi';
- result.serial = rpi.serial;
- result.version = rpi.type + ' - ' + rpi.revision;
- result.memMax = os.totalmem();
- result.memSlots = 0;
- }
- }
-
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- const workload = [];
- workload.push(execPromise('ioreg -c IOPlatformExpertDevice -d 2'));
- workload.push(execPromise('system_profiler SPMemoryDataType'));
- util.promiseAll(
- workload
- ).then((data) => {
- let lines = data.results[0] ? data.results[0].toString().replace(/[<>"]/g, '').split('\n') : [''];
- result.manufacturer = util.getValue(lines, 'manufacturer', '=', true);
- result.model = util.getValue(lines, 'model', '=', true);
- result.version = util.getValue(lines, 'version', '=', true);
- result.serial = util.getValue(lines, 'ioplatformserialnumber', '=', true);
- result.assetTag = util.getValue(lines, 'board-id', '=', true);
-
- // mem
- let devices = data.results[1] ? data.results[1].toString().split(' BANK ') : [''];
- if (devices.length === 1) {
- devices = data.results[1] ? data.results[1].toString().split(' DIMM') : [''];
- }
- devices.shift();
- result.memSlots = devices.length;
-
- if (os.arch() === 'arm64') {
- result.memSlots = 0;
- result.memMax = os.totalmem();
- }
-
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- const workload = [];
- const win10plus = parseInt(os.release()) >= 10;
- const maxCapacityAttribute = win10plus ? 'MaxCapacityEx' : 'MaxCapacity';
- workload.push(util.powerShell('Get-CimInstance Win32_baseboard | select Model,Manufacturer,Product,Version,SerialNumber,PartNumber,SKU | fl'));
- workload.push(util.powerShell(`Get-CimInstance Win32_physicalmemoryarray | select ${maxCapacityAttribute}, MemoryDevices | fl`));
- util.promiseAll(
- workload
- ).then((data) => {
- let lines = data.results[0] ? data.results[0].toString().split('\r\n') : [''];
-
- result.manufacturer = cleanDefaults(util.getValue(lines, 'manufacturer', ':'));
- result.model = cleanDefaults(util.getValue(lines, 'model', ':'));
- if (!result.model) {
- result.model = cleanDefaults(util.getValue(lines, 'product', ':'));
- }
- result.version = cleanDefaults(util.getValue(lines, 'version', ':'));
- result.serial = cleanDefaults(util.getValue(lines, 'serialnumber', ':'));
- result.assetTag = cleanDefaults(util.getValue(lines, 'partnumber', ':'));
- if (!result.assetTag) {
- result.assetTag = cleanDefaults(util.getValue(lines, 'sku', ':'));
- }
-
- // memphysical
- lines = data.results[1] ? data.results[1].toString().split('\r\n') : [''];
- result.memMax = util.toInt(util.getValue(lines, maxCapacityAttribute, ':')) * (win10plus ? 1024 : 1) || null;
- result.memSlots = util.toInt(util.getValue(lines, 'MemoryDevices', ':')) || null;
-
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.baseboard = baseboard;
-
-function macOsChassisType(model) {
- model = model.toLowerCase();
- if (model.startsWith('macbookair')) { return 'Notebook'; }
- if (model.startsWith('macbookpro')) { return 'Laptop'; }
- if (model.startsWith('macbook')) { return 'Notebook'; }
- if (model.startsWith('macmini')) { return 'Desktop'; }
- if (model.startsWith('imac')) { return 'Desktop'; }
- if (model.startsWith('macstudio')) { return 'Desktop'; }
- if (model.startsWith('macpro')) { return 'Tower'; }
- return 'Other';
-}
-
-function chassis(callback) {
- const chassisTypes = ['Other',
- 'Unknown',
- 'Desktop',
- 'Low Profile Desktop',
- 'Pizza Box',
- 'Mini Tower',
- 'Tower',
- 'Portable',
- 'Laptop',
- 'Notebook',
- 'Hand Held',
- 'Docking Station',
- 'All in One',
- 'Sub Notebook',
- 'Space-Saving',
- 'Lunch Box',
- 'Main System Chassis',
- 'Expansion Chassis',
- 'SubChassis',
- 'Bus Expansion Chassis',
- 'Peripheral Chassis',
- 'Storage Chassis',
- 'Rack Mount Chassis',
- 'Sealed-Case PC',
- 'Multi-System Chassis',
- 'Compact PCI',
- 'Advanced TCA',
- 'Blade',
- 'Blade Enclosure',
- 'Tablet',
- 'Convertible',
- 'Detachable',
- 'IoT Gateway ',
- 'Embedded PC',
- 'Mini PC',
- 'Stick PC',
- ];
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- manufacturer: '',
- model: '',
- type: '',
- version: '',
- serial: '-',
- assetTag: '-',
- sku: '',
- };
- if (_linux || _freebsd || _openbsd || _netbsd) {
- const cmd = `echo -n "chassis_asset_tag: "; cat /sys/devices/virtual/dmi/id/chassis_asset_tag 2>/dev/null; echo;
- echo -n "chassis_serial: "; cat /sys/devices/virtual/dmi/id/chassis_serial 2>/dev/null; echo;
- echo -n "chassis_type: "; cat /sys/devices/virtual/dmi/id/chassis_type 2>/dev/null; echo;
- echo -n "chassis_vendor: "; cat /sys/devices/virtual/dmi/id/chassis_vendor 2>/dev/null; echo;
- echo -n "chassis_version: "; cat /sys/devices/virtual/dmi/id/chassis_version 2>/dev/null; echo;`;
- exec(cmd, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- result.manufacturer = cleanDefaults(util.getValue(lines, 'chassis_vendor'));
- const ctype = parseInt(util.getValue(lines, 'chassis_type').replace(/\D/g, ''));
- result.type = cleanDefaults((ctype && !isNaN(ctype) && ctype < chassisTypes.length) ? chassisTypes[ctype - 1] : '');
- result.version = cleanDefaults(util.getValue(lines, 'chassis_version'));
- result.serial = cleanDefaults(util.getValue(lines, 'chassis_serial'));
- result.assetTag = cleanDefaults(util.getValue(lines, 'chassis_asset_tag'));
-
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- exec('ioreg -c IOPlatformExpertDevice -d 2', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().replace(/[<>"]/g, '').split('\n');
- const model = util.getAppleModel(util.getValue(lines, 'model', '=', true));
- // const modelParts = util.splitByNumber(model);
- // const version = util.getValue(lines, 'version', '=', true);
- result.manufacturer = util.getValue(lines, 'manufacturer', '=', true);
- result.model = model.key;
- result.type = macOsChassisType(model.model);
- result.version = model.version;
- result.serial = util.getValue(lines, 'ioplatformserialnumber', '=', true);
- result.assetTag = util.getValue(lines, 'board-id', '=', true) || util.getValue(lines, 'target-type', '=', true);
- result.sku = util.getValue(lines, 'target-sub-type', '=', true);
- }
-
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- util.powerShell('Get-CimInstance Win32_SystemEnclosure | select Model,Manufacturer,ChassisTypes,Version,SerialNumber,PartNumber,SKU,SMBIOSAssetTag | fl').then((stdout, error) => {
- if (!error) {
- let lines = stdout.toString().split('\r\n');
-
- result.manufacturer = cleanDefaults(util.getValue(lines, 'manufacturer', ':'));
- result.model = cleanDefaults(util.getValue(lines, 'model', ':'));
- const ctype = parseInt(util.getValue(lines, 'ChassisTypes', ':').replace(/\D/g, ''));
- result.type = (ctype && !isNaN(ctype) && ctype < chassisTypes.length) ? chassisTypes[ctype - 1] : '';
- result.version = cleanDefaults(util.getValue(lines, 'version', ':'));
- result.serial = cleanDefaults(util.getValue(lines, 'serialnumber', ':'));
- result.assetTag = cleanDefaults(util.getValue(lines, 'partnumber', ':'));
- if (!result.assetTag) {
- result.assetTag = cleanDefaults(util.getValue(lines, 'SMBIOSAssetTag', ':'));
- }
- result.sku = cleanDefaults(util.getValue(lines, 'sku', ':'));
- }
-
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.chassis = chassis;
-
-
-/***/ }),
-
-/***/ 66223:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// usb.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 16. usb
-// ----------------------------------------------------------------------------------
-
-const exec = (__nccwpck_require__(35317).exec);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-function getLinuxUsbType(type, name) {
- let result = type;
- const str = (name + ' ' + type).toLowerCase();
- if (str.indexOf('camera') >= 0) { result = 'Camera'; }
- else if (str.indexOf('hub') >= 0) { result = 'Hub'; }
- else if (str.indexOf('keybrd') >= 0) { result = 'Keyboard'; }
- else if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
- else if (str.indexOf('mouse') >= 0) { result = 'Mouse'; }
- else if (str.indexOf('stora') >= 0) { result = 'Storage'; }
- else if (str.indexOf('microp') >= 0) { result = 'Microphone'; }
- else if (str.indexOf('headset') >= 0) { result = 'Audio'; }
- else if (str.indexOf('audio') >= 0) { result = 'Audio'; }
-
- return result;
-}
-
-function parseLinuxUsb(usb) {
- const result = {};
- const lines = usb.split('\n');
- if (lines && lines.length && lines[0].indexOf('Device') >= 0) {
- const parts = lines[0].split(' ');
- result.bus = parseInt(parts[0], 10);
- if (parts[2]) {
- result.deviceId = parseInt(parts[2], 10);
- } else {
- result.deviceId = null;
- }
- } else {
- result.bus = null;
- result.deviceId = null;
- }
- const idVendor = util.getValue(lines, 'idVendor', ' ', true).trim();
- let vendorParts = idVendor.split(' ');
- vendorParts.shift();
- const vendor = vendorParts.join(' ');
-
- const idProduct = util.getValue(lines, 'idProduct', ' ', true).trim();
- let productParts = idProduct.split(' ');
- productParts.shift();
- const product = productParts.join(' ');
-
- const interfaceClass = util.getValue(lines, 'bInterfaceClass', ' ', true).trim();
- let interfaceClassParts = interfaceClass.split(' ');
- interfaceClassParts.shift();
- const usbType = interfaceClassParts.join(' ');
-
- const iManufacturer = util.getValue(lines, 'iManufacturer', ' ', true).trim();
- let iManufacturerParts = iManufacturer.split(' ');
- iManufacturerParts.shift();
- const manufacturer = iManufacturerParts.join(' ');
-
- const iSerial = util.getValue(lines, 'iSerial', ' ', true).trim();
- let iSerialParts = iSerial.split(' ');
- iSerialParts.shift();
- const serial = iSerialParts.join(' ');
-
- result.id = (idVendor.startsWith('0x') ? idVendor.split(' ')[0].substr(2, 10) : '') + ':' + (idProduct.startsWith('0x') ? idProduct.split(' ')[0].substr(2, 10) : '');
- result.name = product;
- result.type = getLinuxUsbType(usbType, product);
- result.removable = null;
- result.vendor = vendor;
- result.manufacturer = manufacturer;
- result.maxPower = util.getValue(lines, 'MaxPower', ' ', true);
- result.serialNumber = serial;
-
- return result;
-}
-
-function getDarwinUsbType(name) {
- let result = '';
- if (name.indexOf('camera') >= 0) { result = 'Camera'; }
- else if (name.indexOf('touch bar') >= 0) { result = 'Touch Bar'; }
- else if (name.indexOf('controller') >= 0) { result = 'Controller'; }
- else if (name.indexOf('headset') >= 0) { result = 'Audio'; }
- else if (name.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
- else if (name.indexOf('trackpad') >= 0) { result = 'Trackpad'; }
- else if (name.indexOf('sensor') >= 0) { result = 'Sensor'; }
- else if (name.indexOf('bthusb') >= 0) { result = 'Bluetooth'; }
- else if (name.indexOf('bth') >= 0) { result = 'Bluetooth'; }
- else if (name.indexOf('rfcomm') >= 0) { result = 'Bluetooth'; }
- else if (name.indexOf('usbhub') >= 0) { result = 'Hub'; }
- else if (name.indexOf(' hub') >= 0) { result = 'Hub'; }
- else if (name.indexOf('mouse') >= 0) { result = 'Mouse'; }
- else if (name.indexOf('microp') >= 0) { result = 'Microphone'; }
- else if (name.indexOf('removable') >= 0) { result = 'Storage'; }
- return result;
-}
-
-function parseDarwinUsb(usb, id) {
- const result = {};
- result.id = id;
-
- usb = usb.replace(/ \|/g, '');
- usb = usb.trim();
- let lines = usb.split('\n');
- lines.shift();
- try {
- for (let i = 0; i < lines.length; i++) {
- lines[i] = lines[i].trim();
- lines[i] = lines[i].replace(/=/g, ':');
- if (lines[i] !== '{' && lines[i] !== '}' && lines[i + 1] && lines[i + 1].trim() !== '}') {
- lines[i] = lines[i] + ',';
- }
-
- lines[i] = lines[i].replace(':Yes,', ':"Yes",');
- lines[i] = lines[i].replace(': Yes,', ': "Yes",');
- lines[i] = lines[i].replace(': Yes', ': "Yes"');
- lines[i] = lines[i].replace(':No,', ':"No",');
- lines[i] = lines[i].replace(': No,', ': "No",');
- lines[i] = lines[i].replace(': No', ': "No"');
-
- // In this case (("com.apple.developer.driverkit.transport.usb"))
- lines[i] = lines[i].replace('((', '').replace('))', '');
-
- // In case we have <923c11> we need make it "<923c11>" for correct JSON parse
- const match = /<(\w+)>/.exec(lines[i]);
- if (match) {
- const number = match[0];
- lines[i] = lines[i].replace(number, `"${number}"`);
- }
- }
- const usbObj = JSON.parse(lines.join('\n'));
- const removableDrive = (usbObj['Built-In'] ? usbObj['Built-In'].toLowerCase() !== 'yes' : true) && (usbObj['non-removable'] ? usbObj['non-removable'].toLowerCase() === 'no' : true);
-
- result.bus = null;
- result.deviceId = null;
- result.id = usbObj['USB Address'] || null;
- result.name = usbObj['kUSBProductString'] || usbObj['USB Product Name'] || null;
- result.type = getDarwinUsbType((usbObj['kUSBProductString'] || usbObj['USB Product Name'] || '').toLowerCase() + (removableDrive ? ' removable' : ''));
- result.removable = usbObj['non-removable'] ? usbObj['non-removable'].toLowerCase() || '' === 'no' : true;
- result.vendor = usbObj['kUSBVendorString'] || usbObj['USB Vendor Name'] || null;
- result.manufacturer = usbObj['kUSBVendorString'] || usbObj['USB Vendor Name'] || null;
-
- result.maxPower = null;
- result.serialNumber = usbObj['kUSBSerialNumberString'] || null;
-
- if (result.name) {
- return result;
- } else {
- return null;
- }
- } catch (e) {
- return null;
- }
-}
-
-function getWindowsUsbTypeCreation(creationclass, name) {
- let result = '';
- if (name.indexOf('storage') >= 0) { result = 'Storage'; }
- else if (name.indexOf('speicher') >= 0) { result = 'Storage'; }
- else if (creationclass.indexOf('usbhub') >= 0) { result = 'Hub'; }
- else if (creationclass.indexOf('storage') >= 0) { result = 'Storage'; }
- else if (creationclass.indexOf('usbcontroller') >= 0) { result = 'Controller'; }
- else if (creationclass.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
- else if (creationclass.indexOf('pointing') >= 0) { result = 'Mouse'; }
- else if (creationclass.indexOf('microp') >= 0) { result = 'Microphone'; }
- else if (creationclass.indexOf('disk') >= 0) { result = 'Storage'; }
- return result;
-}
-
-function parseWindowsUsb(lines, id) {
- const usbType = getWindowsUsbTypeCreation(util.getValue(lines, 'CreationClassName', ':').toLowerCase(), util.getValue(lines, 'name', ':').toLowerCase());
-
- if (usbType) {
- const result = {};
- result.bus = null;
- result.deviceId = util.getValue(lines, 'deviceid', ':');
- result.id = id;
- result.name = util.getValue(lines, 'name', ':');
- result.type = usbType;
- result.removable = null;
- result.vendor = null;
- result.manufacturer = util.getValue(lines, 'Manufacturer', ':');
- result.maxPower = null;
- result.serialNumber = null;
-
- return result;
- } else {
- return null;
- }
-}
-
-function usb(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux) {
- const cmd = 'export LC_ALL=C; lsusb -v 2>/dev/null; unset LC_ALL';
- exec(cmd, { maxBuffer: 1024 * 1024 * 128 }, function (error, stdout) {
- if (!error) {
- const parts = ('\n\n' + stdout.toString()).split('\n\nBus ');
- for (let i = 1; i < parts.length; i++) {
- const usb = parseLinuxUsb(parts[i]);
- result.push(usb);
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_darwin) {
- let cmd = 'ioreg -p IOUSB -c AppleUSBRootHubDevice -w0 -l';
- exec(cmd, { maxBuffer: 1024 * 1024 * 128 }, function (error, stdout) {
- if (!error) {
- const parts = (stdout.toString()).split(' +-o ');
- for (let i = 1; i < parts.length; i++) {
- const usb = parseDarwinUsb(parts[i]);
- if (usb) {
- result.push(usb);
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_windows) {
- util.powerShell('Get-CimInstance CIM_LogicalDevice | where { $_.Description -match "USB"} | select Name,CreationClassName,DeviceId,Manufacturer | fl').then((stdout, error) => {
- if (!error) {
- const parts = stdout.toString().split(/\n\s*\n/);
- for (let i = 0; i < parts.length; i++) {
- const usb = parseWindowsUsb(parts[i].split('\n'), i);
- if (usb && result.filter(x => x.deviceId === usb.deviceId).length === 0) {
- result.push(usb);
- }
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_sunos || _freebsd || _openbsd || _netbsd) {
- resolve(null);
- }
- });
- });
-}
-
-exports.usb = usb;
-
-
-
-/***/ }),
-
-/***/ 93069:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// users.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 11. Users/Sessions
-// ----------------------------------------------------------------------------------
-
-const exec = (__nccwpck_require__(35317).exec);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-function parseUsersLinux(lines, phase) {
- let result = [];
- let result_who = [];
- let result_w = {};
- let w_first = true;
- let w_header = [];
- let w_pos = [];
- let who_line = {};
-
- let is_whopart = true;
- lines.forEach(function (line) {
- if (line === '---') {
- is_whopart = false;
- } else {
- let l = line.replace(/ +/g, ' ').split(' ');
-
- // who part
- if (is_whopart) {
- result_who.push({
- user: l[0],
- tty: l[1],
- date: l[2],
- time: l[3],
- ip: (l && l.length > 4) ? l[4].replace(/\(/g, '').replace(/\)/g, '') : ''
- });
- } else {
- // w part
- if (w_first) { // header
- w_header = l;
- w_header.forEach(function (item) {
- w_pos.push(line.indexOf(item));
- });
- w_first = false;
- } else {
- // split by w_pos
- result_w.user = line.substring(w_pos[0], w_pos[1] - 1).trim();
- result_w.tty = line.substring(w_pos[1], w_pos[2] - 1).trim();
- result_w.ip = line.substring(w_pos[2], w_pos[3] - 1).replace(/\(/g, '').replace(/\)/g, '').trim();
- result_w.command = line.substring(w_pos[7], 1000).trim();
- // find corresponding 'who' line
- who_line = result_who.filter(function (obj) {
- return (obj.user.substring(0, 8).trim() === result_w.user && obj.tty === result_w.tty);
- });
- if (who_line.length === 1) {
- result.push({
- user: who_line[0].user,
- tty: who_line[0].tty,
- date: who_line[0].date,
- time: who_line[0].time,
- ip: who_line[0].ip,
- command: result_w.command
- });
- }
- }
- }
- }
- });
- if (result.length === 0 && phase === 2) {
- return result_who;
- } else {
- return result;
- }
-}
-
-function parseUsersDarwin(lines) {
- let result = [];
- let result_who = [];
- let result_w = {};
- let who_line = {};
-
- let is_whopart = true;
- lines.forEach(function (line) {
- if (line === '---') {
- is_whopart = false;
- } else {
- let l = line.replace(/ +/g, ' ').split(' ');
-
- // who part
- if (is_whopart) {
- result_who.push({
- user: l[0],
- tty: l[1],
- date: ('' + new Date().getFullYear()) + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(l[2].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + l[3]).slice(-2),
- time: l[4],
- });
- } else {
- // w part
- // split by w_pos
- result_w.user = l[0];
- result_w.tty = l[1];
- result_w.ip = (l[2] !== '-') ? l[2] : '';
- result_w.command = l.slice(5, 1000).join(' ');
- // find corresponding 'who' line
- who_line = result_who.filter(function (obj) {
- return (obj.user.substring(0, 10) === result_w.user.substring(0, 10) && (obj.tty.substring(3, 1000) === result_w.tty || obj.tty === result_w.tty));
- });
- if (who_line.length === 1) {
- result.push({
- user: who_line[0].user,
- tty: who_line[0].tty,
- date: who_line[0].date,
- time: who_line[0].time,
- ip: result_w.ip,
- command: result_w.command
- });
- }
- }
- }
- });
- return result;
-}
-
-function users(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
-
- // linux
- if (_linux) {
- exec('who --ips; echo "---"; w | tail -n +2', function (error, stdout) {
- if (!error) {
- // lines / split
- let lines = stdout.toString().split('\n');
- result = parseUsersLinux(lines, 1);
- if (result.length === 0) {
- exec('who; echo "---"; w | tail -n +2', function (error, stdout) {
- if (!error) {
- // lines / split
- lines = stdout.toString().split('\n');
- result = parseUsersLinux(lines, 2);
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('who; echo "---"; w -ih', function (error, stdout) {
- if (!error) {
- // lines / split
- let lines = stdout.toString().split('\n');
- result = parseUsersDarwin(lines);
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- exec('who; echo "---"; w -h', function (error, stdout) {
- if (!error) {
- // lines / split
- let lines = stdout.toString().split('\n');
- result = parseUsersDarwin(lines);
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
-
- if (_darwin) {
- exec('who; echo "---"; w -ih', function (error, stdout) {
- if (!error) {
- // lines / split
- let lines = stdout.toString().split('\n');
- result = parseUsersDarwin(lines);
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_windows) {
- try {
- let cmd = 'Get-CimInstance Win32_LogonSession | select LogonId,@{n="StartTime";e={$_.StartTime.ToString("yyyy-MM-dd HH:mm:ss")}} | fl' + '; echo \'#-#-#-#\';';
- cmd += 'Get-CimInstance Win32_LoggedOnUser | select antecedent,dependent | fl ' + '; echo \'#-#-#-#\';';
- cmd += '$process = (Get-CimInstance Win32_Process -Filter "name = \'explorer.exe\'"); Invoke-CimMethod -InputObject $process[0] -MethodName GetOwner | select user, domain | fl; get-process -name explorer | select-object sessionid | fl; echo \'#-#-#-#\';';
- cmd += 'query user';
- util.powerShell(cmd).then((data) => {
- if (data) {
- data = data.split('#-#-#-#');
- let sessions = parseWinSessions((data[0] || '').split(/\n\s*\n/));
- let loggedons = parseWinLoggedOn((data[1] || '').split(/\n\s*\n/));
- let queryUser = parseWinUsersQuery((data[3] || '').split('\r\n'));
- let users = parseWinUsers((data[2] || '').split(/\n\s*\n/), queryUser);
- for (let id in loggedons) {
- if ({}.hasOwnProperty.call(loggedons, id)) {
- loggedons[id].dateTime = {}.hasOwnProperty.call(sessions, id) ? sessions[id] : '';
- }
- }
- users.forEach(user => {
- let dateTime = '';
- for (let id in loggedons) {
- if ({}.hasOwnProperty.call(loggedons, id)) {
- if (loggedons[id].user === user.user && (!dateTime || dateTime < loggedons[id].dateTime)) {
- dateTime = loggedons[id].dateTime;
- }
- }
- }
-
- result.push({
- user: user.user,
- tty: user.tty,
- date: `${dateTime.substring(0, 10)}`,
- time: `${dateTime.substring(11, 19)}`,
- ip: '',
- command: ''
- });
- });
- }
- if (callback) { callback(result); }
- resolve(result);
-
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-function parseWinSessions(sessionParts) {
- const sessions = {};
- sessionParts.forEach(session => {
- const lines = session.split('\r\n');
- const id = util.getValue(lines, 'LogonId');
- const starttime = util.getValue(lines, 'starttime');
- if (id) {
- sessions[id] = starttime;
- }
- });
- return sessions;
-}
-
-function fuzzyMatch(name1, name2) {
- name1 = name1.toLowerCase();
- name2 = name2.toLowerCase();
- let eq = 0;
- let len = name1.length;
- if (name2.length > len) { len = name2.length; }
-
- for (let i = 0; i < len; i++) {
- const c1 = name1[i] || '';
- const c2 = name2[i] || '';
- if (c1 === c2) { eq++; }
- }
- return (len > 10 ? eq / len > 0.9 : (len > 0 ? eq / len > 0.8 : false));
-}
-
-function parseWinUsers(userParts, userQuery) {
- const users = [];
- userParts.forEach(user => {
- const lines = user.split('\r\n');
-
- const domain = util.getValue(lines, 'domain', ':', true);
- const username = util.getValue(lines, 'user', ':', true);
- const sessionid = util.getValue(lines, 'sessionid', ':', true);
-
- if (username) {
- const quser = userQuery.filter(item => fuzzyMatch(item.user, username));
- users.push({
- domain,
- user: username,
- tty: quser && quser[0] && quser[0].tty ? quser[0].tty : sessionid
- });
- }
- });
- return users;
-}
-
-function parseWinLoggedOn(loggedonParts) {
- const loggedons = {};
- loggedonParts.forEach(loggedon => {
- const lines = loggedon.split('\r\n');
-
- const antecendent = util.getValue(lines, 'antecedent', ':', true);
- let parts = antecendent.split('=');
- const name = parts.length > 2 ? parts[1].split(',')[0].replace(/"/g, '').trim() : '';
- const domain = parts.length > 2 ? parts[2].replace(/"/g, '').replace(/\)/g, '').trim() : '';
- const dependent = util.getValue(lines, 'dependent', ':', true);
- parts = dependent.split('=');
- const id = parts.length > 1 ? parts[1].replace(/"/g, '').replace(/\)/g, '').trim() : '';
- if (id) {
- loggedons[id] = {
- domain,
- user: name
- };
- }
- });
- return loggedons;
-}
-
-function parseWinUsersQuery(lines) {
- lines = lines.filter(item => item);
- let result = [];
- const header = lines[0];
- const headerDelimiter = [];
- if (header) {
- const start = (header[0] === ' ') ? 1 : 0;
- headerDelimiter.push(start - 1);
- let nextSpace = 0;
- for (let i = start + 1; i < header.length; i++) {
- if (header[i] === ' ' && ((header[i - 1] === ' ') || (header[i - 1] === '.'))) {
- nextSpace = i;
- } else {
- if (nextSpace) {
- headerDelimiter.push(nextSpace);
- nextSpace = 0;
- }
- }
- }
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim()) {
- const user = lines[i].substring(headerDelimiter[0] + 1, headerDelimiter[1]).trim() || '';
- const tty = lines[i].substring(headerDelimiter[1] + 1, headerDelimiter[2] - 2).trim() || '';
- result.push({
- user: user,
- tty: tty,
- });
- }
- }
- }
- return result;
-}
-
-exports.users = users;
-
-
-/***/ }),
-
-/***/ 33225:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// utils.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 0. helper functions
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const fs = __nccwpck_require__(79896);
-const path = __nccwpck_require__(16928);
-const spawn = (__nccwpck_require__(35317).spawn);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const util = __nccwpck_require__(39023);
-
-let _platform = process.platform;
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-
-let _cores = 0;
-let wmicPath = '';
-let codepage = '';
-let _smartMonToolsInstalled = null;
-let _rpi_cpuinfo = null;
-
-const WINDIR = process.env.WINDIR || 'C:\\Windows';
-
-// powerShell
-let _psChild;
-let _psResult = '';
-let _psCmds = [];
-let _psPersistent = false;
-const _psToUTF8 = '$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; ';
-const _psCmdStart = '--###START###--';
-const _psError = '--ERROR--';
-const _psCmdSeperator = '--###ENDCMD###--';
-const _psIdSeperator = '--##ID##--';
-
-const execOptsWin = {
- windowsHide: true,
- maxBuffer: 1024 * 20000,
- encoding: 'UTF-8',
- env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' })
-};
-
-const execOptsLinux = {
- maxBuffer: 1024 * 20000,
- encoding: 'UTF-8',
- stdio: ['pipe', 'pipe', 'ignore']
-};
-
-function toInt(value) {
- let result = parseInt(value, 10);
- if (isNaN(result)) {
- result = 0;
- }
- return result;
-}
-
-function splitByNumber(str) {
- let numberStarted = false;
- let num = '';
- let cpart = '';
- for (const c of str) {
- if ((c >= '0' && c <= '9') || numberStarted) {
- numberStarted = true;
- num += c;
- } else {
- cpart += c;
- }
- }
- return [cpart, num];
-}
-
-const stringObj = new String();
-const stringReplace = new String().replace;
-const stringToLower = new String().toLowerCase;
-const stringToString = new String().toString;
-const stringSubstr = new String().substr;
-const stringTrim = new String().trim;
-const stringStartWith = new String().startsWith;
-const mathMin = Math.min;
-
-function isFunction(functionToCheck) {
- let getType = {};
- return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
-}
-
-function unique(obj) {
- let uniques = [];
- let stringify = {};
- for (let i = 0; i < obj.length; i++) {
- let keys = Object.keys(obj[i]);
- keys.sort(function (a, b) { return a - b; });
- let str = '';
- for (let j = 0; j < keys.length; j++) {
- str += JSON.stringify(keys[j]);
- str += JSON.stringify(obj[i][keys[j]]);
- }
- if (!{}.hasOwnProperty.call(stringify, str)) {
- uniques.push(obj[i]);
- stringify[str] = true;
- }
- }
- return uniques;
-}
-
-function sortByKey(array, keys) {
- return array.sort(function (a, b) {
- let x = '';
- let y = '';
- keys.forEach(function (key) {
- x = x + a[key]; y = y + b[key];
- });
- return ((x < y) ? -1 : ((x > y) ? 1 : 0));
- });
-}
-
-function cores() {
- if (_cores === 0) {
- _cores = os.cpus().length;
- }
- return _cores;
-}
-
-function getValue(lines, property, separator, trimmed, lineMatch) {
- separator = separator || ':';
- property = property.toLowerCase();
- trimmed = trimmed || false;
- lineMatch = lineMatch || false;
- let result = '';
- lines.some((line) => {
- let lineLower = line.toLowerCase().replace(/\t/g, '');
- if (trimmed) {
- lineLower = lineLower.trim();
- }
- if (lineLower.startsWith(property) && (lineMatch ? (lineLower.match(property + separator)) || (lineLower.match(property + ' ' + separator)) : true)) {
- const parts = trimmed ? line.trim().split(separator) : line.split(separator);
- if (parts.length >= 2) {
- parts.shift();
- result = parts.join(separator).trim();
- return true;
- }
- }
- });
- return result;
-}
-
-function decodeEscapeSequence(str, base) {
- base = base || 16;
- return str.replace(/\\x([0-9A-Fa-f]{2})/g, function () {
- return String.fromCharCode(parseInt(arguments[1], base));
- });
-}
-
-function detectSplit(str) {
- let seperator = '';
- let part = 0;
- str.split('').forEach(element => {
- if (element >= '0' && element <= '9') {
- if (part === 1) { part++; }
- } else {
- if (part === 0) { part++; }
- if (part === 1) {
- seperator += element;
- }
- }
- });
- return seperator;
-}
-
-function parseTime(t, pmDesignator) {
- pmDesignator = pmDesignator || '';
- t = t.toUpperCase();
- let hour = 0;
- let min = 0;
- let splitter = detectSplit(t);
- let parts = t.split(splitter);
- if (parts.length >= 2) {
- if (parts[2]) {
- parts[1] += parts[2];
- }
- let isPM = (parts[1] && (parts[1].toLowerCase().indexOf('pm') > -1) || (parts[1].toLowerCase().indexOf('p.m.') > -1) || (parts[1].toLowerCase().indexOf('p. m.') > -1) || (parts[1].toLowerCase().indexOf('n') > -1) || (parts[1].toLowerCase().indexOf('ch') > -1) || (parts[1].toLowerCase().indexOf('ös') > -1) || (pmDesignator && parts[1].toLowerCase().indexOf(pmDesignator) > -1));
- hour = parseInt(parts[0], 10);
- min = parseInt(parts[1], 10);
- hour = isPM && hour < 12 ? hour + 12 : hour;
- return ('0' + hour).substr(-2) + ':' + ('0' + min).substr(-2);
- }
-}
-
-function parseDateTime(dt, culture) {
- const result = {
- date: '',
- time: ''
- };
- culture = culture || {};
- let dateFormat = (culture.dateFormat || '').toLowerCase();
- let pmDesignator = (culture.pmDesignator || '');
-
- const parts = dt.split(' ');
- if (parts[0]) {
- if (parts[0].indexOf('/') >= 0) {
- // Dateformat: mm/dd/yyyy or dd/mm/yyyy or dd/mm/yy or yyyy/mm/dd
- const dtparts = parts[0].split('/');
- if (dtparts.length === 3) {
- if (dtparts[0].length === 4) {
- // Dateformat: yyyy/mm/dd
- result.date = dtparts[0] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[2]).substr(-2);
- } else if (dtparts[2].length === 2) {
- if ((dateFormat.indexOf('/d/') > -1 || dateFormat.indexOf('/dd/') > -1)) {
- // Dateformat: mm/dd/yy
- result.date = '20' + dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
- } else {
- // Dateformat: dd/mm/yy
- result.date = '20' + dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
- }
- } else {
- // Dateformat: mm/dd/yyyy or dd/mm/yyyy
- const isEN = ((dt.toLowerCase().indexOf('pm') > -1) || (dt.toLowerCase().indexOf('p.m.') > -1) || (dt.toLowerCase().indexOf('p. m.') > -1) || (dt.toLowerCase().indexOf('am') > -1) || (dt.toLowerCase().indexOf('a.m.') > -1) || (dt.toLowerCase().indexOf('a. m.') > -1));
- if ((isEN || dateFormat.indexOf('/d/') > -1 || dateFormat.indexOf('/dd/') > -1) && dateFormat.indexOf('dd/') !== 0) {
- // Dateformat: mm/dd/yyyy
- result.date = dtparts[2] + '-' + ('0' + dtparts[0]).substr(-2) + '-' + ('0' + dtparts[1]).substr(-2);
- } else {
- // Dateformat: dd/mm/yyyy
- result.date = dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
- }
- }
- }
- }
- if (parts[0].indexOf('.') >= 0) {
- const dtparts = parts[0].split('.');
- if (dtparts.length === 3) {
- if (dateFormat.indexOf('.d.') > -1 || dateFormat.indexOf('.dd.') > -1) {
- // Dateformat: mm.dd.yyyy
- result.date = dtparts[2] + '-' + ('0' + dtparts[0]).substr(-2) + '-' + ('0' + dtparts[1]).substr(-2);
- } else {
- // Dateformat: dd.mm.yyyy
- result.date = dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
- }
- }
- }
- if (parts[0].indexOf('-') >= 0) {
- // Dateformat: yyyy-mm-dd
- const dtparts = parts[0].split('-');
- if (dtparts.length === 3) {
- result.date = dtparts[0] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[2]).substr(-2);
- }
- }
- }
- if (parts[1]) {
- parts.shift();
- let time = parts.join(' ');
- result.time = parseTime(time, pmDesignator);
- }
- return result;
-}
-
-function parseHead(head, rights) {
- let space = (rights > 0);
- let count = 1;
- let from = 0;
- let to = 0;
- let result = [];
- for (let i = 0; i < head.length; i++) {
- if (count <= rights) {
- if (/\s/.test(head[i]) && !space) {
- to = i - 1;
- result.push({
- from: from,
- to: to + 1,
- cap: head.substring(from, to + 1)
- });
- from = to + 2;
- count++;
- }
- space = head[i] === ' ';
- } else {
- if (!/\s/.test(head[i]) && space) {
- to = i - 1;
- if (from < to) {
- result.push({
- from: from,
- to: to,
- cap: head.substring(from, to)
- });
- }
- from = to + 1;
- count++;
- }
- space = head[i] === ' ';
- }
- }
- to = 5000;
- result.push({
- from: from,
- to: to,
- cap: head.substring(from, to)
- });
- let len = result.length;
- for (let i = 0; i < len; i++) {
- if (result[i].cap.replace(/\s/g, '').length === 0) {
- if (i + 1 < len) {
- result[i].to = result[i + 1].to;
- result[i].cap = result[i].cap + result[i + 1].cap;
- result.splice(i + 1, 1);
- len = len - 1;
- }
- }
- }
- return result;
-}
-
-function findObjectByKey(array, key, value) {
- for (let i = 0; i < array.length; i++) {
- if (array[i][key] === value) {
- return i;
- }
- }
- return -1;
-}
-
-function getWmic() {
- if (os.type() === 'Windows_NT' && !wmicPath) {
- wmicPath = WINDIR + '\\system32\\wbem\\wmic.exe';
- if (!fs.existsSync(wmicPath)) {
- try {
- const wmicPathArray = execSync('WHERE WMIC', execOptsWin).toString().split('\r\n');
- if (wmicPathArray && wmicPathArray.length) {
- wmicPath = wmicPathArray[0];
- } else {
- wmicPath = 'wmic';
- }
- } catch (e) {
- wmicPath = 'wmic';
- }
- }
- }
- return wmicPath;
-}
-
-function wmic(command) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- try {
- powerShell(getWmic() + ' ' + command).then(stdout => {
- resolve(stdout, '');
- });
- } catch (e) {
- resolve('', e);
- }
- });
- });
-}
-
-function getVboxmanage() {
- return _windows ? `"${process.env.VBOX_INSTALL_PATH || process.env.VBOX_MSI_INSTALL_PATH}\\VBoxManage.exe"` : 'vboxmanage';
-}
-
-function powerShellProceedResults(data) {
- let id = '';
- let parts;
- let res = '';
- // startID
- if (data.indexOf(_psCmdStart) >= 0) {
- parts = data.split(_psCmdStart);
- const parts2 = parts[1].split(_psIdSeperator);
- id = parts2[0];
- if (parts2.length > 1) {
- data = parts2.slice(1).join(_psIdSeperator);
- }
- }
- // result;
- if (data.indexOf(_psCmdSeperator) >= 0) {
- parts = data.split(_psCmdSeperator);
- res = parts[0];
- }
- let remove = -1;
- for (let i = 0; i < _psCmds.length; i++) {
- if (_psCmds[i].id === id) {
- remove = i;
- _psCmds[i].callback(res);
- }
- }
- if (remove >= 0) {
- _psCmds.splice(remove, 1);
- }
-}
-
-function powerShellStart() {
- if (!_psChild) {
- _psChild = spawn('powershell.exe', ['-NoProfile', '-NoLogo', '-InputFormat', 'Text', '-NoExit', '-Command', '-'], {
- stdio: 'pipe',
- windowsHide: true,
- maxBuffer: 1024 * 20000,
- encoding: 'UTF-8',
- env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' })
- });
- if (_psChild && _psChild.pid) {
- _psPersistent = true;
- _psChild.stdout.on('data', function (data) {
- _psResult = _psResult + data.toString('utf8');
- if (data.indexOf(_psCmdSeperator) >= 0) {
- powerShellProceedResults(_psResult);
- _psResult = '';
- }
- });
- _psChild.stderr.on('data', function () {
- powerShellProceedResults(_psResult + _psError);
- });
- _psChild.on('error', function () {
- powerShellProceedResults(_psResult + _psError);
- });
- _psChild.on('close', function () {
- if (_psChild) { _psChild.kill(); }
- });
- }
- }
-}
-
-function powerShellRelease() {
- try {
- if (_psChild) {
- _psChild.stdin.write('exit' + os.EOL);
- _psChild.stdin.end();
- _psPersistent = false;
- }
- } catch (e) {
- if (_psChild) { _psChild.kill(); }
- }
- _psChild = null;
-}
-
-function powerShell(cmd) {
-
- /// const pattern = [
- /// '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
- /// '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))'
- /// ].join('|');
-
- if (_psPersistent) {
- const id = Math.random().toString(36).substring(2, 12);
- return new Promise((resolve) => {
- process.nextTick(() => {
- function callback(data) {
- resolve(data);
- }
- _psCmds.push({
- id,
- cmd,
- callback,
- start: new Date()
- });
- try {
- if (_psChild && _psChild.pid) {
- _psChild.stdin.write(_psToUTF8 + 'echo ' + _psCmdStart + id + _psIdSeperator + '; ' + os.EOL + cmd + os.EOL + 'echo ' + _psCmdSeperator + os.EOL);
- }
- } catch (e) {
- resolve('');
- }
- });
- });
-
- } else {
- let result = '';
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- try {
- const child = spawn('powershell.exe', ['-NoProfile', '-NoLogo', '-InputFormat', 'Text', '-NoExit', '-ExecutionPolicy', 'Unrestricted', '-Command', '-'], {
- stdio: 'pipe',
- windowsHide: true,
- maxBuffer: 1024 * 20000,
- encoding: 'UTF-8',
- env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' })
- });
-
- if (child && !child.pid) {
- child.on('error', function () {
- resolve(result);
- });
- }
- if (child && child.pid) {
- child.stdout.on('data', function (data) {
- result = result + data.toString('utf8');
- });
- child.stderr.on('data', function () {
- child.kill();
- resolve(result);
- });
- child.on('close', function () {
- child.kill();
-
- resolve(result);
- });
- child.on('error', function () {
- child.kill();
- resolve(result);
- });
- try {
- child.stdin.write(_psToUTF8 + cmd + os.EOL);
- child.stdin.write('exit' + os.EOL);
- child.stdin.end();
- } catch (e) {
- child.kill();
- resolve(result);
- }
- } else {
- resolve(result);
- }
- } catch (e) {
- resolve(result);
- }
- });
- });
- }
-}
-
-function execSafe(cmd, args, options) {
- let result = '';
- options = options || {};
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- try {
- const child = spawn(cmd, args, options);
-
- if (child && !child.pid) {
- child.on('error', function () {
- resolve(result);
- });
- }
- if (child && child.pid) {
- child.stdout.on('data', function (data) {
- result += data.toString();
- });
- child.on('close', function () {
- child.kill();
- resolve(result);
- });
- child.on('error', function () {
- child.kill();
- resolve(result);
- });
- } else {
- resolve(result);
- }
- } catch (e) {
- resolve(result);
- }
- });
- });
-}
-
-function getCodepage() {
- if (_windows) {
- if (!codepage) {
- try {
- const stdout = execSync('chcp', execOptsWin);
- const lines = stdout.toString().split('\r\n');
- const parts = lines[0].split(':');
- codepage = parts.length > 1 ? parts[1].replace('.', '').trim() : '';
- } catch (err) {
- codepage = '437';
- }
- }
- return codepage;
- }
- if (_linux || _darwin || _freebsd || _openbsd || _netbsd) {
- if (!codepage) {
- try {
- const stdout = execSync('echo $LANG', execOptsLinux);
- const lines = stdout.toString().split('\r\n');
- const parts = lines[0].split('.');
- codepage = parts.length > 1 ? parts[1].trim() : '';
- if (!codepage) {
- codepage = 'UTF-8';
- }
- } catch (err) {
- codepage = 'UTF-8';
- }
- }
- return codepage;
- }
-}
-
-function smartMonToolsInstalled() {
- if (_smartMonToolsInstalled !== null) {
- return _smartMonToolsInstalled;
- }
- _smartMonToolsInstalled = false;
- if (_windows) {
- try {
- const pathArray = execSync('WHERE smartctl 2>nul', execOptsWin).toString().split('\r\n');
- if (pathArray && pathArray.length) {
- _smartMonToolsInstalled = pathArray[0].indexOf(':\\') >= 0;
- } else {
- _smartMonToolsInstalled = false;
- }
- } catch (e) {
- _smartMonToolsInstalled = false;
- }
- }
- if (_linux || _darwin || _freebsd || _openbsd || _netbsd) {
- try {
- const pathArray = execSync('which smartctl 2>/dev/null', execOptsLinux).toString().split('\r\n');
- _smartMonToolsInstalled = pathArray.length > 0;
- } catch (e) {
- util.noop();
- }
- }
- return _smartMonToolsInstalled;
-}
-
-function isRaspberry() {
- const PI_MODEL_NO = [
- 'BCM2708',
- 'BCM2709',
- 'BCM2710',
- 'BCM2711',
- 'BCM2712',
- 'BCM2835',
- 'BCM2836',
- 'BCM2837',
- 'BCM2837B0'
- ];
- let cpuinfo = [];
-
- if (_rpi_cpuinfo !== null) {
- cpuinfo = _rpi_cpuinfo;
- } else {
- try {
- cpuinfo = fs.readFileSync('/proc/cpuinfo', { encoding: 'utf8' }).toString().split('\n');
- _rpi_cpuinfo = cpuinfo;
- } catch (e) {
- return false;
- }
- }
-
- const hardware = getValue(cpuinfo, 'hardware');
- return (hardware && PI_MODEL_NO.indexOf(hardware) > -1);
-}
-
-function isRaspbian() {
- let osrelease = [];
- try {
- osrelease = fs.readFileSync('/etc/os-release', { encoding: 'utf8' }).toString().split('\n');
- } catch (e) {
- return false;
- }
- const id = getValue(osrelease, 'id', '=');
- return (id && id.indexOf('raspbian') > -1);
-}
-
-function execWin(cmd, opts, callback) {
- if (!callback) {
- callback = opts;
- opts = execOptsWin;
- }
- let newCmd = 'chcp 65001 > nul && cmd /C ' + cmd + ' && chcp ' + codepage + ' > nul';
- exec(newCmd, opts, function (error, stdout) {
- callback(error, stdout);
- });
-}
-
-function darwinXcodeExists() {
- const cmdLineToolsExists = fs.existsSync('/Library/Developer/CommandLineTools/usr/bin/');
- const xcodeAppExists = fs.existsSync('/Applications/Xcode.app/Contents/Developer/Tools');
- const xcodeExists = fs.existsSync('/Library/Developer/Xcode/');
- return (cmdLineToolsExists || xcodeExists || xcodeAppExists);
-}
-
-function nanoSeconds() {
- const time = process.hrtime();
- if (!Array.isArray(time) || time.length !== 2) {
- return 0;
- }
- return +time[0] * 1e9 + +time[1];
-}
-
-function countUniqueLines(lines, startingWith) {
- startingWith = startingWith || '';
- const uniqueLines = [];
- lines.forEach(line => {
- if (line.startsWith(startingWith)) {
- if (uniqueLines.indexOf(line) === -1) {
- uniqueLines.push(line);
- }
- }
- });
- return uniqueLines.length;
-}
-
-function countLines(lines, startingWith) {
- startingWith = startingWith || '';
- const uniqueLines = [];
- lines.forEach(line => {
- if (line.startsWith(startingWith)) {
- uniqueLines.push(line);
- }
- });
- return uniqueLines.length;
-}
-
-function sanitizeShellString(str, strict) {
- if (typeof strict === 'undefined') { strict = false; }
- const s = str || '';
- let result = '';
- const l = mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (!(s[i] === undefined ||
- s[i] === '>' ||
- s[i] === '<' ||
- s[i] === '*' ||
- s[i] === '?' ||
- s[i] === '[' ||
- s[i] === ']' ||
- s[i] === '|' ||
- s[i] === '˚' ||
- s[i] === '$' ||
- s[i] === ';' ||
- s[i] === '&' ||
- s[i] === ']' ||
- s[i] === '#' ||
- s[i] === '\\' ||
- s[i] === '\t' ||
- s[i] === '\n' ||
- s[i] === '\r' ||
- s[i] === '\'' ||
- s[i] === '`' ||
- s[i] === '"' ||
- s[i].length > 1 ||
- (strict && s[i] === '(') ||
- (strict && s[i] === ')') ||
- (strict && s[i] === '@') ||
- (strict && s[i] === ' ') ||
- (strict && s[i] == '{') ||
- (strict && s[i] == ';') ||
- (strict && s[i] == '}'))) {
- result = result + s[i];
- }
- }
- return result;
-}
-
-function isPrototypePolluted() {
- const s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
- let notPolluted = true;
- let st = '';
-
- try {
- st.__proto__.replace = stringReplace;
- st.__proto__.toLowerCase = stringToLower;
- st.__proto__.toString = stringToString;
- st.__proto__.substr = stringSubstr;
- } catch (e) {
- Object.setPrototypeOf(st, stringObj);
- }
- notPolluted = notPolluted || (s.length !== 62);
- const ms = Date.now();
- if (typeof ms === 'number' && ms > 1600000000000) {
- const l = ms % 100 + 15;
- for (let i = 0; i < l; i++) {
- const r = Math.random() * 61.99999999 + 1;
- const rs = parseInt(Math.floor(r).toString(), 10);
- const rs2 = parseInt(r.toString().split('.')[0], 10);
- const q = Math.random() * 61.99999999 + 1;
- const qs = parseInt(Math.floor(q).toString(), 10);
- const qs2 = parseInt(q.toString().split('.')[0], 10);
- notPolluted = notPolluted && (r !== q);
- notPolluted = notPolluted && rs === rs2 && qs === qs2;
- st += s[rs - 1];
- }
- notPolluted = notPolluted && st.length === l;
- // string manipulation
- let p = Math.random() * l * 0.9999999999;
- let stm = st.substr(0, p) + ' ' + st.substr(p, 2000);
- try {
- stm.__proto__.replace = stringReplace;
- } catch (e) {
- Object.setPrototypeOf(stm, stringObj);
- }
- let sto = stm.replace(/ /g, '');
- notPolluted = notPolluted && st === sto;
- p = Math.random() * l * 0.9999999999;
- stm = st.substr(0, p) + '{' + st.substr(p, 2000);
- sto = stm.replace(/{/g, '');
- notPolluted = notPolluted && st === sto;
- p = Math.random() * l * 0.9999999999;
- stm = st.substr(0, p) + '*' + st.substr(p, 2000);
- sto = stm.replace(/\*/g, '');
- notPolluted = notPolluted && st === sto;
- p = Math.random() * l * 0.9999999999;
- stm = st.substr(0, p) + '$' + st.substr(p, 2000);
- sto = stm.replace(/\$/g, '');
- notPolluted = notPolluted && st === sto;
-
- // lower
- const stl = st.toLowerCase();
- notPolluted = notPolluted && (stl.length === l) && stl[l - 1] && !(stl[l]);
- for (let i = 0; i < l; i++) {
- const s1 = st[i];
- try {
- s1.__proto__.toLowerCase = stringToLower;
- } catch (e) {
- Object.setPrototypeOf(st, stringObj);
- }
- const s2 = stl ? stl[i] : '';
- const s1l = s1.toLowerCase();
- notPolluted = notPolluted && s1l[0] === s2 && s1l[0] && !(s1l[1]);
- }
- }
- return !notPolluted;
-}
-
-function hex2bin(hex) {
- return ('00000000' + (parseInt(hex, 16)).toString(2)).substr(-8);
-}
-
-function getFilesInPath(source) {
- const lstatSync = fs.lstatSync;
- const readdirSync = fs.readdirSync;
- const join = path.join;
-
- function isDirectory(source) {
- return lstatSync(source).isDirectory();
- }
- function isFile(source) { return lstatSync(source).isFile(); }
-
- function getDirectories(source) {
- return readdirSync(source).map(function (name) { return join(source, name); }).filter(isDirectory);
- }
- function getFiles(source) {
- return readdirSync(source).map(function (name) { return join(source, name); }).filter(isFile);
- }
-
- function getFilesRecursively(source) {
- try {
- let dirs = getDirectories(source);
- let files = dirs
- .map(function (dir) { return getFilesRecursively(dir); })
- .reduce(function (a, b) { return a.concat(b); }, []);
- return files.concat(getFiles(source));
- } catch (e) {
- return [];
- }
- }
-
- if (fs.existsSync(source)) {
- return getFilesRecursively(source);
- } else {
- return [];
- }
-}
-
-function decodePiCpuinfo(lines) {
-
- if (_rpi_cpuinfo === null) {
- _rpi_cpuinfo = lines;
- }
-
- // https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
-
- const oldRevisionCodes = {
- '0002': {
- type: 'B',
- revision: '1.0',
- memory: 256,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '0003': {
- type: 'B',
- revision: '1.0',
- memory: 256,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '0004': {
- type: 'B',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '0005': {
- type: 'B',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Qisda',
- processor: 'BCM2835'
- },
- '0006': {
- type: 'B',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '0007': {
- type: 'A',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '0008': {
- type: 'A',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '0009': {
- type: 'A',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Qisda',
- processor: 'BCM2835'
- },
- '000d': {
- type: 'B',
- revision: '2.0',
- memory: 512,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '000e': {
- type: 'B',
- revision: '2.0',
- memory: 512,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '000f': {
- type: 'B',
- revision: '2.0',
- memory: 512,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '0010': {
- type: 'B+',
- revision: '1.2',
- memory: 512,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '0011': {
- type: 'CM1',
- revision: '1.0',
- memory: 512,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '0012': {
- type: 'A+',
- revision: '1.1',
- memory: 256,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '0013': {
- type: 'B+',
- revision: '1.2',
- memory: 512,
- manufacturer: 'Embest',
- processor: 'BCM2835'
- },
- '0014': {
- type: 'CM1',
- revision: '1.0',
- memory: 512,
- manufacturer: 'Embest',
- processor: 'BCM2835'
- },
- '0015': {
- type: 'A+',
- revision: '1.1',
- memory: 256,
- manufacturer: '512MB Embest',
- processor: 'BCM2835'
- }
- };
-
- const processorList = [
- 'BCM2835',
- 'BCM2836',
- 'BCM2837',
- 'BCM2711',
- 'BCM2712',
- ];
- const manufacturerList = [
- 'Sony UK',
- 'Egoman',
- 'Embest',
- 'Sony Japan',
- 'Embest',
- 'Stadium'
- ];
- const typeList = {
- '00': 'A',
- '01': 'B',
- '02': 'A+',
- '03': 'B+',
- '04': '2B',
- '05': 'Alpha (early prototype)',
- '06': 'CM1',
- '08': '3B',
- '09': 'Zero',
- '0a': 'CM3',
- '0c': 'Zero W',
- '0d': '3B+',
- '0e': '3A+',
- '0f': 'Internal use only',
- '10': 'CM3+',
- '11': '4B',
- '12': 'Zero 2 W',
- '13': '400',
- '14': 'CM4',
- '15': 'CM4S',
- '16': 'Internal use only',
- '17': '5',
- '18': 'CM5',
- '19': '500',
- '1a': 'CM5 Lite',
- };
-
- const revisionCode = getValue(lines, 'revision', ':', true);
- const model = getValue(lines, 'model:', ':', true);
- const serial = getValue(lines, 'serial', ':', true);
-
- let result = {};
- if ({}.hasOwnProperty.call(oldRevisionCodes, revisionCode)) {
- // old revision codes
- result = {
- model,
- serial,
- revisionCode,
- memory: oldRevisionCodes[revisionCode].memory,
- manufacturer: oldRevisionCodes[revisionCode].manufacturer,
- processor: oldRevisionCodes[revisionCode].processor,
- type: oldRevisionCodes[revisionCode].type,
- revision: oldRevisionCodes[revisionCode].revision,
- };
-
- } else {
- // new revision code
- const revision = ('00000000' + getValue(lines, 'revision', ':', true).toLowerCase()).substr(-8);
- const memSizeCode = parseInt(hex2bin(revision.substr(2, 1)).substr(5, 3), 2) || 0;
- const manufacturer = manufacturerList[parseInt(revision.substr(3, 1), 10)];
- const processor = processorList[parseInt(revision.substr(4, 1), 10)];
- const typeCode = revision.substr(5, 2);
-
-
- result = {
- model,
- serial,
- revisionCode,
- memory: 256 * Math.pow(2, memSizeCode),
- manufacturer,
- processor,
- type: {}.hasOwnProperty.call(typeList, typeCode) ? typeList[typeCode] : '',
- revision: '1.' + revision.substr(7, 1),
- };
- }
- return result;
-}
-
-function getRpiGpu() {
- let cpuinfo = null;
- if (_rpi_cpuinfo !== null) {
- cpuinfo = _rpi_cpuinfo;
- } else {
- try {
- cpuinfo = fs.readFileSync('/proc/cpuinfo', { encoding: 'utf8' }).toString().split('\n');
- _rpi_cpuinfo = cpuinfo;
- } catch (e) {
- return false;
- }
- }
-
- const rpi = decodePiCpuinfo(cpuinfo);
- if (rpi.type === '4B' || rpi.type === 'CM4' || rpi.type === 'CM4S' || rpi.type === '400') { return 'VideoCore VI'; }
- if (rpi.type === '5') { return 'VideoCore VII'; }
- return 'VideoCore IV';
-}
-
-function promiseAll(promises) {
- const resolvingPromises = promises.map(function (promise) {
- return new Promise(function (resolve) {
- let payload = new Array(2);
- promise.then(function (result) {
- payload[0] = result;
- })
- .catch(function (error) {
- payload[1] = error;
- })
- .then(function () {
- // The wrapped Promise returns an array: 0 = result, 1 = error ... we resolve all
- resolve(payload);
- });
- });
- });
- const errors = [];
- const results = [];
-
- // Execute all wrapped Promises
- return Promise.all(resolvingPromises)
- .then(function (items) {
- items.forEach(function (payload) {
- if (payload[1]) {
- errors.push(payload[1]);
- results.push(null);
- } else {
- errors.push(null);
- results.push(payload[0]);
- }
- });
-
- return {
- errors: errors,
- results: results
- };
- });
-}
-
-function promisify(nodeStyleFunction) {
- return function () {
- const args = Array.prototype.slice.call(arguments);
- return new Promise(function (resolve, reject) {
- args.push(function (err, data) {
- if (err) {
- reject(err);
- } else {
- resolve(data);
- }
- });
- nodeStyleFunction.apply(null, args);
- });
- };
-}
-
-function promisifySave(nodeStyleFunction) {
- return function () {
- const args = Array.prototype.slice.call(arguments);
- return new Promise(function (resolve) {
- args.push(function (err, data) {
- resolve(data);
- });
- nodeStyleFunction.apply(null, args);
- });
- };
-}
-
-function linuxVersion() {
- let result = '';
- if (_linux) {
- try {
- result = execSync('uname -v', execOptsLinux).toString();
- } catch (e) {
- result = '';
- }
- }
- return result;
-}
-
-function plistParser(xmlStr) {
- const tags = ['array', 'dict', 'key', 'string', 'integer', 'date', 'real', 'data', 'boolean', 'arrayEmpty'];
- const startStr = '' && pos < len) {
- pos++;
- }
-
- let depth = 0;
- let inTagStart = false;
- let inTagContent = false;
- let inTagEnd = false;
- let metaData = [{ tagStart: '', tagEnd: '', tagContent: '', key: '', data: null }];
- let c = '';
- let cn = xmlStr[pos];
-
- while (pos < len) {
- c = cn;
- if (pos + 1 < len) { cn = xmlStr[pos + 1]; }
- if (c === '<') {
- inTagContent = false;
- if (cn === '/') { inTagEnd = true; }
- else if (metaData[depth].tagStart) {
- metaData[depth].tagContent = '';
- if (!metaData[depth].data) { metaData[depth].data = metaData[depth].tagStart === 'array' ? [] : {}; }
- depth++;
- metaData.push({ tagStart: '', tagEnd: '', tagContent: '', key: null, data: null });
- inTagStart = true;
- inTagContent = false;
- }
- else if (!inTagStart) { inTagStart = true; }
- } else if (c === '>') {
- if (metaData[depth].tagStart === 'true/') { inTagStart = false; inTagEnd = true; metaData[depth].tagStart = ''; metaData[depth].tagEnd = '/boolean'; metaData[depth].data = true; }
- if (metaData[depth].tagStart === 'false/') { inTagStart = false; inTagEnd = true; metaData[depth].tagStart = ''; metaData[depth].tagEnd = '/boolean'; metaData[depth].data = false; }
- if (metaData[depth].tagStart === 'array/') { inTagStart = false; inTagEnd = true; metaData[depth].tagStart = ''; metaData[depth].tagEnd = '/arrayEmpty'; metaData[depth].data = []; }
- if (inTagContent) { inTagContent = false; }
- if (inTagStart) {
- inTagStart = false;
- inTagContent = true;
- if (metaData[depth].tagStart === 'array') {
- metaData[depth].data = [];
- }
- if (metaData[depth].tagStart === 'dict') {
- metaData[depth].data = {};
- }
- }
- if (inTagEnd) {
- inTagEnd = false;
- if (metaData[depth].tagEnd && tags.indexOf(metaData[depth].tagEnd.substr(1)) >= 0) {
- if (metaData[depth].tagEnd === '/dict' || metaData[depth].tagEnd === '/array') {
- if (depth > 1 && metaData[depth - 2].tagStart === 'array') {
- metaData[depth - 2].data.push(metaData[depth - 1].data);
- }
- if (depth > 1 && metaData[depth - 2].tagStart === 'dict') {
- metaData[depth - 2].data[metaData[depth - 1].key] = metaData[depth - 1].data;
- }
- depth--;
- metaData.pop();
- metaData[depth].tagContent = '';
- metaData[depth].tagStart = '';
- metaData[depth].tagEnd = '';
- }
- else {
- if (metaData[depth].tagEnd === '/key' && metaData[depth].tagContent) {
- metaData[depth].key = metaData[depth].tagContent;
- } else {
- if (metaData[depth].tagEnd === '/real' && metaData[depth].tagContent) { metaData[depth].data = parseFloat(metaData[depth].tagContent) || 0; }
- if (metaData[depth].tagEnd === '/integer' && metaData[depth].tagContent) { metaData[depth].data = parseInt(metaData[depth].tagContent) || 0; }
- if (metaData[depth].tagEnd === '/string' && metaData[depth].tagContent) { metaData[depth].data = metaData[depth].tagContent || ''; }
- if (metaData[depth].tagEnd === '/boolean') { metaData[depth].data = metaData[depth].tagContent || false; }
- if (metaData[depth].tagEnd === '/arrayEmpty') { metaData[depth].data = metaData[depth].tagContent || []; }
- if (depth > 0 && metaData[depth - 1].tagStart === 'array') { metaData[depth - 1].data.push(metaData[depth].data); }
- if (depth > 0 && metaData[depth - 1].tagStart === 'dict') { metaData[depth - 1].data[metaData[depth].key] = metaData[depth].data; }
- }
- metaData[depth].tagContent = '';
- metaData[depth].tagStart = '';
- metaData[depth].tagEnd = '';
- }
- }
- metaData[depth].tagEnd = '';
- inTagStart = false;
- inTagContent = false;
- }
- } else {
- if (inTagStart) { metaData[depth].tagStart += c; }
- if (inTagEnd) { metaData[depth].tagEnd += c; }
- if (inTagContent) { metaData[depth].tagContent += c; }
- }
- pos++;
- }
- return metaData[0].data;
-}
-
-function strIsNumeric(str) {
- return typeof str === 'string' && !isNaN(str) && !isNaN(parseFloat(str));
-}
-
-function plistReader(output) {
- const lines = output.split('\n');
- for (let i = 0; i < lines.length; i++) {
- if (lines[i].indexOf(' = ') >= 0) {
- const lineParts = lines[i].split(' = ');
- lineParts[0] = lineParts[0].trim();
- if (!lineParts[0].startsWith('"')) {
- lineParts[0] = '"' + lineParts[0] + '"';
- }
- lineParts[1] = lineParts[1].trim();
- if (lineParts[1].indexOf('"') === -1 && lineParts[1].endsWith(';')) {
- const valueString = lineParts[1].substring(0, lineParts[1].length - 1);
- if (!strIsNumeric(valueString)) {
- lineParts[1] = `"${valueString}";`;
- }
- }
- if (lineParts[1].indexOf('"') >= 0 && lineParts[1].endsWith(';')) {
- const valueString = lineParts[1].substring(0, lineParts[1].length - 1).replace(/"/g, '');
- if (strIsNumeric(valueString)) {
- lineParts[1] = `${valueString};`;
- }
- }
- lines[i] = lineParts.join(' : ');
- }
- lines[i] = lines[i].replace(/\(/g, '[').replace(/\)/g, ']').replace(/;/g, ',').trim();
- if (lines[i].startsWith('}') && lines[i - 1] && lines[i - 1].endsWith(',')) {
- lines[i - 1] = lines[i - 1].substring(0, lines[i - 1].length - 1);
- }
- }
- output = lines.join('');
- let obj = {};
- try {
- obj = JSON.parse(output);
- } catch (e) {
- noop();
- }
- return obj;
-}
-
-function semverCompare(v1, v2) {
- let res = 0;
- const parts1 = v1.split('.');
- const parts2 = v2.split('.');
- if (parts1[0] < parts2[0]) { res = 1; }
- else if (parts1[0] > parts2[0]) { res = -1; }
- else if (parts1[0] === parts2[0] && parts1.length >= 2 && parts2.length >= 2) {
- if (parts1[1] < parts2[1]) { res = 1; }
- else if (parts1[1] > parts2[1]) { res = -1; }
- else if (parts1[1] === parts2[1]) {
- if (parts1.length >= 3 && parts2.length >= 3) {
- if (parts1[2] < parts2[2]) { res = 1; }
- else if (parts1[2] > parts2[2]) { res = -1; }
- } else if (parts2.length >= 3) {
- res = 1;
- }
- }
- }
- return res;
-}
-
-function getAppleModel(key) {
- const appleModelIds = [
- {
- key: 'Mac15,12',
- name: 'MacBook Air',
- size: '13-inch',
- processor: 'M3',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac14,15',
- name: 'MacBook Air',
- size: '15-inch',
- processor: 'M2',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac14,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: 'M2',
- year: '2022',
- additional: ''
- },
- {
- key: 'MacBookAir10,1',
- name: 'MacBook Air',
- size: '13-inch',
- processor: 'M1',
- year: '2020',
- additional: ''
- },
- {
- key: 'MacBookAir9,1',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: '2020',
- additional: ''
- },
- {
- key: 'MacBookAir8,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookAir8,1',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: '2018',
- additional: ''
- },
- {
- key: 'MacBookAir7,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: '2017',
- additional: ''
- },
- {
- key: 'MacBookAir7,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Early 2015',
- additional: ''
- },
- {
- key: 'MacBookAir7,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Early 2015',
- additional: ''
- },
- {
- key: 'MacBookAir6,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Early 2014',
- additional: ''
- },
- {
- key: 'MacBookAir6,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Early 2014',
- additional: ''
- },
- {
- key: 'MacBookAir6,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Mid 2013',
- additional: ''
- },
- {
- key: 'MacBookAir6,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Mid 2013',
- additional: ''
- },
- {
- key: 'MacBookAir5,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacBookAir5,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacBookAir4,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'MacBookAir4,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'MacBookAir3,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Late 2010',
- additional: ''
- },
- {
- key: 'MacBookAir3,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Late 2010',
- additional: ''
- },
- {
- key: 'MacBookAir2,1',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Mid 2009',
- additional: ''
- },
- {
- key: 'Mac16,1',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M4',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac16,6',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M4 Pro',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac16,8',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M4 Max',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac16,5',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M4 Pro',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac16,6',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M4 Max',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac15,3',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M3',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,6',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M3 Pro',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,8',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M3 Pro',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,10',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M3 Max',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,7',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M3 Pro',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,9',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M3 Pro',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,11',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M3 Max',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac14,5',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M2 Max',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,9',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M2 Max',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,6',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M2 Max',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,10',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M2 Max',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,7',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: 'M2',
- year: '2022',
- additional: ''
- },
- {
- key: 'MacBookPro18,3',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M1 Pro',
- year: '2021',
- additional: ''
- },
- {
- key: 'MacBookPro18,4',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M1 Max',
- year: '2021',
- additional: ''
- },
- {
- key: 'MacBookPro18,1',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M1 Pro',
- year: '2021',
- additional: ''
- },
- {
- key: 'MacBookPro18,2',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M1 Max',
- year: '2021',
- additional: ''
- },
- {
- key: 'MacBookPro17,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: 'M1',
- year: '2020',
- additional: ''
- },
- {
- key: 'MacBookPro16,3',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2020',
- additional: 'Two Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro16,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2020',
- additional: 'Four Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro16,1',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookPro16,4',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookPro15,3',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookPro15,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookPro15,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookPro15,4',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2019',
- additional: 'Two Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro15,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: '2018',
- additional: ''
- },
- {
- key: 'MacBookPro15,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2018',
- additional: 'Four Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro14,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2017',
- additional: 'Two Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro14,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2017',
- additional: 'Four Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro14,3',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: '2017',
- additional: ''
- },
- {
- key: 'MacBookPro13,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2016',
- additional: 'Two Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro13,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2016',
- additional: 'Four Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro13,3',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: '2016',
- additional: ''
- },
- {
- key: 'MacBookPro11,4',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2015',
- additional: ''
- },
- {
- key: 'MacBookPro11,5',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2015',
- additional: ''
- },
- {
- key: 'MacBookPro12,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Early 2015',
- additional: ''
- },
- {
- key: 'MacBookPro11,2',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'MacBookPro11,3',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'MacBookPro11,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'MacBookPro10,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacBookPro10,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Late 2012',
- additional: ''
- },
- {
- key: 'MacBookPro9,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacBookPro9,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacBookPro8,3',
- name: 'MacBook Pro',
- size: '17-inch',
- processor: '',
- year: 'Early 2011',
- additional: ''
- },
- {
- key: 'MacBookPro8,2',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Early 2011',
- additional: ''
- },
- {
- key: 'MacBookPro8,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Early 2011',
- additional: ''
- },
- {
- key: 'MacBookPro6,1',
- name: 'MacBook Pro',
- size: '17-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'MacBookPro6,2',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'MacBookPro7,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'MacBookPro5,2',
- name: 'MacBook Pro',
- size: '17-inch',
- processor: '',
- year: 'Early 2009',
- additional: ''
- },
- {
- key: 'MacBookPro5,3',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2009',
- additional: ''
- },
- {
- key: 'MacBookPro5,5',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Mid 2009',
- additional: ''
- },
- {
- key: 'MacBookPro5,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Late 2008',
- additional: ''
- },
- {
- key: 'MacBookPro4,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Early 2008',
- additional: ''
- },
- {
- key: 'MacBook10,1',
- name: 'MacBook',
- size: '12-inch',
- processor: '',
- year: '2017',
- additional: ''
- },
- {
- key: 'MacBook9,1',
- name: 'MacBook',
- size: '12-inch',
- processor: '',
- year: 'Early 2016',
- additional: ''
- },
- {
- key: 'MacBook8,1',
- name: 'MacBook',
- size: '12-inch',
- processor: '',
- year: 'Early 2015',
- additional: ''
- },
- {
- key: 'MacBook7,1',
- name: 'MacBook',
- size: '13-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'MacBook6,1',
- name: 'MacBook',
- size: '13-inch',
- processor: '',
- year: 'Late 2009',
- additional: ''
- },
- {
- key: 'MacBook5,2',
- name: 'MacBook',
- size: '13-inch',
- processor: '',
- year: 'Early 2009',
- additional: ''
- },
- {
- key: 'Mac14,13',
- name: 'Mac Studio',
- size: '',
- processor: '',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,14',
- name: 'Mac Studio',
- size: '',
- processor: '',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac13,1',
- name: 'Mac Studio',
- size: '',
- processor: '',
- year: '2022',
- additional: ''
- },
- {
- key: 'Mac13,2',
- name: 'Mac Studio',
- size: '',
- processor: '',
- year: '2022',
- additional: ''
- },
- {
- key: 'Mac16,11',
- name: 'Mac mini',
- size: '',
- processor: 'M4 Pro',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac16,10',
- name: 'Mac mini',
- size: '',
- processor: 'M4',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac14,3',
- name: 'Mac mini',
- size: '',
- processor: 'M2',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,12',
- name: 'Mac mini',
- size: '',
- processor: 'M2 Pro',
- year: '2023',
- additional: ''
- },
- {
- key: 'Macmini9,1',
- name: 'Mac mini',
- size: '',
- processor: 'M1',
- year: '2020',
- additional: ''
- },
- {
- key: 'Macmini8,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Late 2018',
- additional: ''
- },
- {
- key: 'Macmini7,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Late 2014',
- additional: ''
- },
- {
- key: 'Macmini6,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Late 2012',
- additional: ''
- },
- {
- key: 'Macmini6,2',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Late 2012',
- additional: ''
- },
- {
- key: 'Macmini5,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'Macmini5,2',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'Macmini4,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'Macmini3,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Early 2009',
- additional: ''
- },
- {
- key: 'Mac16,3',
- name: 'iMac',
- size: '24-inch',
- processor: 'M4',
- year: '2024',
- additional: 'Four ports'
- },
- {
- key: 'Mac16,2',
- name: 'iMac',
- size: '24-inch',
- processor: 'M4',
- year: '2024',
- additional: 'Two ports'
- },
- {
- key: 'Mac15,5',
- name: 'iMac',
- size: '24-inch',
- processor: 'M3',
- year: '2023',
- additional: 'Four ports'
- },
- {
- key: 'Mac15,4',
- name: 'iMac',
- size: '24-inch',
- processor: 'M3',
- year: '2023',
- additional: 'Two ports'
- },
- {
- key: 'iMac21,1',
- name: 'iMac',
- size: '24-inch',
- processor: 'M1',
- year: '2021',
- additional: ''
- },
- {
- key: 'iMac21,2',
- name: 'iMac',
- size: '24-inch',
- processor: 'M1',
- year: '2021',
- additional: ''
- },
- {
- key: 'iMac20,1',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: '2020',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac20,2',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: '2020',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac19,1',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: '2019',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac19,2',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: '2019',
- additional: 'Retina 4K'
- },
- {
- key: 'iMacPro1,1',
- name: 'iMac Pro',
- size: '',
- processor: '',
- year: '2017',
- additional: ''
- },
- {
- key: 'iMac18,3',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: '2017',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac18,2',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: '2017',
- additional: 'Retina 4K'
- },
- {
- key: 'iMac18,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: '2017',
- additional: ''
- },
- {
- key: 'iMac17,1',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Late 2015',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac16,2',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Late 2015',
- additional: 'Retina 4K'
- },
- {
- key: 'iMac16,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Late 2015',
- additional: ''
- },
- {
- key: 'iMac15,1',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Late 2014',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac14,4',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Mid 2014',
- additional: ''
- },
- {
- key: 'iMac14,2',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'iMac14,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'iMac13,2',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Late 2012',
- additional: ''
- },
- {
- key: 'iMac13,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Late 2012',
- additional: ''
- },
- {
- key: 'iMac12,2',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'iMac12,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'iMac11,3',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'iMac11,2',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'iMac10,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Late 2009',
- additional: ''
- },
- {
- key: 'iMac9,1',
- name: 'iMac',
- size: '20-inch',
- processor: '',
- year: 'Early 2009',
- additional: ''
- },
- {
- key: 'Mac14,8',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,8',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: '2023',
- additional: 'Rack'
- },
- {
- key: 'MacPro7,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacPro7,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: '2019',
- additional: 'Rack'
- },
- {
- key: 'MacPro6,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'MacPro5,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacPro5,1',
- name: 'Mac Pro Server',
- size: '',
- processor: '',
- year: 'Mid 2012',
- additional: 'Server'
- },
- {
- key: 'MacPro5,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: 'Mid 2010',
- additional: ''
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+
+/***/ }),
+
+/***/ 28775:
+/***/ ((__unused_webpack_module, exports) => {
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isValidErrorCode = exports.httpStatusFromErrorCode = exports.TwirpErrorCode = exports.BadRouteError = exports.InternalServerErrorWith = exports.InternalServerError = exports.RequiredArgumentError = exports.InvalidArgumentError = exports.NotFoundError = exports.TwirpError = void 0;
+/**
+ * Represents a twirp error
+ */
+class TwirpError extends Error {
+ constructor(code, msg) {
+ super(msg);
+ this.code = TwirpErrorCode.Internal;
+ this.meta = {};
+ this.code = code;
+ this.msg = msg;
+ Object.setPrototypeOf(this, TwirpError.prototype);
+ }
+ /**
+ * Adds a metadata kv to the error
+ * @param key
+ * @param value
+ */
+ withMeta(key, value) {
+ this.meta[key] = value;
+ return this;
+ }
+ /**
+ * Returns a single metadata value
+ * return "" if not found
+ * @param key
+ */
+ getMeta(key) {
+ return this.meta[key] || "";
+ }
+ /**
+ * Add the original error cause
+ * @param err
+ * @param addMeta
+ */
+ withCause(err, addMeta = false) {
+ this._originalCause = err;
+ if (addMeta) {
+ this.withMeta("cause", err.message);
+ }
+ return this;
+ }
+ cause() {
+ return this._originalCause;
+ }
+ /**
+ * Returns the error representation to JSON
+ */
+ toJSON() {
+ try {
+ return JSON.stringify({
+ code: this.code,
+ msg: this.msg,
+ meta: this.meta,
+ });
+ }
+ catch (e) {
+ return `{"code": "internal", "msg": "There was an error but it could not be serialized into JSON"}`;
+ }
+ }
+ /**
+ * Create a twirp error from an object
+ * @param obj
+ */
+ static fromObject(obj) {
+ const code = obj["code"] || TwirpErrorCode.Unknown;
+ const msg = obj["msg"] || "unknown";
+ const error = new TwirpError(code, msg);
+ if (obj["meta"]) {
+ Object.keys(obj["meta"]).forEach((key) => {
+ error.withMeta(key, obj["meta"][key]);
+ });
+ }
+ return error;
+ }
+}
+exports.TwirpError = TwirpError;
+/**
+ * NotFoundError constructor for the common NotFound error.
+ */
+class NotFoundError extends TwirpError {
+ constructor(msg) {
+ super(TwirpErrorCode.NotFound, msg);
+ }
+}
+exports.NotFoundError = NotFoundError;
+/**
+ * InvalidArgumentError constructor for the common InvalidArgument error. Can be
+ * used when an argument has invalid format, is a number out of range, is a bad
+ * option, etc).
+ */
+class InvalidArgumentError extends TwirpError {
+ constructor(argument, validationMsg) {
+ super(TwirpErrorCode.InvalidArgument, argument + " " + validationMsg);
+ this.withMeta("argument", argument);
+ }
+}
+exports.InvalidArgumentError = InvalidArgumentError;
+/**
+ * RequiredArgumentError is a more specific constructor for InvalidArgument
+ * error. Should be used when the argument is required (expected to have a
+ * non-zero value).
+ */
+class RequiredArgumentError extends InvalidArgumentError {
+ constructor(argument) {
+ super(argument, "is required");
+ }
+}
+exports.RequiredArgumentError = RequiredArgumentError;
+/**
+ * InternalError constructor for the common Internal error. Should be used to
+ * specify that something bad or unexpected happened.
+ */
+class InternalServerError extends TwirpError {
+ constructor(msg) {
+ super(TwirpErrorCode.Internal, msg);
+ }
+}
+exports.InternalServerError = InternalServerError;
+/**
+ * InternalErrorWith makes an internal error, wrapping the original error and using it
+ * for the error message, and with metadata "cause" with the original error type.
+ * This function is used by Twirp services to wrap non-Twirp errors as internal errors.
+ * The wrapped error can be extracted later with err.cause()
+ */
+class InternalServerErrorWith extends InternalServerError {
+ constructor(err) {
+ super(err.message);
+ this.withMeta("cause", err.name);
+ this.withCause(err);
+ }
+}
+exports.InternalServerErrorWith = InternalServerErrorWith;
+/**
+ * A standard BadRoute Error
+ */
+class BadRouteError extends TwirpError {
+ constructor(msg, method, url) {
+ super(TwirpErrorCode.BadRoute, msg);
+ this.withMeta("twirp_invalid_route", method + " " + url);
+ }
+}
+exports.BadRouteError = BadRouteError;
+var TwirpErrorCode;
+(function (TwirpErrorCode) {
+ // Canceled indicates the operation was cancelled (typically by the caller).
+ TwirpErrorCode["Canceled"] = "canceled";
+ // Unknown error. For example when handling errors raised by APIs that do not
+ // return enough error information.
+ TwirpErrorCode["Unknown"] = "unknown";
+ // InvalidArgument indicates client specified an invalid argument. It
+ // indicates arguments that are problematic regardless of the state of the
+ // system (i.e. a malformed file name, required argument, number out of range,
+ // etc.).
+ TwirpErrorCode["InvalidArgument"] = "invalid_argument";
+ // Malformed indicates an error occurred while decoding the client's request.
+ // This may mean that the message was encoded improperly, or that there is a
+ // disagreement in message format between the client and server.
+ TwirpErrorCode["Malformed"] = "malformed";
+ // DeadlineExceeded means operation expired before completion. For operations
+ // that change the state of the system, this error may be returned even if the
+ // operation has completed successfully (timeout).
+ TwirpErrorCode["DeadlineExceeded"] = "deadline_exceeded";
+ // NotFound means some requested entity was not found.
+ TwirpErrorCode["NotFound"] = "not_found";
+ // BadRoute means that the requested URL path wasn't routable to a Twirp
+ // service and method. This is returned by the generated server, and usually
+ // shouldn't be returned by applications. Instead, applications should use
+ // NotFound or Unimplemented.
+ TwirpErrorCode["BadRoute"] = "bad_route";
+ // AlreadyExists means an attempt to create an entity failed because one
+ // already exists.
+ TwirpErrorCode["AlreadyExists"] = "already_exists";
+ // PermissionDenied indicates the caller does not have permission to execute
+ // the specified operation. It must not be used if the caller cannot be
+ // identified (Unauthenticated).
+ TwirpErrorCode["PermissionDenied"] = "permission_denied";
+ // Unauthenticated indicates the request does not have valid authentication
+ // credentials for the operation.
+ TwirpErrorCode["Unauthenticated"] = "unauthenticated";
+ // ResourceExhausted indicates some resource has been exhausted, perhaps a
+ // per-user quota, or perhaps the entire file system is out of space.
+ TwirpErrorCode["ResourceExhausted"] = "resource_exhausted";
+ // FailedPrecondition indicates operation was rejected because the system is
+ // not in a state required for the operation's execution. For example, doing
+ // an rmdir operation on a directory that is non-empty, or on a non-directory
+ // object, or when having conflicting read-modify-write on the same resource.
+ TwirpErrorCode["FailedPrecondition"] = "failed_precondition";
+ // Aborted indicates the operation was aborted, typically due to a concurrency
+ // issue like sequencer check failures, transaction aborts, etc.
+ TwirpErrorCode["Aborted"] = "aborted";
+ // OutOfRange means operation was attempted past the valid range. For example,
+ // seeking or reading past end of a paginated collection.
+ //
+ // Unlike InvalidArgument, this error indicates a problem that may be fixed if
+ // the system state changes (i.e. adding more items to the collection).
+ //
+ // There is a fair bit of overlap between FailedPrecondition and OutOfRange.
+ // We recommend using OutOfRange (the more specific error) when it applies so
+ // that callers who are iterating through a space can easily look for an
+ // OutOfRange error to detect when they are done.
+ TwirpErrorCode["OutOfRange"] = "out_of_range";
+ // Unimplemented indicates operation is not implemented or not
+ // supported/enabled in this service.
+ TwirpErrorCode["Unimplemented"] = "unimplemented";
+ // Internal errors. When some invariants expected by the underlying system
+ // have been broken. In other words, something bad happened in the library or
+ // backend service. Do not confuse with HTTP Internal Server Error; an
+ // Internal error could also happen on the client code, i.e. when parsing a
+ // server response.
+ TwirpErrorCode["Internal"] = "internal";
+ // Unavailable indicates the service is currently unavailable. This is a most
+ // likely a transient condition and may be corrected by retrying with a
+ // backoff.
+ TwirpErrorCode["Unavailable"] = "unavailable";
+ // DataLoss indicates unrecoverable data loss or corruption.
+ TwirpErrorCode["DataLoss"] = "data_loss";
+})(TwirpErrorCode = exports.TwirpErrorCode || (exports.TwirpErrorCode = {}));
+// ServerHTTPStatusFromErrorCode maps a Twirp error type into a similar HTTP
+// response status. It is used by the Twirp server handler to set the HTTP
+// response status code. Returns 0 if the ErrorCode is invalid.
+function httpStatusFromErrorCode(code) {
+ switch (code) {
+ case TwirpErrorCode.Canceled:
+ return 408; // RequestTimeout
+ case TwirpErrorCode.Unknown:
+ return 500; // Internal Server Error
+ case TwirpErrorCode.InvalidArgument:
+ return 400; // BadRequest
+ case TwirpErrorCode.Malformed:
+ return 400; // BadRequest
+ case TwirpErrorCode.DeadlineExceeded:
+ return 408; // RequestTimeout
+ case TwirpErrorCode.NotFound:
+ return 404; // Not Found
+ case TwirpErrorCode.BadRoute:
+ return 404; // Not Found
+ case TwirpErrorCode.AlreadyExists:
+ return 409; // Conflict
+ case TwirpErrorCode.PermissionDenied:
+ return 403; // Forbidden
+ case TwirpErrorCode.Unauthenticated:
+ return 401; // Unauthorized
+ case TwirpErrorCode.ResourceExhausted:
+ return 429; // Too Many Requests
+ case TwirpErrorCode.FailedPrecondition:
+ return 412; // Precondition Failed
+ case TwirpErrorCode.Aborted:
+ return 409; // Conflict
+ case TwirpErrorCode.OutOfRange:
+ return 400; // Bad Request
+ case TwirpErrorCode.Unimplemented:
+ return 501; // Not Implemented
+ case TwirpErrorCode.Internal:
+ return 500; // Internal Server Error
+ case TwirpErrorCode.Unavailable:
+ return 503; // Service Unavailable
+ case TwirpErrorCode.DataLoss:
+ return 500; // Internal Server Error
+ default:
+ return 0; // Invalid!
+ }
+}
+exports.httpStatusFromErrorCode = httpStatusFromErrorCode;
+// IsValidErrorCode returns true if is one of the valid predefined constants.
+function isValidErrorCode(code) {
+ return httpStatusFromErrorCode(code) != 0;
+}
+exports.isValidErrorCode = isValidErrorCode;
+
+
+/***/ }),
+
+/***/ 70048:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+var __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Gateway = exports.Pattern = void 0;
+const querystring_1 = __nccwpck_require__(83480);
+const dotObject = __importStar(__nccwpck_require__(98749));
+const request_1 = __nccwpck_require__(21179);
+const errors_1 = __nccwpck_require__(28775);
+const http_client_1 = __nccwpck_require__(52503);
+const server_1 = __nccwpck_require__(1991);
+var Pattern;
+(function (Pattern) {
+ Pattern["POST"] = "post";
+ Pattern["GET"] = "get";
+ Pattern["PATCH"] = "patch";
+ Pattern["PUT"] = "put";
+ Pattern["DELETE"] = "delete";
+})(Pattern = exports.Pattern || (exports.Pattern = {}));
+/**
+ * The Gateway proxies http requests to Twirp Compliant
+ * handlers
+ */
+class Gateway {
+ constructor(routes) {
+ this.routes = routes;
+ }
+ /**
+ * Middleware that rewrite the current request
+ * to a Twirp compliant request
+ */
+ twirpRewrite(prefix = "/twirp") {
+ return (req, resp, next) => {
+ this.rewrite(req, resp, prefix)
+ .then(() => next())
+ .catch((e) => {
+ if (e instanceof errors_1.TwirpError) {
+ if (e.code !== errors_1.TwirpErrorCode.NotFound) {
+ server_1.writeError(resp, e);
+ }
+ else {
+ next();
+ }
+ }
+ });
+ };
+ }
+ /**
+ * Rewrite an incoming request to a Twirp compliant request
+ * @param req
+ * @param resp
+ * @param prefix
+ */
+ rewrite(req, resp, prefix = "/twirp") {
+ return __awaiter(this, void 0, void 0, function* () {
+ const [match, route] = this.matchRoute(req);
+ const body = yield this.prepareTwirpBody(req, match, route);
+ const twirpUrl = `${prefix}/${route.packageName}.${route.serviceName}/${route.methodName}`;
+ req.url = twirpUrl;
+ req.originalUrl = twirpUrl;
+ req.method = "POST";
+ req.headers["content-type"] = "application/json";
+ req.rawBody = Buffer.from(JSON.stringify(body));
+ if (route.responseBodyKey) {
+ const endFn = resp.end.bind(resp);
+ resp.end = function (chunk) {
+ if (resp.statusCode === 200) {
+ endFn(`{ "${route.responseBodyKey}": ${chunk} }`);
+ }
+ else {
+ endFn(chunk);
+ }
+ };
+ }
+ });
+ }
+ /**
+ * Create a reverse proxy handler to
+ * proxy http requests to Twirp Compliant handlers
+ * @param httpClientOption
+ */
+ reverseProxy(httpClientOption) {
+ const client = http_client_1.NodeHttpRPC(httpClientOption);
+ return (req, res) => __awaiter(this, void 0, void 0, function* () {
+ try {
+ const [match, route] = this.matchRoute(req);
+ const body = yield this.prepareTwirpBody(req, match, route);
+ const response = yield client.request(`${route.packageName}.${route.serviceName}`, route.methodName, "application/json", body);
+ res.statusCode = 200;
+ res.setHeader("content-type", "application/json");
+ let jsonResponse;
+ if (route.responseBodyKey) {
+ jsonResponse = JSON.stringify({ [route.responseBodyKey]: response });
+ }
+ else {
+ jsonResponse = JSON.stringify(response);
+ }
+ res.end(jsonResponse);
+ }
+ catch (e) {
+ server_1.writeError(res, e);
+ }
+ });
+ }
+ /**
+ * Prepares twirp body requests using http.google.annotions
+ * compliant spec
+ *
+ * @param req
+ * @param match
+ * @param route
+ * @protected
+ */
+ prepareTwirpBody(req, match, route) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const _a = match.params, { query_string } = _a, params = __rest(_a, ["query_string"]);
+ let requestBody = Object.assign({}, params);
+ if (query_string && route.bodyKey !== "*") {
+ const queryParams = this.parseQueryString(query_string);
+ requestBody = Object.assign(Object.assign({}, queryParams), requestBody);
+ }
+ let body = {};
+ if (route.bodyKey) {
+ const data = yield request_1.getRequestData(req);
+ try {
+ const jsonBody = JSON.parse(data.toString() || "{}");
+ if (route.bodyKey === "*") {
+ body = jsonBody;
+ }
+ else {
+ body[route.bodyKey] = jsonBody;
+ }
+ }
+ catch (e) {
+ const msg = "the json request could not be decoded";
+ throw new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
+ }
+ }
+ return Object.assign(Object.assign({}, body), requestBody);
+ });
+ }
+ /**
+ * Matches a route
+ * @param req
+ */
+ matchRoute(req) {
+ var _a;
+ const httpMethod = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toLowerCase();
+ if (!httpMethod) {
+ throw new errors_1.BadRouteError(`method not allowed`, req.method || "", req.url || "");
+ }
+ const routes = this.routes[httpMethod];
+ for (const route of routes) {
+ const match = route.matcher(req.url || "/");
+ if (match) {
+ return [match, route];
+ }
+ }
+ throw new errors_1.NotFoundError(`url ${req.url} not found`);
+ }
+ /**
+ * Parse query string
+ * @param queryString
+ */
+ parseQueryString(queryString) {
+ const queryParams = querystring_1.parse(queryString.replace("?", ""));
+ return dotObject.object(queryParams);
+ }
+}
+exports.Gateway = Gateway;
+
+
+/***/ }),
+
+/***/ 99462:
+/***/ (function(__unused_webpack_module, exports) {
+
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isHook = exports.chainHooks = void 0;
+// ChainHooks creates a new ServerHook which chains the callbacks in
+// each of the constituent hooks passed in. Each hook function will be
+// called in the order of the ServerHooks values passed in.
+//
+// For the erroring hooks, RequestReceived and RequestRouted, any returned
+// errors prevent processing by later hooks.
+function chainHooks(...hooks) {
+ if (hooks.length === 0) {
+ return null;
+ }
+ if (hooks.length === 1) {
+ return hooks[0];
+ }
+ const serverHook = {
+ requestReceived(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestReceived) {
+ continue;
+ }
+ yield hook.requestReceived(ctx);
+ }
+ });
+ },
+ requestPrepared(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestPrepared) {
+ continue;
+ }
+ console.warn("hook requestPrepared is deprecated and will be removed in the next release. " +
+ "Please use responsePrepared instead.");
+ yield hook.requestPrepared(ctx);
+ }
+ });
+ },
+ responsePrepared(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.responsePrepared) {
+ continue;
+ }
+ yield hook.responsePrepared(ctx);
+ }
+ });
+ },
+ requestSent(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestSent) {
+ continue;
+ }
+ console.warn("hook requestSent is deprecated and will be removed in the next release. " +
+ "Please use responseSent instead.");
+ yield hook.requestSent(ctx);
+ }
+ });
+ },
+ responseSent(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.responseSent) {
+ continue;
+ }
+ yield hook.responseSent(ctx);
+ }
+ });
+ },
+ requestRouted(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestRouted) {
+ continue;
+ }
+ yield hook.requestRouted(ctx);
+ }
+ });
+ },
+ error(ctx, err) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.error) {
+ continue;
+ }
+ yield hook.error(ctx, err);
+ }
+ });
+ },
+ };
+ return serverHook;
+}
+exports.chainHooks = chainHooks;
+function isHook(object) {
+ return ("requestReceived" in object ||
+ "requestPrepared" in object ||
+ "requestSent" in object ||
+ "requestRouted" in object ||
+ "responsePrepared" in object ||
+ "responseSent" in object ||
+ "error" in object);
+}
+exports.isHook = isHook;
+
+
+/***/ }),
+
+/***/ 52503:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.FetchRPC = exports.wrapErrorResponseToTwirpError = exports.NodeHttpRPC = void 0;
+const http = __importStar(__nccwpck_require__(58611));
+const https = __importStar(__nccwpck_require__(65692));
+const url_1 = __nccwpck_require__(87016);
+const errors_1 = __nccwpck_require__(28775);
+/**
+ * a node HTTP RPC implementation
+ * @param options
+ * @constructor
+ */
+const NodeHttpRPC = (options) => ({
+ request(service, method, contentType, data) {
+ let client;
+ return new Promise((resolve, rejected) => {
+ const responseChunks = [];
+ const requestData = contentType === "application/protobuf"
+ ? Buffer.from(data)
+ : JSON.stringify(data);
+ const url = new url_1.URL(options.baseUrl);
+ const isHttps = url.protocol === "https:";
+ if (isHttps) {
+ client = https;
+ }
+ else {
+ client = http;
+ }
+ const prefix = url.pathname !== "/" ? url.pathname : "";
+ const req = client
+ .request(Object.assign(Object.assign({}, (options ? options : {})), { method: "POST", protocol: url.protocol, host: url.hostname, port: url.port ? url.port : isHttps ? 443 : 80, path: `${prefix}/${service}/${method}`, headers: Object.assign(Object.assign({}, (options.headers ? options.headers : {})), { "Content-Type": contentType, "Content-Length": contentType === "application/protobuf"
+ ? Buffer.byteLength(requestData)
+ : Buffer.from(requestData).byteLength }) }), (res) => {
+ res.on("data", (chunk) => responseChunks.push(chunk));
+ res.on("end", () => {
+ const data = Buffer.concat(responseChunks);
+ if (res.statusCode != 200) {
+ rejected(wrapErrorResponseToTwirpError(data.toString()));
+ }
+ else {
+ if (contentType === "application/json") {
+ resolve(JSON.parse(data.toString()));
+ }
+ else {
+ resolve(data);
+ }
+ }
+ });
+ res.on("error", (err) => {
+ rejected(err);
+ });
+ })
+ .on("error", (err) => {
+ rejected(err);
+ });
+ req.end(requestData);
+ });
},
- {
- key: 'MacPro5,1',
- name: 'Mac Pro Server',
- size: '',
- processor: '',
- year: 'Mid 2010',
- additional: 'Server'
+});
+exports.NodeHttpRPC = NodeHttpRPC;
+function wrapErrorResponseToTwirpError(errorResponse) {
+ return errors_1.TwirpError.fromObject(JSON.parse(errorResponse));
+}
+exports.wrapErrorResponseToTwirpError = wrapErrorResponseToTwirpError;
+/**
+ * a browser fetch RPC implementation
+ */
+const FetchRPC = (options) => ({
+ request(service, method, contentType, data) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const headers = new Headers(options.headers);
+ headers.set("content-type", contentType);
+ const response = yield fetch(`${options.baseUrl}/${service}/${method}`, Object.assign(Object.assign({}, options), { method: "POST", headers, body: data instanceof Uint8Array ? data : JSON.stringify(data) }));
+ if (response.status === 200) {
+ if (contentType === "application/json") {
+ return yield response.json();
+ }
+ return new Uint8Array(yield response.arrayBuffer());
+ }
+ throw errors_1.TwirpError.fromObject(yield response.json());
+ });
},
- {
- key: 'MacPro4,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: 'Early 2009',
- additional: ''
+});
+exports.FetchRPC = FetchRPC;
+
+
+/***/ }),
+
+/***/ 33874:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __exportStar = (this && this.__exportStar) || function(m, exports) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TwirpContentType = void 0;
+__exportStar(__nccwpck_require__(99069), exports);
+__exportStar(__nccwpck_require__(1991), exports);
+__exportStar(__nccwpck_require__(51816), exports);
+__exportStar(__nccwpck_require__(99462), exports);
+__exportStar(__nccwpck_require__(28775), exports);
+__exportStar(__nccwpck_require__(70048), exports);
+__exportStar(__nccwpck_require__(52503), exports);
+var request_1 = __nccwpck_require__(21179);
+Object.defineProperty(exports, "TwirpContentType", ({ enumerable: true, get: function () { return request_1.TwirpContentType; } }));
+
+
+/***/ }),
+
+/***/ 51816:
+/***/ (function(__unused_webpack_module, exports) {
+
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.chainInterceptors = void 0;
+// chains multiple Interceptors into a single Interceptor.
+// The first interceptor wraps the second one, and so on.
+// Returns null if interceptors is empty.
+function chainInterceptors(...interceptors) {
+ if (interceptors.length === 0) {
+ return;
+ }
+ if (interceptors.length === 1) {
+ return interceptors[0];
+ }
+ const first = interceptors[0];
+ return (ctx, request, handler) => __awaiter(this, void 0, void 0, function* () {
+ let next = handler;
+ for (let i = interceptors.length - 1; i > 0; i--) {
+ next = ((next) => (ctx, typedRequest) => {
+ return interceptors[i](ctx, typedRequest, next);
+ })(next);
+ }
+ return first(ctx, request, next);
+ });
+}
+exports.chainInterceptors = chainInterceptors;
+
+
+/***/ }),
+
+/***/ 21179:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseTwirpPath = exports.getRequestData = exports.validateRequest = exports.getContentType = exports.TwirpContentType = void 0;
+const errors_1 = __nccwpck_require__(28775);
+/**
+ * Supported Twirp Content-Type
+ */
+var TwirpContentType;
+(function (TwirpContentType) {
+ TwirpContentType[TwirpContentType["Protobuf"] = 0] = "Protobuf";
+ TwirpContentType[TwirpContentType["JSON"] = 1] = "JSON";
+ TwirpContentType[TwirpContentType["Unknown"] = 2] = "Unknown";
+})(TwirpContentType = exports.TwirpContentType || (exports.TwirpContentType = {}));
+/**
+ * Get supported content-type
+ * @param mimeType
+ */
+function getContentType(mimeType) {
+ switch (mimeType) {
+ case "application/protobuf":
+ return TwirpContentType.Protobuf;
+ case "application/json":
+ return TwirpContentType.JSON;
+ default:
+ return TwirpContentType.Unknown;
+ }
+}
+exports.getContentType = getContentType;
+/**
+ * Validate a twirp request
+ * @param ctx
+ * @param request
+ * @param pathPrefix
+ */
+function validateRequest(ctx, request, pathPrefix) {
+ if (request.method !== "POST") {
+ const msg = `unsupported method ${request.method} (only POST is allowed)`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ const path = parseTwirpPath(request.url || "");
+ if (path.pkgService !==
+ (ctx.packageName ? ctx.packageName + "." : "") + ctx.serviceName) {
+ const msg = `no handler for path ${request.url}`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ if (path.prefix !== pathPrefix) {
+ const msg = `invalid path prefix ${path.prefix}, expected ${pathPrefix}, on path ${request.url}`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ const mimeContentType = request.headers["content-type"] || "";
+ if (ctx.contentType === TwirpContentType.Unknown) {
+ const msg = `unexpected Content-Type: ${request.headers["content-type"]}`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ return Object.assign(Object.assign({}, path), { mimeContentType, contentType: ctx.contentType });
+}
+exports.validateRequest = validateRequest;
+/**
+ * Get request data from the body
+ * @param req
+ */
+function getRequestData(req) {
+ return new Promise((resolve, reject) => {
+ const reqWithRawBody = req;
+ if (reqWithRawBody.rawBody instanceof Buffer) {
+ resolve(reqWithRawBody.rawBody);
+ return;
+ }
+ const chunks = [];
+ req.on("data", (chunk) => chunks.push(chunk));
+ req.on("end", () => __awaiter(this, void 0, void 0, function* () {
+ const data = Buffer.concat(chunks);
+ resolve(data);
+ }));
+ req.on("error", (err) => {
+ if (req.aborted) {
+ reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.DeadlineExceeded, "failed to read request: deadline exceeded"));
+ }
+ else {
+ reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, err.message).withCause(err));
+ }
+ });
+ req.on("close", () => {
+ reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Canceled, "failed to read request: context canceled"));
+ });
+ });
+}
+exports.getRequestData = getRequestData;
+/**
+ * Parses twirp url path
+ * @param path
+ */
+function parseTwirpPath(path) {
+ const parts = path.split("/");
+ if (parts.length < 2) {
+ return {
+ pkgService: "",
+ method: "",
+ prefix: "",
+ };
+ }
+ return {
+ method: parts[parts.length - 1],
+ pkgService: parts[parts.length - 2],
+ prefix: parts.slice(0, parts.length - 2).join("/"),
+ };
+}
+exports.parseTwirpPath = parseTwirpPath;
+
+
+/***/ }),
+
+/***/ 1991:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.writeError = exports.TwirpServer = void 0;
+const hooks_1 = __nccwpck_require__(99462);
+const request_1 = __nccwpck_require__(21179);
+const errors_1 = __nccwpck_require__(28775);
+/**
+ * Runtime server implementation of a TwirpServer
+ */
+class TwirpServer {
+ constructor(options) {
+ this.pathPrefix = "/twirp";
+ this.hooks = [];
+ this.interceptors = [];
+ this.packageName = options.packageName;
+ this.serviceName = options.serviceName;
+ this.methodList = options.methodList;
+ this.matchRoute = options.matchRoute;
+ this.service = options.service;
+ }
+ /**
+ * Returns the prefix for this server
+ */
+ get prefix() {
+ return this.pathPrefix;
+ }
+ /**
+ * The http handler for twirp complaint endpoints
+ * @param options
+ */
+ httpHandler(options) {
+ return (req, resp) => {
+ // setup prefix
+ if ((options === null || options === void 0 ? void 0 : options.prefix) !== undefined) {
+ this.withPrefix(options.prefix);
+ }
+ return this._httpHandler(req, resp);
+ };
+ }
+ /**
+ * Adds interceptors or hooks to the request stack
+ * @param middlewares
+ */
+ use(...middlewares) {
+ middlewares.forEach((middleware) => {
+ if (hooks_1.isHook(middleware)) {
+ this.hooks.push(middleware);
+ return this;
+ }
+ this.interceptors.push(middleware);
+ });
+ return this;
+ }
+ /**
+ * Adds a prefix to the service url path
+ * @param prefix
+ */
+ withPrefix(prefix) {
+ if (prefix === false) {
+ this.pathPrefix = "";
+ }
+ else {
+ this.pathPrefix = prefix;
+ }
+ return this;
+ }
+ /**
+ * Returns the regex matching path for this twirp server
+ */
+ matchingPath() {
+ const baseRegex = this.baseURI().replace(/\./g, "\\.");
+ return new RegExp(`${baseRegex}\/(${this.methodList.join("|")})`);
+ }
+ /**
+ * Returns the base URI for this twirp server
+ */
+ baseURI() {
+ return `${this.pathPrefix}/${this.packageName ? this.packageName + "." : ""}${this.serviceName}`;
+ }
+ /**
+ * Create a twirp context
+ * @param req
+ * @param res
+ * @private
+ */
+ createContext(req, res) {
+ return {
+ packageName: this.packageName,
+ serviceName: this.serviceName,
+ methodName: "",
+ contentType: request_1.getContentType(req.headers["content-type"]),
+ req: req,
+ res: res,
+ };
+ }
+ /**
+ * Twrip server http handler implementation
+ * @param req
+ * @param resp
+ * @private
+ */
+ _httpHandler(req, resp) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const ctx = this.createContext(req, resp);
+ try {
+ yield this.invokeHook("requestReceived", ctx);
+ const { method, mimeContentType } = request_1.validateRequest(ctx, req, this.pathPrefix || "");
+ const handler = this.matchRoute(method, {
+ onMatch: (ctx) => {
+ return this.invokeHook("requestRouted", ctx);
+ },
+ onNotFound: () => {
+ const msg = `no handler for path ${req.url}`;
+ throw new errors_1.BadRouteError(msg, req.method || "", req.url || "");
+ },
+ });
+ const body = yield request_1.getRequestData(req);
+ const response = yield handler(ctx, this.service, body, this.interceptors);
+ yield Promise.all([
+ this.invokeHook("responsePrepared", ctx),
+ // keep backwards compatibility till next release
+ this.invokeHook("requestPrepared", ctx),
+ ]);
+ resp.statusCode = 200;
+ resp.setHeader("Content-Type", mimeContentType);
+ resp.end(response);
+ }
+ catch (e) {
+ yield this.invokeHook("error", ctx, mustBeTwirpError(e));
+ if (!resp.headersSent) {
+ writeError(resp, e);
+ }
+ }
+ finally {
+ yield Promise.all([
+ this.invokeHook("responseSent", ctx),
+ // keep backwards compatibility till next release
+ this.invokeHook("requestSent", ctx),
+ ]);
+ }
+ });
+ }
+ /**
+ * Invoke a hook
+ * @param hookName
+ * @param ctx
+ * @param err
+ * @protected
+ */
+ invokeHook(hookName, ctx, err) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (this.hooks.length === 0) {
+ return;
+ }
+ const chainedHooks = hooks_1.chainHooks(...this.hooks);
+ const hook = chainedHooks === null || chainedHooks === void 0 ? void 0 : chainedHooks[hookName];
+ if (hook) {
+ yield hook(ctx, err || new errors_1.InternalServerError("internal server error"));
+ }
+ });
+ }
+}
+exports.TwirpServer = TwirpServer;
+/**
+ * Write http error response
+ * @param res
+ * @param error
+ */
+function writeError(res, error) {
+ const twirpError = mustBeTwirpError(error);
+ res.setHeader("Content-Type", "application/json");
+ res.statusCode = errors_1.httpStatusFromErrorCode(twirpError.code);
+ res.end(twirpError.toJSON());
+}
+exports.writeError = writeError;
+/**
+ * Make sure that the error passed is a TwirpError
+ * otherwise it will wrap it into an InternalError
+ * @param err
+ */
+function mustBeTwirpError(err) {
+ if (err instanceof errors_1.TwirpError) {
+ return err;
+ }
+ return new errors_1.InternalServerErrorWith(err);
+}
+
+
+/***/ }),
+
+/***/ 61684:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const Client = __nccwpck_require__(45513)
+const Dispatcher = __nccwpck_require__(20303)
+const errors = __nccwpck_require__(53959)
+const Pool = __nccwpck_require__(44288)
+const BalancedPool = __nccwpck_require__(95377)
+const Agent = __nccwpck_require__(92121)
+const util = __nccwpck_require__(89500)
+const { InvalidArgumentError } = errors
+const api = __nccwpck_require__(82531)
+const buildConnector = __nccwpck_require__(91332)
+const MockClient = __nccwpck_require__(72361)
+const MockAgent = __nccwpck_require__(77017)
+const MockPool = __nccwpck_require__(36480)
+const mockErrors = __nccwpck_require__(12673)
+const ProxyAgent = __nccwpck_require__(79276)
+const RetryHandler = __nccwpck_require__(49569)
+const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(61481)
+const DecoratorHandler = __nccwpck_require__(41468)
+const RedirectHandler = __nccwpck_require__(8591)
+const createRedirectInterceptor = __nccwpck_require__(99299)
+
+let hasCrypto
+try {
+ __nccwpck_require__(76982)
+ hasCrypto = true
+} catch {
+ hasCrypto = false
+}
+
+Object.assign(Dispatcher.prototype, api)
+
+module.exports.Dispatcher = Dispatcher
+module.exports.Client = Client
+module.exports.Pool = Pool
+module.exports.BalancedPool = BalancedPool
+module.exports.Agent = Agent
+module.exports.ProxyAgent = ProxyAgent
+module.exports.RetryHandler = RetryHandler
+
+module.exports.DecoratorHandler = DecoratorHandler
+module.exports.RedirectHandler = RedirectHandler
+module.exports.createRedirectInterceptor = createRedirectInterceptor
+
+module.exports.buildConnector = buildConnector
+module.exports.errors = errors
+
+function makeDispatcher (fn) {
+ return (url, opts, handler) => {
+ if (typeof opts === 'function') {
+ handler = opts
+ opts = null
+ }
+
+ if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
+ throw new InvalidArgumentError('invalid url')
+ }
+
+ if (opts != null && typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ if (opts && opts.path != null) {
+ if (typeof opts.path !== 'string') {
+ throw new InvalidArgumentError('invalid opts.path')
+ }
+
+ let path = opts.path
+ if (!opts.path.startsWith('/')) {
+ path = `/${path}`
+ }
+
+ url = new URL(util.parseOrigin(url).origin + path)
+ } else {
+ if (!opts) {
+ opts = typeof url === 'object' ? url : {}
+ }
+
+ url = util.parseURL(url)
+ }
+
+ const { agent, dispatcher = getGlobalDispatcher() } = opts
+
+ if (agent) {
+ throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
+ }
+
+ return fn.call(dispatcher, {
+ ...opts,
+ origin: url.origin,
+ path: url.search ? `${url.pathname}${url.search}` : url.pathname,
+ method: opts.method || (opts.body ? 'PUT' : 'GET')
+ }, handler)
+ }
+}
+
+module.exports.setGlobalDispatcher = setGlobalDispatcher
+module.exports.getGlobalDispatcher = getGlobalDispatcher
+
+if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {
+ let fetchImpl = null
+ module.exports.fetch = async function fetch (resource) {
+ if (!fetchImpl) {
+ fetchImpl = (__nccwpck_require__(11503).fetch)
+ }
+
+ try {
+ return await fetchImpl(...arguments)
+ } catch (err) {
+ if (typeof err === 'object') {
+ Error.captureStackTrace(err, this)
+ }
+
+ throw err
+ }
+ }
+ module.exports.Headers = __nccwpck_require__(12801).Headers
+ module.exports.Response = __nccwpck_require__(89928).Response
+ module.exports.Request = __nccwpck_require__(2630).Request
+ module.exports.FormData = __nccwpck_require__(47453).FormData
+ module.exports.File = __nccwpck_require__(17005).File
+ module.exports.FileReader = __nccwpck_require__(30052).FileReader
+
+ const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(62896)
+
+ module.exports.setGlobalOrigin = setGlobalOrigin
+ module.exports.getGlobalOrigin = getGlobalOrigin
+
+ const { CacheStorage } = __nccwpck_require__(66446)
+ const { kConstruct } = __nccwpck_require__(68652)
+
+ // Cache & CacheStorage are tightly coupled with fetch. Even if it may run
+ // in an older version of Node, it doesn't have any use without fetch.
+ module.exports.caches = new CacheStorage(kConstruct)
+}
+
+if (util.nodeMajor >= 16) {
+ const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(64276)
+
+ module.exports.deleteCookie = deleteCookie
+ module.exports.getCookies = getCookies
+ module.exports.getSetCookies = getSetCookies
+ module.exports.setCookie = setCookie
+
+ const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
+
+ module.exports.parseMIMEType = parseMIMEType
+ module.exports.serializeAMimeType = serializeAMimeType
+}
+
+if (util.nodeMajor >= 18 && hasCrypto) {
+ const { WebSocket } = __nccwpck_require__(90551)
+
+ module.exports.WebSocket = WebSocket
+}
+
+module.exports.request = makeDispatcher(api.request)
+module.exports.stream = makeDispatcher(api.stream)
+module.exports.pipeline = makeDispatcher(api.pipeline)
+module.exports.connect = makeDispatcher(api.connect)
+module.exports.upgrade = makeDispatcher(api.upgrade)
+
+module.exports.MockClient = MockClient
+module.exports.MockPool = MockPool
+module.exports.MockAgent = MockAgent
+module.exports.mockErrors = mockErrors
+
+
+/***/ }),
+
+/***/ 92121:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { InvalidArgumentError } = __nccwpck_require__(53959)
+const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(68031)
+const DispatcherBase = __nccwpck_require__(52421)
+const Pool = __nccwpck_require__(44288)
+const Client = __nccwpck_require__(45513)
+const util = __nccwpck_require__(89500)
+const createRedirectInterceptor = __nccwpck_require__(99299)
+const { WeakRef, FinalizationRegistry } = __nccwpck_require__(90022)()
+
+const kOnConnect = Symbol('onConnect')
+const kOnDisconnect = Symbol('onDisconnect')
+const kOnConnectionError = Symbol('onConnectionError')
+const kMaxRedirections = Symbol('maxRedirections')
+const kOnDrain = Symbol('onDrain')
+const kFactory = Symbol('factory')
+const kFinalizer = Symbol('finalizer')
+const kOptions = Symbol('options')
+
+function defaultFactory (origin, opts) {
+ return opts && opts.connections === 1
+ ? new Client(origin, opts)
+ : new Pool(origin, opts)
+}
+
+class Agent extends DispatcherBase {
+ constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
+ super()
+
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
+ }
+
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
+ }
+
+ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
+ }
+
+ if (connect && typeof connect !== 'function') {
+ connect = { ...connect }
+ }
+
+ this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)
+ ? options.interceptors.Agent
+ : [createRedirectInterceptor({ maxRedirections })]
+
+ this[kOptions] = { ...util.deepClone(options), connect }
+ this[kOptions].interceptors = options.interceptors
+ ? { ...options.interceptors }
+ : undefined
+ this[kMaxRedirections] = maxRedirections
+ this[kFactory] = factory
+ this[kClients] = new Map()
+ this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {
+ const ref = this[kClients].get(key)
+ if (ref !== undefined && ref.deref() === undefined) {
+ this[kClients].delete(key)
+ }
+ })
+
+ const agent = this
+
+ this[kOnDrain] = (origin, targets) => {
+ agent.emit('drain', origin, [agent, ...targets])
+ }
+
+ this[kOnConnect] = (origin, targets) => {
+ agent.emit('connect', origin, [agent, ...targets])
+ }
+
+ this[kOnDisconnect] = (origin, targets, err) => {
+ agent.emit('disconnect', origin, [agent, ...targets], err)
+ }
+
+ this[kOnConnectionError] = (origin, targets, err) => {
+ agent.emit('connectionError', origin, [agent, ...targets], err)
+ }
+ }
+
+ get [kRunning] () {
+ let ret = 0
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore next: gc is undeterministic */
+ if (client) {
+ ret += client[kRunning]
+ }
+ }
+ return ret
+ }
+
+ [kDispatch] (opts, handler) {
+ let key
+ if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
+ key = String(opts.origin)
+ } else {
+ throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
+ }
+
+ const ref = this[kClients].get(key)
+
+ let dispatcher = ref ? ref.deref() : null
+ if (!dispatcher) {
+ dispatcher = this[kFactory](opts.origin, this[kOptions])
+ .on('drain', this[kOnDrain])
+ .on('connect', this[kOnConnect])
+ .on('disconnect', this[kOnDisconnect])
+ .on('connectionError', this[kOnConnectionError])
+
+ this[kClients].set(key, new WeakRef(dispatcher))
+ this[kFinalizer].register(dispatcher, key)
+ }
+
+ return dispatcher.dispatch(opts, handler)
+ }
+
+ async [kClose] () {
+ const closePromises = []
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore else: gc is undeterministic */
+ if (client) {
+ closePromises.push(client.close())
+ }
+ }
+
+ await Promise.all(closePromises)
+ }
+
+ async [kDestroy] (err) {
+ const destroyPromises = []
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore else: gc is undeterministic */
+ if (client) {
+ destroyPromises.push(client.destroy(err))
+ }
+ }
+
+ await Promise.all(destroyPromises)
+ }
+}
+
+module.exports = Agent
+
+
+/***/ }),
+
+/***/ 52730:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const { addAbortListener } = __nccwpck_require__(89500)
+const { RequestAbortedError } = __nccwpck_require__(53959)
+
+const kListener = Symbol('kListener')
+const kSignal = Symbol('kSignal')
+
+function abort (self) {
+ if (self.abort) {
+ self.abort()
+ } else {
+ self.onError(new RequestAbortedError())
+ }
+}
+
+function addSignal (self, signal) {
+ self[kSignal] = null
+ self[kListener] = null
+
+ if (!signal) {
+ return
+ }
+
+ if (signal.aborted) {
+ abort(self)
+ return
+ }
+
+ self[kSignal] = signal
+ self[kListener] = () => {
+ abort(self)
+ }
+
+ addAbortListener(self[kSignal], self[kListener])
+}
+
+function removeSignal (self) {
+ if (!self[kSignal]) {
+ return
+ }
+
+ if ('removeEventListener' in self[kSignal]) {
+ self[kSignal].removeEventListener('abort', self[kListener])
+ } else {
+ self[kSignal].removeListener('abort', self[kListener])
+ }
+
+ self[kSignal] = null
+ self[kListener] = null
+}
+
+module.exports = {
+ addSignal,
+ removeSignal
+}
+
+
+/***/ }),
+
+/***/ 73192:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { AsyncResource } = __nccwpck_require__(90290)
+const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { addSignal, removeSignal } = __nccwpck_require__(52730)
+
+class ConnectHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
+
+ const { signal, opaque, responseHeaders } = opts
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ super('UNDICI_CONNECT')
+
+ this.opaque = opaque || null
+ this.responseHeaders = responseHeaders || null
+ this.callback = callback
+ this.abort = null
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
+
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders () {
+ throw new SocketError('bad connect', null)
+ }
+
+ onUpgrade (statusCode, rawHeaders, socket) {
+ const { callback, opaque, context } = this
+
+ removeSignal(this)
+
+ this.callback = null
+
+ let headers = rawHeaders
+ // Indicates is an HTTP2Session
+ if (headers != null) {
+ headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ }
+
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ headers,
+ socket,
+ opaque,
+ context
+ })
+ }
+
+ onError (err) {
+ const { callback, opaque } = this
+
+ removeSignal(this)
+
+ if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+ }
+}
+
+function connect (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ connect.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
+
+ try {
+ const connectHandler = new ConnectHandler(opts, callback)
+ this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
+
+module.exports = connect
+
+
+/***/ }),
+
+/***/ 62466:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const {
+ Readable,
+ Duplex,
+ PassThrough
+} = __nccwpck_require__(2203)
+const {
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError
+} = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { AsyncResource } = __nccwpck_require__(90290)
+const { addSignal, removeSignal } = __nccwpck_require__(52730)
+const assert = __nccwpck_require__(42613)
+
+const kResume = Symbol('resume')
+
+class PipelineRequest extends Readable {
+ constructor () {
+ super({ autoDestroy: true })
+
+ this[kResume] = null
+ }
+
+ _read () {
+ const { [kResume]: resume } = this
+
+ if (resume) {
+ this[kResume] = null
+ resume()
+ }
+ }
+
+ _destroy (err, callback) {
+ this._read()
+
+ callback(err)
+ }
+}
+
+class PipelineResponse extends Readable {
+ constructor (resume) {
+ super({ autoDestroy: true })
+ this[kResume] = resume
+ }
+
+ _read () {
+ this[kResume]()
+ }
+
+ _destroy (err, callback) {
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError()
+ }
+
+ callback(err)
+ }
+}
+
+class PipelineHandler extends AsyncResource {
+ constructor (opts, handler) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ if (typeof handler !== 'function') {
+ throw new InvalidArgumentError('invalid handler')
+ }
+
+ const { signal, method, opaque, onInfo, responseHeaders } = opts
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
+
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
+
+ super('UNDICI_PIPELINE')
+
+ this.opaque = opaque || null
+ this.responseHeaders = responseHeaders || null
+ this.handler = handler
+ this.abort = null
+ this.context = null
+ this.onInfo = onInfo || null
+
+ this.req = new PipelineRequest().on('error', util.nop)
+
+ this.ret = new Duplex({
+ readableObjectMode: opts.objectMode,
+ autoDestroy: true,
+ read: () => {
+ const { body } = this
+
+ if (body && body.resume) {
+ body.resume()
+ }
+ },
+ write: (chunk, encoding, callback) => {
+ const { req } = this
+
+ if (req.push(chunk, encoding) || req._readableState.destroyed) {
+ callback()
+ } else {
+ req[kResume] = callback
+ }
+ },
+ destroy: (err, callback) => {
+ const { body, req, res, ret, abort } = this
+
+ if (!err && !ret._readableState.endEmitted) {
+ err = new RequestAbortedError()
+ }
+
+ if (abort && err) {
+ abort()
+ }
+
+ util.destroy(body, err)
+ util.destroy(req, err)
+ util.destroy(res, err)
+
+ removeSignal(this)
+
+ callback(err)
+ }
+ }).on('prefinish', () => {
+ const { req } = this
+
+ // Node < 15 does not call _final in same tick.
+ req.push(null)
+ })
+
+ this.res = null
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ const { ret, res } = this
+
+ assert(!res, 'pipeline cannot be retried')
+
+ if (ret.destroyed) {
+ throw new RequestAbortedError()
+ }
+
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders (statusCode, rawHeaders, resume) {
+ const { opaque, handler, context } = this
+
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ this.onInfo({ statusCode, headers })
+ }
+ return
+ }
+
+ this.res = new PipelineResponse(resume)
+
+ let body
+ try {
+ this.handler = null
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ body = this.runInAsyncScope(handler, null, {
+ statusCode,
+ headers,
+ opaque,
+ body: this.res,
+ context
+ })
+ } catch (err) {
+ this.res.on('error', util.nop)
+ throw err
+ }
+
+ if (!body || typeof body.on !== 'function') {
+ throw new InvalidReturnValueError('expected Readable')
+ }
+
+ body
+ .on('data', (chunk) => {
+ const { ret, body } = this
+
+ if (!ret.push(chunk) && body.pause) {
+ body.pause()
+ }
+ })
+ .on('error', (err) => {
+ const { ret } = this
+
+ util.destroy(ret, err)
+ })
+ .on('end', () => {
+ const { ret } = this
+
+ ret.push(null)
+ })
+ .on('close', () => {
+ const { ret } = this
+
+ if (!ret._readableState.ended) {
+ util.destroy(ret, new RequestAbortedError())
+ }
+ })
+
+ this.body = body
+ }
+
+ onData (chunk) {
+ const { res } = this
+ return res.push(chunk)
+ }
+
+ onComplete (trailers) {
+ const { res } = this
+ res.push(null)
+ }
+
+ onError (err) {
+ const { ret } = this
+ this.handler = null
+ util.destroy(ret, err)
+ }
+}
+
+function pipeline (opts, handler) {
+ try {
+ const pipelineHandler = new PipelineHandler(opts, handler)
+ this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
+ return pipelineHandler.ret
+ } catch (err) {
+ return new PassThrough().destroy(err)
+ }
+}
+
+module.exports = pipeline
+
+
+/***/ }),
+
+/***/ 50887:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const Readable = __nccwpck_require__(38947)
+const {
+ InvalidArgumentError,
+ RequestAbortedError
+} = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { getResolveErrorBodyCallback } = __nccwpck_require__(80363)
+const { AsyncResource } = __nccwpck_require__(90290)
+const { addSignal, removeSignal } = __nccwpck_require__(52730)
+
+class RequestHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
+
+ try {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
+
+ if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
+ throw new InvalidArgumentError('invalid highWaterMark')
+ }
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
+
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
+
+ super('UNDICI_REQUEST')
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on('error', util.nop), err)
+ }
+ throw err
+ }
+
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.callback = callback
+ this.res = null
+ this.abort = null
+ this.body = body
+ this.trailers = {}
+ this.context = null
+ this.onInfo = onInfo || null
+ this.throwOnError = throwOnError
+ this.highWaterMark = highWaterMark
+
+ if (util.isStream(body)) {
+ body.on('error', (err) => {
+ this.onError(err)
+ })
+ }
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
+
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
+
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers })
+ }
+ return
+ }
+
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
+ const contentType = parsedHeaders['content-type']
+ const body = new Readable({ resume, abort, contentType, highWaterMark })
+
+ this.callback = null
+ this.res = body
+ if (callback !== null) {
+ if (this.throwOnError && statusCode >= 400) {
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
+ { callback, body, contentType, statusCode, statusMessage, headers }
+ )
+ } else {
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ headers,
+ trailers: this.trailers,
+ opaque,
+ body,
+ context
+ })
+ }
+ }
+ }
+
+ onData (chunk) {
+ const { res } = this
+ return res.push(chunk)
+ }
+
+ onComplete (trailers) {
+ const { res } = this
+
+ removeSignal(this)
+
+ util.parseHeaders(trailers, this.trailers)
+
+ res.push(null)
+ }
+
+ onError (err) {
+ const { res, callback, body, opaque } = this
+
+ removeSignal(this)
+
+ if (callback) {
+ // TODO: Does this need queueMicrotask?
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+
+ if (res) {
+ this.res = null
+ // Ensure all queued handlers are invoked before destroying res.
+ queueMicrotask(() => {
+ util.destroy(res, err)
+ })
+ }
+
+ if (body) {
+ this.body = null
+ util.destroy(body, err)
+ }
+ }
+}
+
+function request (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ request.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
+
+ try {
+ this.dispatch(opts, new RequestHandler(opts, callback))
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
+
+module.exports = request
+module.exports.RequestHandler = RequestHandler
+
+
+/***/ }),
+
+/***/ 44388:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { finished, PassThrough } = __nccwpck_require__(2203)
+const {
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError
+} = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { getResolveErrorBodyCallback } = __nccwpck_require__(80363)
+const { AsyncResource } = __nccwpck_require__(90290)
+const { addSignal, removeSignal } = __nccwpck_require__(52730)
+
+class StreamHandler extends AsyncResource {
+ constructor (opts, factory, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
+
+ try {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
+
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('invalid factory')
+ }
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
+
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
+
+ super('UNDICI_STREAM')
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on('error', util.nop), err)
+ }
+ throw err
+ }
+
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.factory = factory
+ this.callback = callback
+ this.res = null
+ this.abort = null
+ this.context = null
+ this.trailers = null
+ this.body = body
+ this.onInfo = onInfo || null
+ this.throwOnError = throwOnError || false
+
+ if (util.isStream(body)) {
+ body.on('error', (err) => {
+ this.onError(err)
+ })
+ }
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
+
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const { factory, opaque, context, callback, responseHeaders } = this
+
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers })
+ }
+ return
+ }
+
+ this.factory = null
+
+ let res
+
+ if (this.throwOnError && statusCode >= 400) {
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
+ const contentType = parsedHeaders['content-type']
+ res = new PassThrough()
+
+ this.callback = null
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
+ { callback, body: res, contentType, statusCode, statusMessage, headers }
+ )
+ } else {
+ if (factory === null) {
+ return
+ }
+
+ res = this.runInAsyncScope(factory, null, {
+ statusCode,
+ headers,
+ opaque,
+ context
+ })
+
+ if (
+ !res ||
+ typeof res.write !== 'function' ||
+ typeof res.end !== 'function' ||
+ typeof res.on !== 'function'
+ ) {
+ throw new InvalidReturnValueError('expected Writable')
+ }
+
+ // TODO: Avoid finished. It registers an unnecessary amount of listeners.
+ finished(res, { readable: false }, (err) => {
+ const { callback, res, opaque, trailers, abort } = this
+
+ this.res = null
+ if (err || !res.readable) {
+ util.destroy(res, err)
+ }
+
+ this.callback = null
+ this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
+
+ if (err) {
+ abort()
+ }
+ })
+ }
+
+ res.on('drain', resume)
+
+ this.res = res
+
+ const needDrain = res.writableNeedDrain !== undefined
+ ? res.writableNeedDrain
+ : res._writableState && res._writableState.needDrain
+
+ return needDrain !== true
+ }
+
+ onData (chunk) {
+ const { res } = this
+
+ return res ? res.write(chunk) : true
+ }
+
+ onComplete (trailers) {
+ const { res } = this
+
+ removeSignal(this)
+
+ if (!res) {
+ return
+ }
+
+ this.trailers = util.parseHeaders(trailers)
+
+ res.end()
+ }
+
+ onError (err) {
+ const { res, callback, opaque, body } = this
+
+ removeSignal(this)
+
+ this.factory = null
+
+ if (res) {
+ this.res = null
+ util.destroy(res, err)
+ } else if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+
+ if (body) {
+ this.body = null
+ util.destroy(body, err)
+ }
+ }
+}
+
+function stream (opts, factory, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ stream.call(this, opts, factory, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
+
+ try {
+ this.dispatch(opts, new StreamHandler(opts, factory, callback))
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
+
+module.exports = stream
+
+
+/***/ }),
+
+/***/ 56342:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(53959)
+const { AsyncResource } = __nccwpck_require__(90290)
+const util = __nccwpck_require__(89500)
+const { addSignal, removeSignal } = __nccwpck_require__(52730)
+const assert = __nccwpck_require__(42613)
+
+class UpgradeHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
+
+ const { signal, opaque, responseHeaders } = opts
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ super('UNDICI_UPGRADE')
+
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.callback = callback
+ this.abort = null
+ this.context = null
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
+
+ this.abort = abort
+ this.context = null
+ }
+
+ onHeaders () {
+ throw new SocketError('bad upgrade', null)
+ }
+
+ onUpgrade (statusCode, rawHeaders, socket) {
+ const { callback, opaque, context } = this
+
+ assert.strictEqual(statusCode, 101)
+
+ removeSignal(this)
+
+ this.callback = null
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ this.runInAsyncScope(callback, null, null, {
+ headers,
+ socket,
+ opaque,
+ context
+ })
+ }
+
+ onError (err) {
+ const { callback, opaque } = this
+
+ removeSignal(this)
+
+ if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+ }
+}
+
+function upgrade (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ upgrade.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
+
+ try {
+ const upgradeHandler = new UpgradeHandler(opts, callback)
+ this.dispatch({
+ ...opts,
+ method: opts.method || 'GET',
+ upgrade: opts.protocol || 'Websocket'
+ }, upgradeHandler)
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
+
+module.exports = upgrade
+
+
+/***/ }),
+
+/***/ 82531:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+module.exports.request = __nccwpck_require__(50887)
+module.exports.stream = __nccwpck_require__(44388)
+module.exports.pipeline = __nccwpck_require__(62466)
+module.exports.upgrade = __nccwpck_require__(56342)
+module.exports.connect = __nccwpck_require__(73192)
+
+
+/***/ }),
+
+/***/ 38947:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+// Ported from https://github.com/nodejs/undici/pull/907
+
+
+
+const assert = __nccwpck_require__(42613)
+const { Readable } = __nccwpck_require__(2203)
+const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(89500)
+
+let Blob
+
+const kConsume = Symbol('kConsume')
+const kReading = Symbol('kReading')
+const kBody = Symbol('kBody')
+const kAbort = Symbol('abort')
+const kContentType = Symbol('kContentType')
+
+const noop = () => {}
+
+module.exports = class BodyReadable extends Readable {
+ constructor ({
+ resume,
+ abort,
+ contentType = '',
+ highWaterMark = 64 * 1024 // Same as nodejs fs streams.
+ }) {
+ super({
+ autoDestroy: true,
+ read: resume,
+ highWaterMark
+ })
+
+ this._readableState.dataEmitted = false
+
+ this[kAbort] = abort
+ this[kConsume] = null
+ this[kBody] = null
+ this[kContentType] = contentType
+
+ // Is stream being consumed through Readable API?
+ // This is an optimization so that we avoid checking
+ // for 'data' and 'readable' listeners in the hot path
+ // inside push().
+ this[kReading] = false
+ }
+
+ destroy (err) {
+ if (this.destroyed) {
+ // Node < 16
+ return this
+ }
+
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError()
+ }
+
+ if (err) {
+ this[kAbort]()
+ }
+
+ return super.destroy(err)
+ }
+
+ emit (ev, ...args) {
+ if (ev === 'data') {
+ // Node < 16.7
+ this._readableState.dataEmitted = true
+ } else if (ev === 'error') {
+ // Node < 16
+ this._readableState.errorEmitted = true
+ }
+ return super.emit(ev, ...args)
+ }
+
+ on (ev, ...args) {
+ if (ev === 'data' || ev === 'readable') {
+ this[kReading] = true
+ }
+ return super.on(ev, ...args)
+ }
+
+ addListener (ev, ...args) {
+ return this.on(ev, ...args)
+ }
+
+ off (ev, ...args) {
+ const ret = super.off(ev, ...args)
+ if (ev === 'data' || ev === 'readable') {
+ this[kReading] = (
+ this.listenerCount('data') > 0 ||
+ this.listenerCount('readable') > 0
+ )
+ }
+ return ret
+ }
+
+ removeListener (ev, ...args) {
+ return this.off(ev, ...args)
+ }
+
+ push (chunk) {
+ if (this[kConsume] && chunk !== null && this.readableLength === 0) {
+ consumePush(this[kConsume], chunk)
+ return this[kReading] ? super.push(chunk) : true
+ }
+ return super.push(chunk)
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-text
+ async text () {
+ return consume(this, 'text')
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-json
+ async json () {
+ return consume(this, 'json')
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-blob
+ async blob () {
+ return consume(this, 'blob')
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
+ async arrayBuffer () {
+ return consume(this, 'arrayBuffer')
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-formdata
+ async formData () {
+ // TODO: Implement.
+ throw new NotSupportedError()
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-bodyused
+ get bodyUsed () {
+ return util.isDisturbed(this)
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-body
+ get body () {
+ if (!this[kBody]) {
+ this[kBody] = ReadableStreamFrom(this)
+ if (this[kConsume]) {
+ // TODO: Is this the best way to force a lock?
+ this[kBody].getReader() // Ensure stream is locked.
+ assert(this[kBody].locked)
+ }
+ }
+ return this[kBody]
+ }
+
+ dump (opts) {
+ let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144
+ const signal = opts && opts.signal
+
+ if (signal) {
+ try {
+ if (typeof signal !== 'object' || !('aborted' in signal)) {
+ throw new InvalidArgumentError('signal must be an AbortSignal')
+ }
+ util.throwIfAborted(signal)
+ } catch (err) {
+ return Promise.reject(err)
+ }
+ }
+
+ if (this.closed) {
+ return Promise.resolve(null)
+ }
+
+ return new Promise((resolve, reject) => {
+ const signalListenerCleanup = signal
+ ? util.addAbortListener(signal, () => {
+ this.destroy()
+ })
+ : noop
+
+ this
+ .on('close', function () {
+ signalListenerCleanup()
+ if (signal && signal.aborted) {
+ reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))
+ } else {
+ resolve(null)
+ }
+ })
+ .on('error', noop)
+ .on('data', function (chunk) {
+ limit -= chunk.length
+ if (limit <= 0) {
+ this.destroy()
+ }
+ })
+ .resume()
+ })
+ }
+}
+
+// https://streams.spec.whatwg.org/#readablestream-locked
+function isLocked (self) {
+ // Consume is an implicit lock.
+ return (self[kBody] && self[kBody].locked === true) || self[kConsume]
+}
+
+// https://fetch.spec.whatwg.org/#body-unusable
+function isUnusable (self) {
+ return util.isDisturbed(self) || isLocked(self)
+}
+
+async function consume (stream, type) {
+ if (isUnusable(stream)) {
+ throw new TypeError('unusable')
+ }
+
+ assert(!stream[kConsume])
+
+ return new Promise((resolve, reject) => {
+ stream[kConsume] = {
+ type,
+ stream,
+ resolve,
+ reject,
+ length: 0,
+ body: []
+ }
+
+ stream
+ .on('error', function (err) {
+ consumeFinish(this[kConsume], err)
+ })
+ .on('close', function () {
+ if (this[kConsume].body !== null) {
+ consumeFinish(this[kConsume], new RequestAbortedError())
+ }
+ })
+
+ process.nextTick(consumeStart, stream[kConsume])
+ })
+}
+
+function consumeStart (consume) {
+ if (consume.body === null) {
+ return
+ }
+
+ const { _readableState: state } = consume.stream
+
+ for (const chunk of state.buffer) {
+ consumePush(consume, chunk)
+ }
+
+ if (state.endEmitted) {
+ consumeEnd(this[kConsume])
+ } else {
+ consume.stream.on('end', function () {
+ consumeEnd(this[kConsume])
+ })
+ }
+
+ consume.stream.resume()
+
+ while (consume.stream.read() != null) {
+ // Loop
+ }
+}
+
+function consumeEnd (consume) {
+ const { type, body, resolve, stream, length } = consume
+
+ try {
+ if (type === 'text') {
+ resolve(toUSVString(Buffer.concat(body)))
+ } else if (type === 'json') {
+ resolve(JSON.parse(Buffer.concat(body)))
+ } else if (type === 'arrayBuffer') {
+ const dst = new Uint8Array(length)
+
+ let pos = 0
+ for (const buf of body) {
+ dst.set(buf, pos)
+ pos += buf.byteLength
+ }
+
+ resolve(dst.buffer)
+ } else if (type === 'blob') {
+ if (!Blob) {
+ Blob = (__nccwpck_require__(20181).Blob)
+ }
+ resolve(new Blob(body, { type: stream[kContentType] }))
+ }
+
+ consumeFinish(consume)
+ } catch (err) {
+ stream.destroy(err)
+ }
+}
+
+function consumePush (consume, chunk) {
+ consume.length += chunk.length
+ consume.body.push(chunk)
+}
+
+function consumeFinish (consume, err) {
+ if (consume.body === null) {
+ return
+ }
+
+ if (err) {
+ consume.reject(err)
+ } else {
+ consume.resolve()
+ }
+
+ consume.type = null
+ consume.stream = null
+ consume.resolve = null
+ consume.reject = null
+ consume.length = 0
+ consume.body = null
+}
+
+
+/***/ }),
+
+/***/ 80363:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const assert = __nccwpck_require__(42613)
+const {
+ ResponseStatusCodeError
+} = __nccwpck_require__(53959)
+const { toUSVString } = __nccwpck_require__(89500)
+
+async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
+ assert(body)
+
+ let chunks = []
+ let limit = 0
+
+ for await (const chunk of body) {
+ chunks.push(chunk)
+ limit += chunk.length
+ if (limit > 128 * 1024) {
+ chunks = null
+ break
+ }
+ }
+
+ if (statusCode === 204 || !contentType || !chunks) {
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
+ return
+ }
+
+ try {
+ if (contentType.startsWith('application/json')) {
+ const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
+ return
+ }
+
+ if (contentType.startsWith('text/')) {
+ const payload = toUSVString(Buffer.concat(chunks))
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
+ return
+ }
+ } catch (err) {
+ // Process in a fallback if error
+ }
+
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
+}
+
+module.exports = { getResolveErrorBodyCallback }
+
+
+/***/ }),
+
+/***/ 95377:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const {
+ BalancedPoolMissingUpstreamError,
+ InvalidArgumentError
+} = __nccwpck_require__(53959)
+const {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+} = __nccwpck_require__(18804)
+const Pool = __nccwpck_require__(44288)
+const { kUrl, kInterceptors } = __nccwpck_require__(68031)
+const { parseOrigin } = __nccwpck_require__(89500)
+const kFactory = Symbol('factory')
+
+const kOptions = Symbol('options')
+const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
+const kCurrentWeight = Symbol('kCurrentWeight')
+const kIndex = Symbol('kIndex')
+const kWeight = Symbol('kWeight')
+const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
+const kErrorPenalty = Symbol('kErrorPenalty')
+
+function getGreatestCommonDivisor (a, b) {
+ if (b === 0) return a
+ return getGreatestCommonDivisor(b, a % b)
+}
+
+function defaultFactory (origin, opts) {
+ return new Pool(origin, opts)
+}
+
+class BalancedPool extends PoolBase {
+ constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
+ super()
+
+ this[kOptions] = opts
+ this[kIndex] = -1
+ this[kCurrentWeight] = 0
+
+ this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
+ this[kErrorPenalty] = this[kOptions].errorPenalty || 15
+
+ if (!Array.isArray(upstreams)) {
+ upstreams = [upstreams]
+ }
+
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
+ }
+
+ this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
+ ? opts.interceptors.BalancedPool
+ : []
+ this[kFactory] = factory
+
+ for (const upstream of upstreams) {
+ this.addUpstream(upstream)
+ }
+ this._updateBalancedPoolStats()
+ }
+
+ addUpstream (upstream) {
+ const upstreamOrigin = parseOrigin(upstream).origin
+
+ if (this[kClients].find((pool) => (
+ pool[kUrl].origin === upstreamOrigin &&
+ pool.closed !== true &&
+ pool.destroyed !== true
+ ))) {
+ return this
+ }
+ const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
+
+ this[kAddClient](pool)
+ pool.on('connect', () => {
+ pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
+ })
+
+ pool.on('connectionError', () => {
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
+ this._updateBalancedPoolStats()
+ })
+
+ pool.on('disconnect', (...args) => {
+ const err = args[2]
+ if (err && err.code === 'UND_ERR_SOCKET') {
+ // decrease the weight of the pool.
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
+ this._updateBalancedPoolStats()
+ }
+ })
+
+ for (const client of this[kClients]) {
+ client[kWeight] = this[kMaxWeightPerServer]
+ }
+
+ this._updateBalancedPoolStats()
+
+ return this
+ }
+
+ _updateBalancedPoolStats () {
+ this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
+ }
+
+ removeUpstream (upstream) {
+ const upstreamOrigin = parseOrigin(upstream).origin
+
+ const pool = this[kClients].find((pool) => (
+ pool[kUrl].origin === upstreamOrigin &&
+ pool.closed !== true &&
+ pool.destroyed !== true
+ ))
+
+ if (pool) {
+ this[kRemoveClient](pool)
+ }
+
+ return this
+ }
+
+ get upstreams () {
+ return this[kClients]
+ .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
+ .map((p) => p[kUrl].origin)
+ }
+
+ [kGetDispatcher] () {
+ // We validate that pools is greater than 0,
+ // otherwise we would have to wait until an upstream
+ // is added, which might never happen.
+ if (this[kClients].length === 0) {
+ throw new BalancedPoolMissingUpstreamError()
+ }
+
+ const dispatcher = this[kClients].find(dispatcher => (
+ !dispatcher[kNeedDrain] &&
+ dispatcher.closed !== true &&
+ dispatcher.destroyed !== true
+ ))
+
+ if (!dispatcher) {
+ return
+ }
+
+ const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
+
+ if (allClientsBusy) {
+ return
+ }
+
+ let counter = 0
+
+ let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
+
+ while (counter++ < this[kClients].length) {
+ this[kIndex] = (this[kIndex] + 1) % this[kClients].length
+ const pool = this[kClients][this[kIndex]]
+
+ // find pool index with the largest weight
+ if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
+ maxWeightIndex = this[kIndex]
+ }
+
+ // decrease the current weight every `this[kClients].length`.
+ if (this[kIndex] === 0) {
+ // Set the current weight to the next lower weight.
+ this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
+
+ if (this[kCurrentWeight] <= 0) {
+ this[kCurrentWeight] = this[kMaxWeightPerServer]
+ }
+ }
+ if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
+ return pool
+ }
+ }
+
+ this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
+ this[kIndex] = maxWeightIndex
+ return this[kClients][maxWeightIndex]
+ }
+}
+
+module.exports = BalancedPool
+
+
+/***/ }),
+
+/***/ 40611:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { kConstruct } = __nccwpck_require__(68652)
+const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(71173)
+const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(89500)
+const { kHeadersList } = __nccwpck_require__(68031)
+const { webidl } = __nccwpck_require__(94354)
+const { Response, cloneResponse } = __nccwpck_require__(89928)
+const { Request } = __nccwpck_require__(2630)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
+const { fetching } = __nccwpck_require__(11503)
+const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(72847)
+const assert = __nccwpck_require__(42613)
+const { getGlobalDispatcher } = __nccwpck_require__(61481)
+
+/**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
+ * @typedef {Object} CacheBatchOperation
+ * @property {'delete' | 'put'} type
+ * @property {any} request
+ * @property {any} response
+ * @property {import('../../types/cache').CacheQueryOptions} options
+ */
+
+/**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
+ * @typedef {[any, any][]} requestResponseList
+ */
+
+class Cache {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
+ * @type {requestResponseList}
+ */
+ #relevantRequestResponseList
+
+ constructor () {
+ if (arguments[0] !== kConstruct) {
+ webidl.illegalConstructor()
+ }
+
+ this.#relevantRequestResponseList = arguments[1]
+ }
+
+ async match (request, options = {}) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })
+
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
+
+ const p = await this.matchAll(request, options)
+
+ if (p.length === 0) {
+ return
+ }
+
+ return p[0]
+ }
+
+ async matchAll (request = undefined, options = {}) {
+ webidl.brandCheck(this, Cache)
+
+ if (request !== undefined) request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
+
+ // 1.
+ let r = null
+
+ // 2.
+ if (request !== undefined) {
+ if (request instanceof Request) {
+ // 2.1.1
+ r = request[kState]
+
+ // 2.1.2
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return []
+ }
+ } else if (typeof request === 'string') {
+ // 2.2.1
+ r = new Request(request)[kState]
+ }
+ }
+
+ // 5.
+ // 5.1
+ const responses = []
+
+ // 5.2
+ if (request === undefined) {
+ // 5.2.1
+ for (const requestResponse of this.#relevantRequestResponseList) {
+ responses.push(requestResponse[1])
+ }
+ } else { // 5.3
+ // 5.3.1
+ const requestResponses = this.#queryCache(r, options)
+
+ // 5.3.2
+ for (const requestResponse of requestResponses) {
+ responses.push(requestResponse[1])
+ }
+ }
+
+ // 5.4
+ // We don't implement CORs so we don't need to loop over the responses, yay!
+
+ // 5.5.1
+ const responseList = []
+
+ // 5.5.2
+ for (const response of responses) {
+ // 5.5.2.1
+ const responseObject = new Response(response.body?.source ?? null)
+ const body = responseObject[kState].body
+ responseObject[kState] = response
+ responseObject[kState].body = body
+ responseObject[kHeaders][kHeadersList] = response.headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
+
+ responseList.push(responseObject)
+ }
+
+ // 6.
+ return Object.freeze(responseList)
+ }
+
+ async add (request) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })
+
+ request = webidl.converters.RequestInfo(request)
+
+ // 1.
+ const requests = [request]
+
+ // 2.
+ const responseArrayPromise = this.addAll(requests)
+
+ // 3.
+ return await responseArrayPromise
+ }
+
+ async addAll (requests) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })
+
+ requests = webidl.converters['sequence'](requests)
+
+ // 1.
+ const responsePromises = []
+
+ // 2.
+ const requestList = []
+
+ // 3.
+ for (const request of requests) {
+ if (typeof request === 'string') {
+ continue
+ }
+
+ // 3.1
+ const r = request[kState]
+
+ // 3.2
+ if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'Expected http/s scheme when method is not GET.'
+ })
+ }
+ }
+
+ // 4.
+ /** @type {ReturnType[]} */
+ const fetchControllers = []
+
+ // 5.
+ for (const request of requests) {
+ // 5.1
+ const r = new Request(request)[kState]
+
+ // 5.2
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'Expected http/s scheme.'
+ })
+ }
+
+ // 5.4
+ r.initiator = 'fetch'
+ r.destination = 'subresource'
+
+ // 5.5
+ requestList.push(r)
+
+ // 5.6
+ const responsePromise = createDeferredPromise()
+
+ // 5.7
+ fetchControllers.push(fetching({
+ request: r,
+ dispatcher: getGlobalDispatcher(),
+ processResponse (response) {
+ // 1.
+ if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
+ responsePromise.reject(webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'Received an invalid status code or the request failed.'
+ }))
+ } else if (response.headersList.contains('vary')) { // 2.
+ // 2.1
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
+
+ // 2.2
+ for (const fieldValue of fieldValues) {
+ // 2.2.1
+ if (fieldValue === '*') {
+ responsePromise.reject(webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'invalid vary field value'
+ }))
+
+ for (const controller of fetchControllers) {
+ controller.abort()
+ }
+
+ return
+ }
+ }
+ }
+ },
+ processResponseEndOfBody (response) {
+ // 1.
+ if (response.aborted) {
+ responsePromise.reject(new DOMException('aborted', 'AbortError'))
+ return
+ }
+
+ // 2.
+ responsePromise.resolve(response)
+ }
+ }))
+
+ // 5.8
+ responsePromises.push(responsePromise.promise)
+ }
+
+ // 6.
+ const p = Promise.all(responsePromises)
+
+ // 7.
+ const responses = await p
+
+ // 7.1
+ const operations = []
+
+ // 7.2
+ let index = 0
+
+ // 7.3
+ for (const response of responses) {
+ // 7.3.1
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'put', // 7.3.2
+ request: requestList[index], // 7.3.3
+ response // 7.3.4
+ }
+
+ operations.push(operation) // 7.3.5
+
+ index++ // 7.3.6
+ }
+
+ // 7.5
+ const cacheJobPromise = createDeferredPromise()
+
+ // 7.6.1
+ let errorData = null
+
+ // 7.6.2
+ try {
+ this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
+
+ // 7.6.3
+ queueMicrotask(() => {
+ // 7.6.3.1
+ if (errorData === null) {
+ cacheJobPromise.resolve(undefined)
+ } else {
+ // 7.6.3.2
+ cacheJobPromise.reject(errorData)
+ }
+ })
+
+ // 7.7
+ return cacheJobPromise.promise
+ }
+
+ async put (request, response) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })
+
+ request = webidl.converters.RequestInfo(request)
+ response = webidl.converters.Response(response)
+
+ // 1.
+ let innerRequest = null
+
+ // 2.
+ if (request instanceof Request) {
+ innerRequest = request[kState]
+ } else { // 3.
+ innerRequest = new Request(request)[kState]
+ }
+
+ // 4.
+ if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Expected an http/s scheme when method is not GET'
+ })
+ }
+
+ // 5.
+ const innerResponse = response[kState]
+
+ // 6.
+ if (innerResponse.status === 206) {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Got 206 status'
+ })
+ }
+
+ // 7.
+ if (innerResponse.headersList.contains('vary')) {
+ // 7.1.
+ const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
+
+ // 7.2.
+ for (const fieldValue of fieldValues) {
+ // 7.2.1
+ if (fieldValue === '*') {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Got * vary field value'
+ })
+ }
+ }
+ }
+
+ // 8.
+ if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Response body is locked or disturbed'
+ })
+ }
+
+ // 9.
+ const clonedResponse = cloneResponse(innerResponse)
+
+ // 10.
+ const bodyReadPromise = createDeferredPromise()
+
+ // 11.
+ if (innerResponse.body != null) {
+ // 11.1
+ const stream = innerResponse.body.stream
+
+ // 11.2
+ const reader = stream.getReader()
+
+ // 11.3
+ readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
+ } else {
+ bodyReadPromise.resolve(undefined)
+ }
+
+ // 12.
+ /** @type {CacheBatchOperation[]} */
+ const operations = []
+
+ // 13.
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'put', // 14.
+ request: innerRequest, // 15.
+ response: clonedResponse // 16.
+ }
+
+ // 17.
+ operations.push(operation)
+
+ // 19.
+ const bytes = await bodyReadPromise.promise
+
+ if (clonedResponse.body != null) {
+ clonedResponse.body.source = bytes
+ }
+
+ // 19.1
+ const cacheJobPromise = createDeferredPromise()
+
+ // 19.2.1
+ let errorData = null
+
+ // 19.2.2
+ try {
+ this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
+
+ // 19.2.3
+ queueMicrotask(() => {
+ // 19.2.3.1
+ if (errorData === null) {
+ cacheJobPromise.resolve()
+ } else { // 19.2.3.2
+ cacheJobPromise.reject(errorData)
+ }
+ })
+
+ return cacheJobPromise.promise
+ }
+
+ async delete (request, options = {}) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })
+
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
+
+ /**
+ * @type {Request}
+ */
+ let r = null
+
+ if (request instanceof Request) {
+ r = request[kState]
+
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return false
+ }
+ } else {
+ assert(typeof request === 'string')
+
+ r = new Request(request)[kState]
+ }
+
+ /** @type {CacheBatchOperation[]} */
+ const operations = []
+
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'delete',
+ request: r,
+ options
+ }
+
+ operations.push(operation)
+
+ const cacheJobPromise = createDeferredPromise()
+
+ let errorData = null
+ let requestResponses
+
+ try {
+ requestResponses = this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
+
+ queueMicrotask(() => {
+ if (errorData === null) {
+ cacheJobPromise.resolve(!!requestResponses?.length)
+ } else {
+ cacheJobPromise.reject(errorData)
+ }
+ })
+
+ return cacheJobPromise.promise
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
+ * @param {any} request
+ * @param {import('../../types/cache').CacheQueryOptions} options
+ * @returns {readonly Request[]}
+ */
+ async keys (request = undefined, options = {}) {
+ webidl.brandCheck(this, Cache)
+
+ if (request !== undefined) request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
+
+ // 1.
+ let r = null
+
+ // 2.
+ if (request !== undefined) {
+ // 2.1
+ if (request instanceof Request) {
+ // 2.1.1
+ r = request[kState]
+
+ // 2.1.2
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return []
+ }
+ } else if (typeof request === 'string') { // 2.2
+ r = new Request(request)[kState]
+ }
+ }
+
+ // 4.
+ const promise = createDeferredPromise()
+
+ // 5.
+ // 5.1
+ const requests = []
+
+ // 5.2
+ if (request === undefined) {
+ // 5.2.1
+ for (const requestResponse of this.#relevantRequestResponseList) {
+ // 5.2.1.1
+ requests.push(requestResponse[0])
+ }
+ } else { // 5.3
+ // 5.3.1
+ const requestResponses = this.#queryCache(r, options)
+
+ // 5.3.2
+ for (const requestResponse of requestResponses) {
+ // 5.3.2.1
+ requests.push(requestResponse[0])
+ }
+ }
+
+ // 5.4
+ queueMicrotask(() => {
+ // 5.4.1
+ const requestList = []
+
+ // 5.4.2
+ for (const request of requests) {
+ const requestObject = new Request('https://a')
+ requestObject[kState] = request
+ requestObject[kHeaders][kHeadersList] = request.headersList
+ requestObject[kHeaders][kGuard] = 'immutable'
+ requestObject[kRealm] = request.client
+
+ // 5.4.2.1
+ requestList.push(requestObject)
+ }
+
+ // 5.4.3
+ promise.resolve(Object.freeze(requestList))
+ })
+
+ return promise.promise
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
+ * @param {CacheBatchOperation[]} operations
+ * @returns {requestResponseList}
+ */
+ #batchCacheOperations (operations) {
+ // 1.
+ const cache = this.#relevantRequestResponseList
+
+ // 2.
+ const backupCache = [...cache]
+
+ // 3.
+ const addedItems = []
+
+ // 4.1
+ const resultList = []
+
+ try {
+ // 4.2
+ for (const operation of operations) {
+ // 4.2.1
+ if (operation.type !== 'delete' && operation.type !== 'put') {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'operation type does not match "delete" or "put"'
+ })
+ }
+
+ // 4.2.2
+ if (operation.type === 'delete' && operation.response != null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'delete operation should not have an associated response'
+ })
+ }
+
+ // 4.2.3
+ if (this.#queryCache(operation.request, operation.options, addedItems).length) {
+ throw new DOMException('???', 'InvalidStateError')
+ }
+
+ // 4.2.4
+ let requestResponses
+
+ // 4.2.5
+ if (operation.type === 'delete') {
+ // 4.2.5.1
+ requestResponses = this.#queryCache(operation.request, operation.options)
+
+ // TODO: the spec is wrong, this is needed to pass WPTs
+ if (requestResponses.length === 0) {
+ return []
+ }
+
+ // 4.2.5.2
+ for (const requestResponse of requestResponses) {
+ const idx = cache.indexOf(requestResponse)
+ assert(idx !== -1)
+
+ // 4.2.5.2.1
+ cache.splice(idx, 1)
+ }
+ } else if (operation.type === 'put') { // 4.2.6
+ // 4.2.6.1
+ if (operation.response == null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'put operation should have an associated response'
+ })
+ }
+
+ // 4.2.6.2
+ const r = operation.request
+
+ // 4.2.6.3
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'expected http or https scheme'
+ })
+ }
+
+ // 4.2.6.4
+ if (r.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'not get method'
+ })
+ }
+
+ // 4.2.6.5
+ if (operation.options != null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'options must not be defined'
+ })
+ }
+
+ // 4.2.6.6
+ requestResponses = this.#queryCache(operation.request)
+
+ // 4.2.6.7
+ for (const requestResponse of requestResponses) {
+ const idx = cache.indexOf(requestResponse)
+ assert(idx !== -1)
+
+ // 4.2.6.7.1
+ cache.splice(idx, 1)
+ }
+
+ // 4.2.6.8
+ cache.push([operation.request, operation.response])
+
+ // 4.2.6.10
+ addedItems.push([operation.request, operation.response])
+ }
+
+ // 4.2.7
+ resultList.push([operation.request, operation.response])
+ }
+
+ // 4.3
+ return resultList
+ } catch (e) { // 5.
+ // 5.1
+ this.#relevantRequestResponseList.length = 0
+
+ // 5.2
+ this.#relevantRequestResponseList = backupCache
+
+ // 5.3
+ throw e
+ }
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#query-cache
+ * @param {any} requestQuery
+ * @param {import('../../types/cache').CacheQueryOptions} options
+ * @param {requestResponseList} targetStorage
+ * @returns {requestResponseList}
+ */
+ #queryCache (requestQuery, options, targetStorage) {
+ /** @type {requestResponseList} */
+ const resultList = []
+
+ const storage = targetStorage ?? this.#relevantRequestResponseList
+
+ for (const requestResponse of storage) {
+ const [cachedRequest, cachedResponse] = requestResponse
+ if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
+ resultList.push(requestResponse)
+ }
+ }
+
+ return resultList
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
+ * @param {any} requestQuery
+ * @param {any} request
+ * @param {any | null} response
+ * @param {import('../../types/cache').CacheQueryOptions | undefined} options
+ * @returns {boolean}
+ */
+ #requestMatchesCachedItem (requestQuery, request, response = null, options) {
+ // if (options?.ignoreMethod === false && request.method === 'GET') {
+ // return false
+ // }
+
+ const queryURL = new URL(requestQuery.url)
+
+ const cachedURL = new URL(request.url)
+
+ if (options?.ignoreSearch) {
+ cachedURL.search = ''
+
+ queryURL.search = ''
+ }
+
+ if (!urlEquals(queryURL, cachedURL, true)) {
+ return false
+ }
+
+ if (
+ response == null ||
+ options?.ignoreVary ||
+ !response.headersList.contains('vary')
+ ) {
+ return true
+ }
+
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
+
+ for (const fieldValue of fieldValues) {
+ if (fieldValue === '*') {
+ return false
+ }
+
+ const requestValue = request.headersList.get(fieldValue)
+ const queryValue = requestQuery.headersList.get(fieldValue)
+
+ // If one has the header and the other doesn't, or one has
+ // a different value than the other, return false
+ if (requestValue !== queryValue) {
+ return false
+ }
+ }
+
+ return true
+ }
+}
+
+Object.defineProperties(Cache.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'Cache',
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ matchAll: kEnumerableProperty,
+ add: kEnumerableProperty,
+ addAll: kEnumerableProperty,
+ put: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+})
+
+const cacheQueryOptionConverters = [
+ {
+ key: 'ignoreSearch',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'ignoreMethod',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'ignoreVary',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ }
+]
+
+webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
+
+webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
+ ...cacheQueryOptionConverters,
+ {
+ key: 'cacheName',
+ converter: webidl.converters.DOMString
+ }
+])
+
+webidl.converters.Response = webidl.interfaceConverter(Response)
+
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.RequestInfo
+)
+
+module.exports = {
+ Cache
+}
+
+
+/***/ }),
+
+/***/ 66446:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { kConstruct } = __nccwpck_require__(68652)
+const { Cache } = __nccwpck_require__(40611)
+const { webidl } = __nccwpck_require__(94354)
+const { kEnumerableProperty } = __nccwpck_require__(89500)
+
+class CacheStorage {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
+ * @type {Map}
+ */
+ async has (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })
+
+ cacheName = webidl.converters.DOMString(cacheName)
+
+ // 2.1.1
+ // 2.2
+ return this.#caches.has(cacheName)
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async open (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })
+
+ cacheName = webidl.converters.DOMString(cacheName)
+
+ // 2.1
+ if (this.#caches.has(cacheName)) {
+ // await caches.open('v1') !== await caches.open('v1')
+
+ // 2.1.1
+ const cache = this.#caches.get(cacheName)
+
+ // 2.1.1.1
+ return new Cache(kConstruct, cache)
+ }
+
+ // 2.2
+ const cache = []
+
+ // 2.3
+ this.#caches.set(cacheName, cache)
+
+ // 2.4
+ return new Cache(kConstruct, cache)
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async delete (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })
+
+ cacheName = webidl.converters.DOMString(cacheName)
+
+ return this.#caches.delete(cacheName)
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
+ * @returns {string[]}
+ */
+ async keys () {
+ webidl.brandCheck(this, CacheStorage)
+
+ // 2.1
+ const keys = this.#caches.keys()
+
+ // 2.2
+ return [...keys]
+ }
+}
+
+Object.defineProperties(CacheStorage.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'CacheStorage',
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ has: kEnumerableProperty,
+ open: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+})
+
+module.exports = {
+ CacheStorage
+}
+
+
+/***/ }),
+
+/***/ 68652:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+module.exports = {
+ kConstruct: (__nccwpck_require__(68031).kConstruct)
+}
+
+
+/***/ }),
+
+/***/ 71173:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const assert = __nccwpck_require__(42613)
+const { URLSerializer } = __nccwpck_require__(37246)
+const { isValidHeaderName } = __nccwpck_require__(72847)
+
+/**
+ * @see https://url.spec.whatwg.org/#concept-url-equals
+ * @param {URL} A
+ * @param {URL} B
+ * @param {boolean | undefined} excludeFragment
+ * @returns {boolean}
+ */
+function urlEquals (A, B, excludeFragment = false) {
+ const serializedA = URLSerializer(A, excludeFragment)
+
+ const serializedB = URLSerializer(B, excludeFragment)
+
+ return serializedA === serializedB
+}
+
+/**
+ * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
+ * @param {string} header
+ */
+function fieldValues (header) {
+ assert(header !== null)
+
+ const values = []
+
+ for (let value of header.split(',')) {
+ value = value.trim()
+
+ if (!value.length) {
+ continue
+ } else if (!isValidHeaderName(value)) {
+ continue
+ }
+
+ values.push(value)
+ }
+
+ return values
+}
+
+module.exports = {
+ urlEquals,
+ fieldValues
+}
+
+
+/***/ }),
+
+/***/ 45513:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+// @ts-check
+
+
+
+/* global WebAssembly */
+
+const assert = __nccwpck_require__(42613)
+const net = __nccwpck_require__(69278)
+const http = __nccwpck_require__(58611)
+const { pipeline } = __nccwpck_require__(2203)
+const util = __nccwpck_require__(89500)
+const timers = __nccwpck_require__(82576)
+const Request = __nccwpck_require__(69691)
+const DispatcherBase = __nccwpck_require__(52421)
+const {
+ RequestContentLengthMismatchError,
+ ResponseContentLengthMismatchError,
+ InvalidArgumentError,
+ RequestAbortedError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ SocketError,
+ InformationalError,
+ BodyTimeoutError,
+ HTTPParserError,
+ ResponseExceededMaxSizeError,
+ ClientDestroyedError
+} = __nccwpck_require__(53959)
+const buildConnector = __nccwpck_require__(91332)
+const {
+ kUrl,
+ kReset,
+ kServerName,
+ kClient,
+ kBusy,
+ kParser,
+ kConnect,
+ kBlocking,
+ kResuming,
+ kRunning,
+ kPending,
+ kSize,
+ kWriting,
+ kQueue,
+ kConnected,
+ kConnecting,
+ kNeedDrain,
+ kNoRef,
+ kKeepAliveDefaultTimeout,
+ kHostHeader,
+ kPendingIdx,
+ kRunningIdx,
+ kError,
+ kPipelining,
+ kSocket,
+ kKeepAliveTimeoutValue,
+ kMaxHeadersSize,
+ kKeepAliveMaxTimeout,
+ kKeepAliveTimeoutThreshold,
+ kHeadersTimeout,
+ kBodyTimeout,
+ kStrictContentLength,
+ kConnector,
+ kMaxRedirections,
+ kMaxRequests,
+ kCounter,
+ kClose,
+ kDestroy,
+ kDispatch,
+ kInterceptors,
+ kLocalAddress,
+ kMaxResponseSize,
+ kHTTPConnVersion,
+ // HTTP2
+ kHost,
+ kHTTP2Session,
+ kHTTP2SessionState,
+ kHTTP2BuildRequest,
+ kHTTP2CopyHeaders,
+ kHTTP1BuildRequest
+} = __nccwpck_require__(68031)
+
+/** @type {import('http2')} */
+let http2
+try {
+ http2 = __nccwpck_require__(85675)
+} catch {
+ // @ts-ignore
+ http2 = { constants: {} }
+}
+
+const {
+ constants: {
+ HTTP2_HEADER_AUTHORITY,
+ HTTP2_HEADER_METHOD,
+ HTTP2_HEADER_PATH,
+ HTTP2_HEADER_SCHEME,
+ HTTP2_HEADER_CONTENT_LENGTH,
+ HTTP2_HEADER_EXPECT,
+ HTTP2_HEADER_STATUS
+ }
+} = http2
+
+// Experimental
+let h2ExperimentalWarned = false
+
+const FastBuffer = Buffer[Symbol.species]
+
+const kClosedResolve = Symbol('kClosedResolve')
+
+const channels = {}
+
+try {
+ const diagnosticsChannel = __nccwpck_require__(31637)
+ channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')
+ channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')
+ channels.connectError = diagnosticsChannel.channel('undici:client:connectError')
+ channels.connected = diagnosticsChannel.channel('undici:client:connected')
+} catch {
+ channels.sendHeaders = { hasSubscribers: false }
+ channels.beforeConnect = { hasSubscribers: false }
+ channels.connectError = { hasSubscribers: false }
+ channels.connected = { hasSubscribers: false }
+}
+
+/**
+ * @type {import('../types/client').default}
+ */
+class Client extends DispatcherBase {
+ /**
+ *
+ * @param {string|URL} url
+ * @param {import('../types/client').Client.Options} options
+ */
+ constructor (url, {
+ interceptors,
+ maxHeaderSize,
+ headersTimeout,
+ socketTimeout,
+ requestTimeout,
+ connectTimeout,
+ bodyTimeout,
+ idleTimeout,
+ keepAlive,
+ keepAliveTimeout,
+ maxKeepAliveTimeout,
+ keepAliveMaxTimeout,
+ keepAliveTimeoutThreshold,
+ socketPath,
+ pipelining,
+ tls,
+ strictContentLength,
+ maxCachedSessions,
+ maxRedirections,
+ connect,
+ maxRequestsPerClient,
+ localAddress,
+ maxResponseSize,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ // h2
+ allowH2,
+ maxConcurrentStreams
+ } = {}) {
+ super()
+
+ if (keepAlive !== undefined) {
+ throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
+ }
+
+ if (socketTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
+ }
+
+ if (requestTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
+ }
+
+ if (idleTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
+ }
+
+ if (maxKeepAliveTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
+ }
+
+ if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
+ throw new InvalidArgumentError('invalid maxHeaderSize')
+ }
+
+ if (socketPath != null && typeof socketPath !== 'string') {
+ throw new InvalidArgumentError('invalid socketPath')
+ }
+
+ if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
+ throw new InvalidArgumentError('invalid connectTimeout')
+ }
+
+ if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
+ throw new InvalidArgumentError('invalid keepAliveTimeout')
+ }
+
+ if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
+ throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
+ }
+
+ if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
+ throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
+ }
+
+ if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
+ }
+
+ if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
+ }
+
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
+ }
+
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
+ }
+
+ if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
+ throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
+ }
+
+ if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
+ throw new InvalidArgumentError('localAddress must be valid string IP address')
+ }
+
+ if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
+ throw new InvalidArgumentError('maxResponseSize must be a positive number')
+ }
+
+ if (
+ autoSelectFamilyAttemptTimeout != null &&
+ (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
+ ) {
+ throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
+ }
+
+ // h2
+ if (allowH2 != null && typeof allowH2 !== 'boolean') {
+ throw new InvalidArgumentError('allowH2 must be a valid boolean value')
+ }
+
+ if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
+ throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')
+ }
+
+ if (typeof connect !== 'function') {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
+ ...connect
+ })
+ }
+
+ this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)
+ ? interceptors.Client
+ : [createRedirectInterceptor({ maxRedirections })]
+ this[kUrl] = util.parseOrigin(url)
+ this[kConnector] = connect
+ this[kSocket] = null
+ this[kPipelining] = pipelining != null ? pipelining : 1
+ this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
+ this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
+ this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
+ this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold
+ this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
+ this[kServerName] = null
+ this[kLocalAddress] = localAddress != null ? localAddress : null
+ this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
+ this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
+ this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
+ this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
+ this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
+ this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
+ this[kMaxRedirections] = maxRedirections
+ this[kMaxRequests] = maxRequestsPerClient
+ this[kClosedResolve] = null
+ this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
+ this[kHTTPConnVersion] = 'h1'
+
+ // HTTP/2
+ this[kHTTP2Session] = null
+ this[kHTTP2SessionState] = !allowH2
+ ? null
+ : {
+ // streams: null, // Fixed queue of streams - For future support of `push`
+ openStreams: 0, // Keep track of them to decide wether or not unref the session
+ maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
+ }
+ this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`
+
+ // kQueue is built up of 3 sections separated by
+ // the kRunningIdx and kPendingIdx indices.
+ // | complete | running | pending |
+ // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
+ // kRunningIdx points to the first running element.
+ // kPendingIdx points to the first pending element.
+ // This implements a fast queue with an amortized
+ // time of O(1).
+
+ this[kQueue] = []
+ this[kRunningIdx] = 0
+ this[kPendingIdx] = 0
+ }
+
+ get pipelining () {
+ return this[kPipelining]
+ }
+
+ set pipelining (value) {
+ this[kPipelining] = value
+ resume(this, true)
+ }
+
+ get [kPending] () {
+ return this[kQueue].length - this[kPendingIdx]
+ }
+
+ get [kRunning] () {
+ return this[kPendingIdx] - this[kRunningIdx]
+ }
+
+ get [kSize] () {
+ return this[kQueue].length - this[kRunningIdx]
+ }
+
+ get [kConnected] () {
+ return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed
+ }
+
+ get [kBusy] () {
+ const socket = this[kSocket]
+ return (
+ (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||
+ (this[kSize] >= (this[kPipelining] || 1)) ||
+ this[kPending] > 0
+ )
+ }
+
+ /* istanbul ignore: only used for test */
+ [kConnect] (cb) {
+ connect(this)
+ this.once('connect', cb)
+ }
+
+ [kDispatch] (opts, handler) {
+ const origin = opts.origin || this[kUrl].origin
+
+ const request = this[kHTTPConnVersion] === 'h2'
+ ? Request[kHTTP2BuildRequest](origin, opts, handler)
+ : Request[kHTTP1BuildRequest](origin, opts, handler)
+
+ this[kQueue].push(request)
+ if (this[kResuming]) {
+ // Do nothing.
+ } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
+ // Wait a tick in case stream/iterator is ended in the same tick.
+ this[kResuming] = 1
+ process.nextTick(resume, this)
+ } else {
+ resume(this, true)
+ }
+
+ if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
+ this[kNeedDrain] = 2
+ }
+
+ return this[kNeedDrain] < 2
+ }
+
+ async [kClose] () {
+ // TODO: for H2 we need to gracefully flush the remaining enqueued
+ // request and close each stream.
+ return new Promise((resolve) => {
+ if (!this[kSize]) {
+ resolve(null)
+ } else {
+ this[kClosedResolve] = resolve
+ }
+ })
+ }
+
+ async [kDestroy] (err) {
+ return new Promise((resolve) => {
+ const requests = this[kQueue].splice(this[kPendingIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(this, request, err)
+ }
+
+ const callback = () => {
+ if (this[kClosedResolve]) {
+ // TODO (fix): Should we error here with ClientDestroyedError?
+ this[kClosedResolve]()
+ this[kClosedResolve] = null
+ }
+ resolve()
+ }
+
+ if (this[kHTTP2Session] != null) {
+ util.destroy(this[kHTTP2Session], err)
+ this[kHTTP2Session] = null
+ this[kHTTP2SessionState] = null
+ }
+
+ if (!this[kSocket]) {
+ queueMicrotask(callback)
+ } else {
+ util.destroy(this[kSocket].on('close', callback), err)
+ }
+
+ resume(this)
+ })
+ }
+}
+
+function onHttp2SessionError (err) {
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+
+ this[kSocket][kError] = err
+
+ onError(this[kClient], err)
+}
+
+function onHttp2FrameError (type, code, id) {
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
+
+ if (id === 0) {
+ this[kSocket][kError] = err
+ onError(this[kClient], err)
+ }
+}
+
+function onHttp2SessionEnd () {
+ util.destroy(this, new SocketError('other side closed'))
+ util.destroy(this[kSocket], new SocketError('other side closed'))
+}
+
+function onHTTP2GoAway (code) {
+ const client = this[kClient]
+ const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`)
+ client[kSocket] = null
+ client[kHTTP2Session] = null
+
+ if (client.destroyed) {
+ assert(this[kPending] === 0)
+
+ // Fail entire queue.
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(this, request, err)
+ }
+ } else if (client[kRunning] > 0) {
+ // Fail head of pipeline.
+ const request = client[kQueue][client[kRunningIdx]]
+ client[kQueue][client[kRunningIdx]++] = null
+
+ errorRequest(client, request, err)
+ }
+
+ client[kPendingIdx] = client[kRunningIdx]
+
+ assert(client[kRunning] === 0)
+
+ client.emit('disconnect',
+ client[kUrl],
+ [client],
+ err
+ )
+
+ resume(client)
+}
+
+const constants = __nccwpck_require__(40748)
+const createRedirectInterceptor = __nccwpck_require__(99299)
+const EMPTY_BUF = Buffer.alloc(0)
+
+async function lazyllhttp () {
+ const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(63922) : undefined
+
+ let mod
+ try {
+ mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(53742), 'base64'))
+ } catch (e) {
+ /* istanbul ignore next */
+
+ // We could check if the error was caused by the simd option not
+ // being enabled, but the occurring of this other error
+ // * https://github.com/emscripten-core/emscripten/issues/11495
+ // got me to remove that check to avoid breaking Node 12.
+ mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(63922), 'base64'))
+ }
+
+ return await WebAssembly.instantiate(mod, {
+ env: {
+ /* eslint-disable camelcase */
+
+ wasm_on_url: (p, at, len) => {
+ /* istanbul ignore next */
+ return 0
+ },
+ wasm_on_status: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_message_begin: (p) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onMessageBegin() || 0
+ },
+ wasm_on_header_field: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_header_value: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
+ },
+ wasm_on_body: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_message_complete: (p) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onMessageComplete() || 0
+ }
+
+ /* eslint-enable camelcase */
+ }
+ })
+}
+
+let llhttpInstance = null
+let llhttpPromise = lazyllhttp()
+llhttpPromise.catch()
+
+let currentParser = null
+let currentBufferRef = null
+let currentBufferSize = 0
+let currentBufferPtr = null
+
+const TIMEOUT_HEADERS = 1
+const TIMEOUT_BODY = 2
+const TIMEOUT_IDLE = 3
+
+class Parser {
+ constructor (client, socket, { exports }) {
+ assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
+
+ this.llhttp = exports
+ this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
+ this.client = client
+ this.socket = socket
+ this.timeout = null
+ this.timeoutValue = null
+ this.timeoutType = null
+ this.statusCode = null
+ this.statusText = ''
+ this.upgrade = false
+ this.headers = []
+ this.headersSize = 0
+ this.headersMaxSize = client[kMaxHeadersSize]
+ this.shouldKeepAlive = false
+ this.paused = false
+ this.resume = this.resume.bind(this)
+
+ this.bytesRead = 0
+
+ this.keepAlive = ''
+ this.contentLength = ''
+ this.connection = ''
+ this.maxResponseSize = client[kMaxResponseSize]
+ }
+
+ setTimeout (value, type) {
+ this.timeoutType = type
+ if (value !== this.timeoutValue) {
+ timers.clearTimeout(this.timeout)
+ if (value) {
+ this.timeout = timers.setTimeout(onParserTimeout, value, this)
+ // istanbul ignore else: only for jest
+ if (this.timeout.unref) {
+ this.timeout.unref()
+ }
+ } else {
+ this.timeout = null
+ }
+ this.timeoutValue = value
+ } else if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
+ }
+
+ resume () {
+ if (this.socket.destroyed || !this.paused) {
+ return
+ }
+
+ assert(this.ptr != null)
+ assert(currentParser == null)
+
+ this.llhttp.llhttp_resume(this.ptr)
+
+ assert(this.timeoutType === TIMEOUT_BODY)
+ if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
+
+ this.paused = false
+ this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
+ this.readMore()
+ }
+
+ readMore () {
+ while (!this.paused && this.ptr) {
+ const chunk = this.socket.read()
+ if (chunk === null) {
+ break
+ }
+ this.execute(chunk)
+ }
+ }
+
+ execute (data) {
+ assert(this.ptr != null)
+ assert(currentParser == null)
+ assert(!this.paused)
+
+ const { socket, llhttp } = this
+
+ if (data.length > currentBufferSize) {
+ if (currentBufferPtr) {
+ llhttp.free(currentBufferPtr)
+ }
+ currentBufferSize = Math.ceil(data.length / 4096) * 4096
+ currentBufferPtr = llhttp.malloc(currentBufferSize)
+ }
+
+ new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
+
+ // Call `execute` on the wasm parser.
+ // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
+ // and finally the length of bytes to parse.
+ // The return value is an error code or `constants.ERROR.OK`.
+ try {
+ let ret
+
+ try {
+ currentBufferRef = data
+ currentParser = this
+ ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)
+ /* eslint-disable-next-line no-useless-catch */
+ } catch (err) {
+ /* istanbul ignore next: difficult to make a test case for */
+ throw err
+ } finally {
+ currentParser = null
+ currentBufferRef = null
+ }
+
+ const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
+
+ if (ret === constants.ERROR.PAUSED_UPGRADE) {
+ this.onUpgrade(data.slice(offset))
+ } else if (ret === constants.ERROR.PAUSED) {
+ this.paused = true
+ socket.unshift(data.slice(offset))
+ } else if (ret !== constants.ERROR.OK) {
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr)
+ let message = ''
+ /* istanbul ignore else: difficult to make a test case for */
+ if (ptr) {
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
+ message =
+ 'Response does not match the HTTP/1.1 protocol (' +
+ Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
+ ')'
+ }
+ throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
+ }
+ } catch (err) {
+ util.destroy(socket, err)
+ }
+ }
+
+ destroy () {
+ assert(this.ptr != null)
+ assert(currentParser == null)
+
+ this.llhttp.llhttp_free(this.ptr)
+ this.ptr = null
+
+ timers.clearTimeout(this.timeout)
+ this.timeout = null
+ this.timeoutValue = null
+ this.timeoutType = null
+
+ this.paused = false
+ }
+
+ onStatus (buf) {
+ this.statusText = buf.toString()
+ }
+
+ onMessageBegin () {
+ const { socket, client } = this
+
+ /* istanbul ignore next: difficult to make a test case for */
+ if (socket.destroyed) {
+ return -1
+ }
+
+ const request = client[kQueue][client[kRunningIdx]]
+ if (!request) {
+ return -1
+ }
+ }
+
+ onHeaderField (buf) {
+ const len = this.headers.length
+
+ if ((len & 1) === 0) {
+ this.headers.push(buf)
+ } else {
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ }
+
+ this.trackHeader(buf.length)
+ }
+
+ onHeaderValue (buf) {
+ let len = this.headers.length
+
+ if ((len & 1) === 1) {
+ this.headers.push(buf)
+ len += 1
+ } else {
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ }
+
+ const key = this.headers[len - 2]
+ if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {
+ this.keepAlive += buf.toString()
+ } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {
+ this.connection += buf.toString()
+ } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {
+ this.contentLength += buf.toString()
+ }
+
+ this.trackHeader(buf.length)
+ }
+
+ trackHeader (len) {
+ this.headersSize += len
+ if (this.headersSize >= this.headersMaxSize) {
+ util.destroy(this.socket, new HeadersOverflowError())
+ }
+ }
+
+ onUpgrade (head) {
+ const { upgrade, client, socket, headers, statusCode } = this
+
+ assert(upgrade)
+
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
+
+ assert(!socket.destroyed)
+ assert(socket === client[kSocket])
+ assert(!this.paused)
+ assert(request.upgrade || request.method === 'CONNECT')
+
+ this.statusCode = null
+ this.statusText = ''
+ this.shouldKeepAlive = null
+
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
+
+ socket.unshift(head)
+
+ socket[kParser].destroy()
+ socket[kParser] = null
+
+ socket[kClient] = null
+ socket[kError] = null
+ socket
+ .removeListener('error', onSocketError)
+ .removeListener('readable', onSocketReadable)
+ .removeListener('end', onSocketEnd)
+ .removeListener('close', onSocketClose)
+
+ client[kSocket] = null
+ client[kQueue][client[kRunningIdx]++] = null
+ client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
+
+ try {
+ request.onUpgrade(statusCode, headers, socket)
+ } catch (err) {
+ util.destroy(socket, err)
+ }
+
+ resume(client)
+ }
+
+ onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
+ const { client, socket, headers, statusText } = this
+
+ /* istanbul ignore next: difficult to make a test case for */
+ if (socket.destroyed) {
+ return -1
+ }
+
+ const request = client[kQueue][client[kRunningIdx]]
+
+ /* istanbul ignore next: difficult to make a test case for */
+ if (!request) {
+ return -1
+ }
+
+ assert(!this.upgrade)
+ assert(this.statusCode < 200)
+
+ if (statusCode === 100) {
+ util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
+ return -1
+ }
+
+ /* this can only happen if server is misbehaving */
+ if (upgrade && !request.upgrade) {
+ util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
+ return -1
+ }
+
+ assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)
+
+ this.statusCode = statusCode
+ this.shouldKeepAlive = (
+ shouldKeepAlive ||
+ // Override llhttp value which does not allow keepAlive for HEAD.
+ (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
+ )
+
+ if (this.statusCode >= 200) {
+ const bodyTimeout = request.bodyTimeout != null
+ ? request.bodyTimeout
+ : client[kBodyTimeout]
+ this.setTimeout(bodyTimeout, TIMEOUT_BODY)
+ } else if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
+
+ if (request.method === 'CONNECT') {
+ assert(client[kRunning] === 1)
+ this.upgrade = true
+ return 2
+ }
+
+ if (upgrade) {
+ assert(client[kRunning] === 1)
+ this.upgrade = true
+ return 2
+ }
+
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
+
+ if (this.shouldKeepAlive && client[kPipelining]) {
+ const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
+
+ if (keepAliveTimeout != null) {
+ const timeout = Math.min(
+ keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
+ client[kKeepAliveMaxTimeout]
+ )
+ if (timeout <= 0) {
+ socket[kReset] = true
+ } else {
+ client[kKeepAliveTimeoutValue] = timeout
+ }
+ } else {
+ client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
+ }
+ } else {
+ // Stop more requests from being dispatched.
+ socket[kReset] = true
+ }
+
+ const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
+
+ if (request.aborted) {
+ return -1
+ }
+
+ if (request.method === 'HEAD') {
+ return 1
+ }
+
+ if (statusCode < 200) {
+ return 1
+ }
+
+ if (socket[kBlocking]) {
+ socket[kBlocking] = false
+ resume(client)
+ }
+
+ return pause ? constants.ERROR.PAUSED : 0
+ }
+
+ onBody (buf) {
+ const { client, socket, statusCode, maxResponseSize } = this
+
+ if (socket.destroyed) {
+ return -1
+ }
+
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
+
+ assert.strictEqual(this.timeoutType, TIMEOUT_BODY)
+ if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
+
+ assert(statusCode >= 200)
+
+ if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
+ util.destroy(socket, new ResponseExceededMaxSizeError())
+ return -1
+ }
+
+ this.bytesRead += buf.length
+
+ if (request.onData(buf) === false) {
+ return constants.ERROR.PAUSED
+ }
+ }
+
+ onMessageComplete () {
+ const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
+
+ if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
+ return -1
+ }
+
+ if (upgrade) {
+ return
+ }
+
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
+
+ assert(statusCode >= 100)
+
+ this.statusCode = null
+ this.statusText = ''
+ this.bytesRead = 0
+ this.contentLength = ''
+ this.keepAlive = ''
+ this.connection = ''
+
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
+
+ if (statusCode < 200) {
+ return
+ }
+
+ /* istanbul ignore next: should be handled by llhttp? */
+ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
+ util.destroy(socket, new ResponseContentLengthMismatchError())
+ return -1
+ }
+
+ request.onComplete(headers)
+
+ client[kQueue][client[kRunningIdx]++] = null
+
+ if (socket[kWriting]) {
+ assert.strictEqual(client[kRunning], 0)
+ // Response completed before request.
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (!shouldKeepAlive) {
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (socket[kReset] && client[kRunning] === 0) {
+ // Destroy socket once all requests have completed.
+ // The request at the tail of the pipeline is the one
+ // that requested reset and no further requests should
+ // have been queued since then.
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (client[kPipelining] === 1) {
+ // We must wait a full event loop cycle to reuse this socket to make sure
+ // that non-spec compliant servers are not closing the connection even if they
+ // said they won't.
+ setImmediate(resume, client)
+ } else {
+ resume(client)
+ }
+ }
+}
+
+function onParserTimeout (parser) {
+ const { socket, timeoutType, client } = parser
+
+ /* istanbul ignore else */
+ if (timeoutType === TIMEOUT_HEADERS) {
+ if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
+ assert(!parser.paused, 'cannot be paused while waiting for headers')
+ util.destroy(socket, new HeadersTimeoutError())
+ }
+ } else if (timeoutType === TIMEOUT_BODY) {
+ if (!parser.paused) {
+ util.destroy(socket, new BodyTimeoutError())
+ }
+ } else if (timeoutType === TIMEOUT_IDLE) {
+ assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
+ util.destroy(socket, new InformationalError('socket idle timeout'))
+ }
+}
+
+function onSocketReadable () {
+ const { [kParser]: parser } = this
+ if (parser) {
+ parser.readMore()
+ }
+}
+
+function onSocketError (err) {
+ const { [kClient]: client, [kParser]: parser } = this
+
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+
+ if (client[kHTTPConnVersion] !== 'h2') {
+ // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
+ // to the user.
+ if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so for as a valid response.
+ parser.onMessageComplete()
+ return
+ }
+ }
+
+ this[kError] = err
+
+ onError(this[kClient], err)
+}
+
+function onError (client, err) {
+ if (
+ client[kRunning] === 0 &&
+ err.code !== 'UND_ERR_INFO' &&
+ err.code !== 'UND_ERR_SOCKET'
+ ) {
+ // Error is not caused by running request and not a recoverable
+ // socket error.
+
+ assert(client[kPendingIdx] === client[kRunningIdx])
+
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(client, request, err)
+ }
+ assert(client[kSize] === 0)
+ }
+}
+
+function onSocketEnd () {
+ const { [kParser]: parser, [kClient]: client } = this
+
+ if (client[kHTTPConnVersion] !== 'h2') {
+ if (parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so far as a valid response.
+ parser.onMessageComplete()
+ return
+ }
+ }
+
+ util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
+}
+
+function onSocketClose () {
+ const { [kClient]: client, [kParser]: parser } = this
+
+ if (client[kHTTPConnVersion] === 'h1' && parser) {
+ if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so far as a valid response.
+ parser.onMessageComplete()
+ }
+
+ this[kParser].destroy()
+ this[kParser] = null
+ }
+
+ const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
+
+ client[kSocket] = null
+
+ if (client.destroyed) {
+ assert(client[kPending] === 0)
+
+ // Fail entire queue.
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(client, request, err)
+ }
+ } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
+ // Fail head of pipeline.
+ const request = client[kQueue][client[kRunningIdx]]
+ client[kQueue][client[kRunningIdx]++] = null
+
+ errorRequest(client, request, err)
+ }
+
+ client[kPendingIdx] = client[kRunningIdx]
+
+ assert(client[kRunning] === 0)
+
+ client.emit('disconnect', client[kUrl], [client], err)
+
+ resume(client)
+}
+
+async function connect (client) {
+ assert(!client[kConnecting])
+ assert(!client[kSocket])
+
+ let { host, hostname, protocol, port } = client[kUrl]
+
+ // Resolve ipv6
+ if (hostname[0] === '[') {
+ const idx = hostname.indexOf(']')
+
+ assert(idx !== -1)
+ const ip = hostname.substring(1, idx)
+
+ assert(net.isIP(ip))
+ hostname = ip
+ }
+
+ client[kConnecting] = true
+
+ if (channels.beforeConnect.hasSubscribers) {
+ channels.beforeConnect.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector]
+ })
+ }
+
+ try {
+ const socket = await new Promise((resolve, reject) => {
+ client[kConnector]({
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ }, (err, socket) => {
+ if (err) {
+ reject(err)
+ } else {
+ resolve(socket)
+ }
+ })
+ })
+
+ if (client.destroyed) {
+ util.destroy(socket.on('error', () => {}), new ClientDestroyedError())
+ return
+ }
+
+ client[kConnecting] = false
+
+ assert(socket)
+
+ const isH2 = socket.alpnProtocol === 'h2'
+ if (isH2) {
+ if (!h2ExperimentalWarned) {
+ h2ExperimentalWarned = true
+ process.emitWarning('H2 support is experimental, expect them to change at any time.', {
+ code: 'UNDICI-H2'
+ })
+ }
+
+ const session = http2.connect(client[kUrl], {
+ createConnection: () => socket,
+ peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams
+ })
+
+ client[kHTTPConnVersion] = 'h2'
+ session[kClient] = client
+ session[kSocket] = socket
+ session.on('error', onHttp2SessionError)
+ session.on('frameError', onHttp2FrameError)
+ session.on('end', onHttp2SessionEnd)
+ session.on('goaway', onHTTP2GoAway)
+ session.on('close', onSocketClose)
+ session.unref()
+
+ client[kHTTP2Session] = session
+ socket[kHTTP2Session] = session
+ } else {
+ if (!llhttpInstance) {
+ llhttpInstance = await llhttpPromise
+ llhttpPromise = null
+ }
+
+ socket[kNoRef] = false
+ socket[kWriting] = false
+ socket[kReset] = false
+ socket[kBlocking] = false
+ socket[kParser] = new Parser(client, socket, llhttpInstance)
+ }
+
+ socket[kCounter] = 0
+ socket[kMaxRequests] = client[kMaxRequests]
+ socket[kClient] = client
+ socket[kError] = null
+
+ socket
+ .on('error', onSocketError)
+ .on('readable', onSocketReadable)
+ .on('end', onSocketEnd)
+ .on('close', onSocketClose)
+
+ client[kSocket] = socket
+
+ if (channels.connected.hasSubscribers) {
+ channels.connected.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ socket
+ })
+ }
+ client.emit('connect', client[kUrl], [client])
+ } catch (err) {
+ if (client.destroyed) {
+ return
+ }
+
+ client[kConnecting] = false
+
+ if (channels.connectError.hasSubscribers) {
+ channels.connectError.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ error: err
+ })
+ }
+
+ if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
+ assert(client[kRunning] === 0)
+ while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
+ const request = client[kQueue][client[kPendingIdx]++]
+ errorRequest(client, request, err)
+ }
+ } else {
+ onError(client, err)
+ }
+
+ client.emit('connectionError', client[kUrl], [client], err)
+ }
+
+ resume(client)
+}
+
+function emitDrain (client) {
+ client[kNeedDrain] = 0
+ client.emit('drain', client[kUrl], [client])
+}
+
+function resume (client, sync) {
+ if (client[kResuming] === 2) {
+ return
+ }
+
+ client[kResuming] = 2
+
+ _resume(client, sync)
+ client[kResuming] = 0
+
+ if (client[kRunningIdx] > 256) {
+ client[kQueue].splice(0, client[kRunningIdx])
+ client[kPendingIdx] -= client[kRunningIdx]
+ client[kRunningIdx] = 0
+ }
+}
+
+function _resume (client, sync) {
+ while (true) {
+ if (client.destroyed) {
+ assert(client[kPending] === 0)
+ return
+ }
+
+ if (client[kClosedResolve] && !client[kSize]) {
+ client[kClosedResolve]()
+ client[kClosedResolve] = null
+ return
+ }
+
+ const socket = client[kSocket]
+
+ if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {
+ if (client[kSize] === 0) {
+ if (!socket[kNoRef] && socket.unref) {
+ socket.unref()
+ socket[kNoRef] = true
+ }
+ } else if (socket[kNoRef] && socket.ref) {
+ socket.ref()
+ socket[kNoRef] = false
+ }
+
+ if (client[kSize] === 0) {
+ if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
+ socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)
+ }
+ } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
+ if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
+ const request = client[kQueue][client[kRunningIdx]]
+ const headersTimeout = request.headersTimeout != null
+ ? request.headersTimeout
+ : client[kHeadersTimeout]
+ socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
+ }
+ }
+ }
+
+ if (client[kBusy]) {
+ client[kNeedDrain] = 2
+ } else if (client[kNeedDrain] === 2) {
+ if (sync) {
+ client[kNeedDrain] = 1
+ process.nextTick(emitDrain, client)
+ } else {
+ emitDrain(client)
+ }
+ continue
+ }
+
+ if (client[kPending] === 0) {
+ return
+ }
+
+ if (client[kRunning] >= (client[kPipelining] || 1)) {
+ return
+ }
+
+ const request = client[kQueue][client[kPendingIdx]]
+
+ if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
+ if (client[kRunning] > 0) {
+ return
+ }
+
+ client[kServerName] = request.servername
+
+ if (socket && socket.servername !== request.servername) {
+ util.destroy(socket, new InformationalError('servername changed'))
+ return
+ }
+ }
+
+ if (client[kConnecting]) {
+ return
+ }
+
+ if (!socket && !client[kHTTP2Session]) {
+ connect(client)
+ return
+ }
+
+ if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {
+ return
+ }
+
+ if (client[kRunning] > 0 && !request.idempotent) {
+ // Non-idempotent request cannot be retried.
+ // Ensure that no other requests are inflight and
+ // could cause failure.
+ return
+ }
+
+ if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
+ // Don't dispatch an upgrade until all preceding requests have completed.
+ // A misbehaving server might upgrade the connection before all pipelined
+ // request has completed.
+ return
+ }
+
+ if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
+ (util.isStream(request.body) || util.isAsyncIterable(request.body))) {
+ // Request with stream or iterator body can error while other requests
+ // are inflight and indirectly error those as well.
+ // Ensure this doesn't happen by waiting for inflight
+ // to complete before dispatching.
+
+ // Request with stream or iterator body cannot be retried.
+ // Ensure that no other requests are inflight and
+ // could cause failure.
+ return
+ }
+
+ if (!request.aborted && write(client, request)) {
+ client[kPendingIdx]++
+ } else {
+ client[kQueue].splice(client[kPendingIdx], 1)
+ }
+ }
+}
+
+// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
+function shouldSendContentLength (method) {
+ return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
+}
+
+function write (client, request) {
+ if (client[kHTTPConnVersion] === 'h2') {
+ writeH2(client, client[kHTTP2Session], request)
+ return
+ }
+
+ const { body, method, path, host, upgrade, headers, blocking, reset } = request
+
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
+
+ // Sending a payload body on a request that does not
+ // expect it can cause undefined behavior on some
+ // servers and corrupt connection state. Do not
+ // re-use the connection for further requests.
+
+ const expectsPayload = (
+ method === 'PUT' ||
+ method === 'POST' ||
+ method === 'PATCH'
+ )
+
+ if (body && typeof body.read === 'function') {
+ // Try to read EOF in order to get length.
+ body.read(0)
+ }
+
+ const bodyLength = util.bodyLength(body)
+
+ let contentLength = bodyLength
+
+ if (contentLength === null) {
+ contentLength = request.contentLength
+ }
+
+ if (contentLength === 0 && !expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD NOT send a Content-Length header field when
+ // the request message does not contain a payload body and the method
+ // semantics do not anticipate such a body.
+
+ contentLength = null
+ }
+
+ // https://github.com/nodejs/undici/issues/2046
+ // A user agent may send a Content-Length header with 0 value, this should be allowed.
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
+ if (client[kStrictContentLength]) {
+ errorRequest(client, request, new RequestContentLengthMismatchError())
+ return false
+ }
+
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
+
+ const socket = client[kSocket]
+
+ try {
+ request.onConnect((err) => {
+ if (request.aborted || request.completed) {
+ return
+ }
+
+ errorRequest(client, request, err || new RequestAbortedError())
+
+ util.destroy(socket, new InformationalError('aborted'))
+ })
+ } catch (err) {
+ errorRequest(client, request, err)
+ }
+
+ if (request.aborted) {
+ return false
+ }
+
+ if (method === 'HEAD') {
+ // https://github.com/mcollina/undici/issues/258
+ // Close after a HEAD request to interop with misbehaving servers
+ // that may send a body in the response.
+
+ socket[kReset] = true
+ }
+
+ if (upgrade || method === 'CONNECT') {
+ // On CONNECT or upgrade, block pipeline from dispatching further
+ // requests on this connection.
+
+ socket[kReset] = true
+ }
+
+ if (reset != null) {
+ socket[kReset] = reset
+ }
+
+ if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
+ socket[kReset] = true
+ }
+
+ if (blocking) {
+ socket[kBlocking] = true
+ }
+
+ let header = `${method} ${path} HTTP/1.1\r\n`
+
+ if (typeof host === 'string') {
+ header += `host: ${host}\r\n`
+ } else {
+ header += client[kHostHeader]
+ }
+
+ if (upgrade) {
+ header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
+ } else if (client[kPipelining] && !socket[kReset]) {
+ header += 'connection: keep-alive\r\n'
+ } else {
+ header += 'connection: close\r\n'
+ }
+
+ if (headers) {
+ header += headers
+ }
+
+ if (channels.sendHeaders.hasSubscribers) {
+ channels.sendHeaders.publish({ request, headers: header, socket })
+ }
+
+ /* istanbul ignore else: assertion */
+ if (!body || bodyLength === 0) {
+ if (contentLength === 0) {
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
+ } else {
+ assert(contentLength === null, 'no body must not have content length')
+ socket.write(`${header}\r\n`, 'latin1')
+ }
+ request.onRequestSent()
+ } else if (util.isBuffer(body)) {
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
+
+ socket.cork()
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ socket.write(body)
+ socket.uncork()
+ request.onBodySent(body)
+ request.onRequestSent()
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === 'function') {
+ writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })
+ } else {
+ writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })
+ }
+ } else if (util.isStream(body)) {
+ writeStream({ body, client, request, socket, contentLength, header, expectsPayload })
+ } else if (util.isIterable(body)) {
+ writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })
+ } else {
+ assert(false)
+ }
+
+ return true
+}
+
+function writeH2 (client, session, request) {
+ const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
+
+ let headers
+ if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())
+ else headers = reqHeaders
+
+ if (upgrade) {
+ errorRequest(client, request, new Error('Upgrade not supported for H2'))
+ return false
+ }
+
+ try {
+ // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?
+ request.onConnect((err) => {
+ if (request.aborted || request.completed) {
+ return
+ }
+
+ errorRequest(client, request, err || new RequestAbortedError())
+ })
+ } catch (err) {
+ errorRequest(client, request, err)
+ }
+
+ if (request.aborted) {
+ return false
+ }
+
+ /** @type {import('node:http2').ClientHttp2Stream} */
+ let stream
+ const h2State = client[kHTTP2SessionState]
+
+ headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]
+ headers[HTTP2_HEADER_METHOD] = method
+
+ if (method === 'CONNECT') {
+ session.ref()
+ // we are already connected, streams are pending, first request
+ // will create a new stream. We trigger a request to create the stream and wait until
+ // `ready` event is triggered
+ // We disabled endStream to allow the user to write to the stream
+ stream = session.request(headers, { endStream: false, signal })
+
+ if (stream.id && !stream.pending) {
+ request.onUpgrade(null, null, stream)
+ ++h2State.openStreams
+ } else {
+ stream.once('ready', () => {
+ request.onUpgrade(null, null, stream)
+ ++h2State.openStreams
+ })
+ }
+
+ stream.once('close', () => {
+ h2State.openStreams -= 1
+ // TODO(HTTP/2): unref only if current streams count is 0
+ if (h2State.openStreams === 0) session.unref()
+ })
+
+ return true
+ }
+
+ // https://tools.ietf.org/html/rfc7540#section-8.3
+ // :path and :scheme headers must be omited when sending CONNECT
+
+ headers[HTTP2_HEADER_PATH] = path
+ headers[HTTP2_HEADER_SCHEME] = 'https'
+
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
+
+ // Sending a payload body on a request that does not
+ // expect it can cause undefined behavior on some
+ // servers and corrupt connection state. Do not
+ // re-use the connection for further requests.
+
+ const expectsPayload = (
+ method === 'PUT' ||
+ method === 'POST' ||
+ method === 'PATCH'
+ )
+
+ if (body && typeof body.read === 'function') {
+ // Try to read EOF in order to get length.
+ body.read(0)
+ }
+
+ let contentLength = util.bodyLength(body)
+
+ if (contentLength == null) {
+ contentLength = request.contentLength
+ }
+
+ if (contentLength === 0 || !expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD NOT send a Content-Length header field when
+ // the request message does not contain a payload body and the method
+ // semantics do not anticipate such a body.
+
+ contentLength = null
+ }
+
+ // https://github.com/nodejs/undici/issues/2046
+ // A user agent may send a Content-Length header with 0 value, this should be allowed.
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
+ if (client[kStrictContentLength]) {
+ errorRequest(client, request, new RequestContentLengthMismatchError())
+ return false
+ }
+
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
+
+ if (contentLength != null) {
+ assert(body, 'no body must not have content length')
+ headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
+ }
+
+ session.ref()
+
+ const shouldEndStream = method === 'GET' || method === 'HEAD'
+ if (expectContinue) {
+ headers[HTTP2_HEADER_EXPECT] = '100-continue'
+ stream = session.request(headers, { endStream: shouldEndStream, signal })
+
+ stream.once('continue', writeBodyH2)
+ } else {
+ stream = session.request(headers, {
+ endStream: shouldEndStream,
+ signal
+ })
+ writeBodyH2()
+ }
+
+ // Increment counter as we have new several streams open
+ ++h2State.openStreams
+
+ stream.once('response', headers => {
+ const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
+
+ if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {
+ stream.pause()
+ }
+ })
+
+ stream.once('end', () => {
+ request.onComplete([])
+ })
+
+ stream.on('data', (chunk) => {
+ if (request.onData(chunk) === false) {
+ stream.pause()
+ }
+ })
+
+ stream.once('close', () => {
+ h2State.openStreams -= 1
+ // TODO(HTTP/2): unref only if current streams count is 0
+ if (h2State.openStreams === 0) {
+ session.unref()
+ }
+ })
+
+ stream.once('error', function (err) {
+ if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
+ h2State.streams -= 1
+ util.destroy(stream, err)
+ }
+ })
+
+ stream.once('frameError', (type, code) => {
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
+ errorRequest(client, request, err)
+
+ if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
+ h2State.streams -= 1
+ util.destroy(stream, err)
+ }
+ })
+
+ // stream.on('aborted', () => {
+ // // TODO(HTTP/2): Support aborted
+ // })
+
+ // stream.on('timeout', () => {
+ // // TODO(HTTP/2): Support timeout
+ // })
+
+ // stream.on('push', headers => {
+ // // TODO(HTTP/2): Suppor push
+ // })
+
+ // stream.on('trailers', headers => {
+ // // TODO(HTTP/2): Support trailers
+ // })
+
+ return true
+
+ function writeBodyH2 () {
+ /* istanbul ignore else: assertion */
+ if (!body) {
+ request.onRequestSent()
+ } else if (util.isBuffer(body)) {
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
+ stream.cork()
+ stream.write(body)
+ stream.uncork()
+ stream.end()
+ request.onBodySent(body)
+ request.onRequestSent()
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === 'function') {
+ writeIterable({
+ client,
+ request,
+ contentLength,
+ h2stream: stream,
+ expectsPayload,
+ body: body.stream(),
+ socket: client[kSocket],
+ header: ''
+ })
+ } else {
+ writeBlob({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ h2stream: stream,
+ header: '',
+ socket: client[kSocket]
+ })
+ }
+ } else if (util.isStream(body)) {
+ writeStream({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ socket: client[kSocket],
+ h2stream: stream,
+ header: ''
+ })
+ } else if (util.isIterable(body)) {
+ writeIterable({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ header: '',
+ h2stream: stream,
+ socket: client[kSocket]
+ })
+ } else {
+ assert(false)
+ }
+ }
+}
+
+function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
+
+ if (client[kHTTPConnVersion] === 'h2') {
+ // For HTTP/2, is enough to pipe the stream
+ const pipe = pipeline(
+ body,
+ h2stream,
+ (err) => {
+ if (err) {
+ util.destroy(body, err)
+ util.destroy(h2stream, err)
+ } else {
+ request.onRequestSent()
+ }
+ }
+ )
+
+ pipe.on('data', onPipeData)
+ pipe.once('end', () => {
+ pipe.removeListener('data', onPipeData)
+ util.destroy(pipe)
+ })
+
+ function onPipeData (chunk) {
+ request.onBodySent(chunk)
+ }
+
+ return
+ }
+
+ let finished = false
+
+ const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
+
+ const onData = function (chunk) {
+ if (finished) {
+ return
+ }
+
+ try {
+ if (!writer.write(chunk) && this.pause) {
+ this.pause()
+ }
+ } catch (err) {
+ util.destroy(this, err)
+ }
+ }
+ const onDrain = function () {
+ if (finished) {
+ return
+ }
+
+ if (body.resume) {
+ body.resume()
+ }
+ }
+ const onAbort = function () {
+ if (finished) {
+ return
+ }
+ const err = new RequestAbortedError()
+ queueMicrotask(() => onFinished(err))
+ }
+ const onFinished = function (err) {
+ if (finished) {
+ return
+ }
+
+ finished = true
+
+ assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
+
+ socket
+ .off('drain', onDrain)
+ .off('error', onFinished)
+
+ body
+ .removeListener('data', onData)
+ .removeListener('end', onFinished)
+ .removeListener('error', onFinished)
+ .removeListener('close', onAbort)
+
+ if (!err) {
+ try {
+ writer.end()
+ } catch (er) {
+ err = er
+ }
+ }
+
+ writer.destroy(err)
+
+ if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
+ util.destroy(body, err)
+ } else {
+ util.destroy(body)
+ }
+ }
+
+ body
+ .on('data', onData)
+ .on('end', onFinished)
+ .on('error', onFinished)
+ .on('close', onAbort)
+
+ if (body.resume) {
+ body.resume()
+ }
+
+ socket
+ .on('drain', onDrain)
+ .on('error', onFinished)
+}
+
+async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength === body.size, 'blob body must have content length')
+
+ const isH2 = client[kHTTPConnVersion] === 'h2'
+ try {
+ if (contentLength != null && contentLength !== body.size) {
+ throw new RequestContentLengthMismatchError()
}
- ];
- const list = appleModelIds.filter((model) => model.key === key);
- if (list.length === 0) {
+ const buffer = Buffer.from(await body.arrayBuffer())
+
+ if (isH2) {
+ h2stream.cork()
+ h2stream.write(buffer)
+ h2stream.uncork()
+ } else {
+ socket.cork()
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ socket.write(buffer)
+ socket.uncork()
+ }
+
+ request.onBodySent(buffer)
+ request.onRequestSent()
+
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
+
+ resume(client)
+ } catch (err) {
+ util.destroy(isH2 ? h2stream : socket, err)
+ }
+}
+
+async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
+
+ let callback = null
+ function onDrain () {
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb()
+ }
+ }
+
+ const waitForDrain = () => new Promise((resolve, reject) => {
+ assert(callback === null)
+
+ if (socket[kError]) {
+ reject(socket[kError])
+ } else {
+ callback = resolve
+ }
+ })
+
+ if (client[kHTTPConnVersion] === 'h2') {
+ h2stream
+ .on('close', onDrain)
+ .on('drain', onDrain)
+
+ try {
+ // It's up to the user to somehow abort the async iterable.
+ for await (const chunk of body) {
+ if (socket[kError]) {
+ throw socket[kError]
+ }
+
+ const res = h2stream.write(chunk)
+ request.onBodySent(chunk)
+ if (!res) {
+ await waitForDrain()
+ }
+ }
+ } catch (err) {
+ h2stream.destroy(err)
+ } finally {
+ request.onRequestSent()
+ h2stream.end()
+ h2stream
+ .off('close', onDrain)
+ .off('drain', onDrain)
+ }
+
+ return
+ }
+
+ socket
+ .on('close', onDrain)
+ .on('drain', onDrain)
+
+ const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
+ try {
+ // It's up to the user to somehow abort the async iterable.
+ for await (const chunk of body) {
+ if (socket[kError]) {
+ throw socket[kError]
+ }
+
+ if (!writer.write(chunk)) {
+ await waitForDrain()
+ }
+ }
+
+ writer.end()
+ } catch (err) {
+ writer.destroy(err)
+ } finally {
+ socket
+ .off('close', onDrain)
+ .off('drain', onDrain)
+ }
+}
+
+class AsyncWriter {
+ constructor ({ socket, request, contentLength, client, expectsPayload, header }) {
+ this.socket = socket
+ this.request = request
+ this.contentLength = contentLength
+ this.client = client
+ this.bytesWritten = 0
+ this.expectsPayload = expectsPayload
+ this.header = header
+
+ socket[kWriting] = true
+ }
+
+ write (chunk) {
+ const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
+
+ if (socket[kError]) {
+ throw socket[kError]
+ }
+
+ if (socket.destroyed) {
+ return false
+ }
+
+ const len = Buffer.byteLength(chunk)
+ if (!len) {
+ return true
+ }
+
+ // We should defer writing chunks.
+ if (contentLength !== null && bytesWritten + len > contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError()
+ }
+
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
+
+ socket.cork()
+
+ if (bytesWritten === 0) {
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
+
+ if (contentLength === null) {
+ socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
+ } else {
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ }
+ }
+
+ if (contentLength === null) {
+ socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
+ }
+
+ this.bytesWritten += len
+
+ const ret = socket.write(chunk)
+
+ socket.uncork()
+
+ request.onBodySent(chunk)
+
+ if (!ret) {
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ // istanbul ignore else: only for jest
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh()
+ }
+ }
+ }
+
+ return ret
+ }
+
+ end () {
+ const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
+ request.onRequestSent()
+
+ socket[kWriting] = false
+
+ if (socket[kError]) {
+ throw socket[kError]
+ }
+
+ if (socket.destroyed) {
+ return
+ }
+
+ if (bytesWritten === 0) {
+ if (expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD send a Content-Length in a request message when
+ // no Transfer-Encoding is sent and the request method defines a meaning
+ // for an enclosed payload body.
+
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
+ } else {
+ socket.write(`${header}\r\n`, 'latin1')
+ }
+ } else if (contentLength === null) {
+ socket.write('\r\n0\r\n\r\n', 'latin1')
+ }
+
+ if (contentLength !== null && bytesWritten !== contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError()
+ } else {
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
+ }
+
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ // istanbul ignore else: only for jest
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh()
+ }
+ }
+
+ resume(client)
+ }
+
+ destroy (err) {
+ const { socket, client } = this
+
+ socket[kWriting] = false
+
+ if (err) {
+ assert(client[kRunning] <= 1, 'pipeline should only contain this request')
+ util.destroy(socket, err)
+ }
+ }
+}
+
+function errorRequest (client, request, err) {
+ try {
+ request.onError(err)
+ assert(request.aborted)
+ } catch (err) {
+ client.emit('error', err)
+ }
+}
+
+module.exports = Client
+
+
+/***/ }),
+
+/***/ 90022:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+/* istanbul ignore file: only for Node 12 */
+
+const { kConnected, kSize } = __nccwpck_require__(68031)
+
+class CompatWeakRef {
+ constructor (value) {
+ this.value = value
+ }
+
+ deref () {
+ return this.value[kConnected] === 0 && this.value[kSize] === 0
+ ? undefined
+ : this.value
+ }
+}
+
+class CompatFinalizer {
+ constructor (finalizer) {
+ this.finalizer = finalizer
+ }
+
+ register (dispatcher, key) {
+ if (dispatcher.on) {
+ dispatcher.on('disconnect', () => {
+ if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
+ this.finalizer(key)
+ }
+ })
+ }
+ }
+}
+
+module.exports = function () {
+ // FIXME: remove workaround when the Node bug is fixed
+ // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
+ if (process.env.NODE_V8_COVERAGE) {
return {
- key: key,
- model: 'Apple',
- version: 'Unknown'
- };
+ WeakRef: CompatWeakRef,
+ FinalizationRegistry: CompatFinalizer
+ }
}
- const features = [];
- if (list[0].size) { features.push(list[0].size); }
- if (list[0].processor) { features.push(list[0].processor); }
- if (list[0].year) { features.push(list[0].year); }
- if (list[0].additional) { features.push(list[0].additional); }
return {
- key: key,
- model: list[0].name,
- version: list[0].name + ' (' + features.join(', ') + ')'
- };
+ WeakRef: global.WeakRef || CompatWeakRef,
+ FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
+ }
}
-function checkWebsite(url, timeout = 5000) {
- const http = ((url.startsWith('https:') || url.indexOf(':443/') > 0 || url.indexOf(':8443/') > 0) ? __nccwpck_require__(65692) : __nccwpck_require__(58611));
- const t = Date.now();
- return new Promise((resolve) => {
- const request = http
- .get(url, { rejectUnauthorized: false }, function (res) {
- res.on('data', () => { });
- res.on('end', () => {
- resolve({
- url,
- statusCode: res.statusCode,
- message: res.statusMessage,
- time: Date.now() - t
- });
- });
- })
- .on("error", function (e) {
- resolve({
- url,
- statusCode: 404,
- message: e.message,
- time: Date.now() - t
- });
- })
- .setTimeout(timeout, () => {
- request.close();
- resolve({
- url,
- statusCode: 408,
- message: 'Request Timeout',
- time: Date.now() - t
- });
- });
- });
-};
-function noop() { }
+/***/ }),
-exports.toInt = toInt;
-exports.splitByNumber = splitByNumber;
-exports.execOptsWin = execOptsWin;
-exports.execOptsLinux = execOptsLinux;
-exports.getCodepage = getCodepage;
-exports.execWin = execWin;
-exports.isFunction = isFunction;
-exports.unique = unique;
-exports.sortByKey = sortByKey;
-exports.cores = cores;
-exports.getValue = getValue;
-exports.decodeEscapeSequence = decodeEscapeSequence;
-exports.parseDateTime = parseDateTime;
-exports.parseHead = parseHead;
-exports.findObjectByKey = findObjectByKey;
-exports.getWmic = getWmic;
-exports.wmic = wmic;
-exports.darwinXcodeExists = darwinXcodeExists;
-exports.getVboxmanage = getVboxmanage;
-exports.powerShell = powerShell;
-exports.powerShellStart = powerShellStart;
-exports.powerShellRelease = powerShellRelease;
-exports.execSafe = execSafe;
-exports.nanoSeconds = nanoSeconds;
-exports.countUniqueLines = countUniqueLines;
-exports.countLines = countLines;
-exports.noop = noop;
-exports.isRaspberry = isRaspberry;
-exports.isRaspbian = isRaspbian;
-exports.sanitizeShellString = sanitizeShellString;
-exports.isPrototypePolluted = isPrototypePolluted;
-exports.decodePiCpuinfo = decodePiCpuinfo;
-exports.getRpiGpu = getRpiGpu;
-exports.promiseAll = promiseAll;
-exports.promisify = promisify;
-exports.promisifySave = promisifySave;
-exports.smartMonToolsInstalled = smartMonToolsInstalled;
-exports.linuxVersion = linuxVersion;
-exports.plistParser = plistParser;
-exports.plistReader = plistReader;
-exports.stringObj = stringObj;
-exports.stringReplace = stringReplace;
-exports.stringToLower = stringToLower;
-exports.stringToString = stringToString;
-exports.stringSubstr = stringSubstr;
-exports.stringTrim = stringTrim;
-exports.stringStartWith = stringStartWith;
-exports.mathMin = mathMin;
-exports.WINDIR = WINDIR;
-exports.getFilesInPath = getFilesInPath;
-exports.semverCompare = semverCompare;
-exports.getAppleModel = getAppleModel;
-exports.checkWebsite = checkWebsite;
+/***/ 16985:
+/***/ ((module) => {
+
+
+
+// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size
+const maxAttributeValueSize = 1024
+
+// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size
+const maxNameValuePairSize = 4096
+
+module.exports = {
+ maxAttributeValueSize,
+ maxNameValuePairSize
+}
+
+
+/***/ }),
+
+/***/ 64276:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { parseSetCookie } = __nccwpck_require__(16695)
+const { stringify, getHeadersList } = __nccwpck_require__(83126)
+const { webidl } = __nccwpck_require__(94354)
+const { Headers } = __nccwpck_require__(12801)
+
+/**
+ * @typedef {Object} Cookie
+ * @property {string} name
+ * @property {string} value
+ * @property {Date|number|undefined} expires
+ * @property {number|undefined} maxAge
+ * @property {string|undefined} domain
+ * @property {string|undefined} path
+ * @property {boolean|undefined} secure
+ * @property {boolean|undefined} httpOnly
+ * @property {'Strict'|'Lax'|'None'} sameSite
+ * @property {string[]} unparsed
+ */
+
+/**
+ * @param {Headers} headers
+ * @returns {Record}
+ */
+function getCookies (headers) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })
+
+ webidl.brandCheck(headers, Headers, { strict: false })
+
+ const cookie = headers.get('cookie')
+ const out = {}
+
+ if (!cookie) {
+ return out
+ }
+
+ for (const piece of cookie.split(';')) {
+ const [name, ...value] = piece.split('=')
+
+ out[name.trim()] = value.join('=')
+ }
+
+ return out
+}
+
+/**
+ * @param {Headers} headers
+ * @param {string} name
+ * @param {{ path?: string, domain?: string }|undefined} attributes
+ * @returns {void}
+ */
+function deleteCookie (headers, name, attributes) {
+ webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })
+
+ webidl.brandCheck(headers, Headers, { strict: false })
+
+ name = webidl.converters.DOMString(name)
+ attributes = webidl.converters.DeleteCookieAttributes(attributes)
+
+ // Matches behavior of
+ // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
+ setCookie(headers, {
+ name,
+ value: '',
+ expires: new Date(0),
+ ...attributes
+ })
+}
+/**
+ * @param {Headers} headers
+ * @returns {Cookie[]}
+ */
+function getSetCookies (headers) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })
-/***/ }),
+ webidl.brandCheck(headers, Headers, { strict: false })
-/***/ 3881:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ const cookies = getHeadersList(headers).cookies
+ if (!cookies) {
+ return []
+ }
-// @ts-check
-// ==================================================================================
-// virtualbox.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 14. Docker
-// ----------------------------------------------------------------------------------
+ // In older versions of undici, cookies is a list of name:value.
+ return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair))
+}
-const os = __nccwpck_require__(70857);
-const exec = (__nccwpck_require__(35317).exec);
-const util = __nccwpck_require__(33225);
+/**
+ * @param {Headers} headers
+ * @param {Cookie} cookie
+ * @returns {void}
+ */
+function setCookie (headers, cookie) {
+ webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })
-function vboxInfo(callback) {
+ webidl.brandCheck(headers, Headers, { strict: false })
- // fallback - if only callback is given
- let result = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
- try {
- exec(util.getVboxmanage() + ' list vms --long', function (error, stdout) {
- let parts = (os.EOL + stdout.toString()).split(os.EOL + 'Name:');
- parts.shift();
- parts.forEach(part => {
- const lines = ('Name:' + part).split(os.EOL);
- const state = util.getValue(lines, 'State');
- const running = state.startsWith('running');
- const runningSinceString = running ? state.replace('running (since ', '').replace(')', '').trim() : '';
- let runningSince = 0;
- try {
- if (running) {
- const sinceDateObj = new Date(runningSinceString);
- const offset = sinceDateObj.getTimezoneOffset();
- runningSince = Math.round((Date.now() - Date.parse(sinceDateObj)) / 1000) + offset * 60;
- }
- } catch (e) {
- util.noop();
- }
- const stoppedSinceString = !running ? state.replace('powered off (since', '').replace(')', '').trim() : '';
- let stoppedSince = 0;
- try {
- if (!running) {
- const sinceDateObj = new Date(stoppedSinceString);
- const offset = sinceDateObj.getTimezoneOffset();
- stoppedSince = Math.round((Date.now() - Date.parse(sinceDateObj)) / 1000) + offset * 60;
- }
- } catch (e) {
- util.noop();
- }
- result.push({
- id: util.getValue(lines, 'UUID'),
- name: util.getValue(lines, 'Name'),
- running,
- started: runningSinceString,
- runningSince,
- stopped: stoppedSinceString,
- stoppedSince,
- guestOS: util.getValue(lines, 'Guest OS'),
- hardwareUUID: util.getValue(lines, 'Hardware UUID'),
- memory: parseInt(util.getValue(lines, 'Memory size', ' '), 10),
- vram: parseInt(util.getValue(lines, 'VRAM size'), 10),
- cpus: parseInt(util.getValue(lines, 'Number of CPUs'), 10),
- cpuExepCap: util.getValue(lines, 'CPU exec cap'),
- cpuProfile: util.getValue(lines, 'CPUProfile'),
- chipset: util.getValue(lines, 'Chipset'),
- firmware: util.getValue(lines, 'Firmware'),
- pageFusion: util.getValue(lines, 'Page Fusion') === 'enabled',
- configFile: util.getValue(lines, 'Config file'),
- snapshotFolder: util.getValue(lines, 'Snapshot folder'),
- logFolder: util.getValue(lines, 'Log folder'),
- hpet: util.getValue(lines, 'HPET') === 'enabled',
- pae: util.getValue(lines, 'PAE') === 'enabled',
- longMode: util.getValue(lines, 'Long Mode') === 'enabled',
- tripleFaultReset: util.getValue(lines, 'Triple Fault Reset') === 'enabled',
- apic: util.getValue(lines, 'APIC') === 'enabled',
- x2Apic: util.getValue(lines, 'X2APIC') === 'enabled',
- acpi: util.getValue(lines, 'ACPI') === 'enabled',
- ioApic: util.getValue(lines, 'IOAPIC') === 'enabled',
- biosApicMode: util.getValue(lines, 'BIOS APIC mode'),
- bootMenuMode: util.getValue(lines, 'Boot menu mode'),
- bootDevice1: util.getValue(lines, 'Boot Device 1'),
- bootDevice2: util.getValue(lines, 'Boot Device 2'),
- bootDevice3: util.getValue(lines, 'Boot Device 3'),
- bootDevice4: util.getValue(lines, 'Boot Device 4'),
- timeOffset: util.getValue(lines, 'Time offset'),
- rtc: util.getValue(lines, 'RTC'),
- });
- });
+ cookie = webidl.converters.Cookie(cookie)
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
+ const str = stringify(cookie)
+
+ if (str) {
+ headers.append('Set-Cookie', stringify(cookie))
+ }
}
-exports.vboxInfo = vboxInfo;
+webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'path',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'domain',
+ defaultValue: null
+ }
+])
+
+webidl.converters.Cookie = webidl.dictionaryConverter([
+ {
+ converter: webidl.converters.DOMString,
+ key: 'name'
+ },
+ {
+ converter: webidl.converters.DOMString,
+ key: 'value'
+ },
+ {
+ converter: webidl.nullableConverter((value) => {
+ if (typeof value === 'number') {
+ return webidl.converters['unsigned long long'](value)
+ }
+
+ return new Date(value)
+ }),
+ key: 'expires',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters['long long']),
+ key: 'maxAge',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'domain',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'path',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.boolean),
+ key: 'secure',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.boolean),
+ key: 'httpOnly',
+ defaultValue: null
+ },
+ {
+ converter: webidl.converters.USVString,
+ key: 'sameSite',
+ allowedValues: ['Strict', 'Lax', 'None']
+ },
+ {
+ converter: webidl.sequenceConverter(webidl.converters.DOMString),
+ key: 'unparsed',
+ defaultValue: []
+ }
+])
+
+module.exports = {
+ getCookies,
+ deleteCookie,
+ getSetCookies,
+ setCookie
+}
/***/ }),
-/***/ 81180:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 16695:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// @ts-check
-// ==================================================================================
-// wifi.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 9. wifi
-// ----------------------------------------------------------------------------------
-const os = __nccwpck_require__(70857);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const util = __nccwpck_require__(33225);
+const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(16985)
+const { isCTLExcludingHtab } = __nccwpck_require__(83126)
+const { collectASequenceOfCodePointsFast } = __nccwpck_require__(37246)
+const assert = __nccwpck_require__(42613)
-let _platform = process.platform;
+/**
+ * @description Parses the field-value attributes of a set-cookie header string.
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
+ * @param {string} header
+ * @returns if the header is invalid, null will be returned
+ */
+function parseSetCookie (header) {
+ // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
+ // character (CTL characters excluding HTAB): Abort these steps and
+ // ignore the set-cookie-string entirely.
+ if (isCTLExcludingHtab(header)) {
+ return null
+ }
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
+ let nameValuePair = ''
+ let unparsedAttributes = ''
+ let name = ''
+ let value = ''
-function wifiDBFromQuality(quality) {
- const qual = parseFloat(quality);
- if (qual < 0) { return 0; }
- if (qual >= 100) { return -50; }
- return (qual / 2 - 100);
-}
+ // 2. If the set-cookie-string contains a %x3B (";") character:
+ if (header.includes(';')) {
+ // 1. The name-value-pair string consists of the characters up to,
+ // but not including, the first %x3B (";"), and the unparsed-
+ // attributes consist of the remainder of the set-cookie-string
+ // (including the %x3B (";") in question).
+ const position = { position: 0 }
-function wifiQualityFromDB(db) {
- const result = 2 * (parseFloat(db) + 100);
- return result <= 100 ? result : 100;
-}
+ nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
+ unparsedAttributes = header.slice(position.position)
+ } else {
+ // Otherwise:
-const _wifi_frequencies = {
- 1: 2412,
- 2: 2417,
- 3: 2422,
- 4: 2427,
- 5: 2432,
- 6: 2437,
- 7: 2442,
- 8: 2447,
- 9: 2452,
- 10: 2457,
- 11: 2462,
- 12: 2467,
- 13: 2472,
- 14: 2484,
- 32: 5160,
- 34: 5170,
- 36: 5180,
- 38: 5190,
- 40: 5200,
- 42: 5210,
- 44: 5220,
- 46: 5230,
- 48: 5240,
- 50: 5250,
- 52: 5260,
- 54: 5270,
- 56: 5280,
- 58: 5290,
- 60: 5300,
- 62: 5310,
- 64: 5320,
- 68: 5340,
- 96: 5480,
- 100: 5500,
- 102: 5510,
- 104: 5520,
- 106: 5530,
- 108: 5540,
- 110: 5550,
- 112: 5560,
- 114: 5570,
- 116: 5580,
- 118: 5590,
- 120: 5600,
- 122: 5610,
- 124: 5620,
- 126: 5630,
- 128: 5640,
- 132: 5660,
- 134: 5670,
- 136: 5680,
- 138: 5690,
- 140: 5700,
- 142: 5710,
- 144: 5720,
- 149: 5745,
- 151: 5755,
- 153: 5765,
- 155: 5775,
- 157: 5785,
- 159: 5795,
- 161: 5805,
- 165: 5825,
- 169: 5845,
- 173: 5865,
- 183: 4915,
- 184: 4920,
- 185: 4925,
- 187: 4935,
- 188: 4940,
- 189: 4945,
- 192: 4960,
- 196: 4980
-};
+ // 1. The name-value-pair string consists of all the characters
+ // contained in the set-cookie-string, and the unparsed-
+ // attributes is the empty string.
+ nameValuePair = header
+ }
-function wifiFrequencyFromChannel(channel) {
- return {}.hasOwnProperty.call(_wifi_frequencies, channel) ? _wifi_frequencies[channel] : null;
-}
+ // 3. If the name-value-pair string lacks a %x3D ("=") character, then
+ // the name string is empty, and the value string is the value of
+ // name-value-pair.
+ if (!nameValuePair.includes('=')) {
+ value = nameValuePair
+ } else {
+ // Otherwise, the name string consists of the characters up to, but
+ // not including, the first %x3D ("=") character, and the (possibly
+ // empty) value string consists of the characters after the first
+ // %x3D ("=") character.
+ const position = { position: 0 }
+ name = collectASequenceOfCodePointsFast(
+ '=',
+ nameValuePair,
+ position
+ )
+ value = nameValuePair.slice(position.position + 1)
+ }
-function wifiChannelFromFrequencs(frequency) {
- let channel = 0;
- for (let key in _wifi_frequencies) {
- if ({}.hasOwnProperty.call(_wifi_frequencies, key)) {
- if (_wifi_frequencies[key] === frequency) { channel = util.toInt(key); }
- }
+ // 4. Remove any leading or trailing WSP characters from the name
+ // string and the value string.
+ name = name.trim()
+ value = value.trim()
+
+ // 5. If the sum of the lengths of the name string and the value string
+ // is more than 4096 octets, abort these steps and ignore the set-
+ // cookie-string entirely.
+ if (name.length + value.length > maxNameValuePairSize) {
+ return null
}
- return channel;
-}
-function ifaceListLinux() {
- const result = [];
- const cmd = 'iw dev 2>/dev/null';
- try {
- const all = execSync(cmd, util.execOptsLinux).toString().split('\n').map(line => line.trim()).join('\n');
- const parts = all.split('\nInterface ');
- parts.shift();
- parts.forEach(ifaceDetails => {
- const lines = ifaceDetails.split('\n');
- const iface = lines[0];
- const id = util.toInt(util.getValue(lines, 'ifindex', ' '));
- const mac = util.getValue(lines, 'addr', ' ');
- const channel = util.toInt(util.getValue(lines, 'channel', ' '));
- result.push({
- id,
- iface,
- mac,
- channel
- });
- });
- return result;
- } catch (e) {
- try {
- const all = execSync('nmcli -t -f general,wifi-properties,wired-properties,interface-flags,capabilities,nsp device show 2>/dev/null', util.execOptsLinux).toString();
- const parts = all.split('\n\n');
- let i = 1;
- parts.forEach(ifaceDetails => {
- const lines = ifaceDetails.split('\n');
- const iface = util.getValue(lines, 'GENERAL.DEVICE');
- const type = util.getValue(lines, 'GENERAL.TYPE');
- const id = i++; // // util.getValue(lines, 'GENERAL.PATH');
- const mac = util.getValue(lines, 'GENERAL.HWADDR');
- const channel = '';
- if (type.toLowerCase() === 'wifi') {
- result.push({
- id,
- iface,
- mac,
- channel
- });
- }
- });
- return result;
- } catch (e) {
- return [];
- }
+ // 6. The cookie-name is the name string, and the cookie-value is the
+ // value string.
+ return {
+ name, value, ...parseUnparsedAttributes(unparsedAttributes)
}
}
-function nmiDeviceLinux(iface) {
- const cmd = `nmcli -t -f general,wifi-properties,capabilities,ip4,ip6 device show ${iface} 2> /dev/null`;
- try {
- const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- const ssid = util.getValue(lines, 'GENERAL.CONNECTION');
- return {
- iface,
- type: util.getValue(lines, 'GENERAL.TYPE'),
- vendor: util.getValue(lines, 'GENERAL.VENDOR'),
- product: util.getValue(lines, 'GENERAL.PRODUCT'),
- mac: util.getValue(lines, 'GENERAL.HWADDR').toLowerCase(),
- ssid: ssid !== '--' ? ssid : null
- };
- } catch (e) {
- return {};
+/**
+ * Parses the remaining attributes of a set-cookie header
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
+ * @param {string} unparsedAttributes
+ * @param {[Object.]={}} cookieAttributeList
+ */
+function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
+ // 1. If the unparsed-attributes string is empty, skip the rest of
+ // these steps.
+ if (unparsedAttributes.length === 0) {
+ return cookieAttributeList
}
-}
-function nmiConnectionLinux(ssid) {
- const cmd = `nmcli -t --show-secrets connection show ${ssid} 2>/dev/null`;
- try {
- const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- const bssid = util.getValue(lines, '802-11-wireless.seen-bssids').toLowerCase();
- return {
- ssid: ssid !== '--' ? ssid : null,
- uuid: util.getValue(lines, 'connection.uuid'),
- type: util.getValue(lines, 'connection.type'),
- autoconnect: util.getValue(lines, 'connection.autoconnect') === 'yes',
- security: util.getValue(lines, '802-11-wireless-security.key-mgmt'),
- bssid: bssid !== '--' ? bssid : null
- };
- } catch (e) {
- return {};
+ // 2. Discard the first character of the unparsed-attributes (which
+ // will be a %x3B (";") character).
+ assert(unparsedAttributes[0] === ';')
+ unparsedAttributes = unparsedAttributes.slice(1)
+
+ let cookieAv = ''
+
+ // 3. If the remaining unparsed-attributes contains a %x3B (";")
+ // character:
+ if (unparsedAttributes.includes(';')) {
+ // 1. Consume the characters of the unparsed-attributes up to, but
+ // not including, the first %x3B (";") character.
+ cookieAv = collectASequenceOfCodePointsFast(
+ ';',
+ unparsedAttributes,
+ { position: 0 }
+ )
+ unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
+ } else {
+ // Otherwise:
+
+ // 1. Consume the remainder of the unparsed-attributes.
+ cookieAv = unparsedAttributes
+ unparsedAttributes = ''
+ }
+
+ // Let the cookie-av string be the characters consumed in this step.
+
+ let attributeName = ''
+ let attributeValue = ''
+
+ // 4. If the cookie-av string contains a %x3D ("=") character:
+ if (cookieAv.includes('=')) {
+ // 1. The (possibly empty) attribute-name string consists of the
+ // characters up to, but not including, the first %x3D ("=")
+ // character, and the (possibly empty) attribute-value string
+ // consists of the characters after the first %x3D ("=")
+ // character.
+ const position = { position: 0 }
+
+ attributeName = collectASequenceOfCodePointsFast(
+ '=',
+ cookieAv,
+ position
+ )
+ attributeValue = cookieAv.slice(position.position + 1)
+ } else {
+ // Otherwise:
+
+ // 1. The attribute-name string consists of the entire cookie-av
+ // string, and the attribute-value string is empty.
+ attributeName = cookieAv
}
-}
-function wpaConnectionLinux(iface) {
- if (!iface) {
- return {};
- }
- const cmd = `wpa_cli -i ${iface} status 2>&1`;
- try {
- const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- const freq = util.toInt(util.getValue(lines, 'freq', '='));
- return {
- ssid: util.getValue(lines, 'ssid', '='),
- uuid: util.getValue(lines, 'uuid', '='),
- security: util.getValue(lines, 'key_mgmt', '='),
- freq,
- channel: wifiChannelFromFrequencs(freq),
- bssid: util.getValue(lines, 'bssid', '=').toLowerCase()
- };
- } catch (e) {
- return {};
- }
-}
+ // 5. Remove any leading or trailing WSP characters from the attribute-
+ // name string and the attribute-value string.
+ attributeName = attributeName.trim()
+ attributeValue = attributeValue.trim()
-function getWifiNetworkListNmi() {
- const result = [];
- const cmd = 'nmcli -t -m multiline --fields active,ssid,bssid,mode,chan,freq,signal,security,wpa-flags,rsn-flags device wifi list 2>/dev/null';
- try {
- const stdout = execSync(cmd, util.execOptsLinux);
- const parts = stdout.toString().split('ACTIVE:');
- parts.shift();
- parts.forEach(part => {
- part = 'ACTIVE:' + part;
- const lines = part.split(os.EOL);
- const channel = util.getValue(lines, 'CHAN');
- const frequency = util.getValue(lines, 'FREQ').toLowerCase().replace('mhz', '').trim();
- const security = util.getValue(lines, 'SECURITY').replace('(', '').replace(')', '');
- const wpaFlags = util.getValue(lines, 'WPA-FLAGS').replace('(', '').replace(')', '');
- const rsnFlags = util.getValue(lines, 'RSN-FLAGS').replace('(', '').replace(')', '');
- const quality = util.getValue(lines, 'SIGNAL');
- result.push({
- ssid: util.getValue(lines, 'SSID'),
- bssid: util.getValue(lines, 'BSSID').toLowerCase(),
- mode: util.getValue(lines, 'MODE'),
- channel: channel ? parseInt(channel, 10) : null,
- frequency: frequency ? parseInt(frequency, 10) : null,
- signalLevel: wifiDBFromQuality(quality),
- quality: quality ? parseInt(quality, 10) : null,
- security: security && security !== 'none' ? security.split(' ') : [],
- wpaFlags: wpaFlags && wpaFlags !== 'none' ? wpaFlags.split(' ') : [],
- rsnFlags: rsnFlags && rsnFlags !== 'none' ? rsnFlags.split(' ') : []
- });
- });
- return result;
- } catch (e) {
- return [];
+ // 6. If the attribute-value is longer than 1024 octets, ignore the
+ // cookie-av string and return to Step 1 of this algorithm.
+ if (attributeValue.length > maxAttributeValueSize) {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
-}
-function getWifiNetworkListIw(iface) {
- const result = [];
- try {
- let iwlistParts = execSync(`export LC_ALL=C; iwlist ${iface} scan 2>&1; unset LC_ALL`, util.execOptsLinux).toString().split(' Cell ');
- if (iwlistParts[0].indexOf('resource busy') >= 0) { return -1; }
- if (iwlistParts.length > 1) {
- iwlistParts.shift();
- iwlistParts.forEach(element => {
- const lines = element.split('\n');
- const channel = util.getValue(lines, 'channel', ':', true);
- const address = (lines && lines.length && lines[0].indexOf('Address:') >= 0 ? lines[0].split('Address:')[1].trim().toLowerCase() : '');
- const mode = util.getValue(lines, 'mode', ':', true);
- const frequency = util.getValue(lines, 'frequency', ':', true);
- const qualityString = util.getValue(lines, 'Quality', '=', true);
- const dbParts = qualityString.toLowerCase().split('signal level=');
- const db = dbParts.length > 1 ? util.toInt(dbParts[1]) : 0;
- const quality = db ? wifiQualityFromDB(db) : 0;
- const ssid = util.getValue(lines, 'essid', ':', true);
+ // 7. Process the attribute-name and attribute-value according to the
+ // requirements in the following subsections. (Notice that
+ // attributes with unrecognized attribute-names are ignored.)
+ const attributeNameLowercase = attributeName.toLowerCase()
- // security and wpa-flags
- const isWpa = element.indexOf(' WPA ') >= 0;
- const isWpa2 = element.indexOf('WPA2 ') >= 0;
- const security = [];
- if (isWpa) { security.push('WPA'); }
- if (isWpa2) { security.push('WPA2'); }
- const wpaFlags = [];
- let wpaFlag = '';
- lines.forEach(function (line) {
- const l = line.trim().toLowerCase();
- if (l.indexOf('group cipher') >= 0) {
- if (wpaFlag) {
- wpaFlags.push(wpaFlag);
- }
- const parts = l.split(':');
- if (parts.length > 1) {
- wpaFlag = parts[1].trim().toUpperCase();
- }
- }
- if (l.indexOf('pairwise cipher') >= 0) {
- const parts = l.split(':');
- if (parts.length > 1) {
- if (parts[1].indexOf('tkip')) { wpaFlag = (wpaFlag ? 'TKIP/' + wpaFlag : 'TKIP'); }
- else if (parts[1].indexOf('ccmp')) { wpaFlag = (wpaFlag ? 'CCMP/' + wpaFlag : 'CCMP'); }
- else if (parts[1].indexOf('proprietary')) { wpaFlag = (wpaFlag ? 'PROP/' + wpaFlag : 'PROP'); }
- }
- }
- if (l.indexOf('authentication suites') >= 0) {
- const parts = l.split(':');
- if (parts.length > 1) {
- if (parts[1].indexOf('802.1x')) { wpaFlag = (wpaFlag ? '802.1x/' + wpaFlag : '802.1x'); }
- else if (parts[1].indexOf('psk')) { wpaFlag = (wpaFlag ? 'PSK/' + wpaFlag : 'PSK'); }
- }
- }
- });
- if (wpaFlag) {
- wpaFlags.push(wpaFlag);
- }
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
+ // If the attribute-name case-insensitively matches the string
+ // "Expires", the user agent MUST process the cookie-av as follows.
+ if (attributeNameLowercase === 'expires') {
+ // 1. Let the expiry-time be the result of parsing the attribute-value
+ // as cookie-date (see Section 5.1.1).
+ const expiryTime = new Date(attributeValue)
- result.push({
- ssid,
- bssid: address,
- mode,
- channel: channel ? util.toInt(channel) : null,
- frequency: frequency ? util.toInt(frequency.replace('.', '')) : null,
- signalLevel: db,
- quality,
- security,
- wpaFlags,
- rsnFlags: []
- });
- });
+ // 2. If the attribute-value failed to parse as a cookie date, ignore
+ // the cookie-av.
+
+ cookieAttributeList.expires = expiryTime
+ } else if (attributeNameLowercase === 'max-age') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
+ // If the attribute-name case-insensitively matches the string "Max-
+ // Age", the user agent MUST process the cookie-av as follows.
+
+ // 1. If the first character of the attribute-value is not a DIGIT or a
+ // "-" character, ignore the cookie-av.
+ const charCode = attributeValue.charCodeAt(0)
+
+ if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
- return result;
- } catch (e) {
- return -1;
- }
-}
-function parseWifiDarwinXX(wifiObj) {
- const result = [];
- if (wifiObj) {
- wifiObj.forEach(function (wifiItem) {
- const signalLevel = wifiItem.RSSI;
- let security = [];
- let wpaFlags = [];
- let ssid = wifiItem.SSID_STR || '';
- if (wifiItem.WPA_IE) {
- security.push('WPA');
- if (wifiItem.WPA_IE.IE_KEY_WPA_UCIPHERS) {
- wifiItem.WPA_IE.IE_KEY_WPA_UCIPHERS.forEach(function (ciphers) {
- if (ciphers === 0 && wpaFlags.indexOf('unknown/TKIP') === -1) { wpaFlags.push('unknown/TKIP'); }
- if (ciphers === 2 && wpaFlags.indexOf('PSK/TKIP') === -1) { wpaFlags.push('PSK/TKIP'); }
- if (ciphers === 4 && wpaFlags.indexOf('PSK/AES') === -1) { wpaFlags.push('PSK/AES'); }
- });
- }
- }
- if (wifiItem.RSN_IE) {
- security.push('WPA2');
- if (wifiItem.RSN_IE.IE_KEY_RSN_UCIPHERS) {
- wifiItem.RSN_IE.IE_KEY_RSN_UCIPHERS.forEach(function (ciphers) {
- if (ciphers === 0 && wpaFlags.indexOf('unknown/TKIP') === -1) { wpaFlags.push('unknown/TKIP'); }
- if (ciphers === 2 && wpaFlags.indexOf('TKIP/TKIP') === -1) { wpaFlags.push('TKIP/TKIP'); }
- if (ciphers === 4 && wpaFlags.indexOf('PSK/AES') === -1) { wpaFlags.push('PSK/AES'); }
- });
- }
- }
- if (wifiItem.SSID && ssid === '') {
- try {
- ssid = Buffer.from(wifiItem.SSID, 'base64').toString('utf8');
- } catch (err) {
- util.noop();
- }
- }
- result.push({
- ssid,
- bssid: wifiItem.BSSID || '',
- mode: '',
- channel: wifiItem.CHANNEL,
- frequency: wifiFrequencyFromChannel(wifiItem.CHANNEL),
- signalLevel: signalLevel ? parseInt(signalLevel, 10) : null,
- quality: wifiQualityFromDB(signalLevel),
- security,
- wpaFlags,
- rsnFlags: []
- });
- });
- }
- return result;
-}
+ // 2. If the remainder of attribute-value contains a non-DIGIT
+ // character, ignore the cookie-av.
+ if (!/^\d+$/.test(attributeValue)) {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ }
-function parseWifiDarwin(wifiStr) {
- const result = [];
- try {
- let wifiObj = JSON.parse(wifiStr);
- wifiObj = wifiObj.SPAirPortDataType[0].spairport_airport_interfaces[0].spairport_airport_other_local_wireless_networks;
- wifiObj.forEach(function (wifiItem) {
+ // 3. Let delta-seconds be the attribute-value converted to an integer.
+ const deltaSeconds = Number(attributeValue)
- let security = [];
- const sm = wifiItem.spairport_security_mode;
- if (sm === 'spairport_security_mode_wep') {
- security.push('WEP');
- } else if (sm === 'spairport_security_mode_wpa2_personal') {
- security.push('WPA2');
- } else if (sm.startsWith('spairport_security_mode_wpa2_enterprise')) {
- security.push('WPA2 EAP');
- } else if (sm.startsWith('pairport_security_mode_wpa3_transition')) {
- security.push('WPA2/WPA3');
- } else if (sm.startsWith('pairport_security_mode_wpa3')) {
- security.push('WPA3');
- }
- const channel = parseInt(('' + wifiItem.spairport_network_channel).split(' ')[0]) || 0;
- const signalLevel = wifiItem.spairport_signal_noise || null;
+ // 4. Let cookie-age-limit be the maximum age of the cookie (which
+ // SHOULD be 400 days or less, see Section 4.1.2.2).
- result.push({
- ssid: wifiItem._name || '',
- bssid: wifiItem.spairport_network_bssid || null,
- mode: wifiItem.spairport_network_phymode,
- channel,
- frequency: wifiFrequencyFromChannel(channel),
- signalLevel: signalLevel ? parseInt(signalLevel, 10) : null,
- quality: wifiQualityFromDB(signalLevel),
- security,
- wpaFlags: [],
- rsnFlags: []
- });
- });
- return result;
- } catch (e) {
- return result;
- }
-};
-function wifiNetworks(callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux) {
- result = getWifiNetworkListNmi();
- if (result.length === 0) {
- try {
- const iwconfigParts = execSync('export LC_ALL=C; iwconfig 2>/dev/null; unset LC_ALL', util.execOptsLinux).toString().split('\n\n');
- let iface = '';
- iwconfigParts.forEach(element => {
- if (element.indexOf('no wireless') === -1 && element.trim() !== '') {
- iface = element.split(' ')[0];
- }
- });
- if (iface) {
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface, true);
- const l = util.mathMin(s.length, 2000);
+ // 5. Set delta-seconds to the smaller of its present value and cookie-
+ // age-limit.
+ // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
+ // 6. If delta-seconds is less than or equal to zero (0), let expiry-
+ // time be the earliest representable date and time. Otherwise, let
+ // the expiry-time be the current date and time plus delta-seconds
+ // seconds.
+ // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
- const res = getWifiNetworkListIw(ifaceSanitized);
- if (res === -1) {
- // try again after 4 secs
- setTimeout(function (iface) {
- const res = getWifiNetworkListIw(iface);
- if (res != -1) { result = res; }
- if (callback) {
- callback(result);
- }
- resolve(result);
- }, 4000);
- } else {
- result = res;
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- } catch (e) {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- } else if (_darwin) {
- let cmd = 'system_profiler SPAirPortDataType -json 2>/dev/null';
- exec(cmd, { maxBuffer: 1024 * 40000 }, function (error, stdout) {
- result = parseWifiDarwin(stdout.toString());
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else if (_windows) {
- let cmd = 'netsh wlan show networks mode=Bssid';
- util.powerShell(cmd).then((stdout) => {
- const ssidParts = stdout.toString('utf8').split(os.EOL + os.EOL + 'SSID ');
- ssidParts.shift();
+ // 7. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Max-Age and an attribute-value of expiry-time.
+ cookieAttributeList.maxAge = deltaSeconds
+ } else if (attributeNameLowercase === 'domain') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
+ // If the attribute-name case-insensitively matches the string "Domain",
+ // the user agent MUST process the cookie-av as follows.
- ssidParts.forEach(ssidPart => {
- const ssidLines = ssidPart.split(os.EOL);
- if (ssidLines && ssidLines.length >= 8 && ssidLines[0].indexOf(':') >= 0) {
- const bssidsParts = ssidPart.split(' BSSID');
- bssidsParts.shift();
+ // 1. Let cookie-domain be the attribute-value.
+ let cookieDomain = attributeValue
- bssidsParts.forEach((bssidPart) => {
- const bssidLines = bssidPart.split(os.EOL);
- const bssidLine = bssidLines[0].split(':');
- bssidLine.shift();
- const bssid = bssidLine.join(':').trim().toLowerCase();
- const channel = bssidLines[3].split(':').pop().trim();
- const quality = bssidLines[1].split(':').pop().trim();
+ // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
+ // cookie-domain without its leading %x2E (".").
+ if (cookieDomain[0] === '.') {
+ cookieDomain = cookieDomain.slice(1)
+ }
- result.push({
- ssid: ssidLines[0].split(':').pop().trim(),
- bssid,
- mode: '',
- channel: channel ? parseInt(channel, 10) : null,
- frequency: wifiFrequencyFromChannel(channel),
- signalLevel: wifiDBFromQuality(quality),
- quality: quality ? parseInt(quality, 10) : null,
- security: [ssidLines[2].split(':').pop().trim()],
- wpaFlags: [ssidLines[3].split(':').pop().trim()],
- rsnFlags: []
- });
- });
- }
- });
+ // 3. Convert the cookie-domain to lower case.
+ cookieDomain = cookieDomain.toLowerCase()
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- });
-}
+ // 4. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Domain and an attribute-value of cookie-domain.
+ cookieAttributeList.domain = cookieDomain
+ } else if (attributeNameLowercase === 'path') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
+ // If the attribute-name case-insensitively matches the string "Path",
+ // the user agent MUST process the cookie-av as follows.
-exports.wifiNetworks = wifiNetworks;
+ // 1. If the attribute-value is empty or if the first character of the
+ // attribute-value is not %x2F ("/"):
+ let cookiePath = ''
+ if (attributeValue.length === 0 || attributeValue[0] !== '/') {
+ // 1. Let cookie-path be the default-path.
+ cookiePath = '/'
+ } else {
+ // Otherwise:
-function getVendor(model) {
- model = model.toLowerCase();
- let result = '';
- if (model.indexOf('intel') >= 0) { result = 'Intel'; }
- else if (model.indexOf('realtek') >= 0) { result = 'Realtek'; }
- else if (model.indexOf('qualcom') >= 0) { result = 'Qualcom'; }
- else if (model.indexOf('broadcom') >= 0) { result = 'Broadcom'; }
- else if (model.indexOf('cavium') >= 0) { result = 'Cavium'; }
- else if (model.indexOf('cisco') >= 0) { result = 'Cisco'; }
- else if (model.indexOf('marvel') >= 0) { result = 'Marvel'; }
- else if (model.indexOf('zyxel') >= 0) { result = 'Zyxel'; }
- else if (model.indexOf('melanox') >= 0) { result = 'Melanox'; }
- else if (model.indexOf('d-link') >= 0) { result = 'D-Link'; }
- else if (model.indexOf('tp-link') >= 0) { result = 'TP-Link'; }
- else if (model.indexOf('asus') >= 0) { result = 'Asus'; }
- else if (model.indexOf('linksys') >= 0) { result = 'Linksys'; }
- return result;
-}
+ // 1. Let cookie-path be the attribute-value.
+ cookiePath = attributeValue
+ }
+
+ // 2. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Path and an attribute-value of cookie-path.
+ cookieAttributeList.path = cookiePath
+ } else if (attributeNameLowercase === 'secure') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
+ // If the attribute-name case-insensitively matches the string "Secure",
+ // the user agent MUST append an attribute to the cookie-attribute-list
+ // with an attribute-name of Secure and an empty attribute-value.
+
+ cookieAttributeList.secure = true
+ } else if (attributeNameLowercase === 'httponly') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
+ // If the attribute-name case-insensitively matches the string
+ // "HttpOnly", the user agent MUST append an attribute to the cookie-
+ // attribute-list with an attribute-name of HttpOnly and an empty
+ // attribute-value.
+
+ cookieAttributeList.httpOnly = true
+ } else if (attributeNameLowercase === 'samesite') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
+ // If the attribute-name case-insensitively matches the string
+ // "SameSite", the user agent MUST process the cookie-av as follows:
+
+ // 1. Let enforcement be "Default".
+ let enforcement = 'Default'
+
+ const attributeValueLowercase = attributeValue.toLowerCase()
+ // 2. If cookie-av's attribute-value is a case-insensitive match for
+ // "None", set enforcement to "None".
+ if (attributeValueLowercase.includes('none')) {
+ enforcement = 'None'
+ }
+
+ // 3. If cookie-av's attribute-value is a case-insensitive match for
+ // "Strict", set enforcement to "Strict".
+ if (attributeValueLowercase.includes('strict')) {
+ enforcement = 'Strict'
+ }
+
+ // 4. If cookie-av's attribute-value is a case-insensitive match for
+ // "Lax", set enforcement to "Lax".
+ if (attributeValueLowercase.includes('lax')) {
+ enforcement = 'Lax'
+ }
+
+ // 5. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of "SameSite" and an attribute-value of
+ // enforcement.
+ cookieAttributeList.sameSite = enforcement
+ } else {
+ cookieAttributeList.unparsed ??= []
-function formatBssid(s) {
- s = s.replace(//g, '').match(/.{1,2}/g) || [];
- return s.join(':');
+ cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
+ }
+
+ // 8. Return to Step 1 of this algorithm.
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
-function wifiConnections(callback) {
+module.exports = {
+ parseSetCookie,
+ parseUnparsedAttributes
+}
- return new Promise((resolve) => {
- process.nextTick(() => {
- const result = [];
- if (_linux) {
- const ifaces = ifaceListLinux();
- const networkList = getWifiNetworkListNmi();
- ifaces.forEach(ifaceDetail => {
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(ifaceDetail.iface, true);
- const ll = util.mathMin(s.length, 2000);
+/***/ }),
- for (let i = 0; i <= ll; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
+/***/ 83126:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- const nmiDetails = nmiDeviceLinux(ifaceSanitized);
- const wpaDetails = wpaConnectionLinux(ifaceSanitized);
- const ssid = nmiDetails.ssid || wpaDetails.ssid;
- const network = networkList.filter(nw => nw.ssid === ssid);
- let ssidSanitized = '';
- const t = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(ssid, true);
- const l = util.mathMin(t.length, 32);
- for (let i = 0; i <= l; i++) {
- if (t[i] !== undefined) {
- ssidSanitized = ssidSanitized + t[i];
- }
- }
- const nmiConnection = nmiConnectionLinux(ssidSanitized);
- const channel = network && network.length && network[0].channel ? network[0].channel : (wpaDetails.channel ? wpaDetails.channel : null);
- const bssid = network && network.length && network[0].bssid ? network[0].bssid : (wpaDetails.bssid ? wpaDetails.bssid : null);
- const signalLevel = network && network.length && network[0].signalLevel ? network[0].signalLevel : null;
- if (ssid && bssid) {
- result.push({
- id: ifaceDetail.id,
- iface: ifaceDetail.iface,
- model: nmiDetails.product,
- ssid,
- bssid: network && network.length && network[0].bssid ? network[0].bssid : (wpaDetails.bssid ? wpaDetails.bssid : null),
- channel,
- frequency: channel ? wifiFrequencyFromChannel(channel) : null,
- type: nmiConnection.type ? nmiConnection.type : '802.11',
- security: nmiConnection.security ? nmiConnection.security : (wpaDetails.security ? wpaDetails.security : null),
- signalLevel,
- quality: wifiQualityFromDB(signalLevel),
- txRate: null
- });
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else if (_darwin) {
- let cmd = 'system_profiler SPNetworkDataType SPAirPortDataType -xml 2>/dev/null; echo "######" ; ioreg -n AppleBCMWLANSkywalkInterface -r 2>/dev/null';
- exec(cmd, function (error, stdout) {
- try {
- const parts = stdout.toString().split('######');
- const profilerObj = util.plistParser(parts[0]);
- const networkObj = profilerObj[0]._SPCommandLineArguments.indexOf('SPNetworkDataType') >= 0 ? profilerObj[0]._items : profilerObj[1]._items;
- const airportObj = profilerObj[0]._SPCommandLineArguments.indexOf('SPAirPortDataType') >= 0 ? profilerObj[0]._items[0].spairport_airport_interfaces : profilerObj[1]._items[0].spairport_airport_interfaces;
- // parts[1] : ioreg
- let lines3 = [];
- if (parts[1].indexOf(' | {') > 0 && parts[1].indexOf(' | }') > parts[1].indexOf(' | {')) {
- lines3 = parts[1].split(' | {')[1].split(' | }')[0].replace(/ \| /g, '').replace(/"/g, '').split('\n');
- }
+const assert = __nccwpck_require__(42613)
+const { kHeadersList } = __nccwpck_require__(68031)
- const networkWifiObj = networkObj.find((item) => { return item._name === 'Wi-Fi'; });
- const airportWifiObj = airportObj[0].spairport_current_network_information;
+function isCTLExcludingHtab (value) {
+ if (value.length === 0) {
+ return false
+ }
- const channel = parseInt(('' + airportWifiObj.spairport_network_channel).split(' ')[0]) || 0;
- const signalLevel = airportWifiObj.spairport_signal_noise || null;
+ for (const char of value) {
+ const code = char.charCodeAt(0)
- let security = [];
- const sm = airportWifiObj.spairport_security_mode;
- if (sm === 'spairport_security_mode_wep') {
- security.push('WEP');
- } else if (sm === 'spairport_security_mode_wpa2_personal') {
- security.push('WPA2');
- } else if (sm.startsWith('spairport_security_mode_wpa2_enterprise')) {
- security.push('WPA2 EAP');
- } else if (sm.startsWith('pairport_security_mode_wpa3_transition')) {
- security.push('WPA2/WPA3');
- } else if (sm.startsWith('pairport_security_mode_wpa3')) {
- security.push('WPA3');
- }
+ if (
+ (code >= 0x00 || code <= 0x08) ||
+ (code >= 0x0A || code <= 0x1F) ||
+ code === 0x7F
+ ) {
+ return false
+ }
+ }
+}
- result.push({
- id: networkWifiObj._name || 'Wi-Fi',
- iface: networkWifiObj.interface || '',
- model: networkWifiObj.hardware || '',
- ssid: airportWifiObj._name || '',
- bssid: airportWifiObj.spairport_network_bssid || '',
- channel,
- frequency: channel ? wifiFrequencyFromChannel(channel) : null,
- type: airportWifiObj.spairport_network_phymode || '802.11',
- security,
- signalLevel: signalLevel ? parseInt(signalLevel, 10) : null,
- quality: wifiQualityFromDB(signalLevel),
- txRate: airportWifiObj.spairport_network_rate || null,
- });
+/**
+ CHAR =
+ token = 1*
+ separators = "(" | ")" | "<" | ">" | "@"
+ | "," | ";" | ":" | "\" | <">
+ | "/" | "[" | "]" | "?" | "="
+ | "{" | "}" | SP | HT
+ * @param {string} name
+ */
+function validateCookieName (name) {
+ for (const char of name) {
+ const code = char.charCodeAt(0)
- } catch (e) {
- util.noop();
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else if (_windows) {
- let cmd = 'netsh wlan show interfaces';
- util.powerShell(cmd).then(function (stdout) {
- const allLines = stdout.toString().split('\r\n');
- for (let i = 0; i < allLines.length; i++) {
- allLines[i] = allLines[i].trim();
- }
- const parts = allLines.join('\r\n').split(':\r\n\r\n');
- parts.shift();
- parts.forEach(part => {
- const lines = part.split('\r\n');
- if (lines.length >= 5) {
- const iface = lines[0].indexOf(':') >= 0 ? lines[0].split(':')[1].trim() : '';
- const model = lines[1].indexOf(':') >= 0 ? lines[1].split(':')[1].trim() : '';
- const id = lines[2].indexOf(':') >= 0 ? lines[2].split(':')[1].trim() : '';
- const ssid = util.getValue(lines, 'SSID', ':', true);
- const bssid = util.getValue(lines, 'BSSID', ':', true) || util.getValue(lines, 'AP BSSID', ':', true);
- const quality = util.getValue(lines, 'Signal', ':', true);
- const signalLevel = wifiDBFromQuality(quality);
- const type = util.getValue(lines, 'Radio type', ':', true) || util.getValue(lines, 'Type de radio', ':', true) || util.getValue(lines, 'Funktyp', ':', true) || null;
- const security = util.getValue(lines, 'authentication', ':', true) || util.getValue(lines, 'Authentification', ':', true) || util.getValue(lines, 'Authentifizierung', ':', true) || null;
- const channel = util.getValue(lines, 'Channel', ':', true) || util.getValue(lines, 'Canal', ':', true) || util.getValue(lines, 'Kanal', ':', true) || null;
- const txRate = util.getValue(lines, 'Transmit rate (mbps)', ':', true) || util.getValue(lines, 'Transmission (mbit/s)', ':', true) || util.getValue(lines, 'Empfangsrate (MBit/s)', ':', true) || null;
- if (model && id && ssid && bssid) {
- result.push({
- id,
- iface,
- model,
- ssid,
- bssid,
- channel: util.toInt(channel),
- frequency: channel ? wifiFrequencyFromChannel(channel) : null,
- type,
- security,
- signalLevel,
- quality: quality ? parseInt(quality, 10) : null,
- txRate: util.toInt(txRate) || null
- });
- }
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- });
+ if (
+ (code <= 0x20 || code > 0x7F) ||
+ char === '(' ||
+ char === ')' ||
+ char === '>' ||
+ char === '<' ||
+ char === '@' ||
+ char === ',' ||
+ char === ';' ||
+ char === ':' ||
+ char === '\\' ||
+ char === '"' ||
+ char === '/' ||
+ char === '[' ||
+ char === ']' ||
+ char === '?' ||
+ char === '=' ||
+ char === '{' ||
+ char === '}'
+ ) {
+ throw new Error('Invalid cookie name')
+ }
+ }
}
-exports.wifiConnections = wifiConnections;
+/**
+ cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
+ cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
+ ; US-ASCII characters excluding CTLs,
+ ; whitespace DQUOTE, comma, semicolon,
+ ; and backslash
+ * @param {string} value
+ */
+function validateCookieValue (value) {
+ for (const char of value) {
+ const code = char.charCodeAt(0)
-function wifiInterfaces(callback) {
+ if (
+ code < 0x21 || // exclude CTLs (0-31)
+ code === 0x22 ||
+ code === 0x2C ||
+ code === 0x3B ||
+ code === 0x5C ||
+ code > 0x7E // non-ascii
+ ) {
+ throw new Error('Invalid header value')
+ }
+ }
+}
- return new Promise((resolve) => {
- process.nextTick(() => {
- const result = [];
+/**
+ * path-value =
+ * @param {string} path
+ */
+function validateCookiePath (path) {
+ for (const char of path) {
+ const code = char.charCodeAt(0)
- if (_linux) {
- const ifaces = ifaceListLinux();
- ifaces.forEach(ifaceDetail => {
- const nmiDetails = nmiDeviceLinux(ifaceDetail.iface);
- result.push({
- id: ifaceDetail.id,
- iface: ifaceDetail.iface,
- model: nmiDetails.product ? nmiDetails.product : null,
- vendor: nmiDetails.vendor ? nmiDetails.vendor : null,
- mac: ifaceDetail.mac,
- });
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else if (_darwin) {
- let cmd = 'system_profiler SPNetworkDataType';
- exec(cmd, function (error, stdout) {
- const parts1 = stdout.toString().split('\n\n Wi-Fi:\n\n');
- if (parts1.length > 1) {
- const lines = parts1[1].split('\n\n')[0].split('\n');
- const iface = util.getValue(lines, 'BSD Device Name', ':', true);
- const mac = util.getValue(lines, 'MAC Address', ':', true);
- const model = util.getValue(lines, 'hardware', ':', true);
- result.push({
- id: 'Wi-Fi',
- iface,
- model,
- vendor: '',
- mac
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else if (_windows) {
- let cmd = 'netsh wlan show interfaces';
- util.powerShell(cmd).then(function (stdout) {
- const allLines = stdout.toString().split('\r\n');
- for (let i = 0; i < allLines.length; i++) {
- allLines[i] = allLines[i].trim();
- }
- const parts = allLines.join('\r\n').split(':\r\n\r\n');
- parts.shift();
- parts.forEach(part => {
- const lines = part.split('\r\n');
- if (lines.length >= 5) {
- const iface = lines[0].indexOf(':') >= 0 ? lines[0].split(':')[1].trim() : '';
- const model = lines[1].indexOf(':') >= 0 ? lines[1].split(':')[1].trim() : '';
- const id = lines[2].indexOf(':') >= 0 ? lines[2].split(':')[1].trim() : '';
- const macParts = lines[3].indexOf(':') >= 0 ? lines[3].split(':') : [];
- macParts.shift();
- const mac = macParts.join(':').trim();
- const vendor = getVendor(model);
- if (iface && model && id && mac) {
- result.push({
- id,
- iface,
- model,
- vendor,
- mac,
- });
- }
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- });
+ if (code < 0x21 || char === ';') {
+ throw new Error('Invalid cookie path')
+ }
+ }
}
-exports.wifiInterfaces = wifiInterfaces;
+/**
+ * I have no idea why these values aren't allowed to be honest,
+ * but Deno tests these. - Khafra
+ * @param {string} domain
+ */
+function validateCookieDomain (domain) {
+ if (
+ domain.startsWith('-') ||
+ domain.endsWith('.') ||
+ domain.endsWith('-')
+ ) {
+ throw new Error('Invalid cookie domain')
+ }
+}
+/**
+ * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
+ * @param {number|Date} date
+ IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
+ ; fixed length/zone/capitalization subset of the format
+ ; see Section 3.3 of [RFC5322]
-/***/ }),
+ day-name = %x4D.6F.6E ; "Mon", case-sensitive
+ / %x54.75.65 ; "Tue", case-sensitive
+ / %x57.65.64 ; "Wed", case-sensitive
+ / %x54.68.75 ; "Thu", case-sensitive
+ / %x46.72.69 ; "Fri", case-sensitive
+ / %x53.61.74 ; "Sat", case-sensitive
+ / %x53.75.6E ; "Sun", case-sensitive
+ date1 = day SP month SP year
+ ; e.g., 02 Jun 1982
-/***/ 94176:
-/***/ ((module) => {
+ day = 2DIGIT
+ month = %x4A.61.6E ; "Jan", case-sensitive
+ / %x46.65.62 ; "Feb", case-sensitive
+ / %x4D.61.72 ; "Mar", case-sensitive
+ / %x41.70.72 ; "Apr", case-sensitive
+ / %x4D.61.79 ; "May", case-sensitive
+ / %x4A.75.6E ; "Jun", case-sensitive
+ / %x4A.75.6C ; "Jul", case-sensitive
+ / %x41.75.67 ; "Aug", case-sensitive
+ / %x53.65.70 ; "Sep", case-sensitive
+ / %x4F.63.74 ; "Oct", case-sensitive
+ / %x4E.6F.76 ; "Nov", case-sensitive
+ / %x44.65.63 ; "Dec", case-sensitive
+ year = 4DIGIT
-/******************************************************************************
-Copyright (c) Microsoft Corporation.
+ GMT = %x47.4D.54 ; "GMT", case-sensitive
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
+ time-of-day = hour ":" minute ":" second
+ ; 00:00:00 - 23:59:60 (leap second)
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */
-var __extends;
-var __assign;
-var __rest;
-var __decorate;
-var __param;
-var __esDecorate;
-var __runInitializers;
-var __propKey;
-var __setFunctionName;
-var __metadata;
-var __awaiter;
-var __generator;
-var __exportStar;
-var __values;
-var __read;
-var __spread;
-var __spreadArrays;
-var __spreadArray;
-var __await;
-var __asyncGenerator;
-var __asyncDelegator;
-var __asyncValues;
-var __makeTemplateObject;
-var __importStar;
-var __importDefault;
-var __classPrivateFieldGet;
-var __classPrivateFieldSet;
-var __classPrivateFieldIn;
-var __createBinding;
-var __addDisposableResource;
-var __disposeResources;
-var __rewriteRelativeImportExtension;
-(function (factory) {
- var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
- if (typeof define === "function" && define.amd) {
- define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
- }
- else if ( true && typeof module.exports === "object") {
- factory(createExporter(root, createExporter(module.exports)));
- }
- else {
- factory(createExporter(root));
- }
- function createExporter(exports, previous) {
- if (exports !== root) {
- if (typeof Object.create === "function") {
- Object.defineProperty(exports, "__esModule", { value: true });
- }
- else {
- exports.__esModule = true;
- }
- }
- return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
- }
-})
-(function (exporter) {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
+ hour = 2DIGIT
+ minute = 2DIGIT
+ second = 2DIGIT
+ */
+function toIMFDate (date) {
+ if (typeof date === 'number') {
+ date = new Date(date)
+ }
- __extends = function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
+ const days = [
+ 'Sun', 'Mon', 'Tue', 'Wed',
+ 'Thu', 'Fri', 'Sat'
+ ]
+
+ const months = [
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
+ ]
+
+ const dayName = days[date.getUTCDay()]
+ const day = date.getUTCDate().toString().padStart(2, '0')
+ const month = months[date.getUTCMonth()]
+ const year = date.getUTCFullYear()
+ const hour = date.getUTCHours().toString().padStart(2, '0')
+ const minute = date.getUTCMinutes().toString().padStart(2, '0')
+ const second = date.getUTCSeconds().toString().padStart(2, '0')
+
+ return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`
+}
+
+/**
+ max-age-av = "Max-Age=" non-zero-digit *DIGIT
+ ; In practice, both expires-av and max-age-av
+ ; are limited to dates representable by the
+ ; user agent.
+ * @param {number} maxAge
+ */
+function validateCookieMaxAge (maxAge) {
+ if (maxAge < 0) {
+ throw new Error('Invalid cookie max-age')
+ }
+}
- __assign = Object.assign || function (t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
+/**
+ * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
+ * @param {import('./index').Cookie} cookie
+ */
+function stringify (cookie) {
+ if (cookie.name.length === 0) {
+ return null
+ }
- __rest = function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
- };
+ validateCookieName(cookie.name)
+ validateCookieValue(cookie.value)
- __decorate = function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
+ const out = [`${cookie.name}=${cookie.value}`]
- __param = function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
+ if (cookie.name.startsWith('__Secure-')) {
+ cookie.secure = true
+ }
- __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
- function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
- var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
- var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
- var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
- var _, done = false;
- for (var i = decorators.length - 1; i >= 0; i--) {
- var context = {};
- for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
- for (var p in contextIn.access) context.access[p] = contextIn.access[p];
- context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
- var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
- if (kind === "accessor") {
- if (result === void 0) continue;
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
- if (_ = accept(result.get)) descriptor.get = _;
- if (_ = accept(result.set)) descriptor.set = _;
- if (_ = accept(result.init)) initializers.unshift(_);
- }
- else if (_ = accept(result)) {
- if (kind === "field") initializers.unshift(_);
- else descriptor[key] = _;
- }
- }
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
- done = true;
- };
+ if (cookie.name.startsWith('__Host-')) {
+ cookie.secure = true
+ cookie.domain = null
+ cookie.path = '/'
+ }
- __runInitializers = function (thisArg, initializers, value) {
- var useValue = arguments.length > 2;
- for (var i = 0; i < initializers.length; i++) {
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
- }
- return useValue ? value : void 0;
- };
+ if (cookie.secure) {
+ out.push('Secure')
+ }
- __propKey = function (x) {
- return typeof x === "symbol" ? x : "".concat(x);
- };
+ if (cookie.httpOnly) {
+ out.push('HttpOnly')
+ }
- __setFunctionName = function (f, name, prefix) {
- if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
- return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
- };
+ if (typeof cookie.maxAge === 'number') {
+ validateCookieMaxAge(cookie.maxAge)
+ out.push(`Max-Age=${cookie.maxAge}`)
+ }
- __metadata = function (metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
- };
+ if (cookie.domain) {
+ validateCookieDomain(cookie.domain)
+ out.push(`Domain=${cookie.domain}`)
+ }
- __awaiter = function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
+ if (cookie.path) {
+ validateCookiePath(cookie.path)
+ out.push(`Path=${cookie.path}`)
+ }
- __generator = function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
+ if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
+ out.push(`Expires=${toIMFDate(cookie.expires)}`)
+ }
- __exportStar = function(m, o) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
- };
+ if (cookie.sameSite) {
+ out.push(`SameSite=${cookie.sameSite}`)
+ }
- __createBinding = Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- });
+ for (const part of cookie.unparsed) {
+ if (!part.includes('=')) {
+ throw new Error('Invalid unparsed')
+ }
- __values = function (o) {
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
- if (m) return m.call(o);
- if (o && typeof o.length === "number") return {
- next: function () {
- if (o && i >= o.length) o = void 0;
- return { value: o && o[i++], done: !o };
- }
- };
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
- };
+ const [key, ...value] = part.split('=')
- __read = function (o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
- };
+ out.push(`${key.trim()}=${value.join('=')}`)
+ }
- /** @deprecated */
- __spread = function () {
- for (var ar = [], i = 0; i < arguments.length; i++)
- ar = ar.concat(__read(arguments[i]));
- return ar;
- };
+ return out.join('; ')
+}
- /** @deprecated */
- __spreadArrays = function () {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
- };
+let kHeadersListNode
- __spreadArray = function (to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
- };
+function getHeadersList (headers) {
+ if (headers[kHeadersList]) {
+ return headers[kHeadersList]
+ }
- __await = function (v) {
- return this instanceof __await ? (this.v = v, this) : new __await(v);
- };
+ if (!kHeadersListNode) {
+ kHeadersListNode = Object.getOwnPropertySymbols(headers).find(
+ (symbol) => symbol.description === 'headers list'
+ )
- __asyncGenerator = function (thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
- function fulfill(value) { resume("next", value); }
- function reject(value) { resume("throw", value); }
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
- };
+ assert(kHeadersListNode, 'Headers cannot be parsed')
+ }
- __asyncDelegator = function (o) {
- var i, p;
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
- };
+ const headersList = headers[kHeadersListNode]
+ assert(headersList)
- __asyncValues = function (o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
- };
+ return headersList
+}
- __makeTemplateObject = function (cooked, raw) {
- if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
- return cooked;
- };
+module.exports = {
+ isCTLExcludingHtab,
+ stringify,
+ getHeadersList
+}
- var __setModuleDefault = Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- };
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
+/***/ }),
- __importStar = function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
+/***/ 91332:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- __importDefault = function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
- __classPrivateFieldGet = function (receiver, state, kind, f) {
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
- };
- __classPrivateFieldSet = function (receiver, state, value, kind, f) {
- if (kind === "m") throw new TypeError("Private method is not writable");
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
- };
+const net = __nccwpck_require__(69278)
+const assert = __nccwpck_require__(42613)
+const util = __nccwpck_require__(89500)
+const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(53959)
- __classPrivateFieldIn = function (state, receiver) {
- if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
- return typeof state === "function" ? receiver === state : state.has(receiver);
- };
+let tls // include tls conditionally since it is not always available
- __addDisposableResource = function (env, value, async) {
- if (value !== null && value !== void 0) {
- if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
- var dispose, inner;
- if (async) {
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
- dispose = value[Symbol.asyncDispose];
- }
- if (dispose === void 0) {
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
- dispose = value[Symbol.dispose];
- if (async) inner = dispose;
- }
- if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
- if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
- env.stack.push({ value: value, dispose: dispose, async: async });
+// TODO: session re-use does not wait for the first
+// connection to resolve the session and might therefore
+// resolve the same servername multiple times even when
+// re-use is enabled.
+
+let SessionCache
+// FIXME: remove workaround when the Node bug is fixed
+// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
+if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {
+ SessionCache = class WeakSessionCache {
+ constructor (maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions
+ this._sessionCache = new Map()
+ this._sessionRegistry = new global.FinalizationRegistry((key) => {
+ if (this._sessionCache.size < this._maxCachedSessions) {
+ return
}
- else if (async) {
- env.stack.push({ async: true });
+
+ const ref = this._sessionCache.get(key)
+ if (ref !== undefined && ref.deref() === undefined) {
+ this._sessionCache.delete(key)
}
- return value;
- };
+ })
+ }
- var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
- var e = new Error(message);
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
- };
+ get (sessionKey) {
+ const ref = this._sessionCache.get(sessionKey)
+ return ref ? ref.deref() : null
+ }
- __disposeResources = function (env) {
- function fail(e) {
- env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
- env.hasError = true;
- }
- var r, s = 0;
- function next() {
- while (r = env.stack.pop()) {
- try {
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
- if (r.dispose) {
- var result = r.dispose.call(r.value);
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
- }
- else s |= 1;
- }
- catch (e) {
- fail(e);
- }
- }
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
- if (env.hasError) throw env.error;
- }
- return next();
- };
+ set (sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return
+ }
- __rewriteRelativeImportExtension = function (path, preserveJsx) {
- if (typeof path === "string" && /^\.\.?\//.test(path)) {
- return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
- return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
- });
- }
- return path;
- };
+ this._sessionCache.set(sessionKey, new WeakRef(session))
+ this._sessionRegistry.register(session, sessionKey)
+ }
+ }
+} else {
+ SessionCache = class SimpleSessionCache {
+ constructor (maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions
+ this._sessionCache = new Map()
+ }
- exporter("__extends", __extends);
- exporter("__assign", __assign);
- exporter("__rest", __rest);
- exporter("__decorate", __decorate);
- exporter("__param", __param);
- exporter("__esDecorate", __esDecorate);
- exporter("__runInitializers", __runInitializers);
- exporter("__propKey", __propKey);
- exporter("__setFunctionName", __setFunctionName);
- exporter("__metadata", __metadata);
- exporter("__awaiter", __awaiter);
- exporter("__generator", __generator);
- exporter("__exportStar", __exportStar);
- exporter("__createBinding", __createBinding);
- exporter("__values", __values);
- exporter("__read", __read);
- exporter("__spread", __spread);
- exporter("__spreadArrays", __spreadArrays);
- exporter("__spreadArray", __spreadArray);
- exporter("__await", __await);
- exporter("__asyncGenerator", __asyncGenerator);
- exporter("__asyncDelegator", __asyncDelegator);
- exporter("__asyncValues", __asyncValues);
- exporter("__makeTemplateObject", __makeTemplateObject);
- exporter("__importStar", __importStar);
- exporter("__importDefault", __importDefault);
- exporter("__classPrivateFieldGet", __classPrivateFieldGet);
- exporter("__classPrivateFieldSet", __classPrivateFieldSet);
- exporter("__classPrivateFieldIn", __classPrivateFieldIn);
- exporter("__addDisposableResource", __addDisposableResource);
- exporter("__disposeResources", __disposeResources);
- exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
-});
+ get (sessionKey) {
+ return this._sessionCache.get(sessionKey)
+ }
+
+ set (sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return
+ }
+
+ if (this._sessionCache.size >= this._maxCachedSessions) {
+ // remove the oldest session
+ const { value: oldestKey } = this._sessionCache.keys().next()
+ this._sessionCache.delete(oldestKey)
+ }
+
+ this._sessionCache.set(sessionKey, session)
+ }
+ }
+}
+
+function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {
+ if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
+ throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
+ }
+
+ const options = { path: socketPath, ...opts }
+ const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
+ timeout = timeout == null ? 10e3 : timeout
+ allowH2 = allowH2 != null ? allowH2 : false
+ return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
+ let socket
+ if (protocol === 'https:') {
+ if (!tls) {
+ tls = __nccwpck_require__(64756)
+ }
+ servername = servername || options.servername || util.getServerName(host) || null
+
+ const sessionKey = servername || hostname
+ const session = sessionCache.get(sessionKey) || null
+
+ assert(sessionKey)
+
+ socket = tls.connect({
+ highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
+ ...options,
+ servername,
+ session,
+ localAddress,
+ // TODO(HTTP/2): Add support for h2c
+ ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
+ socket: httpSocket, // upgrade socket connection
+ port: port || 443,
+ host: hostname
+ })
+
+ socket
+ .on('session', function (session) {
+ // TODO (fix): Can a session become invalid once established? Don't think so?
+ sessionCache.set(sessionKey, session)
+ })
+ } else {
+ assert(!httpSocket, 'httpSocket can only be sent on TLS update')
+ socket = net.connect({
+ highWaterMark: 64 * 1024, // Same as nodejs fs streams.
+ ...options,
+ localAddress,
+ port: port || 80,
+ host: hostname
+ })
+ }
-0 && (0);
+ // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
+ if (options.keepAlive == null || options.keepAlive) {
+ const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
+ socket.setKeepAlive(true, keepAliveInitialDelay)
+ }
+ const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)
-/***/ }),
+ socket
+ .setNoDelay(true)
+ .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
+ cancelTimeout()
-/***/ 5070:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb(null, this)
+ }
+ })
+ .on('error', function (err) {
+ cancelTimeout()
-module.exports = __nccwpck_require__(35862);
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb(err)
+ }
+ })
+ return socket
+ }
+}
-/***/ }),
+function setupTimeout (onConnectTimeout, timeout) {
+ if (!timeout) {
+ return () => {}
+ }
-/***/ 35862:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ let s1 = null
+ let s2 = null
+ const timeoutId = setTimeout(() => {
+ // setImmediate is added to make sure that we priotorise socket error events over timeouts
+ s1 = setImmediate(() => {
+ if (process.platform === 'win32') {
+ // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
+ s2 = setImmediate(() => onConnectTimeout())
+ } else {
+ onConnectTimeout()
+ }
+ })
+ }, timeout)
+ return () => {
+ clearTimeout(timeoutId)
+ clearImmediate(s1)
+ clearImmediate(s2)
+ }
+}
+function onConnectTimeout (socket) {
+ util.destroy(socket, new ConnectTimeoutError())
+}
+module.exports = buildConnector
-var net = __nccwpck_require__(69278);
-var tls = __nccwpck_require__(64756);
-var http = __nccwpck_require__(58611);
-var https = __nccwpck_require__(65692);
-var events = __nccwpck_require__(24434);
-var assert = __nccwpck_require__(42613);
-var util = __nccwpck_require__(39023);
+/***/ }),
-exports.httpOverHttp = httpOverHttp;
-exports.httpsOverHttp = httpsOverHttp;
-exports.httpOverHttps = httpOverHttps;
-exports.httpsOverHttps = httpsOverHttps;
+/***/ 42371:
+/***/ ((module) => {
-function httpOverHttp(options) {
- var agent = new TunnelingAgent(options);
- agent.request = http.request;
- return agent;
-}
-function httpsOverHttp(options) {
- var agent = new TunnelingAgent(options);
- agent.request = http.request;
- agent.createSocket = createSecureSocket;
- agent.defaultPort = 443;
- return agent;
-}
+/** @type {Record} */
+const headerNameLowerCasedRecord = {}
-function httpOverHttps(options) {
- var agent = new TunnelingAgent(options);
- agent.request = https.request;
- return agent;
-}
+// https://developer.mozilla.org/docs/Web/HTTP/Headers
+const wellknownHeaderNames = [
+ 'Accept',
+ 'Accept-Encoding',
+ 'Accept-Language',
+ 'Accept-Ranges',
+ 'Access-Control-Allow-Credentials',
+ 'Access-Control-Allow-Headers',
+ 'Access-Control-Allow-Methods',
+ 'Access-Control-Allow-Origin',
+ 'Access-Control-Expose-Headers',
+ 'Access-Control-Max-Age',
+ 'Access-Control-Request-Headers',
+ 'Access-Control-Request-Method',
+ 'Age',
+ 'Allow',
+ 'Alt-Svc',
+ 'Alt-Used',
+ 'Authorization',
+ 'Cache-Control',
+ 'Clear-Site-Data',
+ 'Connection',
+ 'Content-Disposition',
+ 'Content-Encoding',
+ 'Content-Language',
+ 'Content-Length',
+ 'Content-Location',
+ 'Content-Range',
+ 'Content-Security-Policy',
+ 'Content-Security-Policy-Report-Only',
+ 'Content-Type',
+ 'Cookie',
+ 'Cross-Origin-Embedder-Policy',
+ 'Cross-Origin-Opener-Policy',
+ 'Cross-Origin-Resource-Policy',
+ 'Date',
+ 'Device-Memory',
+ 'Downlink',
+ 'ECT',
+ 'ETag',
+ 'Expect',
+ 'Expect-CT',
+ 'Expires',
+ 'Forwarded',
+ 'From',
+ 'Host',
+ 'If-Match',
+ 'If-Modified-Since',
+ 'If-None-Match',
+ 'If-Range',
+ 'If-Unmodified-Since',
+ 'Keep-Alive',
+ 'Last-Modified',
+ 'Link',
+ 'Location',
+ 'Max-Forwards',
+ 'Origin',
+ 'Permissions-Policy',
+ 'Pragma',
+ 'Proxy-Authenticate',
+ 'Proxy-Authorization',
+ 'RTT',
+ 'Range',
+ 'Referer',
+ 'Referrer-Policy',
+ 'Refresh',
+ 'Retry-After',
+ 'Sec-WebSocket-Accept',
+ 'Sec-WebSocket-Extensions',
+ 'Sec-WebSocket-Key',
+ 'Sec-WebSocket-Protocol',
+ 'Sec-WebSocket-Version',
+ 'Server',
+ 'Server-Timing',
+ 'Service-Worker-Allowed',
+ 'Service-Worker-Navigation-Preload',
+ 'Set-Cookie',
+ 'SourceMap',
+ 'Strict-Transport-Security',
+ 'Supports-Loading-Mode',
+ 'TE',
+ 'Timing-Allow-Origin',
+ 'Trailer',
+ 'Transfer-Encoding',
+ 'Upgrade',
+ 'Upgrade-Insecure-Requests',
+ 'User-Agent',
+ 'Vary',
+ 'Via',
+ 'WWW-Authenticate',
+ 'X-Content-Type-Options',
+ 'X-DNS-Prefetch-Control',
+ 'X-Frame-Options',
+ 'X-Permitted-Cross-Domain-Policies',
+ 'X-Powered-By',
+ 'X-Requested-With',
+ 'X-XSS-Protection'
+]
-function httpsOverHttps(options) {
- var agent = new TunnelingAgent(options);
- agent.request = https.request;
- agent.createSocket = createSecureSocket;
- agent.defaultPort = 443;
- return agent;
+for (let i = 0; i < wellknownHeaderNames.length; ++i) {
+ const key = wellknownHeaderNames[i]
+ const lowerCasedKey = key.toLowerCase()
+ headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
+ lowerCasedKey
}
+// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
+Object.setPrototypeOf(headerNameLowerCasedRecord, null)
-function TunnelingAgent(options) {
- var self = this;
- self.options = options || {};
- self.proxyOptions = self.options.proxy || {};
- self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
- self.requests = [];
- self.sockets = [];
-
- self.on('free', function onFree(socket, host, port, localAddress) {
- var options = toOptions(host, port, localAddress);
- for (var i = 0, len = self.requests.length; i < len; ++i) {
- var pending = self.requests[i];
- if (pending.host === options.host && pending.port === options.port) {
- // Detect the request to connect same origin server,
- // reuse the connection.
- self.requests.splice(i, 1);
- pending.request.onSocket(socket);
- return;
- }
- }
- socket.destroy();
- self.removeSocket(socket);
- });
+module.exports = {
+ wellknownHeaderNames,
+ headerNameLowerCasedRecord
}
-util.inherits(TunnelingAgent, events.EventEmitter);
-TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
- var self = this;
- var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
- if (self.sockets.length >= this.maxSockets) {
- // We are over limit so we'll add it to the queue.
- self.requests.push(options);
- return;
- }
+/***/ }),
- // If we are under maxSockets create a new one.
- self.createSocket(options, function(socket) {
- socket.on('free', onFree);
- socket.on('close', onCloseOrRemove);
- socket.on('agentRemove', onCloseOrRemove);
- req.onSocket(socket);
+/***/ 53959:
+/***/ ((module) => {
- function onFree() {
- self.emit('free', socket, options);
- }
- function onCloseOrRemove(err) {
- self.removeSocket(socket);
- socket.removeListener('free', onFree);
- socket.removeListener('close', onCloseOrRemove);
- socket.removeListener('agentRemove', onCloseOrRemove);
- }
- });
-};
-TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
- var self = this;
- var placeholder = {};
- self.sockets.push(placeholder);
+class UndiciError extends Error {
+ constructor (message) {
+ super(message)
+ this.name = 'UndiciError'
+ this.code = 'UND_ERR'
+ }
+}
- var connectOptions = mergeOptions({}, self.proxyOptions, {
- method: 'CONNECT',
- path: options.host + ':' + options.port,
- agent: false,
- headers: {
- host: options.host + ':' + options.port
- }
- });
- if (options.localAddress) {
- connectOptions.localAddress = options.localAddress;
+class ConnectTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ConnectTimeoutError)
+ this.name = 'ConnectTimeoutError'
+ this.message = message || 'Connect Timeout Error'
+ this.code = 'UND_ERR_CONNECT_TIMEOUT'
}
- if (connectOptions.proxyAuth) {
- connectOptions.headers = connectOptions.headers || {};
- connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
- new Buffer(connectOptions.proxyAuth).toString('base64');
+}
+
+class HeadersTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, HeadersTimeoutError)
+ this.name = 'HeadersTimeoutError'
+ this.message = message || 'Headers Timeout Error'
+ this.code = 'UND_ERR_HEADERS_TIMEOUT'
}
+}
- debug('making CONNECT request');
- var connectReq = self.request(connectOptions);
- connectReq.useChunkedEncodingByDefault = false; // for v0.6
- connectReq.once('response', onResponse); // for v0.6
- connectReq.once('upgrade', onUpgrade); // for v0.6
- connectReq.once('connect', onConnect); // for v0.7 or later
- connectReq.once('error', onError);
- connectReq.end();
+class HeadersOverflowError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, HeadersOverflowError)
+ this.name = 'HeadersOverflowError'
+ this.message = message || 'Headers Overflow Error'
+ this.code = 'UND_ERR_HEADERS_OVERFLOW'
+ }
+}
- function onResponse(res) {
- // Very hacky. This is necessary to avoid http-parser leaks.
- res.upgrade = true;
+class BodyTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, BodyTimeoutError)
+ this.name = 'BodyTimeoutError'
+ this.message = message || 'Body Timeout Error'
+ this.code = 'UND_ERR_BODY_TIMEOUT'
}
+}
- function onUpgrade(res, socket, head) {
- // Hacky.
- process.nextTick(function() {
- onConnect(res, socket, head);
- });
+class ResponseStatusCodeError extends UndiciError {
+ constructor (message, statusCode, headers, body) {
+ super(message)
+ Error.captureStackTrace(this, ResponseStatusCodeError)
+ this.name = 'ResponseStatusCodeError'
+ this.message = message || 'Response Status Code Error'
+ this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
+ this.body = body
+ this.status = statusCode
+ this.statusCode = statusCode
+ this.headers = headers
}
+}
- function onConnect(res, socket, head) {
- connectReq.removeAllListeners();
- socket.removeAllListeners();
+class InvalidArgumentError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InvalidArgumentError)
+ this.name = 'InvalidArgumentError'
+ this.message = message || 'Invalid Argument Error'
+ this.code = 'UND_ERR_INVALID_ARG'
+ }
+}
- if (res.statusCode !== 200) {
- debug('tunneling socket could not be established, statusCode=%d',
- res.statusCode);
- socket.destroy();
- var error = new Error('tunneling socket could not be established, ' +
- 'statusCode=' + res.statusCode);
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
- return;
- }
- if (head.length > 0) {
- debug('got illegal response body from proxy');
- socket.destroy();
- var error = new Error('got illegal response body from proxy');
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
- return;
- }
- debug('tunneling connection has established');
- self.sockets[self.sockets.indexOf(placeholder)] = socket;
- return cb(socket);
+class InvalidReturnValueError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InvalidReturnValueError)
+ this.name = 'InvalidReturnValueError'
+ this.message = message || 'Invalid Return Value Error'
+ this.code = 'UND_ERR_INVALID_RETURN_VALUE'
}
+}
- function onError(cause) {
- connectReq.removeAllListeners();
+class RequestAbortedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, RequestAbortedError)
+ this.name = 'AbortError'
+ this.message = message || 'Request aborted'
+ this.code = 'UND_ERR_ABORTED'
+ }
+}
- debug('tunneling socket could not be established, cause=%s\n',
- cause.message, cause.stack);
- var error = new Error('tunneling socket could not be established, ' +
- 'cause=' + cause.message);
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
+class InformationalError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InformationalError)
+ this.name = 'InformationalError'
+ this.message = message || 'Request information'
+ this.code = 'UND_ERR_INFO'
}
-};
+}
-TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
- var pos = this.sockets.indexOf(socket)
- if (pos === -1) {
- return;
+class RequestContentLengthMismatchError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, RequestContentLengthMismatchError)
+ this.name = 'RequestContentLengthMismatchError'
+ this.message = message || 'Request body length does not match content-length header'
+ this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
}
- this.sockets.splice(pos, 1);
+}
- var pending = this.requests.shift();
- if (pending) {
- // If we have pending requests and a socket gets closed a new one
- // needs to be created to take over in the pool for the one that closed.
- this.createSocket(pending, function(socket) {
- pending.request.onSocket(socket);
- });
+class ResponseContentLengthMismatchError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ResponseContentLengthMismatchError)
+ this.name = 'ResponseContentLengthMismatchError'
+ this.message = message || 'Response body length does not match content-length header'
+ this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
}
-};
+}
-function createSecureSocket(options, cb) {
- var self = this;
- TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
- var hostHeader = options.request.getHeader('host');
- var tlsOptions = mergeOptions({}, self.options, {
- socket: socket,
- servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
- });
+class ClientDestroyedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ClientDestroyedError)
+ this.name = 'ClientDestroyedError'
+ this.message = message || 'The client is destroyed'
+ this.code = 'UND_ERR_DESTROYED'
+ }
+}
- // 0 is dummy port for v0.6
- var secureSocket = tls.connect(0, tlsOptions);
- self.sockets[self.sockets.indexOf(socket)] = secureSocket;
- cb(secureSocket);
- });
+class ClientClosedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ClientClosedError)
+ this.name = 'ClientClosedError'
+ this.message = message || 'The client is closed'
+ this.code = 'UND_ERR_CLOSED'
+ }
}
+class SocketError extends UndiciError {
+ constructor (message, socket) {
+ super(message)
+ Error.captureStackTrace(this, SocketError)
+ this.name = 'SocketError'
+ this.message = message || 'Socket error'
+ this.code = 'UND_ERR_SOCKET'
+ this.socket = socket
+ }
+}
-function toOptions(host, port, localAddress) {
- if (typeof host === 'string') { // since v0.10
- return {
- host: host,
- port: port,
- localAddress: localAddress
- };
+class NotSupportedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, NotSupportedError)
+ this.name = 'NotSupportedError'
+ this.message = message || 'Not supported error'
+ this.code = 'UND_ERR_NOT_SUPPORTED'
}
- return host; // for v0.11 or later
}
-function mergeOptions(target) {
- for (var i = 1, len = arguments.length; i < len; ++i) {
- var overrides = arguments[i];
- if (typeof overrides === 'object') {
- var keys = Object.keys(overrides);
- for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
- var k = keys[j];
- if (overrides[k] !== undefined) {
- target[k] = overrides[k];
- }
- }
- }
+class BalancedPoolMissingUpstreamError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, NotSupportedError)
+ this.name = 'MissingUpstreamError'
+ this.message = message || 'No upstream has been added to the BalancedPool'
+ this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
}
- return target;
}
+class HTTPParserError extends Error {
+ constructor (message, code, data) {
+ super(message)
+ Error.captureStackTrace(this, HTTPParserError)
+ this.name = 'HTTPParserError'
+ this.code = code ? `HPE_${code}` : undefined
+ this.data = data ? data.toString() : undefined
+ }
+}
-var debug;
-if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
- debug = function() {
- var args = Array.prototype.slice.call(arguments);
- if (typeof args[0] === 'string') {
- args[0] = 'TUNNEL: ' + args[0];
- } else {
- args.unshift('TUNNEL:');
- }
- console.error.apply(console, args);
+class ResponseExceededMaxSizeError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ResponseExceededMaxSizeError)
+ this.name = 'ResponseExceededMaxSizeError'
+ this.message = message || 'Response content exceeded max size'
+ this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
}
-} else {
- debug = function() {};
}
-exports.debug = debug; // for test
+class RequestRetryError extends UndiciError {
+ constructor (message, code, { headers, data }) {
+ super(message)
+ Error.captureStackTrace(this, RequestRetryError)
+ this.name = 'RequestRetryError'
+ this.message = message || 'Request retry error'
+ this.code = 'UND_ERR_REQ_RETRY'
+ this.statusCode = code
+ this.data = data
+ this.headers = headers
+ }
+}
-/***/ }),
+module.exports = {
+ HTTPParserError,
+ UndiciError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ BodyTimeoutError,
+ RequestContentLengthMismatchError,
+ ConnectTimeoutError,
+ ResponseStatusCodeError,
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError,
+ ClientDestroyedError,
+ ClientClosedError,
+ InformationalError,
+ SocketError,
+ NotSupportedError,
+ ResponseContentLengthMismatchError,
+ BalancedPoolMissingUpstreamError,
+ ResponseExceededMaxSizeError,
+ RequestRetryError
+}
-/***/ 99069:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ }),
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+/***/ 69691:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-/***/ }),
-/***/ 28775:
-/***/ ((__unused_webpack_module, exports) => {
+const {
+ InvalidArgumentError,
+ NotSupportedError
+} = __nccwpck_require__(53959)
+const assert = __nccwpck_require__(42613)
+const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(68031)
+const util = __nccwpck_require__(89500)
+// tokenRegExp and headerCharRegex have been lifted from
+// https://github.com/nodejs/node/blob/main/lib/_http_common.js
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isValidErrorCode = exports.httpStatusFromErrorCode = exports.TwirpErrorCode = exports.BadRouteError = exports.InternalServerErrorWith = exports.InternalServerError = exports.RequiredArgumentError = exports.InvalidArgumentError = exports.NotFoundError = exports.TwirpError = void 0;
-/**
- * Represents a twirp error
- */
-class TwirpError extends Error {
- constructor(code, msg) {
- super(msg);
- this.code = TwirpErrorCode.Internal;
- this.meta = {};
- this.code = code;
- this.msg = msg;
- Object.setPrototypeOf(this, TwirpError.prototype);
- }
- /**
- * Adds a metadata kv to the error
- * @param key
- * @param value
- */
- withMeta(key, value) {
- this.meta[key] = value;
- return this;
- }
- /**
- * Returns a single metadata value
- * return "" if not found
- * @param key
- */
- getMeta(key) {
- return this.meta[key] || "";
- }
- /**
- * Add the original error cause
- * @param err
- * @param addMeta
- */
- withCause(err, addMeta = false) {
- this._originalCause = err;
- if (addMeta) {
- this.withMeta("cause", err.message);
- }
- return this;
- }
- cause() {
- return this._originalCause;
- }
- /**
- * Returns the error representation to JSON
- */
- toJSON() {
- try {
- return JSON.stringify({
- code: this.code,
- msg: this.msg,
- meta: this.meta,
- });
- }
- catch (e) {
- return `{"code": "internal", "msg": "There was an error but it could not be serialized into JSON"}`;
- }
- }
- /**
- * Create a twirp error from an object
- * @param obj
- */
- static fromObject(obj) {
- const code = obj["code"] || TwirpErrorCode.Unknown;
- const msg = obj["msg"] || "unknown";
- const error = new TwirpError(code, msg);
- if (obj["meta"]) {
- Object.keys(obj["meta"]).forEach((key) => {
- error.withMeta(key, obj["meta"][key]);
- });
- }
- return error;
- }
-}
-exports.TwirpError = TwirpError;
-/**
- * NotFoundError constructor for the common NotFound error.
- */
-class NotFoundError extends TwirpError {
- constructor(msg) {
- super(TwirpErrorCode.NotFound, msg);
- }
-}
-exports.NotFoundError = NotFoundError;
-/**
- * InvalidArgumentError constructor for the common InvalidArgument error. Can be
- * used when an argument has invalid format, is a number out of range, is a bad
- * option, etc).
- */
-class InvalidArgumentError extends TwirpError {
- constructor(argument, validationMsg) {
- super(TwirpErrorCode.InvalidArgument, argument + " " + validationMsg);
- this.withMeta("argument", argument);
- }
-}
-exports.InvalidArgumentError = InvalidArgumentError;
-/**
- * RequiredArgumentError is a more specific constructor for InvalidArgument
- * error. Should be used when the argument is required (expected to have a
- * non-zero value).
- */
-class RequiredArgumentError extends InvalidArgumentError {
- constructor(argument) {
- super(argument, "is required");
- }
-}
-exports.RequiredArgumentError = RequiredArgumentError;
-/**
- * InternalError constructor for the common Internal error. Should be used to
- * specify that something bad or unexpected happened.
- */
-class InternalServerError extends TwirpError {
- constructor(msg) {
- super(TwirpErrorCode.Internal, msg);
- }
-}
-exports.InternalServerError = InternalServerError;
/**
- * InternalErrorWith makes an internal error, wrapping the original error and using it
- * for the error message, and with metadata "cause" with the original error type.
- * This function is used by Twirp services to wrap non-Twirp errors as internal errors.
- * The wrapped error can be extracted later with err.cause()
+ * Verifies that the given val is a valid HTTP token
+ * per the rules defined in RFC 7230
+ * See https://tools.ietf.org/html/rfc7230#section-3.2.6
*/
-class InternalServerErrorWith extends InternalServerError {
- constructor(err) {
- super(err.message);
- this.withMeta("cause", err.name);
- this.withCause(err);
- }
-}
-exports.InternalServerErrorWith = InternalServerErrorWith;
+const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/
+
/**
- * A standard BadRoute Error
+ * Matches if val contains an invalid field-vchar
+ * field-value = *( field-content / obs-fold )
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
+ * field-vchar = VCHAR / obs-text
*/
-class BadRouteError extends TwirpError {
- constructor(msg, method, url) {
- super(TwirpErrorCode.BadRoute, msg);
- this.withMeta("twirp_invalid_route", method + " " + url);
- }
-}
-exports.BadRouteError = BadRouteError;
-var TwirpErrorCode;
-(function (TwirpErrorCode) {
- // Canceled indicates the operation was cancelled (typically by the caller).
- TwirpErrorCode["Canceled"] = "canceled";
- // Unknown error. For example when handling errors raised by APIs that do not
- // return enough error information.
- TwirpErrorCode["Unknown"] = "unknown";
- // InvalidArgument indicates client specified an invalid argument. It
- // indicates arguments that are problematic regardless of the state of the
- // system (i.e. a malformed file name, required argument, number out of range,
- // etc.).
- TwirpErrorCode["InvalidArgument"] = "invalid_argument";
- // Malformed indicates an error occurred while decoding the client's request.
- // This may mean that the message was encoded improperly, or that there is a
- // disagreement in message format between the client and server.
- TwirpErrorCode["Malformed"] = "malformed";
- // DeadlineExceeded means operation expired before completion. For operations
- // that change the state of the system, this error may be returned even if the
- // operation has completed successfully (timeout).
- TwirpErrorCode["DeadlineExceeded"] = "deadline_exceeded";
- // NotFound means some requested entity was not found.
- TwirpErrorCode["NotFound"] = "not_found";
- // BadRoute means that the requested URL path wasn't routable to a Twirp
- // service and method. This is returned by the generated server, and usually
- // shouldn't be returned by applications. Instead, applications should use
- // NotFound or Unimplemented.
- TwirpErrorCode["BadRoute"] = "bad_route";
- // AlreadyExists means an attempt to create an entity failed because one
- // already exists.
- TwirpErrorCode["AlreadyExists"] = "already_exists";
- // PermissionDenied indicates the caller does not have permission to execute
- // the specified operation. It must not be used if the caller cannot be
- // identified (Unauthenticated).
- TwirpErrorCode["PermissionDenied"] = "permission_denied";
- // Unauthenticated indicates the request does not have valid authentication
- // credentials for the operation.
- TwirpErrorCode["Unauthenticated"] = "unauthenticated";
- // ResourceExhausted indicates some resource has been exhausted, perhaps a
- // per-user quota, or perhaps the entire file system is out of space.
- TwirpErrorCode["ResourceExhausted"] = "resource_exhausted";
- // FailedPrecondition indicates operation was rejected because the system is
- // not in a state required for the operation's execution. For example, doing
- // an rmdir operation on a directory that is non-empty, or on a non-directory
- // object, or when having conflicting read-modify-write on the same resource.
- TwirpErrorCode["FailedPrecondition"] = "failed_precondition";
- // Aborted indicates the operation was aborted, typically due to a concurrency
- // issue like sequencer check failures, transaction aborts, etc.
- TwirpErrorCode["Aborted"] = "aborted";
- // OutOfRange means operation was attempted past the valid range. For example,
- // seeking or reading past end of a paginated collection.
- //
- // Unlike InvalidArgument, this error indicates a problem that may be fixed if
- // the system state changes (i.e. adding more items to the collection).
- //
- // There is a fair bit of overlap between FailedPrecondition and OutOfRange.
- // We recommend using OutOfRange (the more specific error) when it applies so
- // that callers who are iterating through a space can easily look for an
- // OutOfRange error to detect when they are done.
- TwirpErrorCode["OutOfRange"] = "out_of_range";
- // Unimplemented indicates operation is not implemented or not
- // supported/enabled in this service.
- TwirpErrorCode["Unimplemented"] = "unimplemented";
- // Internal errors. When some invariants expected by the underlying system
- // have been broken. In other words, something bad happened in the library or
- // backend service. Do not confuse with HTTP Internal Server Error; an
- // Internal error could also happen on the client code, i.e. when parsing a
- // server response.
- TwirpErrorCode["Internal"] = "internal";
- // Unavailable indicates the service is currently unavailable. This is a most
- // likely a transient condition and may be corrected by retrying with a
- // backoff.
- TwirpErrorCode["Unavailable"] = "unavailable";
- // DataLoss indicates unrecoverable data loss or corruption.
- TwirpErrorCode["DataLoss"] = "data_loss";
-})(TwirpErrorCode = exports.TwirpErrorCode || (exports.TwirpErrorCode = {}));
-// ServerHTTPStatusFromErrorCode maps a Twirp error type into a similar HTTP
-// response status. It is used by the Twirp server handler to set the HTTP
-// response status code. Returns 0 if the ErrorCode is invalid.
-function httpStatusFromErrorCode(code) {
- switch (code) {
- case TwirpErrorCode.Canceled:
- return 408; // RequestTimeout
- case TwirpErrorCode.Unknown:
- return 500; // Internal Server Error
- case TwirpErrorCode.InvalidArgument:
- return 400; // BadRequest
- case TwirpErrorCode.Malformed:
- return 400; // BadRequest
- case TwirpErrorCode.DeadlineExceeded:
- return 408; // RequestTimeout
- case TwirpErrorCode.NotFound:
- return 404; // Not Found
- case TwirpErrorCode.BadRoute:
- return 404; // Not Found
- case TwirpErrorCode.AlreadyExists:
- return 409; // Conflict
- case TwirpErrorCode.PermissionDenied:
- return 403; // Forbidden
- case TwirpErrorCode.Unauthenticated:
- return 401; // Unauthorized
- case TwirpErrorCode.ResourceExhausted:
- return 429; // Too Many Requests
- case TwirpErrorCode.FailedPrecondition:
- return 412; // Precondition Failed
- case TwirpErrorCode.Aborted:
- return 409; // Conflict
- case TwirpErrorCode.OutOfRange:
- return 400; // Bad Request
- case TwirpErrorCode.Unimplemented:
- return 501; // Not Implemented
- case TwirpErrorCode.Internal:
- return 500; // Internal Server Error
- case TwirpErrorCode.Unavailable:
- return 503; // Service Unavailable
- case TwirpErrorCode.DataLoss:
- return 500; // Internal Server Error
- default:
- return 0; // Invalid!
- }
-}
-exports.httpStatusFromErrorCode = httpStatusFromErrorCode;
-// IsValidErrorCode returns true if is one of the valid predefined constants.
-function isValidErrorCode(code) {
- return httpStatusFromErrorCode(code) != 0;
-}
-exports.isValidErrorCode = isValidErrorCode;
+const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
+
+// Verifies that a given path is valid does not contain control chars \x00 to \x20
+const invalidPathRegex = /[^\u0021-\u00ff]/
+const kHandler = Symbol('handler')
-/***/ }),
+const channels = {}
-/***/ 70048:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+let extractBody
+try {
+ const diagnosticsChannel = __nccwpck_require__(31637)
+ channels.create = diagnosticsChannel.channel('undici:request:create')
+ channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')
+ channels.headers = diagnosticsChannel.channel('undici:request:headers')
+ channels.trailers = diagnosticsChannel.channel('undici:request:trailers')
+ channels.error = diagnosticsChannel.channel('undici:request:error')
+} catch {
+ channels.create = { hasSubscribers: false }
+ channels.bodySent = { hasSubscribers: false }
+ channels.headers = { hasSubscribers: false }
+ channels.trailers = { hasSubscribers: false }
+ channels.error = { hasSubscribers: false }
+}
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Gateway = exports.Pattern = void 0;
-const querystring_1 = __nccwpck_require__(83480);
-const dotObject = __importStar(__nccwpck_require__(98749));
-const request_1 = __nccwpck_require__(21179);
-const errors_1 = __nccwpck_require__(28775);
-const http_client_1 = __nccwpck_require__(52503);
-const server_1 = __nccwpck_require__(1991);
-var Pattern;
-(function (Pattern) {
- Pattern["POST"] = "post";
- Pattern["GET"] = "get";
- Pattern["PATCH"] = "patch";
- Pattern["PUT"] = "put";
- Pattern["DELETE"] = "delete";
-})(Pattern = exports.Pattern || (exports.Pattern = {}));
-/**
- * The Gateway proxies http requests to Twirp Compliant
- * handlers
- */
-class Gateway {
- constructor(routes) {
- this.routes = routes;
- }
- /**
- * Middleware that rewrite the current request
- * to a Twirp compliant request
- */
- twirpRewrite(prefix = "/twirp") {
- return (req, resp, next) => {
- this.rewrite(req, resp, prefix)
- .then(() => next())
- .catch((e) => {
- if (e instanceof errors_1.TwirpError) {
- if (e.code !== errors_1.TwirpErrorCode.NotFound) {
- server_1.writeError(resp, e);
- }
- else {
- next();
- }
- }
- });
- };
+class Request {
+ constructor (origin, {
+ path,
+ method,
+ body,
+ headers,
+ query,
+ idempotent,
+ blocking,
+ upgrade,
+ headersTimeout,
+ bodyTimeout,
+ reset,
+ throwOnError,
+ expectContinue
+ }, handler) {
+ if (typeof path !== 'string') {
+ throw new InvalidArgumentError('path must be a string')
+ } else if (
+ path[0] !== '/' &&
+ !(path.startsWith('http://') || path.startsWith('https://')) &&
+ method !== 'CONNECT'
+ ) {
+ throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
+ } else if (invalidPathRegex.exec(path) !== null) {
+ throw new InvalidArgumentError('invalid request path')
}
- /**
- * Rewrite an incoming request to a Twirp compliant request
- * @param req
- * @param resp
- * @param prefix
- */
- rewrite(req, resp, prefix = "/twirp") {
- return __awaiter(this, void 0, void 0, function* () {
- const [match, route] = this.matchRoute(req);
- const body = yield this.prepareTwirpBody(req, match, route);
- const twirpUrl = `${prefix}/${route.packageName}.${route.serviceName}/${route.methodName}`;
- req.url = twirpUrl;
- req.originalUrl = twirpUrl;
- req.method = "POST";
- req.headers["content-type"] = "application/json";
- req.rawBody = Buffer.from(JSON.stringify(body));
- if (route.responseBodyKey) {
- const endFn = resp.end.bind(resp);
- resp.end = function (chunk) {
- if (resp.statusCode === 200) {
- endFn(`{ "${route.responseBodyKey}": ${chunk} }`);
- }
- else {
- endFn(chunk);
- }
- };
- }
- });
+
+ if (typeof method !== 'string') {
+ throw new InvalidArgumentError('method must be a string')
+ } else if (tokenRegExp.exec(method) === null) {
+ throw new InvalidArgumentError('invalid request method')
}
- /**
- * Create a reverse proxy handler to
- * proxy http requests to Twirp Compliant handlers
- * @param httpClientOption
- */
- reverseProxy(httpClientOption) {
- const client = http_client_1.NodeHttpRPC(httpClientOption);
- return (req, res) => __awaiter(this, void 0, void 0, function* () {
- try {
- const [match, route] = this.matchRoute(req);
- const body = yield this.prepareTwirpBody(req, match, route);
- const response = yield client.request(`${route.packageName}.${route.serviceName}`, route.methodName, "application/json", body);
- res.statusCode = 200;
- res.setHeader("content-type", "application/json");
- let jsonResponse;
- if (route.responseBodyKey) {
- jsonResponse = JSON.stringify({ [route.responseBodyKey]: response });
- }
- else {
- jsonResponse = JSON.stringify(response);
- }
- res.end(jsonResponse);
- }
- catch (e) {
- server_1.writeError(res, e);
- }
- });
+
+ if (upgrade && typeof upgrade !== 'string') {
+ throw new InvalidArgumentError('upgrade must be a string')
}
- /**
- * Prepares twirp body requests using http.google.annotions
- * compliant spec
- *
- * @param req
- * @param match
- * @param route
- * @protected
- */
- prepareTwirpBody(req, match, route) {
- return __awaiter(this, void 0, void 0, function* () {
- const _a = match.params, { query_string } = _a, params = __rest(_a, ["query_string"]);
- let requestBody = Object.assign({}, params);
- if (query_string && route.bodyKey !== "*") {
- const queryParams = this.parseQueryString(query_string);
- requestBody = Object.assign(Object.assign({}, queryParams), requestBody);
- }
- let body = {};
- if (route.bodyKey) {
- const data = yield request_1.getRequestData(req);
- try {
- const jsonBody = JSON.parse(data.toString() || "{}");
- if (route.bodyKey === "*") {
- body = jsonBody;
- }
- else {
- body[route.bodyKey] = jsonBody;
- }
- }
- catch (e) {
- const msg = "the json request could not be decoded";
- throw new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
- }
- }
- return Object.assign(Object.assign({}, body), requestBody);
- });
+
+ if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError('invalid headersTimeout')
}
- /**
- * Matches a route
- * @param req
- */
- matchRoute(req) {
- var _a;
- const httpMethod = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toLowerCase();
- if (!httpMethod) {
- throw new errors_1.BadRouteError(`method not allowed`, req.method || "", req.url || "");
+
+ if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError('invalid bodyTimeout')
+ }
+
+ if (reset != null && typeof reset !== 'boolean') {
+ throw new InvalidArgumentError('invalid reset')
+ }
+
+ if (expectContinue != null && typeof expectContinue !== 'boolean') {
+ throw new InvalidArgumentError('invalid expectContinue')
+ }
+
+ this.headersTimeout = headersTimeout
+
+ this.bodyTimeout = bodyTimeout
+
+ this.throwOnError = throwOnError === true
+
+ this.method = method
+
+ this.abort = null
+
+ if (body == null) {
+ this.body = null
+ } else if (util.isStream(body)) {
+ this.body = body
+
+ const rState = this.body._readableState
+ if (!rState || !rState.autoDestroy) {
+ this.endHandler = function autoDestroy () {
+ util.destroy(this)
}
- const routes = this.routes[httpMethod];
- for (const route of routes) {
- const match = route.matcher(req.url || "/");
- if (match) {
- return [match, route];
- }
+ this.body.on('end', this.endHandler)
+ }
+
+ this.errorHandler = err => {
+ if (this.abort) {
+ this.abort(err)
+ } else {
+ this.error = err
}
- throw new errors_1.NotFoundError(`url ${req.url} not found`);
- }
- /**
- * Parse query string
- * @param queryString
- */
- parseQueryString(queryString) {
- const queryParams = querystring_1.parse(queryString.replace("?", ""));
- return dotObject.object(queryParams);
+ }
+ this.body.on('error', this.errorHandler)
+ } else if (util.isBuffer(body)) {
+ this.body = body.byteLength ? body : null
+ } else if (ArrayBuffer.isView(body)) {
+ this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
+ } else if (body instanceof ArrayBuffer) {
+ this.body = body.byteLength ? Buffer.from(body) : null
+ } else if (typeof body === 'string') {
+ this.body = body.length ? Buffer.from(body) : null
+ } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {
+ this.body = body
+ } else {
+ throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
}
-}
-exports.Gateway = Gateway;
+ this.completed = false
-/***/ }),
+ this.aborted = false
-/***/ 99462:
-/***/ (function(__unused_webpack_module, exports) {
+ this.upgrade = upgrade || null
+ this.path = query ? util.buildURL(path, query) : path
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isHook = exports.chainHooks = void 0;
-// ChainHooks creates a new ServerHook which chains the callbacks in
-// each of the constituent hooks passed in. Each hook function will be
-// called in the order of the ServerHooks values passed in.
-//
-// For the erroring hooks, RequestReceived and RequestRouted, any returned
-// errors prevent processing by later hooks.
-function chainHooks(...hooks) {
- if (hooks.length === 0) {
- return null;
+ this.origin = origin
+
+ this.idempotent = idempotent == null
+ ? method === 'HEAD' || method === 'GET'
+ : idempotent
+
+ this.blocking = blocking == null ? false : blocking
+
+ this.reset = reset == null ? null : reset
+
+ this.host = null
+
+ this.contentLength = null
+
+ this.contentType = null
+
+ this.headers = ''
+
+ // Only for H2
+ this.expectContinue = expectContinue != null ? expectContinue : false
+
+ if (Array.isArray(headers)) {
+ if (headers.length % 2 !== 0) {
+ throw new InvalidArgumentError('headers array must be even')
+ }
+ for (let i = 0; i < headers.length; i += 2) {
+ processHeader(this, headers[i], headers[i + 1])
+ }
+ } else if (headers && typeof headers === 'object') {
+ const keys = Object.keys(headers)
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i]
+ processHeader(this, key, headers[key])
+ }
+ } else if (headers != null) {
+ throw new InvalidArgumentError('headers must be an object or an array')
}
- if (hooks.length === 1) {
- return hooks[0];
+
+ if (util.isFormDataLike(this.body)) {
+ if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {
+ throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')
+ }
+
+ if (!extractBody) {
+ extractBody = (__nccwpck_require__(37791).extractBody)
+ }
+
+ const [bodyStream, contentType] = extractBody(body)
+ if (this.contentType == null) {
+ this.contentType = contentType
+ this.headers += `content-type: ${contentType}\r\n`
+ }
+ this.body = bodyStream.stream
+ this.contentLength = bodyStream.length
+ } else if (util.isBlobLike(body) && this.contentType == null && body.type) {
+ this.contentType = body.type
+ this.headers += `content-type: ${body.type}\r\n`
}
- const serverHook = {
- requestReceived(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestReceived) {
- continue;
- }
- yield hook.requestReceived(ctx);
- }
- });
- },
- requestPrepared(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestPrepared) {
- continue;
- }
- console.warn("hook requestPrepared is deprecated and will be removed in the next release. " +
- "Please use responsePrepared instead.");
- yield hook.requestPrepared(ctx);
- }
- });
- },
- responsePrepared(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.responsePrepared) {
- continue;
- }
- yield hook.responsePrepared(ctx);
- }
- });
- },
- requestSent(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestSent) {
- continue;
- }
- console.warn("hook requestSent is deprecated and will be removed in the next release. " +
- "Please use responseSent instead.");
- yield hook.requestSent(ctx);
- }
- });
- },
- responseSent(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.responseSent) {
- continue;
- }
- yield hook.responseSent(ctx);
- }
- });
- },
- requestRouted(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestRouted) {
- continue;
- }
- yield hook.requestRouted(ctx);
- }
- });
- },
- error(ctx, err) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.error) {
- continue;
- }
- yield hook.error(ctx, err);
- }
- });
- },
- };
- return serverHook;
-}
-exports.chainHooks = chainHooks;
-function isHook(object) {
- return ("requestReceived" in object ||
- "requestPrepared" in object ||
- "requestSent" in object ||
- "requestRouted" in object ||
- "responsePrepared" in object ||
- "responseSent" in object ||
- "error" in object);
-}
-exports.isHook = isHook;
+ util.validateHandler(handler, method, upgrade)
-/***/ }),
+ this.servername = util.getServerName(this.host)
-/***/ 52503:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ this[kHandler] = handler
+ if (channels.create.hasSubscribers) {
+ channels.create.publish({ request: this })
+ }
+ }
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.FetchRPC = exports.wrapErrorResponseToTwirpError = exports.NodeHttpRPC = void 0;
-const http = __importStar(__nccwpck_require__(58611));
-const https = __importStar(__nccwpck_require__(65692));
-const url_1 = __nccwpck_require__(87016);
-const errors_1 = __nccwpck_require__(28775);
-/**
- * a node HTTP RPC implementation
- * @param options
- * @constructor
- */
-const NodeHttpRPC = (options) => ({
- request(service, method, contentType, data) {
- let client;
- return new Promise((resolve, rejected) => {
- const responseChunks = [];
- const requestData = contentType === "application/protobuf"
- ? Buffer.from(data)
- : JSON.stringify(data);
- const url = new url_1.URL(options.baseUrl);
- const isHttps = url.protocol === "https:";
- if (isHttps) {
- client = https;
- }
- else {
- client = http;
- }
- const prefix = url.pathname !== "/" ? url.pathname : "";
- const req = client
- .request(Object.assign(Object.assign({}, (options ? options : {})), { method: "POST", protocol: url.protocol, host: url.hostname, port: url.port ? url.port : isHttps ? 443 : 80, path: `${prefix}/${service}/${method}`, headers: Object.assign(Object.assign({}, (options.headers ? options.headers : {})), { "Content-Type": contentType, "Content-Length": contentType === "application/protobuf"
- ? Buffer.byteLength(requestData)
- : Buffer.from(requestData).byteLength }) }), (res) => {
- res.on("data", (chunk) => responseChunks.push(chunk));
- res.on("end", () => {
- const data = Buffer.concat(responseChunks);
- if (res.statusCode != 200) {
- rejected(wrapErrorResponseToTwirpError(data.toString()));
- }
- else {
- if (contentType === "application/json") {
- resolve(JSON.parse(data.toString()));
- }
- else {
- resolve(data);
- }
- }
- });
- res.on("error", (err) => {
- rejected(err);
- });
- })
- .on("error", (err) => {
- rejected(err);
- });
- req.end(requestData);
- });
- },
-});
-exports.NodeHttpRPC = NodeHttpRPC;
-function wrapErrorResponseToTwirpError(errorResponse) {
- return errors_1.TwirpError.fromObject(JSON.parse(errorResponse));
-}
-exports.wrapErrorResponseToTwirpError = wrapErrorResponseToTwirpError;
-/**
- * a browser fetch RPC implementation
- */
-const FetchRPC = (options) => ({
- request(service, method, contentType, data) {
- return __awaiter(this, void 0, void 0, function* () {
- const headers = new Headers(options.headers);
- headers.set("content-type", contentType);
- const response = yield fetch(`${options.baseUrl}/${service}/${method}`, Object.assign(Object.assign({}, options), { method: "POST", headers, body: data instanceof Uint8Array ? data : JSON.stringify(data) }));
- if (response.status === 200) {
- if (contentType === "application/json") {
- return yield response.json();
- }
- return new Uint8Array(yield response.arrayBuffer());
- }
- throw errors_1.TwirpError.fromObject(yield response.json());
- });
- },
-});
-exports.FetchRPC = FetchRPC;
+ onBodySent (chunk) {
+ if (this[kHandler].onBodySent) {
+ try {
+ return this[kHandler].onBodySent(chunk)
+ } catch (err) {
+ this.abort(err)
+ }
+ }
+ }
+
+ onRequestSent () {
+ if (channels.bodySent.hasSubscribers) {
+ channels.bodySent.publish({ request: this })
+ }
+
+ if (this[kHandler].onRequestSent) {
+ try {
+ return this[kHandler].onRequestSent()
+ } catch (err) {
+ this.abort(err)
+ }
+ }
+ }
+
+ onConnect (abort) {
+ assert(!this.aborted)
+ assert(!this.completed)
+
+ if (this.error) {
+ abort(this.error)
+ } else {
+ this.abort = abort
+ return this[kHandler].onConnect(abort)
+ }
+ }
+ onHeaders (statusCode, headers, resume, statusText) {
+ assert(!this.aborted)
+ assert(!this.completed)
-/***/ }),
+ if (channels.headers.hasSubscribers) {
+ channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
+ }
-/***/ 33874:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ try {
+ return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
+ } catch (err) {
+ this.abort(err)
+ }
+ }
+ onData (chunk) {
+ assert(!this.aborted)
+ assert(!this.completed)
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TwirpContentType = void 0;
-__exportStar(__nccwpck_require__(99069), exports);
-__exportStar(__nccwpck_require__(1991), exports);
-__exportStar(__nccwpck_require__(51816), exports);
-__exportStar(__nccwpck_require__(99462), exports);
-__exportStar(__nccwpck_require__(28775), exports);
-__exportStar(__nccwpck_require__(70048), exports);
-__exportStar(__nccwpck_require__(52503), exports);
-var request_1 = __nccwpck_require__(21179);
-Object.defineProperty(exports, "TwirpContentType", ({ enumerable: true, get: function () { return request_1.TwirpContentType; } }));
+ try {
+ return this[kHandler].onData(chunk)
+ } catch (err) {
+ this.abort(err)
+ return false
+ }
+ }
+ onUpgrade (statusCode, headers, socket) {
+ assert(!this.aborted)
+ assert(!this.completed)
-/***/ }),
+ return this[kHandler].onUpgrade(statusCode, headers, socket)
+ }
-/***/ 51816:
-/***/ (function(__unused_webpack_module, exports) {
+ onComplete (trailers) {
+ this.onFinally()
+ assert(!this.aborted)
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.chainInterceptors = void 0;
-// chains multiple Interceptors into a single Interceptor.
-// The first interceptor wraps the second one, and so on.
-// Returns null if interceptors is empty.
-function chainInterceptors(...interceptors) {
- if (interceptors.length === 0) {
- return;
+ this.completed = true
+ if (channels.trailers.hasSubscribers) {
+ channels.trailers.publish({ request: this, trailers })
}
- if (interceptors.length === 1) {
- return interceptors[0];
+
+ try {
+ return this[kHandler].onComplete(trailers)
+ } catch (err) {
+ // TODO (fix): This might be a bad idea?
+ this.onError(err)
}
- const first = interceptors[0];
- return (ctx, request, handler) => __awaiter(this, void 0, void 0, function* () {
- let next = handler;
- for (let i = interceptors.length - 1; i > 0; i--) {
- next = ((next) => (ctx, typedRequest) => {
- return interceptors[i](ctx, typedRequest, next);
- })(next);
- }
- return first(ctx, request, next);
- });
-}
-exports.chainInterceptors = chainInterceptors;
+ }
+ onError (error) {
+ this.onFinally()
-/***/ }),
+ if (channels.error.hasSubscribers) {
+ channels.error.publish({ request: this, error })
+ }
-/***/ 21179:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ if (this.aborted) {
+ return
+ }
+ this.aborted = true
+ return this[kHandler].onError(error)
+ }
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.parseTwirpPath = exports.getRequestData = exports.validateRequest = exports.getContentType = exports.TwirpContentType = void 0;
-const errors_1 = __nccwpck_require__(28775);
-/**
- * Supported Twirp Content-Type
- */
-var TwirpContentType;
-(function (TwirpContentType) {
- TwirpContentType[TwirpContentType["Protobuf"] = 0] = "Protobuf";
- TwirpContentType[TwirpContentType["JSON"] = 1] = "JSON";
- TwirpContentType[TwirpContentType["Unknown"] = 2] = "Unknown";
-})(TwirpContentType = exports.TwirpContentType || (exports.TwirpContentType = {}));
-/**
- * Get supported content-type
- * @param mimeType
- */
-function getContentType(mimeType) {
- switch (mimeType) {
- case "application/protobuf":
- return TwirpContentType.Protobuf;
- case "application/json":
- return TwirpContentType.JSON;
- default:
- return TwirpContentType.Unknown;
- }
-}
-exports.getContentType = getContentType;
-/**
- * Validate a twirp request
- * @param ctx
- * @param request
- * @param pathPrefix
- */
-function validateRequest(ctx, request, pathPrefix) {
- if (request.method !== "POST") {
- const msg = `unsupported method ${request.method} (only POST is allowed)`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
- }
- const path = parseTwirpPath(request.url || "");
- if (path.pkgService !==
- (ctx.packageName ? ctx.packageName + "." : "") + ctx.serviceName) {
- const msg = `no handler for path ${request.url}`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ onFinally () {
+ if (this.errorHandler) {
+ this.body.off('error', this.errorHandler)
+ this.errorHandler = null
}
- if (path.prefix !== pathPrefix) {
- const msg = `invalid path prefix ${path.prefix}, expected ${pathPrefix}, on path ${request.url}`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+
+ if (this.endHandler) {
+ this.body.off('end', this.endHandler)
+ this.endHandler = null
}
- const mimeContentType = request.headers["content-type"] || "";
- if (ctx.contentType === TwirpContentType.Unknown) {
- const msg = `unexpected Content-Type: ${request.headers["content-type"]}`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+
+ // TODO: adjust to support H2
+ addHeader (key, value) {
+ processHeader(this, key, value)
+ return this
+ }
+
+ static [kHTTP1BuildRequest] (origin, opts, handler) {
+ // TODO: Migrate header parsing here, to make Requests
+ // HTTP agnostic
+ return new Request(origin, opts, handler)
+ }
+
+ static [kHTTP2BuildRequest] (origin, opts, handler) {
+ const headers = opts.headers
+ opts = { ...opts, headers: null }
+
+ const request = new Request(origin, opts, handler)
+
+ request.headers = {}
+
+ if (Array.isArray(headers)) {
+ if (headers.length % 2 !== 0) {
+ throw new InvalidArgumentError('headers array must be even')
+ }
+ for (let i = 0; i < headers.length; i += 2) {
+ processHeader(request, headers[i], headers[i + 1], true)
+ }
+ } else if (headers && typeof headers === 'object') {
+ const keys = Object.keys(headers)
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i]
+ processHeader(request, key, headers[key], true)
+ }
+ } else if (headers != null) {
+ throw new InvalidArgumentError('headers must be an object or an array')
}
- return Object.assign(Object.assign({}, path), { mimeContentType, contentType: ctx.contentType });
-}
-exports.validateRequest = validateRequest;
-/**
- * Get request data from the body
- * @param req
- */
-function getRequestData(req) {
- return new Promise((resolve, reject) => {
- const reqWithRawBody = req;
- if (reqWithRawBody.rawBody instanceof Buffer) {
- resolve(reqWithRawBody.rawBody);
- return;
- }
- const chunks = [];
- req.on("data", (chunk) => chunks.push(chunk));
- req.on("end", () => __awaiter(this, void 0, void 0, function* () {
- const data = Buffer.concat(chunks);
- resolve(data);
- }));
- req.on("error", (err) => {
- if (req.aborted) {
- reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.DeadlineExceeded, "failed to read request: deadline exceeded"));
- }
- else {
- reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, err.message).withCause(err));
- }
- });
- req.on("close", () => {
- reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Canceled, "failed to read request: context canceled"));
- });
- });
-}
-exports.getRequestData = getRequestData;
-/**
- * Parses twirp url path
- * @param path
- */
-function parseTwirpPath(path) {
- const parts = path.split("/");
- if (parts.length < 2) {
- return {
- pkgService: "",
- method: "",
- prefix: "",
- };
+
+ return request
+ }
+
+ static [kHTTP2CopyHeaders] (raw) {
+ const rawHeaders = raw.split('\r\n')
+ const headers = {}
+
+ for (const header of rawHeaders) {
+ const [key, value] = header.split(': ')
+
+ if (value == null || value.length === 0) continue
+
+ if (headers[key]) headers[key] += `,${value}`
+ else headers[key] = value
}
- return {
- method: parts[parts.length - 1],
- pkgService: parts[parts.length - 2],
- prefix: parts.slice(0, parts.length - 2).join("/"),
- };
+
+ return headers
+ }
}
-exports.parseTwirpPath = parseTwirpPath;
+function processHeaderValue (key, val, skipAppend) {
+ if (val && typeof val === 'object') {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ }
-/***/ }),
+ val = val != null ? `${val}` : ''
-/***/ 1991:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ if (headerCharRegex.exec(val) !== null) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ }
+ return skipAppend ? val : `${key}: ${val}\r\n`
+}
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.writeError = exports.TwirpServer = void 0;
-const hooks_1 = __nccwpck_require__(99462);
-const request_1 = __nccwpck_require__(21179);
-const errors_1 = __nccwpck_require__(28775);
-/**
- * Runtime server implementation of a TwirpServer
- */
-class TwirpServer {
- constructor(options) {
- this.pathPrefix = "/twirp";
- this.hooks = [];
- this.interceptors = [];
- this.packageName = options.packageName;
- this.serviceName = options.serviceName;
- this.methodList = options.methodList;
- this.matchRoute = options.matchRoute;
- this.service = options.service;
- }
- /**
- * Returns the prefix for this server
- */
- get prefix() {
- return this.pathPrefix;
- }
- /**
- * The http handler for twirp complaint endpoints
- * @param options
- */
- httpHandler(options) {
- return (req, resp) => {
- // setup prefix
- if ((options === null || options === void 0 ? void 0 : options.prefix) !== undefined) {
- this.withPrefix(options.prefix);
- }
- return this._httpHandler(req, resp);
- };
- }
- /**
- * Adds interceptors or hooks to the request stack
- * @param middlewares
- */
- use(...middlewares) {
- middlewares.forEach((middleware) => {
- if (hooks_1.isHook(middleware)) {
- this.hooks.push(middleware);
- return this;
- }
- this.interceptors.push(middleware);
- });
- return this;
- }
- /**
- * Adds a prefix to the service url path
- * @param prefix
- */
- withPrefix(prefix) {
- if (prefix === false) {
- this.pathPrefix = "";
- }
- else {
- this.pathPrefix = prefix;
- }
- return this;
- }
- /**
- * Returns the regex matching path for this twirp server
- */
- matchingPath() {
- const baseRegex = this.baseURI().replace(/\./g, "\\.");
- return new RegExp(`${baseRegex}\/(${this.methodList.join("|")})`);
- }
- /**
- * Returns the base URI for this twirp server
- */
- baseURI() {
- return `${this.pathPrefix}/${this.packageName ? this.packageName + "." : ""}${this.serviceName}`;
+function processHeader (request, key, val, skipAppend = false) {
+ if (val && (typeof val === 'object' && !Array.isArray(val))) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ } else if (val === undefined) {
+ return
+ }
+
+ if (
+ request.host === null &&
+ key.length === 4 &&
+ key.toLowerCase() === 'host'
+ ) {
+ if (headerCharRegex.exec(val) !== null) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
}
- /**
- * Create a twirp context
- * @param req
- * @param res
- * @private
- */
- createContext(req, res) {
- return {
- packageName: this.packageName,
- serviceName: this.serviceName,
- methodName: "",
- contentType: request_1.getContentType(req.headers["content-type"]),
- req: req,
- res: res,
- };
+ // Consumed by Client
+ request.host = val
+ } else if (
+ request.contentLength === null &&
+ key.length === 14 &&
+ key.toLowerCase() === 'content-length'
+ ) {
+ request.contentLength = parseInt(val, 10)
+ if (!Number.isFinite(request.contentLength)) {
+ throw new InvalidArgumentError('invalid content-length header')
}
- /**
- * Twrip server http handler implementation
- * @param req
- * @param resp
- * @private
- */
- _httpHandler(req, resp) {
- return __awaiter(this, void 0, void 0, function* () {
- const ctx = this.createContext(req, resp);
- try {
- yield this.invokeHook("requestReceived", ctx);
- const { method, mimeContentType } = request_1.validateRequest(ctx, req, this.pathPrefix || "");
- const handler = this.matchRoute(method, {
- onMatch: (ctx) => {
- return this.invokeHook("requestRouted", ctx);
- },
- onNotFound: () => {
- const msg = `no handler for path ${req.url}`;
- throw new errors_1.BadRouteError(msg, req.method || "", req.url || "");
- },
- });
- const body = yield request_1.getRequestData(req);
- const response = yield handler(ctx, this.service, body, this.interceptors);
- yield Promise.all([
- this.invokeHook("responsePrepared", ctx),
- // keep backwards compatibility till next release
- this.invokeHook("requestPrepared", ctx),
- ]);
- resp.statusCode = 200;
- resp.setHeader("Content-Type", mimeContentType);
- resp.end(response);
- }
- catch (e) {
- yield this.invokeHook("error", ctx, mustBeTwirpError(e));
- if (!resp.headersSent) {
- writeError(resp, e);
- }
- }
- finally {
- yield Promise.all([
- this.invokeHook("responseSent", ctx),
- // keep backwards compatibility till next release
- this.invokeHook("requestSent", ctx),
- ]);
- }
- });
+ } else if (
+ request.contentType === null &&
+ key.length === 12 &&
+ key.toLowerCase() === 'content-type'
+ ) {
+ request.contentType = val
+ if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
+ else request.headers += processHeaderValue(key, val)
+ } else if (
+ key.length === 17 &&
+ key.toLowerCase() === 'transfer-encoding'
+ ) {
+ throw new InvalidArgumentError('invalid transfer-encoding header')
+ } else if (
+ key.length === 10 &&
+ key.toLowerCase() === 'connection'
+ ) {
+ const value = typeof val === 'string' ? val.toLowerCase() : null
+ if (value !== 'close' && value !== 'keep-alive') {
+ throw new InvalidArgumentError('invalid connection header')
+ } else if (value === 'close') {
+ request.reset = true
}
- /**
- * Invoke a hook
- * @param hookName
- * @param ctx
- * @param err
- * @protected
- */
- invokeHook(hookName, ctx, err) {
- return __awaiter(this, void 0, void 0, function* () {
- if (this.hooks.length === 0) {
- return;
- }
- const chainedHooks = hooks_1.chainHooks(...this.hooks);
- const hook = chainedHooks === null || chainedHooks === void 0 ? void 0 : chainedHooks[hookName];
- if (hook) {
- yield hook(ctx, err || new errors_1.InternalServerError("internal server error"));
- }
- });
+ } else if (
+ key.length === 10 &&
+ key.toLowerCase() === 'keep-alive'
+ ) {
+ throw new InvalidArgumentError('invalid keep-alive header')
+ } else if (
+ key.length === 7 &&
+ key.toLowerCase() === 'upgrade'
+ ) {
+ throw new InvalidArgumentError('invalid upgrade header')
+ } else if (
+ key.length === 6 &&
+ key.toLowerCase() === 'expect'
+ ) {
+ throw new NotSupportedError('expect header not supported')
+ } else if (tokenRegExp.exec(key) === null) {
+ throw new InvalidArgumentError('invalid header key')
+ } else {
+ if (Array.isArray(val)) {
+ for (let i = 0; i < val.length; i++) {
+ if (skipAppend) {
+ if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`
+ else request.headers[key] = processHeaderValue(key, val[i], skipAppend)
+ } else {
+ request.headers += processHeaderValue(key, val[i])
+ }
+ }
+ } else {
+ if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
+ else request.headers += processHeaderValue(key, val)
}
+ }
}
-exports.TwirpServer = TwirpServer;
-/**
- * Write http error response
- * @param res
- * @param error
- */
-function writeError(res, error) {
- const twirpError = mustBeTwirpError(error);
- res.setHeader("Content-Type", "application/json");
- res.statusCode = errors_1.httpStatusFromErrorCode(twirpError.code);
- res.end(twirpError.toJSON());
-}
-exports.writeError = writeError;
-/**
- * Make sure that the error passed is a TwirpError
- * otherwise it will wrap it into an InternalError
- * @param err
- */
-function mustBeTwirpError(err) {
- if (err instanceof errors_1.TwirpError) {
- return err;
- }
- return new errors_1.InternalServerErrorWith(err);
+
+module.exports = Request
+
+
+/***/ }),
+
+/***/ 68031:
+/***/ ((module) => {
+
+module.exports = {
+ kClose: Symbol('close'),
+ kDestroy: Symbol('destroy'),
+ kDispatch: Symbol('dispatch'),
+ kUrl: Symbol('url'),
+ kWriting: Symbol('writing'),
+ kResuming: Symbol('resuming'),
+ kQueue: Symbol('queue'),
+ kConnect: Symbol('connect'),
+ kConnecting: Symbol('connecting'),
+ kHeadersList: Symbol('headers list'),
+ kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
+ kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
+ kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
+ kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
+ kKeepAlive: Symbol('keep alive'),
+ kHeadersTimeout: Symbol('headers timeout'),
+ kBodyTimeout: Symbol('body timeout'),
+ kServerName: Symbol('server name'),
+ kLocalAddress: Symbol('local address'),
+ kHost: Symbol('host'),
+ kNoRef: Symbol('no ref'),
+ kBodyUsed: Symbol('used'),
+ kRunning: Symbol('running'),
+ kBlocking: Symbol('blocking'),
+ kPending: Symbol('pending'),
+ kSize: Symbol('size'),
+ kBusy: Symbol('busy'),
+ kQueued: Symbol('queued'),
+ kFree: Symbol('free'),
+ kConnected: Symbol('connected'),
+ kClosed: Symbol('closed'),
+ kNeedDrain: Symbol('need drain'),
+ kReset: Symbol('reset'),
+ kDestroyed: Symbol.for('nodejs.stream.destroyed'),
+ kMaxHeadersSize: Symbol('max headers size'),
+ kRunningIdx: Symbol('running index'),
+ kPendingIdx: Symbol('pending index'),
+ kError: Symbol('error'),
+ kClients: Symbol('clients'),
+ kClient: Symbol('client'),
+ kParser: Symbol('parser'),
+ kOnDestroyed: Symbol('destroy callbacks'),
+ kPipelining: Symbol('pipelining'),
+ kSocket: Symbol('socket'),
+ kHostHeader: Symbol('host header'),
+ kConnector: Symbol('connector'),
+ kStrictContentLength: Symbol('strict content length'),
+ kMaxRedirections: Symbol('maxRedirections'),
+ kMaxRequests: Symbol('maxRequestsPerClient'),
+ kProxy: Symbol('proxy agent options'),
+ kCounter: Symbol('socket request counter'),
+ kInterceptors: Symbol('dispatch interceptors'),
+ kMaxResponseSize: Symbol('max response size'),
+ kHTTP2Session: Symbol('http2Session'),
+ kHTTP2SessionState: Symbol('http2Session state'),
+ kHTTP2BuildRequest: Symbol('http2 build request'),
+ kHTTP1BuildRequest: Symbol('http1 build request'),
+ kHTTP2CopyHeaders: Symbol('http2 copy headers'),
+ kHTTPConnVersion: Symbol('http connection version'),
+ kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
+ kConstruct: Symbol('constructable')
}
/***/ }),
-/***/ 61684:
+/***/ 89500:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const Client = __nccwpck_require__(45513)
-const Dispatcher = __nccwpck_require__(20303)
-const errors = __nccwpck_require__(53959)
-const Pool = __nccwpck_require__(44288)
-const BalancedPool = __nccwpck_require__(95377)
-const Agent = __nccwpck_require__(92121)
-const util = __nccwpck_require__(89500)
-const { InvalidArgumentError } = errors
-const api = __nccwpck_require__(82531)
-const buildConnector = __nccwpck_require__(91332)
-const MockClient = __nccwpck_require__(72361)
-const MockAgent = __nccwpck_require__(77017)
-const MockPool = __nccwpck_require__(36480)
-const mockErrors = __nccwpck_require__(12673)
-const ProxyAgent = __nccwpck_require__(79276)
-const RetryHandler = __nccwpck_require__(49569)
-const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(61481)
-const DecoratorHandler = __nccwpck_require__(41468)
-const RedirectHandler = __nccwpck_require__(8591)
-const createRedirectInterceptor = __nccwpck_require__(99299)
+const assert = __nccwpck_require__(42613)
+const { kDestroyed, kBodyUsed } = __nccwpck_require__(68031)
+const { IncomingMessage } = __nccwpck_require__(58611)
+const stream = __nccwpck_require__(2203)
+const net = __nccwpck_require__(69278)
+const { InvalidArgumentError } = __nccwpck_require__(53959)
+const { Blob } = __nccwpck_require__(20181)
+const nodeUtil = __nccwpck_require__(39023)
+const { stringify } = __nccwpck_require__(83480)
+const { headerNameLowerCasedRecord } = __nccwpck_require__(42371)
-let hasCrypto
-try {
- __nccwpck_require__(76982)
- hasCrypto = true
-} catch {
- hasCrypto = false
+const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
+
+function nop () {}
+
+function isStream (obj) {
+ return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
}
-Object.assign(Dispatcher.prototype, api)
+// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
+function isBlobLike (object) {
+ return (Blob && object instanceof Blob) || (
+ object &&
+ typeof object === 'object' &&
+ (typeof object.stream === 'function' ||
+ typeof object.arrayBuffer === 'function') &&
+ /^(Blob|File)$/.test(object[Symbol.toStringTag])
+ )
+}
-module.exports.Dispatcher = Dispatcher
-module.exports.Client = Client
-module.exports.Pool = Pool
-module.exports.BalancedPool = BalancedPool
-module.exports.Agent = Agent
-module.exports.ProxyAgent = ProxyAgent
-module.exports.RetryHandler = RetryHandler
+function buildURL (url, queryParams) {
+ if (url.includes('?') || url.includes('#')) {
+ throw new Error('Query params cannot be passed when url already contains "?" or "#".')
+ }
-module.exports.DecoratorHandler = DecoratorHandler
-module.exports.RedirectHandler = RedirectHandler
-module.exports.createRedirectInterceptor = createRedirectInterceptor
+ const stringified = stringify(queryParams)
-module.exports.buildConnector = buildConnector
-module.exports.errors = errors
+ if (stringified) {
+ url += '?' + stringified
+ }
-function makeDispatcher (fn) {
- return (url, opts, handler) => {
- if (typeof opts === 'function') {
- handler = opts
- opts = null
- }
+ return url
+}
- if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
- throw new InvalidArgumentError('invalid url')
- }
+function parseURL (url) {
+ if (typeof url === 'string') {
+ url = new URL(url)
- if (opts != null && typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+ if (!/^https?:/.test(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
}
- if (opts && opts.path != null) {
- if (typeof opts.path !== 'string') {
- throw new InvalidArgumentError('invalid opts.path')
- }
+ return url
+ }
- let path = opts.path
- if (!opts.path.startsWith('/')) {
- path = `/${path}`
- }
+ if (!url || typeof url !== 'object') {
+ throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
+ }
- url = new URL(util.parseOrigin(url).origin + path)
- } else {
- if (!opts) {
- opts = typeof url === 'object' ? url : {}
- }
+ if (!/^https?:/.test(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ }
- url = util.parseURL(url)
+ if (!(url instanceof URL)) {
+ if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {
+ throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
}
- const { agent, dispatcher = getGlobalDispatcher() } = opts
-
- if (agent) {
- throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
+ if (url.path != null && typeof url.path !== 'string') {
+ throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
}
- return fn.call(dispatcher, {
- ...opts,
- origin: url.origin,
- path: url.search ? `${url.pathname}${url.search}` : url.pathname,
- method: opts.method || (opts.body ? 'PUT' : 'GET')
- }, handler)
- }
-}
+ if (url.pathname != null && typeof url.pathname !== 'string') {
+ throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
+ }
-module.exports.setGlobalDispatcher = setGlobalDispatcher
-module.exports.getGlobalDispatcher = getGlobalDispatcher
+ if (url.hostname != null && typeof url.hostname !== 'string') {
+ throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
+ }
-if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {
- let fetchImpl = null
- module.exports.fetch = async function fetch (resource) {
- if (!fetchImpl) {
- fetchImpl = (__nccwpck_require__(11503).fetch)
+ if (url.origin != null && typeof url.origin !== 'string') {
+ throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
}
- try {
- return await fetchImpl(...arguments)
- } catch (err) {
- if (typeof err === 'object') {
- Error.captureStackTrace(err, this)
- }
+ const port = url.port != null
+ ? url.port
+ : (url.protocol === 'https:' ? 443 : 80)
+ let origin = url.origin != null
+ ? url.origin
+ : `${url.protocol}//${url.hostname}:${port}`
+ let path = url.path != null
+ ? url.path
+ : `${url.pathname || ''}${url.search || ''}`
- throw err
+ if (origin.endsWith('/')) {
+ origin = origin.substring(0, origin.length - 1)
+ }
+
+ if (path && !path.startsWith('/')) {
+ path = `/${path}`
}
+ // new URL(path, origin) is unsafe when `path` contains an absolute URL
+ // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
+ // If first parameter is a relative URL, second param is required, and will be used as the base URL.
+ // If first parameter is an absolute URL, a given second param will be ignored.
+ url = new URL(origin + path)
}
- module.exports.Headers = __nccwpck_require__(12801).Headers
- module.exports.Response = __nccwpck_require__(89928).Response
- module.exports.Request = __nccwpck_require__(2630).Request
- module.exports.FormData = __nccwpck_require__(47453).FormData
- module.exports.File = __nccwpck_require__(17005).File
- module.exports.FileReader = __nccwpck_require__(30052).FileReader
- const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(62896)
+ return url
+}
- module.exports.setGlobalOrigin = setGlobalOrigin
- module.exports.getGlobalOrigin = getGlobalOrigin
+function parseOrigin (url) {
+ url = parseURL(url)
- const { CacheStorage } = __nccwpck_require__(66446)
- const { kConstruct } = __nccwpck_require__(68652)
+ if (url.pathname !== '/' || url.search || url.hash) {
+ throw new InvalidArgumentError('invalid url')
+ }
- // Cache & CacheStorage are tightly coupled with fetch. Even if it may run
- // in an older version of Node, it doesn't have any use without fetch.
- module.exports.caches = new CacheStorage(kConstruct)
+ return url
}
-if (util.nodeMajor >= 16) {
- const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(64276)
-
- module.exports.deleteCookie = deleteCookie
- module.exports.getCookies = getCookies
- module.exports.getSetCookies = getSetCookies
- module.exports.setCookie = setCookie
-
- const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
+function getHostname (host) {
+ if (host[0] === '[') {
+ const idx = host.indexOf(']')
- module.exports.parseMIMEType = parseMIMEType
- module.exports.serializeAMimeType = serializeAMimeType
-}
+ assert(idx !== -1)
+ return host.substring(1, idx)
+ }
-if (util.nodeMajor >= 18 && hasCrypto) {
- const { WebSocket } = __nccwpck_require__(90551)
+ const idx = host.indexOf(':')
+ if (idx === -1) return host
- module.exports.WebSocket = WebSocket
+ return host.substring(0, idx)
}
-module.exports.request = makeDispatcher(api.request)
-module.exports.stream = makeDispatcher(api.stream)
-module.exports.pipeline = makeDispatcher(api.pipeline)
-module.exports.connect = makeDispatcher(api.connect)
-module.exports.upgrade = makeDispatcher(api.upgrade)
-
-module.exports.MockClient = MockClient
-module.exports.MockPool = MockPool
-module.exports.MockAgent = MockAgent
-module.exports.mockErrors = mockErrors
+// IP addresses are not valid server names per RFC6066
+// > Currently, the only server names supported are DNS hostnames
+function getServerName (host) {
+ if (!host) {
+ return null
+ }
+ assert.strictEqual(typeof host, 'string')
-/***/ }),
+ const servername = getHostname(host)
+ if (net.isIP(servername)) {
+ return ''
+ }
-/***/ 92121:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ return servername
+}
+function deepClone (obj) {
+ return JSON.parse(JSON.stringify(obj))
+}
+function isAsyncIterable (obj) {
+ return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
+}
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(68031)
-const DispatcherBase = __nccwpck_require__(52421)
-const Pool = __nccwpck_require__(44288)
-const Client = __nccwpck_require__(45513)
-const util = __nccwpck_require__(89500)
-const createRedirectInterceptor = __nccwpck_require__(99299)
-const { WeakRef, FinalizationRegistry } = __nccwpck_require__(90022)()
+function isIterable (obj) {
+ return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
+}
-const kOnConnect = Symbol('onConnect')
-const kOnDisconnect = Symbol('onDisconnect')
-const kOnConnectionError = Symbol('onConnectionError')
-const kMaxRedirections = Symbol('maxRedirections')
-const kOnDrain = Symbol('onDrain')
-const kFactory = Symbol('factory')
-const kFinalizer = Symbol('finalizer')
-const kOptions = Symbol('options')
+function bodyLength (body) {
+ if (body == null) {
+ return 0
+ } else if (isStream(body)) {
+ const state = body._readableState
+ return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
+ ? state.length
+ : null
+ } else if (isBlobLike(body)) {
+ return body.size != null ? body.size : null
+ } else if (isBuffer(body)) {
+ return body.byteLength
+ }
-function defaultFactory (origin, opts) {
- return opts && opts.connections === 1
- ? new Client(origin, opts)
- : new Pool(origin, opts)
+ return null
}
-class Agent extends DispatcherBase {
- constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
- super()
-
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
+function isDestroyed (stream) {
+ return !stream || !!(stream.destroyed || stream[kDestroyed])
+}
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
- }
+function isReadableAborted (stream) {
+ const state = stream && stream._readableState
+ return isDestroyed(stream) && state && !state.endEmitted
+}
- if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
+function destroy (stream, err) {
+ if (stream == null || !isStream(stream) || isDestroyed(stream)) {
+ return
+ }
- if (connect && typeof connect !== 'function') {
- connect = { ...connect }
+ if (typeof stream.destroy === 'function') {
+ if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
+ // See: https://github.com/nodejs/node/pull/38505/files
+ stream.socket = null
}
- this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)
- ? options.interceptors.Agent
- : [createRedirectInterceptor({ maxRedirections })]
+ stream.destroy(err)
+ } else if (err) {
+ process.nextTick((stream, err) => {
+ stream.emit('error', err)
+ }, stream, err)
+ }
- this[kOptions] = { ...util.deepClone(options), connect }
- this[kOptions].interceptors = options.interceptors
- ? { ...options.interceptors }
- : undefined
- this[kMaxRedirections] = maxRedirections
- this[kFactory] = factory
- this[kClients] = new Map()
- this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {
- const ref = this[kClients].get(key)
- if (ref !== undefined && ref.deref() === undefined) {
- this[kClients].delete(key)
- }
- })
+ if (stream.destroyed !== true) {
+ stream[kDestroyed] = true
+ }
+}
- const agent = this
+const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
+function parseKeepAliveTimeout (val) {
+ const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
+ return m ? parseInt(m[1], 10) * 1000 : null
+}
- this[kOnDrain] = (origin, targets) => {
- agent.emit('drain', origin, [agent, ...targets])
- }
+/**
+ * Retrieves a header name and returns its lowercase value.
+ * @param {string | Buffer} value Header name
+ * @returns {string}
+ */
+function headerNameToString (value) {
+ return headerNameLowerCasedRecord[value] || value.toLowerCase()
+}
- this[kOnConnect] = (origin, targets) => {
- agent.emit('connect', origin, [agent, ...targets])
- }
+function parseHeaders (headers, obj = {}) {
+ // For H2 support
+ if (!Array.isArray(headers)) return headers
- this[kOnDisconnect] = (origin, targets, err) => {
- agent.emit('disconnect', origin, [agent, ...targets], err)
- }
+ for (let i = 0; i < headers.length; i += 2) {
+ const key = headers[i].toString().toLowerCase()
+ let val = obj[key]
- this[kOnConnectionError] = (origin, targets, err) => {
- agent.emit('connectionError', origin, [agent, ...targets], err)
+ if (!val) {
+ if (Array.isArray(headers[i + 1])) {
+ obj[key] = headers[i + 1].map(x => x.toString('utf8'))
+ } else {
+ obj[key] = headers[i + 1].toString('utf8')
+ }
+ } else {
+ if (!Array.isArray(val)) {
+ val = [val]
+ obj[key] = val
+ }
+ val.push(headers[i + 1].toString('utf8'))
}
}
- get [kRunning] () {
- let ret = 0
- for (const ref of this[kClients].values()) {
- const client = ref.deref()
- /* istanbul ignore next: gc is undeterministic */
- if (client) {
- ret += client[kRunning]
- }
- }
- return ret
+ // See https://github.com/nodejs/node/pull/46528
+ if ('content-length' in obj && 'content-disposition' in obj) {
+ obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
}
- [kDispatch] (opts, handler) {
- let key
- if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
- key = String(opts.origin)
+ return obj
+}
+
+function parseRawHeaders (headers) {
+ const ret = []
+ let hasContentLength = false
+ let contentDispositionIdx = -1
+
+ for (let n = 0; n < headers.length; n += 2) {
+ const key = headers[n + 0].toString()
+ const val = headers[n + 1].toString('utf8')
+
+ if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
+ ret.push(key, val)
+ hasContentLength = true
+ } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
+ contentDispositionIdx = ret.push(key, val) - 1
} else {
- throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
+ ret.push(key, val)
}
+ }
- const ref = this[kClients].get(key)
+ // See https://github.com/nodejs/node/pull/46528
+ if (hasContentLength && contentDispositionIdx !== -1) {
+ ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
+ }
- let dispatcher = ref ? ref.deref() : null
- if (!dispatcher) {
- dispatcher = this[kFactory](opts.origin, this[kOptions])
- .on('drain', this[kOnDrain])
- .on('connect', this[kOnConnect])
- .on('disconnect', this[kOnDisconnect])
- .on('connectionError', this[kOnConnectionError])
+ return ret
+}
- this[kClients].set(key, new WeakRef(dispatcher))
- this[kFinalizer].register(dispatcher, key)
- }
+function isBuffer (buffer) {
+ // See, https://github.com/mcollina/undici/pull/319
+ return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
+}
- return dispatcher.dispatch(opts, handler)
+function validateHandler (handler, method, upgrade) {
+ if (!handler || typeof handler !== 'object') {
+ throw new InvalidArgumentError('handler must be an object')
}
- async [kClose] () {
- const closePromises = []
- for (const ref of this[kClients].values()) {
- const client = ref.deref()
- /* istanbul ignore else: gc is undeterministic */
- if (client) {
- closePromises.push(client.close())
- }
- }
+ if (typeof handler.onConnect !== 'function') {
+ throw new InvalidArgumentError('invalid onConnect method')
+ }
- await Promise.all(closePromises)
+ if (typeof handler.onError !== 'function') {
+ throw new InvalidArgumentError('invalid onError method')
}
- async [kDestroy] (err) {
- const destroyPromises = []
- for (const ref of this[kClients].values()) {
- const client = ref.deref()
- /* istanbul ignore else: gc is undeterministic */
- if (client) {
- destroyPromises.push(client.destroy(err))
- }
+ if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
+ throw new InvalidArgumentError('invalid onBodySent method')
+ }
+
+ if (upgrade || method === 'CONNECT') {
+ if (typeof handler.onUpgrade !== 'function') {
+ throw new InvalidArgumentError('invalid onUpgrade method')
+ }
+ } else {
+ if (typeof handler.onHeaders !== 'function') {
+ throw new InvalidArgumentError('invalid onHeaders method')
}
- await Promise.all(destroyPromises)
+ if (typeof handler.onData !== 'function') {
+ throw new InvalidArgumentError('invalid onData method')
+ }
+
+ if (typeof handler.onComplete !== 'function') {
+ throw new InvalidArgumentError('invalid onComplete method')
+ }
}
}
-module.exports = Agent
+// A body is disturbed if it has been read from and it cannot
+// be re-used without losing state or data.
+function isDisturbed (body) {
+ return !!(body && (
+ stream.isDisturbed
+ ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?
+ : body[kBodyUsed] ||
+ body.readableDidRead ||
+ (body._readableState && body._readableState.dataEmitted) ||
+ isReadableAborted(body)
+ ))
+}
+function isErrored (body) {
+ return !!(body && (
+ stream.isErrored
+ ? stream.isErrored(body)
+ : /state: 'errored'/.test(nodeUtil.inspect(body)
+ )))
+}
-/***/ }),
+function isReadable (body) {
+ return !!(body && (
+ stream.isReadable
+ ? stream.isReadable(body)
+ : /state: 'readable'/.test(nodeUtil.inspect(body)
+ )))
+}
-/***/ 52730:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+function getSocketInfo (socket) {
+ return {
+ localAddress: socket.localAddress,
+ localPort: socket.localPort,
+ remoteAddress: socket.remoteAddress,
+ remotePort: socket.remotePort,
+ remoteFamily: socket.remoteFamily,
+ timeout: socket.timeout,
+ bytesWritten: socket.bytesWritten,
+ bytesRead: socket.bytesRead
+ }
+}
-const { addAbortListener } = __nccwpck_require__(89500)
-const { RequestAbortedError } = __nccwpck_require__(53959)
+async function * convertIterableToBuffer (iterable) {
+ for await (const chunk of iterable) {
+ yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+ }
+}
-const kListener = Symbol('kListener')
-const kSignal = Symbol('kSignal')
+let ReadableStream
+function ReadableStreamFrom (iterable) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
-function abort (self) {
- if (self.abort) {
- self.abort()
- } else {
- self.onError(new RequestAbortedError())
+ if (ReadableStream.from) {
+ return ReadableStream.from(convertIterableToBuffer(iterable))
}
+
+ let iterator
+ return new ReadableStream(
+ {
+ async start () {
+ iterator = iterable[Symbol.asyncIterator]()
+ },
+ async pull (controller) {
+ const { done, value } = await iterator.next()
+ if (done) {
+ queueMicrotask(() => {
+ controller.close()
+ })
+ } else {
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
+ controller.enqueue(new Uint8Array(buf))
+ }
+ return controller.desiredSize > 0
+ },
+ async cancel (reason) {
+ await iterator.return()
+ }
+ },
+ 0
+ )
}
-function addSignal (self, signal) {
- self[kSignal] = null
- self[kListener] = null
+// The chunk should be a FormData instance and contains
+// all the required methods.
+function isFormDataLike (object) {
+ return (
+ object &&
+ typeof object === 'object' &&
+ typeof object.append === 'function' &&
+ typeof object.delete === 'function' &&
+ typeof object.get === 'function' &&
+ typeof object.getAll === 'function' &&
+ typeof object.has === 'function' &&
+ typeof object.set === 'function' &&
+ object[Symbol.toStringTag] === 'FormData'
+ )
+}
- if (!signal) {
- return
+function throwIfAborted (signal) {
+ if (!signal) { return }
+ if (typeof signal.throwIfAborted === 'function') {
+ signal.throwIfAborted()
+ } else {
+ if (signal.aborted) {
+ // DOMException not available < v17.0.0
+ const err = new Error('The operation was aborted')
+ err.name = 'AbortError'
+ throw err
+ }
}
+}
- if (signal.aborted) {
- abort(self)
- return
+function addAbortListener (signal, listener) {
+ if ('addEventListener' in signal) {
+ signal.addEventListener('abort', listener, { once: true })
+ return () => signal.removeEventListener('abort', listener)
}
+ signal.addListener('abort', listener)
+ return () => signal.removeListener('abort', listener)
+}
- self[kSignal] = signal
- self[kListener] = () => {
- abort(self)
+const hasToWellFormed = !!String.prototype.toWellFormed
+
+/**
+ * @param {string} val
+ */
+function toUSVString (val) {
+ if (hasToWellFormed) {
+ return `${val}`.toWellFormed()
+ } else if (nodeUtil.toUSVString) {
+ return nodeUtil.toUSVString(val)
}
- addAbortListener(self[kSignal], self[kListener])
+ return `${val}`
}
-function removeSignal (self) {
- if (!self[kSignal]) {
- return
- }
-
- if ('removeEventListener' in self[kSignal]) {
- self[kSignal].removeEventListener('abort', self[kListener])
- } else {
- self[kSignal].removeListener('abort', self[kListener])
- }
+// Parsed accordingly to RFC 9110
+// https://www.rfc-editor.org/rfc/rfc9110#field.content-range
+function parseRangeHeader (range) {
+ if (range == null || range === '') return { start: 0, end: null, size: null }
- self[kSignal] = null
- self[kListener] = null
+ const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
+ return m
+ ? {
+ start: parseInt(m[1]),
+ end: m[2] ? parseInt(m[2]) : null,
+ size: m[3] ? parseInt(m[3]) : null
+ }
+ : null
}
+const kEnumerableProperty = Object.create(null)
+kEnumerableProperty.enumerable = true
+
module.exports = {
- addSignal,
- removeSignal
+ kEnumerableProperty,
+ nop,
+ isDisturbed,
+ isErrored,
+ isReadable,
+ toUSVString,
+ isReadableAborted,
+ isBlobLike,
+ parseOrigin,
+ parseURL,
+ getServerName,
+ isStream,
+ isIterable,
+ isAsyncIterable,
+ isDestroyed,
+ headerNameToString,
+ parseRawHeaders,
+ parseHeaders,
+ parseKeepAliveTimeout,
+ destroy,
+ bodyLength,
+ deepClone,
+ ReadableStreamFrom,
+ isBuffer,
+ validateHandler,
+ getSocketInfo,
+ isFormDataLike,
+ buildURL,
+ throwIfAborted,
+ addAbortListener,
+ parseRangeHeader,
+ nodeMajor,
+ nodeMinor,
+ nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),
+ safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']
}
/***/ }),
-/***/ 73192:
+/***/ 52421:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { AsyncResource } = __nccwpck_require__(90290)
-const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { addSignal, removeSignal } = __nccwpck_require__(52730)
+const Dispatcher = __nccwpck_require__(20303)
+const {
+ ClientDestroyedError,
+ ClientClosedError,
+ InvalidArgumentError
+} = __nccwpck_require__(53959)
+const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(68031)
-class ConnectHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+const kDestroyed = Symbol('destroyed')
+const kClosed = Symbol('closed')
+const kOnDestroyed = Symbol('onDestroyed')
+const kOnClosed = Symbol('onClosed')
+const kInterceptedDispatch = Symbol('Intercepted Dispatch')
+
+class DispatcherBase extends Dispatcher {
+ constructor () {
+ super()
+
+ this[kDestroyed] = false
+ this[kOnDestroyed] = null
+ this[kClosed] = false
+ this[kOnClosed] = []
+ }
+
+ get destroyed () {
+ return this[kDestroyed]
+ }
+
+ get closed () {
+ return this[kClosed]
+ }
+
+ get interceptors () {
+ return this[kInterceptors]
+ }
+
+ set interceptors (newInterceptors) {
+ if (newInterceptors) {
+ for (let i = newInterceptors.length - 1; i >= 0; i--) {
+ const interceptor = this[kInterceptors][i]
+ if (typeof interceptor !== 'function') {
+ throw new InvalidArgumentError('interceptor must be an function')
+ }
+ }
+ }
+
+ this[kInterceptors] = newInterceptors
+ }
+
+ close (callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ this.close((err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
}
if (typeof callback !== 'function') {
throw new InvalidArgumentError('invalid callback')
}
- const { signal, opaque, responseHeaders } = opts
+ if (this[kDestroyed]) {
+ queueMicrotask(() => callback(new ClientDestroyedError(), null))
+ return
+ }
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ if (this[kClosed]) {
+ if (this[kOnClosed]) {
+ this[kOnClosed].push(callback)
+ } else {
+ queueMicrotask(() => callback(null, null))
+ }
+ return
}
- super('UNDICI_CONNECT')
+ this[kClosed] = true
+ this[kOnClosed].push(callback)
- this.opaque = opaque || null
- this.responseHeaders = responseHeaders || null
- this.callback = callback
- this.abort = null
+ const onClosed = () => {
+ const callbacks = this[kOnClosed]
+ this[kOnClosed] = null
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null)
+ }
+ }
- addSignal(this, signal)
+ // Should not error.
+ this[kClose]()
+ .then(() => this.destroy())
+ .then(() => {
+ queueMicrotask(onClosed)
+ })
}
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
+ destroy (err, callback) {
+ if (typeof err === 'function') {
+ callback = err
+ err = null
}
- this.abort = abort
- this.context = context
- }
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ this.destroy(err, (err, data) => {
+ return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
+ })
+ })
+ }
- onHeaders () {
- throw new SocketError('bad connect', null)
- }
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
- onUpgrade (statusCode, rawHeaders, socket) {
- const { callback, opaque, context } = this
+ if (this[kDestroyed]) {
+ if (this[kOnDestroyed]) {
+ this[kOnDestroyed].push(callback)
+ } else {
+ queueMicrotask(() => callback(null, null))
+ }
+ return
+ }
- removeSignal(this)
+ if (!err) {
+ err = new ClientDestroyedError()
+ }
- this.callback = null
+ this[kDestroyed] = true
+ this[kOnDestroyed] = this[kOnDestroyed] || []
+ this[kOnDestroyed].push(callback)
- let headers = rawHeaders
- // Indicates is an HTTP2Session
- if (headers != null) {
- headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ const onDestroyed = () => {
+ const callbacks = this[kOnDestroyed]
+ this[kOnDestroyed] = null
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null)
+ }
}
- this.runInAsyncScope(callback, null, null, {
- statusCode,
- headers,
- socket,
- opaque,
- context
+ // Should not error.
+ this[kDestroy](err).then(() => {
+ queueMicrotask(onDestroyed)
})
}
- onError (err) {
- const { callback, opaque } = this
-
- removeSignal(this)
-
- if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
+ [kInterceptedDispatch] (opts, handler) {
+ if (!this[kInterceptors] || this[kInterceptors].length === 0) {
+ this[kInterceptedDispatch] = this[kDispatch]
+ return this[kDispatch](opts, handler)
}
- }
-}
-
-function connect (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- connect.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
- try {
- const connectHandler = new ConnectHandler(opts, callback)
- this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
+ let dispatch = this[kDispatch].bind(this)
+ for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
+ dispatch = this[kInterceptors][i](dispatch)
}
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
+ this[kInterceptedDispatch] = dispatch
+ return dispatch(opts, handler)
}
-}
-module.exports = connect
+ dispatch (opts, handler) {
+ if (!handler || typeof handler !== 'object') {
+ throw new InvalidArgumentError('handler must be an object')
+ }
+ try {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('opts must be an object.')
+ }
-/***/ }),
+ if (this[kDestroyed] || this[kOnDestroyed]) {
+ throw new ClientDestroyedError()
+ }
-/***/ 62466:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (this[kClosed]) {
+ throw new ClientClosedError()
+ }
+ return this[kInterceptedDispatch](opts, handler)
+ } catch (err) {
+ if (typeof handler.onError !== 'function') {
+ throw new InvalidArgumentError('invalid onError method')
+ }
+ handler.onError(err)
-const {
- Readable,
- Duplex,
- PassThrough
-} = __nccwpck_require__(2203)
-const {
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError
-} = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { AsyncResource } = __nccwpck_require__(90290)
-const { addSignal, removeSignal } = __nccwpck_require__(52730)
-const assert = __nccwpck_require__(42613)
+ return false
+ }
+ }
+}
-const kResume = Symbol('resume')
+module.exports = DispatcherBase
-class PipelineRequest extends Readable {
- constructor () {
- super({ autoDestroy: true })
- this[kResume] = null
- }
+/***/ }),
- _read () {
- const { [kResume]: resume } = this
+/***/ 20303:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (resume) {
- this[kResume] = null
- resume()
- }
- }
- _destroy (err, callback) {
- this._read()
- callback(err)
- }
-}
+const EventEmitter = __nccwpck_require__(24434)
-class PipelineResponse extends Readable {
- constructor (resume) {
- super({ autoDestroy: true })
- this[kResume] = resume
+class Dispatcher extends EventEmitter {
+ dispatch () {
+ throw new Error('not implemented')
}
- _read () {
- this[kResume]()
+ close () {
+ throw new Error('not implemented')
}
- _destroy (err, callback) {
- if (!err && !this._readableState.endEmitted) {
- err = new RequestAbortedError()
- }
-
- callback(err)
+ destroy () {
+ throw new Error('not implemented')
}
}
-class PipelineHandler extends AsyncResource {
- constructor (opts, handler) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+module.exports = Dispatcher
- if (typeof handler !== 'function') {
- throw new InvalidArgumentError('invalid handler')
- }
- const { signal, method, opaque, onInfo, responseHeaders } = opts
+/***/ }),
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+/***/ 37791:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
- super('UNDICI_PIPELINE')
+const Busboy = __nccwpck_require__(75249)
+const util = __nccwpck_require__(89500)
+const {
+ ReadableStreamFrom,
+ isBlobLike,
+ isReadableStreamLike,
+ readableStreamClose,
+ createDeferredPromise,
+ fullyReadBody
+} = __nccwpck_require__(72847)
+const { FormData } = __nccwpck_require__(47453)
+const { kState } = __nccwpck_require__(63730)
+const { webidl } = __nccwpck_require__(94354)
+const { DOMException, structuredClone } = __nccwpck_require__(21234)
+const { Blob, File: NativeFile } = __nccwpck_require__(20181)
+const { kBodyUsed } = __nccwpck_require__(68031)
+const assert = __nccwpck_require__(42613)
+const { isErrored } = __nccwpck_require__(89500)
+const { isUint8Array, isArrayBuffer } = __nccwpck_require__(98253)
+const { File: UndiciFile } = __nccwpck_require__(17005)
+const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
- this.opaque = opaque || null
- this.responseHeaders = responseHeaders || null
- this.handler = handler
- this.abort = null
- this.context = null
- this.onInfo = onInfo || null
+let ReadableStream = globalThis.ReadableStream
- this.req = new PipelineRequest().on('error', util.nop)
+/** @type {globalThis['File']} */
+const File = NativeFile ?? UndiciFile
+const textEncoder = new TextEncoder()
+const textDecoder = new TextDecoder()
- this.ret = new Duplex({
- readableObjectMode: opts.objectMode,
- autoDestroy: true,
- read: () => {
- const { body } = this
+// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
+function extractBody (object, keepalive = false) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
- if (body && body.resume) {
- body.resume()
- }
- },
- write: (chunk, encoding, callback) => {
- const { req } = this
+ // 1. Let stream be null.
+ let stream = null
- if (req.push(chunk, encoding) || req._readableState.destroyed) {
- callback()
- } else {
- req[kResume] = callback
- }
+ // 2. If object is a ReadableStream object, then set stream to object.
+ if (object instanceof ReadableStream) {
+ stream = object
+ } else if (isBlobLike(object)) {
+ // 3. Otherwise, if object is a Blob object, set stream to the
+ // result of running object’s get stream.
+ stream = object.stream()
+ } else {
+ // 4. Otherwise, set stream to a new ReadableStream object, and set
+ // up stream.
+ stream = new ReadableStream({
+ async pull (controller) {
+ controller.enqueue(
+ typeof source === 'string' ? textEncoder.encode(source) : source
+ )
+ queueMicrotask(() => readableStreamClose(controller))
},
- destroy: (err, callback) => {
- const { body, req, res, ret, abort } = this
+ start () {},
+ type: undefined
+ })
+ }
- if (!err && !ret._readableState.endEmitted) {
- err = new RequestAbortedError()
- }
+ // 5. Assert: stream is a ReadableStream object.
+ assert(isReadableStreamLike(stream))
- if (abort && err) {
- abort()
- }
+ // 6. Let action be null.
+ let action = null
- util.destroy(body, err)
- util.destroy(req, err)
- util.destroy(res, err)
+ // 7. Let source be null.
+ let source = null
- removeSignal(this)
+ // 8. Let length be null.
+ let length = null
- callback(err)
- }
- }).on('prefinish', () => {
- const { req } = this
+ // 9. Let type be null.
+ let type = null
- // Node < 15 does not call _final in same tick.
- req.push(null)
- })
+ // 10. Switch on object:
+ if (typeof object === 'string') {
+ // Set source to the UTF-8 encoding of object.
+ // Note: setting source to a Uint8Array here breaks some mocking assumptions.
+ source = object
- this.res = null
+ // Set type to `text/plain;charset=UTF-8`.
+ type = 'text/plain;charset=UTF-8'
+ } else if (object instanceof URLSearchParams) {
+ // URLSearchParams
- addSignal(this, signal)
- }
+ // spec says to run application/x-www-form-urlencoded on body.list
+ // this is implemented in Node.js as apart of an URLSearchParams instance toString method
+ // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
+ // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
- onConnect (abort, context) {
- const { ret, res } = this
+ // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
+ source = object.toString()
- assert(!res, 'pipeline cannot be retried')
+ // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
+ type = 'application/x-www-form-urlencoded;charset=UTF-8'
+ } else if (isArrayBuffer(object)) {
+ // BufferSource/ArrayBuffer
- if (ret.destroyed) {
- throw new RequestAbortedError()
- }
+ // Set source to a copy of the bytes held by object.
+ source = new Uint8Array(object.slice())
+ } else if (ArrayBuffer.isView(object)) {
+ // BufferSource/ArrayBufferView
- this.abort = abort
- this.context = context
- }
+ // Set source to a copy of the bytes held by object.
+ source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
+ } else if (util.isFormDataLike(object)) {
+ const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`
+ const prefix = `--${boundary}\r\nContent-Disposition: form-data`
- onHeaders (statusCode, rawHeaders, resume) {
- const { opaque, handler, context } = this
+ /*! formdata-polyfill. MIT License. Jimmy Wärting */
+ const escape = (str) =>
+ str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
+ const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
- if (statusCode < 200) {
- if (this.onInfo) {
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- this.onInfo({ statusCode, headers })
- }
- return
- }
+ // Set action to this step: run the multipart/form-data
+ // encoding algorithm, with object’s entry list and UTF-8.
+ // - This ensures that the body is immutable and can't be changed afterwords
+ // - That the content-length is calculated in advance.
+ // - And that all parts are pre-encoded and ready to be sent.
- this.res = new PipelineResponse(resume)
+ const blobParts = []
+ const rn = new Uint8Array([13, 10]) // '\r\n'
+ length = 0
+ let hasUnknownSizeValue = false
- let body
- try {
- this.handler = null
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- body = this.runInAsyncScope(handler, null, {
- statusCode,
- headers,
- opaque,
- body: this.res,
- context
- })
- } catch (err) {
- this.res.on('error', util.nop)
- throw err
+ for (const [name, value] of object) {
+ if (typeof value === 'string') {
+ const chunk = textEncoder.encode(prefix +
+ `; name="${escape(normalizeLinefeeds(name))}"` +
+ `\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
+ blobParts.push(chunk)
+ length += chunk.byteLength
+ } else {
+ const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
+ (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
+ `Content-Type: ${
+ value.type || 'application/octet-stream'
+ }\r\n\r\n`)
+ blobParts.push(chunk, value, rn)
+ if (typeof value.size === 'number') {
+ length += chunk.byteLength + value.size + rn.byteLength
+ } else {
+ hasUnknownSizeValue = true
+ }
+ }
}
- if (!body || typeof body.on !== 'function') {
- throw new InvalidReturnValueError('expected Readable')
+ const chunk = textEncoder.encode(`--${boundary}--`)
+ blobParts.push(chunk)
+ length += chunk.byteLength
+ if (hasUnknownSizeValue) {
+ length = null
}
- body
- .on('data', (chunk) => {
- const { ret, body } = this
+ // Set source to object.
+ source = object
- if (!ret.push(chunk) && body.pause) {
- body.pause()
+ action = async function * () {
+ for (const part of blobParts) {
+ if (part.stream) {
+ yield * part.stream()
+ } else {
+ yield part
}
- })
- .on('error', (err) => {
- const { ret } = this
+ }
+ }
- util.destroy(ret, err)
- })
- .on('end', () => {
- const { ret } = this
+ // Set type to `multipart/form-data; boundary=`,
+ // followed by the multipart/form-data boundary string generated
+ // by the multipart/form-data encoding algorithm.
+ type = 'multipart/form-data; boundary=' + boundary
+ } else if (isBlobLike(object)) {
+ // Blob
- ret.push(null)
- })
- .on('close', () => {
- const { ret } = this
+ // Set source to object.
+ source = object
- if (!ret._readableState.ended) {
- util.destroy(ret, new RequestAbortedError())
- }
- })
+ // Set length to object’s size.
+ length = object.size
- this.body = body
- }
+ // If object’s type attribute is not the empty byte sequence, set
+ // type to its value.
+ if (object.type) {
+ type = object.type
+ }
+ } else if (typeof object[Symbol.asyncIterator] === 'function') {
+ // If keepalive is true, then throw a TypeError.
+ if (keepalive) {
+ throw new TypeError('keepalive')
+ }
- onData (chunk) {
- const { res } = this
- return res.push(chunk)
- }
+ // If object is disturbed or locked, then throw a TypeError.
+ if (util.isDisturbed(object) || object.locked) {
+ throw new TypeError(
+ 'Response body object should not be disturbed or locked'
+ )
+ }
- onComplete (trailers) {
- const { res } = this
- res.push(null)
+ stream =
+ object instanceof ReadableStream ? object : ReadableStreamFrom(object)
}
- onError (err) {
- const { ret } = this
- this.handler = null
- util.destroy(ret, err)
+ // 11. If source is a byte sequence, then set action to a
+ // step that returns source and length to source’s length.
+ if (typeof source === 'string' || util.isBuffer(source)) {
+ length = Buffer.byteLength(source)
}
-}
-function pipeline (opts, handler) {
- try {
- const pipelineHandler = new PipelineHandler(opts, handler)
- this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
- return pipelineHandler.ret
- } catch (err) {
- return new PassThrough().destroy(err)
+ // 12. If action is non-null, then run these steps in in parallel:
+ if (action != null) {
+ // Run action.
+ let iterator
+ stream = new ReadableStream({
+ async start () {
+ iterator = action(object)[Symbol.asyncIterator]()
+ },
+ async pull (controller) {
+ const { value, done } = await iterator.next()
+ if (done) {
+ // When running action is done, close stream.
+ queueMicrotask(() => {
+ controller.close()
+ })
+ } else {
+ // Whenever one or more bytes are available and stream is not errored,
+ // enqueue a Uint8Array wrapping an ArrayBuffer containing the available
+ // bytes into stream.
+ if (!isErrored(stream)) {
+ controller.enqueue(new Uint8Array(value))
+ }
+ }
+ return controller.desiredSize > 0
+ },
+ async cancel (reason) {
+ await iterator.return()
+ },
+ type: undefined
+ })
}
-}
-
-module.exports = pipeline
+ // 13. Let body be a body whose stream is stream, source is source,
+ // and length is length.
+ const body = { stream, source, length }
-/***/ }),
+ // 14. Return (body, type).
+ return [body, type]
+}
-/***/ 50887:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
+function safelyExtractBody (object, keepalive = false) {
+ if (!ReadableStream) {
+ // istanbul ignore next
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
+ // To safely extract a body and a `Content-Type` value from
+ // a byte sequence or BodyInit object object, run these steps:
+ // 1. If object is a ReadableStream object, then:
+ if (object instanceof ReadableStream) {
+ // Assert: object is neither disturbed nor locked.
+ // istanbul ignore next
+ assert(!util.isDisturbed(object), 'The body has already been consumed.')
+ // istanbul ignore next
+ assert(!object.locked, 'The stream is locked.')
+ }
-const Readable = __nccwpck_require__(38947)
-const {
- InvalidArgumentError,
- RequestAbortedError
-} = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { getResolveErrorBodyCallback } = __nccwpck_require__(80363)
-const { AsyncResource } = __nccwpck_require__(90290)
-const { addSignal, removeSignal } = __nccwpck_require__(52730)
+ // 2. Return the results of extracting object.
+ return extractBody(object, keepalive)
+}
-class RequestHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+function cloneBody (body) {
+ // To clone a body body, run these steps:
- const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
+ // https://fetch.spec.whatwg.org/#concept-body-clone
- try {
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ // 1. Let « out1, out2 » be the result of teeing body’s stream.
+ const [out1, out2] = body.stream.tee()
+ const out2Clone = structuredClone(out2, { transfer: [out2] })
+ // This, for whatever reasons, unrefs out2Clone which allows
+ // the process to exit by itself.
+ const [, finalClone] = out2Clone.tee()
- if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
- throw new InvalidArgumentError('invalid highWaterMark')
- }
+ // 2. Set body’s stream to out1.
+ body.stream = out1
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+ // 3. Return a body whose stream is out2 and other members are copied from body.
+ return {
+ stream: finalClone,
+ length: body.length,
+ source: body.source
+ }
+}
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
+async function * consumeBody (body) {
+ if (body) {
+ if (isUint8Array(body)) {
+ yield body
+ } else {
+ const stream = body.stream
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
+ if (util.isDisturbed(stream)) {
+ throw new TypeError('The body has already been consumed.')
}
- super('UNDICI_REQUEST')
- } catch (err) {
- if (util.isStream(body)) {
- util.destroy(body.on('error', util.nop), err)
+ if (stream.locked) {
+ throw new TypeError('The stream is locked.')
}
- throw err
- }
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.callback = callback
- this.res = null
- this.abort = null
- this.body = body
- this.trailers = {}
- this.context = null
- this.onInfo = onInfo || null
- this.throwOnError = throwOnError
- this.highWaterMark = highWaterMark
+ // Compat.
+ stream[kBodyUsed] = true
- if (util.isStream(body)) {
- body.on('error', (err) => {
- this.onError(err)
- })
+ yield * stream
}
-
- addSignal(this, signal)
}
+}
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
- }
-
- this.abort = abort
- this.context = context
+function throwIfAborted (state) {
+ if (state.aborted) {
+ throw new DOMException('The operation was aborted.', 'AbortError')
}
+}
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
+function bodyMixinMethods (instance) {
+ const methods = {
+ blob () {
+ // The blob() method steps are to return the result of
+ // running consume body with this and the following step
+ // given a byte sequence bytes: return a Blob whose
+ // contents are bytes and whose type attribute is this’s
+ // MIME type.
+ return specConsumeBody(this, (bytes) => {
+ let mimeType = bodyMimeType(this)
- const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ if (mimeType === 'failure') {
+ mimeType = ''
+ } else if (mimeType) {
+ mimeType = serializeAMimeType(mimeType)
+ }
- if (statusCode < 200) {
- if (this.onInfo) {
- this.onInfo({ statusCode, headers })
- }
- return
- }
+ // Return a Blob whose contents are bytes and type attribute
+ // is mimeType.
+ return new Blob([bytes], { type: mimeType })
+ }, instance)
+ },
- const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
- const contentType = parsedHeaders['content-type']
- const body = new Readable({ resume, abort, contentType, highWaterMark })
+ arrayBuffer () {
+ // The arrayBuffer() method steps are to return the result
+ // of running consume body with this and the following step
+ // given a byte sequence bytes: return a new ArrayBuffer
+ // whose contents are bytes.
+ return specConsumeBody(this, (bytes) => {
+ return new Uint8Array(bytes).buffer
+ }, instance)
+ },
- this.callback = null
- this.res = body
- if (callback !== null) {
- if (this.throwOnError && statusCode >= 400) {
- this.runInAsyncScope(getResolveErrorBodyCallback, null,
- { callback, body, contentType, statusCode, statusMessage, headers }
- )
- } else {
- this.runInAsyncScope(callback, null, null, {
- statusCode,
- headers,
- trailers: this.trailers,
- opaque,
- body,
- context
- })
- }
- }
- }
+ text () {
+ // The text() method steps are to return the result of running
+ // consume body with this and UTF-8 decode.
+ return specConsumeBody(this, utf8DecodeBytes, instance)
+ },
- onData (chunk) {
- const { res } = this
- return res.push(chunk)
- }
+ json () {
+ // The json() method steps are to return the result of running
+ // consume body with this and parse JSON from bytes.
+ return specConsumeBody(this, parseJSONFromBytes, instance)
+ },
- onComplete (trailers) {
- const { res } = this
+ async formData () {
+ webidl.brandCheck(this, instance)
- removeSignal(this)
+ throwIfAborted(this[kState])
- util.parseHeaders(trailers, this.trailers)
+ const contentType = this.headers.get('Content-Type')
- res.push(null)
- }
+ // If mimeType’s essence is "multipart/form-data", then:
+ if (/multipart\/form-data/.test(contentType)) {
+ const headers = {}
+ for (const [key, value] of this.headers) headers[key.toLowerCase()] = value
- onError (err) {
- const { res, callback, body, opaque } = this
+ const responseFormData = new FormData()
- removeSignal(this)
+ let busboy
- if (callback) {
- // TODO: Does this need queueMicrotask?
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
+ try {
+ busboy = new Busboy({
+ headers,
+ preservePath: true
+ })
+ } catch (err) {
+ throw new DOMException(`${err}`, 'AbortError')
+ }
- if (res) {
- this.res = null
- // Ensure all queued handlers are invoked before destroying res.
- queueMicrotask(() => {
- util.destroy(res, err)
- })
- }
+ busboy.on('field', (name, value) => {
+ responseFormData.append(name, value)
+ })
+ busboy.on('file', (name, value, filename, encoding, mimeType) => {
+ const chunks = []
- if (body) {
- this.body = null
- util.destroy(body, err)
- }
- }
-}
+ if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {
+ let base64chunk = ''
-function request (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- request.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
+ value.on('data', (chunk) => {
+ base64chunk += chunk.toString().replace(/[\r\n]/gm, '')
- try {
- this.dispatch(opts, new RequestHandler(opts, callback))
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
-}
+ const end = base64chunk.length - base64chunk.length % 4
+ chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))
-module.exports = request
-module.exports.RequestHandler = RequestHandler
+ base64chunk = base64chunk.slice(end)
+ })
+ value.on('end', () => {
+ chunks.push(Buffer.from(base64chunk, 'base64'))
+ responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
+ })
+ } else {
+ value.on('data', (chunk) => {
+ chunks.push(chunk)
+ })
+ value.on('end', () => {
+ responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
+ })
+ }
+ })
+ const busboyResolve = new Promise((resolve, reject) => {
+ busboy.on('finish', resolve)
+ busboy.on('error', (err) => reject(new TypeError(err)))
+ })
-/***/ }),
+ if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)
+ busboy.end()
+ await busboyResolve
-/***/ 44388:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ return responseFormData
+ } else if (/application\/x-www-form-urlencoded/.test(contentType)) {
+ // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then:
+ // 1. Let entries be the result of parsing bytes.
+ let entries
+ try {
+ let text = ''
+ // application/x-www-form-urlencoded parser will keep the BOM.
+ // https://url.spec.whatwg.org/#concept-urlencoded-parser
+ // Note that streaming decoder is stateful and cannot be reused
+ const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
+ for await (const chunk of consumeBody(this[kState].body)) {
+ if (!isUint8Array(chunk)) {
+ throw new TypeError('Expected Uint8Array chunk')
+ }
+ text += streamingDecoder.decode(chunk, { stream: true })
+ }
+ text += streamingDecoder.decode()
+ entries = new URLSearchParams(text)
+ } catch (err) {
+ // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.
+ // 2. If entries is failure, then throw a TypeError.
+ throw Object.assign(new TypeError(), { cause: err })
+ }
-const { finished, PassThrough } = __nccwpck_require__(2203)
-const {
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError
-} = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { getResolveErrorBodyCallback } = __nccwpck_require__(80363)
-const { AsyncResource } = __nccwpck_require__(90290)
-const { addSignal, removeSignal } = __nccwpck_require__(52730)
+ // 3. Return a new FormData object whose entries are entries.
+ const formData = new FormData()
+ for (const [name, value] of entries) {
+ formData.append(name, value)
+ }
+ return formData
+ } else {
+ // Wait a tick before checking if the request has been aborted.
+ // Otherwise, a TypeError can be thrown when an AbortError should.
+ await Promise.resolve()
-class StreamHandler extends AsyncResource {
- constructor (opts, factory, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+ throwIfAborted(this[kState])
+
+ // Otherwise, throw a TypeError.
+ throw webidl.errors.exception({
+ header: `${instance.name}.formData`,
+ message: 'Could not parse content as FormData.'
+ })
+ }
}
+ }
- const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
+ return methods
+}
- try {
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+function mixinBody (prototype) {
+ Object.assign(prototype.prototype, bodyMixinMethods(prototype))
+}
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('invalid factory')
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
+ * @param {Response|Request} object
+ * @param {(value: unknown) => unknown} convertBytesToJSValue
+ * @param {Response|Request} instance
+ */
+async function specConsumeBody (object, convertBytesToJSValue, instance) {
+ webidl.brandCheck(object, instance)
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+ throwIfAborted(object[kState])
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
+ // 1. If object is unusable, then return a promise rejected
+ // with a TypeError.
+ if (bodyUnusable(object[kState].body)) {
+ throw new TypeError('Body is unusable')
+ }
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
+ // 2. Let promise be a new promise.
+ const promise = createDeferredPromise()
- super('UNDICI_STREAM')
- } catch (err) {
- if (util.isStream(body)) {
- util.destroy(body.on('error', util.nop), err)
- }
- throw err
+ // 3. Let errorSteps given error be to reject promise with error.
+ const errorSteps = (error) => promise.reject(error)
+
+ // 4. Let successSteps given a byte sequence data be to resolve
+ // promise with the result of running convertBytesToJSValue
+ // with data. If that threw an exception, then run errorSteps
+ // with that exception.
+ const successSteps = (data) => {
+ try {
+ promise.resolve(convertBytesToJSValue(data))
+ } catch (e) {
+ errorSteps(e)
}
+ }
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.factory = factory
- this.callback = callback
- this.res = null
- this.abort = null
- this.context = null
- this.trailers = null
- this.body = body
- this.onInfo = onInfo || null
- this.throwOnError = throwOnError || false
+ // 5. If object’s body is null, then run successSteps with an
+ // empty byte sequence.
+ if (object[kState].body == null) {
+ successSteps(new Uint8Array())
+ return promise.promise
+ }
- if (util.isStream(body)) {
- body.on('error', (err) => {
- this.onError(err)
- })
- }
+ // 6. Otherwise, fully read object’s body given successSteps,
+ // errorSteps, and object’s relevant global object.
+ await fullyReadBody(object[kState].body, successSteps, errorSteps)
- addSignal(this, signal)
+ // 7. Return promise.
+ return promise.promise
+}
+
+// https://fetch.spec.whatwg.org/#body-unusable
+function bodyUnusable (body) {
+ // An object including the Body interface mixin is
+ // said to be unusable if its body is non-null and
+ // its body’s stream is disturbed or locked.
+ return body != null && (body.stream.locked || util.isDisturbed(body.stream))
+}
+
+/**
+ * @see https://encoding.spec.whatwg.org/#utf-8-decode
+ * @param {Buffer} buffer
+ */
+function utf8DecodeBytes (buffer) {
+ if (buffer.length === 0) {
+ return ''
}
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
- }
+ // 1. Let buffer be the result of peeking three bytes from
+ // ioQueue, converted to a byte sequence.
- this.abort = abort
- this.context = context
+ // 2. If buffer is 0xEF 0xBB 0xBF, then read three
+ // bytes from ioQueue. (Do nothing with those bytes.)
+ if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
+ buffer = buffer.subarray(3)
}
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const { factory, opaque, context, callback, responseHeaders } = this
+ // 3. Process a queue with an instance of UTF-8’s
+ // decoder, ioQueue, output, and "replacement".
+ const output = textDecoder.decode(buffer)
- const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ // 4. Return output.
+ return output
+}
- if (statusCode < 200) {
- if (this.onInfo) {
- this.onInfo({ statusCode, headers })
- }
- return
- }
+/**
+ * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
+ * @param {Uint8Array} bytes
+ */
+function parseJSONFromBytes (bytes) {
+ return JSON.parse(utf8DecodeBytes(bytes))
+}
- this.factory = null
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
+ * @param {import('./response').Response|import('./request').Request} object
+ */
+function bodyMimeType (object) {
+ const { headersList } = object[kState]
+ const contentType = headersList.get('content-type')
- let res
+ if (contentType === null) {
+ return 'failure'
+ }
- if (this.throwOnError && statusCode >= 400) {
- const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
- const contentType = parsedHeaders['content-type']
- res = new PassThrough()
+ return parseMIMEType(contentType)
+}
- this.callback = null
- this.runInAsyncScope(getResolveErrorBodyCallback, null,
- { callback, body: res, contentType, statusCode, statusMessage, headers }
- )
- } else {
- if (factory === null) {
- return
- }
+module.exports = {
+ extractBody,
+ safelyExtractBody,
+ cloneBody,
+ mixinBody
+}
- res = this.runInAsyncScope(factory, null, {
- statusCode,
- headers,
- opaque,
- context
- })
- if (
- !res ||
- typeof res.write !== 'function' ||
- typeof res.end !== 'function' ||
- typeof res.on !== 'function'
- ) {
- throw new InvalidReturnValueError('expected Writable')
- }
+/***/ }),
- // TODO: Avoid finished. It registers an unnecessary amount of listeners.
- finished(res, { readable: false }, (err) => {
- const { callback, res, opaque, trailers, abort } = this
+/***/ 21234:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- this.res = null
- if (err || !res.readable) {
- util.destroy(res, err)
- }
- this.callback = null
- this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
- if (err) {
- abort()
- }
- })
- }
+const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(28167)
- res.on('drain', resume)
+const corsSafeListedMethods = ['GET', 'HEAD', 'POST']
+const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
- this.res = res
+const nullBodyStatus = [101, 204, 205, 304]
- const needDrain = res.writableNeedDrain !== undefined
- ? res.writableNeedDrain
- : res._writableState && res._writableState.needDrain
+const redirectStatus = [301, 302, 303, 307, 308]
+const redirectStatusSet = new Set(redirectStatus)
+
+// https://fetch.spec.whatwg.org/#block-bad-port
+const badPorts = [
+ '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',
+ '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',
+ '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',
+ '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',
+ '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',
+ '10080'
+]
+
+const badPortsSet = new Set(badPorts)
+
+// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
+const referrerPolicy = [
+ '',
+ 'no-referrer',
+ 'no-referrer-when-downgrade',
+ 'same-origin',
+ 'origin',
+ 'strict-origin',
+ 'origin-when-cross-origin',
+ 'strict-origin-when-cross-origin',
+ 'unsafe-url'
+]
+const referrerPolicySet = new Set(referrerPolicy)
- return needDrain !== true
- }
+const requestRedirect = ['follow', 'manual', 'error']
- onData (chunk) {
- const { res } = this
+const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
+const safeMethodsSet = new Set(safeMethods)
- return res ? res.write(chunk) : true
- }
+const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']
- onComplete (trailers) {
- const { res } = this
+const requestCredentials = ['omit', 'same-origin', 'include']
- removeSignal(this)
+const requestCache = [
+ 'default',
+ 'no-store',
+ 'reload',
+ 'no-cache',
+ 'force-cache',
+ 'only-if-cached'
+]
- if (!res) {
- return
- }
+// https://fetch.spec.whatwg.org/#request-body-header-name
+const requestBodyHeader = [
+ 'content-encoding',
+ 'content-language',
+ 'content-location',
+ 'content-type',
+ // See https://github.com/nodejs/undici/issues/2021
+ // 'Content-Length' is a forbidden header name, which is typically
+ // removed in the Headers implementation. However, undici doesn't
+ // filter out headers, so we add it here.
+ 'content-length'
+]
- this.trailers = util.parseHeaders(trailers)
+// https://fetch.spec.whatwg.org/#enumdef-requestduplex
+const requestDuplex = [
+ 'half'
+]
- res.end()
- }
+// http://fetch.spec.whatwg.org/#forbidden-method
+const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']
+const forbiddenMethodsSet = new Set(forbiddenMethods)
- onError (err) {
- const { res, callback, opaque, body } = this
+const subresource = [
+ 'audio',
+ 'audioworklet',
+ 'font',
+ 'image',
+ 'manifest',
+ 'paintworklet',
+ 'script',
+ 'style',
+ 'track',
+ 'video',
+ 'xslt',
+ ''
+]
+const subresourceSet = new Set(subresource)
- removeSignal(this)
+/** @type {globalThis['DOMException']} */
+const DOMException = globalThis.DOMException ?? (() => {
+ // DOMException was only made a global in Node v17.0.0,
+ // but fetch supports >= v16.8.
+ try {
+ atob('~')
+ } catch (err) {
+ return Object.getPrototypeOf(err).constructor
+ }
+})()
- this.factory = null
+let channel
- if (res) {
- this.res = null
- util.destroy(res, err)
- } else if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
+/** @type {globalThis['structuredClone']} */
+const structuredClone =
+ globalThis.structuredClone ??
+ // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js
+ // structuredClone was added in v17.0.0, but fetch supports v16.8
+ function structuredClone (value, options = undefined) {
+ if (arguments.length === 0) {
+ throw new TypeError('missing argument')
}
- if (body) {
- this.body = null
- util.destroy(body, err)
+ if (!channel) {
+ channel = new MessageChannel()
}
- }
-}
-
-function stream (opts, factory, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- stream.call(this, opts, factory, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
+ channel.port1.unref()
+ channel.port2.unref()
+ channel.port1.postMessage(value, options?.transfer)
+ return receiveMessageOnPort(channel.port2).message
}
- try {
- this.dispatch(opts, new StreamHandler(opts, factory, callback))
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
+module.exports = {
+ DOMException,
+ structuredClone,
+ subresource,
+ forbiddenMethods,
+ requestBodyHeader,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ redirectStatus,
+ corsSafeListedMethods,
+ nullBodyStatus,
+ safeMethods,
+ badPorts,
+ requestDuplex,
+ subresourceSet,
+ badPortsSet,
+ redirectStatusSet,
+ corsSafeListedMethodsSet,
+ safeMethodsSet,
+ forbiddenMethodsSet,
+ referrerPolicySet
}
-module.exports = stream
-
/***/ }),
-/***/ 56342:
+/***/ 37246:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+const assert = __nccwpck_require__(42613)
+const { atob } = __nccwpck_require__(20181)
+const { isomorphicDecode } = __nccwpck_require__(72847)
+const encoder = new TextEncoder()
-const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(53959)
-const { AsyncResource } = __nccwpck_require__(90290)
-const util = __nccwpck_require__(89500)
-const { addSignal, removeSignal } = __nccwpck_require__(52730)
-const assert = __nccwpck_require__(42613)
+/**
+ * @see https://mimesniff.spec.whatwg.org/#http-token-code-point
+ */
+const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/
+const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line
+/**
+ * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
+ */
+const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line
-class UpgradeHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+// https://fetch.spec.whatwg.org/#data-url-processor
+/** @param {URL} dataURL */
+function dataURLProcessor (dataURL) {
+ // 1. Assert: dataURL’s scheme is "data".
+ assert(dataURL.protocol === 'data:')
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ // 2. Let input be the result of running the URL
+ // serializer on dataURL with exclude fragment
+ // set to true.
+ let input = URLSerializer(dataURL, true)
- const { signal, opaque, responseHeaders } = opts
+ // 3. Remove the leading "data:" string from input.
+ input = input.slice(5)
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+ // 4. Let position point at the start of input.
+ const position = { position: 0 }
- super('UNDICI_UPGRADE')
+ // 5. Let mimeType be the result of collecting a
+ // sequence of code points that are not equal
+ // to U+002C (,), given position.
+ let mimeType = collectASequenceOfCodePointsFast(
+ ',',
+ input,
+ position
+ )
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.callback = callback
- this.abort = null
- this.context = null
+ // 6. Strip leading and trailing ASCII whitespace
+ // from mimeType.
+ // Undici implementation note: we need to store the
+ // length because if the mimetype has spaces removed,
+ // the wrong amount will be sliced from the input in
+ // step #9
+ const mimeTypeLength = mimeType.length
+ mimeType = removeASCIIWhitespace(mimeType, true, true)
- addSignal(this, signal)
+ // 7. If position is past the end of input, then
+ // return failure
+ if (position.position >= input.length) {
+ return 'failure'
}
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
+ // 8. Advance position by 1.
+ position.position++
+
+ // 9. Let encodedBody be the remainder of input.
+ const encodedBody = input.slice(mimeTypeLength + 1)
+
+ // 10. Let body be the percent-decoding of encodedBody.
+ let body = stringPercentDecode(encodedBody)
+
+ // 11. If mimeType ends with U+003B (;), followed by
+ // zero or more U+0020 SPACE, followed by an ASCII
+ // case-insensitive match for "base64", then:
+ if (/;(\u0020){0,}base64$/i.test(mimeType)) {
+ // 1. Let stringBody be the isomorphic decode of body.
+ const stringBody = isomorphicDecode(body)
+
+ // 2. Set body to the forgiving-base64 decode of
+ // stringBody.
+ body = forgivingBase64(stringBody)
+
+ // 3. If body is failure, then return failure.
+ if (body === 'failure') {
+ return 'failure'
}
- this.abort = abort
- this.context = null
+ // 4. Remove the last 6 code points from mimeType.
+ mimeType = mimeType.slice(0, -6)
+
+ // 5. Remove trailing U+0020 SPACE code points from mimeType,
+ // if any.
+ mimeType = mimeType.replace(/(\u0020)+$/, '')
+
+ // 6. Remove the last U+003B (;) code point from mimeType.
+ mimeType = mimeType.slice(0, -1)
}
- onHeaders () {
- throw new SocketError('bad upgrade', null)
+ // 12. If mimeType starts with U+003B (;), then prepend
+ // "text/plain" to mimeType.
+ if (mimeType.startsWith(';')) {
+ mimeType = 'text/plain' + mimeType
}
- onUpgrade (statusCode, rawHeaders, socket) {
- const { callback, opaque, context } = this
+ // 13. Let mimeTypeRecord be the result of parsing
+ // mimeType.
+ let mimeTypeRecord = parseMIMEType(mimeType)
- assert.strictEqual(statusCode, 101)
+ // 14. If mimeTypeRecord is failure, then set
+ // mimeTypeRecord to text/plain;charset=US-ASCII.
+ if (mimeTypeRecord === 'failure') {
+ mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
+ }
- removeSignal(this)
+ // 15. Return a new data: URL struct whose MIME
+ // type is mimeTypeRecord and body is body.
+ // https://fetch.spec.whatwg.org/#data-url-struct
+ return { mimeType: mimeTypeRecord, body }
+}
- this.callback = null
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- this.runInAsyncScope(callback, null, null, {
- headers,
- socket,
- opaque,
- context
- })
+// https://url.spec.whatwg.org/#concept-url-serializer
+/**
+ * @param {URL} url
+ * @param {boolean} excludeFragment
+ */
+function URLSerializer (url, excludeFragment = false) {
+ if (!excludeFragment) {
+ return url.href
}
- onError (err) {
- const { callback, opaque } = this
+ const href = url.href
+ const hashLength = url.hash.length
- removeSignal(this)
+ return hashLength === 0 ? href : href.substring(0, href.length - hashLength)
+}
- if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
+// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
+/**
+ * @param {(char: string) => boolean} condition
+ * @param {string} input
+ * @param {{ position: number }} position
+ */
+function collectASequenceOfCodePoints (condition, input, position) {
+ // 1. Let result be the empty string.
+ let result = ''
+
+ // 2. While position doesn’t point past the end of input and the
+ // code point at position within input meets the condition condition:
+ while (position.position < input.length && condition(input[position.position])) {
+ // 1. Append that code point to the end of result.
+ result += input[position.position]
+
+ // 2. Advance position by 1.
+ position.position++
}
+
+ // 3. Return result.
+ return result
}
-function upgrade (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- upgrade.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
+/**
+ * A faster collectASequenceOfCodePoints that only works when comparing a single character.
+ * @param {string} char
+ * @param {string} input
+ * @param {{ position: number }} position
+ */
+function collectASequenceOfCodePointsFast (char, input, position) {
+ const idx = input.indexOf(char, position.position)
+ const start = position.position
- try {
- const upgradeHandler = new UpgradeHandler(opts, callback)
- this.dispatch({
- ...opts,
- method: opts.method || 'GET',
- upgrade: opts.protocol || 'Websocket'
- }, upgradeHandler)
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
+ if (idx === -1) {
+ position.position = input.length
+ return input.slice(start)
}
+
+ position.position = idx
+ return input.slice(start, position.position)
}
-module.exports = upgrade
+// https://url.spec.whatwg.org/#string-percent-decode
+/** @param {string} input */
+function stringPercentDecode (input) {
+ // 1. Let bytes be the UTF-8 encoding of input.
+ const bytes = encoder.encode(input)
+ // 2. Return the percent-decoding of bytes.
+ return percentDecode(bytes)
+}
-/***/ }),
+// https://url.spec.whatwg.org/#percent-decode
+/** @param {Uint8Array} input */
+function percentDecode (input) {
+ // 1. Let output be an empty byte sequence.
+ /** @type {number[]} */
+ const output = []
-/***/ 82531:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. For each byte byte in input:
+ for (let i = 0; i < input.length; i++) {
+ const byte = input[i]
+ // 1. If byte is not 0x25 (%), then append byte to output.
+ if (byte !== 0x25) {
+ output.push(byte)
+ // 2. Otherwise, if byte is 0x25 (%) and the next two bytes
+ // after byte in input are not in the ranges
+ // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),
+ // and 0x61 (a) to 0x66 (f), all inclusive, append byte
+ // to output.
+ } else if (
+ byte === 0x25 &&
+ !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))
+ ) {
+ output.push(0x25)
-module.exports.request = __nccwpck_require__(50887)
-module.exports.stream = __nccwpck_require__(44388)
-module.exports.pipeline = __nccwpck_require__(62466)
-module.exports.upgrade = __nccwpck_require__(56342)
-module.exports.connect = __nccwpck_require__(73192)
+ // 3. Otherwise:
+ } else {
+ // 1. Let bytePoint be the two bytes after byte in input,
+ // decoded, and then interpreted as hexadecimal number.
+ const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])
+ const bytePoint = Number.parseInt(nextTwoBytes, 16)
+ // 2. Append a byte whose value is bytePoint to output.
+ output.push(bytePoint)
-/***/ }),
+ // 3. Skip the next two bytes in input.
+ i += 2
+ }
+ }
-/***/ 38947:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 3. Return output.
+ return Uint8Array.from(output)
+}
-// Ported from https://github.com/nodejs/undici/pull/907
+// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
+/** @param {string} input */
+function parseMIMEType (input) {
+ // 1. Remove any leading and trailing HTTP whitespace
+ // from input.
+ input = removeHTTPWhitespace(input, true, true)
+ // 2. Let position be a position variable for input,
+ // initially pointing at the start of input.
+ const position = { position: 0 }
+ // 3. Let type be the result of collecting a sequence
+ // of code points that are not U+002F (/) from
+ // input, given position.
+ const type = collectASequenceOfCodePointsFast(
+ '/',
+ input,
+ position
+ )
-const assert = __nccwpck_require__(42613)
-const { Readable } = __nccwpck_require__(2203)
-const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(89500)
+ // 4. If type is the empty string or does not solely
+ // contain HTTP token code points, then return failure.
+ // https://mimesniff.spec.whatwg.org/#http-token-code-point
+ if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
+ return 'failure'
+ }
-let Blob
+ // 5. If position is past the end of input, then return
+ // failure
+ if (position.position > input.length) {
+ return 'failure'
+ }
-const kConsume = Symbol('kConsume')
-const kReading = Symbol('kReading')
-const kBody = Symbol('kBody')
-const kAbort = Symbol('abort')
-const kContentType = Symbol('kContentType')
+ // 6. Advance position by 1. (This skips past U+002F (/).)
+ position.position++
-const noop = () => {}
+ // 7. Let subtype be the result of collecting a sequence of
+ // code points that are not U+003B (;) from input, given
+ // position.
+ let subtype = collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
-module.exports = class BodyReadable extends Readable {
- constructor ({
- resume,
- abort,
- contentType = '',
- highWaterMark = 64 * 1024 // Same as nodejs fs streams.
- }) {
- super({
- autoDestroy: true,
- read: resume,
- highWaterMark
- })
+ // 8. Remove any trailing HTTP whitespace from subtype.
+ subtype = removeHTTPWhitespace(subtype, false, true)
+
+ // 9. If subtype is the empty string or does not solely
+ // contain HTTP token code points, then return failure.
+ if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
+ return 'failure'
+ }
+
+ const typeLowercase = type.toLowerCase()
+ const subtypeLowercase = subtype.toLowerCase()
+
+ // 10. Let mimeType be a new MIME type record whose type
+ // is type, in ASCII lowercase, and subtype is subtype,
+ // in ASCII lowercase.
+ // https://mimesniff.spec.whatwg.org/#mime-type
+ const mimeType = {
+ type: typeLowercase,
+ subtype: subtypeLowercase,
+ /** @type {Map} */
+ parameters: new Map(),
+ // https://mimesniff.spec.whatwg.org/#mime-type-essence
+ essence: `${typeLowercase}/${subtypeLowercase}`
+ }
- this._readableState.dataEmitted = false
+ // 11. While position is not past the end of input:
+ while (position.position < input.length) {
+ // 1. Advance position by 1. (This skips past U+003B (;).)
+ position.position++
- this[kAbort] = abort
- this[kConsume] = null
- this[kBody] = null
- this[kContentType] = contentType
+ // 2. Collect a sequence of code points that are HTTP
+ // whitespace from input given position.
+ collectASequenceOfCodePoints(
+ // https://fetch.spec.whatwg.org/#http-whitespace
+ char => HTTP_WHITESPACE_REGEX.test(char),
+ input,
+ position
+ )
- // Is stream being consumed through Readable API?
- // This is an optimization so that we avoid checking
- // for 'data' and 'readable' listeners in the hot path
- // inside push().
- this[kReading] = false
- }
+ // 3. Let parameterName be the result of collecting a
+ // sequence of code points that are not U+003B (;)
+ // or U+003D (=) from input, given position.
+ let parameterName = collectASequenceOfCodePoints(
+ (char) => char !== ';' && char !== '=',
+ input,
+ position
+ )
- destroy (err) {
- if (this.destroyed) {
- // Node < 16
- return this
- }
+ // 4. Set parameterName to parameterName, in ASCII
+ // lowercase.
+ parameterName = parameterName.toLowerCase()
- if (!err && !this._readableState.endEmitted) {
- err = new RequestAbortedError()
+ // 5. If position is not past the end of input, then:
+ if (position.position < input.length) {
+ // 1. If the code point at position within input is
+ // U+003B (;), then continue.
+ if (input[position.position] === ';') {
+ continue
+ }
+
+ // 2. Advance position by 1. (This skips past U+003D (=).)
+ position.position++
}
- if (err) {
- this[kAbort]()
+ // 6. If position is past the end of input, then break.
+ if (position.position > input.length) {
+ break
}
- return super.destroy(err)
- }
+ // 7. Let parameterValue be null.
+ let parameterValue = null
- emit (ev, ...args) {
- if (ev === 'data') {
- // Node < 16.7
- this._readableState.dataEmitted = true
- } else if (ev === 'error') {
- // Node < 16
- this._readableState.errorEmitted = true
+ // 8. If the code point at position within input is
+ // U+0022 ("), then:
+ if (input[position.position] === '"') {
+ // 1. Set parameterValue to the result of collecting
+ // an HTTP quoted string from input, given position
+ // and the extract-value flag.
+ parameterValue = collectAnHTTPQuotedString(input, position, true)
+
+ // 2. Collect a sequence of code points that are not
+ // U+003B (;) from input, given position.
+ collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
+
+ // 9. Otherwise:
+ } else {
+ // 1. Set parameterValue to the result of collecting
+ // a sequence of code points that are not U+003B (;)
+ // from input, given position.
+ parameterValue = collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
+
+ // 2. Remove any trailing HTTP whitespace from parameterValue.
+ parameterValue = removeHTTPWhitespace(parameterValue, false, true)
+
+ // 3. If parameterValue is the empty string, then continue.
+ if (parameterValue.length === 0) {
+ continue
+ }
}
- return super.emit(ev, ...args)
- }
- on (ev, ...args) {
- if (ev === 'data' || ev === 'readable') {
- this[kReading] = true
+ // 10. If all of the following are true
+ // - parameterName is not the empty string
+ // - parameterName solely contains HTTP token code points
+ // - parameterValue solely contains HTTP quoted-string token code points
+ // - mimeType’s parameters[parameterName] does not exist
+ // then set mimeType’s parameters[parameterName] to parameterValue.
+ if (
+ parameterName.length !== 0 &&
+ HTTP_TOKEN_CODEPOINTS.test(parameterName) &&
+ (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&
+ !mimeType.parameters.has(parameterName)
+ ) {
+ mimeType.parameters.set(parameterName, parameterValue)
}
- return super.on(ev, ...args)
}
- addListener (ev, ...args) {
- return this.on(ev, ...args)
- }
+ // 12. Return mimeType.
+ return mimeType
+}
- off (ev, ...args) {
- const ret = super.off(ev, ...args)
- if (ev === 'data' || ev === 'readable') {
- this[kReading] = (
- this.listenerCount('data') > 0 ||
- this.listenerCount('readable') > 0
- )
- }
- return ret
- }
+// https://infra.spec.whatwg.org/#forgiving-base64-decode
+/** @param {string} data */
+function forgivingBase64 (data) {
+ // 1. Remove all ASCII whitespace from data.
+ data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line
- removeListener (ev, ...args) {
- return this.off(ev, ...args)
+ // 2. If data’s code point length divides by 4 leaving
+ // no remainder, then:
+ if (data.length % 4 === 0) {
+ // 1. If data ends with one or two U+003D (=) code points,
+ // then remove them from data.
+ data = data.replace(/=?=$/, '')
}
- push (chunk) {
- if (this[kConsume] && chunk !== null && this.readableLength === 0) {
- consumePush(this[kConsume], chunk)
- return this[kReading] ? super.push(chunk) : true
- }
- return super.push(chunk)
+ // 3. If data’s code point length divides by 4 leaving
+ // a remainder of 1, then return failure.
+ if (data.length % 4 === 1) {
+ return 'failure'
}
- // https://fetch.spec.whatwg.org/#dom-body-text
- async text () {
- return consume(this, 'text')
+ // 4. If data contains a code point that is not one of
+ // U+002B (+)
+ // U+002F (/)
+ // ASCII alphanumeric
+ // then return failure.
+ if (/[^+/0-9A-Za-z]/.test(data)) {
+ return 'failure'
}
- // https://fetch.spec.whatwg.org/#dom-body-json
- async json () {
- return consume(this, 'json')
- }
+ const binary = atob(data)
+ const bytes = new Uint8Array(binary.length)
- // https://fetch.spec.whatwg.org/#dom-body-blob
- async blob () {
- return consume(this, 'blob')
+ for (let byte = 0; byte < binary.length; byte++) {
+ bytes[byte] = binary.charCodeAt(byte)
}
- // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
- async arrayBuffer () {
- return consume(this, 'arrayBuffer')
- }
+ return bytes
+}
- // https://fetch.spec.whatwg.org/#dom-body-formdata
- async formData () {
- // TODO: Implement.
- throw new NotSupportedError()
- }
+// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
+// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string
+/**
+ * @param {string} input
+ * @param {{ position: number }} position
+ * @param {boolean?} extractValue
+ */
+function collectAnHTTPQuotedString (input, position, extractValue) {
+ // 1. Let positionStart be position.
+ const positionStart = position.position
- // https://fetch.spec.whatwg.org/#dom-body-bodyused
- get bodyUsed () {
- return util.isDisturbed(this)
- }
+ // 2. Let value be the empty string.
+ let value = ''
- // https://fetch.spec.whatwg.org/#dom-body-body
- get body () {
- if (!this[kBody]) {
- this[kBody] = ReadableStreamFrom(this)
- if (this[kConsume]) {
- // TODO: Is this the best way to force a lock?
- this[kBody].getReader() // Ensure stream is locked.
- assert(this[kBody].locked)
- }
- }
- return this[kBody]
- }
+ // 3. Assert: the code point at position within input
+ // is U+0022 (").
+ assert(input[position.position] === '"')
- dump (opts) {
- let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144
- const signal = opts && opts.signal
+ // 4. Advance position by 1.
+ position.position++
- if (signal) {
- try {
- if (typeof signal !== 'object' || !('aborted' in signal)) {
- throw new InvalidArgumentError('signal must be an AbortSignal')
- }
- util.throwIfAborted(signal)
- } catch (err) {
- return Promise.reject(err)
- }
- }
+ // 5. While true:
+ while (true) {
+ // 1. Append the result of collecting a sequence of code points
+ // that are not U+0022 (") or U+005C (\) from input, given
+ // position, to value.
+ value += collectASequenceOfCodePoints(
+ (char) => char !== '"' && char !== '\\',
+ input,
+ position
+ )
- if (this.closed) {
- return Promise.resolve(null)
+ // 2. If position is past the end of input, then break.
+ if (position.position >= input.length) {
+ break
}
- return new Promise((resolve, reject) => {
- const signalListenerCleanup = signal
- ? util.addAbortListener(signal, () => {
- this.destroy()
- })
- : noop
+ // 3. Let quoteOrBackslash be the code point at position within
+ // input.
+ const quoteOrBackslash = input[position.position]
- this
- .on('close', function () {
- signalListenerCleanup()
- if (signal && signal.aborted) {
- reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))
- } else {
- resolve(null)
- }
- })
- .on('error', noop)
- .on('data', function (chunk) {
- limit -= chunk.length
- if (limit <= 0) {
- this.destroy()
- }
- })
- .resume()
- })
- }
-}
+ // 4. Advance position by 1.
+ position.position++
-// https://streams.spec.whatwg.org/#readablestream-locked
-function isLocked (self) {
- // Consume is an implicit lock.
- return (self[kBody] && self[kBody].locked === true) || self[kConsume]
-}
+ // 5. If quoteOrBackslash is U+005C (\), then:
+ if (quoteOrBackslash === '\\') {
+ // 1. If position is past the end of input, then append
+ // U+005C (\) to value and break.
+ if (position.position >= input.length) {
+ value += '\\'
+ break
+ }
-// https://fetch.spec.whatwg.org/#body-unusable
-function isUnusable (self) {
- return util.isDisturbed(self) || isLocked(self)
-}
+ // 2. Append the code point at position within input to value.
+ value += input[position.position]
-async function consume (stream, type) {
- if (isUnusable(stream)) {
- throw new TypeError('unusable')
- }
+ // 3. Advance position by 1.
+ position.position++
- assert(!stream[kConsume])
+ // 6. Otherwise:
+ } else {
+ // 1. Assert: quoteOrBackslash is U+0022 (").
+ assert(quoteOrBackslash === '"')
- return new Promise((resolve, reject) => {
- stream[kConsume] = {
- type,
- stream,
- resolve,
- reject,
- length: 0,
- body: []
+ // 2. Break.
+ break
}
+ }
- stream
- .on('error', function (err) {
- consumeFinish(this[kConsume], err)
- })
- .on('close', function () {
- if (this[kConsume].body !== null) {
- consumeFinish(this[kConsume], new RequestAbortedError())
- }
- })
-
- process.nextTick(consumeStart, stream[kConsume])
- })
-}
-
-function consumeStart (consume) {
- if (consume.body === null) {
- return
+ // 6. If the extract-value flag is set, then return value.
+ if (extractValue) {
+ return value
}
- const { _readableState: state } = consume.stream
+ // 7. Return the code points from positionStart to position,
+ // inclusive, within input.
+ return input.slice(positionStart, position.position)
+}
- for (const chunk of state.buffer) {
- consumePush(consume, chunk)
- }
+/**
+ * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
+ */
+function serializeAMimeType (mimeType) {
+ assert(mimeType !== 'failure')
+ const { parameters, essence } = mimeType
- if (state.endEmitted) {
- consumeEnd(this[kConsume])
- } else {
- consume.stream.on('end', function () {
- consumeEnd(this[kConsume])
- })
- }
+ // 1. Let serialization be the concatenation of mimeType’s
+ // type, U+002F (/), and mimeType’s subtype.
+ let serialization = essence
- consume.stream.resume()
+ // 2. For each name → value of mimeType’s parameters:
+ for (let [name, value] of parameters.entries()) {
+ // 1. Append U+003B (;) to serialization.
+ serialization += ';'
- while (consume.stream.read() != null) {
- // Loop
- }
-}
+ // 2. Append name to serialization.
+ serialization += name
-function consumeEnd (consume) {
- const { type, body, resolve, stream, length } = consume
+ // 3. Append U+003D (=) to serialization.
+ serialization += '='
- try {
- if (type === 'text') {
- resolve(toUSVString(Buffer.concat(body)))
- } else if (type === 'json') {
- resolve(JSON.parse(Buffer.concat(body)))
- } else if (type === 'arrayBuffer') {
- const dst = new Uint8Array(length)
+ // 4. If value does not solely contain HTTP token code
+ // points or value is the empty string, then:
+ if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
+ // 1. Precede each occurence of U+0022 (") or
+ // U+005C (\) in value with U+005C (\).
+ value = value.replace(/(\\|")/g, '\\$1')
- let pos = 0
- for (const buf of body) {
- dst.set(buf, pos)
- pos += buf.byteLength
- }
+ // 2. Prepend U+0022 (") to value.
+ value = '"' + value
- resolve(dst.buffer)
- } else if (type === 'blob') {
- if (!Blob) {
- Blob = (__nccwpck_require__(20181).Blob)
- }
- resolve(new Blob(body, { type: stream[kContentType] }))
+ // 3. Append U+0022 (") to value.
+ value += '"'
}
- consumeFinish(consume)
- } catch (err) {
- stream.destroy(err)
+ // 5. Append value to serialization.
+ serialization += value
}
+
+ // 3. Return serialization.
+ return serialization
}
-function consumePush (consume, chunk) {
- consume.length += chunk.length
- consume.body.push(chunk)
+/**
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
+ * @param {string} char
+ */
+function isHTTPWhiteSpace (char) {
+ return char === '\r' || char === '\n' || char === '\t' || char === ' '
}
-function consumeFinish (consume, err) {
- if (consume.body === null) {
- return
+/**
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
+ * @param {string} str
+ */
+function removeHTTPWhitespace (str, leading = true, trailing = true) {
+ let lead = 0
+ let trail = str.length - 1
+
+ if (leading) {
+ for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);
}
- if (err) {
- consume.reject(err)
- } else {
- consume.resolve()
+ if (trailing) {
+ for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);
}
- consume.type = null
- consume.stream = null
- consume.resolve = null
- consume.reject = null
- consume.length = 0
- consume.body = null
+ return str.slice(lead, trail + 1)
}
+/**
+ * @see https://infra.spec.whatwg.org/#ascii-whitespace
+ * @param {string} char
+ */
+function isASCIIWhitespace (char) {
+ return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' '
+}
-/***/ }),
-
-/***/ 80363:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const assert = __nccwpck_require__(42613)
-const {
- ResponseStatusCodeError
-} = __nccwpck_require__(53959)
-const { toUSVString } = __nccwpck_require__(89500)
-
-async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
- assert(body)
-
- let chunks = []
- let limit = 0
-
- for await (const chunk of body) {
- chunks.push(chunk)
- limit += chunk.length
- if (limit > 128 * 1024) {
- chunks = null
- break
- }
- }
+/**
+ * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
+ */
+function removeASCIIWhitespace (str, leading = true, trailing = true) {
+ let lead = 0
+ let trail = str.length - 1
- if (statusCode === 204 || !contentType || !chunks) {
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
- return
+ if (leading) {
+ for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);
}
-
- try {
- if (contentType.startsWith('application/json')) {
- const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
- return
- }
-
- if (contentType.startsWith('text/')) {
- const payload = toUSVString(Buffer.concat(chunks))
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
- return
- }
- } catch (err) {
- // Process in a fallback if error
+
+ if (trailing) {
+ for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);
}
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
+ return str.slice(lead, trail + 1)
}
-module.exports = { getResolveErrorBodyCallback }
+module.exports = {
+ dataURLProcessor,
+ URLSerializer,
+ collectASequenceOfCodePoints,
+ collectASequenceOfCodePointsFast,
+ stringPercentDecode,
+ parseMIMEType,
+ collectAnHTTPQuotedString,
+ serializeAMimeType
+}
/***/ }),
-/***/ 95377:
+/***/ 17005:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const {
- BalancedPoolMissingUpstreamError,
- InvalidArgumentError
-} = __nccwpck_require__(53959)
-const {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kGetDispatcher
-} = __nccwpck_require__(18804)
-const Pool = __nccwpck_require__(44288)
-const { kUrl, kInterceptors } = __nccwpck_require__(68031)
-const { parseOrigin } = __nccwpck_require__(89500)
-const kFactory = Symbol('factory')
+const { Blob, File: NativeFile } = __nccwpck_require__(20181)
+const { types } = __nccwpck_require__(39023)
+const { kState } = __nccwpck_require__(63730)
+const { isBlobLike } = __nccwpck_require__(72847)
+const { webidl } = __nccwpck_require__(94354)
+const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
+const { kEnumerableProperty } = __nccwpck_require__(89500)
+const encoder = new TextEncoder()
-const kOptions = Symbol('options')
-const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
-const kCurrentWeight = Symbol('kCurrentWeight')
-const kIndex = Symbol('kIndex')
-const kWeight = Symbol('kWeight')
-const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
-const kErrorPenalty = Symbol('kErrorPenalty')
+class File extends Blob {
+ constructor (fileBits, fileName, options = {}) {
+ // The File constructor is invoked with two or three parameters, depending
+ // on whether the optional dictionary parameter is used. When the File()
+ // constructor is invoked, user agents must run the following steps:
+ webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })
-function getGreatestCommonDivisor (a, b) {
- if (b === 0) return a
- return getGreatestCommonDivisor(b, a % b)
-}
+ fileBits = webidl.converters['sequence'](fileBits)
+ fileName = webidl.converters.USVString(fileName)
+ options = webidl.converters.FilePropertyBag(options)
-function defaultFactory (origin, opts) {
- return new Pool(origin, opts)
-}
+ // 1. Let bytes be the result of processing blob parts given fileBits and
+ // options.
+ // Note: Blob handles this for us
-class BalancedPool extends PoolBase {
- constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
- super()
+ // 2. Let n be the fileName argument to the constructor.
+ const n = fileName
- this[kOptions] = opts
- this[kIndex] = -1
- this[kCurrentWeight] = 0
+ // 3. Process FilePropertyBag dictionary argument by running the following
+ // substeps:
- this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
- this[kErrorPenalty] = this[kOptions].errorPenalty || 15
+ // 1. If the type member is provided and is not the empty string, let t
+ // be set to the type dictionary member. If t contains any characters
+ // outside the range U+0020 to U+007E, then set t to the empty string
+ // and return from these substeps.
+ // 2. Convert every character in t to ASCII lowercase.
+ let t = options.type
+ let d
- if (!Array.isArray(upstreams)) {
- upstreams = [upstreams]
- }
+ // eslint-disable-next-line no-labels
+ substep: {
+ if (t) {
+ t = parseMIMEType(t)
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
+ if (t === 'failure') {
+ t = ''
+ // eslint-disable-next-line no-labels
+ break substep
+ }
- this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
- ? opts.interceptors.BalancedPool
- : []
- this[kFactory] = factory
+ t = serializeAMimeType(t).toLowerCase()
+ }
- for (const upstream of upstreams) {
- this.addUpstream(upstream)
+ // 3. If the lastModified member is provided, let d be set to the
+ // lastModified dictionary member. If it is not provided, set d to the
+ // current date and time represented as the number of milliseconds since
+ // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
+ d = options.lastModified
}
- this._updateBalancedPoolStats()
- }
- addUpstream (upstream) {
- const upstreamOrigin = parseOrigin(upstream).origin
+ // 4. Return a new File object F such that:
+ // F refers to the bytes byte sequence.
+ // F.size is set to the number of total bytes in bytes.
+ // F.name is set to n.
+ // F.type is set to t.
+ // F.lastModified is set to d.
- if (this[kClients].find((pool) => (
- pool[kUrl].origin === upstreamOrigin &&
- pool.closed !== true &&
- pool.destroyed !== true
- ))) {
- return this
+ super(processBlobParts(fileBits, options), { type: t })
+ this[kState] = {
+ name: n,
+ lastModified: d,
+ type: t
}
- const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
-
- this[kAddClient](pool)
- pool.on('connect', () => {
- pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
- })
-
- pool.on('connectionError', () => {
- pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
- this._updateBalancedPoolStats()
- })
+ }
- pool.on('disconnect', (...args) => {
- const err = args[2]
- if (err && err.code === 'UND_ERR_SOCKET') {
- // decrease the weight of the pool.
- pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
- this._updateBalancedPoolStats()
- }
- })
+ get name () {
+ webidl.brandCheck(this, File)
- for (const client of this[kClients]) {
- client[kWeight] = this[kMaxWeightPerServer]
- }
+ return this[kState].name
+ }
- this._updateBalancedPoolStats()
+ get lastModified () {
+ webidl.brandCheck(this, File)
- return this
+ return this[kState].lastModified
}
- _updateBalancedPoolStats () {
- this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
+ get type () {
+ webidl.brandCheck(this, File)
+
+ return this[kState].type
}
+}
- removeUpstream (upstream) {
- const upstreamOrigin = parseOrigin(upstream).origin
+class FileLike {
+ constructor (blobLike, fileName, options = {}) {
+ // TODO: argument idl type check
- const pool = this[kClients].find((pool) => (
- pool[kUrl].origin === upstreamOrigin &&
- pool.closed !== true &&
- pool.destroyed !== true
- ))
+ // The File constructor is invoked with two or three parameters, depending
+ // on whether the optional dictionary parameter is used. When the File()
+ // constructor is invoked, user agents must run the following steps:
- if (pool) {
- this[kRemoveClient](pool)
- }
+ // 1. Let bytes be the result of processing blob parts given fileBits and
+ // options.
- return this
- }
+ // 2. Let n be the fileName argument to the constructor.
+ const n = fileName
- get upstreams () {
- return this[kClients]
- .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
- .map((p) => p[kUrl].origin)
- }
+ // 3. Process FilePropertyBag dictionary argument by running the following
+ // substeps:
- [kGetDispatcher] () {
- // We validate that pools is greater than 0,
- // otherwise we would have to wait until an upstream
- // is added, which might never happen.
- if (this[kClients].length === 0) {
- throw new BalancedPoolMissingUpstreamError()
- }
+ // 1. If the type member is provided and is not the empty string, let t
+ // be set to the type dictionary member. If t contains any characters
+ // outside the range U+0020 to U+007E, then set t to the empty string
+ // and return from these substeps.
+ // TODO
+ const t = options.type
- const dispatcher = this[kClients].find(dispatcher => (
- !dispatcher[kNeedDrain] &&
- dispatcher.closed !== true &&
- dispatcher.destroyed !== true
- ))
+ // 2. Convert every character in t to ASCII lowercase.
+ // TODO
- if (!dispatcher) {
- return
- }
+ // 3. If the lastModified member is provided, let d be set to the
+ // lastModified dictionary member. If it is not provided, set d to the
+ // current date and time represented as the number of milliseconds since
+ // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
+ const d = options.lastModified ?? Date.now()
- const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
+ // 4. Return a new File object F such that:
+ // F refers to the bytes byte sequence.
+ // F.size is set to the number of total bytes in bytes.
+ // F.name is set to n.
+ // F.type is set to t.
+ // F.lastModified is set to d.
- if (allClientsBusy) {
- return
+ this[kState] = {
+ blobLike,
+ name: n,
+ type: t,
+ lastModified: d
}
+ }
- let counter = 0
+ stream (...args) {
+ webidl.brandCheck(this, FileLike)
- let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
+ return this[kState].blobLike.stream(...args)
+ }
- while (counter++ < this[kClients].length) {
- this[kIndex] = (this[kIndex] + 1) % this[kClients].length
- const pool = this[kClients][this[kIndex]]
+ arrayBuffer (...args) {
+ webidl.brandCheck(this, FileLike)
- // find pool index with the largest weight
- if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
- maxWeightIndex = this[kIndex]
- }
+ return this[kState].blobLike.arrayBuffer(...args)
+ }
- // decrease the current weight every `this[kClients].length`.
- if (this[kIndex] === 0) {
- // Set the current weight to the next lower weight.
- this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
+ slice (...args) {
+ webidl.brandCheck(this, FileLike)
- if (this[kCurrentWeight] <= 0) {
- this[kCurrentWeight] = this[kMaxWeightPerServer]
- }
- }
- if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
- return pool
- }
- }
+ return this[kState].blobLike.slice(...args)
+ }
- this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
- this[kIndex] = maxWeightIndex
- return this[kClients][maxWeightIndex]
+ text (...args) {
+ webidl.brandCheck(this, FileLike)
+
+ return this[kState].blobLike.text(...args)
}
-}
-module.exports = BalancedPool
+ get size () {
+ webidl.brandCheck(this, FileLike)
+ return this[kState].blobLike.size
+ }
-/***/ }),
+ get type () {
+ webidl.brandCheck(this, FileLike)
-/***/ 40611:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ return this[kState].blobLike.type
+ }
+ get name () {
+ webidl.brandCheck(this, FileLike)
+ return this[kState].name
+ }
-const { kConstruct } = __nccwpck_require__(68652)
-const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(71173)
-const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(89500)
-const { kHeadersList } = __nccwpck_require__(68031)
-const { webidl } = __nccwpck_require__(94354)
-const { Response, cloneResponse } = __nccwpck_require__(89928)
-const { Request } = __nccwpck_require__(2630)
-const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
-const { fetching } = __nccwpck_require__(11503)
-const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(72847)
-const assert = __nccwpck_require__(42613)
-const { getGlobalDispatcher } = __nccwpck_require__(61481)
+ get lastModified () {
+ webidl.brandCheck(this, FileLike)
-/**
- * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
- * @typedef {Object} CacheBatchOperation
- * @property {'delete' | 'put'} type
- * @property {any} request
- * @property {any} response
- * @property {import('../../types/cache').CacheQueryOptions} options
- */
+ return this[kState].lastModified
+ }
-/**
- * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
- * @typedef {[any, any][]} requestResponseList
- */
+ get [Symbol.toStringTag] () {
+ return 'File'
+ }
+}
-class Cache {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
- * @type {requestResponseList}
- */
- #relevantRequestResponseList
+Object.defineProperties(File.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'File',
+ configurable: true
+ },
+ name: kEnumerableProperty,
+ lastModified: kEnumerableProperty
+})
- constructor () {
- if (arguments[0] !== kConstruct) {
- webidl.illegalConstructor()
+webidl.converters.Blob = webidl.interfaceConverter(Blob)
+
+webidl.converters.BlobPart = function (V, opts) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
}
- this.#relevantRequestResponseList = arguments[1]
+ if (
+ ArrayBuffer.isView(V) ||
+ types.isAnyArrayBuffer(V)
+ ) {
+ return webidl.converters.BufferSource(V, opts)
+ }
}
- async match (request, options = {}) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })
-
- request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+ return webidl.converters.USVString(V, opts)
+}
- const p = await this.matchAll(request, options)
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.BlobPart
+)
- if (p.length === 0) {
- return
+// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag
+webidl.converters.FilePropertyBag = webidl.dictionaryConverter([
+ {
+ key: 'lastModified',
+ converter: webidl.converters['long long'],
+ get defaultValue () {
+ return Date.now()
}
+ },
+ {
+ key: 'type',
+ converter: webidl.converters.DOMString,
+ defaultValue: ''
+ },
+ {
+ key: 'endings',
+ converter: (value) => {
+ value = webidl.converters.DOMString(value)
+ value = value.toLowerCase()
- return p[0]
- }
+ if (value !== 'native') {
+ value = 'transparent'
+ }
- async matchAll (request = undefined, options = {}) {
- webidl.brandCheck(this, Cache)
+ return value
+ },
+ defaultValue: 'transparent'
+ }
+])
- if (request !== undefined) request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+/**
+ * @see https://www.w3.org/TR/FileAPI/#process-blob-parts
+ * @param {(NodeJS.TypedArray|Blob|string)[]} parts
+ * @param {{ type: string, endings: string }} options
+ */
+function processBlobParts (parts, options) {
+ // 1. Let bytes be an empty sequence of bytes.
+ /** @type {NodeJS.TypedArray[]} */
+ const bytes = []
- // 1.
- let r = null
+ // 2. For each element in parts:
+ for (const element of parts) {
+ // 1. If element is a USVString, run the following substeps:
+ if (typeof element === 'string') {
+ // 1. Let s be element.
+ let s = element
- // 2.
- if (request !== undefined) {
- if (request instanceof Request) {
- // 2.1.1
- r = request[kState]
+ // 2. If the endings member of options is "native", set s
+ // to the result of converting line endings to native
+ // of element.
+ if (options.endings === 'native') {
+ s = convertLineEndingsNative(s)
+ }
- // 2.1.2
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return []
- }
- } else if (typeof request === 'string') {
- // 2.2.1
- r = new Request(request)[kState]
+ // 3. Append the result of UTF-8 encoding s to bytes.
+ bytes.push(encoder.encode(s))
+ } else if (
+ types.isAnyArrayBuffer(element) ||
+ types.isTypedArray(element)
+ ) {
+ // 2. If element is a BufferSource, get a copy of the
+ // bytes held by the buffer source, and append those
+ // bytes to bytes.
+ if (!element.buffer) { // ArrayBuffer
+ bytes.push(new Uint8Array(element))
+ } else {
+ bytes.push(
+ new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
+ )
}
+ } else if (isBlobLike(element)) {
+ // 3. If element is a Blob, append the bytes it represents
+ // to bytes.
+ bytes.push(element)
}
+ }
- // 5.
- // 5.1
- const responses = []
+ // 3. Return bytes.
+ return bytes
+}
- // 5.2
- if (request === undefined) {
- // 5.2.1
- for (const requestResponse of this.#relevantRequestResponseList) {
- responses.push(requestResponse[1])
- }
- } else { // 5.3
- // 5.3.1
- const requestResponses = this.#queryCache(r, options)
+/**
+ * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native
+ * @param {string} s
+ */
+function convertLineEndingsNative (s) {
+ // 1. Let native line ending be be the code point U+000A LF.
+ let nativeLineEnding = '\n'
- // 5.3.2
- for (const requestResponse of requestResponses) {
- responses.push(requestResponse[1])
- }
- }
+ // 2. If the underlying platform’s conventions are to
+ // represent newlines as a carriage return and line feed
+ // sequence, set native line ending to the code point
+ // U+000D CR followed by the code point U+000A LF.
+ if (process.platform === 'win32') {
+ nativeLineEnding = '\r\n'
+ }
+
+ return s.replace(/\r?\n/g, nativeLineEnding)
+}
+
+// If this function is moved to ./util.js, some tools (such as
+// rollup) will warn about circular dependencies. See:
+// https://github.com/nodejs/undici/issues/1629
+function isFileLike (object) {
+ return (
+ (NativeFile && object instanceof NativeFile) ||
+ object instanceof File || (
+ object &&
+ (typeof object.stream === 'function' ||
+ typeof object.arrayBuffer === 'function') &&
+ object[Symbol.toStringTag] === 'File'
+ )
+ )
+}
- // 5.4
- // We don't implement CORs so we don't need to loop over the responses, yay!
+module.exports = { File, FileLike, isFileLike }
- // 5.5.1
- const responseList = []
- // 5.5.2
- for (const response of responses) {
- // 5.5.2.1
- const responseObject = new Response(response.body?.source ?? null)
- const body = responseObject[kState].body
- responseObject[kState] = response
- responseObject[kState].body = body
- responseObject[kHeaders][kHeadersList] = response.headersList
- responseObject[kHeaders][kGuard] = 'immutable'
+/***/ }),
- responseList.push(responseObject)
- }
+/***/ 47453:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 6.
- return Object.freeze(responseList)
- }
- async add (request) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })
- request = webidl.converters.RequestInfo(request)
+const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(72847)
+const { kState } = __nccwpck_require__(63730)
+const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(17005)
+const { webidl } = __nccwpck_require__(94354)
+const { Blob, File: NativeFile } = __nccwpck_require__(20181)
- // 1.
- const requests = [request]
+/** @type {globalThis['File']} */
+const File = NativeFile ?? UndiciFile
- // 2.
- const responseArrayPromise = this.addAll(requests)
+// https://xhr.spec.whatwg.org/#formdata
+class FormData {
+ constructor (form) {
+ if (form !== undefined) {
+ throw webidl.errors.conversionFailed({
+ prefix: 'FormData constructor',
+ argument: 'Argument 1',
+ types: ['undefined']
+ })
+ }
- // 3.
- return await responseArrayPromise
+ this[kState] = []
}
- async addAll (requests) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })
+ append (name, value, filename = undefined) {
+ webidl.brandCheck(this, FormData)
- requests = webidl.converters['sequence'](requests)
+ webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })
- // 1.
- const responsePromises = []
+ if (arguments.length === 3 && !isBlobLike(value)) {
+ throw new TypeError(
+ "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
+ )
+ }
- // 2.
- const requestList = []
+ // 1. Let value be value if given; otherwise blobValue.
- // 3.
- for (const request of requests) {
- if (typeof request === 'string') {
- continue
- }
+ name = webidl.converters.USVString(name)
+ value = isBlobLike(value)
+ ? webidl.converters.Blob(value, { strict: false })
+ : webidl.converters.USVString(value)
+ filename = arguments.length === 3
+ ? webidl.converters.USVString(filename)
+ : undefined
- // 3.1
- const r = request[kState]
+ // 2. Let entry be the result of creating an entry with
+ // name, value, and filename if given.
+ const entry = makeEntry(name, value, filename)
- // 3.2
- if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'Expected http/s scheme when method is not GET.'
- })
- }
- }
+ // 3. Append entry to this’s entry list.
+ this[kState].push(entry)
+ }
- // 4.
- /** @type {ReturnType[]} */
- const fetchControllers = []
+ delete (name) {
+ webidl.brandCheck(this, FormData)
- // 5.
- for (const request of requests) {
- // 5.1
- const r = new Request(request)[kState]
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })
- // 5.2
- if (!urlIsHttpHttpsScheme(r.url)) {
- throw webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'Expected http/s scheme.'
- })
- }
+ name = webidl.converters.USVString(name)
- // 5.4
- r.initiator = 'fetch'
- r.destination = 'subresource'
+ // The delete(name) method steps are to remove all entries whose name
+ // is name from this’s entry list.
+ this[kState] = this[kState].filter(entry => entry.name !== name)
+ }
- // 5.5
- requestList.push(r)
+ get (name) {
+ webidl.brandCheck(this, FormData)
- // 5.6
- const responsePromise = createDeferredPromise()
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })
- // 5.7
- fetchControllers.push(fetching({
- request: r,
- dispatcher: getGlobalDispatcher(),
- processResponse (response) {
- // 1.
- if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
- responsePromise.reject(webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'Received an invalid status code or the request failed.'
- }))
- } else if (response.headersList.contains('vary')) { // 2.
- // 2.1
- const fieldValues = getFieldValues(response.headersList.get('vary'))
+ name = webidl.converters.USVString(name)
- // 2.2
- for (const fieldValue of fieldValues) {
- // 2.2.1
- if (fieldValue === '*') {
- responsePromise.reject(webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'invalid vary field value'
- }))
+ // 1. If there is no entry whose name is name in this’s entry list,
+ // then return null.
+ const idx = this[kState].findIndex((entry) => entry.name === name)
+ if (idx === -1) {
+ return null
+ }
- for (const controller of fetchControllers) {
- controller.abort()
- }
+ // 2. Return the value of the first entry whose name is name from
+ // this’s entry list.
+ return this[kState][idx].value
+ }
- return
- }
- }
- }
- },
- processResponseEndOfBody (response) {
- // 1.
- if (response.aborted) {
- responsePromise.reject(new DOMException('aborted', 'AbortError'))
- return
- }
+ getAll (name) {
+ webidl.brandCheck(this, FormData)
- // 2.
- responsePromise.resolve(response)
- }
- }))
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })
- // 5.8
- responsePromises.push(responsePromise.promise)
- }
+ name = webidl.converters.USVString(name)
- // 6.
- const p = Promise.all(responsePromises)
+ // 1. If there is no entry whose name is name in this’s entry list,
+ // then return the empty list.
+ // 2. Return the values of all entries whose name is name, in order,
+ // from this’s entry list.
+ return this[kState]
+ .filter((entry) => entry.name === name)
+ .map((entry) => entry.value)
+ }
- // 7.
- const responses = await p
+ has (name) {
+ webidl.brandCheck(this, FormData)
- // 7.1
- const operations = []
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })
- // 7.2
- let index = 0
+ name = webidl.converters.USVString(name)
- // 7.3
- for (const response of responses) {
- // 7.3.1
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'put', // 7.3.2
- request: requestList[index], // 7.3.3
- response // 7.3.4
- }
+ // The has(name) method steps are to return true if there is an entry
+ // whose name is name in this’s entry list; otherwise false.
+ return this[kState].findIndex((entry) => entry.name === name) !== -1
+ }
- operations.push(operation) // 7.3.5
+ set (name, value, filename = undefined) {
+ webidl.brandCheck(this, FormData)
- index++ // 7.3.6
+ webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })
+
+ if (arguments.length === 3 && !isBlobLike(value)) {
+ throw new TypeError(
+ "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
+ )
}
- // 7.5
- const cacheJobPromise = createDeferredPromise()
+ // The set(name, value) and set(name, blobValue, filename) method steps
+ // are:
- // 7.6.1
- let errorData = null
+ // 1. Let value be value if given; otherwise blobValue.
- // 7.6.2
- try {
- this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
- }
+ name = webidl.converters.USVString(name)
+ value = isBlobLike(value)
+ ? webidl.converters.Blob(value, { strict: false })
+ : webidl.converters.USVString(value)
+ filename = arguments.length === 3
+ ? toUSVString(filename)
+ : undefined
- // 7.6.3
- queueMicrotask(() => {
- // 7.6.3.1
- if (errorData === null) {
- cacheJobPromise.resolve(undefined)
- } else {
- // 7.6.3.2
- cacheJobPromise.reject(errorData)
- }
- })
+ // 2. Let entry be the result of creating an entry with name, value, and
+ // filename if given.
+ const entry = makeEntry(name, value, filename)
- // 7.7
- return cacheJobPromise.promise
+ // 3. If there are entries in this’s entry list whose name is name, then
+ // replace the first such entry with entry and remove the others.
+ const idx = this[kState].findIndex((entry) => entry.name === name)
+ if (idx !== -1) {
+ this[kState] = [
+ ...this[kState].slice(0, idx),
+ entry,
+ ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
+ ]
+ } else {
+ // 4. Otherwise, append entry to this’s entry list.
+ this[kState].push(entry)
+ }
}
- async put (request, response) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })
+ entries () {
+ webidl.brandCheck(this, FormData)
- request = webidl.converters.RequestInfo(request)
- response = webidl.converters.Response(response)
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'key+value'
+ )
+ }
- // 1.
- let innerRequest = null
+ keys () {
+ webidl.brandCheck(this, FormData)
- // 2.
- if (request instanceof Request) {
- innerRequest = request[kState]
- } else { // 3.
- innerRequest = new Request(request)[kState]
- }
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'key'
+ )
+ }
- // 4.
- if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Expected an http/s scheme when method is not GET'
- })
- }
+ values () {
+ webidl.brandCheck(this, FormData)
- // 5.
- const innerResponse = response[kState]
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'value'
+ )
+ }
- // 6.
- if (innerResponse.status === 206) {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Got 206 status'
- })
- }
+ /**
+ * @param {(value: string, key: string, self: FormData) => void} callbackFn
+ * @param {unknown} thisArg
+ */
+ forEach (callbackFn, thisArg = globalThis) {
+ webidl.brandCheck(this, FormData)
- // 7.
- if (innerResponse.headersList.contains('vary')) {
- // 7.1.
- const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })
- // 7.2.
- for (const fieldValue of fieldValues) {
- // 7.2.1
- if (fieldValue === '*') {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Got * vary field value'
- })
- }
- }
+ if (typeof callbackFn !== 'function') {
+ throw new TypeError(
+ "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."
+ )
}
- // 8.
- if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Response body is locked or disturbed'
- })
+ for (const [key, value] of this) {
+ callbackFn.apply(thisArg, [value, key, this])
}
+ }
+}
- // 9.
- const clonedResponse = cloneResponse(innerResponse)
+FormData.prototype[Symbol.iterator] = FormData.prototype.entries
- // 10.
- const bodyReadPromise = createDeferredPromise()
+Object.defineProperties(FormData.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'FormData',
+ configurable: true
+ }
+})
- // 11.
- if (innerResponse.body != null) {
- // 11.1
- const stream = innerResponse.body.stream
+/**
+ * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
+ * @param {string} name
+ * @param {string|Blob} value
+ * @param {?string} filename
+ * @returns
+ */
+function makeEntry (name, value, filename) {
+ // 1. Set name to the result of converting name into a scalar value string.
+ // "To convert a string into a scalar value string, replace any surrogates
+ // with U+FFFD."
+ // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end
+ name = Buffer.from(name).toString('utf8')
- // 11.2
- const reader = stream.getReader()
+ // 2. If value is a string, then set value to the result of converting
+ // value into a scalar value string.
+ if (typeof value === 'string') {
+ value = Buffer.from(value).toString('utf8')
+ } else {
+ // 3. Otherwise:
- // 11.3
- readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
- } else {
- bodyReadPromise.resolve(undefined)
+ // 1. If value is not a File object, then set value to a new File object,
+ // representing the same bytes, whose name attribute value is "blob"
+ if (!isFileLike(value)) {
+ value = value instanceof Blob
+ ? new File([value], 'blob', { type: value.type })
+ : new FileLike(value, 'blob', { type: value.type })
}
- // 12.
- /** @type {CacheBatchOperation[]} */
- const operations = []
+ // 2. If filename is given, then set value to a new File object,
+ // representing the same bytes, whose name attribute is filename.
+ if (filename !== undefined) {
+ /** @type {FilePropertyBag} */
+ const options = {
+ type: value.type,
+ lastModified: value.lastModified
+ }
- // 13.
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'put', // 14.
- request: innerRequest, // 15.
- response: clonedResponse // 16.
+ value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile
+ ? new File([value], filename, options)
+ : new FileLike(value, filename, options)
}
+ }
- // 17.
- operations.push(operation)
-
- // 19.
- const bytes = await bodyReadPromise.promise
+ // 4. Return an entry whose name is name and whose value is value.
+ return { name, value }
+}
- if (clonedResponse.body != null) {
- clonedResponse.body.source = bytes
- }
+module.exports = { FormData }
- // 19.1
- const cacheJobPromise = createDeferredPromise()
- // 19.2.1
- let errorData = null
+/***/ }),
- // 19.2.2
- try {
- this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
- }
+/***/ 62896:
+/***/ ((module) => {
- // 19.2.3
- queueMicrotask(() => {
- // 19.2.3.1
- if (errorData === null) {
- cacheJobPromise.resolve()
- } else { // 19.2.3.2
- cacheJobPromise.reject(errorData)
- }
- })
- return cacheJobPromise.promise
- }
- async delete (request, options = {}) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })
+// In case of breaking changes, increase the version
+// number to avoid conflicts.
+const globalOrigin = Symbol.for('undici.globalOrigin.1')
- request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+function getGlobalOrigin () {
+ return globalThis[globalOrigin]
+}
- /**
- * @type {Request}
- */
- let r = null
+function setGlobalOrigin (newOrigin) {
+ if (newOrigin === undefined) {
+ Object.defineProperty(globalThis, globalOrigin, {
+ value: undefined,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
- if (request instanceof Request) {
- r = request[kState]
+ return
+ }
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return false
- }
- } else {
- assert(typeof request === 'string')
+ const parsedURL = new URL(newOrigin)
- r = new Request(request)[kState]
- }
+ if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
+ throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
+ }
- /** @type {CacheBatchOperation[]} */
- const operations = []
+ Object.defineProperty(globalThis, globalOrigin, {
+ value: parsedURL,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
+}
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'delete',
- request: r,
- options
- }
+module.exports = {
+ getGlobalOrigin,
+ setGlobalOrigin
+}
- operations.push(operation)
- const cacheJobPromise = createDeferredPromise()
+/***/ }),
- let errorData = null
- let requestResponses
+/***/ 12801:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- try {
- requestResponses = this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
- }
+// https://github.com/Ethan-Arrowood/undici-fetch
- queueMicrotask(() => {
- if (errorData === null) {
- cacheJobPromise.resolve(!!requestResponses?.length)
- } else {
- cacheJobPromise.reject(errorData)
- }
- })
- return cacheJobPromise.promise
- }
- /**
- * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
- * @param {any} request
- * @param {import('../../types/cache').CacheQueryOptions} options
- * @returns {readonly Request[]}
- */
- async keys (request = undefined, options = {}) {
- webidl.brandCheck(this, Cache)
+const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
+const { kGuard } = __nccwpck_require__(63730)
+const { kEnumerableProperty } = __nccwpck_require__(89500)
+const {
+ makeIterator,
+ isValidHeaderName,
+ isValidHeaderValue
+} = __nccwpck_require__(72847)
+const { webidl } = __nccwpck_require__(94354)
+const assert = __nccwpck_require__(42613)
- if (request !== undefined) request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+const kHeadersMap = Symbol('headers map')
+const kHeadersSortedMap = Symbol('headers map sorted')
- // 1.
- let r = null
+/**
+ * @param {number} code
+ */
+function isHTTPWhiteSpaceCharCode (code) {
+ return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
+}
- // 2.
- if (request !== undefined) {
- // 2.1
- if (request instanceof Request) {
- // 2.1.1
- r = request[kState]
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
+ * @param {string} potentialValue
+ */
+function headerValueNormalize (potentialValue) {
+ // To normalize a byte sequence potentialValue, remove
+ // any leading and trailing HTTP whitespace bytes from
+ // potentialValue.
+ let i = 0; let j = potentialValue.length
- // 2.1.2
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return []
- }
- } else if (typeof request === 'string') { // 2.2
- r = new Request(request)[kState]
- }
- }
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i
- // 4.
- const promise = createDeferredPromise()
+ return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)
+}
- // 5.
- // 5.1
- const requests = []
+function fill (headers, object) {
+ // To fill a Headers object headers with a given object object, run these steps:
- // 5.2
- if (request === undefined) {
- // 5.2.1
- for (const requestResponse of this.#relevantRequestResponseList) {
- // 5.2.1.1
- requests.push(requestResponse[0])
+ // 1. If object is a sequence, then for each header in object:
+ // Note: webidl conversion to array has already been done.
+ if (Array.isArray(object)) {
+ for (let i = 0; i < object.length; ++i) {
+ const header = object[i]
+ // 1. If header does not contain exactly two items, then throw a TypeError.
+ if (header.length !== 2) {
+ throw webidl.errors.exception({
+ header: 'Headers constructor',
+ message: `expected name/value pair to be length 2, found ${header.length}.`
+ })
}
- } else { // 5.3
- // 5.3.1
- const requestResponses = this.#queryCache(r, options)
- // 5.3.2
- for (const requestResponse of requestResponses) {
- // 5.3.2.1
- requests.push(requestResponse[0])
- }
+ // 2. Append (header’s first item, header’s second item) to headers.
+ appendHeader(headers, header[0], header[1])
}
+ } else if (typeof object === 'object' && object !== null) {
+ // Note: null should throw
- // 5.4
- queueMicrotask(() => {
- // 5.4.1
- const requestList = []
-
- // 5.4.2
- for (const request of requests) {
- const requestObject = new Request('https://a')
- requestObject[kState] = request
- requestObject[kHeaders][kHeadersList] = request.headersList
- requestObject[kHeaders][kGuard] = 'immutable'
- requestObject[kRealm] = request.client
+ // 2. Otherwise, object is a record, then for each key → value in object,
+ // append (key, value) to headers
+ const keys = Object.keys(object)
+ for (let i = 0; i < keys.length; ++i) {
+ appendHeader(headers, keys[i], object[keys[i]])
+ }
+ } else {
+ throw webidl.errors.conversionFailed({
+ prefix: 'Headers constructor',
+ argument: 'Argument 1',
+ types: ['sequence>', 'record']
+ })
+ }
+}
- // 5.4.2.1
- requestList.push(requestObject)
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-headers-append
+ */
+function appendHeader (headers, name, value) {
+ // 1. Normalize value.
+ value = headerValueNormalize(value)
- // 5.4.3
- promise.resolve(Object.freeze(requestList))
+ // 2. If name is not a header name or value is not a
+ // header value, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.append',
+ value: name,
+ type: 'header name'
+ })
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.append',
+ value,
+ type: 'header value'
})
+ }
- return promise.promise
+ // 3. If headers’s guard is "immutable", then throw a TypeError.
+ // 4. Otherwise, if headers’s guard is "request" and name is a
+ // forbidden header name, return.
+ // Note: undici does not implement forbidden header names
+ if (headers[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (headers[kGuard] === 'request-no-cors') {
+ // 5. Otherwise, if headers’s guard is "request-no-cors":
+ // TODO
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
- * @param {CacheBatchOperation[]} operations
- * @returns {requestResponseList}
- */
- #batchCacheOperations (operations) {
- // 1.
- const cache = this.#relevantRequestResponseList
+ // 6. Otherwise, if headers’s guard is "response" and name is a
+ // forbidden response-header name, return.
- // 2.
- const backupCache = [...cache]
+ // 7. Append (name, value) to headers’s header list.
+ return headers[kHeadersList].append(name, value)
- // 3.
- const addedItems = []
+ // 8. If headers’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from headers
+}
- // 4.1
- const resultList = []
+class HeadersList {
+ /** @type {[string, string][]|null} */
+ cookies = null
- try {
- // 4.2
- for (const operation of operations) {
- // 4.2.1
- if (operation.type !== 'delete' && operation.type !== 'put') {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'operation type does not match "delete" or "put"'
- })
- }
+ constructor (init) {
+ if (init instanceof HeadersList) {
+ this[kHeadersMap] = new Map(init[kHeadersMap])
+ this[kHeadersSortedMap] = init[kHeadersSortedMap]
+ this.cookies = init.cookies === null ? null : [...init.cookies]
+ } else {
+ this[kHeadersMap] = new Map(init)
+ this[kHeadersSortedMap] = null
+ }
+ }
- // 4.2.2
- if (operation.type === 'delete' && operation.response != null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'delete operation should not have an associated response'
- })
- }
+ // https://fetch.spec.whatwg.org/#header-list-contains
+ contains (name) {
+ // A header list list contains a header name name if list
+ // contains a header whose name is a byte-case-insensitive
+ // match for name.
+ name = name.toLowerCase()
- // 4.2.3
- if (this.#queryCache(operation.request, operation.options, addedItems).length) {
- throw new DOMException('???', 'InvalidStateError')
- }
+ return this[kHeadersMap].has(name)
+ }
- // 4.2.4
- let requestResponses
+ clear () {
+ this[kHeadersMap].clear()
+ this[kHeadersSortedMap] = null
+ this.cookies = null
+ }
- // 4.2.5
- if (operation.type === 'delete') {
- // 4.2.5.1
- requestResponses = this.#queryCache(operation.request, operation.options)
+ // https://fetch.spec.whatwg.org/#concept-header-list-append
+ append (name, value) {
+ this[kHeadersSortedMap] = null
- // TODO: the spec is wrong, this is needed to pass WPTs
- if (requestResponses.length === 0) {
- return []
- }
+ // 1. If list contains name, then set name to the first such
+ // header’s name.
+ const lowercaseName = name.toLowerCase()
+ const exists = this[kHeadersMap].get(lowercaseName)
- // 4.2.5.2
- for (const requestResponse of requestResponses) {
- const idx = cache.indexOf(requestResponse)
- assert(idx !== -1)
+ // 2. Append (name, value) to list.
+ if (exists) {
+ const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
+ this[kHeadersMap].set(lowercaseName, {
+ name: exists.name,
+ value: `${exists.value}${delimiter}${value}`
+ })
+ } else {
+ this[kHeadersMap].set(lowercaseName, { name, value })
+ }
- // 4.2.5.2.1
- cache.splice(idx, 1)
- }
- } else if (operation.type === 'put') { // 4.2.6
- // 4.2.6.1
- if (operation.response == null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'put operation should have an associated response'
- })
- }
+ if (lowercaseName === 'set-cookie') {
+ this.cookies ??= []
+ this.cookies.push(value)
+ }
+ }
- // 4.2.6.2
- const r = operation.request
+ // https://fetch.spec.whatwg.org/#concept-header-list-set
+ set (name, value) {
+ this[kHeadersSortedMap] = null
+ const lowercaseName = name.toLowerCase()
- // 4.2.6.3
- if (!urlIsHttpHttpsScheme(r.url)) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'expected http or https scheme'
- })
- }
+ if (lowercaseName === 'set-cookie') {
+ this.cookies = [value]
+ }
- // 4.2.6.4
- if (r.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'not get method'
- })
- }
+ // 1. If list contains name, then set the value of
+ // the first such header to value and remove the
+ // others.
+ // 2. Otherwise, append header (name, value) to list.
+ this[kHeadersMap].set(lowercaseName, { name, value })
+ }
- // 4.2.6.5
- if (operation.options != null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'options must not be defined'
- })
- }
+ // https://fetch.spec.whatwg.org/#concept-header-list-delete
+ delete (name) {
+ this[kHeadersSortedMap] = null
- // 4.2.6.6
- requestResponses = this.#queryCache(operation.request)
+ name = name.toLowerCase()
- // 4.2.6.7
- for (const requestResponse of requestResponses) {
- const idx = cache.indexOf(requestResponse)
- assert(idx !== -1)
+ if (name === 'set-cookie') {
+ this.cookies = null
+ }
- // 4.2.6.7.1
- cache.splice(idx, 1)
- }
+ this[kHeadersMap].delete(name)
+ }
- // 4.2.6.8
- cache.push([operation.request, operation.response])
+ // https://fetch.spec.whatwg.org/#concept-header-list-get
+ get (name) {
+ const value = this[kHeadersMap].get(name.toLowerCase())
- // 4.2.6.10
- addedItems.push([operation.request, operation.response])
- }
+ // 1. If list does not contain name, then return null.
+ // 2. Return the values of all headers in list whose name
+ // is a byte-case-insensitive match for name,
+ // separated from each other by 0x2C 0x20, in order.
+ return value === undefined ? null : value.value
+ }
- // 4.2.7
- resultList.push([operation.request, operation.response])
+ * [Symbol.iterator] () {
+ // use the lowercased name
+ for (const [name, { value }] of this[kHeadersMap]) {
+ yield [name, value]
+ }
+ }
+
+ get entries () {
+ const headers = {}
+
+ if (this[kHeadersMap].size) {
+ for (const { name, value } of this[kHeadersMap].values()) {
+ headers[name] = value
}
+ }
- // 4.3
- return resultList
- } catch (e) { // 5.
- // 5.1
- this.#relevantRequestResponseList.length = 0
+ return headers
+ }
+}
- // 5.2
- this.#relevantRequestResponseList = backupCache
+// https://fetch.spec.whatwg.org/#headers-class
+class Headers {
+ constructor (init = undefined) {
+ if (init === kConstruct) {
+ return
+ }
+ this[kHeadersList] = new HeadersList()
- // 5.3
- throw e
+ // The new Headers(init) constructor steps are:
+
+ // 1. Set this’s guard to "none".
+ this[kGuard] = 'none'
+
+ // 2. If init is given, then fill this with init.
+ if (init !== undefined) {
+ init = webidl.converters.HeadersInit(init)
+ fill(this, init)
}
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#query-cache
- * @param {any} requestQuery
- * @param {import('../../types/cache').CacheQueryOptions} options
- * @param {requestResponseList} targetStorage
- * @returns {requestResponseList}
- */
- #queryCache (requestQuery, options, targetStorage) {
- /** @type {requestResponseList} */
- const resultList = []
+ // https://fetch.spec.whatwg.org/#dom-headers-append
+ append (name, value) {
+ webidl.brandCheck(this, Headers)
- const storage = targetStorage ?? this.#relevantRequestResponseList
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })
- for (const requestResponse of storage) {
- const [cachedRequest, cachedResponse] = requestResponse
- if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
- resultList.push(requestResponse)
- }
- }
+ name = webidl.converters.ByteString(name)
+ value = webidl.converters.ByteString(value)
- return resultList
+ return appendHeader(this, name, value)
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
- * @param {any} requestQuery
- * @param {any} request
- * @param {any | null} response
- * @param {import('../../types/cache').CacheQueryOptions | undefined} options
- * @returns {boolean}
- */
- #requestMatchesCachedItem (requestQuery, request, response = null, options) {
- // if (options?.ignoreMethod === false && request.method === 'GET') {
- // return false
- // }
-
- const queryURL = new URL(requestQuery.url)
+ // https://fetch.spec.whatwg.org/#dom-headers-delete
+ delete (name) {
+ webidl.brandCheck(this, Headers)
- const cachedURL = new URL(request.url)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })
- if (options?.ignoreSearch) {
- cachedURL.search = ''
+ name = webidl.converters.ByteString(name)
- queryURL.search = ''
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.delete',
+ value: name,
+ type: 'header name'
+ })
}
- if (!urlEquals(queryURL, cachedURL, true)) {
- return false
+ // 2. If this’s guard is "immutable", then throw a TypeError.
+ // 3. Otherwise, if this’s guard is "request" and name is a
+ // forbidden header name, return.
+ // 4. Otherwise, if this’s guard is "request-no-cors", name
+ // is not a no-CORS-safelisted request-header name, and
+ // name is not a privileged no-CORS request-header name,
+ // return.
+ // 5. Otherwise, if this’s guard is "response" and name is
+ // a forbidden response-header name, return.
+ // Note: undici does not implement forbidden header names
+ if (this[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (this[kGuard] === 'request-no-cors') {
+ // TODO
}
- if (
- response == null ||
- options?.ignoreVary ||
- !response.headersList.contains('vary')
- ) {
- return true
+ // 6. If this’s header list does not contain name, then
+ // return.
+ if (!this[kHeadersList].contains(name)) {
+ return
}
- const fieldValues = getFieldValues(response.headersList.get('vary'))
+ // 7. Delete name from this’s header list.
+ // 8. If this’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from this.
+ this[kHeadersList].delete(name)
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-headers-get
+ get (name) {
+ webidl.brandCheck(this, Headers)
- for (const fieldValue of fieldValues) {
- if (fieldValue === '*') {
- return false
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })
- const requestValue = request.headersList.get(fieldValue)
- const queryValue = requestQuery.headersList.get(fieldValue)
+ name = webidl.converters.ByteString(name)
- // If one has the header and the other doesn't, or one has
- // a different value than the other, return false
- if (requestValue !== queryValue) {
- return false
- }
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.get',
+ value: name,
+ type: 'header name'
+ })
}
- return true
+ // 2. Return the result of getting name from this’s header
+ // list.
+ return this[kHeadersList].get(name)
}
-}
-Object.defineProperties(Cache.prototype, {
- [Symbol.toStringTag]: {
- value: 'Cache',
- configurable: true
- },
- match: kEnumerableProperty,
- matchAll: kEnumerableProperty,
- add: kEnumerableProperty,
- addAll: kEnumerableProperty,
- put: kEnumerableProperty,
- delete: kEnumerableProperty,
- keys: kEnumerableProperty
-})
+ // https://fetch.spec.whatwg.org/#dom-headers-has
+ has (name) {
+ webidl.brandCheck(this, Headers)
-const cacheQueryOptionConverters = [
- {
- key: 'ignoreSearch',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'ignoreMethod',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'ignoreVary',
- converter: webidl.converters.boolean,
- defaultValue: false
- }
-]
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })
-webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
+ name = webidl.converters.ByteString(name)
-webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
- ...cacheQueryOptionConverters,
- {
- key: 'cacheName',
- converter: webidl.converters.DOMString
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.has',
+ value: name,
+ type: 'header name'
+ })
+ }
+
+ // 2. Return true if this’s header list contains name;
+ // otherwise false.
+ return this[kHeadersList].contains(name)
}
-])
-webidl.converters.Response = webidl.interfaceConverter(Response)
+ // https://fetch.spec.whatwg.org/#dom-headers-set
+ set (name, value) {
+ webidl.brandCheck(this, Headers)
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.RequestInfo
-)
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })
-module.exports = {
- Cache
-}
+ name = webidl.converters.ByteString(name)
+ value = webidl.converters.ByteString(value)
+ // 1. Normalize value.
+ value = headerValueNormalize(value)
-/***/ }),
+ // 2. If name is not a header name or value is not a
+ // header value, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.set',
+ value: name,
+ type: 'header name'
+ })
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.set',
+ value,
+ type: 'header value'
+ })
+ }
-/***/ 66446:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 3. If this’s guard is "immutable", then throw a TypeError.
+ // 4. Otherwise, if this’s guard is "request" and name is a
+ // forbidden header name, return.
+ // 5. Otherwise, if this’s guard is "request-no-cors" and
+ // name/value is not a no-CORS-safelisted request-header,
+ // return.
+ // 6. Otherwise, if this’s guard is "response" and name is a
+ // forbidden response-header name, return.
+ // Note: undici does not implement forbidden header names
+ if (this[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (this[kGuard] === 'request-no-cors') {
+ // TODO
+ }
+ // 7. Set (name, value) in this’s header list.
+ // 8. If this’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from this
+ this[kHeadersList].set(name, value)
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
+ getSetCookie () {
+ webidl.brandCheck(this, Headers)
-const { kConstruct } = __nccwpck_require__(68652)
-const { Cache } = __nccwpck_require__(40611)
-const { webidl } = __nccwpck_require__(94354)
-const { kEnumerableProperty } = __nccwpck_require__(89500)
+ // 1. If this’s header list does not contain `Set-Cookie`, then return « ».
+ // 2. Return the values of all headers in this’s header list whose name is
+ // a byte-case-insensitive match for `Set-Cookie`, in order.
-class CacheStorage {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
- * @type {Map a[0] < b[0] ? -1 : 1)
+ const cookies = this[kHeadersList].cookies
- // 2.2.1.2
- const response = await cache.match(request, options)
+ // 3. For each name of names:
+ for (let i = 0; i < names.length; ++i) {
+ const [name, value] = names[i]
+ // 1. If name is `set-cookie`, then:
+ if (name === 'set-cookie') {
+ // 1. Let values be a list of all values of headers in list whose name
+ // is a byte-case-insensitive match for name, in order.
- if (response !== undefined) {
- return response
+ // 2. For each value of values:
+ // 1. Append (name, value) to headers.
+ for (let j = 0; j < cookies.length; ++j) {
+ headers.push([name, cookies[j]])
}
+ } else {
+ // 2. Otherwise:
+
+ // 1. Let value be the result of getting name from list.
+
+ // 2. Assert: value is non-null.
+ assert(value !== null)
+
+ // 3. Append (name, value) to headers.
+ headers.push([name, value])
}
}
- }
-
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-has
- * @param {string} cacheName
- * @returns {Promise}
- */
- async has (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })
- cacheName = webidl.converters.DOMString(cacheName)
+ this[kHeadersList][kHeadersSortedMap] = headers
- // 2.1.1
- // 2.2
- return this.#caches.has(cacheName)
+ // 4. Return headers.
+ return headers
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
- * @param {string} cacheName
- * @returns {Promise}
- */
- async open (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })
+ keys () {
+ webidl.brandCheck(this, Headers)
- cacheName = webidl.converters.DOMString(cacheName)
+ if (this[kGuard] === 'immutable') {
+ const value = this[kHeadersSortedMap]
+ return makeIterator(() => value, 'Headers',
+ 'key')
+ }
- // 2.1
- if (this.#caches.has(cacheName)) {
- // await caches.open('v1') !== await caches.open('v1')
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'key'
+ )
+ }
- // 2.1.1
- const cache = this.#caches.get(cacheName)
+ values () {
+ webidl.brandCheck(this, Headers)
- // 2.1.1.1
- return new Cache(kConstruct, cache)
+ if (this[kGuard] === 'immutable') {
+ const value = this[kHeadersSortedMap]
+ return makeIterator(() => value, 'Headers',
+ 'value')
}
- // 2.2
- const cache = []
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'value'
+ )
+ }
- // 2.3
- this.#caches.set(cacheName, cache)
+ entries () {
+ webidl.brandCheck(this, Headers)
- // 2.4
- return new Cache(kConstruct, cache)
+ if (this[kGuard] === 'immutable') {
+ const value = this[kHeadersSortedMap]
+ return makeIterator(() => value, 'Headers',
+ 'key+value')
+ }
+
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'key+value'
+ )
}
/**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
- * @param {string} cacheName
- * @returns {Promise}
+ * @param {(value: string, key: string, self: Headers) => void} callbackFn
+ * @param {unknown} thisArg
*/
- async delete (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })
+ forEach (callbackFn, thisArg = globalThis) {
+ webidl.brandCheck(this, Headers)
- cacheName = webidl.converters.DOMString(cacheName)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })
- return this.#caches.delete(cacheName)
- }
+ if (typeof callbackFn !== 'function') {
+ throw new TypeError(
+ "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
+ )
+ }
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
- * @returns {string[]}
- */
- async keys () {
- webidl.brandCheck(this, CacheStorage)
+ for (const [key, value] of this) {
+ callbackFn.apply(thisArg, [value, key, this])
+ }
+ }
- // 2.1
- const keys = this.#caches.keys()
+ [Symbol.for('nodejs.util.inspect.custom')] () {
+ webidl.brandCheck(this, Headers)
- // 2.2
- return [...keys]
+ return this[kHeadersList]
}
}
-Object.defineProperties(CacheStorage.prototype, {
+Headers.prototype[Symbol.iterator] = Headers.prototype.entries
+
+Object.defineProperties(Headers.prototype, {
+ append: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ get: kEnumerableProperty,
+ has: kEnumerableProperty,
+ set: kEnumerableProperty,
+ getSetCookie: kEnumerableProperty,
+ keys: kEnumerableProperty,
+ values: kEnumerableProperty,
+ entries: kEnumerableProperty,
+ forEach: kEnumerableProperty,
+ [Symbol.iterator]: { enumerable: false },
[Symbol.toStringTag]: {
- value: 'CacheStorage',
+ value: 'Headers',
configurable: true
- },
- match: kEnumerableProperty,
- has: kEnumerableProperty,
- open: kEnumerableProperty,
- delete: kEnumerableProperty,
- keys: kEnumerableProperty
+ }
})
-module.exports = {
- CacheStorage
-}
-
-
-/***/ }),
-
-/***/ 68652:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+webidl.converters.HeadersInit = function (V) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (V[Symbol.iterator]) {
+ return webidl.converters['sequence>'](V)
+ }
+ return webidl.converters['record'](V)
+ }
+ throw webidl.errors.conversionFailed({
+ prefix: 'Headers constructor',
+ argument: 'Argument 1',
+ types: ['sequence>', 'record']
+ })
+}
module.exports = {
- kConstruct: (__nccwpck_require__(68031).kConstruct)
+ fill,
+ Headers,
+ HeadersList
}
/***/ }),
-/***/ 71173:
+/***/ 11503:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// https://github.com/Ethan-Arrowood/undici-fetch
+
+const {
+ Response,
+ makeNetworkError,
+ makeAppropriateNetworkError,
+ filterResponse,
+ makeResponse
+} = __nccwpck_require__(89928)
+const { Headers } = __nccwpck_require__(12801)
+const { Request, makeRequest } = __nccwpck_require__(2630)
+const zlib = __nccwpck_require__(43106)
+const {
+ bytesMatch,
+ makePolicyContainer,
+ clonePolicyContainer,
+ requestBadPort,
+ TAOCheck,
+ appendRequestOriginHeader,
+ responseLocationURL,
+ requestCurrentURL,
+ setRequestReferrerPolicyOnRedirect,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ createOpaqueTimingInfo,
+ appendFetchMetadata,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ determineRequestsReferrer,
+ coarsenedSharedCurrentTime,
+ createDeferredPromise,
+ isBlobLike,
+ sameOrigin,
+ isCancelled,
+ isAborted,
+ isErrorLike,
+ fullyReadBody,
+ readableStreamClose,
+ isomorphicEncode,
+ urlIsLocal,
+ urlIsHttpHttpsScheme,
+ urlHasHttpsScheme
+} = __nccwpck_require__(72847)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
const assert = __nccwpck_require__(42613)
-const { URLSerializer } = __nccwpck_require__(37246)
-const { isValidHeaderName } = __nccwpck_require__(72847)
+const { safelyExtractBody } = __nccwpck_require__(37791)
+const {
+ redirectStatusSet,
+ nullBodyStatus,
+ safeMethodsSet,
+ requestBodyHeader,
+ subresourceSet,
+ DOMException
+} = __nccwpck_require__(21234)
+const { kHeadersList } = __nccwpck_require__(68031)
+const EE = __nccwpck_require__(24434)
+const { Readable, pipeline } = __nccwpck_require__(2203)
+const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(89500)
+const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(37246)
+const { TransformStream } = __nccwpck_require__(63774)
+const { getGlobalDispatcher } = __nccwpck_require__(61481)
+const { webidl } = __nccwpck_require__(94354)
+const { STATUS_CODES } = __nccwpck_require__(58611)
+const GET_OR_HEAD = ['GET', 'HEAD']
-/**
- * @see https://url.spec.whatwg.org/#concept-url-equals
- * @param {URL} A
- * @param {URL} B
- * @param {boolean | undefined} excludeFragment
- * @returns {boolean}
- */
-function urlEquals (A, B, excludeFragment = false) {
- const serializedA = URLSerializer(A, excludeFragment)
+/** @type {import('buffer').resolveObjectURL} */
+let resolveObjectURL
+let ReadableStream = globalThis.ReadableStream
- const serializedB = URLSerializer(B, excludeFragment)
+class Fetch extends EE {
+ constructor (dispatcher) {
+ super()
- return serializedA === serializedB
-}
+ this.dispatcher = dispatcher
+ this.connection = null
+ this.dump = false
+ this.state = 'ongoing'
+ // 2 terminated listeners get added per request,
+ // but only 1 gets removed. If there are 20 redirects,
+ // 21 listeners will be added.
+ // See https://github.com/nodejs/undici/issues/1711
+ // TODO (fix): Find and fix root cause for leaked listener.
+ this.setMaxListeners(21)
+ }
-/**
- * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
- * @param {string} header
- */
-function fieldValues (header) {
- assert(header !== null)
+ terminate (reason) {
+ if (this.state !== 'ongoing') {
+ return
+ }
- const values = []
+ this.state = 'terminated'
+ this.connection?.destroy(reason)
+ this.emit('terminated', reason)
+ }
- for (let value of header.split(',')) {
- value = value.trim()
+ // https://fetch.spec.whatwg.org/#fetch-controller-abort
+ abort (error) {
+ if (this.state !== 'ongoing') {
+ return
+ }
- if (!value.length) {
- continue
- } else if (!isValidHeaderName(value)) {
- continue
+ // 1. Set controller’s state to "aborted".
+ this.state = 'aborted'
+
+ // 2. Let fallbackError be an "AbortError" DOMException.
+ // 3. Set error to fallbackError if it is not given.
+ if (!error) {
+ error = new DOMException('The operation was aborted.', 'AbortError')
}
- values.push(value)
- }
+ // 4. Let serializedError be StructuredSerialize(error).
+ // If that threw an exception, catch it, and let
+ // serializedError be StructuredSerialize(fallbackError).
- return values
-}
+ // 5. Set controller’s serialized abort reason to serializedError.
+ this.serializedAbortReason = error
-module.exports = {
- urlEquals,
- fieldValues
+ this.connection?.destroy(error)
+ this.emit('terminated', error)
+ }
}
+// https://fetch.spec.whatwg.org/#fetch-method
+function fetch (input, init = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
-/***/ }),
-
-/***/ 45513:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 1. Let p be a new promise.
+ const p = createDeferredPromise()
-// @ts-check
+ // 2. Let requestObject be the result of invoking the initial value of
+ // Request as constructor with input and init as arguments. If this throws
+ // an exception, reject p with it and return p.
+ let requestObject
+ try {
+ requestObject = new Request(input, init)
+ } catch (e) {
+ p.reject(e)
+ return p.promise
+ }
+ // 3. Let request be requestObject’s request.
+ const request = requestObject[kState]
-/* global WebAssembly */
+ // 4. If requestObject’s signal’s aborted flag is set, then:
+ if (requestObject.signal.aborted) {
+ // 1. Abort the fetch() call with p, request, null, and
+ // requestObject’s signal’s abort reason.
+ abortFetch(p, request, null, requestObject.signal.reason)
-const assert = __nccwpck_require__(42613)
-const net = __nccwpck_require__(69278)
-const http = __nccwpck_require__(58611)
-const { pipeline } = __nccwpck_require__(2203)
-const util = __nccwpck_require__(89500)
-const timers = __nccwpck_require__(82576)
-const Request = __nccwpck_require__(69691)
-const DispatcherBase = __nccwpck_require__(52421)
-const {
- RequestContentLengthMismatchError,
- ResponseContentLengthMismatchError,
- InvalidArgumentError,
- RequestAbortedError,
- HeadersTimeoutError,
- HeadersOverflowError,
- SocketError,
- InformationalError,
- BodyTimeoutError,
- HTTPParserError,
- ResponseExceededMaxSizeError,
- ClientDestroyedError
-} = __nccwpck_require__(53959)
-const buildConnector = __nccwpck_require__(91332)
-const {
- kUrl,
- kReset,
- kServerName,
- kClient,
- kBusy,
- kParser,
- kConnect,
- kBlocking,
- kResuming,
- kRunning,
- kPending,
- kSize,
- kWriting,
- kQueue,
- kConnected,
- kConnecting,
- kNeedDrain,
- kNoRef,
- kKeepAliveDefaultTimeout,
- kHostHeader,
- kPendingIdx,
- kRunningIdx,
- kError,
- kPipelining,
- kSocket,
- kKeepAliveTimeoutValue,
- kMaxHeadersSize,
- kKeepAliveMaxTimeout,
- kKeepAliveTimeoutThreshold,
- kHeadersTimeout,
- kBodyTimeout,
- kStrictContentLength,
- kConnector,
- kMaxRedirections,
- kMaxRequests,
- kCounter,
- kClose,
- kDestroy,
- kDispatch,
- kInterceptors,
- kLocalAddress,
- kMaxResponseSize,
- kHTTPConnVersion,
- // HTTP2
- kHost,
- kHTTP2Session,
- kHTTP2SessionState,
- kHTTP2BuildRequest,
- kHTTP2CopyHeaders,
- kHTTP1BuildRequest
-} = __nccwpck_require__(68031)
+ // 2. Return p.
+ return p.promise
+ }
-/** @type {import('http2')} */
-let http2
-try {
- http2 = __nccwpck_require__(85675)
-} catch {
- // @ts-ignore
- http2 = { constants: {} }
-}
+ // 5. Let globalObject be request’s client’s global object.
+ const globalObject = request.client.globalObject
-const {
- constants: {
- HTTP2_HEADER_AUTHORITY,
- HTTP2_HEADER_METHOD,
- HTTP2_HEADER_PATH,
- HTTP2_HEADER_SCHEME,
- HTTP2_HEADER_CONTENT_LENGTH,
- HTTP2_HEADER_EXPECT,
- HTTP2_HEADER_STATUS
+ // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
+ // request’s service-workers mode to "none".
+ if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
+ request.serviceWorkers = 'none'
}
-} = http2
-// Experimental
-let h2ExperimentalWarned = false
+ // 7. Let responseObject be null.
+ let responseObject = null
-const FastBuffer = Buffer[Symbol.species]
+ // 8. Let relevantRealm be this’s relevant Realm.
+ const relevantRealm = null
-const kClosedResolve = Symbol('kClosedResolve')
+ // 9. Let locallyAborted be false.
+ let locallyAborted = false
-const channels = {}
+ // 10. Let controller be null.
+ let controller = null
-try {
- const diagnosticsChannel = __nccwpck_require__(31637)
- channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')
- channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')
- channels.connectError = diagnosticsChannel.channel('undici:client:connectError')
- channels.connected = diagnosticsChannel.channel('undici:client:connected')
-} catch {
- channels.sendHeaders = { hasSubscribers: false }
- channels.beforeConnect = { hasSubscribers: false }
- channels.connectError = { hasSubscribers: false }
- channels.connected = { hasSubscribers: false }
-}
+ // 11. Add the following abort steps to requestObject’s signal:
+ addAbortListener(
+ requestObject.signal,
+ () => {
+ // 1. Set locallyAborted to true.
+ locallyAborted = true
-/**
- * @type {import('../types/client').default}
- */
-class Client extends DispatcherBase {
- /**
- *
- * @param {string|URL} url
- * @param {import('../types/client').Client.Options} options
- */
- constructor (url, {
- interceptors,
- maxHeaderSize,
- headersTimeout,
- socketTimeout,
- requestTimeout,
- connectTimeout,
- bodyTimeout,
- idleTimeout,
- keepAlive,
- keepAliveTimeout,
- maxKeepAliveTimeout,
- keepAliveMaxTimeout,
- keepAliveTimeoutThreshold,
- socketPath,
- pipelining,
- tls,
- strictContentLength,
- maxCachedSessions,
- maxRedirections,
- connect,
- maxRequestsPerClient,
- localAddress,
- maxResponseSize,
- autoSelectFamily,
- autoSelectFamilyAttemptTimeout,
- // h2
- allowH2,
- maxConcurrentStreams
- } = {}) {
- super()
+ // 2. Assert: controller is non-null.
+ assert(controller != null)
- if (keepAlive !== undefined) {
- throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
- }
+ // 3. Abort controller with requestObject’s signal’s abort reason.
+ controller.abort(requestObject.signal.reason)
- if (socketTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
+ // 4. Abort the fetch() call with p, request, responseObject,
+ // and requestObject’s signal’s abort reason.
+ abortFetch(p, request, responseObject, requestObject.signal.reason)
}
+ )
- if (requestTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
- }
+ // 12. Let handleFetchDone given response response be to finalize and
+ // report timing with response, globalObject, and "fetch".
+ const handleFetchDone = (response) =>
+ finalizeAndReportTiming(response, 'fetch')
- if (idleTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
- }
+ // 13. Set controller to the result of calling fetch given request,
+ // with processResponseEndOfBody set to handleFetchDone, and processResponse
+ // given response being these substeps:
- if (maxKeepAliveTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
+ const processResponse = (response) => {
+ // 1. If locallyAborted is true, terminate these substeps.
+ if (locallyAborted) {
+ return Promise.resolve()
}
- if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
- throw new InvalidArgumentError('invalid maxHeaderSize')
- }
+ // 2. If response’s aborted flag is set, then:
+ if (response.aborted) {
+ // 1. Let deserializedError be the result of deserialize a serialized
+ // abort reason given controller’s serialized abort reason and
+ // relevantRealm.
- if (socketPath != null && typeof socketPath !== 'string') {
- throw new InvalidArgumentError('invalid socketPath')
- }
+ // 2. Abort the fetch() call with p, request, responseObject, and
+ // deserializedError.
- if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
- throw new InvalidArgumentError('invalid connectTimeout')
+ abortFetch(p, request, responseObject, controller.serializedAbortReason)
+ return Promise.resolve()
}
- if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
- throw new InvalidArgumentError('invalid keepAliveTimeout')
+ // 3. If response is a network error, then reject p with a TypeError
+ // and terminate these substeps.
+ if (response.type === 'error') {
+ p.reject(
+ Object.assign(new TypeError('fetch failed'), { cause: response.error })
+ )
+ return Promise.resolve()
}
- if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
- throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
- }
+ // 4. Set responseObject to the result of creating a Response object,
+ // given response, "immutable", and relevantRealm.
+ responseObject = new Response()
+ responseObject[kState] = response
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kHeadersList] = response.headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
- if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
- throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
- }
+ // 5. Resolve p with responseObject.
+ p.resolve(responseObject)
+ }
- if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
- }
+ controller = fetching({
+ request,
+ processResponseEndOfBody: handleFetchDone,
+ processResponse,
+ dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
+ })
- if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
- }
+ // 14. Return p.
+ return p.promise
+}
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
- }
+// https://fetch.spec.whatwg.org/#finalize-and-report-timing
+function finalizeAndReportTiming (response, initiatorType = 'other') {
+ // 1. If response is an aborted network error, then return.
+ if (response.type === 'error' && response.aborted) {
+ return
+ }
- if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
+ // 2. If response’s URL list is null or empty, then return.
+ if (!response.urlList?.length) {
+ return
+ }
- if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
- throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
- }
+ // 3. Let originalURL be response’s URL list[0].
+ const originalURL = response.urlList[0]
- if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
- throw new InvalidArgumentError('localAddress must be valid string IP address')
- }
+ // 4. Let timingInfo be response’s timing info.
+ let timingInfo = response.timingInfo
- if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
- throw new InvalidArgumentError('maxResponseSize must be a positive number')
- }
+ // 5. Let cacheState be response’s cache state.
+ let cacheState = response.cacheState
- if (
- autoSelectFamilyAttemptTimeout != null &&
- (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
- ) {
- throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
- }
+ // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
+ if (!urlIsHttpHttpsScheme(originalURL)) {
+ return
+ }
- // h2
- if (allowH2 != null && typeof allowH2 !== 'boolean') {
- throw new InvalidArgumentError('allowH2 must be a valid boolean value')
- }
+ // 7. If timingInfo is null, then return.
+ if (timingInfo === null) {
+ return
+ }
- if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
- throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')
- }
+ // 8. If response’s timing allow passed flag is not set, then:
+ if (!response.timingAllowPassed) {
+ // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
+ timingInfo = createOpaqueTimingInfo({
+ startTime: timingInfo.startTime
+ })
- if (typeof connect !== 'function') {
- connect = buildConnector({
- ...tls,
- maxCachedSessions,
- allowH2,
- socketPath,
- timeout: connectTimeout,
- ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
- ...connect
- })
- }
+ // 2. Set cacheState to the empty string.
+ cacheState = ''
+ }
- this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)
- ? interceptors.Client
- : [createRedirectInterceptor({ maxRedirections })]
- this[kUrl] = util.parseOrigin(url)
- this[kConnector] = connect
- this[kSocket] = null
- this[kPipelining] = pipelining != null ? pipelining : 1
- this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
- this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
- this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
- this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold
- this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
- this[kServerName] = null
- this[kLocalAddress] = localAddress != null ? localAddress : null
- this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
- this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
- this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
- this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
- this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
- this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
- this[kMaxRedirections] = maxRedirections
- this[kMaxRequests] = maxRequestsPerClient
- this[kClosedResolve] = null
- this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
- this[kHTTPConnVersion] = 'h1'
+ // 9. Set timingInfo’s end time to the coarsened shared current time
+ // given global’s relevant settings object’s cross-origin isolated
+ // capability.
+ // TODO: given global’s relevant settings object’s cross-origin isolated
+ // capability?
+ timingInfo.endTime = coarsenedSharedCurrentTime()
- // HTTP/2
- this[kHTTP2Session] = null
- this[kHTTP2SessionState] = !allowH2
- ? null
- : {
- // streams: null, // Fixed queue of streams - For future support of `push`
- openStreams: 0, // Keep track of them to decide wether or not unref the session
- maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
- }
- this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`
+ // 10. Set response’s timing info to timingInfo.
+ response.timingInfo = timingInfo
- // kQueue is built up of 3 sections separated by
- // the kRunningIdx and kPendingIdx indices.
- // | complete | running | pending |
- // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
- // kRunningIdx points to the first running element.
- // kPendingIdx points to the first pending element.
- // This implements a fast queue with an amortized
- // time of O(1).
+ // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
+ // global, and cacheState.
+ markResourceTiming(
+ timingInfo,
+ originalURL,
+ initiatorType,
+ globalThis,
+ cacheState
+ )
+}
- this[kQueue] = []
- this[kRunningIdx] = 0
- this[kPendingIdx] = 0
+// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
+function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {
+ if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {
+ performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)
}
+}
- get pipelining () {
- return this[kPipelining]
+// https://fetch.spec.whatwg.org/#abort-fetch
+function abortFetch (p, request, responseObject, error) {
+ // Note: AbortSignal.reason was added in node v17.2.0
+ // which would give us an undefined error to reject with.
+ // Remove this once node v16 is no longer supported.
+ if (!error) {
+ error = new DOMException('The operation was aborted.', 'AbortError')
}
- set pipelining (value) {
- this[kPipelining] = value
- resume(this, true)
+ // 1. Reject promise with error.
+ p.reject(error)
+
+ // 2. If request’s body is not null and is readable, then cancel request’s
+ // body with error.
+ if (request.body != null && isReadable(request.body?.stream)) {
+ request.body.stream.cancel(error).catch((err) => {
+ if (err.code === 'ERR_INVALID_STATE') {
+ // Node bug?
+ return
+ }
+ throw err
+ })
+ }
+
+ // 3. If responseObject is null, then return.
+ if (responseObject == null) {
+ return
+ }
+
+ // 4. Let response be responseObject’s response.
+ const response = responseObject[kState]
+
+ // 5. If response’s body is not null and is readable, then error response’s
+ // body with error.
+ if (response.body != null && isReadable(response.body?.stream)) {
+ response.body.stream.cancel(error).catch((err) => {
+ if (err.code === 'ERR_INVALID_STATE') {
+ // Node bug?
+ return
+ }
+ throw err
+ })
+ }
+}
+
+// https://fetch.spec.whatwg.org/#fetching
+function fetching ({
+ request,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseEndOfBody,
+ processResponseConsumeBody,
+ useParallelQueue = false,
+ dispatcher // undici
+}) {
+ // 1. Let taskDestination be null.
+ let taskDestination = null
+
+ // 2. Let crossOriginIsolatedCapability be false.
+ let crossOriginIsolatedCapability = false
+
+ // 3. If request’s client is non-null, then:
+ if (request.client != null) {
+ // 1. Set taskDestination to request’s client’s global object.
+ taskDestination = request.client.globalObject
+
+ // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
+ // isolated capability.
+ crossOriginIsolatedCapability =
+ request.client.crossOriginIsolatedCapability
}
- get [kPending] () {
- return this[kQueue].length - this[kPendingIdx]
- }
+ // 4. If useParallelQueue is true, then set taskDestination to the result of
+ // starting a new parallel queue.
+ // TODO
- get [kRunning] () {
- return this[kPendingIdx] - this[kRunningIdx]
- }
+ // 5. Let timingInfo be a new fetch timing info whose start time and
+ // post-redirect start time are the coarsened shared current time given
+ // crossOriginIsolatedCapability.
+ const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
+ const timingInfo = createOpaqueTimingInfo({
+ startTime: currenTime
+ })
- get [kSize] () {
- return this[kQueue].length - this[kRunningIdx]
+ // 6. Let fetchParams be a new fetch params whose
+ // request is request,
+ // timing info is timingInfo,
+ // process request body chunk length is processRequestBodyChunkLength,
+ // process request end-of-body is processRequestEndOfBody,
+ // process response is processResponse,
+ // process response consume body is processResponseConsumeBody,
+ // process response end-of-body is processResponseEndOfBody,
+ // task destination is taskDestination,
+ // and cross-origin isolated capability is crossOriginIsolatedCapability.
+ const fetchParams = {
+ controller: new Fetch(dispatcher),
+ request,
+ timingInfo,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseConsumeBody,
+ processResponseEndOfBody,
+ taskDestination,
+ crossOriginIsolatedCapability
}
- get [kConnected] () {
- return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed
- }
+ // 7. If request’s body is a byte sequence, then set request’s body to
+ // request’s body as a body.
+ // NOTE: Since fetching is only called from fetch, body should already be
+ // extracted.
+ assert(!request.body || request.body.stream)
- get [kBusy] () {
- const socket = this[kSocket]
- return (
- (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||
- (this[kSize] >= (this[kPipelining] || 1)) ||
- this[kPending] > 0
- )
+ // 8. If request’s window is "client", then set request’s window to request’s
+ // client, if request’s client’s global object is a Window object; otherwise
+ // "no-window".
+ if (request.window === 'client') {
+ // TODO: What if request.client is null?
+ request.window =
+ request.client?.globalObject?.constructor?.name === 'Window'
+ ? request.client
+ : 'no-window'
}
- /* istanbul ignore: only used for test */
- [kConnect] (cb) {
- connect(this)
- this.once('connect', cb)
+ // 9. If request’s origin is "client", then set request’s origin to request’s
+ // client’s origin.
+ if (request.origin === 'client') {
+ // TODO: What if request.client is null?
+ request.origin = request.client?.origin
}
- [kDispatch] (opts, handler) {
- const origin = opts.origin || this[kUrl].origin
-
- const request = this[kHTTPConnVersion] === 'h2'
- ? Request[kHTTP2BuildRequest](origin, opts, handler)
- : Request[kHTTP1BuildRequest](origin, opts, handler)
+ // 10. If all of the following conditions are true:
+ // TODO
- this[kQueue].push(request)
- if (this[kResuming]) {
- // Do nothing.
- } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
- // Wait a tick in case stream/iterator is ended in the same tick.
- this[kResuming] = 1
- process.nextTick(resume, this)
+ // 11. If request’s policy container is "client", then:
+ if (request.policyContainer === 'client') {
+ // 1. If request’s client is non-null, then set request’s policy
+ // container to a clone of request’s client’s policy container. [HTML]
+ if (request.client != null) {
+ request.policyContainer = clonePolicyContainer(
+ request.client.policyContainer
+ )
} else {
- resume(this, true)
+ // 2. Otherwise, set request’s policy container to a new policy
+ // container.
+ request.policyContainer = makePolicyContainer()
}
+ }
- if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
- this[kNeedDrain] = 2
- }
+ // 12. If request’s header list does not contain `Accept`, then:
+ if (!request.headersList.contains('accept')) {
+ // 1. Let value be `*/*`.
+ const value = '*/*'
- return this[kNeedDrain] < 2
+ // 2. A user agent should set value to the first matching statement, if
+ // any, switching on request’s destination:
+ // "document"
+ // "frame"
+ // "iframe"
+ // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
+ // "image"
+ // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
+ // "style"
+ // `text/css,*/*;q=0.1`
+ // TODO
+
+ // 3. Append `Accept`/value to request’s header list.
+ request.headersList.append('accept', value)
}
- async [kClose] () {
- // TODO: for H2 we need to gracefully flush the remaining enqueued
- // request and close each stream.
- return new Promise((resolve) => {
- if (!this[kSize]) {
- resolve(null)
- } else {
- this[kClosedResolve] = resolve
- }
- })
+ // 13. If request’s header list does not contain `Accept-Language`, then
+ // user agents should append `Accept-Language`/an appropriate value to
+ // request’s header list.
+ if (!request.headersList.contains('accept-language')) {
+ request.headersList.append('accept-language', '*')
}
- async [kDestroy] (err) {
- return new Promise((resolve) => {
- const requests = this[kQueue].splice(this[kPendingIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- errorRequest(this, request, err)
- }
+ // 14. If request’s priority is null, then use request’s initiator and
+ // destination appropriately in setting request’s priority to a
+ // user-agent-defined object.
+ if (request.priority === null) {
+ // TODO
+ }
- const callback = () => {
- if (this[kClosedResolve]) {
- // TODO (fix): Should we error here with ClientDestroyedError?
- this[kClosedResolve]()
- this[kClosedResolve] = null
- }
- resolve()
- }
+ // 15. If request is a subresource request, then:
+ if (subresourceSet.has(request.destination)) {
+ // TODO
+ }
- if (this[kHTTP2Session] != null) {
- util.destroy(this[kHTTP2Session], err)
- this[kHTTP2Session] = null
- this[kHTTP2SessionState] = null
- }
+ // 16. Run main fetch given fetchParams.
+ mainFetch(fetchParams)
+ .catch(err => {
+ fetchParams.controller.terminate(err)
+ })
- if (!this[kSocket]) {
- queueMicrotask(callback)
- } else {
- util.destroy(this[kSocket].on('close', callback), err)
- }
+ // 17. Return fetchParam's controller
+ return fetchParams.controller
+}
- resume(this)
- })
+// https://fetch.spec.whatwg.org/#concept-main-fetch
+async function mainFetch (fetchParams, recursive = false) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
+
+ // 2. Let response be null.
+ let response = null
+
+ // 3. If request’s local-URLs-only flag is set and request’s current URL is
+ // not local, then set response to a network error.
+ if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
+ response = makeNetworkError('local URLs only')
}
-}
-function onHttp2SessionError (err) {
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+ // 4. Run report Content Security Policy violations for request.
+ // TODO
- this[kSocket][kError] = err
+ // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
+ tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
- onError(this[kClient], err)
-}
+ // 6. If should request be blocked due to a bad port, should fetching request
+ // be blocked as mixed content, or should request be blocked by Content
+ // Security Policy returns blocked, then set response to a network error.
+ if (requestBadPort(request) === 'blocked') {
+ response = makeNetworkError('bad port')
+ }
+ // TODO: should fetching request be blocked as mixed content?
+ // TODO: should request be blocked by Content Security Policy?
-function onHttp2FrameError (type, code, id) {
- const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
+ // 7. If request’s referrer policy is the empty string, then set request’s
+ // referrer policy to request’s policy container’s referrer policy.
+ if (request.referrerPolicy === '') {
+ request.referrerPolicy = request.policyContainer.referrerPolicy
+ }
- if (id === 0) {
- this[kSocket][kError] = err
- onError(this[kClient], err)
+ // 8. If request’s referrer is not "no-referrer", then set request’s
+ // referrer to the result of invoking determine request’s referrer.
+ if (request.referrer !== 'no-referrer') {
+ request.referrer = determineRequestsReferrer(request)
}
-}
-function onHttp2SessionEnd () {
- util.destroy(this, new SocketError('other side closed'))
- util.destroy(this[kSocket], new SocketError('other side closed'))
-}
+ // 9. Set request’s current URL’s scheme to "https" if all of the following
+ // conditions are true:
+ // - request’s current URL’s scheme is "http"
+ // - request’s current URL’s host is a domain
+ // - Matching request’s current URL’s host per Known HSTS Host Domain Name
+ // Matching results in either a superdomain match with an asserted
+ // includeSubDomains directive or a congruent match (with or without an
+ // asserted includeSubDomains directive). [HSTS]
+ // TODO
-function onHTTP2GoAway (code) {
- const client = this[kClient]
- const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`)
- client[kSocket] = null
- client[kHTTP2Session] = null
+ // 10. If recursive is false, then run the remaining steps in parallel.
+ // TODO
- if (client.destroyed) {
- assert(this[kPending] === 0)
+ // 11. If response is null, then set response to the result of running
+ // the steps corresponding to the first matching statement:
+ if (response === null) {
+ response = await (async () => {
+ const currentURL = requestCurrentURL(request)
- // Fail entire queue.
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- errorRequest(this, request, err)
- }
- } else if (client[kRunning] > 0) {
- // Fail head of pipeline.
- const request = client[kQueue][client[kRunningIdx]]
- client[kQueue][client[kRunningIdx]++] = null
+ if (
+ // - request’s current URL’s origin is same origin with request’s origin,
+ // and request’s response tainting is "basic"
+ (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
+ // request’s current URL’s scheme is "data"
+ (currentURL.protocol === 'data:') ||
+ // - request’s mode is "navigate" or "websocket"
+ (request.mode === 'navigate' || request.mode === 'websocket')
+ ) {
+ // 1. Set request’s response tainting to "basic".
+ request.responseTainting = 'basic'
- errorRequest(client, request, err)
- }
+ // 2. Return the result of running scheme fetch given fetchParams.
+ return await schemeFetch(fetchParams)
+ }
- client[kPendingIdx] = client[kRunningIdx]
+ // request’s mode is "same-origin"
+ if (request.mode === 'same-origin') {
+ // 1. Return a network error.
+ return makeNetworkError('request mode cannot be "same-origin"')
+ }
- assert(client[kRunning] === 0)
+ // request’s mode is "no-cors"
+ if (request.mode === 'no-cors') {
+ // 1. If request’s redirect mode is not "follow", then return a network
+ // error.
+ if (request.redirect !== 'follow') {
+ return makeNetworkError(
+ 'redirect mode cannot be "follow" for "no-cors" request'
+ )
+ }
- client.emit('disconnect',
- client[kUrl],
- [client],
- err
- )
+ // 2. Set request’s response tainting to "opaque".
+ request.responseTainting = 'opaque'
- resume(client)
-}
+ // 3. Return the result of running scheme fetch given fetchParams.
+ return await schemeFetch(fetchParams)
+ }
-const constants = __nccwpck_require__(40748)
-const createRedirectInterceptor = __nccwpck_require__(99299)
-const EMPTY_BUF = Buffer.alloc(0)
+ // request’s current URL’s scheme is not an HTTP(S) scheme
+ if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
+ // Return a network error.
+ return makeNetworkError('URL scheme must be a HTTP(S) scheme')
+ }
-async function lazyllhttp () {
- const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(63922) : undefined
+ // - request’s use-CORS-preflight flag is set
+ // - request’s unsafe-request flag is set and either request’s method is
+ // not a CORS-safelisted method or CORS-unsafe request-header names with
+ // request’s header list is not empty
+ // 1. Set request’s response tainting to "cors".
+ // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
+ // given fetchParams and true.
+ // 3. If corsWithPreflightResponse is a network error, then clear cache
+ // entries using request.
+ // 4. Return corsWithPreflightResponse.
+ // TODO
- let mod
- try {
- mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(53742), 'base64'))
- } catch (e) {
- /* istanbul ignore next */
+ // Otherwise
+ // 1. Set request’s response tainting to "cors".
+ request.responseTainting = 'cors'
- // We could check if the error was caused by the simd option not
- // being enabled, but the occurring of this other error
- // * https://github.com/emscripten-core/emscripten/issues/11495
- // got me to remove that check to avoid breaking Node 12.
- mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(63922), 'base64'))
+ // 2. Return the result of running HTTP fetch given fetchParams.
+ return await httpFetch(fetchParams)
+ })()
}
- return await WebAssembly.instantiate(mod, {
- env: {
- /* eslint-disable camelcase */
-
- wasm_on_url: (p, at, len) => {
- /* istanbul ignore next */
- return 0
- },
- wasm_on_status: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_message_begin: (p) => {
- assert.strictEqual(currentParser.ptr, p)
- return currentParser.onMessageBegin() || 0
- },
- wasm_on_header_field: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_header_value: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
- assert.strictEqual(currentParser.ptr, p)
- return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
- },
- wasm_on_body: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_message_complete: (p) => {
- assert.strictEqual(currentParser.ptr, p)
- return currentParser.onMessageComplete() || 0
- }
+ // 12. If recursive is true, then return response.
+ if (recursive) {
+ return response
+ }
- /* eslint-enable camelcase */
+ // 13. If response is not a network error and response is not a filtered
+ // response, then:
+ if (response.status !== 0 && !response.internalResponse) {
+ // If request’s response tainting is "cors", then:
+ if (request.responseTainting === 'cors') {
+ // 1. Let headerNames be the result of extracting header list values
+ // given `Access-Control-Expose-Headers` and response’s header list.
+ // TODO
+ // 2. If request’s credentials mode is not "include" and headerNames
+ // contains `*`, then set response’s CORS-exposed header-name list to
+ // all unique header names in response’s header list.
+ // TODO
+ // 3. Otherwise, if headerNames is not null or failure, then set
+ // response’s CORS-exposed header-name list to headerNames.
+ // TODO
}
- })
-}
-
-let llhttpInstance = null
-let llhttpPromise = lazyllhttp()
-llhttpPromise.catch()
-let currentParser = null
-let currentBufferRef = null
-let currentBufferSize = 0
-let currentBufferPtr = null
+ // Set response to the following filtered response with response as its
+ // internal response, depending on request’s response tainting:
+ if (request.responseTainting === 'basic') {
+ response = filterResponse(response, 'basic')
+ } else if (request.responseTainting === 'cors') {
+ response = filterResponse(response, 'cors')
+ } else if (request.responseTainting === 'opaque') {
+ response = filterResponse(response, 'opaque')
+ } else {
+ assert(false)
+ }
+ }
-const TIMEOUT_HEADERS = 1
-const TIMEOUT_BODY = 2
-const TIMEOUT_IDLE = 3
+ // 14. Let internalResponse be response, if response is a network error,
+ // and response’s internal response otherwise.
+ let internalResponse =
+ response.status === 0 ? response : response.internalResponse
-class Parser {
- constructor (client, socket, { exports }) {
- assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
+ // 15. If internalResponse’s URL list is empty, then set it to a clone of
+ // request’s URL list.
+ if (internalResponse.urlList.length === 0) {
+ internalResponse.urlList.push(...request.urlList)
+ }
- this.llhttp = exports
- this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
- this.client = client
- this.socket = socket
- this.timeout = null
- this.timeoutValue = null
- this.timeoutType = null
- this.statusCode = null
- this.statusText = ''
- this.upgrade = false
- this.headers = []
- this.headersSize = 0
- this.headersMaxSize = client[kMaxHeadersSize]
- this.shouldKeepAlive = false
- this.paused = false
- this.resume = this.resume.bind(this)
+ // 16. If request’s timing allow failed flag is unset, then set
+ // internalResponse’s timing allow passed flag.
+ if (!request.timingAllowFailed) {
+ response.timingAllowPassed = true
+ }
- this.bytesRead = 0
+ // 17. If response is not a network error and any of the following returns
+ // blocked
+ // - should internalResponse to request be blocked as mixed content
+ // - should internalResponse to request be blocked by Content Security Policy
+ // - should internalResponse to request be blocked due to its MIME type
+ // - should internalResponse to request be blocked due to nosniff
+ // TODO
- this.keepAlive = ''
- this.contentLength = ''
- this.connection = ''
- this.maxResponseSize = client[kMaxResponseSize]
+ // 18. If response’s type is "opaque", internalResponse’s status is 206,
+ // internalResponse’s range-requested flag is set, and request’s header
+ // list does not contain `Range`, then set response and internalResponse
+ // to a network error.
+ if (
+ response.type === 'opaque' &&
+ internalResponse.status === 206 &&
+ internalResponse.rangeRequested &&
+ !request.headers.contains('range')
+ ) {
+ response = internalResponse = makeNetworkError()
}
- setTimeout (value, type) {
- this.timeoutType = type
- if (value !== this.timeoutValue) {
- timers.clearTimeout(this.timeout)
- if (value) {
- this.timeout = timers.setTimeout(onParserTimeout, value, this)
- // istanbul ignore else: only for jest
- if (this.timeout.unref) {
- this.timeout.unref()
- }
- } else {
- this.timeout = null
- }
- this.timeoutValue = value
- } else if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
+ // 19. If response is not a network error and either request’s method is
+ // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
+ // set internalResponse’s body to null and disregard any enqueuing toward
+ // it (if any).
+ if (
+ response.status !== 0 &&
+ (request.method === 'HEAD' ||
+ request.method === 'CONNECT' ||
+ nullBodyStatus.includes(internalResponse.status))
+ ) {
+ internalResponse.body = null
+ fetchParams.controller.dump = true
}
- resume () {
- if (this.socket.destroyed || !this.paused) {
+ // 20. If request’s integrity metadata is not the empty string, then:
+ if (request.integrity) {
+ // 1. Let processBodyError be this step: run fetch finale given fetchParams
+ // and a network error.
+ const processBodyError = (reason) =>
+ fetchFinale(fetchParams, makeNetworkError(reason))
+
+ // 2. If request’s response tainting is "opaque", or response’s body is null,
+ // then run processBodyError and abort these steps.
+ if (request.responseTainting === 'opaque' || response.body == null) {
+ processBodyError(response.error)
return
}
- assert(this.ptr != null)
- assert(currentParser == null)
+ // 3. Let processBody given bytes be these steps:
+ const processBody = (bytes) => {
+ // 1. If bytes do not match request’s integrity metadata,
+ // then run processBodyError and abort these steps. [SRI]
+ if (!bytesMatch(bytes, request.integrity)) {
+ processBodyError('integrity mismatch')
+ return
+ }
- this.llhttp.llhttp_resume(this.ptr)
+ // 2. Set response’s body to bytes as a body.
+ response.body = safelyExtractBody(bytes)[0]
- assert(this.timeoutType === TIMEOUT_BODY)
- if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
+ // 3. Run fetch finale given fetchParams and response.
+ fetchFinale(fetchParams, response)
}
- this.paused = false
- this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
- this.readMore()
+ // 4. Fully read response’s body given processBody and processBodyError.
+ await fullyReadBody(response.body, processBody, processBodyError)
+ } else {
+ // 21. Otherwise, run fetch finale given fetchParams and response.
+ fetchFinale(fetchParams, response)
}
+}
- readMore () {
- while (!this.paused && this.ptr) {
- const chunk = this.socket.read()
- if (chunk === null) {
- break
- }
- this.execute(chunk)
- }
+// https://fetch.spec.whatwg.org/#concept-scheme-fetch
+// given a fetch params fetchParams
+function schemeFetch (fetchParams) {
+ // Note: since the connection is destroyed on redirect, which sets fetchParams to a
+ // cancelled state, we do not want this condition to trigger *unless* there have been
+ // no redirects. See https://github.com/nodejs/undici/issues/1776
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
+ return Promise.resolve(makeAppropriateNetworkError(fetchParams))
}
- execute (data) {
- assert(this.ptr != null)
- assert(currentParser == null)
- assert(!this.paused)
+ // 2. Let request be fetchParams’s request.
+ const { request } = fetchParams
- const { socket, llhttp } = this
+ const { protocol: scheme } = requestCurrentURL(request)
- if (data.length > currentBufferSize) {
- if (currentBufferPtr) {
- llhttp.free(currentBufferPtr)
- }
- currentBufferSize = Math.ceil(data.length / 4096) * 4096
- currentBufferPtr = llhttp.malloc(currentBufferSize)
- }
+ // 3. Switch on request’s current URL’s scheme and run the associated steps:
+ switch (scheme) {
+ case 'about:': {
+ // If request’s current URL’s path is the string "blank", then return a new response
+ // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
+ // and body is the empty byte sequence as a body.
- new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
+ // Otherwise, return a network error.
+ return Promise.resolve(makeNetworkError('about scheme is not supported'))
+ }
+ case 'blob:': {
+ if (!resolveObjectURL) {
+ resolveObjectURL = (__nccwpck_require__(20181).resolveObjectURL)
+ }
- // Call `execute` on the wasm parser.
- // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
- // and finally the length of bytes to parse.
- // The return value is an error code or `constants.ERROR.OK`.
- try {
- let ret
+ // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
+ const blobURLEntry = requestCurrentURL(request)
- try {
- currentBufferRef = data
- currentParser = this
- ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)
- /* eslint-disable-next-line no-useless-catch */
- } catch (err) {
- /* istanbul ignore next: difficult to make a test case for */
- throw err
- } finally {
- currentParser = null
- currentBufferRef = null
+ // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
+ // Buffer.resolveObjectURL does not ignore URL queries.
+ if (blobURLEntry.search.length !== 0) {
+ return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
}
- const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
+ const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())
- if (ret === constants.ERROR.PAUSED_UPGRADE) {
- this.onUpgrade(data.slice(offset))
- } else if (ret === constants.ERROR.PAUSED) {
- this.paused = true
- socket.unshift(data.slice(offset))
- } else if (ret !== constants.ERROR.OK) {
- const ptr = llhttp.llhttp_get_error_reason(this.ptr)
- let message = ''
- /* istanbul ignore else: difficult to make a test case for */
- if (ptr) {
- const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
- message =
- 'Response does not match the HTTP/1.1 protocol (' +
- Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
- ')'
- }
- throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
+ // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
+ // object is not a Blob object, then return a network error.
+ if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {
+ return Promise.resolve(makeNetworkError('invalid method'))
}
- } catch (err) {
- util.destroy(socket, err)
- }
- }
- destroy () {
- assert(this.ptr != null)
- assert(currentParser == null)
+ // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.
+ const bodyWithType = safelyExtractBody(blobURLEntryObject)
- this.llhttp.llhttp_free(this.ptr)
- this.ptr = null
+ // 4. Let body be bodyWithType’s body.
+ const body = bodyWithType[0]
- timers.clearTimeout(this.timeout)
- this.timeout = null
- this.timeoutValue = null
- this.timeoutType = null
+ // 5. Let length be body’s length, serialized and isomorphic encoded.
+ const length = isomorphicEncode(`${body.length}`)
- this.paused = false
- }
+ // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.
+ const type = bodyWithType[1] ?? ''
- onStatus (buf) {
- this.statusText = buf.toString()
- }
+ // 7. Return a new response whose status message is `OK`, header list is
+ // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.
+ const response = makeResponse({
+ statusText: 'OK',
+ headersList: [
+ ['content-length', { name: 'Content-Length', value: length }],
+ ['content-type', { name: 'Content-Type', value: type }]
+ ]
+ })
- onMessageBegin () {
- const { socket, client } = this
+ response.body = body
- /* istanbul ignore next: difficult to make a test case for */
- if (socket.destroyed) {
- return -1
+ return Promise.resolve(response)
}
+ case 'data:': {
+ // 1. Let dataURLStruct be the result of running the
+ // data: URL processor on request’s current URL.
+ const currentURL = requestCurrentURL(request)
+ const dataURLStruct = dataURLProcessor(currentURL)
- const request = client[kQueue][client[kRunningIdx]]
- if (!request) {
- return -1
- }
- }
+ // 2. If dataURLStruct is failure, then return a
+ // network error.
+ if (dataURLStruct === 'failure') {
+ return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
+ }
- onHeaderField (buf) {
- const len = this.headers.length
+ // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
+ const mimeType = serializeAMimeType(dataURLStruct.mimeType)
- if ((len & 1) === 0) {
- this.headers.push(buf)
- } else {
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ // 4. Return a response whose status message is `OK`,
+ // header list is « (`Content-Type`, mimeType) »,
+ // and body is dataURLStruct’s body as a body.
+ return Promise.resolve(makeResponse({
+ statusText: 'OK',
+ headersList: [
+ ['content-type', { name: 'Content-Type', value: mimeType }]
+ ],
+ body: safelyExtractBody(dataURLStruct.body)[0]
+ }))
}
+ case 'file:': {
+ // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
+ // When in doubt, return a network error.
+ return Promise.resolve(makeNetworkError('not implemented... yet...'))
+ }
+ case 'http:':
+ case 'https:': {
+ // Return the result of running HTTP fetch given fetchParams.
- this.trackHeader(buf.length)
+ return httpFetch(fetchParams)
+ .catch((err) => makeNetworkError(err))
+ }
+ default: {
+ return Promise.resolve(makeNetworkError('unknown scheme'))
+ }
}
+}
- onHeaderValue (buf) {
- let len = this.headers.length
+// https://fetch.spec.whatwg.org/#finalize-response
+function finalizeResponse (fetchParams, response) {
+ // 1. Set fetchParams’s request’s done flag.
+ fetchParams.request.done = true
- if ((len & 1) === 1) {
- this.headers.push(buf)
- len += 1
- } else {
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
- }
+ // 2, If fetchParams’s process response done is not null, then queue a fetch
+ // task to run fetchParams’s process response done given response, with
+ // fetchParams’s task destination.
+ if (fetchParams.processResponseDone != null) {
+ queueMicrotask(() => fetchParams.processResponseDone(response))
+ }
+}
- const key = this.headers[len - 2]
- if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {
- this.keepAlive += buf.toString()
- } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {
- this.connection += buf.toString()
- } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {
- this.contentLength += buf.toString()
- }
+// https://fetch.spec.whatwg.org/#fetch-finale
+function fetchFinale (fetchParams, response) {
+ // 1. If response is a network error, then:
+ if (response.type === 'error') {
+ // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».
+ response.urlList = [fetchParams.request.urlList[0]]
- this.trackHeader(buf.length)
+ // 2. Set response’s timing info to the result of creating an opaque timing
+ // info for fetchParams’s timing info.
+ response.timingInfo = createOpaqueTimingInfo({
+ startTime: fetchParams.timingInfo.startTime
+ })
}
- trackHeader (len) {
- this.headersSize += len
- if (this.headersSize >= this.headersMaxSize) {
- util.destroy(this.socket, new HeadersOverflowError())
+ // 2. Let processResponseEndOfBody be the following steps:
+ const processResponseEndOfBody = () => {
+ // 1. Set fetchParams’s request’s done flag.
+ fetchParams.request.done = true
+
+ // If fetchParams’s process response end-of-body is not null,
+ // then queue a fetch task to run fetchParams’s process response
+ // end-of-body given response with fetchParams’s task destination.
+ if (fetchParams.processResponseEndOfBody != null) {
+ queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
}
}
- onUpgrade (head) {
- const { upgrade, client, socket, headers, statusCode } = this
-
- assert(upgrade)
-
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
+ // 3. If fetchParams’s process response is non-null, then queue a fetch task
+ // to run fetchParams’s process response given response, with fetchParams’s
+ // task destination.
+ if (fetchParams.processResponse != null) {
+ queueMicrotask(() => fetchParams.processResponse(response))
+ }
- assert(!socket.destroyed)
- assert(socket === client[kSocket])
- assert(!this.paused)
- assert(request.upgrade || request.method === 'CONNECT')
+ // 4. If response’s body is null, then run processResponseEndOfBody.
+ if (response.body == null) {
+ processResponseEndOfBody()
+ } else {
+ // 5. Otherwise:
- this.statusCode = null
- this.statusText = ''
- this.shouldKeepAlive = null
+ // 1. Let transformStream be a new a TransformStream.
- assert(this.headers.length % 2 === 0)
- this.headers = []
- this.headersSize = 0
+ // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,
+ // enqueues chunk in transformStream.
+ const identityTransformAlgorithm = (chunk, controller) => {
+ controller.enqueue(chunk)
+ }
- socket.unshift(head)
+ // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm
+ // and flushAlgorithm set to processResponseEndOfBody.
+ const transformStream = new TransformStream({
+ start () {},
+ transform: identityTransformAlgorithm,
+ flush: processResponseEndOfBody
+ }, {
+ size () {
+ return 1
+ }
+ }, {
+ size () {
+ return 1
+ }
+ })
- socket[kParser].destroy()
- socket[kParser] = null
+ // 4. Set response’s body to the result of piping response’s body through transformStream.
+ response.body = { stream: response.body.stream.pipeThrough(transformStream) }
+ }
- socket[kClient] = null
- socket[kError] = null
- socket
- .removeListener('error', onSocketError)
- .removeListener('readable', onSocketReadable)
- .removeListener('end', onSocketEnd)
- .removeListener('close', onSocketClose)
+ // 6. If fetchParams’s process response consume body is non-null, then:
+ if (fetchParams.processResponseConsumeBody != null) {
+ // 1. Let processBody given nullOrBytes be this step: run fetchParams’s
+ // process response consume body given response and nullOrBytes.
+ const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)
- client[kSocket] = null
- client[kQueue][client[kRunningIdx]++] = null
- client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
+ // 2. Let processBodyError be this step: run fetchParams’s process
+ // response consume body given response and failure.
+ const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)
- try {
- request.onUpgrade(statusCode, headers, socket)
- } catch (err) {
- util.destroy(socket, err)
+ // 3. If response’s body is null, then queue a fetch task to run processBody
+ // given null, with fetchParams’s task destination.
+ if (response.body == null) {
+ queueMicrotask(() => processBody(null))
+ } else {
+ // 4. Otherwise, fully read response’s body given processBody, processBodyError,
+ // and fetchParams’s task destination.
+ return fullyReadBody(response.body, processBody, processBodyError)
}
-
- resume(client)
+ return Promise.resolve()
}
+}
- onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
- const { client, socket, headers, statusText } = this
+// https://fetch.spec.whatwg.org/#http-fetch
+async function httpFetch (fetchParams) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- /* istanbul ignore next: difficult to make a test case for */
- if (socket.destroyed) {
- return -1
- }
+ // 2. Let response be null.
+ let response = null
- const request = client[kQueue][client[kRunningIdx]]
+ // 3. Let actualResponse be null.
+ let actualResponse = null
- /* istanbul ignore next: difficult to make a test case for */
- if (!request) {
- return -1
- }
+ // 4. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
- assert(!this.upgrade)
- assert(this.statusCode < 200)
+ // 5. If request’s service-workers mode is "all", then:
+ if (request.serviceWorkers === 'all') {
+ // TODO
+ }
- if (statusCode === 100) {
- util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
- return -1
- }
+ // 6. If response is null, then:
+ if (response === null) {
+ // 1. If makeCORSPreflight is true and one of these conditions is true:
+ // TODO
- /* this can only happen if server is misbehaving */
- if (upgrade && !request.upgrade) {
- util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
- return -1
+ // 2. If request’s redirect mode is "follow", then set request’s
+ // service-workers mode to "none".
+ if (request.redirect === 'follow') {
+ request.serviceWorkers = 'none'
}
- assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)
-
- this.statusCode = statusCode
- this.shouldKeepAlive = (
- shouldKeepAlive ||
- // Override llhttp value which does not allow keepAlive for HEAD.
- (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
- )
-
- if (this.statusCode >= 200) {
- const bodyTimeout = request.bodyTimeout != null
- ? request.bodyTimeout
- : client[kBodyTimeout]
- this.setTimeout(bodyTimeout, TIMEOUT_BODY)
- } else if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
+ // 3. Set response and actualResponse to the result of running
+ // HTTP-network-or-cache fetch given fetchParams.
+ actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
- if (request.method === 'CONNECT') {
- assert(client[kRunning] === 1)
- this.upgrade = true
- return 2
+ // 4. If request’s response tainting is "cors" and a CORS check
+ // for request and response returns failure, then return a network error.
+ if (
+ request.responseTainting === 'cors' &&
+ corsCheck(request, response) === 'failure'
+ ) {
+ return makeNetworkError('cors failure')
}
- if (upgrade) {
- assert(client[kRunning] === 1)
- this.upgrade = true
- return 2
+ // 5. If the TAO check for request and response returns failure, then set
+ // request’s timing allow failed flag.
+ if (TAOCheck(request, response) === 'failure') {
+ request.timingAllowFailed = true
}
+ }
- assert(this.headers.length % 2 === 0)
- this.headers = []
- this.headersSize = 0
+ // 7. If either request’s response tainting or response’s type
+ // is "opaque", and the cross-origin resource policy check with
+ // request’s origin, request’s client, request’s destination,
+ // and actualResponse returns blocked, then return a network error.
+ if (
+ (request.responseTainting === 'opaque' || response.type === 'opaque') &&
+ crossOriginResourcePolicyCheck(
+ request.origin,
+ request.client,
+ request.destination,
+ actualResponse
+ ) === 'blocked'
+ ) {
+ return makeNetworkError('blocked')
+ }
- if (this.shouldKeepAlive && client[kPipelining]) {
- const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
+ // 8. If actualResponse’s status is a redirect status, then:
+ if (redirectStatusSet.has(actualResponse.status)) {
+ // 1. If actualResponse’s status is not 303, request’s body is not null,
+ // and the connection uses HTTP/2, then user agents may, and are even
+ // encouraged to, transmit an RST_STREAM frame.
+ // See, https://github.com/whatwg/fetch/issues/1288
+ if (request.redirect !== 'manual') {
+ fetchParams.controller.connection.destroy()
+ }
- if (keepAliveTimeout != null) {
- const timeout = Math.min(
- keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
- client[kKeepAliveMaxTimeout]
- )
- if (timeout <= 0) {
- socket[kReset] = true
- } else {
- client[kKeepAliveTimeoutValue] = timeout
- }
- } else {
- client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
- }
+ // 2. Switch on request’s redirect mode:
+ if (request.redirect === 'error') {
+ // Set response to a network error.
+ response = makeNetworkError('unexpected redirect')
+ } else if (request.redirect === 'manual') {
+ // Set response to an opaque-redirect filtered response whose internal
+ // response is actualResponse.
+ // NOTE(spec): On the web this would return an `opaqueredirect` response,
+ // but that doesn't make sense server side.
+ // See https://github.com/nodejs/undici/issues/1193.
+ response = actualResponse
+ } else if (request.redirect === 'follow') {
+ // Set response to the result of running HTTP-redirect fetch given
+ // fetchParams and response.
+ response = await httpRedirectFetch(fetchParams, response)
} else {
- // Stop more requests from being dispatched.
- socket[kReset] = true
+ assert(false)
}
+ }
- const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
+ // 9. Set response’s timing info to timingInfo.
+ response.timingInfo = timingInfo
- if (request.aborted) {
- return -1
- }
+ // 10. Return response.
+ return response
+}
- if (request.method === 'HEAD') {
- return 1
- }
+// https://fetch.spec.whatwg.org/#http-redirect-fetch
+function httpRedirectFetch (fetchParams, response) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- if (statusCode < 200) {
- return 1
- }
+ // 2. Let actualResponse be response, if response is not a filtered response,
+ // and response’s internal response otherwise.
+ const actualResponse = response.internalResponse
+ ? response.internalResponse
+ : response
- if (socket[kBlocking]) {
- socket[kBlocking] = false
- resume(client)
+ // 3. Let locationURL be actualResponse’s location URL given request’s current
+ // URL’s fragment.
+ let locationURL
+
+ try {
+ locationURL = responseLocationURL(
+ actualResponse,
+ requestCurrentURL(request).hash
+ )
+
+ // 4. If locationURL is null, then return response.
+ if (locationURL == null) {
+ return response
}
+ } catch (err) {
+ // 5. If locationURL is failure, then return a network error.
+ return Promise.resolve(makeNetworkError(err))
+ }
- return pause ? constants.ERROR.PAUSED : 0
+ // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
+ // error.
+ if (!urlIsHttpHttpsScheme(locationURL)) {
+ return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
}
- onBody (buf) {
- const { client, socket, statusCode, maxResponseSize } = this
+ // 7. If request’s redirect count is 20, then return a network error.
+ if (request.redirectCount === 20) {
+ return Promise.resolve(makeNetworkError('redirect count exceeded'))
+ }
- if (socket.destroyed) {
- return -1
- }
+ // 8. Increase request’s redirect count by 1.
+ request.redirectCount += 1
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
+ // 9. If request’s mode is "cors", locationURL includes credentials, and
+ // request’s origin is not same origin with locationURL’s origin, then return
+ // a network error.
+ if (
+ request.mode === 'cors' &&
+ (locationURL.username || locationURL.password) &&
+ !sameOrigin(request, locationURL)
+ ) {
+ return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
+ }
- assert.strictEqual(this.timeoutType, TIMEOUT_BODY)
- if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
+ // 10. If request’s response tainting is "cors" and locationURL includes
+ // credentials, then return a network error.
+ if (
+ request.responseTainting === 'cors' &&
+ (locationURL.username || locationURL.password)
+ ) {
+ return Promise.resolve(makeNetworkError(
+ 'URL cannot contain credentials for request mode "cors"'
+ ))
+ }
- assert(statusCode >= 200)
+ // 11. If actualResponse’s status is not 303, request’s body is non-null,
+ // and request’s body’s source is null, then return a network error.
+ if (
+ actualResponse.status !== 303 &&
+ request.body != null &&
+ request.body.source == null
+ ) {
+ return Promise.resolve(makeNetworkError())
+ }
- if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
- util.destroy(socket, new ResponseExceededMaxSizeError())
- return -1
+ // 12. If one of the following is true
+ // - actualResponse’s status is 301 or 302 and request’s method is `POST`
+ // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
+ if (
+ ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
+ (actualResponse.status === 303 &&
+ !GET_OR_HEAD.includes(request.method))
+ ) {
+ // then:
+ // 1. Set request’s method to `GET` and request’s body to null.
+ request.method = 'GET'
+ request.body = null
+
+ // 2. For each headerName of request-body-header name, delete headerName from
+ // request’s header list.
+ for (const headerName of requestBodyHeader) {
+ request.headersList.delete(headerName)
}
+ }
- this.bytesRead += buf.length
+ // 13. If request’s current URL’s origin is not same origin with locationURL’s
+ // origin, then for each headerName of CORS non-wildcard request-header name,
+ // delete headerName from request’s header list.
+ if (!sameOrigin(requestCurrentURL(request), locationURL)) {
+ // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
+ request.headersList.delete('authorization')
- if (request.onData(buf) === false) {
- return constants.ERROR.PAUSED
- }
+ // https://fetch.spec.whatwg.org/#authentication-entries
+ request.headersList.delete('proxy-authorization', true)
+
+ // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
+ request.headersList.delete('cookie')
+ request.headersList.delete('host')
}
- onMessageComplete () {
- const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
+ // 14. If request’s body is non-null, then set request’s body to the first return
+ // value of safely extracting request’s body’s source.
+ if (request.body != null) {
+ assert(request.body.source != null)
+ request.body = safelyExtractBody(request.body.source)[0]
+ }
- if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
- return -1
- }
+ // 15. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
- if (upgrade) {
- return
- }
+ // 16. Set timingInfo’s redirect end time and post-redirect start time to the
+ // coarsened shared current time given fetchParams’s cross-origin isolated
+ // capability.
+ timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
+ coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
+ // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
+ // redirect start time to timingInfo’s start time.
+ if (timingInfo.redirectStartTime === 0) {
+ timingInfo.redirectStartTime = timingInfo.startTime
+ }
- assert(statusCode >= 100)
+ // 18. Append locationURL to request’s URL list.
+ request.urlList.push(locationURL)
- this.statusCode = null
- this.statusText = ''
- this.bytesRead = 0
- this.contentLength = ''
- this.keepAlive = ''
- this.connection = ''
+ // 19. Invoke set request’s referrer policy on redirect on request and
+ // actualResponse.
+ setRequestReferrerPolicyOnRedirect(request, actualResponse)
- assert(this.headers.length % 2 === 0)
- this.headers = []
- this.headersSize = 0
+ // 20. Return the result of running main fetch given fetchParams and true.
+ return mainFetch(fetchParams, true)
+}
- if (statusCode < 200) {
- return
- }
+// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
+async function httpNetworkOrCacheFetch (
+ fetchParams,
+ isAuthenticationFetch = false,
+ isNewConnectionFetch = false
+) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- /* istanbul ignore next: should be handled by llhttp? */
- if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
- util.destroy(socket, new ResponseContentLengthMismatchError())
- return -1
- }
+ // 2. Let httpFetchParams be null.
+ let httpFetchParams = null
- request.onComplete(headers)
+ // 3. Let httpRequest be null.
+ let httpRequest = null
- client[kQueue][client[kRunningIdx]++] = null
+ // 4. Let response be null.
+ let response = null
- if (socket[kWriting]) {
- assert.strictEqual(client[kRunning], 0)
- // Response completed before request.
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (!shouldKeepAlive) {
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (socket[kReset] && client[kRunning] === 0) {
- // Destroy socket once all requests have completed.
- // The request at the tail of the pipeline is the one
- // that requested reset and no further requests should
- // have been queued since then.
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (client[kPipelining] === 1) {
- // We must wait a full event loop cycle to reuse this socket to make sure
- // that non-spec compliant servers are not closing the connection even if they
- // said they won't.
- setImmediate(resume, client)
- } else {
- resume(client)
- }
- }
-}
+ // 5. Let storedResponse be null.
+ // TODO: cache
-function onParserTimeout (parser) {
- const { socket, timeoutType, client } = parser
+ // 6. Let httpCache be null.
+ const httpCache = null
- /* istanbul ignore else */
- if (timeoutType === TIMEOUT_HEADERS) {
- if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
- assert(!parser.paused, 'cannot be paused while waiting for headers')
- util.destroy(socket, new HeadersTimeoutError())
- }
- } else if (timeoutType === TIMEOUT_BODY) {
- if (!parser.paused) {
- util.destroy(socket, new BodyTimeoutError())
- }
- } else if (timeoutType === TIMEOUT_IDLE) {
- assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
- util.destroy(socket, new InformationalError('socket idle timeout'))
- }
-}
+ // 7. Let the revalidatingFlag be unset.
+ const revalidatingFlag = false
-function onSocketReadable () {
- const { [kParser]: parser } = this
- if (parser) {
- parser.readMore()
- }
-}
+ // 8. Run these steps, but abort when the ongoing fetch is terminated:
-function onSocketError (err) {
- const { [kClient]: client, [kParser]: parser } = this
+ // 1. If request’s window is "no-window" and request’s redirect mode is
+ // "error", then set httpFetchParams to fetchParams and httpRequest to
+ // request.
+ if (request.window === 'no-window' && request.redirect === 'error') {
+ httpFetchParams = fetchParams
+ httpRequest = request
+ } else {
+ // Otherwise:
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+ // 1. Set httpRequest to a clone of request.
+ httpRequest = makeRequest(request)
- if (client[kHTTPConnVersion] !== 'h2') {
- // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
- // to the user.
- if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so for as a valid response.
- parser.onMessageComplete()
- return
- }
+ // 2. Set httpFetchParams to a copy of fetchParams.
+ httpFetchParams = { ...fetchParams }
+
+ // 3. Set httpFetchParams’s request to httpRequest.
+ httpFetchParams.request = httpRequest
}
- this[kError] = err
+ // 3. Let includeCredentials be true if one of
+ const includeCredentials =
+ request.credentials === 'include' ||
+ (request.credentials === 'same-origin' &&
+ request.responseTainting === 'basic')
- onError(this[kClient], err)
-}
+ // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
+ // body is non-null; otherwise null.
+ const contentLength = httpRequest.body ? httpRequest.body.length : null
-function onError (client, err) {
+ // 5. Let contentLengthHeaderValue be null.
+ let contentLengthHeaderValue = null
+
+ // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
+ // `PUT`, then set contentLengthHeaderValue to `0`.
if (
- client[kRunning] === 0 &&
- err.code !== 'UND_ERR_INFO' &&
- err.code !== 'UND_ERR_SOCKET'
+ httpRequest.body == null &&
+ ['POST', 'PUT'].includes(httpRequest.method)
) {
- // Error is not caused by running request and not a recoverable
- // socket error.
+ contentLengthHeaderValue = '0'
+ }
- assert(client[kPendingIdx] === client[kRunningIdx])
+ // 7. If contentLength is non-null, then set contentLengthHeaderValue to
+ // contentLength, serialized and isomorphic encoded.
+ if (contentLength != null) {
+ contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
+ }
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- errorRequest(client, request, err)
- }
- assert(client[kSize] === 0)
+ // 8. If contentLengthHeaderValue is non-null, then append
+ // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
+ // list.
+ if (contentLengthHeaderValue != null) {
+ httpRequest.headersList.append('content-length', contentLengthHeaderValue)
}
-}
-function onSocketEnd () {
- const { [kParser]: parser, [kClient]: client } = this
+ // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
+ // contentLengthHeaderValue) to httpRequest’s header list.
- if (client[kHTTPConnVersion] !== 'h2') {
- if (parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so far as a valid response.
- parser.onMessageComplete()
- return
- }
+ // 10. If contentLength is non-null and httpRequest’s keepalive is true,
+ // then:
+ if (contentLength != null && httpRequest.keepalive) {
+ // NOTE: keepalive is a noop outside of browser context.
}
- util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
-}
+ // 11. If httpRequest’s referrer is a URL, then append
+ // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
+ // to httpRequest’s header list.
+ if (httpRequest.referrer instanceof URL) {
+ httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))
+ }
-function onSocketClose () {
- const { [kClient]: client, [kParser]: parser } = this
+ // 12. Append a request `Origin` header for httpRequest.
+ appendRequestOriginHeader(httpRequest)
- if (client[kHTTPConnVersion] === 'h1' && parser) {
- if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so far as a valid response.
- parser.onMessageComplete()
- }
+ // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
+ appendFetchMetadata(httpRequest)
- this[kParser].destroy()
- this[kParser] = null
+ // 14. If httpRequest’s header list does not contain `User-Agent`, then
+ // user agents should append `User-Agent`/default `User-Agent` value to
+ // httpRequest’s header list.
+ if (!httpRequest.headersList.contains('user-agent')) {
+ httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')
}
- const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
+ // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
+ // list contains `If-Modified-Since`, `If-None-Match`,
+ // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
+ // httpRequest’s cache mode to "no-store".
+ if (
+ httpRequest.cache === 'default' &&
+ (httpRequest.headersList.contains('if-modified-since') ||
+ httpRequest.headersList.contains('if-none-match') ||
+ httpRequest.headersList.contains('if-unmodified-since') ||
+ httpRequest.headersList.contains('if-match') ||
+ httpRequest.headersList.contains('if-range'))
+ ) {
+ httpRequest.cache = 'no-store'
+ }
- client[kSocket] = null
+ // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
+ // no-cache cache-control header modification flag is unset, and
+ // httpRequest’s header list does not contain `Cache-Control`, then append
+ // `Cache-Control`/`max-age=0` to httpRequest’s header list.
+ if (
+ httpRequest.cache === 'no-cache' &&
+ !httpRequest.preventNoCacheCacheControlHeaderModification &&
+ !httpRequest.headersList.contains('cache-control')
+ ) {
+ httpRequest.headersList.append('cache-control', 'max-age=0')
+ }
- if (client.destroyed) {
- assert(client[kPending] === 0)
+ // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
+ if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
+ // 1. If httpRequest’s header list does not contain `Pragma`, then append
+ // `Pragma`/`no-cache` to httpRequest’s header list.
+ if (!httpRequest.headersList.contains('pragma')) {
+ httpRequest.headersList.append('pragma', 'no-cache')
+ }
- // Fail entire queue.
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- errorRequest(client, request, err)
+ // 2. If httpRequest’s header list does not contain `Cache-Control`,
+ // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
+ if (!httpRequest.headersList.contains('cache-control')) {
+ httpRequest.headersList.append('cache-control', 'no-cache')
}
- } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
- // Fail head of pipeline.
- const request = client[kQueue][client[kRunningIdx]]
- client[kQueue][client[kRunningIdx]++] = null
+ }
- errorRequest(client, request, err)
+ // 18. If httpRequest’s header list contains `Range`, then append
+ // `Accept-Encoding`/`identity` to httpRequest’s header list.
+ if (httpRequest.headersList.contains('range')) {
+ httpRequest.headersList.append('accept-encoding', 'identity')
}
- client[kPendingIdx] = client[kRunningIdx]
+ // 19. Modify httpRequest’s header list per HTTP. Do not append a given
+ // header if httpRequest’s header list contains that header’s name.
+ // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
+ if (!httpRequest.headersList.contains('accept-encoding')) {
+ if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
+ httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')
+ } else {
+ httpRequest.headersList.append('accept-encoding', 'gzip, deflate')
+ }
+ }
- assert(client[kRunning] === 0)
+ httpRequest.headersList.delete('host')
- client.emit('disconnect', client[kUrl], [client], err)
+ // 20. If includeCredentials is true, then:
+ if (includeCredentials) {
+ // 1. If the user agent is not configured to block cookies for httpRequest
+ // (see section 7 of [COOKIES]), then:
+ // TODO: credentials
+ // 2. If httpRequest’s header list does not contain `Authorization`, then:
+ // TODO: credentials
+ }
- resume(client)
-}
+ // 21. If there’s a proxy-authentication entry, use it as appropriate.
+ // TODO: proxy-authentication
-async function connect (client) {
- assert(!client[kConnecting])
- assert(!client[kSocket])
+ // 22. Set httpCache to the result of determining the HTTP cache
+ // partition, given httpRequest.
+ // TODO: cache
- let { host, hostname, protocol, port } = client[kUrl]
+ // 23. If httpCache is null, then set httpRequest’s cache mode to
+ // "no-store".
+ if (httpCache == null) {
+ httpRequest.cache = 'no-store'
+ }
- // Resolve ipv6
- if (hostname[0] === '[') {
- const idx = hostname.indexOf(']')
+ // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
+ // then:
+ if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {
+ // TODO: cache
+ }
+
+ // 9. If aborted, then return the appropriate network error for fetchParams.
+ // TODO
+
+ // 10. If response is null, then:
+ if (response == null) {
+ // 1. If httpRequest’s cache mode is "only-if-cached", then return a
+ // network error.
+ if (httpRequest.mode === 'only-if-cached') {
+ return makeNetworkError('only if cached')
+ }
+
+ // 2. Let forwardResponse be the result of running HTTP-network fetch
+ // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
+ const forwardResponse = await httpNetworkFetch(
+ httpFetchParams,
+ includeCredentials,
+ isNewConnectionFetch
+ )
+
+ // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
+ // in the range 200 to 399, inclusive, invalidate appropriate stored
+ // responses in httpCache, as per the "Invalidation" chapter of HTTP
+ // Caching, and set storedResponse to null. [HTTP-CACHING]
+ if (
+ !safeMethodsSet.has(httpRequest.method) &&
+ forwardResponse.status >= 200 &&
+ forwardResponse.status <= 399
+ ) {
+ // TODO: cache
+ }
- assert(idx !== -1)
- const ip = hostname.substring(1, idx)
+ // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
+ // then:
+ if (revalidatingFlag && forwardResponse.status === 304) {
+ // TODO: cache
+ }
- assert(net.isIP(ip))
- hostname = ip
+ // 5. If response is null, then:
+ if (response == null) {
+ // 1. Set response to forwardResponse.
+ response = forwardResponse
+
+ // 2. Store httpRequest and forwardResponse in httpCache, as per the
+ // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
+ // TODO: cache
+ }
}
- client[kConnecting] = true
+ // 11. Set response’s URL list to a clone of httpRequest’s URL list.
+ response.urlList = [...httpRequest.urlList]
- if (channels.beforeConnect.hasSubscribers) {
- channels.beforeConnect.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector]
- })
+ // 12. If httpRequest’s header list contains `Range`, then set response’s
+ // range-requested flag.
+ if (httpRequest.headersList.contains('range')) {
+ response.rangeRequested = true
}
- try {
- const socket = await new Promise((resolve, reject) => {
- client[kConnector]({
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- }, (err, socket) => {
- if (err) {
- reject(err)
- } else {
- resolve(socket)
- }
- })
- })
+ // 13. Set response’s request-includes-credentials to includeCredentials.
+ response.requestIncludesCredentials = includeCredentials
- if (client.destroyed) {
- util.destroy(socket.on('error', () => {}), new ClientDestroyedError())
- return
- }
+ // 14. If response’s status is 401, httpRequest’s response tainting is not
+ // "cors", includeCredentials is true, and request’s window is an environment
+ // settings object, then:
+ // TODO
- client[kConnecting] = false
+ // 15. If response’s status is 407, then:
+ if (response.status === 407) {
+ // 1. If request’s window is "no-window", then return a network error.
+ if (request.window === 'no-window') {
+ return makeNetworkError()
+ }
- assert(socket)
+ // 2. ???
- const isH2 = socket.alpnProtocol === 'h2'
- if (isH2) {
- if (!h2ExperimentalWarned) {
- h2ExperimentalWarned = true
- process.emitWarning('H2 support is experimental, expect them to change at any time.', {
- code: 'UNDICI-H2'
- })
- }
+ // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams)
+ }
- const session = http2.connect(client[kUrl], {
- createConnection: () => socket,
- peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams
- })
+ // 4. Prompt the end user as appropriate in request’s window and store
+ // the result as a proxy-authentication entry. [HTTP-AUTH]
+ // TODO: Invoke some kind of callback?
- client[kHTTPConnVersion] = 'h2'
- session[kClient] = client
- session[kSocket] = socket
- session.on('error', onHttp2SessionError)
- session.on('frameError', onHttp2FrameError)
- session.on('end', onHttp2SessionEnd)
- session.on('goaway', onHTTP2GoAway)
- session.on('close', onSocketClose)
- session.unref()
+ // 5. Set response to the result of running HTTP-network-or-cache fetch given
+ // fetchParams.
+ // TODO
+ return makeNetworkError('proxy authentication required')
+ }
- client[kHTTP2Session] = session
- socket[kHTTP2Session] = session
- } else {
- if (!llhttpInstance) {
- llhttpInstance = await llhttpPromise
- llhttpPromise = null
- }
+ // 16. If all of the following are true
+ if (
+ // response’s status is 421
+ response.status === 421 &&
+ // isNewConnectionFetch is false
+ !isNewConnectionFetch &&
+ // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
+ (request.body == null || request.body.source != null)
+ ) {
+ // then:
- socket[kNoRef] = false
- socket[kWriting] = false
- socket[kReset] = false
- socket[kBlocking] = false
- socket[kParser] = new Parser(client, socket, llhttpInstance)
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams)
}
- socket[kCounter] = 0
- socket[kMaxRequests] = client[kMaxRequests]
- socket[kClient] = client
- socket[kError] = null
+ // 2. Set response to the result of running HTTP-network-or-cache
+ // fetch given fetchParams, isAuthenticationFetch, and true.
- socket
- .on('error', onSocketError)
- .on('readable', onSocketReadable)
- .on('end', onSocketEnd)
- .on('close', onSocketClose)
+ // TODO (spec): The spec doesn't specify this but we need to cancel
+ // the active response before we can start a new one.
+ // https://github.com/whatwg/fetch/issues/1293
+ fetchParams.controller.connection.destroy()
- client[kSocket] = socket
+ response = await httpNetworkOrCacheFetch(
+ fetchParams,
+ isAuthenticationFetch,
+ true
+ )
+ }
- if (channels.connected.hasSubscribers) {
- channels.connected.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector],
- socket
- })
- }
- client.emit('connect', client[kUrl], [client])
- } catch (err) {
- if (client.destroyed) {
- return
- }
+ // 17. If isAuthenticationFetch is true, then create an authentication entry
+ if (isAuthenticationFetch) {
+ // TODO
+ }
- client[kConnecting] = false
+ // 18. Return response.
+ return response
+}
- if (channels.connectError.hasSubscribers) {
- channels.connectError.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector],
- error: err
- })
- }
+// https://fetch.spec.whatwg.org/#http-network-fetch
+async function httpNetworkFetch (
+ fetchParams,
+ includeCredentials = false,
+ forceNewConnection = false
+) {
+ assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
- if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
- assert(client[kRunning] === 0)
- while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
- const request = client[kQueue][client[kPendingIdx]++]
- errorRequest(client, request, err)
+ fetchParams.controller.connection = {
+ abort: null,
+ destroyed: false,
+ destroy (err) {
+ if (!this.destroyed) {
+ this.destroyed = true
+ this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
}
- } else {
- onError(client, err)
}
-
- client.emit('connectionError', client[kUrl], [client], err)
}
- resume(client)
-}
-
-function emitDrain (client) {
- client[kNeedDrain] = 0
- client.emit('drain', client[kUrl], [client])
-}
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
-function resume (client, sync) {
- if (client[kResuming] === 2) {
- return
- }
+ // 2. Let response be null.
+ let response = null
- client[kResuming] = 2
+ // 3. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
- _resume(client, sync)
- client[kResuming] = 0
+ // 4. Let httpCache be the result of determining the HTTP cache partition,
+ // given request.
+ // TODO: cache
+ const httpCache = null
- if (client[kRunningIdx] > 256) {
- client[kQueue].splice(0, client[kRunningIdx])
- client[kPendingIdx] -= client[kRunningIdx]
- client[kRunningIdx] = 0
+ // 5. If httpCache is null, then set request’s cache mode to "no-store".
+ if (httpCache == null) {
+ request.cache = 'no-store'
}
-}
-function _resume (client, sync) {
- while (true) {
- if (client.destroyed) {
- assert(client[kPending] === 0)
- return
- }
+ // 6. Let networkPartitionKey be the result of determining the network
+ // partition key given request.
+ // TODO
- if (client[kClosedResolve] && !client[kSize]) {
- client[kClosedResolve]()
- client[kClosedResolve] = null
- return
- }
+ // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
+ // "no".
+ const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
- const socket = client[kSocket]
+ // 8. Switch on request’s mode:
+ if (request.mode === 'websocket') {
+ // Let connection be the result of obtaining a WebSocket connection,
+ // given request’s current URL.
+ // TODO
+ } else {
+ // Let connection be the result of obtaining a connection, given
+ // networkPartitionKey, request’s current URL’s origin,
+ // includeCredentials, and forceNewConnection.
+ // TODO
+ }
- if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {
- if (client[kSize] === 0) {
- if (!socket[kNoRef] && socket.unref) {
- socket.unref()
- socket[kNoRef] = true
- }
- } else if (socket[kNoRef] && socket.ref) {
- socket.ref()
- socket[kNoRef] = false
- }
+ // 9. Run these steps, but abort when the ongoing fetch is terminated:
- if (client[kSize] === 0) {
- if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
- socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)
- }
- } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
- if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
- const request = client[kQueue][client[kRunningIdx]]
- const headersTimeout = request.headersTimeout != null
- ? request.headersTimeout
- : client[kHeadersTimeout]
- socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
- }
- }
- }
+ // 1. If connection is failure, then return a network error.
- if (client[kBusy]) {
- client[kNeedDrain] = 2
- } else if (client[kNeedDrain] === 2) {
- if (sync) {
- client[kNeedDrain] = 1
- process.nextTick(emitDrain, client)
- } else {
- emitDrain(client)
- }
- continue
- }
+ // 2. Set timingInfo’s final connection timing info to the result of
+ // calling clamp and coarsen connection timing info with connection’s
+ // timing info, timingInfo’s post-redirect start time, and fetchParams’s
+ // cross-origin isolated capability.
- if (client[kPending] === 0) {
- return
- }
+ // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
+ // and request’s body’s source is null, then append (`Transfer-Encoding`,
+ // `chunked`) to request’s header list.
- if (client[kRunning] >= (client[kPipelining] || 1)) {
- return
- }
+ // 4. Set timingInfo’s final network-request start time to the coarsened
+ // shared current time given fetchParams’s cross-origin isolated
+ // capability.
- const request = client[kQueue][client[kPendingIdx]]
+ // 5. Set response to the result of making an HTTP request over connection
+ // using request with the following caveats:
- if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
- if (client[kRunning] > 0) {
- return
- }
+ // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
+ // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
- client[kServerName] = request.servername
+ // - If request’s body is non-null, and request’s body’s source is null,
+ // then the user agent may have a buffer of up to 64 kibibytes and store
+ // a part of request’s body in that buffer. If the user agent reads from
+ // request’s body beyond that buffer’s size and the user agent needs to
+ // resend request, then instead return a network error.
- if (socket && socket.servername !== request.servername) {
- util.destroy(socket, new InformationalError('servername changed'))
- return
- }
- }
+ // - Set timingInfo’s final network-response start time to the coarsened
+ // shared current time given fetchParams’s cross-origin isolated capability,
+ // immediately after the user agent’s HTTP parser receives the first byte
+ // of the response (e.g., frame header bytes for HTTP/2 or response status
+ // line for HTTP/1.x).
- if (client[kConnecting]) {
- return
- }
+ // - Wait until all the headers are transmitted.
- if (!socket && !client[kHTTP2Session]) {
- connect(client)
- return
- }
+ // - Any responses whose status is in the range 100 to 199, inclusive,
+ // and is not 101, are to be ignored, except for the purposes of setting
+ // timingInfo’s final network-response start time above.
- if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {
- return
- }
+ // - If request’s header list contains `Transfer-Encoding`/`chunked` and
+ // response is transferred via HTTP/1.0 or older, then return a network
+ // error.
- if (client[kRunning] > 0 && !request.idempotent) {
- // Non-idempotent request cannot be retried.
- // Ensure that no other requests are inflight and
- // could cause failure.
- return
- }
+ // - If the HTTP request results in a TLS client certificate dialog, then:
- if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
- // Don't dispatch an upgrade until all preceding requests have completed.
- // A misbehaving server might upgrade the connection before all pipelined
- // request has completed.
- return
- }
+ // 1. If request’s window is an environment settings object, make the
+ // dialog available in request’s window.
- if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
- (util.isStream(request.body) || util.isAsyncIterable(request.body))) {
- // Request with stream or iterator body can error while other requests
- // are inflight and indirectly error those as well.
- // Ensure this doesn't happen by waiting for inflight
- // to complete before dispatching.
+ // 2. Otherwise, return a network error.
- // Request with stream or iterator body cannot be retried.
- // Ensure that no other requests are inflight and
- // could cause failure.
- return
- }
+ // To transmit request’s body body, run these steps:
+ let requestBody = null
+ // 1. If body is null and fetchParams’s process request end-of-body is
+ // non-null, then queue a fetch task given fetchParams’s process request
+ // end-of-body and fetchParams’s task destination.
+ if (request.body == null && fetchParams.processRequestEndOfBody) {
+ queueMicrotask(() => fetchParams.processRequestEndOfBody())
+ } else if (request.body != null) {
+ // 2. Otherwise, if body is non-null:
- if (!request.aborted && write(client, request)) {
- client[kPendingIdx]++
- } else {
- client[kQueue].splice(client[kPendingIdx], 1)
- }
- }
-}
+ // 1. Let processBodyChunk given bytes be these steps:
+ const processBodyChunk = async function * (bytes) {
+ // 1. If the ongoing fetch is terminated, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
-// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
-function shouldSendContentLength (method) {
- return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
-}
+ // 2. Run this step in parallel: transmit bytes.
+ yield bytes
-function write (client, request) {
- if (client[kHTTPConnVersion] === 'h2') {
- writeH2(client, client[kHTTP2Session], request)
- return
- }
+ // 3. If fetchParams’s process request body is non-null, then run
+ // fetchParams’s process request body given bytes’s length.
+ fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
+ }
- const { body, method, path, host, upgrade, headers, blocking, reset } = request
+ // 2. Let processEndOfBody be these steps:
+ const processEndOfBody = () => {
+ // 1. If fetchParams is canceled, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
- // https://tools.ietf.org/html/rfc7231#section-4.3.1
- // https://tools.ietf.org/html/rfc7231#section-4.3.2
- // https://tools.ietf.org/html/rfc7231#section-4.3.5
+ // 2. If fetchParams’s process request end-of-body is non-null,
+ // then run fetchParams’s process request end-of-body.
+ if (fetchParams.processRequestEndOfBody) {
+ fetchParams.processRequestEndOfBody()
+ }
+ }
- // Sending a payload body on a request that does not
- // expect it can cause undefined behavior on some
- // servers and corrupt connection state. Do not
- // re-use the connection for further requests.
+ // 3. Let processBodyError given e be these steps:
+ const processBodyError = (e) => {
+ // 1. If fetchParams is canceled, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
- const expectsPayload = (
- method === 'PUT' ||
- method === 'POST' ||
- method === 'PATCH'
- )
+ // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
+ if (e.name === 'AbortError') {
+ fetchParams.controller.abort()
+ } else {
+ fetchParams.controller.terminate(e)
+ }
+ }
- if (body && typeof body.read === 'function') {
- // Try to read EOF in order to get length.
- body.read(0)
+ // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
+ // processBodyError, and fetchParams’s task destination.
+ requestBody = (async function * () {
+ try {
+ for await (const bytes of request.body.stream) {
+ yield * processBodyChunk(bytes)
+ }
+ processEndOfBody()
+ } catch (err) {
+ processBodyError(err)
+ }
+ })()
}
- const bodyLength = util.bodyLength(body)
-
- let contentLength = bodyLength
-
- if (contentLength === null) {
- contentLength = request.contentLength
- }
+ try {
+ // socket is only provided for websockets
+ const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
- if (contentLength === 0 && !expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD NOT send a Content-Length header field when
- // the request message does not contain a payload body and the method
- // semantics do not anticipate such a body.
+ if (socket) {
+ response = makeResponse({ status, statusText, headersList, socket })
+ } else {
+ const iterator = body[Symbol.asyncIterator]()
+ fetchParams.controller.next = () => iterator.next()
- contentLength = null
- }
+ response = makeResponse({ status, statusText, headersList })
+ }
+ } catch (err) {
+ // 10. If aborted, then:
+ if (err.name === 'AbortError') {
+ // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
+ fetchParams.controller.connection.destroy()
- // https://github.com/nodejs/undici/issues/2046
- // A user agent may send a Content-Length header with 0 value, this should be allowed.
- if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
- if (client[kStrictContentLength]) {
- errorRequest(client, request, new RequestContentLengthMismatchError())
- return false
+ // 2. Return the appropriate network error for fetchParams.
+ return makeAppropriateNetworkError(fetchParams, err)
}
- process.emitWarning(new RequestContentLengthMismatchError())
+ return makeNetworkError(err)
}
- const socket = client[kSocket]
+ // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
+ // if it is suspended.
+ const pullAlgorithm = () => {
+ fetchParams.controller.resume()
+ }
- try {
- request.onConnect((err) => {
- if (request.aborted || request.completed) {
- return
- }
+ // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
+ // controller with reason, given reason.
+ const cancelAlgorithm = (reason) => {
+ fetchParams.controller.abort(reason)
+ }
- errorRequest(client, request, err || new RequestAbortedError())
+ // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
+ // the user agent.
+ // TODO
- util.destroy(socket, new InformationalError('aborted'))
- })
- } catch (err) {
- errorRequest(client, request, err)
- }
+ // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
+ // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
+ // TODO
- if (request.aborted) {
- return false
+ // 15. Let stream be a new ReadableStream.
+ // 16. Set up stream with pullAlgorithm set to pullAlgorithm,
+ // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to
+ // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
}
- if (method === 'HEAD') {
- // https://github.com/mcollina/undici/issues/258
- // Close after a HEAD request to interop with misbehaving servers
- // that may send a body in the response.
+ const stream = new ReadableStream(
+ {
+ async start (controller) {
+ fetchParams.controller.controller = controller
+ },
+ async pull (controller) {
+ await pullAlgorithm(controller)
+ },
+ async cancel (reason) {
+ await cancelAlgorithm(reason)
+ }
+ },
+ {
+ highWaterMark: 0,
+ size () {
+ return 1
+ }
+ }
+ )
- socket[kReset] = true
- }
+ // 17. Run these steps, but abort when the ongoing fetch is terminated:
- if (upgrade || method === 'CONNECT') {
- // On CONNECT or upgrade, block pipeline from dispatching further
- // requests on this connection.
+ // 1. Set response’s body to a new body whose stream is stream.
+ response.body = { stream }
- socket[kReset] = true
- }
+ // 2. If response is not a network error and request’s cache mode is
+ // not "no-store", then update response in httpCache for request.
+ // TODO
- if (reset != null) {
- socket[kReset] = reset
- }
+ // 3. If includeCredentials is true and the user agent is not configured
+ // to block cookies for request (see section 7 of [COOKIES]), then run the
+ // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
+ // the value of each header whose name is a byte-case-insensitive match for
+ // `Set-Cookie` in response’s header list, if any, and request’s current URL.
+ // TODO
- if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
- socket[kReset] = true
- }
+ // 18. If aborted, then:
+ // TODO
- if (blocking) {
- socket[kBlocking] = true
- }
+ // 19. Run these steps in parallel:
- let header = `${method} ${path} HTTP/1.1\r\n`
+ // 1. Run these steps, but abort when fetchParams is canceled:
+ fetchParams.controller.on('terminated', onAborted)
+ fetchParams.controller.resume = async () => {
+ // 1. While true
+ while (true) {
+ // 1-3. See onData...
- if (typeof host === 'string') {
- header += `host: ${host}\r\n`
- } else {
- header += client[kHostHeader]
- }
+ // 4. Set bytes to the result of handling content codings given
+ // codings and bytes.
+ let bytes
+ let isFailure
+ try {
+ const { done, value } = await fetchParams.controller.next()
- if (upgrade) {
- header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
- } else if (client[kPipelining] && !socket[kReset]) {
- header += 'connection: keep-alive\r\n'
- } else {
- header += 'connection: close\r\n'
- }
+ if (isAborted(fetchParams)) {
+ break
+ }
- if (headers) {
- header += headers
- }
+ bytes = done ? undefined : value
+ } catch (err) {
+ if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
+ // zlib doesn't like empty streams.
+ bytes = undefined
+ } else {
+ bytes = err
- if (channels.sendHeaders.hasSubscribers) {
- channels.sendHeaders.publish({ request, headers: header, socket })
- }
+ // err may be propagated from the result of calling readablestream.cancel,
+ // which might not be an error. https://github.com/nodejs/undici/issues/2009
+ isFailure = true
+ }
+ }
- /* istanbul ignore else: assertion */
- if (!body || bodyLength === 0) {
- if (contentLength === 0) {
- socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
- } else {
- assert(contentLength === null, 'no body must not have content length')
- socket.write(`${header}\r\n`, 'latin1')
- }
- request.onRequestSent()
- } else if (util.isBuffer(body)) {
- assert(contentLength === body.byteLength, 'buffer body must have content length')
+ if (bytes === undefined) {
+ // 2. Otherwise, if the bytes transmission for response’s message
+ // body is done normally and stream is readable, then close
+ // stream, finalize response for fetchParams and response, and
+ // abort these in-parallel steps.
+ readableStreamClose(fetchParams.controller.controller)
- socket.cork()
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- socket.write(body)
- socket.uncork()
- request.onBodySent(body)
- request.onRequestSent()
- if (!expectsPayload) {
- socket[kReset] = true
- }
- } else if (util.isBlobLike(body)) {
- if (typeof body.stream === 'function') {
- writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })
- } else {
- writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })
- }
- } else if (util.isStream(body)) {
- writeStream({ body, client, request, socket, contentLength, header, expectsPayload })
- } else if (util.isIterable(body)) {
- writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })
- } else {
- assert(false)
- }
+ finalizeResponse(fetchParams, response)
- return true
-}
+ return
+ }
-function writeH2 (client, session, request) {
- const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
+ // 5. Increase timingInfo’s decoded body size by bytes’s length.
+ timingInfo.decodedBodySize += bytes?.byteLength ?? 0
- let headers
- if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())
- else headers = reqHeaders
+ // 6. If bytes is failure, then terminate fetchParams’s controller.
+ if (isFailure) {
+ fetchParams.controller.terminate(bytes)
+ return
+ }
- if (upgrade) {
- errorRequest(client, request, new Error('Upgrade not supported for H2'))
- return false
- }
+ // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
+ // into stream.
+ fetchParams.controller.controller.enqueue(new Uint8Array(bytes))
- try {
- // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?
- request.onConnect((err) => {
- if (request.aborted || request.completed) {
+ // 8. If stream is errored, then terminate the ongoing fetch.
+ if (isErrored(stream)) {
+ fetchParams.controller.terminate()
return
}
- errorRequest(client, request, err || new RequestAbortedError())
- })
- } catch (err) {
- errorRequest(client, request, err)
+ // 9. If stream doesn’t need more data ask the user agent to suspend
+ // the ongoing fetch.
+ if (!fetchParams.controller.controller.desiredSize) {
+ return
+ }
+ }
}
- if (request.aborted) {
- return false
+ // 2. If aborted, then:
+ function onAborted (reason) {
+ // 2. If fetchParams is aborted, then:
+ if (isAborted(fetchParams)) {
+ // 1. Set response’s aborted flag.
+ response.aborted = true
+
+ // 2. If stream is readable, then error stream with the result of
+ // deserialize a serialized abort reason given fetchParams’s
+ // controller’s serialized abort reason and an
+ // implementation-defined realm.
+ if (isReadable(stream)) {
+ fetchParams.controller.controller.error(
+ fetchParams.controller.serializedAbortReason
+ )
+ }
+ } else {
+ // 3. Otherwise, if stream is readable, error stream with a TypeError.
+ if (isReadable(stream)) {
+ fetchParams.controller.controller.error(new TypeError('terminated', {
+ cause: isErrorLike(reason) ? reason : undefined
+ }))
+ }
+ }
+
+ // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
+ // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
+ fetchParams.controller.connection.destroy()
}
- /** @type {import('node:http2').ClientHttp2Stream} */
- let stream
- const h2State = client[kHTTP2SessionState]
+ // 20. Return response.
+ return response
- headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]
- headers[HTTP2_HEADER_METHOD] = method
+ async function dispatch ({ body }) {
+ const url = requestCurrentURL(request)
+ /** @type {import('../..').Agent} */
+ const agent = fetchParams.controller.dispatcher
- if (method === 'CONNECT') {
- session.ref()
- // we are already connected, streams are pending, first request
- // will create a new stream. We trigger a request to create the stream and wait until
- // `ready` event is triggered
- // We disabled endStream to allow the user to write to the stream
- stream = session.request(headers, { endStream: false, signal })
+ return new Promise((resolve, reject) => agent.dispatch(
+ {
+ path: url.pathname + url.search,
+ origin: url.origin,
+ method: request.method,
+ body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
+ headers: request.headersList.entries,
+ maxRedirections: 0,
+ upgrade: request.mode === 'websocket' ? 'websocket' : undefined
+ },
+ {
+ body: null,
+ abort: null,
- if (stream.id && !stream.pending) {
- request.onUpgrade(null, null, stream)
- ++h2State.openStreams
- } else {
- stream.once('ready', () => {
- request.onUpgrade(null, null, stream)
- ++h2State.openStreams
- })
- }
+ onConnect (abort) {
+ // TODO (fix): Do we need connection here?
+ const { connection } = fetchParams.controller
- stream.once('close', () => {
- h2State.openStreams -= 1
- // TODO(HTTP/2): unref only if current streams count is 0
- if (h2State.openStreams === 0) session.unref()
- })
+ if (connection.destroyed) {
+ abort(new DOMException('The operation was aborted.', 'AbortError'))
+ } else {
+ fetchParams.controller.on('terminated', abort)
+ this.abort = connection.abort = abort
+ }
+ },
- return true
- }
+ onHeaders (status, headersList, resume, statusText) {
+ if (status < 200) {
+ return
+ }
- // https://tools.ietf.org/html/rfc7540#section-8.3
- // :path and :scheme headers must be omited when sending CONNECT
+ let codings = []
+ let location = ''
- headers[HTTP2_HEADER_PATH] = path
- headers[HTTP2_HEADER_SCHEME] = 'https'
+ const headers = new Headers()
- // https://tools.ietf.org/html/rfc7231#section-4.3.1
- // https://tools.ietf.org/html/rfc7231#section-4.3.2
- // https://tools.ietf.org/html/rfc7231#section-4.3.5
+ // For H2, the headers are a plain JS object
+ // We distinguish between them and iterate accordingly
+ if (Array.isArray(headersList)) {
+ for (let n = 0; n < headersList.length; n += 2) {
+ const key = headersList[n + 0].toString('latin1')
+ const val = headersList[n + 1].toString('latin1')
+ if (key.toLowerCase() === 'content-encoding') {
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
+ // "All content-coding values are case-insensitive..."
+ codings = val.toLowerCase().split(',').map((x) => x.trim())
+ } else if (key.toLowerCase() === 'location') {
+ location = val
+ }
- // Sending a payload body on a request that does not
- // expect it can cause undefined behavior on some
- // servers and corrupt connection state. Do not
- // re-use the connection for further requests.
+ headers[kHeadersList].append(key, val)
+ }
+ } else {
+ const keys = Object.keys(headersList)
+ for (const key of keys) {
+ const val = headersList[key]
+ if (key.toLowerCase() === 'content-encoding') {
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
+ // "All content-coding values are case-insensitive..."
+ codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()
+ } else if (key.toLowerCase() === 'location') {
+ location = val
+ }
- const expectsPayload = (
- method === 'PUT' ||
- method === 'POST' ||
- method === 'PATCH'
- )
+ headers[kHeadersList].append(key, val)
+ }
+ }
- if (body && typeof body.read === 'function') {
- // Try to read EOF in order to get length.
- body.read(0)
- }
+ this.body = new Readable({ read: resume })
- let contentLength = util.bodyLength(body)
+ const decoders = []
- if (contentLength == null) {
- contentLength = request.contentLength
- }
+ const willFollow = request.redirect === 'follow' &&
+ location &&
+ redirectStatusSet.has(status)
- if (contentLength === 0 || !expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD NOT send a Content-Length header field when
- // the request message does not contain a payload body and the method
- // semantics do not anticipate such a body.
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
+ if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
+ for (const coding of codings) {
+ // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
+ if (coding === 'x-gzip' || coding === 'gzip') {
+ decoders.push(zlib.createGunzip({
+ // Be less strict when decoding compressed responses, since sometimes
+ // servers send slightly invalid responses that are still accepted
+ // by common browsers.
+ // Always using Z_SYNC_FLUSH is what cURL does.
+ flush: zlib.constants.Z_SYNC_FLUSH,
+ finishFlush: zlib.constants.Z_SYNC_FLUSH
+ }))
+ } else if (coding === 'deflate') {
+ decoders.push(zlib.createInflate())
+ } else if (coding === 'br') {
+ decoders.push(zlib.createBrotliDecompress())
+ } else {
+ decoders.length = 0
+ break
+ }
+ }
+ }
- contentLength = null
- }
+ resolve({
+ status,
+ statusText,
+ headersList: headers[kHeadersList],
+ body: decoders.length
+ ? pipeline(this.body, ...decoders, () => { })
+ : this.body.on('error', () => {})
+ })
- // https://github.com/nodejs/undici/issues/2046
- // A user agent may send a Content-Length header with 0 value, this should be allowed.
- if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
- if (client[kStrictContentLength]) {
- errorRequest(client, request, new RequestContentLengthMismatchError())
- return false
- }
+ return true
+ },
- process.emitWarning(new RequestContentLengthMismatchError())
- }
+ onData (chunk) {
+ if (fetchParams.controller.dump) {
+ return
+ }
- if (contentLength != null) {
- assert(body, 'no body must not have content length')
- headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
- }
+ // 1. If one or more bytes have been transmitted from response’s
+ // message body, then:
- session.ref()
+ // 1. Let bytes be the transmitted bytes.
+ const bytes = chunk
- const shouldEndStream = method === 'GET' || method === 'HEAD'
- if (expectContinue) {
- headers[HTTP2_HEADER_EXPECT] = '100-continue'
- stream = session.request(headers, { endStream: shouldEndStream, signal })
+ // 2. Let codings be the result of extracting header list values
+ // given `Content-Encoding` and response’s header list.
+ // See pullAlgorithm.
- stream.once('continue', writeBodyH2)
- } else {
- stream = session.request(headers, {
- endStream: shouldEndStream,
- signal
- })
- writeBodyH2()
- }
+ // 3. Increase timingInfo’s encoded body size by bytes’s length.
+ timingInfo.encodedBodySize += bytes.byteLength
- // Increment counter as we have new several streams open
- ++h2State.openStreams
+ // 4. See pullAlgorithm...
- stream.once('response', headers => {
- const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
+ return this.body.push(bytes)
+ },
- if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {
- stream.pause()
- }
- })
+ onComplete () {
+ if (this.abort) {
+ fetchParams.controller.off('terminated', this.abort)
+ }
- stream.once('end', () => {
- request.onComplete([])
- })
+ fetchParams.controller.ended = true
- stream.on('data', (chunk) => {
- if (request.onData(chunk) === false) {
- stream.pause()
- }
- })
+ this.body.push(null)
+ },
- stream.once('close', () => {
- h2State.openStreams -= 1
- // TODO(HTTP/2): unref only if current streams count is 0
- if (h2State.openStreams === 0) {
- session.unref()
- }
- })
+ onError (error) {
+ if (this.abort) {
+ fetchParams.controller.off('terminated', this.abort)
+ }
- stream.once('error', function (err) {
- if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
- h2State.streams -= 1
- util.destroy(stream, err)
- }
- })
+ this.body?.destroy(error)
- stream.once('frameError', (type, code) => {
- const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
- errorRequest(client, request, err)
+ fetchParams.controller.terminate(error)
- if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
- h2State.streams -= 1
- util.destroy(stream, err)
- }
- })
+ reject(error)
+ },
- // stream.on('aborted', () => {
- // // TODO(HTTP/2): Support aborted
- // })
+ onUpgrade (status, headersList, socket) {
+ if (status !== 101) {
+ return
+ }
- // stream.on('timeout', () => {
- // // TODO(HTTP/2): Support timeout
- // })
+ const headers = new Headers()
- // stream.on('push', headers => {
- // // TODO(HTTP/2): Suppor push
- // })
+ for (let n = 0; n < headersList.length; n += 2) {
+ const key = headersList[n + 0].toString('latin1')
+ const val = headersList[n + 1].toString('latin1')
- // stream.on('trailers', headers => {
- // // TODO(HTTP/2): Support trailers
- // })
+ headers[kHeadersList].append(key, val)
+ }
- return true
+ resolve({
+ status,
+ statusText: STATUS_CODES[status],
+ headersList: headers[kHeadersList],
+ socket
+ })
- function writeBodyH2 () {
- /* istanbul ignore else: assertion */
- if (!body) {
- request.onRequestSent()
- } else if (util.isBuffer(body)) {
- assert(contentLength === body.byteLength, 'buffer body must have content length')
- stream.cork()
- stream.write(body)
- stream.uncork()
- stream.end()
- request.onBodySent(body)
- request.onRequestSent()
- } else if (util.isBlobLike(body)) {
- if (typeof body.stream === 'function') {
- writeIterable({
- client,
- request,
- contentLength,
- h2stream: stream,
- expectsPayload,
- body: body.stream(),
- socket: client[kSocket],
- header: ''
- })
- } else {
- writeBlob({
- body,
- client,
- request,
- contentLength,
- expectsPayload,
- h2stream: stream,
- header: '',
- socket: client[kSocket]
- })
+ return true
+ }
}
- } else if (util.isStream(body)) {
- writeStream({
- body,
- client,
- request,
- contentLength,
- expectsPayload,
- socket: client[kSocket],
- h2stream: stream,
- header: ''
- })
- } else if (util.isIterable(body)) {
- writeIterable({
- body,
- client,
- request,
- contentLength,
- expectsPayload,
- header: '',
- h2stream: stream,
- socket: client[kSocket]
- })
- } else {
- assert(false)
- }
+ ))
}
}
-function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
+module.exports = {
+ fetch,
+ Fetch,
+ fetching,
+ finalizeAndReportTiming
+}
- if (client[kHTTPConnVersion] === 'h2') {
- // For HTTP/2, is enough to pipe the stream
- const pipe = pipeline(
- body,
- h2stream,
- (err) => {
- if (err) {
- util.destroy(body, err)
- util.destroy(h2stream, err)
- } else {
- request.onRequestSent()
- }
- }
- )
- pipe.on('data', onPipeData)
- pipe.once('end', () => {
- pipe.removeListener('data', onPipeData)
- util.destroy(pipe)
- })
+/***/ }),
- function onPipeData (chunk) {
- request.onBodySent(chunk)
- }
+/***/ 2630:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return
- }
+/* globals AbortController */
- let finished = false
- const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
- const onData = function (chunk) {
- if (finished) {
- return
- }
+const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(37791)
+const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(12801)
+const { FinalizationRegistry } = __nccwpck_require__(90022)()
+const util = __nccwpck_require__(89500)
+const {
+ isValidHTTPToken,
+ sameOrigin,
+ normalizeMethod,
+ makePolicyContainer,
+ normalizeMethodRecord
+} = __nccwpck_require__(72847)
+const {
+ forbiddenMethodsSet,
+ corsSafeListedMethodsSet,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ requestDuplex
+} = __nccwpck_require__(21234)
+const { kEnumerableProperty } = util
+const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(63730)
+const { webidl } = __nccwpck_require__(94354)
+const { getGlobalOrigin } = __nccwpck_require__(62896)
+const { URLSerializer } = __nccwpck_require__(37246)
+const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
+const assert = __nccwpck_require__(42613)
+const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(24434)
- try {
- if (!writer.write(chunk) && this.pause) {
- this.pause()
- }
- } catch (err) {
- util.destroy(this, err)
- }
- }
- const onDrain = function () {
- if (finished) {
- return
- }
+let TransformStream = globalThis.TransformStream
- if (body.resume) {
- body.resume()
- }
- }
- const onAbort = function () {
- if (finished) {
+const kAbortController = Symbol('abortController')
+
+const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
+ signal.removeEventListener('abort', abort)
+})
+
+// https://fetch.spec.whatwg.org/#request-class
+class Request {
+ // https://fetch.spec.whatwg.org/#dom-request
+ constructor (input, init = {}) {
+ if (input === kConstruct) {
return
}
- const err = new RequestAbortedError()
- queueMicrotask(() => onFinished(err))
- }
- const onFinished = function (err) {
- if (finished) {
- return
+
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })
+
+ input = webidl.converters.RequestInfo(input)
+ init = webidl.converters.RequestInit(init)
+
+ // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
+ this[kRealm] = {
+ settingsObject: {
+ baseUrl: getGlobalOrigin(),
+ get origin () {
+ return this.baseUrl?.origin
+ },
+ policyContainer: makePolicyContainer()
+ }
}
- finished = true
+ // 1. Let request be null.
+ let request = null
- assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
+ // 2. Let fallbackMode be null.
+ let fallbackMode = null
- socket
- .off('drain', onDrain)
- .off('error', onFinished)
+ // 3. Let baseURL be this’s relevant settings object’s API base URL.
+ const baseUrl = this[kRealm].settingsObject.baseUrl
- body
- .removeListener('data', onData)
- .removeListener('end', onFinished)
- .removeListener('error', onFinished)
- .removeListener('close', onAbort)
+ // 4. Let signal be null.
+ let signal = null
- if (!err) {
+ // 5. If input is a string, then:
+ if (typeof input === 'string') {
+ // 1. Let parsedURL be the result of parsing input with baseURL.
+ // 2. If parsedURL is failure, then throw a TypeError.
+ let parsedURL
try {
- writer.end()
- } catch (er) {
- err = er
+ parsedURL = new URL(input, baseUrl)
+ } catch (err) {
+ throw new TypeError('Failed to parse URL from ' + input, { cause: err })
}
- }
- writer.destroy(err)
+ // 3. If parsedURL includes credentials, then throw a TypeError.
+ if (parsedURL.username || parsedURL.password) {
+ throw new TypeError(
+ 'Request cannot be constructed from a URL that includes credentials: ' +
+ input
+ )
+ }
- if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
- util.destroy(body, err)
+ // 4. Set request to a new request whose URL is parsedURL.
+ request = makeRequest({ urlList: [parsedURL] })
+
+ // 5. Set fallbackMode to "cors".
+ fallbackMode = 'cors'
} else {
- util.destroy(body)
- }
- }
+ // 6. Otherwise:
- body
- .on('data', onData)
- .on('end', onFinished)
- .on('error', onFinished)
- .on('close', onAbort)
+ // 7. Assert: input is a Request object.
+ assert(input instanceof Request)
- if (body.resume) {
- body.resume()
- }
+ // 8. Set request to input’s request.
+ request = input[kState]
- socket
- .on('drain', onDrain)
- .on('error', onFinished)
-}
+ // 9. Set signal to input’s signal.
+ signal = input[kSignal]
+ }
-async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
- assert(contentLength === body.size, 'blob body must have content length')
+ // 7. Let origin be this’s relevant settings object’s origin.
+ const origin = this[kRealm].settingsObject.origin
- const isH2 = client[kHTTPConnVersion] === 'h2'
- try {
- if (contentLength != null && contentLength !== body.size) {
- throw new RequestContentLengthMismatchError()
+ // 8. Let window be "client".
+ let window = 'client'
+
+ // 9. If request’s window is an environment settings object and its origin
+ // is same origin with origin, then set window to request’s window.
+ if (
+ request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
+ sameOrigin(request.window, origin)
+ ) {
+ window = request.window
}
- const buffer = Buffer.from(await body.arrayBuffer())
+ // 10. If init["window"] exists and is non-null, then throw a TypeError.
+ if (init.window != null) {
+ throw new TypeError(`'window' option '${window}' must be null`)
+ }
- if (isH2) {
- h2stream.cork()
- h2stream.write(buffer)
- h2stream.uncork()
- } else {
- socket.cork()
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- socket.write(buffer)
- socket.uncork()
+ // 11. If init["window"] exists, then set window to "no-window".
+ if ('window' in init) {
+ window = 'no-window'
}
- request.onBodySent(buffer)
- request.onRequestSent()
+ // 12. Set request to a new request with the following properties:
+ request = makeRequest({
+ // URL request’s URL.
+ // undici implementation note: this is set as the first item in request's urlList in makeRequest
+ // method request’s method.
+ method: request.method,
+ // header list A copy of request’s header list.
+ // undici implementation note: headersList is cloned in makeRequest
+ headersList: request.headersList,
+ // unsafe-request flag Set.
+ unsafeRequest: request.unsafeRequest,
+ // client This’s relevant settings object.
+ client: this[kRealm].settingsObject,
+ // window window.
+ window,
+ // priority request’s priority.
+ priority: request.priority,
+ // origin request’s origin. The propagation of the origin is only significant for navigation requests
+ // being handled by a service worker. In this scenario a request can have an origin that is different
+ // from the current client.
+ origin: request.origin,
+ // referrer request’s referrer.
+ referrer: request.referrer,
+ // referrer policy request’s referrer policy.
+ referrerPolicy: request.referrerPolicy,
+ // mode request’s mode.
+ mode: request.mode,
+ // credentials mode request’s credentials mode.
+ credentials: request.credentials,
+ // cache mode request’s cache mode.
+ cache: request.cache,
+ // redirect mode request’s redirect mode.
+ redirect: request.redirect,
+ // integrity metadata request’s integrity metadata.
+ integrity: request.integrity,
+ // keepalive request’s keepalive.
+ keepalive: request.keepalive,
+ // reload-navigation flag request’s reload-navigation flag.
+ reloadNavigation: request.reloadNavigation,
+ // history-navigation flag request’s history-navigation flag.
+ historyNavigation: request.historyNavigation,
+ // URL list A clone of request’s URL list.
+ urlList: [...request.urlList]
+ })
- if (!expectsPayload) {
- socket[kReset] = true
- }
+ const initHasKey = Object.keys(init).length !== 0
- resume(client)
- } catch (err) {
- util.destroy(isH2 ? h2stream : socket, err)
- }
-}
+ // 13. If init is not empty, then:
+ if (initHasKey) {
+ // 1. If request’s mode is "navigate", then set it to "same-origin".
+ if (request.mode === 'navigate') {
+ request.mode = 'same-origin'
+ }
-async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
+ // 2. Unset request’s reload-navigation flag.
+ request.reloadNavigation = false
- let callback = null
- function onDrain () {
- if (callback) {
- const cb = callback
- callback = null
- cb()
- }
- }
+ // 3. Unset request’s history-navigation flag.
+ request.historyNavigation = false
- const waitForDrain = () => new Promise((resolve, reject) => {
- assert(callback === null)
+ // 4. Set request’s origin to "client".
+ request.origin = 'client'
- if (socket[kError]) {
- reject(socket[kError])
- } else {
- callback = resolve
- }
- })
+ // 5. Set request’s referrer to "client"
+ request.referrer = 'client'
- if (client[kHTTPConnVersion] === 'h2') {
- h2stream
- .on('close', onDrain)
- .on('drain', onDrain)
+ // 6. Set request’s referrer policy to the empty string.
+ request.referrerPolicy = ''
- try {
- // It's up to the user to somehow abort the async iterable.
- for await (const chunk of body) {
- if (socket[kError]) {
- throw socket[kError]
- }
+ // 7. Set request’s URL to request’s current URL.
+ request.url = request.urlList[request.urlList.length - 1]
- const res = h2stream.write(chunk)
- request.onBodySent(chunk)
- if (!res) {
- await waitForDrain()
- }
- }
- } catch (err) {
- h2stream.destroy(err)
- } finally {
- request.onRequestSent()
- h2stream.end()
- h2stream
- .off('close', onDrain)
- .off('drain', onDrain)
+ // 8. Set request’s URL list to « request’s URL ».
+ request.urlList = [request.url]
}
- return
- }
-
- socket
- .on('close', onDrain)
- .on('drain', onDrain)
+ // 14. If init["referrer"] exists, then:
+ if (init.referrer !== undefined) {
+ // 1. Let referrer be init["referrer"].
+ const referrer = init.referrer
- const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
- try {
- // It's up to the user to somehow abort the async iterable.
- for await (const chunk of body) {
- if (socket[kError]) {
- throw socket[kError]
- }
+ // 2. If referrer is the empty string, then set request’s referrer to "no-referrer".
+ if (referrer === '') {
+ request.referrer = 'no-referrer'
+ } else {
+ // 1. Let parsedReferrer be the result of parsing referrer with
+ // baseURL.
+ // 2. If parsedReferrer is failure, then throw a TypeError.
+ let parsedReferrer
+ try {
+ parsedReferrer = new URL(referrer, baseUrl)
+ } catch (err) {
+ throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
+ }
- if (!writer.write(chunk)) {
- await waitForDrain()
+ // 3. If one of the following is true
+ // - parsedReferrer’s scheme is "about" and path is the string "client"
+ // - parsedReferrer’s origin is not same origin with origin
+ // then set request’s referrer to "client".
+ if (
+ (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||
+ (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl))
+ ) {
+ request.referrer = 'client'
+ } else {
+ // 4. Otherwise, set request’s referrer to parsedReferrer.
+ request.referrer = parsedReferrer
+ }
}
}
- writer.end()
- } catch (err) {
- writer.destroy(err)
- } finally {
- socket
- .off('close', onDrain)
- .off('drain', onDrain)
- }
-}
+ // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
+ // to it.
+ if (init.referrerPolicy !== undefined) {
+ request.referrerPolicy = init.referrerPolicy
+ }
-class AsyncWriter {
- constructor ({ socket, request, contentLength, client, expectsPayload, header }) {
- this.socket = socket
- this.request = request
- this.contentLength = contentLength
- this.client = client
- this.bytesWritten = 0
- this.expectsPayload = expectsPayload
- this.header = header
+ // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
+ let mode
+ if (init.mode !== undefined) {
+ mode = init.mode
+ } else {
+ mode = fallbackMode
+ }
- socket[kWriting] = true
- }
+ // 17. If mode is "navigate", then throw a TypeError.
+ if (mode === 'navigate') {
+ throw webidl.errors.exception({
+ header: 'Request constructor',
+ message: 'invalid request mode navigate.'
+ })
+ }
- write (chunk) {
- const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
+ // 18. If mode is non-null, set request’s mode to mode.
+ if (mode != null) {
+ request.mode = mode
+ }
- if (socket[kError]) {
- throw socket[kError]
+ // 19. If init["credentials"] exists, then set request’s credentials mode
+ // to it.
+ if (init.credentials !== undefined) {
+ request.credentials = init.credentials
}
- if (socket.destroyed) {
- return false
+ // 18. If init["cache"] exists, then set request’s cache mode to it.
+ if (init.cache !== undefined) {
+ request.cache = init.cache
}
- const len = Buffer.byteLength(chunk)
- if (!len) {
- return true
+ // 21. If request’s cache mode is "only-if-cached" and request’s mode is
+ // not "same-origin", then throw a TypeError.
+ if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
+ throw new TypeError(
+ "'only-if-cached' can be set only with 'same-origin' mode"
+ )
}
- // We should defer writing chunks.
- if (contentLength !== null && bytesWritten + len > contentLength) {
- if (client[kStrictContentLength]) {
- throw new RequestContentLengthMismatchError()
- }
+ // 22. If init["redirect"] exists, then set request’s redirect mode to it.
+ if (init.redirect !== undefined) {
+ request.redirect = init.redirect
+ }
- process.emitWarning(new RequestContentLengthMismatchError())
+ // 23. If init["integrity"] exists, then set request’s integrity metadata to it.
+ if (init.integrity != null) {
+ request.integrity = String(init.integrity)
}
- socket.cork()
+ // 24. If init["keepalive"] exists, then set request’s keepalive to it.
+ if (init.keepalive !== undefined) {
+ request.keepalive = Boolean(init.keepalive)
+ }
- if (bytesWritten === 0) {
- if (!expectsPayload) {
- socket[kReset] = true
+ // 25. If init["method"] exists, then:
+ if (init.method !== undefined) {
+ // 1. Let method be init["method"].
+ let method = init.method
+
+ // 2. If method is not a method or method is a forbidden method, then
+ // throw a TypeError.
+ if (!isValidHTTPToken(method)) {
+ throw new TypeError(`'${method}' is not a valid HTTP method.`)
}
- if (contentLength === null) {
- socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
- } else {
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ if (forbiddenMethodsSet.has(method.toUpperCase())) {
+ throw new TypeError(`'${method}' HTTP method is unsupported.`)
}
+
+ // 3. Normalize method.
+ method = normalizeMethodRecord[method] ?? normalizeMethod(method)
+
+ // 4. Set request’s method to method.
+ request.method = method
}
- if (contentLength === null) {
- socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
+ // 26. If init["signal"] exists, then set signal to it.
+ if (init.signal !== undefined) {
+ signal = init.signal
}
- this.bytesWritten += len
+ // 27. Set this’s request to request.
+ this[kState] = request
- const ret = socket.write(chunk)
+ // 28. Set this’s signal to a new AbortSignal object with this’s relevant
+ // Realm.
+ // TODO: could this be simplified with AbortSignal.any
+ // (https://dom.spec.whatwg.org/#dom-abortsignal-any)
+ const ac = new AbortController()
+ this[kSignal] = ac.signal
+ this[kSignal][kRealm] = this[kRealm]
- socket.uncork()
+ // 29. If signal is not null, then make this’s signal follow signal.
+ if (signal != null) {
+ if (
+ !signal ||
+ typeof signal.aborted !== 'boolean' ||
+ typeof signal.addEventListener !== 'function'
+ ) {
+ throw new TypeError(
+ "Failed to construct 'Request': member signal is not of type AbortSignal."
+ )
+ }
- request.onBodySent(chunk)
+ if (signal.aborted) {
+ ac.abort(signal.reason)
+ } else {
+ // Keep a strong ref to ac while request object
+ // is alive. This is needed to prevent AbortController
+ // from being prematurely garbage collected.
+ // See, https://github.com/nodejs/undici/issues/1926.
+ this[kAbortController] = ac
- if (!ret) {
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
- // istanbul ignore else: only for jest
- if (socket[kParser].timeout.refresh) {
- socket[kParser].timeout.refresh()
+ const acRef = new WeakRef(ac)
+ const abort = function () {
+ const ac = acRef.deref()
+ if (ac !== undefined) {
+ ac.abort(this.reason)
+ }
}
+
+ // Third-party AbortControllers may not work with these.
+ // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
+ try {
+ // If the max amount of listeners is equal to the default, increase it
+ // This is only available in node >= v19.9.0
+ if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
+ setMaxListeners(100, signal)
+ } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
+ setMaxListeners(100, signal)
+ }
+ } catch {}
+
+ util.addAbortListener(signal, abort)
+ requestFinalizer.register(ac, { signal, abort })
}
}
- return ret
- }
-
- end () {
- const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
- request.onRequestSent()
+ // 30. Set this’s headers to a new Headers object with this’s relevant
+ // Realm, whose header list is request’s header list and guard is
+ // "request".
+ this[kHeaders] = new Headers(kConstruct)
+ this[kHeaders][kHeadersList] = request.headersList
+ this[kHeaders][kGuard] = 'request'
+ this[kHeaders][kRealm] = this[kRealm]
- socket[kWriting] = false
+ // 31. If this’s request’s mode is "no-cors", then:
+ if (mode === 'no-cors') {
+ // 1. If this’s request’s method is not a CORS-safelisted method,
+ // then throw a TypeError.
+ if (!corsSafeListedMethodsSet.has(request.method)) {
+ throw new TypeError(
+ `'${request.method} is unsupported in no-cors mode.`
+ )
+ }
- if (socket[kError]) {
- throw socket[kError]
+ // 2. Set this’s headers’s guard to "request-no-cors".
+ this[kHeaders][kGuard] = 'request-no-cors'
}
- if (socket.destroyed) {
- return
- }
+ // 32. If init is not empty, then:
+ if (initHasKey) {
+ /** @type {HeadersList} */
+ const headersList = this[kHeaders][kHeadersList]
+ // 1. Let headers be a copy of this’s headers and its associated header
+ // list.
+ // 2. If init["headers"] exists, then set headers to init["headers"].
+ const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)
- if (bytesWritten === 0) {
- if (expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD send a Content-Length in a request message when
- // no Transfer-Encoding is sent and the request method defines a meaning
- // for an enclosed payload body.
+ // 3. Empty this’s headers’s header list.
+ headersList.clear()
- socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
+ // 4. If headers is a Headers object, then for each header in its header
+ // list, append header’s name/header’s value to this’s headers.
+ if (headers instanceof HeadersList) {
+ for (const [key, val] of headers) {
+ headersList.append(key, val)
+ }
+ // Note: Copy the `set-cookie` meta-data.
+ headersList.cookies = headers.cookies
} else {
- socket.write(`${header}\r\n`, 'latin1')
+ // 5. Otherwise, fill this’s headers with headers.
+ fillHeaders(this[kHeaders], headers)
}
- } else if (contentLength === null) {
- socket.write('\r\n0\r\n\r\n', 'latin1')
}
- if (contentLength !== null && bytesWritten !== contentLength) {
- if (client[kStrictContentLength]) {
- throw new RequestContentLengthMismatchError()
- } else {
- process.emitWarning(new RequestContentLengthMismatchError())
- }
+ // 33. Let inputBody be input’s request’s body if input is a Request
+ // object; otherwise null.
+ const inputBody = input instanceof Request ? input[kState].body : null
+
+ // 34. If either init["body"] exists and is non-null or inputBody is
+ // non-null, and request’s method is `GET` or `HEAD`, then throw a
+ // TypeError.
+ if (
+ (init.body != null || inputBody != null) &&
+ (request.method === 'GET' || request.method === 'HEAD')
+ ) {
+ throw new TypeError('Request with GET/HEAD method cannot have body.')
}
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
- // istanbul ignore else: only for jest
- if (socket[kParser].timeout.refresh) {
- socket[kParser].timeout.refresh()
+ // 35. Let initBody be null.
+ let initBody = null
+
+ // 36. If init["body"] exists and is non-null, then:
+ if (init.body != null) {
+ // 1. Let Content-Type be null.
+ // 2. Set initBody and Content-Type to the result of extracting
+ // init["body"], with keepalive set to request’s keepalive.
+ const [extractedBody, contentType] = extractBody(
+ init.body,
+ request.keepalive
+ )
+ initBody = extractedBody
+
+ // 3, If Content-Type is non-null and this’s headers’s header list does
+ // not contain `Content-Type`, then append `Content-Type`/Content-Type to
+ // this’s headers.
+ if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) {
+ this[kHeaders].append('content-type', contentType)
}
}
- resume(client)
- }
+ // 37. Let inputOrInitBody be initBody if it is non-null; otherwise
+ // inputBody.
+ const inputOrInitBody = initBody ?? inputBody
- destroy (err) {
- const { socket, client } = this
+ // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is
+ // null, then:
+ if (inputOrInitBody != null && inputOrInitBody.source == null) {
+ // 1. If initBody is non-null and init["duplex"] does not exist,
+ // then throw a TypeError.
+ if (initBody != null && init.duplex == null) {
+ throw new TypeError('RequestInit: duplex option is required when sending a body.')
+ }
- socket[kWriting] = false
+ // 2. If this’s request’s mode is neither "same-origin" nor "cors",
+ // then throw a TypeError.
+ if (request.mode !== 'same-origin' && request.mode !== 'cors') {
+ throw new TypeError(
+ 'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
+ )
+ }
- if (err) {
- assert(client[kRunning] <= 1, 'pipeline should only contain this request')
- util.destroy(socket, err)
+ // 3. Set this’s request’s use-CORS-preflight flag.
+ request.useCORSPreflightFlag = true
}
- }
-}
-
-function errorRequest (client, request, err) {
- try {
- request.onError(err)
- assert(request.aborted)
- } catch (err) {
- client.emit('error', err)
- }
-}
-module.exports = Client
+ // 39. Let finalBody be inputOrInitBody.
+ let finalBody = inputOrInitBody
+ // 40. If initBody is null and inputBody is non-null, then:
+ if (initBody == null && inputBody != null) {
+ // 1. If input is unusable, then throw a TypeError.
+ if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {
+ throw new TypeError(
+ 'Cannot construct a Request with a Request object that has already been used.'
+ )
+ }
-/***/ }),
+ // 2. Set finalBody to the result of creating a proxy for inputBody.
+ if (!TransformStream) {
+ TransformStream = (__nccwpck_require__(63774).TransformStream)
+ }
-/***/ 90022:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // https://streams.spec.whatwg.org/#readablestream-create-a-proxy
+ const identityTransform = new TransformStream()
+ inputBody.stream.pipeThrough(identityTransform)
+ finalBody = {
+ source: inputBody.source,
+ length: inputBody.length,
+ stream: identityTransform.readable
+ }
+ }
+ // 41. Set this’s request’s body to finalBody.
+ this[kState].body = finalBody
+ }
+ // Returns request’s HTTP method, which is "GET" by default.
+ get method () {
+ webidl.brandCheck(this, Request)
-/* istanbul ignore file: only for Node 12 */
+ // The method getter steps are to return this’s request’s method.
+ return this[kState].method
+ }
-const { kConnected, kSize } = __nccwpck_require__(68031)
+ // Returns the URL of request as a string.
+ get url () {
+ webidl.brandCheck(this, Request)
-class CompatWeakRef {
- constructor (value) {
- this.value = value
+ // The url getter steps are to return this’s request’s URL, serialized.
+ return URLSerializer(this[kState].url)
}
- deref () {
- return this.value[kConnected] === 0 && this.value[kSize] === 0
- ? undefined
- : this.value
+ // Returns a Headers object consisting of the headers associated with request.
+ // Note that headers added in the network layer by the user agent will not
+ // be accounted for in this object, e.g., the "Host" header.
+ get headers () {
+ webidl.brandCheck(this, Request)
+
+ // The headers getter steps are to return this’s headers.
+ return this[kHeaders]
}
-}
-class CompatFinalizer {
- constructor (finalizer) {
- this.finalizer = finalizer
+ // Returns the kind of resource requested by request, e.g., "document"
+ // or "script".
+ get destination () {
+ webidl.brandCheck(this, Request)
+
+ // The destination getter are to return this’s request’s destination.
+ return this[kState].destination
}
- register (dispatcher, key) {
- if (dispatcher.on) {
- dispatcher.on('disconnect', () => {
- if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
- this.finalizer(key)
- }
- })
+ // Returns the referrer of request. Its value can be a same-origin URL if
+ // explicitly set in init, the empty string to indicate no referrer, and
+ // "about:client" when defaulting to the global’s default. This is used
+ // during fetching to determine the value of the `Referer` header of the
+ // request being made.
+ get referrer () {
+ webidl.brandCheck(this, Request)
+
+ // 1. If this’s request’s referrer is "no-referrer", then return the
+ // empty string.
+ if (this[kState].referrer === 'no-referrer') {
+ return ''
}
- }
-}
-module.exports = function () {
- // FIXME: remove workaround when the Node bug is fixed
- // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
- if (process.env.NODE_V8_COVERAGE) {
- return {
- WeakRef: CompatWeakRef,
- FinalizationRegistry: CompatFinalizer
+ // 2. If this’s request’s referrer is "client", then return
+ // "about:client".
+ if (this[kState].referrer === 'client') {
+ return 'about:client'
}
+
+ // Return this’s request’s referrer, serialized.
+ return this[kState].referrer.toString()
}
- return {
- WeakRef: global.WeakRef || CompatWeakRef,
- FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
+
+ // Returns the referrer policy associated with request.
+ // This is used during fetching to compute the value of the request’s
+ // referrer.
+ get referrerPolicy () {
+ webidl.brandCheck(this, Request)
+
+ // The referrerPolicy getter steps are to return this’s request’s referrer policy.
+ return this[kState].referrerPolicy
}
-}
+ // Returns the mode associated with request, which is a string indicating
+ // whether the request will use CORS, or will be restricted to same-origin
+ // URLs.
+ get mode () {
+ webidl.brandCheck(this, Request)
-/***/ }),
+ // The mode getter steps are to return this’s request’s mode.
+ return this[kState].mode
+ }
-/***/ 16985:
-/***/ ((module) => {
+ // Returns the credentials mode associated with request,
+ // which is a string indicating whether credentials will be sent with the
+ // request always, never, or only when sent to a same-origin URL.
+ get credentials () {
+ // The credentials getter steps are to return this’s request’s credentials mode.
+ return this[kState].credentials
+ }
+ // Returns the cache mode associated with request,
+ // which is a string indicating how the request will
+ // interact with the browser’s cache when fetching.
+ get cache () {
+ webidl.brandCheck(this, Request)
+ // The cache getter steps are to return this’s request’s cache mode.
+ return this[kState].cache
+ }
-// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size
-const maxAttributeValueSize = 1024
+ // Returns the redirect mode associated with request,
+ // which is a string indicating how redirects for the
+ // request will be handled during fetching. A request
+ // will follow redirects by default.
+ get redirect () {
+ webidl.brandCheck(this, Request)
-// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size
-const maxNameValuePairSize = 4096
+ // The redirect getter steps are to return this’s request’s redirect mode.
+ return this[kState].redirect
+ }
-module.exports = {
- maxAttributeValueSize,
- maxNameValuePairSize
-}
+ // Returns request’s subresource integrity metadata, which is a
+ // cryptographic hash of the resource being fetched. Its value
+ // consists of multiple hashes separated by whitespace. [SRI]
+ get integrity () {
+ webidl.brandCheck(this, Request)
+ // The integrity getter steps are to return this’s request’s integrity
+ // metadata.
+ return this[kState].integrity
+ }
-/***/ }),
+ // Returns a boolean indicating whether or not request can outlive the
+ // global in which it was created.
+ get keepalive () {
+ webidl.brandCheck(this, Request)
-/***/ 64276:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // The keepalive getter steps are to return this’s request’s keepalive.
+ return this[kState].keepalive
+ }
+ // Returns a boolean indicating whether or not request is for a reload
+ // navigation.
+ get isReloadNavigation () {
+ webidl.brandCheck(this, Request)
+ // The isReloadNavigation getter steps are to return true if this’s
+ // request’s reload-navigation flag is set; otherwise false.
+ return this[kState].reloadNavigation
+ }
-const { parseSetCookie } = __nccwpck_require__(16695)
-const { stringify, getHeadersList } = __nccwpck_require__(83126)
-const { webidl } = __nccwpck_require__(94354)
-const { Headers } = __nccwpck_require__(12801)
+ // Returns a boolean indicating whether or not request is for a history
+ // navigation (a.k.a. back-foward navigation).
+ get isHistoryNavigation () {
+ webidl.brandCheck(this, Request)
-/**
- * @typedef {Object} Cookie
- * @property {string} name
- * @property {string} value
- * @property {Date|number|undefined} expires
- * @property {number|undefined} maxAge
- * @property {string|undefined} domain
- * @property {string|undefined} path
- * @property {boolean|undefined} secure
- * @property {boolean|undefined} httpOnly
- * @property {'Strict'|'Lax'|'None'} sameSite
- * @property {string[]} unparsed
- */
+ // The isHistoryNavigation getter steps are to return true if this’s request’s
+ // history-navigation flag is set; otherwise false.
+ return this[kState].historyNavigation
+ }
-/**
- * @param {Headers} headers
- * @returns {Record}
- */
-function getCookies (headers) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })
+ // Returns the signal associated with request, which is an AbortSignal
+ // object indicating whether or not request has been aborted, and its
+ // abort event handler.
+ get signal () {
+ webidl.brandCheck(this, Request)
+
+ // The signal getter steps are to return this’s signal.
+ return this[kSignal]
+ }
- webidl.brandCheck(headers, Headers, { strict: false })
+ get body () {
+ webidl.brandCheck(this, Request)
- const cookie = headers.get('cookie')
- const out = {}
+ return this[kState].body ? this[kState].body.stream : null
+ }
- if (!cookie) {
- return out
+ get bodyUsed () {
+ webidl.brandCheck(this, Request)
+
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
}
- for (const piece of cookie.split(';')) {
- const [name, ...value] = piece.split('=')
+ get duplex () {
+ webidl.brandCheck(this, Request)
- out[name.trim()] = value.join('=')
+ return 'half'
}
- return out
-}
+ // Returns a clone of request.
+ clone () {
+ webidl.brandCheck(this, Request)
-/**
- * @param {Headers} headers
- * @param {string} name
- * @param {{ path?: string, domain?: string }|undefined} attributes
- * @returns {void}
- */
-function deleteCookie (headers, name, attributes) {
- webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })
+ // 1. If this is unusable, then throw a TypeError.
+ if (this.bodyUsed || this.body?.locked) {
+ throw new TypeError('unusable')
+ }
- webidl.brandCheck(headers, Headers, { strict: false })
+ // 2. Let clonedRequest be the result of cloning this’s request.
+ const clonedRequest = cloneRequest(this[kState])
- name = webidl.converters.DOMString(name)
- attributes = webidl.converters.DeleteCookieAttributes(attributes)
+ // 3. Let clonedRequestObject be the result of creating a Request object,
+ // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
+ const clonedRequestObject = new Request(kConstruct)
+ clonedRequestObject[kState] = clonedRequest
+ clonedRequestObject[kRealm] = this[kRealm]
+ clonedRequestObject[kHeaders] = new Headers(kConstruct)
+ clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList
+ clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]
+ clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]
- // Matches behavior of
- // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
- setCookie(headers, {
- name,
- value: '',
- expires: new Date(0),
- ...attributes
- })
+ // 4. Make clonedRequestObject’s signal follow this’s signal.
+ const ac = new AbortController()
+ if (this.signal.aborted) {
+ ac.abort(this.signal.reason)
+ } else {
+ util.addAbortListener(
+ this.signal,
+ () => {
+ ac.abort(this.signal.reason)
+ }
+ )
+ }
+ clonedRequestObject[kSignal] = ac.signal
+
+ // 4. Return clonedRequestObject.
+ return clonedRequestObject
+ }
}
-/**
- * @param {Headers} headers
- * @returns {Cookie[]}
- */
-function getSetCookies (headers) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })
+mixinBody(Request)
- webidl.brandCheck(headers, Headers, { strict: false })
+function makeRequest (init) {
+ // https://fetch.spec.whatwg.org/#requests
+ const request = {
+ method: 'GET',
+ localURLsOnly: false,
+ unsafeRequest: false,
+ body: null,
+ client: null,
+ reservedClient: null,
+ replacesClientId: '',
+ window: 'client',
+ keepalive: false,
+ serviceWorkers: 'all',
+ initiator: '',
+ destination: '',
+ priority: null,
+ origin: 'client',
+ policyContainer: 'client',
+ referrer: 'client',
+ referrerPolicy: '',
+ mode: 'no-cors',
+ useCORSPreflightFlag: false,
+ credentials: 'same-origin',
+ useCredentials: false,
+ cache: 'default',
+ redirect: 'follow',
+ integrity: '',
+ cryptoGraphicsNonceMetadata: '',
+ parserMetadata: '',
+ reloadNavigation: false,
+ historyNavigation: false,
+ userActivation: false,
+ taintedOrigin: false,
+ redirectCount: 0,
+ responseTainting: 'basic',
+ preventNoCacheCacheControlHeaderModification: false,
+ done: false,
+ timingAllowFailed: false,
+ ...init,
+ headersList: init.headersList
+ ? new HeadersList(init.headersList)
+ : new HeadersList()
+ }
+ request.url = request.urlList[0]
+ return request
+}
- const cookies = getHeadersList(headers).cookies
+// https://fetch.spec.whatwg.org/#concept-request-clone
+function cloneRequest (request) {
+ // To clone a request request, run these steps:
- if (!cookies) {
- return []
+ // 1. Let newRequest be a copy of request, except for its body.
+ const newRequest = makeRequest({ ...request, body: null })
+
+ // 2. If request’s body is non-null, set newRequest’s body to the
+ // result of cloning request’s body.
+ if (request.body != null) {
+ newRequest.body = cloneBody(request.body)
}
- // In older versions of undici, cookies is a list of name:value.
- return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair))
+ // 3. Return newRequest.
+ return newRequest
}
-/**
- * @param {Headers} headers
- * @param {Cookie} cookie
- * @returns {void}
- */
-function setCookie (headers, cookie) {
- webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })
-
- webidl.brandCheck(headers, Headers, { strict: false })
+Object.defineProperties(Request.prototype, {
+ method: kEnumerableProperty,
+ url: kEnumerableProperty,
+ headers: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ clone: kEnumerableProperty,
+ signal: kEnumerableProperty,
+ duplex: kEnumerableProperty,
+ destination: kEnumerableProperty,
+ body: kEnumerableProperty,
+ bodyUsed: kEnumerableProperty,
+ isHistoryNavigation: kEnumerableProperty,
+ isReloadNavigation: kEnumerableProperty,
+ keepalive: kEnumerableProperty,
+ integrity: kEnumerableProperty,
+ cache: kEnumerableProperty,
+ credentials: kEnumerableProperty,
+ attribute: kEnumerableProperty,
+ referrerPolicy: kEnumerableProperty,
+ referrer: kEnumerableProperty,
+ mode: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'Request',
+ configurable: true
+ }
+})
- cookie = webidl.converters.Cookie(cookie)
+webidl.converters.Request = webidl.interfaceConverter(
+ Request
+)
- const str = stringify(cookie)
+// https://fetch.spec.whatwg.org/#requestinfo
+webidl.converters.RequestInfo = function (V) {
+ if (typeof V === 'string') {
+ return webidl.converters.USVString(V)
+ }
- if (str) {
- headers.append('Set-Cookie', stringify(cookie))
+ if (V instanceof Request) {
+ return webidl.converters.Request(V)
}
+
+ return webidl.converters.USVString(V)
}
-webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
+webidl.converters.AbortSignal = webidl.interfaceConverter(
+ AbortSignal
+)
+
+// https://fetch.spec.whatwg.org/#requestinit
+webidl.converters.RequestInit = webidl.dictionaryConverter([
{
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'path',
- defaultValue: null
+ key: 'method',
+ converter: webidl.converters.ByteString
},
{
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'domain',
- defaultValue: null
- }
-])
-
-webidl.converters.Cookie = webidl.dictionaryConverter([
+ key: 'headers',
+ converter: webidl.converters.HeadersInit
+ },
+ {
+ key: 'body',
+ converter: webidl.nullableConverter(
+ webidl.converters.BodyInit
+ )
+ },
+ {
+ key: 'referrer',
+ converter: webidl.converters.USVString
+ },
{
+ key: 'referrerPolicy',
converter: webidl.converters.DOMString,
- key: 'name'
+ // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
+ allowedValues: referrerPolicy
},
{
+ key: 'mode',
converter: webidl.converters.DOMString,
- key: 'value'
+ // https://fetch.spec.whatwg.org/#concept-request-mode
+ allowedValues: requestMode
},
{
- converter: webidl.nullableConverter((value) => {
- if (typeof value === 'number') {
- return webidl.converters['unsigned long long'](value)
- }
-
- return new Date(value)
- }),
- key: 'expires',
- defaultValue: null
+ key: 'credentials',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestcredentials
+ allowedValues: requestCredentials
},
{
- converter: webidl.nullableConverter(webidl.converters['long long']),
- key: 'maxAge',
- defaultValue: null
+ key: 'cache',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestcache
+ allowedValues: requestCache
},
{
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'domain',
- defaultValue: null
+ key: 'redirect',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestredirect
+ allowedValues: requestRedirect
},
{
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'path',
- defaultValue: null
+ key: 'integrity',
+ converter: webidl.converters.DOMString
},
{
- converter: webidl.nullableConverter(webidl.converters.boolean),
- key: 'secure',
- defaultValue: null
+ key: 'keepalive',
+ converter: webidl.converters.boolean
},
{
- converter: webidl.nullableConverter(webidl.converters.boolean),
- key: 'httpOnly',
- defaultValue: null
+ key: 'signal',
+ converter: webidl.nullableConverter(
+ (signal) => webidl.converters.AbortSignal(
+ signal,
+ { strict: false }
+ )
+ )
},
{
- converter: webidl.converters.USVString,
- key: 'sameSite',
- allowedValues: ['Strict', 'Lax', 'None']
+ key: 'window',
+ converter: webidl.converters.any
},
{
- converter: webidl.sequenceConverter(webidl.converters.DOMString),
- key: 'unparsed',
- defaultValue: []
+ key: 'duplex',
+ converter: webidl.converters.DOMString,
+ allowedValues: requestDuplex
}
])
-module.exports = {
- getCookies,
- deleteCookie,
- getSetCookies,
- setCookie
-}
+module.exports = { Request, makeRequest }
/***/ }),
-/***/ 16695:
+/***/ 89928:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(16985)
-const { isCTLExcludingHtab } = __nccwpck_require__(83126)
-const { collectASequenceOfCodePointsFast } = __nccwpck_require__(37246)
+const { Headers, HeadersList, fill } = __nccwpck_require__(12801)
+const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(37791)
+const util = __nccwpck_require__(89500)
+const { kEnumerableProperty } = util
+const {
+ isValidReasonPhrase,
+ isCancelled,
+ isAborted,
+ isBlobLike,
+ serializeJavascriptValueToJSONString,
+ isErrorLike,
+ isomorphicEncode
+} = __nccwpck_require__(72847)
+const {
+ redirectStatusSet,
+ nullBodyStatus,
+ DOMException
+} = __nccwpck_require__(21234)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
+const { webidl } = __nccwpck_require__(94354)
+const { FormData } = __nccwpck_require__(47453)
+const { getGlobalOrigin } = __nccwpck_require__(62896)
+const { URLSerializer } = __nccwpck_require__(37246)
+const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
const assert = __nccwpck_require__(42613)
+const { types } = __nccwpck_require__(39023)
-/**
- * @description Parses the field-value attributes of a set-cookie header string.
- * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
- * @param {string} header
- * @returns if the header is invalid, null will be returned
- */
-function parseSetCookie (header) {
- // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
- // character (CTL characters excluding HTAB): Abort these steps and
- // ignore the set-cookie-string entirely.
- if (isCTLExcludingHtab(header)) {
- return null
- }
+const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(63774).ReadableStream)
+const textEncoder = new TextEncoder('utf-8')
- let nameValuePair = ''
- let unparsedAttributes = ''
- let name = ''
- let value = ''
+// https://fetch.spec.whatwg.org/#response-class
+class Response {
+ // Creates network error Response.
+ static error () {
+ // TODO
+ const relevantRealm = { settingsObject: {} }
- // 2. If the set-cookie-string contains a %x3B (";") character:
- if (header.includes(';')) {
- // 1. The name-value-pair string consists of the characters up to,
- // but not including, the first %x3B (";"), and the unparsed-
- // attributes consist of the remainder of the set-cookie-string
- // (including the %x3B (";") in question).
- const position = { position: 0 }
+ // The static error() method steps are to return the result of creating a
+ // Response object, given a new network error, "immutable", and this’s
+ // relevant Realm.
+ const responseObject = new Response()
+ responseObject[kState] = makeNetworkError()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
+ return responseObject
+ }
- nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
- unparsedAttributes = header.slice(position.position)
- } else {
- // Otherwise:
+ // https://fetch.spec.whatwg.org/#dom-response-json
+ static json (data, init = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })
- // 1. The name-value-pair string consists of all the characters
- // contained in the set-cookie-string, and the unparsed-
- // attributes is the empty string.
- nameValuePair = header
- }
+ if (init !== null) {
+ init = webidl.converters.ResponseInit(init)
+ }
- // 3. If the name-value-pair string lacks a %x3D ("=") character, then
- // the name string is empty, and the value string is the value of
- // name-value-pair.
- if (!nameValuePair.includes('=')) {
- value = nameValuePair
- } else {
- // Otherwise, the name string consists of the characters up to, but
- // not including, the first %x3D ("=") character, and the (possibly
- // empty) value string consists of the characters after the first
- // %x3D ("=") character.
- const position = { position: 0 }
- name = collectASequenceOfCodePointsFast(
- '=',
- nameValuePair,
- position
+ // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
+ const bytes = textEncoder.encode(
+ serializeJavascriptValueToJSONString(data)
)
- value = nameValuePair.slice(position.position + 1)
- }
- // 4. Remove any leading or trailing WSP characters from the name
- // string and the value string.
- name = name.trim()
- value = value.trim()
+ // 2. Let body be the result of extracting bytes.
+ const body = extractBody(bytes)
- // 5. If the sum of the lengths of the name string and the value string
- // is more than 4096 octets, abort these steps and ignore the set-
- // cookie-string entirely.
- if (name.length + value.length > maxNameValuePairSize) {
- return null
- }
+ // 3. Let responseObject be the result of creating a Response object, given a new response,
+ // "response", and this’s relevant Realm.
+ const relevantRealm = { settingsObject: {} }
+ const responseObject = new Response()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kGuard] = 'response'
+ responseObject[kHeaders][kRealm] = relevantRealm
- // 6. The cookie-name is the name string, and the cookie-value is the
- // value string.
- return {
- name, value, ...parseUnparsedAttributes(unparsedAttributes)
- }
-}
+ // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
+ initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
-/**
- * Parses the remaining attributes of a set-cookie header
- * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
- * @param {string} unparsedAttributes
- * @param {[Object.]={}} cookieAttributeList
- */
-function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
- // 1. If the unparsed-attributes string is empty, skip the rest of
- // these steps.
- if (unparsedAttributes.length === 0) {
- return cookieAttributeList
+ // 5. Return responseObject.
+ return responseObject
}
- // 2. Discard the first character of the unparsed-attributes (which
- // will be a %x3B (";") character).
- assert(unparsedAttributes[0] === ';')
- unparsedAttributes = unparsedAttributes.slice(1)
-
- let cookieAv = ''
+ // Creates a redirect Response that redirects to url with status status.
+ static redirect (url, status = 302) {
+ const relevantRealm = { settingsObject: {} }
- // 3. If the remaining unparsed-attributes contains a %x3B (";")
- // character:
- if (unparsedAttributes.includes(';')) {
- // 1. Consume the characters of the unparsed-attributes up to, but
- // not including, the first %x3B (";") character.
- cookieAv = collectASequenceOfCodePointsFast(
- ';',
- unparsedAttributes,
- { position: 0 }
- )
- unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
- } else {
- // Otherwise:
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })
- // 1. Consume the remainder of the unparsed-attributes.
- cookieAv = unparsedAttributes
- unparsedAttributes = ''
- }
+ url = webidl.converters.USVString(url)
+ status = webidl.converters['unsigned short'](status)
- // Let the cookie-av string be the characters consumed in this step.
+ // 1. Let parsedURL be the result of parsing url with current settings
+ // object’s API base URL.
+ // 2. If parsedURL is failure, then throw a TypeError.
+ // TODO: base-URL?
+ let parsedURL
+ try {
+ parsedURL = new URL(url, getGlobalOrigin())
+ } catch (err) {
+ throw Object.assign(new TypeError('Failed to parse URL from ' + url), {
+ cause: err
+ })
+ }
- let attributeName = ''
- let attributeValue = ''
+ // 3. If status is not a redirect status, then throw a RangeError.
+ if (!redirectStatusSet.has(status)) {
+ throw new RangeError('Invalid status code ' + status)
+ }
- // 4. If the cookie-av string contains a %x3D ("=") character:
- if (cookieAv.includes('=')) {
- // 1. The (possibly empty) attribute-name string consists of the
- // characters up to, but not including, the first %x3D ("=")
- // character, and the (possibly empty) attribute-value string
- // consists of the characters after the first %x3D ("=")
- // character.
- const position = { position: 0 }
+ // 4. Let responseObject be the result of creating a Response object,
+ // given a new response, "immutable", and this’s relevant Realm.
+ const responseObject = new Response()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
- attributeName = collectASequenceOfCodePointsFast(
- '=',
- cookieAv,
- position
- )
- attributeValue = cookieAv.slice(position.position + 1)
- } else {
- // Otherwise:
+ // 5. Set responseObject’s response’s status to status.
+ responseObject[kState].status = status
- // 1. The attribute-name string consists of the entire cookie-av
- // string, and the attribute-value string is empty.
- attributeName = cookieAv
- }
+ // 6. Let value be parsedURL, serialized and isomorphic encoded.
+ const value = isomorphicEncode(URLSerializer(parsedURL))
- // 5. Remove any leading or trailing WSP characters from the attribute-
- // name string and the attribute-value string.
- attributeName = attributeName.trim()
- attributeValue = attributeValue.trim()
+ // 7. Append `Location`/value to responseObject’s response’s header list.
+ responseObject[kState].headersList.append('location', value)
- // 6. If the attribute-value is longer than 1024 octets, ignore the
- // cookie-av string and return to Step 1 of this algorithm.
- if (attributeValue.length > maxAttributeValueSize) {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ // 8. Return responseObject.
+ return responseObject
}
- // 7. Process the attribute-name and attribute-value according to the
- // requirements in the following subsections. (Notice that
- // attributes with unrecognized attribute-names are ignored.)
- const attributeNameLowercase = attributeName.toLowerCase()
+ // https://fetch.spec.whatwg.org/#dom-response
+ constructor (body = null, init = {}) {
+ if (body !== null) {
+ body = webidl.converters.BodyInit(body)
+ }
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
- // If the attribute-name case-insensitively matches the string
- // "Expires", the user agent MUST process the cookie-av as follows.
- if (attributeNameLowercase === 'expires') {
- // 1. Let the expiry-time be the result of parsing the attribute-value
- // as cookie-date (see Section 5.1.1).
- const expiryTime = new Date(attributeValue)
+ init = webidl.converters.ResponseInit(init)
- // 2. If the attribute-value failed to parse as a cookie date, ignore
- // the cookie-av.
+ // TODO
+ this[kRealm] = { settingsObject: {} }
- cookieAttributeList.expires = expiryTime
- } else if (attributeNameLowercase === 'max-age') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
- // If the attribute-name case-insensitively matches the string "Max-
- // Age", the user agent MUST process the cookie-av as follows.
+ // 1. Set this’s response to a new response.
+ this[kState] = makeResponse({})
- // 1. If the first character of the attribute-value is not a DIGIT or a
- // "-" character, ignore the cookie-av.
- const charCode = attributeValue.charCodeAt(0)
+ // 2. Set this’s headers to a new Headers object with this’s relevant
+ // Realm, whose header list is this’s response’s header list and guard
+ // is "response".
+ this[kHeaders] = new Headers(kConstruct)
+ this[kHeaders][kGuard] = 'response'
+ this[kHeaders][kHeadersList] = this[kState].headersList
+ this[kHeaders][kRealm] = this[kRealm]
- if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
- }
+ // 3. Let bodyWithType be null.
+ let bodyWithType = null
- // 2. If the remainder of attribute-value contains a non-DIGIT
- // character, ignore the cookie-av.
- if (!/^\d+$/.test(attributeValue)) {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ // 4. If body is non-null, then set bodyWithType to the result of extracting body.
+ if (body != null) {
+ const [extractedBody, type] = extractBody(body)
+ bodyWithType = { body: extractedBody, type }
}
- // 3. Let delta-seconds be the attribute-value converted to an integer.
- const deltaSeconds = Number(attributeValue)
+ // 5. Perform initialize a response given this, init, and bodyWithType.
+ initializeResponse(this, init, bodyWithType)
+ }
- // 4. Let cookie-age-limit be the maximum age of the cookie (which
- // SHOULD be 400 days or less, see Section 4.1.2.2).
+ // Returns response’s type, e.g., "cors".
+ get type () {
+ webidl.brandCheck(this, Response)
- // 5. Set delta-seconds to the smaller of its present value and cookie-
- // age-limit.
- // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
+ // The type getter steps are to return this’s response’s type.
+ return this[kState].type
+ }
- // 6. If delta-seconds is less than or equal to zero (0), let expiry-
- // time be the earliest representable date and time. Otherwise, let
- // the expiry-time be the current date and time plus delta-seconds
- // seconds.
- // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
+ // Returns response’s URL, if it has one; otherwise the empty string.
+ get url () {
+ webidl.brandCheck(this, Response)
- // 7. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Max-Age and an attribute-value of expiry-time.
- cookieAttributeList.maxAge = deltaSeconds
- } else if (attributeNameLowercase === 'domain') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
- // If the attribute-name case-insensitively matches the string "Domain",
- // the user agent MUST process the cookie-av as follows.
+ const urlList = this[kState].urlList
- // 1. Let cookie-domain be the attribute-value.
- let cookieDomain = attributeValue
+ // The url getter steps are to return the empty string if this’s
+ // response’s URL is null; otherwise this’s response’s URL,
+ // serialized with exclude fragment set to true.
+ const url = urlList[urlList.length - 1] ?? null
- // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
- // cookie-domain without its leading %x2E (".").
- if (cookieDomain[0] === '.') {
- cookieDomain = cookieDomain.slice(1)
+ if (url === null) {
+ return ''
}
- // 3. Convert the cookie-domain to lower case.
- cookieDomain = cookieDomain.toLowerCase()
+ return URLSerializer(url, true)
+ }
- // 4. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Domain and an attribute-value of cookie-domain.
- cookieAttributeList.domain = cookieDomain
- } else if (attributeNameLowercase === 'path') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
- // If the attribute-name case-insensitively matches the string "Path",
- // the user agent MUST process the cookie-av as follows.
+ // Returns whether response was obtained through a redirect.
+ get redirected () {
+ webidl.brandCheck(this, Response)
- // 1. If the attribute-value is empty or if the first character of the
- // attribute-value is not %x2F ("/"):
- let cookiePath = ''
- if (attributeValue.length === 0 || attributeValue[0] !== '/') {
- // 1. Let cookie-path be the default-path.
- cookiePath = '/'
- } else {
- // Otherwise:
+ // The redirected getter steps are to return true if this’s response’s URL
+ // list has more than one item; otherwise false.
+ return this[kState].urlList.length > 1
+ }
- // 1. Let cookie-path be the attribute-value.
- cookiePath = attributeValue
- }
+ // Returns response’s status.
+ get status () {
+ webidl.brandCheck(this, Response)
- // 2. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Path and an attribute-value of cookie-path.
- cookieAttributeList.path = cookiePath
- } else if (attributeNameLowercase === 'secure') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
- // If the attribute-name case-insensitively matches the string "Secure",
- // the user agent MUST append an attribute to the cookie-attribute-list
- // with an attribute-name of Secure and an empty attribute-value.
+ // The status getter steps are to return this’s response’s status.
+ return this[kState].status
+ }
- cookieAttributeList.secure = true
- } else if (attributeNameLowercase === 'httponly') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
- // If the attribute-name case-insensitively matches the string
- // "HttpOnly", the user agent MUST append an attribute to the cookie-
- // attribute-list with an attribute-name of HttpOnly and an empty
- // attribute-value.
+ // Returns whether response’s status is an ok status.
+ get ok () {
+ webidl.brandCheck(this, Response)
- cookieAttributeList.httpOnly = true
- } else if (attributeNameLowercase === 'samesite') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
- // If the attribute-name case-insensitively matches the string
- // "SameSite", the user agent MUST process the cookie-av as follows:
+ // The ok getter steps are to return true if this’s response’s status is an
+ // ok status; otherwise false.
+ return this[kState].status >= 200 && this[kState].status <= 299
+ }
- // 1. Let enforcement be "Default".
- let enforcement = 'Default'
+ // Returns response’s status message.
+ get statusText () {
+ webidl.brandCheck(this, Response)
- const attributeValueLowercase = attributeValue.toLowerCase()
- // 2. If cookie-av's attribute-value is a case-insensitive match for
- // "None", set enforcement to "None".
- if (attributeValueLowercase.includes('none')) {
- enforcement = 'None'
- }
+ // The statusText getter steps are to return this’s response’s status
+ // message.
+ return this[kState].statusText
+ }
- // 3. If cookie-av's attribute-value is a case-insensitive match for
- // "Strict", set enforcement to "Strict".
- if (attributeValueLowercase.includes('strict')) {
- enforcement = 'Strict'
- }
+ // Returns response’s headers as Headers.
+ get headers () {
+ webidl.brandCheck(this, Response)
- // 4. If cookie-av's attribute-value is a case-insensitive match for
- // "Lax", set enforcement to "Lax".
- if (attributeValueLowercase.includes('lax')) {
- enforcement = 'Lax'
- }
+ // The headers getter steps are to return this’s headers.
+ return this[kHeaders]
+ }
- // 5. Append an attribute to the cookie-attribute-list with an
- // attribute-name of "SameSite" and an attribute-value of
- // enforcement.
- cookieAttributeList.sameSite = enforcement
- } else {
- cookieAttributeList.unparsed ??= []
+ get body () {
+ webidl.brandCheck(this, Response)
- cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
+ return this[kState].body ? this[kState].body.stream : null
}
- // 8. Return to Step 1 of this algorithm.
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
-}
+ get bodyUsed () {
+ webidl.brandCheck(this, Response)
-module.exports = {
- parseSetCookie,
- parseUnparsedAttributes
-}
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
+ }
+ // Returns a clone of response.
+ clone () {
+ webidl.brandCheck(this, Response)
-/***/ }),
+ // 1. If this is unusable, then throw a TypeError.
+ if (this.bodyUsed || (this.body && this.body.locked)) {
+ throw webidl.errors.exception({
+ header: 'Response.clone',
+ message: 'Body has already been consumed.'
+ })
+ }
-/***/ 83126:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Let clonedResponse be the result of cloning this’s response.
+ const clonedResponse = cloneResponse(this[kState])
+ // 3. Return the result of creating a Response object, given
+ // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
+ const clonedResponseObject = new Response()
+ clonedResponseObject[kState] = clonedResponse
+ clonedResponseObject[kRealm] = this[kRealm]
+ clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList
+ clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]
+ clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]
+ return clonedResponseObject
+ }
+}
-const assert = __nccwpck_require__(42613)
-const { kHeadersList } = __nccwpck_require__(68031)
+mixinBody(Response)
-function isCTLExcludingHtab (value) {
- if (value.length === 0) {
- return false
+Object.defineProperties(Response.prototype, {
+ type: kEnumerableProperty,
+ url: kEnumerableProperty,
+ status: kEnumerableProperty,
+ ok: kEnumerableProperty,
+ redirected: kEnumerableProperty,
+ statusText: kEnumerableProperty,
+ headers: kEnumerableProperty,
+ clone: kEnumerableProperty,
+ body: kEnumerableProperty,
+ bodyUsed: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'Response',
+ configurable: true
}
+})
- for (const char of value) {
- const code = char.charCodeAt(0)
+Object.defineProperties(Response, {
+ json: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ error: kEnumerableProperty
+})
- if (
- (code >= 0x00 || code <= 0x08) ||
- (code >= 0x0A || code <= 0x1F) ||
- code === 0x7F
- ) {
- return false
- }
+// https://fetch.spec.whatwg.org/#concept-response-clone
+function cloneResponse (response) {
+ // To clone a response response, run these steps:
+
+ // 1. If response is a filtered response, then return a new identical
+ // filtered response whose internal response is a clone of response’s
+ // internal response.
+ if (response.internalResponse) {
+ return filterResponse(
+ cloneResponse(response.internalResponse),
+ response.type
+ )
}
-}
-/**
- CHAR =
- token = 1*
- separators = "(" | ")" | "<" | ">" | "@"
- | "," | ";" | ":" | "\" | <">
- | "/" | "[" | "]" | "?" | "="
- | "{" | "}" | SP | HT
- * @param {string} name
- */
-function validateCookieName (name) {
- for (const char of name) {
- const code = char.charCodeAt(0)
+ // 2. Let newResponse be a copy of response, except for its body.
+ const newResponse = makeResponse({ ...response, body: null })
- if (
- (code <= 0x20 || code > 0x7F) ||
- char === '(' ||
- char === ')' ||
- char === '>' ||
- char === '<' ||
- char === '@' ||
- char === ',' ||
- char === ';' ||
- char === ':' ||
- char === '\\' ||
- char === '"' ||
- char === '/' ||
- char === '[' ||
- char === ']' ||
- char === '?' ||
- char === '=' ||
- char === '{' ||
- char === '}'
- ) {
- throw new Error('Invalid cookie name')
- }
+ // 3. If response’s body is non-null, then set newResponse’s body to the
+ // result of cloning response’s body.
+ if (response.body != null) {
+ newResponse.body = cloneBody(response.body)
}
-}
-/**
- cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
- cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
- ; US-ASCII characters excluding CTLs,
- ; whitespace DQUOTE, comma, semicolon,
- ; and backslash
- * @param {string} value
- */
-function validateCookieValue (value) {
- for (const char of value) {
- const code = char.charCodeAt(0)
+ // 4. Return newResponse.
+ return newResponse
+}
- if (
- code < 0x21 || // exclude CTLs (0-31)
- code === 0x22 ||
- code === 0x2C ||
- code === 0x3B ||
- code === 0x5C ||
- code > 0x7E // non-ascii
- ) {
- throw new Error('Invalid header value')
- }
+function makeResponse (init) {
+ return {
+ aborted: false,
+ rangeRequested: false,
+ timingAllowPassed: false,
+ requestIncludesCredentials: false,
+ type: 'default',
+ status: 200,
+ timingInfo: null,
+ cacheState: '',
+ statusText: '',
+ ...init,
+ headersList: init.headersList
+ ? new HeadersList(init.headersList)
+ : new HeadersList(),
+ urlList: init.urlList ? [...init.urlList] : []
}
}
-/**
- * path-value =
- * @param {string} path
- */
-function validateCookiePath (path) {
- for (const char of path) {
- const code = char.charCodeAt(0)
-
- if (code < 0x21 || char === ';') {
- throw new Error('Invalid cookie path')
- }
- }
+function makeNetworkError (reason) {
+ const isError = isErrorLike(reason)
+ return makeResponse({
+ type: 'error',
+ status: 0,
+ error: isError
+ ? reason
+ : new Error(reason ? String(reason) : reason),
+ aborted: reason && reason.name === 'AbortError'
+ })
}
-/**
- * I have no idea why these values aren't allowed to be honest,
- * but Deno tests these. - Khafra
- * @param {string} domain
- */
-function validateCookieDomain (domain) {
- if (
- domain.startsWith('-') ||
- domain.endsWith('.') ||
- domain.endsWith('-')
- ) {
- throw new Error('Invalid cookie domain')
+function makeFilteredResponse (response, state) {
+ state = {
+ internalResponse: response,
+ ...state
}
-}
-/**
- * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
- * @param {number|Date} date
- IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
- ; fixed length/zone/capitalization subset of the format
- ; see Section 3.3 of [RFC5322]
+ return new Proxy(response, {
+ get (target, p) {
+ return p in state ? state[p] : target[p]
+ },
+ set (target, p, value) {
+ assert(!(p in state))
+ target[p] = value
+ return true
+ }
+ })
+}
- day-name = %x4D.6F.6E ; "Mon", case-sensitive
- / %x54.75.65 ; "Tue", case-sensitive
- / %x57.65.64 ; "Wed", case-sensitive
- / %x54.68.75 ; "Thu", case-sensitive
- / %x46.72.69 ; "Fri", case-sensitive
- / %x53.61.74 ; "Sat", case-sensitive
- / %x53.75.6E ; "Sun", case-sensitive
- date1 = day SP month SP year
- ; e.g., 02 Jun 1982
+// https://fetch.spec.whatwg.org/#concept-filtered-response
+function filterResponse (response, type) {
+ // Set response to the following filtered response with response as its
+ // internal response, depending on request’s response tainting:
+ if (type === 'basic') {
+ // A basic filtered response is a filtered response whose type is "basic"
+ // and header list excludes any headers in internal response’s header list
+ // whose name is a forbidden response-header name.
- day = 2DIGIT
- month = %x4A.61.6E ; "Jan", case-sensitive
- / %x46.65.62 ; "Feb", case-sensitive
- / %x4D.61.72 ; "Mar", case-sensitive
- / %x41.70.72 ; "Apr", case-sensitive
- / %x4D.61.79 ; "May", case-sensitive
- / %x4A.75.6E ; "Jun", case-sensitive
- / %x4A.75.6C ; "Jul", case-sensitive
- / %x41.75.67 ; "Aug", case-sensitive
- / %x53.65.70 ; "Sep", case-sensitive
- / %x4F.63.74 ; "Oct", case-sensitive
- / %x4E.6F.76 ; "Nov", case-sensitive
- / %x44.65.63 ; "Dec", case-sensitive
- year = 4DIGIT
+ // Note: undici does not implement forbidden response-header names
+ return makeFilteredResponse(response, {
+ type: 'basic',
+ headersList: response.headersList
+ })
+ } else if (type === 'cors') {
+ // A CORS filtered response is a filtered response whose type is "cors"
+ // and header list excludes any headers in internal response’s header
+ // list whose name is not a CORS-safelisted response-header name, given
+ // internal response’s CORS-exposed header-name list.
- GMT = %x47.4D.54 ; "GMT", case-sensitive
+ // Note: undici does not implement CORS-safelisted response-header names
+ return makeFilteredResponse(response, {
+ type: 'cors',
+ headersList: response.headersList
+ })
+ } else if (type === 'opaque') {
+ // An opaque filtered response is a filtered response whose type is
+ // "opaque", URL list is the empty list, status is 0, status message
+ // is the empty byte sequence, header list is empty, and body is null.
- time-of-day = hour ":" minute ":" second
- ; 00:00:00 - 23:59:60 (leap second)
+ return makeFilteredResponse(response, {
+ type: 'opaque',
+ urlList: Object.freeze([]),
+ status: 0,
+ statusText: '',
+ body: null
+ })
+ } else if (type === 'opaqueredirect') {
+ // An opaque-redirect filtered response is a filtered response whose type
+ // is "opaqueredirect", status is 0, status message is the empty byte
+ // sequence, header list is empty, and body is null.
- hour = 2DIGIT
- minute = 2DIGIT
- second = 2DIGIT
- */
-function toIMFDate (date) {
- if (typeof date === 'number') {
- date = new Date(date)
+ return makeFilteredResponse(response, {
+ type: 'opaqueredirect',
+ status: 0,
+ statusText: '',
+ headersList: [],
+ body: null
+ })
+ } else {
+ assert(false)
}
+}
- const days = [
- 'Sun', 'Mon', 'Tue', 'Wed',
- 'Thu', 'Fri', 'Sat'
- ]
-
- const months = [
- 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
- ]
-
- const dayName = days[date.getUTCDay()]
- const day = date.getUTCDate().toString().padStart(2, '0')
- const month = months[date.getUTCMonth()]
- const year = date.getUTCFullYear()
- const hour = date.getUTCHours().toString().padStart(2, '0')
- const minute = date.getUTCMinutes().toString().padStart(2, '0')
- const second = date.getUTCSeconds().toString().padStart(2, '0')
+// https://fetch.spec.whatwg.org/#appropriate-network-error
+function makeAppropriateNetworkError (fetchParams, err = null) {
+ // 1. Assert: fetchParams is canceled.
+ assert(isCancelled(fetchParams))
- return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`
+ // 2. Return an aborted network error if fetchParams is aborted;
+ // otherwise return a network error.
+ return isAborted(fetchParams)
+ ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))
+ : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))
}
-/**
- max-age-av = "Max-Age=" non-zero-digit *DIGIT
- ; In practice, both expires-av and max-age-av
- ; are limited to dates representable by the
- ; user agent.
- * @param {number} maxAge
- */
-function validateCookieMaxAge (maxAge) {
- if (maxAge < 0) {
- throw new Error('Invalid cookie max-age')
+// https://whatpr.org/fetch/1392.html#initialize-a-response
+function initializeResponse (response, init, body) {
+ // 1. If init["status"] is not in the range 200 to 599, inclusive, then
+ // throw a RangeError.
+ if (init.status !== null && (init.status < 200 || init.status > 599)) {
+ throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')
}
-}
-/**
- * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
- * @param {import('./index').Cookie} cookie
- */
-function stringify (cookie) {
- if (cookie.name.length === 0) {
- return null
+ // 2. If init["statusText"] does not match the reason-phrase token production,
+ // then throw a TypeError.
+ if ('statusText' in init && init.statusText != null) {
+ // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:
+ // reason-phrase = *( HTAB / SP / VCHAR / obs-text )
+ if (!isValidReasonPhrase(String(init.statusText))) {
+ throw new TypeError('Invalid statusText')
+ }
}
- validateCookieName(cookie.name)
- validateCookieValue(cookie.value)
-
- const out = [`${cookie.name}=${cookie.value}`]
-
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
- if (cookie.name.startsWith('__Secure-')) {
- cookie.secure = true
+ // 3. Set response’s response’s status to init["status"].
+ if ('status' in init && init.status != null) {
+ response[kState].status = init.status
}
- if (cookie.name.startsWith('__Host-')) {
- cookie.secure = true
- cookie.domain = null
- cookie.path = '/'
+ // 4. Set response’s response’s status message to init["statusText"].
+ if ('statusText' in init && init.statusText != null) {
+ response[kState].statusText = init.statusText
}
- if (cookie.secure) {
- out.push('Secure')
+ // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
+ if ('headers' in init && init.headers != null) {
+ fill(response[kHeaders], init.headers)
}
- if (cookie.httpOnly) {
- out.push('HttpOnly')
+ // 6. If body was given, then:
+ if (body) {
+ // 1. If response's status is a null body status, then throw a TypeError.
+ if (nullBodyStatus.includes(response.status)) {
+ throw webidl.errors.exception({
+ header: 'Response constructor',
+ message: 'Invalid response status code ' + response.status
+ })
+ }
+
+ // 2. Set response's body to body's body.
+ response[kState].body = body.body
+
+ // 3. If body's type is non-null and response's header list does not contain
+ // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.
+ if (body.type != null && !response[kState].headersList.contains('Content-Type')) {
+ response[kState].headersList.append('content-type', body.type)
+ }
}
+}
- if (typeof cookie.maxAge === 'number') {
- validateCookieMaxAge(cookie.maxAge)
- out.push(`Max-Age=${cookie.maxAge}`)
+webidl.converters.ReadableStream = webidl.interfaceConverter(
+ ReadableStream
+)
+
+webidl.converters.FormData = webidl.interfaceConverter(
+ FormData
+)
+
+webidl.converters.URLSearchParams = webidl.interfaceConverter(
+ URLSearchParams
+)
+
+// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
+webidl.converters.XMLHttpRequestBodyInit = function (V) {
+ if (typeof V === 'string') {
+ return webidl.converters.USVString(V)
}
- if (cookie.domain) {
- validateCookieDomain(cookie.domain)
- out.push(`Domain=${cookie.domain}`)
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
}
- if (cookie.path) {
- validateCookiePath(cookie.path)
- out.push(`Path=${cookie.path}`)
+ if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {
+ return webidl.converters.BufferSource(V)
}
- if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
- out.push(`Expires=${toIMFDate(cookie.expires)}`)
+ if (util.isFormDataLike(V)) {
+ return webidl.converters.FormData(V, { strict: false })
}
- if (cookie.sameSite) {
- out.push(`SameSite=${cookie.sameSite}`)
+ if (V instanceof URLSearchParams) {
+ return webidl.converters.URLSearchParams(V)
}
- for (const part of cookie.unparsed) {
- if (!part.includes('=')) {
- throw new Error('Invalid unparsed')
- }
+ return webidl.converters.DOMString(V)
+}
- const [key, ...value] = part.split('=')
+// https://fetch.spec.whatwg.org/#bodyinit
+webidl.converters.BodyInit = function (V) {
+ if (V instanceof ReadableStream) {
+ return webidl.converters.ReadableStream(V)
+ }
- out.push(`${key.trim()}=${value.join('=')}`)
+ // Note: the spec doesn't include async iterables,
+ // this is an undici extension.
+ if (V?.[Symbol.asyncIterator]) {
+ return V
}
- return out.join('; ')
+ return webidl.converters.XMLHttpRequestBodyInit(V)
}
-let kHeadersListNode
-
-function getHeadersList (headers) {
- if (headers[kHeadersList]) {
- return headers[kHeadersList]
+webidl.converters.ResponseInit = webidl.dictionaryConverter([
+ {
+ key: 'status',
+ converter: webidl.converters['unsigned short'],
+ defaultValue: 200
+ },
+ {
+ key: 'statusText',
+ converter: webidl.converters.ByteString,
+ defaultValue: ''
+ },
+ {
+ key: 'headers',
+ converter: webidl.converters.HeadersInit
}
+])
- if (!kHeadersListNode) {
- kHeadersListNode = Object.getOwnPropertySymbols(headers).find(
- (symbol) => symbol.description === 'headers list'
- )
+module.exports = {
+ makeNetworkError,
+ makeResponse,
+ makeAppropriateNetworkError,
+ filterResponse,
+ Response,
+ cloneResponse
+}
- assert(kHeadersListNode, 'Headers cannot be parsed')
- }
- const headersList = headers[kHeadersListNode]
- assert(headersList)
+/***/ }),
+
+/***/ 63730:
+/***/ ((module) => {
+
- return headersList
-}
module.exports = {
- isCTLExcludingHtab,
- stringify,
- getHeadersList
+ kUrl: Symbol('url'),
+ kHeaders: Symbol('headers'),
+ kSignal: Symbol('signal'),
+ kState: Symbol('state'),
+ kGuard: Symbol('guard'),
+ kRealm: Symbol('realm')
}
/***/ }),
-/***/ 91332:
+/***/ 72847:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const net = __nccwpck_require__(69278)
+const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(21234)
+const { getGlobalOrigin } = __nccwpck_require__(62896)
+const { performance } = __nccwpck_require__(82987)
+const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(89500)
const assert = __nccwpck_require__(42613)
-const util = __nccwpck_require__(89500)
-const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(53959)
-
-let tls // include tls conditionally since it is not always available
-
-// TODO: session re-use does not wait for the first
-// connection to resolve the session and might therefore
-// resolve the same servername multiple times even when
-// re-use is enabled.
+const { isUint8Array } = __nccwpck_require__(98253)
-let SessionCache
-// FIXME: remove workaround when the Node bug is fixed
-// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
-if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {
- SessionCache = class WeakSessionCache {
- constructor (maxCachedSessions) {
- this._maxCachedSessions = maxCachedSessions
- this._sessionCache = new Map()
- this._sessionRegistry = new global.FinalizationRegistry((key) => {
- if (this._sessionCache.size < this._maxCachedSessions) {
- return
- }
+let supportedHashes = []
- const ref = this._sessionCache.get(key)
- if (ref !== undefined && ref.deref() === undefined) {
- this._sessionCache.delete(key)
- }
- })
- }
+// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
+/** @type {import('crypto')|undefined} */
+let crypto
- get (sessionKey) {
- const ref = this._sessionCache.get(sessionKey)
- return ref ? ref.deref() : null
- }
+try {
+ crypto = __nccwpck_require__(76982)
+ const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
+ supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
+/* c8 ignore next 3 */
+} catch {
+}
- set (sessionKey, session) {
- if (this._maxCachedSessions === 0) {
- return
- }
+function responseURL (response) {
+ // https://fetch.spec.whatwg.org/#responses
+ // A response has an associated URL. It is a pointer to the last URL
+ // in response’s URL list and null if response’s URL list is empty.
+ const urlList = response.urlList
+ const length = urlList.length
+ return length === 0 ? null : urlList[length - 1].toString()
+}
- this._sessionCache.set(sessionKey, new WeakRef(session))
- this._sessionRegistry.register(session, sessionKey)
- }
+// https://fetch.spec.whatwg.org/#concept-response-location-url
+function responseLocationURL (response, requestFragment) {
+ // 1. If response’s status is not a redirect status, then return null.
+ if (!redirectStatusSet.has(response.status)) {
+ return null
}
-} else {
- SessionCache = class SimpleSessionCache {
- constructor (maxCachedSessions) {
- this._maxCachedSessions = maxCachedSessions
- this._sessionCache = new Map()
- }
-
- get (sessionKey) {
- return this._sessionCache.get(sessionKey)
- }
-
- set (sessionKey, session) {
- if (this._maxCachedSessions === 0) {
- return
- }
- if (this._sessionCache.size >= this._maxCachedSessions) {
- // remove the oldest session
- const { value: oldestKey } = this._sessionCache.keys().next()
- this._sessionCache.delete(oldestKey)
- }
+ // 2. Let location be the result of extracting header list values given
+ // `Location` and response’s header list.
+ let location = response.headersList.get('location')
- this._sessionCache.set(sessionKey, session)
- }
+ // 3. If location is a header value, then set location to the result of
+ // parsing location with response’s URL.
+ if (location !== null && isValidHeaderValue(location)) {
+ location = new URL(location, responseURL(response))
}
-}
-function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {
- if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
- throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
+ // 4. If location is a URL whose fragment is null, then set location’s
+ // fragment to requestFragment.
+ if (location && !location.hash) {
+ location.hash = requestFragment
}
- const options = { path: socketPath, ...opts }
- const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
- timeout = timeout == null ? 10e3 : timeout
- allowH2 = allowH2 != null ? allowH2 : false
- return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
- let socket
- if (protocol === 'https:') {
- if (!tls) {
- tls = __nccwpck_require__(64756)
- }
- servername = servername || options.servername || util.getServerName(host) || null
+ // 5. Return location.
+ return location
+}
- const sessionKey = servername || hostname
- const session = sessionCache.get(sessionKey) || null
+/** @returns {URL} */
+function requestCurrentURL (request) {
+ return request.urlList[request.urlList.length - 1]
+}
- assert(sessionKey)
+function requestBadPort (request) {
+ // 1. Let url be request’s current URL.
+ const url = requestCurrentURL(request)
- socket = tls.connect({
- highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
- ...options,
- servername,
- session,
- localAddress,
- // TODO(HTTP/2): Add support for h2c
- ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
- socket: httpSocket, // upgrade socket connection
- port: port || 443,
- host: hostname
- })
+ // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,
+ // then return blocked.
+ if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
+ return 'blocked'
+ }
- socket
- .on('session', function (session) {
- // TODO (fix): Can a session become invalid once established? Don't think so?
- sessionCache.set(sessionKey, session)
- })
- } else {
- assert(!httpSocket, 'httpSocket can only be sent on TLS update')
- socket = net.connect({
- highWaterMark: 64 * 1024, // Same as nodejs fs streams.
- ...options,
- localAddress,
- port: port || 80,
- host: hostname
- })
- }
+ // 3. Return allowed.
+ return 'allowed'
+}
- // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
- if (options.keepAlive == null || options.keepAlive) {
- const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
- socket.setKeepAlive(true, keepAliveInitialDelay)
+function isErrorLike (object) {
+ return object instanceof Error || (
+ object?.constructor?.name === 'Error' ||
+ object?.constructor?.name === 'DOMException'
+ )
+}
+
+// Check whether |statusText| is a ByteString and
+// matches the Reason-Phrase token production.
+// RFC 2616: https://tools.ietf.org/html/rfc2616
+// RFC 7230: https://tools.ietf.org/html/rfc7230
+// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )"
+// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116
+function isValidReasonPhrase (statusText) {
+ for (let i = 0; i < statusText.length; ++i) {
+ const c = statusText.charCodeAt(i)
+ if (
+ !(
+ (
+ c === 0x09 || // HTAB
+ (c >= 0x20 && c <= 0x7e) || // SP / VCHAR
+ (c >= 0x80 && c <= 0xff)
+ ) // obs-text
+ )
+ ) {
+ return false
}
+ }
+ return true
+}
- const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)
+/**
+ * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
+ * @param {number} c
+ */
+function isTokenCharCode (c) {
+ switch (c) {
+ case 0x22:
+ case 0x28:
+ case 0x29:
+ case 0x2c:
+ case 0x2f:
+ case 0x3a:
+ case 0x3b:
+ case 0x3c:
+ case 0x3d:
+ case 0x3e:
+ case 0x3f:
+ case 0x40:
+ case 0x5b:
+ case 0x5c:
+ case 0x5d:
+ case 0x7b:
+ case 0x7d:
+ // DQUOTE and "(),/:;<=>?@[\]{}"
+ return false
+ default:
+ // VCHAR %x21-7E
+ return c >= 0x21 && c <= 0x7e
+ }
+}
- socket
- .setNoDelay(true)
- .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
- cancelTimeout()
+/**
+ * @param {string} characters
+ */
+function isValidHTTPToken (characters) {
+ if (characters.length === 0) {
+ return false
+ }
+ for (let i = 0; i < characters.length; ++i) {
+ if (!isTokenCharCode(characters.charCodeAt(i))) {
+ return false
+ }
+ }
+ return true
+}
- if (callback) {
- const cb = callback
- callback = null
- cb(null, this)
- }
- })
- .on('error', function (err) {
- cancelTimeout()
+/**
+ * @see https://fetch.spec.whatwg.org/#header-name
+ * @param {string} potentialValue
+ */
+function isValidHeaderName (potentialValue) {
+ return isValidHTTPToken(potentialValue)
+}
- if (callback) {
- const cb = callback
- callback = null
- cb(err)
- }
- })
+/**
+ * @see https://fetch.spec.whatwg.org/#header-value
+ * @param {string} potentialValue
+ */
+function isValidHeaderValue (potentialValue) {
+ // - Has no leading or trailing HTTP tab or space bytes.
+ // - Contains no 0x00 (NUL) or HTTP newline bytes.
+ if (
+ potentialValue.startsWith('\t') ||
+ potentialValue.startsWith(' ') ||
+ potentialValue.endsWith('\t') ||
+ potentialValue.endsWith(' ')
+ ) {
+ return false
+ }
- return socket
+ if (
+ potentialValue.includes('\0') ||
+ potentialValue.includes('\r') ||
+ potentialValue.includes('\n')
+ ) {
+ return false
}
+
+ return true
}
-function setupTimeout (onConnectTimeout, timeout) {
- if (!timeout) {
- return () => {}
- }
+// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
+function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
+ // Given a request request and a response actualResponse, this algorithm
+ // updates request’s referrer policy according to the Referrer-Policy
+ // header (if any) in actualResponse.
- let s1 = null
- let s2 = null
- const timeoutId = setTimeout(() => {
- // setImmediate is added to make sure that we priotorise socket error events over timeouts
- s1 = setImmediate(() => {
- if (process.platform === 'win32') {
- // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
- s2 = setImmediate(() => onConnectTimeout())
- } else {
- onConnectTimeout()
+ // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
+ // from a Referrer-Policy header on actualResponse.
+
+ // 8.1 Parse a referrer policy from a Referrer-Policy header
+ // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
+ const { headersList } = actualResponse
+ // 2. Let policy be the empty string.
+ // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.
+ // 4. Return policy.
+ const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')
+
+ // Note: As the referrer-policy can contain multiple policies
+ // separated by comma, we need to loop through all of them
+ // and pick the first valid one.
+ // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy
+ let policy = ''
+ if (policyHeader.length > 0) {
+ // The right-most policy takes precedence.
+ // The left-most policy is the fallback.
+ for (let i = policyHeader.length; i !== 0; i--) {
+ const token = policyHeader[i - 1].trim()
+ if (referrerPolicyTokens.has(token)) {
+ policy = token
+ break
}
- })
- }, timeout)
- return () => {
- clearTimeout(timeoutId)
- clearImmediate(s1)
- clearImmediate(s2)
+ }
}
-}
-function onConnectTimeout (socket) {
- util.destroy(socket, new ConnectTimeoutError())
+ // 2. If policy is not the empty string, then set request’s referrer policy to policy.
+ if (policy !== '') {
+ request.referrerPolicy = policy
+ }
}
-module.exports = buildConnector
+// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
+function crossOriginResourcePolicyCheck () {
+ // TODO
+ return 'allowed'
+}
+// https://fetch.spec.whatwg.org/#concept-cors-check
+function corsCheck () {
+ // TODO
+ return 'success'
+}
-/***/ }),
+// https://fetch.spec.whatwg.org/#concept-tao-check
+function TAOCheck () {
+ // TODO
+ return 'success'
+}
-/***/ 42371:
-/***/ ((module) => {
+function appendFetchMetadata (httpRequest) {
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
+ // TODO
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
+ // 1. Assert: r’s url is a potentially trustworthy URL.
+ // TODO
-/** @type {Record} */
-const headerNameLowerCasedRecord = {}
+ // 2. Let header be a Structured Header whose value is a token.
+ let header = null
-// https://developer.mozilla.org/docs/Web/HTTP/Headers
-const wellknownHeaderNames = [
- 'Accept',
- 'Accept-Encoding',
- 'Accept-Language',
- 'Accept-Ranges',
- 'Access-Control-Allow-Credentials',
- 'Access-Control-Allow-Headers',
- 'Access-Control-Allow-Methods',
- 'Access-Control-Allow-Origin',
- 'Access-Control-Expose-Headers',
- 'Access-Control-Max-Age',
- 'Access-Control-Request-Headers',
- 'Access-Control-Request-Method',
- 'Age',
- 'Allow',
- 'Alt-Svc',
- 'Alt-Used',
- 'Authorization',
- 'Cache-Control',
- 'Clear-Site-Data',
- 'Connection',
- 'Content-Disposition',
- 'Content-Encoding',
- 'Content-Language',
- 'Content-Length',
- 'Content-Location',
- 'Content-Range',
- 'Content-Security-Policy',
- 'Content-Security-Policy-Report-Only',
- 'Content-Type',
- 'Cookie',
- 'Cross-Origin-Embedder-Policy',
- 'Cross-Origin-Opener-Policy',
- 'Cross-Origin-Resource-Policy',
- 'Date',
- 'Device-Memory',
- 'Downlink',
- 'ECT',
- 'ETag',
- 'Expect',
- 'Expect-CT',
- 'Expires',
- 'Forwarded',
- 'From',
- 'Host',
- 'If-Match',
- 'If-Modified-Since',
- 'If-None-Match',
- 'If-Range',
- 'If-Unmodified-Since',
- 'Keep-Alive',
- 'Last-Modified',
- 'Link',
- 'Location',
- 'Max-Forwards',
- 'Origin',
- 'Permissions-Policy',
- 'Pragma',
- 'Proxy-Authenticate',
- 'Proxy-Authorization',
- 'RTT',
- 'Range',
- 'Referer',
- 'Referrer-Policy',
- 'Refresh',
- 'Retry-After',
- 'Sec-WebSocket-Accept',
- 'Sec-WebSocket-Extensions',
- 'Sec-WebSocket-Key',
- 'Sec-WebSocket-Protocol',
- 'Sec-WebSocket-Version',
- 'Server',
- 'Server-Timing',
- 'Service-Worker-Allowed',
- 'Service-Worker-Navigation-Preload',
- 'Set-Cookie',
- 'SourceMap',
- 'Strict-Transport-Security',
- 'Supports-Loading-Mode',
- 'TE',
- 'Timing-Allow-Origin',
- 'Trailer',
- 'Transfer-Encoding',
- 'Upgrade',
- 'Upgrade-Insecure-Requests',
- 'User-Agent',
- 'Vary',
- 'Via',
- 'WWW-Authenticate',
- 'X-Content-Type-Options',
- 'X-DNS-Prefetch-Control',
- 'X-Frame-Options',
- 'X-Permitted-Cross-Domain-Policies',
- 'X-Powered-By',
- 'X-Requested-With',
- 'X-XSS-Protection'
-]
+ // 3. Set header’s value to r’s mode.
+ header = httpRequest.mode
-for (let i = 0; i < wellknownHeaderNames.length; ++i) {
- const key = wellknownHeaderNames[i]
- const lowerCasedKey = key.toLowerCase()
- headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
- lowerCasedKey
-}
+ // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
+ httpRequest.headersList.set('sec-fetch-mode', header)
-// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
-Object.setPrototypeOf(headerNameLowerCasedRecord, null)
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
+ // TODO
-module.exports = {
- wellknownHeaderNames,
- headerNameLowerCasedRecord
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
+ // TODO
}
+// https://fetch.spec.whatwg.org/#append-a-request-origin-header
+function appendRequestOriginHeader (request) {
+ // 1. Let serializedOrigin be the result of byte-serializing a request origin with request.
+ let serializedOrigin = request.origin
-/***/ }),
-
-/***/ 53959:
-/***/ ((module) => {
-
+ // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list.
+ if (request.responseTainting === 'cors' || request.mode === 'websocket') {
+ if (serializedOrigin) {
+ request.headersList.append('origin', serializedOrigin)
+ }
+ // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
+ } else if (request.method !== 'GET' && request.method !== 'HEAD') {
+ // 1. Switch on request’s referrer policy:
+ switch (request.referrerPolicy) {
+ case 'no-referrer':
+ // Set serializedOrigin to `null`.
+ serializedOrigin = null
+ break
+ case 'no-referrer-when-downgrade':
+ case 'strict-origin':
+ case 'strict-origin-when-cross-origin':
+ // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`.
+ if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
+ serializedOrigin = null
+ }
+ break
+ case 'same-origin':
+ // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`.
+ if (!sameOrigin(request, requestCurrentURL(request))) {
+ serializedOrigin = null
+ }
+ break
+ default:
+ // Do nothing.
+ }
-class UndiciError extends Error {
- constructor (message) {
- super(message)
- this.name = 'UndiciError'
- this.code = 'UND_ERR'
+ if (serializedOrigin) {
+ // 2. Append (`Origin`, serializedOrigin) to request’s header list.
+ request.headersList.append('origin', serializedOrigin)
+ }
}
}
-class ConnectTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ConnectTimeoutError)
- this.name = 'ConnectTimeoutError'
- this.message = message || 'Connect Timeout Error'
- this.code = 'UND_ERR_CONNECT_TIMEOUT'
- }
+function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
+ // TODO
+ return performance.now()
}
-class HeadersTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, HeadersTimeoutError)
- this.name = 'HeadersTimeoutError'
- this.message = message || 'Headers Timeout Error'
- this.code = 'UND_ERR_HEADERS_TIMEOUT'
+// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
+function createOpaqueTimingInfo (timingInfo) {
+ return {
+ startTime: timingInfo.startTime ?? 0,
+ redirectStartTime: 0,
+ redirectEndTime: 0,
+ postRedirectStartTime: timingInfo.startTime ?? 0,
+ finalServiceWorkerStartTime: 0,
+ finalNetworkResponseStartTime: 0,
+ finalNetworkRequestStartTime: 0,
+ endTime: 0,
+ encodedBodySize: 0,
+ decodedBodySize: 0,
+ finalConnectionTimingInfo: null
}
}
-class HeadersOverflowError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, HeadersOverflowError)
- this.name = 'HeadersOverflowError'
- this.message = message || 'Headers Overflow Error'
- this.code = 'UND_ERR_HEADERS_OVERFLOW'
+// https://html.spec.whatwg.org/multipage/origin.html#policy-container
+function makePolicyContainer () {
+ // Note: the fetch spec doesn't make use of embedder policy or CSP list
+ return {
+ referrerPolicy: 'strict-origin-when-cross-origin'
}
}
-class BodyTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, BodyTimeoutError)
- this.name = 'BodyTimeoutError'
- this.message = message || 'Body Timeout Error'
- this.code = 'UND_ERR_BODY_TIMEOUT'
+// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
+function clonePolicyContainer (policyContainer) {
+ return {
+ referrerPolicy: policyContainer.referrerPolicy
}
}
-class ResponseStatusCodeError extends UndiciError {
- constructor (message, statusCode, headers, body) {
- super(message)
- Error.captureStackTrace(this, ResponseStatusCodeError)
- this.name = 'ResponseStatusCodeError'
- this.message = message || 'Response Status Code Error'
- this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
- this.body = body
- this.status = statusCode
- this.statusCode = statusCode
- this.headers = headers
- }
-}
+// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
+function determineRequestsReferrer (request) {
+ // 1. Let policy be request's referrer policy.
+ const policy = request.referrerPolicy
-class InvalidArgumentError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, InvalidArgumentError)
- this.name = 'InvalidArgumentError'
- this.message = message || 'Invalid Argument Error'
- this.code = 'UND_ERR_INVALID_ARG'
- }
-}
+ // Note: policy cannot (shouldn't) be null or an empty string.
+ assert(policy)
-class InvalidReturnValueError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, InvalidReturnValueError)
- this.name = 'InvalidReturnValueError'
- this.message = message || 'Invalid Return Value Error'
- this.code = 'UND_ERR_INVALID_RETURN_VALUE'
- }
-}
+ // 2. Let environment be request’s client.
-class RequestAbortedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, RequestAbortedError)
- this.name = 'AbortError'
- this.message = message || 'Request aborted'
- this.code = 'UND_ERR_ABORTED'
- }
-}
+ let referrerSource = null
-class InformationalError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, InformationalError)
- this.name = 'InformationalError'
- this.message = message || 'Request information'
- this.code = 'UND_ERR_INFO'
- }
-}
+ // 3. Switch on request’s referrer:
+ if (request.referrer === 'client') {
+ // Note: node isn't a browser and doesn't implement document/iframes,
+ // so we bypass this step and replace it with our own.
-class RequestContentLengthMismatchError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, RequestContentLengthMismatchError)
- this.name = 'RequestContentLengthMismatchError'
- this.message = message || 'Request body length does not match content-length header'
- this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
- }
-}
+ const globalOrigin = getGlobalOrigin()
-class ResponseContentLengthMismatchError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ResponseContentLengthMismatchError)
- this.name = 'ResponseContentLengthMismatchError'
- this.message = message || 'Response body length does not match content-length header'
- this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
- }
-}
+ if (!globalOrigin || globalOrigin.origin === 'null') {
+ return 'no-referrer'
+ }
-class ClientDestroyedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ClientDestroyedError)
- this.name = 'ClientDestroyedError'
- this.message = message || 'The client is destroyed'
- this.code = 'UND_ERR_DESTROYED'
+ // note: we need to clone it as it's mutated
+ referrerSource = new URL(globalOrigin)
+ } else if (request.referrer instanceof URL) {
+ // Let referrerSource be request’s referrer.
+ referrerSource = request.referrer
}
-}
-class ClientClosedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ClientClosedError)
- this.name = 'ClientClosedError'
- this.message = message || 'The client is closed'
- this.code = 'UND_ERR_CLOSED'
- }
-}
+ // 4. Let request’s referrerURL be the result of stripping referrerSource for
+ // use as a referrer.
+ let referrerURL = stripURLForReferrer(referrerSource)
-class SocketError extends UndiciError {
- constructor (message, socket) {
- super(message)
- Error.captureStackTrace(this, SocketError)
- this.name = 'SocketError'
- this.message = message || 'Socket error'
- this.code = 'UND_ERR_SOCKET'
- this.socket = socket
+ // 5. Let referrerOrigin be the result of stripping referrerSource for use as
+ // a referrer, with the origin-only flag set to true.
+ const referrerOrigin = stripURLForReferrer(referrerSource, true)
+
+ // 6. If the result of serializing referrerURL is a string whose length is
+ // greater than 4096, set referrerURL to referrerOrigin.
+ if (referrerURL.toString().length > 4096) {
+ referrerURL = referrerOrigin
}
-}
-class NotSupportedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, NotSupportedError)
- this.name = 'NotSupportedError'
- this.message = message || 'Not supported error'
- this.code = 'UND_ERR_NOT_SUPPORTED'
+ const areSameOrigin = sameOrigin(request, referrerURL)
+ const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
+ !isURLPotentiallyTrustworthy(request.url)
+
+ // 8. Execute the switch statements corresponding to the value of policy:
+ switch (policy) {
+ case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
+ case 'unsafe-url': return referrerURL
+ case 'same-origin':
+ return areSameOrigin ? referrerOrigin : 'no-referrer'
+ case 'origin-when-cross-origin':
+ return areSameOrigin ? referrerURL : referrerOrigin
+ case 'strict-origin-when-cross-origin': {
+ const currentURL = requestCurrentURL(request)
+
+ // 1. If the origin of referrerURL and the origin of request’s current
+ // URL are the same, then return referrerURL.
+ if (sameOrigin(referrerURL, currentURL)) {
+ return referrerURL
+ }
+
+ // 2. If referrerURL is a potentially trustworthy URL and request’s
+ // current URL is not a potentially trustworthy URL, then return no
+ // referrer.
+ if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
+ return 'no-referrer'
+ }
+
+ // 3. Return referrerOrigin.
+ return referrerOrigin
+ }
+ case 'strict-origin': // eslint-disable-line
+ /**
+ * 1. If referrerURL is a potentially trustworthy URL and
+ * request’s current URL is not a potentially trustworthy URL,
+ * then return no referrer.
+ * 2. Return referrerOrigin
+ */
+ case 'no-referrer-when-downgrade': // eslint-disable-line
+ /**
+ * 1. If referrerURL is a potentially trustworthy URL and
+ * request’s current URL is not a potentially trustworthy URL,
+ * then return no referrer.
+ * 2. Return referrerOrigin
+ */
+
+ default: // eslint-disable-line
+ return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
}
}
-class BalancedPoolMissingUpstreamError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, NotSupportedError)
- this.name = 'MissingUpstreamError'
- this.message = message || 'No upstream has been added to the BalancedPool'
- this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
+/**
+ * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
+ * @param {URL} url
+ * @param {boolean|undefined} originOnly
+ */
+function stripURLForReferrer (url, originOnly) {
+ // 1. Assert: url is a URL.
+ assert(url instanceof URL)
+
+ // 2. If url’s scheme is a local scheme, then return no referrer.
+ if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
+ return 'no-referrer'
}
-}
-class HTTPParserError extends Error {
- constructor (message, code, data) {
- super(message)
- Error.captureStackTrace(this, HTTPParserError)
- this.name = 'HTTPParserError'
- this.code = code ? `HPE_${code}` : undefined
- this.data = data ? data.toString() : undefined
+ // 3. Set url’s username to the empty string.
+ url.username = ''
+
+ // 4. Set url’s password to the empty string.
+ url.password = ''
+
+ // 5. Set url’s fragment to null.
+ url.hash = ''
+
+ // 6. If the origin-only flag is true, then:
+ if (originOnly) {
+ // 1. Set url’s path to « the empty string ».
+ url.pathname = ''
+
+ // 2. Set url’s query to null.
+ url.search = ''
}
+
+ // 7. Return url.
+ return url
}
-class ResponseExceededMaxSizeError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ResponseExceededMaxSizeError)
- this.name = 'ResponseExceededMaxSizeError'
- this.message = message || 'Response content exceeded max size'
- this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
+function isURLPotentiallyTrustworthy (url) {
+ if (!(url instanceof URL)) {
+ return false
}
-}
-class RequestRetryError extends UndiciError {
- constructor (message, code, { headers, data }) {
- super(message)
- Error.captureStackTrace(this, RequestRetryError)
- this.name = 'RequestRetryError'
- this.message = message || 'Request retry error'
- this.code = 'UND_ERR_REQ_RETRY'
- this.statusCode = code
- this.data = data
- this.headers = headers
+ // If child of about, return true
+ if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
+ return true
}
-}
-module.exports = {
- HTTPParserError,
- UndiciError,
- HeadersTimeoutError,
- HeadersOverflowError,
- BodyTimeoutError,
- RequestContentLengthMismatchError,
- ConnectTimeoutError,
- ResponseStatusCodeError,
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError,
- ClientDestroyedError,
- ClientClosedError,
- InformationalError,
- SocketError,
- NotSupportedError,
- ResponseContentLengthMismatchError,
- BalancedPoolMissingUpstreamError,
- ResponseExceededMaxSizeError,
- RequestRetryError
-}
+ // If scheme is data, return true
+ if (url.protocol === 'data:') return true
+ // If file, return true
+ if (url.protocol === 'file:') return true
-/***/ }),
+ return isOriginPotentiallyTrustworthy(url.origin)
-/***/ 69691:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ function isOriginPotentiallyTrustworthy (origin) {
+ // If origin is explicitly null, return false
+ if (origin == null || origin === 'null') return false
+ const originAsURL = new URL(origin)
+ // If secure, return true
+ if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
+ return true
+ }
-const {
- InvalidArgumentError,
- NotSupportedError
-} = __nccwpck_require__(53959)
-const assert = __nccwpck_require__(42613)
-const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(68031)
-const util = __nccwpck_require__(89500)
+ // If localhost or variants, return true
+ if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
+ (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
+ (originAsURL.hostname.endsWith('.localhost'))) {
+ return true
+ }
-// tokenRegExp and headerCharRegex have been lifted from
-// https://github.com/nodejs/node/blob/main/lib/_http_common.js
+ // If any other, return false
+ return false
+ }
+}
/**
- * Verifies that the given val is a valid HTTP token
- * per the rules defined in RFC 7230
- * See https://tools.ietf.org/html/rfc7230#section-3.2.6
+ * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
+ * @param {Uint8Array} bytes
+ * @param {string} metadataList
*/
-const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/
+function bytesMatch (bytes, metadataList) {
+ // If node is not built with OpenSSL support, we cannot check
+ // a request's integrity, so allow it by default (the spec will
+ // allow requests if an invalid hash is given, as precedence).
+ /* istanbul ignore if: only if node is built with --without-ssl */
+ if (crypto === undefined) {
+ return true
+ }
-/**
- * Matches if val contains an invalid field-vchar
- * field-value = *( field-content / obs-fold )
- * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
- * field-vchar = VCHAR / obs-text
- */
-const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
+ // 1. Let parsedMetadata be the result of parsing metadataList.
+ const parsedMetadata = parseMetadata(metadataList)
-// Verifies that a given path is valid does not contain control chars \x00 to \x20
-const invalidPathRegex = /[^\u0021-\u00ff]/
+ // 2. If parsedMetadata is no metadata, return true.
+ if (parsedMetadata === 'no metadata') {
+ return true
+ }
-const kHandler = Symbol('handler')
+ // 3. If response is not eligible for integrity validation, return false.
+ // TODO
-const channels = {}
+ // 4. If parsedMetadata is the empty set, return true.
+ if (parsedMetadata.length === 0) {
+ return true
+ }
-let extractBody
+ // 5. Let metadata be the result of getting the strongest
+ // metadata from parsedMetadata.
+ const strongest = getStrongestMetadata(parsedMetadata)
+ const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)
-try {
- const diagnosticsChannel = __nccwpck_require__(31637)
- channels.create = diagnosticsChannel.channel('undici:request:create')
- channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')
- channels.headers = diagnosticsChannel.channel('undici:request:headers')
- channels.trailers = diagnosticsChannel.channel('undici:request:trailers')
- channels.error = diagnosticsChannel.channel('undici:request:error')
-} catch {
- channels.create = { hasSubscribers: false }
- channels.bodySent = { hasSubscribers: false }
- channels.headers = { hasSubscribers: false }
- channels.trailers = { hasSubscribers: false }
- channels.error = { hasSubscribers: false }
-}
+ // 6. For each item in metadata:
+ for (const item of metadata) {
+ // 1. Let algorithm be the alg component of item.
+ const algorithm = item.algo
-class Request {
- constructor (origin, {
- path,
- method,
- body,
- headers,
- query,
- idempotent,
- blocking,
- upgrade,
- headersTimeout,
- bodyTimeout,
- reset,
- throwOnError,
- expectContinue
- }, handler) {
- if (typeof path !== 'string') {
- throw new InvalidArgumentError('path must be a string')
- } else if (
- path[0] !== '/' &&
- !(path.startsWith('http://') || path.startsWith('https://')) &&
- method !== 'CONNECT'
- ) {
- throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
- } else if (invalidPathRegex.exec(path) !== null) {
- throw new InvalidArgumentError('invalid request path')
- }
+ // 2. Let expectedValue be the val component of item.
+ const expectedValue = item.hash
- if (typeof method !== 'string') {
- throw new InvalidArgumentError('method must be a string')
- } else if (tokenRegExp.exec(method) === null) {
- throw new InvalidArgumentError('invalid request method')
- }
+ // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e
+ // "be liberal with padding". This is annoying, and it's not even in the spec.
- if (upgrade && typeof upgrade !== 'string') {
- throw new InvalidArgumentError('upgrade must be a string')
- }
+ // 3. Let actualValue be the result of applying algorithm to bytes.
+ let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
- if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError('invalid headersTimeout')
+ if (actualValue[actualValue.length - 1] === '=') {
+ if (actualValue[actualValue.length - 2] === '=') {
+ actualValue = actualValue.slice(0, -2)
+ } else {
+ actualValue = actualValue.slice(0, -1)
+ }
}
- if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError('invalid bodyTimeout')
+ // 4. If actualValue is a case-sensitive match for expectedValue,
+ // return true.
+ if (compareBase64Mixed(actualValue, expectedValue)) {
+ return true
}
+ }
- if (reset != null && typeof reset !== 'boolean') {
- throw new InvalidArgumentError('invalid reset')
- }
+ // 7. Return false.
+ return false
+}
- if (expectContinue != null && typeof expectContinue !== 'boolean') {
- throw new InvalidArgumentError('invalid expectContinue')
- }
+// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options
+// https://www.w3.org/TR/CSP2/#source-list-syntax
+// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1
+const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i
- this.headersTimeout = headersTimeout
+/**
+ * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
+ * @param {string} metadata
+ */
+function parseMetadata (metadata) {
+ // 1. Let result be the empty set.
+ /** @type {{ algo: string, hash: string }[]} */
+ const result = []
- this.bodyTimeout = bodyTimeout
+ // 2. Let empty be equal to true.
+ let empty = true
- this.throwOnError = throwOnError === true
+ // 3. For each token returned by splitting metadata on spaces:
+ for (const token of metadata.split(' ')) {
+ // 1. Set empty to false.
+ empty = false
- this.method = method
+ // 2. Parse token as a hash-with-options.
+ const parsedToken = parseHashWithOptions.exec(token)
- this.abort = null
+ // 3. If token does not parse, continue to the next token.
+ if (
+ parsedToken === null ||
+ parsedToken.groups === undefined ||
+ parsedToken.groups.algo === undefined
+ ) {
+ // Note: Chromium blocks the request at this point, but Firefox
+ // gives a warning that an invalid integrity was given. The
+ // correct behavior is to ignore these, and subsequently not
+ // check the integrity of the resource.
+ continue
+ }
- if (body == null) {
- this.body = null
- } else if (util.isStream(body)) {
- this.body = body
+ // 4. Let algorithm be the hash-algo component of token.
+ const algorithm = parsedToken.groups.algo.toLowerCase()
- const rState = this.body._readableState
- if (!rState || !rState.autoDestroy) {
- this.endHandler = function autoDestroy () {
- util.destroy(this)
- }
- this.body.on('end', this.endHandler)
- }
+ // 5. If algorithm is a hash function recognized by the user
+ // agent, add the parsed token to result.
+ if (supportedHashes.includes(algorithm)) {
+ result.push(parsedToken.groups)
+ }
+ }
- this.errorHandler = err => {
- if (this.abort) {
- this.abort(err)
- } else {
- this.error = err
- }
- }
- this.body.on('error', this.errorHandler)
- } else if (util.isBuffer(body)) {
- this.body = body.byteLength ? body : null
- } else if (ArrayBuffer.isView(body)) {
- this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
- } else if (body instanceof ArrayBuffer) {
- this.body = body.byteLength ? Buffer.from(body) : null
- } else if (typeof body === 'string') {
- this.body = body.length ? Buffer.from(body) : null
- } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {
- this.body = body
- } else {
- throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
+ // 4. Return no metadata if empty is true, otherwise return result.
+ if (empty === true) {
+ return 'no metadata'
+ }
+
+ return result
+}
+
+/**
+ * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList
+ */
+function getStrongestMetadata (metadataList) {
+ // Let algorithm be the algo component of the first item in metadataList.
+ // Can be sha256
+ let algorithm = metadataList[0].algo
+ // If the algorithm is sha512, then it is the strongest
+ // and we can return immediately
+ if (algorithm[3] === '5') {
+ return algorithm
+ }
+
+ for (let i = 1; i < metadataList.length; ++i) {
+ const metadata = metadataList[i]
+ // If the algorithm is sha512, then it is the strongest
+ // and we can break the loop immediately
+ if (metadata.algo[3] === '5') {
+ algorithm = 'sha512'
+ break
+ // If the algorithm is sha384, then a potential sha256 or sha384 is ignored
+ } else if (algorithm[3] === '3') {
+ continue
+ // algorithm is sha256, check if algorithm is sha384 and if so, set it as
+ // the strongest
+ } else if (metadata.algo[3] === '3') {
+ algorithm = 'sha384'
}
+ }
+ return algorithm
+}
- this.completed = false
+function filterMetadataListByAlgorithm (metadataList, algorithm) {
+ if (metadataList.length === 1) {
+ return metadataList
+ }
- this.aborted = false
+ let pos = 0
+ for (let i = 0; i < metadataList.length; ++i) {
+ if (metadataList[i].algo === algorithm) {
+ metadataList[pos++] = metadataList[i]
+ }
+ }
- this.upgrade = upgrade || null
+ metadataList.length = pos
- this.path = query ? util.buildURL(path, query) : path
+ return metadataList
+}
- this.origin = origin
+/**
+ * Compares two base64 strings, allowing for base64url
+ * in the second string.
+ *
+* @param {string} actualValue always base64
+ * @param {string} expectedValue base64 or base64url
+ * @returns {boolean}
+ */
+function compareBase64Mixed (actualValue, expectedValue) {
+ if (actualValue.length !== expectedValue.length) {
+ return false
+ }
+ for (let i = 0; i < actualValue.length; ++i) {
+ if (actualValue[i] !== expectedValue[i]) {
+ if (
+ (actualValue[i] === '+' && expectedValue[i] === '-') ||
+ (actualValue[i] === '/' && expectedValue[i] === '_')
+ ) {
+ continue
+ }
+ return false
+ }
+ }
- this.idempotent = idempotent == null
- ? method === 'HEAD' || method === 'GET'
- : idempotent
+ return true
+}
- this.blocking = blocking == null ? false : blocking
+// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
+function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
+ // TODO
+}
- this.reset = reset == null ? null : reset
+/**
+ * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
+ * @param {URL} A
+ * @param {URL} B
+ */
+function sameOrigin (A, B) {
+ // 1. If A and B are the same opaque origin, then return true.
+ if (A.origin === B.origin && A.origin === 'null') {
+ return true
+ }
- this.host = null
+ // 2. If A and B are both tuple origins and their schemes,
+ // hosts, and port are identical, then return true.
+ if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
+ return true
+ }
- this.contentLength = null
+ // 3. Return false.
+ return false
+}
- this.contentType = null
+function createDeferredPromise () {
+ let res
+ let rej
+ const promise = new Promise((resolve, reject) => {
+ res = resolve
+ rej = reject
+ })
- this.headers = ''
+ return { promise, resolve: res, reject: rej }
+}
- // Only for H2
- this.expectContinue = expectContinue != null ? expectContinue : false
+function isAborted (fetchParams) {
+ return fetchParams.controller.state === 'aborted'
+}
- if (Array.isArray(headers)) {
- if (headers.length % 2 !== 0) {
- throw new InvalidArgumentError('headers array must be even')
- }
- for (let i = 0; i < headers.length; i += 2) {
- processHeader(this, headers[i], headers[i + 1])
- }
- } else if (headers && typeof headers === 'object') {
- const keys = Object.keys(headers)
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i]
- processHeader(this, key, headers[key])
- }
- } else if (headers != null) {
- throw new InvalidArgumentError('headers must be an object or an array')
- }
+function isCancelled (fetchParams) {
+ return fetchParams.controller.state === 'aborted' ||
+ fetchParams.controller.state === 'terminated'
+}
- if (util.isFormDataLike(this.body)) {
- if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {
- throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')
- }
+const normalizeMethodRecord = {
+ delete: 'DELETE',
+ DELETE: 'DELETE',
+ get: 'GET',
+ GET: 'GET',
+ head: 'HEAD',
+ HEAD: 'HEAD',
+ options: 'OPTIONS',
+ OPTIONS: 'OPTIONS',
+ post: 'POST',
+ POST: 'POST',
+ put: 'PUT',
+ PUT: 'PUT'
+}
- if (!extractBody) {
- extractBody = (__nccwpck_require__(37791).extractBody)
- }
+// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
+Object.setPrototypeOf(normalizeMethodRecord, null)
- const [bodyStream, contentType] = extractBody(body)
- if (this.contentType == null) {
- this.contentType = contentType
- this.headers += `content-type: ${contentType}\r\n`
- }
- this.body = bodyStream.stream
- this.contentLength = bodyStream.length
- } else if (util.isBlobLike(body) && this.contentType == null && body.type) {
- this.contentType = body.type
- this.headers += `content-type: ${body.type}\r\n`
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-method-normalize
+ * @param {string} method
+ */
+function normalizeMethod (method) {
+ return normalizeMethodRecord[method.toLowerCase()] ?? method
+}
- util.validateHandler(handler, method, upgrade)
+// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
+function serializeJavascriptValueToJSONString (value) {
+ // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
+ const result = JSON.stringify(value)
- this.servername = util.getServerName(this.host)
+ // 2. If result is undefined, then throw a TypeError.
+ if (result === undefined) {
+ throw new TypeError('Value is not JSON serializable')
+ }
+
+ // 3. Assert: result is a string.
+ assert(typeof result === 'string')
- this[kHandler] = handler
+ // 4. Return result.
+ return result
+}
- if (channels.create.hasSubscribers) {
- channels.create.publish({ request: this })
- }
- }
+// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
+const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
- onBodySent (chunk) {
- if (this[kHandler].onBodySent) {
- try {
- return this[kHandler].onBodySent(chunk)
- } catch (err) {
- this.abort(err)
- }
- }
+/**
+ * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
+ * @param {() => unknown[]} iterator
+ * @param {string} name name of the instance
+ * @param {'key'|'value'|'key+value'} kind
+ */
+function makeIterator (iterator, name, kind) {
+ const object = {
+ index: 0,
+ kind,
+ target: iterator
}
- onRequestSent () {
- if (channels.bodySent.hasSubscribers) {
- channels.bodySent.publish({ request: this })
- }
+ const i = {
+ next () {
+ // 1. Let interface be the interface for which the iterator prototype object exists.
- if (this[kHandler].onRequestSent) {
- try {
- return this[kHandler].onRequestSent()
- } catch (err) {
- this.abort(err)
- }
- }
- }
+ // 2. Let thisValue be the this value.
- onConnect (abort) {
- assert(!this.aborted)
- assert(!this.completed)
+ // 3. Let object be ? ToObject(thisValue).
- if (this.error) {
- abort(this.error)
- } else {
- this.abort = abort
- return this[kHandler].onConnect(abort)
- }
- }
+ // 4. If object is a platform object, then perform a security
+ // check, passing:
- onHeaders (statusCode, headers, resume, statusText) {
- assert(!this.aborted)
- assert(!this.completed)
+ // 5. If object is not a default iterator object for interface,
+ // then throw a TypeError.
+ if (Object.getPrototypeOf(this) !== i) {
+ throw new TypeError(
+ `'next' called on an object that does not implement interface ${name} Iterator.`
+ )
+ }
- if (channels.headers.hasSubscribers) {
- channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
- }
+ // 6. Let index be object’s index.
+ // 7. Let kind be object’s kind.
+ // 8. Let values be object’s target's value pairs to iterate over.
+ const { index, kind, target } = object
+ const values = target()
- try {
- return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
- } catch (err) {
- this.abort(err)
- }
- }
+ // 9. Let len be the length of values.
+ const len = values.length
- onData (chunk) {
- assert(!this.aborted)
- assert(!this.completed)
+ // 10. If index is greater than or equal to len, then return
+ // CreateIterResultObject(undefined, true).
+ if (index >= len) {
+ return { value: undefined, done: true }
+ }
- try {
- return this[kHandler].onData(chunk)
- } catch (err) {
- this.abort(err)
- return false
- }
- }
+ // 11. Let pair be the entry in values at index index.
+ const pair = values[index]
- onUpgrade (statusCode, headers, socket) {
- assert(!this.aborted)
- assert(!this.completed)
+ // 12. Set object’s index to index + 1.
+ object.index = index + 1
- return this[kHandler].onUpgrade(statusCode, headers, socket)
+ // 13. Return the iterator result for pair and kind.
+ return iteratorResult(pair, kind)
+ },
+ // The class string of an iterator prototype object for a given interface is the
+ // result of concatenating the identifier of the interface and the string " Iterator".
+ [Symbol.toStringTag]: `${name} Iterator`
}
- onComplete (trailers) {
- this.onFinally()
+ // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.
+ Object.setPrototypeOf(i, esIteratorPrototype)
+ // esIteratorPrototype needs to be the prototype of i
+ // which is the prototype of an empty object. Yes, it's confusing.
+ return Object.setPrototypeOf({}, i)
+}
- assert(!this.aborted)
+// https://webidl.spec.whatwg.org/#iterator-result
+function iteratorResult (pair, kind) {
+ let result
- this.completed = true
- if (channels.trailers.hasSubscribers) {
- channels.trailers.publish({ request: this, trailers })
+ // 1. Let result be a value determined by the value of kind:
+ switch (kind) {
+ case 'key': {
+ // 1. Let idlKey be pair’s key.
+ // 2. Let key be the result of converting idlKey to an
+ // ECMAScript value.
+ // 3. result is key.
+ result = pair[0]
+ break
}
-
- try {
- return this[kHandler].onComplete(trailers)
- } catch (err) {
- // TODO (fix): This might be a bad idea?
- this.onError(err)
+ case 'value': {
+ // 1. Let idlValue be pair’s value.
+ // 2. Let value be the result of converting idlValue to
+ // an ECMAScript value.
+ // 3. result is value.
+ result = pair[1]
+ break
+ }
+ case 'key+value': {
+ // 1. Let idlKey be pair’s key.
+ // 2. Let idlValue be pair’s value.
+ // 3. Let key be the result of converting idlKey to an
+ // ECMAScript value.
+ // 4. Let value be the result of converting idlValue to
+ // an ECMAScript value.
+ // 5. Let array be ! ArrayCreate(2).
+ // 6. Call ! CreateDataProperty(array, "0", key).
+ // 7. Call ! CreateDataProperty(array, "1", value).
+ // 8. result is array.
+ result = pair
+ break
}
}
- onError (error) {
- this.onFinally()
+ // 2. Return CreateIterResultObject(result, false).
+ return { value: result, done: false }
+}
- if (channels.error.hasSubscribers) {
- channels.error.publish({ request: this, error })
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#body-fully-read
+ */
+async function fullyReadBody (body, processBody, processBodyError) {
+ // 1. If taskDestination is null, then set taskDestination to
+ // the result of starting a new parallel queue.
- if (this.aborted) {
- return
- }
- this.aborted = true
+ // 2. Let successSteps given a byte sequence bytes be to queue a
+ // fetch task to run processBody given bytes, with taskDestination.
+ const successSteps = processBody
- return this[kHandler].onError(error)
- }
+ // 3. Let errorSteps be to queue a fetch task to run processBodyError,
+ // with taskDestination.
+ const errorSteps = processBodyError
- onFinally () {
- if (this.errorHandler) {
- this.body.off('error', this.errorHandler)
- this.errorHandler = null
- }
+ // 4. Let reader be the result of getting a reader for body’s stream.
+ // If that threw an exception, then run errorSteps with that
+ // exception and return.
+ let reader
- if (this.endHandler) {
- this.body.off('end', this.endHandler)
- this.endHandler = null
- }
+ try {
+ reader = body.stream.getReader()
+ } catch (e) {
+ errorSteps(e)
+ return
}
- // TODO: adjust to support H2
- addHeader (key, value) {
- processHeader(this, key, value)
- return this
+ // 5. Read all bytes from reader, given successSteps and errorSteps.
+ try {
+ const result = await readAllBytes(reader)
+ successSteps(result)
+ } catch (e) {
+ errorSteps(e)
}
+}
- static [kHTTP1BuildRequest] (origin, opts, handler) {
- // TODO: Migrate header parsing here, to make Requests
- // HTTP agnostic
- return new Request(origin, opts, handler)
+/** @type {ReadableStream} */
+let ReadableStream = globalThis.ReadableStream
+
+function isReadableStreamLike (stream) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
}
- static [kHTTP2BuildRequest] (origin, opts, handler) {
- const headers = opts.headers
- opts = { ...opts, headers: null }
+ return stream instanceof ReadableStream || (
+ stream[Symbol.toStringTag] === 'ReadableStream' &&
+ typeof stream.tee === 'function'
+ )
+}
- const request = new Request(origin, opts, handler)
+const MAXIMUM_ARGUMENT_LENGTH = 65535
- request.headers = {}
+/**
+ * @see https://infra.spec.whatwg.org/#isomorphic-decode
+ * @param {number[]|Uint8Array} input
+ */
+function isomorphicDecode (input) {
+ // 1. To isomorphic decode a byte sequence input, return a string whose code point
+ // length is equal to input’s length and whose code points have the same values
+ // as the values of input’s bytes, in the same order.
- if (Array.isArray(headers)) {
- if (headers.length % 2 !== 0) {
- throw new InvalidArgumentError('headers array must be even')
- }
- for (let i = 0; i < headers.length; i += 2) {
- processHeader(request, headers[i], headers[i + 1], true)
- }
- } else if (headers && typeof headers === 'object') {
- const keys = Object.keys(headers)
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i]
- processHeader(request, key, headers[key], true)
- }
- } else if (headers != null) {
- throw new InvalidArgumentError('headers must be an object or an array')
+ if (input.length < MAXIMUM_ARGUMENT_LENGTH) {
+ return String.fromCharCode(...input)
+ }
+
+ return input.reduce((previous, current) => previous + String.fromCharCode(current), '')
+}
+
+/**
+ * @param {ReadableStreamController} controller
+ */
+function readableStreamClose (controller) {
+ try {
+ controller.close()
+ } catch (err) {
+ // TODO: add comment explaining why this error occurs.
+ if (!err.message.includes('Controller is already closed')) {
+ throw err
}
+ }
+}
- return request
+/**
+ * @see https://infra.spec.whatwg.org/#isomorphic-encode
+ * @param {string} input
+ */
+function isomorphicEncode (input) {
+ // 1. Assert: input contains no code points greater than U+00FF.
+ for (let i = 0; i < input.length; i++) {
+ assert(input.charCodeAt(i) <= 0xFF)
}
- static [kHTTP2CopyHeaders] (raw) {
- const rawHeaders = raw.split('\r\n')
- const headers = {}
+ // 2. Return a byte sequence whose length is equal to input’s code
+ // point length and whose bytes have the same values as the
+ // values of input’s code points, in the same order
+ return input
+}
- for (const header of rawHeaders) {
- const [key, value] = header.split(': ')
+/**
+ * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
+ * @see https://streams.spec.whatwg.org/#read-loop
+ * @param {ReadableStreamDefaultReader} reader
+ */
+async function readAllBytes (reader) {
+ const bytes = []
+ let byteLength = 0
- if (value == null || value.length === 0) continue
+ while (true) {
+ const { done, value: chunk } = await reader.read()
- if (headers[key]) headers[key] += `,${value}`
- else headers[key] = value
+ if (done) {
+ // 1. Call successSteps with bytes.
+ return Buffer.concat(bytes, byteLength)
}
- return headers
- }
-}
+ // 1. If chunk is not a Uint8Array object, call failureSteps
+ // with a TypeError and abort these steps.
+ if (!isUint8Array(chunk)) {
+ throw new TypeError('Received non-Uint8Array chunk')
+ }
-function processHeaderValue (key, val, skipAppend) {
- if (val && typeof val === 'object') {
- throw new InvalidArgumentError(`invalid ${key} header`)
+ // 2. Append the bytes represented by chunk to bytes.
+ bytes.push(chunk)
+ byteLength += chunk.length
+
+ // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
}
+}
- val = val != null ? `${val}` : ''
+/**
+ * @see https://fetch.spec.whatwg.org/#is-local
+ * @param {URL} url
+ */
+function urlIsLocal (url) {
+ assert('protocol' in url) // ensure it's a url object
- if (headerCharRegex.exec(val) !== null) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- }
+ const protocol = url.protocol
- return skipAppend ? val : `${key}: ${val}\r\n`
+ return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
}
-function processHeader (request, key, val, skipAppend = false) {
- if (val && (typeof val === 'object' && !Array.isArray(val))) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- } else if (val === undefined) {
- return
+/**
+ * @param {string|URL} url
+ */
+function urlHasHttpsScheme (url) {
+ if (typeof url === 'string') {
+ return url.startsWith('https:')
}
- if (
- request.host === null &&
- key.length === 4 &&
- key.toLowerCase() === 'host'
- ) {
- if (headerCharRegex.exec(val) !== null) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- }
- // Consumed by Client
- request.host = val
- } else if (
- request.contentLength === null &&
- key.length === 14 &&
- key.toLowerCase() === 'content-length'
- ) {
- request.contentLength = parseInt(val, 10)
- if (!Number.isFinite(request.contentLength)) {
- throw new InvalidArgumentError('invalid content-length header')
- }
- } else if (
- request.contentType === null &&
- key.length === 12 &&
- key.toLowerCase() === 'content-type'
- ) {
- request.contentType = val
- if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
- else request.headers += processHeaderValue(key, val)
- } else if (
- key.length === 17 &&
- key.toLowerCase() === 'transfer-encoding'
- ) {
- throw new InvalidArgumentError('invalid transfer-encoding header')
- } else if (
- key.length === 10 &&
- key.toLowerCase() === 'connection'
- ) {
- const value = typeof val === 'string' ? val.toLowerCase() : null
- if (value !== 'close' && value !== 'keep-alive') {
- throw new InvalidArgumentError('invalid connection header')
- } else if (value === 'close') {
- request.reset = true
- }
- } else if (
- key.length === 10 &&
- key.toLowerCase() === 'keep-alive'
- ) {
- throw new InvalidArgumentError('invalid keep-alive header')
- } else if (
- key.length === 7 &&
- key.toLowerCase() === 'upgrade'
- ) {
- throw new InvalidArgumentError('invalid upgrade header')
- } else if (
- key.length === 6 &&
- key.toLowerCase() === 'expect'
- ) {
- throw new NotSupportedError('expect header not supported')
- } else if (tokenRegExp.exec(key) === null) {
- throw new InvalidArgumentError('invalid header key')
- } else {
- if (Array.isArray(val)) {
- for (let i = 0; i < val.length; i++) {
- if (skipAppend) {
- if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`
- else request.headers[key] = processHeaderValue(key, val[i], skipAppend)
- } else {
- request.headers += processHeaderValue(key, val[i])
- }
- }
- } else {
- if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
- else request.headers += processHeaderValue(key, val)
- }
- }
+ return url.protocol === 'https:'
}
-module.exports = Request
-
-
-/***/ }),
+/**
+ * @see https://fetch.spec.whatwg.org/#http-scheme
+ * @param {URL} url
+ */
+function urlIsHttpHttpsScheme (url) {
+ assert('protocol' in url) // ensure it's a url object
-/***/ 68031:
-/***/ ((module) => {
+ const protocol = url.protocol
-module.exports = {
- kClose: Symbol('close'),
- kDestroy: Symbol('destroy'),
- kDispatch: Symbol('dispatch'),
- kUrl: Symbol('url'),
- kWriting: Symbol('writing'),
- kResuming: Symbol('resuming'),
- kQueue: Symbol('queue'),
- kConnect: Symbol('connect'),
- kConnecting: Symbol('connecting'),
- kHeadersList: Symbol('headers list'),
- kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
- kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
- kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
- kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
- kKeepAlive: Symbol('keep alive'),
- kHeadersTimeout: Symbol('headers timeout'),
- kBodyTimeout: Symbol('body timeout'),
- kServerName: Symbol('server name'),
- kLocalAddress: Symbol('local address'),
- kHost: Symbol('host'),
- kNoRef: Symbol('no ref'),
- kBodyUsed: Symbol('used'),
- kRunning: Symbol('running'),
- kBlocking: Symbol('blocking'),
- kPending: Symbol('pending'),
- kSize: Symbol('size'),
- kBusy: Symbol('busy'),
- kQueued: Symbol('queued'),
- kFree: Symbol('free'),
- kConnected: Symbol('connected'),
- kClosed: Symbol('closed'),
- kNeedDrain: Symbol('need drain'),
- kReset: Symbol('reset'),
- kDestroyed: Symbol.for('nodejs.stream.destroyed'),
- kMaxHeadersSize: Symbol('max headers size'),
- kRunningIdx: Symbol('running index'),
- kPendingIdx: Symbol('pending index'),
- kError: Symbol('error'),
- kClients: Symbol('clients'),
- kClient: Symbol('client'),
- kParser: Symbol('parser'),
- kOnDestroyed: Symbol('destroy callbacks'),
- kPipelining: Symbol('pipelining'),
- kSocket: Symbol('socket'),
- kHostHeader: Symbol('host header'),
- kConnector: Symbol('connector'),
- kStrictContentLength: Symbol('strict content length'),
- kMaxRedirections: Symbol('maxRedirections'),
- kMaxRequests: Symbol('maxRequestsPerClient'),
- kProxy: Symbol('proxy agent options'),
- kCounter: Symbol('socket request counter'),
- kInterceptors: Symbol('dispatch interceptors'),
- kMaxResponseSize: Symbol('max response size'),
- kHTTP2Session: Symbol('http2Session'),
- kHTTP2SessionState: Symbol('http2Session state'),
- kHTTP2BuildRequest: Symbol('http2 build request'),
- kHTTP1BuildRequest: Symbol('http1 build request'),
- kHTTP2CopyHeaders: Symbol('http2 copy headers'),
- kHTTPConnVersion: Symbol('http connection version'),
- kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
- kConstruct: Symbol('constructable')
+ return protocol === 'http:' || protocol === 'https:'
+}
+
+/**
+ * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.
+ */
+const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))
+
+module.exports = {
+ isAborted,
+ isCancelled,
+ createDeferredPromise,
+ ReadableStreamFrom,
+ toUSVString,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ coarsenedSharedCurrentTime,
+ determineRequestsReferrer,
+ makePolicyContainer,
+ clonePolicyContainer,
+ appendFetchMetadata,
+ appendRequestOriginHeader,
+ TAOCheck,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ createOpaqueTimingInfo,
+ setRequestReferrerPolicyOnRedirect,
+ isValidHTTPToken,
+ requestBadPort,
+ requestCurrentURL,
+ responseURL,
+ responseLocationURL,
+ isBlobLike,
+ isURLPotentiallyTrustworthy,
+ isValidReasonPhrase,
+ sameOrigin,
+ normalizeMethod,
+ serializeJavascriptValueToJSONString,
+ makeIterator,
+ isValidHeaderName,
+ isValidHeaderValue,
+ hasOwn,
+ isErrorLike,
+ fullyReadBody,
+ bytesMatch,
+ isReadableStreamLike,
+ readableStreamClose,
+ isomorphicEncode,
+ isomorphicDecode,
+ urlIsLocal,
+ urlHasHttpsScheme,
+ urlIsHttpHttpsScheme,
+ readAllBytes,
+ normalizeMethodRecord,
+ parseMetadata
}
/***/ }),
-/***/ 89500:
+/***/ 94354:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const assert = __nccwpck_require__(42613)
-const { kDestroyed, kBodyUsed } = __nccwpck_require__(68031)
-const { IncomingMessage } = __nccwpck_require__(58611)
-const stream = __nccwpck_require__(2203)
-const net = __nccwpck_require__(69278)
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-const { Blob } = __nccwpck_require__(20181)
-const nodeUtil = __nccwpck_require__(39023)
-const { stringify } = __nccwpck_require__(83480)
-const { headerNameLowerCasedRecord } = __nccwpck_require__(42371)
+const { types } = __nccwpck_require__(39023)
+const { hasOwn, toUSVString } = __nccwpck_require__(72847)
-const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
+/** @type {import('../../types/webidl').Webidl} */
+const webidl = {}
+webidl.converters = {}
+webidl.util = {}
+webidl.errors = {}
-function nop () {}
+webidl.errors.exception = function (message) {
+ return new TypeError(`${message.header}: ${message.message}`)
+}
-function isStream (obj) {
- return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
+webidl.errors.conversionFailed = function (context) {
+ const plural = context.types.length === 1 ? '' : ' one of'
+ const message =
+ `${context.argument} could not be converted to` +
+ `${plural}: ${context.types.join(', ')}.`
+
+ return webidl.errors.exception({
+ header: context.prefix,
+ message
+ })
}
-// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
-function isBlobLike (object) {
- return (Blob && object instanceof Blob) || (
- object &&
- typeof object === 'object' &&
- (typeof object.stream === 'function' ||
- typeof object.arrayBuffer === 'function') &&
- /^(Blob|File)$/.test(object[Symbol.toStringTag])
- )
+webidl.errors.invalidArgument = function (context) {
+ return webidl.errors.exception({
+ header: context.prefix,
+ message: `"${context.value}" is an invalid ${context.type}.`
+ })
}
-function buildURL (url, queryParams) {
- if (url.includes('?') || url.includes('#')) {
- throw new Error('Query params cannot be passed when url already contains "?" or "#".')
+// https://webidl.spec.whatwg.org/#implements
+webidl.brandCheck = function (V, I, opts = undefined) {
+ if (opts?.strict !== false && !(V instanceof I)) {
+ throw new TypeError('Illegal invocation')
+ } else {
+ return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]
}
+}
- const stringified = stringify(queryParams)
-
- if (stringified) {
- url += '?' + stringified
+webidl.argumentLengthCheck = function ({ length }, min, ctx) {
+ if (length < min) {
+ throw webidl.errors.exception({
+ message: `${min} argument${min !== 1 ? 's' : ''} required, ` +
+ `but${length ? ' only' : ''} ${length} found.`,
+ ...ctx
+ })
}
+}
- return url
+webidl.illegalConstructor = function () {
+ throw webidl.errors.exception({
+ header: 'TypeError',
+ message: 'Illegal constructor'
+ })
}
-function parseURL (url) {
- if (typeof url === 'string') {
- url = new URL(url)
+// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
+webidl.util.Type = function (V) {
+ switch (typeof V) {
+ case 'undefined': return 'Undefined'
+ case 'boolean': return 'Boolean'
+ case 'string': return 'String'
+ case 'symbol': return 'Symbol'
+ case 'number': return 'Number'
+ case 'bigint': return 'BigInt'
+ case 'function':
+ case 'object': {
+ if (V === null) {
+ return 'Null'
+ }
- if (!/^https?:/.test(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ return 'Object'
}
-
- return url
}
+}
- if (!url || typeof url !== 'object') {
- throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
+// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
+webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {
+ let upperBound
+ let lowerBound
+
+ // 1. If bitLength is 64, then:
+ if (bitLength === 64) {
+ // 1. Let upperBound be 2^53 − 1.
+ upperBound = Math.pow(2, 53) - 1
+
+ // 2. If signedness is "unsigned", then let lowerBound be 0.
+ if (signedness === 'unsigned') {
+ lowerBound = 0
+ } else {
+ // 3. Otherwise let lowerBound be −2^53 + 1.
+ lowerBound = Math.pow(-2, 53) + 1
+ }
+ } else if (signedness === 'unsigned') {
+ // 2. Otherwise, if signedness is "unsigned", then:
+
+ // 1. Let lowerBound be 0.
+ lowerBound = 0
+
+ // 2. Let upperBound be 2^bitLength − 1.
+ upperBound = Math.pow(2, bitLength) - 1
+ } else {
+ // 3. Otherwise:
+
+ // 1. Let lowerBound be -2^bitLength − 1.
+ lowerBound = Math.pow(-2, bitLength) - 1
+
+ // 2. Let upperBound be 2^bitLength − 1 − 1.
+ upperBound = Math.pow(2, bitLength - 1) - 1
}
- if (!/^https?:/.test(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ // 4. Let x be ? ToNumber(V).
+ let x = Number(V)
+
+ // 5. If x is −0, then set x to +0.
+ if (x === 0) {
+ x = 0
}
- if (!(url instanceof URL)) {
- if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {
- throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
+ // 6. If the conversion is to an IDL type associated
+ // with the [EnforceRange] extended attribute, then:
+ if (opts.enforceRange === true) {
+ // 1. If x is NaN, +∞, or −∞, then throw a TypeError.
+ if (
+ Number.isNaN(x) ||
+ x === Number.POSITIVE_INFINITY ||
+ x === Number.NEGATIVE_INFINITY
+ ) {
+ throw webidl.errors.exception({
+ header: 'Integer conversion',
+ message: `Could not convert ${V} to an integer.`
+ })
}
- if (url.path != null && typeof url.path !== 'string') {
- throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
- }
+ // 2. Set x to IntegerPart(x).
+ x = webidl.util.IntegerPart(x)
- if (url.pathname != null && typeof url.pathname !== 'string') {
- throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
+ // 3. If x < lowerBound or x > upperBound, then
+ // throw a TypeError.
+ if (x < lowerBound || x > upperBound) {
+ throw webidl.errors.exception({
+ header: 'Integer conversion',
+ message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
+ })
}
- if (url.hostname != null && typeof url.hostname !== 'string') {
- throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
- }
+ // 4. Return x.
+ return x
+ }
- if (url.origin != null && typeof url.origin !== 'string') {
- throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
+ // 7. If x is not NaN and the conversion is to an IDL
+ // type associated with the [Clamp] extended
+ // attribute, then:
+ if (!Number.isNaN(x) && opts.clamp === true) {
+ // 1. Set x to min(max(x, lowerBound), upperBound).
+ x = Math.min(Math.max(x, lowerBound), upperBound)
+
+ // 2. Round x to the nearest integer, choosing the
+ // even integer if it lies halfway between two,
+ // and choosing +0 rather than −0.
+ if (Math.floor(x) % 2 === 0) {
+ x = Math.floor(x)
+ } else {
+ x = Math.ceil(x)
}
- const port = url.port != null
- ? url.port
- : (url.protocol === 'https:' ? 443 : 80)
- let origin = url.origin != null
- ? url.origin
- : `${url.protocol}//${url.hostname}:${port}`
- let path = url.path != null
- ? url.path
- : `${url.pathname || ''}${url.search || ''}`
+ // 3. Return x.
+ return x
+ }
- if (origin.endsWith('/')) {
- origin = origin.substring(0, origin.length - 1)
- }
+ // 8. If x is NaN, +0, +∞, or −∞, then return +0.
+ if (
+ Number.isNaN(x) ||
+ (x === 0 && Object.is(0, x)) ||
+ x === Number.POSITIVE_INFINITY ||
+ x === Number.NEGATIVE_INFINITY
+ ) {
+ return 0
+ }
- if (path && !path.startsWith('/')) {
- path = `/${path}`
- }
- // new URL(path, origin) is unsafe when `path` contains an absolute URL
- // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
- // If first parameter is a relative URL, second param is required, and will be used as the base URL.
- // If first parameter is an absolute URL, a given second param will be ignored.
- url = new URL(origin + path)
+ // 9. Set x to IntegerPart(x).
+ x = webidl.util.IntegerPart(x)
+
+ // 10. Set x to x modulo 2^bitLength.
+ x = x % Math.pow(2, bitLength)
+
+ // 11. If signedness is "signed" and x ≥ 2^bitLength − 1,
+ // then return x − 2^bitLength.
+ if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
+ return x - Math.pow(2, bitLength)
}
- return url
+ // 12. Otherwise, return x.
+ return x
}
-function parseOrigin (url) {
- url = parseURL(url)
+// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
+webidl.util.IntegerPart = function (n) {
+ // 1. Let r be floor(abs(n)).
+ const r = Math.floor(Math.abs(n))
- if (url.pathname !== '/' || url.search || url.hash) {
- throw new InvalidArgumentError('invalid url')
+ // 2. If n < 0, then return -1 × r.
+ if (n < 0) {
+ return -1 * r
}
- return url
+ // 3. Otherwise, return r.
+ return r
}
-function getHostname (host) {
- if (host[0] === '[') {
- const idx = host.indexOf(']')
+// https://webidl.spec.whatwg.org/#es-sequence
+webidl.sequenceConverter = function (converter) {
+ return (V) => {
+ // 1. If Type(V) is not Object, throw a TypeError.
+ if (webidl.util.Type(V) !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Sequence',
+ message: `Value of type ${webidl.util.Type(V)} is not an Object.`
+ })
+ }
- assert(idx !== -1)
- return host.substring(1, idx)
- }
+ // 2. Let method be ? GetMethod(V, @@iterator).
+ /** @type {Generator} */
+ const method = V?.[Symbol.iterator]?.()
+ const seq = []
- const idx = host.indexOf(':')
- if (idx === -1) return host
+ // 3. If method is undefined, throw a TypeError.
+ if (
+ method === undefined ||
+ typeof method.next !== 'function'
+ ) {
+ throw webidl.errors.exception({
+ header: 'Sequence',
+ message: 'Object is not an iterator.'
+ })
+ }
- return host.substring(0, idx)
-}
+ // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
+ while (true) {
+ const { done, value } = method.next()
-// IP addresses are not valid server names per RFC6066
-// > Currently, the only server names supported are DNS hostnames
-function getServerName (host) {
- if (!host) {
- return null
- }
+ if (done) {
+ break
+ }
- assert.strictEqual(typeof host, 'string')
+ seq.push(converter(value))
+ }
- const servername = getHostname(host)
- if (net.isIP(servername)) {
- return ''
+ return seq
}
-
- return servername
}
-function deepClone (obj) {
- return JSON.parse(JSON.stringify(obj))
-}
+// https://webidl.spec.whatwg.org/#es-to-record
+webidl.recordConverter = function (keyConverter, valueConverter) {
+ return (O) => {
+ // 1. If Type(O) is not Object, throw a TypeError.
+ if (webidl.util.Type(O) !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Record',
+ message: `Value of type ${webidl.util.Type(O)} is not an Object.`
+ })
+ }
-function isAsyncIterable (obj) {
- return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
+ // 2. Let result be a new empty instance of record.
+ const result = {}
+
+ if (!types.isProxy(O)) {
+ // Object.keys only returns enumerable properties
+ const keys = Object.keys(O)
+
+ for (const key of keys) {
+ // 1. Let typedKey be key converted to an IDL value of type K.
+ const typedKey = keyConverter(key)
+
+ // 2. Let value be ? Get(O, key).
+ // 3. Let typedValue be value converted to an IDL value of type V.
+ const typedValue = valueConverter(O[key])
+
+ // 4. Set result[typedKey] to typedValue.
+ result[typedKey] = typedValue
+ }
+
+ // 5. Return result.
+ return result
+ }
+
+ // 3. Let keys be ? O.[[OwnPropertyKeys]]().
+ const keys = Reflect.ownKeys(O)
+
+ // 4. For each key of keys.
+ for (const key of keys) {
+ // 1. Let desc be ? O.[[GetOwnProperty]](key).
+ const desc = Reflect.getOwnPropertyDescriptor(O, key)
+
+ // 2. If desc is not undefined and desc.[[Enumerable]] is true:
+ if (desc?.enumerable) {
+ // 1. Let typedKey be key converted to an IDL value of type K.
+ const typedKey = keyConverter(key)
+
+ // 2. Let value be ? Get(O, key).
+ // 3. Let typedValue be value converted to an IDL value of type V.
+ const typedValue = valueConverter(O[key])
+
+ // 4. Set result[typedKey] to typedValue.
+ result[typedKey] = typedValue
+ }
+ }
+
+ // 5. Return result.
+ return result
+ }
}
-function isIterable (obj) {
- return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
+webidl.interfaceConverter = function (i) {
+ return (V, opts = {}) => {
+ if (opts.strict !== false && !(V instanceof i)) {
+ throw webidl.errors.exception({
+ header: i.name,
+ message: `Expected ${V} to be an instance of ${i.name}.`
+ })
+ }
+
+ return V
+ }
}
-function bodyLength (body) {
- if (body == null) {
- return 0
- } else if (isStream(body)) {
- const state = body._readableState
- return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
- ? state.length
- : null
- } else if (isBlobLike(body)) {
- return body.size != null ? body.size : null
- } else if (isBuffer(body)) {
- return body.byteLength
+webidl.dictionaryConverter = function (converters) {
+ return (dictionary) => {
+ const type = webidl.util.Type(dictionary)
+ const dict = {}
+
+ if (type === 'Null' || type === 'Undefined') {
+ return dict
+ } else if (type !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
+ })
+ }
+
+ for (const options of converters) {
+ const { key, defaultValue, required, converter } = options
+
+ if (required === true) {
+ if (!hasOwn(dictionary, key)) {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `Missing required key "${key}".`
+ })
+ }
+ }
+
+ let value = dictionary[key]
+ const hasDefault = hasOwn(options, 'defaultValue')
+
+ // Only use defaultValue if value is undefined and
+ // a defaultValue options was provided.
+ if (hasDefault && value !== null) {
+ value = value ?? defaultValue
+ }
+
+ // A key can be optional and have no default value.
+ // When this happens, do not perform a conversion,
+ // and do not assign the key a value.
+ if (required || hasDefault || value !== undefined) {
+ value = converter(value)
+
+ if (
+ options.allowedValues &&
+ !options.allowedValues.includes(value)
+ ) {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
+ })
+ }
+
+ dict[key] = value
+ }
+ }
+
+ return dict
}
+}
+
+webidl.nullableConverter = function (converter) {
+ return (V) => {
+ if (V === null) {
+ return V
+ }
- return null
+ return converter(V)
+ }
}
-function isDestroyed (stream) {
- return !stream || !!(stream.destroyed || stream[kDestroyed])
-}
+// https://webidl.spec.whatwg.org/#es-DOMString
+webidl.converters.DOMString = function (V, opts = {}) {
+ // 1. If V is null and the conversion is to an IDL type
+ // associated with the [LegacyNullToEmptyString]
+ // extended attribute, then return the DOMString value
+ // that represents the empty string.
+ if (V === null && opts.legacyNullToEmptyString) {
+ return ''
+ }
-function isReadableAborted (stream) {
- const state = stream && stream._readableState
- return isDestroyed(stream) && state && !state.endEmitted
+ // 2. Let x be ? ToString(V).
+ if (typeof V === 'symbol') {
+ throw new TypeError('Could not convert argument of type symbol to string.')
+ }
+
+ // 3. Return the IDL DOMString value that represents the
+ // same sequence of code units as the one the
+ // ECMAScript String value x represents.
+ return String(V)
}
-function destroy (stream, err) {
- if (stream == null || !isStream(stream) || isDestroyed(stream)) {
- return
- }
+// https://webidl.spec.whatwg.org/#es-ByteString
+webidl.converters.ByteString = function (V) {
+ // 1. Let x be ? ToString(V).
+ // Note: DOMString converter perform ? ToString(V)
+ const x = webidl.converters.DOMString(V)
- if (typeof stream.destroy === 'function') {
- if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
- // See: https://github.com/nodejs/node/pull/38505/files
- stream.socket = null
+ // 2. If the value of any element of x is greater than
+ // 255, then throw a TypeError.
+ for (let index = 0; index < x.length; index++) {
+ if (x.charCodeAt(index) > 255) {
+ throw new TypeError(
+ 'Cannot convert argument to a ByteString because the character at ' +
+ `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
+ )
}
-
- stream.destroy(err)
- } else if (err) {
- process.nextTick((stream, err) => {
- stream.emit('error', err)
- }, stream, err)
}
- if (stream.destroyed !== true) {
- stream[kDestroyed] = true
- }
+ // 3. Return an IDL ByteString value whose length is the
+ // length of x, and where the value of each element is
+ // the value of the corresponding element of x.
+ return x
}
-const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
-function parseKeepAliveTimeout (val) {
- const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
- return m ? parseInt(m[1], 10) * 1000 : null
+// https://webidl.spec.whatwg.org/#es-USVString
+webidl.converters.USVString = toUSVString
+
+// https://webidl.spec.whatwg.org/#es-boolean
+webidl.converters.boolean = function (V) {
+ // 1. Let x be the result of computing ToBoolean(V).
+ const x = Boolean(V)
+
+ // 2. Return the IDL boolean value that is the one that represents
+ // the same truth value as the ECMAScript Boolean value x.
+ return x
}
-/**
- * Retrieves a header name and returns its lowercase value.
- * @param {string | Buffer} value Header name
- * @returns {string}
- */
-function headerNameToString (value) {
- return headerNameLowerCasedRecord[value] || value.toLowerCase()
+// https://webidl.spec.whatwg.org/#es-any
+webidl.converters.any = function (V) {
+ return V
}
-function parseHeaders (headers, obj = {}) {
- // For H2 support
- if (!Array.isArray(headers)) return headers
+// https://webidl.spec.whatwg.org/#es-long-long
+webidl.converters['long long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 64, "signed").
+ const x = webidl.util.ConvertToInt(V, 64, 'signed')
- for (let i = 0; i < headers.length; i += 2) {
- const key = headers[i].toString().toLowerCase()
- let val = obj[key]
+ // 2. Return the IDL long long value that represents
+ // the same numeric value as x.
+ return x
+}
- if (!val) {
- if (Array.isArray(headers[i + 1])) {
- obj[key] = headers[i + 1].map(x => x.toString('utf8'))
- } else {
- obj[key] = headers[i + 1].toString('utf8')
- }
- } else {
- if (!Array.isArray(val)) {
- val = [val]
- obj[key] = val
- }
- val.push(headers[i + 1].toString('utf8'))
- }
- }
+// https://webidl.spec.whatwg.org/#es-unsigned-long-long
+webidl.converters['unsigned long long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 64, 'unsigned')
- // See https://github.com/nodejs/node/pull/46528
- if ('content-length' in obj && 'content-disposition' in obj) {
- obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
- }
+ // 2. Return the IDL unsigned long long value that
+ // represents the same numeric value as x.
+ return x
+}
- return obj
+// https://webidl.spec.whatwg.org/#es-unsigned-long
+webidl.converters['unsigned long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 32, 'unsigned')
+
+ // 2. Return the IDL unsigned long value that
+ // represents the same numeric value as x.
+ return x
}
-function parseRawHeaders (headers) {
- const ret = []
- let hasContentLength = false
- let contentDispositionIdx = -1
+// https://webidl.spec.whatwg.org/#es-unsigned-short
+webidl.converters['unsigned short'] = function (V, opts) {
+ // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)
- for (let n = 0; n < headers.length; n += 2) {
- const key = headers[n + 0].toString()
- const val = headers[n + 1].toString('utf8')
+ // 2. Return the IDL unsigned short value that represents
+ // the same numeric value as x.
+ return x
+}
- if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
- ret.push(key, val)
- hasContentLength = true
- } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
- contentDispositionIdx = ret.push(key, val) - 1
- } else {
- ret.push(key, val)
- }
+// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
+webidl.converters.ArrayBuffer = function (V, opts = {}) {
+ // 1. If Type(V) is not Object, or V does not have an
+ // [[ArrayBufferData]] internal slot, then throw a
+ // TypeError.
+ // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
+ // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances
+ if (
+ webidl.util.Type(V) !== 'Object' ||
+ !types.isAnyArrayBuffer(V)
+ ) {
+ throw webidl.errors.conversionFailed({
+ prefix: `${V}`,
+ argument: `${V}`,
+ types: ['ArrayBuffer']
+ })
}
- // See https://github.com/nodejs/node/pull/46528
- if (hasContentLength && contentDispositionIdx !== -1) {
- ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
+ // 2. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V) is true, then throw a
+ // TypeError.
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
}
- return ret
-}
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V) is true, then throw a
+ // TypeError.
+ // Note: resizable ArrayBuffers are currently a proposal.
-function isBuffer (buffer) {
- // See, https://github.com/mcollina/undici/pull/319
- return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
+ // 4. Return the IDL ArrayBuffer value that is a
+ // reference to the same object as V.
+ return V
}
-function validateHandler (handler, method, upgrade) {
- if (!handler || typeof handler !== 'object') {
- throw new InvalidArgumentError('handler must be an object')
- }
+webidl.converters.TypedArray = function (V, T, opts = {}) {
+ // 1. Let T be the IDL type V is being converted to.
- if (typeof handler.onConnect !== 'function') {
- throw new InvalidArgumentError('invalid onConnect method')
+ // 2. If Type(V) is not Object, or V does not have a
+ // [[TypedArrayName]] internal slot with a value
+ // equal to T’s name, then throw a TypeError.
+ if (
+ webidl.util.Type(V) !== 'Object' ||
+ !types.isTypedArray(V) ||
+ V.constructor.name !== T.name
+ ) {
+ throw webidl.errors.conversionFailed({
+ prefix: `${T.name}`,
+ argument: `${V}`,
+ types: [T.name]
+ })
}
- if (typeof handler.onError !== 'function') {
- throw new InvalidArgumentError('invalid onError method')
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
}
- if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
- throw new InvalidArgumentError('invalid onBodySent method')
- }
+ // 4. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ // Note: resizable array buffers are currently a proposal
- if (upgrade || method === 'CONNECT') {
- if (typeof handler.onUpgrade !== 'function') {
- throw new InvalidArgumentError('invalid onUpgrade method')
- }
- } else {
- if (typeof handler.onHeaders !== 'function') {
- throw new InvalidArgumentError('invalid onHeaders method')
- }
+ // 5. Return the IDL value of type T that is a reference
+ // to the same object as V.
+ return V
+}
- if (typeof handler.onData !== 'function') {
- throw new InvalidArgumentError('invalid onData method')
- }
+webidl.converters.DataView = function (V, opts = {}) {
+ // 1. If Type(V) is not Object, or V does not have a
+ // [[DataView]] internal slot, then throw a TypeError.
+ if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {
+ throw webidl.errors.exception({
+ header: 'DataView',
+ message: 'Object is not a DataView.'
+ })
+ }
- if (typeof handler.onComplete !== 'function') {
- throw new InvalidArgumentError('invalid onComplete method')
- }
+ // 2. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,
+ // then throw a TypeError.
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
}
-}
-// A body is disturbed if it has been read from and it cannot
-// be re-used without losing state or data.
-function isDisturbed (body) {
- return !!(body && (
- stream.isDisturbed
- ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?
- : body[kBodyUsed] ||
- body.readableDidRead ||
- (body._readableState && body._readableState.dataEmitted) ||
- isReadableAborted(body)
- ))
-}
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ // Note: resizable ArrayBuffers are currently a proposal
-function isErrored (body) {
- return !!(body && (
- stream.isErrored
- ? stream.isErrored(body)
- : /state: 'errored'/.test(nodeUtil.inspect(body)
- )))
+ // 4. Return the IDL DataView value that is a reference
+ // to the same object as V.
+ return V
}
-function isReadable (body) {
- return !!(body && (
- stream.isReadable
- ? stream.isReadable(body)
- : /state: 'readable'/.test(nodeUtil.inspect(body)
- )))
-}
+// https://webidl.spec.whatwg.org/#BufferSource
+webidl.converters.BufferSource = function (V, opts = {}) {
+ if (types.isAnyArrayBuffer(V)) {
+ return webidl.converters.ArrayBuffer(V, opts)
+ }
-function getSocketInfo (socket) {
- return {
- localAddress: socket.localAddress,
- localPort: socket.localPort,
- remoteAddress: socket.remoteAddress,
- remotePort: socket.remotePort,
- remoteFamily: socket.remoteFamily,
- timeout: socket.timeout,
- bytesWritten: socket.bytesWritten,
- bytesRead: socket.bytesRead
+ if (types.isTypedArray(V)) {
+ return webidl.converters.TypedArray(V, V.constructor)
}
-}
-async function * convertIterableToBuffer (iterable) {
- for await (const chunk of iterable) {
- yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+ if (types.isDataView(V)) {
+ return webidl.converters.DataView(V, opts)
}
+
+ throw new TypeError(`Could not convert ${V} to a BufferSource.`)
}
-let ReadableStream
-function ReadableStreamFrom (iterable) {
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(63774).ReadableStream)
- }
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.ByteString
+)
- if (ReadableStream.from) {
- return ReadableStream.from(convertIterableToBuffer(iterable))
- }
+webidl.converters['sequence>'] = webidl.sequenceConverter(
+ webidl.converters['sequence']
+)
- let iterator
- return new ReadableStream(
- {
- async start () {
- iterator = iterable[Symbol.asyncIterator]()
- },
- async pull (controller) {
- const { done, value } = await iterator.next()
- if (done) {
- queueMicrotask(() => {
- controller.close()
- })
- } else {
- const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
- controller.enqueue(new Uint8Array(buf))
- }
- return controller.desiredSize > 0
- },
- async cancel (reason) {
- await iterator.return()
- }
- },
- 0
- )
-}
+webidl.converters['record'] = webidl.recordConverter(
+ webidl.converters.ByteString,
+ webidl.converters.ByteString
+)
-// The chunk should be a FormData instance and contains
-// all the required methods.
-function isFormDataLike (object) {
- return (
- object &&
- typeof object === 'object' &&
- typeof object.append === 'function' &&
- typeof object.delete === 'function' &&
- typeof object.get === 'function' &&
- typeof object.getAll === 'function' &&
- typeof object.has === 'function' &&
- typeof object.set === 'function' &&
- object[Symbol.toStringTag] === 'FormData'
- )
+module.exports = {
+ webidl
}
-function throwIfAborted (signal) {
- if (!signal) { return }
- if (typeof signal.throwIfAborted === 'function') {
- signal.throwIfAborted()
- } else {
- if (signal.aborted) {
- // DOMException not available < v17.0.0
- const err = new Error('The operation was aborted')
- err.name = 'AbortError'
- throw err
- }
- }
-}
-function addAbortListener (signal, listener) {
- if ('addEventListener' in signal) {
- signal.addEventListener('abort', listener, { once: true })
- return () => signal.removeEventListener('abort', listener)
- }
- signal.addListener('abort', listener)
- return () => signal.removeListener('abort', listener)
-}
+/***/ }),
+
+/***/ 68064:
+/***/ ((module) => {
+
-const hasToWellFormed = !!String.prototype.toWellFormed
/**
- * @param {string} val
+ * @see https://encoding.spec.whatwg.org/#concept-encoding-get
+ * @param {string|undefined} label
*/
-function toUSVString (val) {
- if (hasToWellFormed) {
- return `${val}`.toWellFormed()
- } else if (nodeUtil.toUSVString) {
- return nodeUtil.toUSVString(val)
+function getEncoding (label) {
+ if (!label) {
+ return 'failure'
+ }
+
+ // 1. Remove any leading and trailing ASCII whitespace from label.
+ // 2. If label is an ASCII case-insensitive match for any of the
+ // labels listed in the table below, then return the
+ // corresponding encoding; otherwise return failure.
+ switch (label.trim().toLowerCase()) {
+ case 'unicode-1-1-utf-8':
+ case 'unicode11utf8':
+ case 'unicode20utf8':
+ case 'utf-8':
+ case 'utf8':
+ case 'x-unicode20utf8':
+ return 'UTF-8'
+ case '866':
+ case 'cp866':
+ case 'csibm866':
+ case 'ibm866':
+ return 'IBM866'
+ case 'csisolatin2':
+ case 'iso-8859-2':
+ case 'iso-ir-101':
+ case 'iso8859-2':
+ case 'iso88592':
+ case 'iso_8859-2':
+ case 'iso_8859-2:1987':
+ case 'l2':
+ case 'latin2':
+ return 'ISO-8859-2'
+ case 'csisolatin3':
+ case 'iso-8859-3':
+ case 'iso-ir-109':
+ case 'iso8859-3':
+ case 'iso88593':
+ case 'iso_8859-3':
+ case 'iso_8859-3:1988':
+ case 'l3':
+ case 'latin3':
+ return 'ISO-8859-3'
+ case 'csisolatin4':
+ case 'iso-8859-4':
+ case 'iso-ir-110':
+ case 'iso8859-4':
+ case 'iso88594':
+ case 'iso_8859-4':
+ case 'iso_8859-4:1988':
+ case 'l4':
+ case 'latin4':
+ return 'ISO-8859-4'
+ case 'csisolatincyrillic':
+ case 'cyrillic':
+ case 'iso-8859-5':
+ case 'iso-ir-144':
+ case 'iso8859-5':
+ case 'iso88595':
+ case 'iso_8859-5':
+ case 'iso_8859-5:1988':
+ return 'ISO-8859-5'
+ case 'arabic':
+ case 'asmo-708':
+ case 'csiso88596e':
+ case 'csiso88596i':
+ case 'csisolatinarabic':
+ case 'ecma-114':
+ case 'iso-8859-6':
+ case 'iso-8859-6-e':
+ case 'iso-8859-6-i':
+ case 'iso-ir-127':
+ case 'iso8859-6':
+ case 'iso88596':
+ case 'iso_8859-6':
+ case 'iso_8859-6:1987':
+ return 'ISO-8859-6'
+ case 'csisolatingreek':
+ case 'ecma-118':
+ case 'elot_928':
+ case 'greek':
+ case 'greek8':
+ case 'iso-8859-7':
+ case 'iso-ir-126':
+ case 'iso8859-7':
+ case 'iso88597':
+ case 'iso_8859-7':
+ case 'iso_8859-7:1987':
+ case 'sun_eu_greek':
+ return 'ISO-8859-7'
+ case 'csiso88598e':
+ case 'csisolatinhebrew':
+ case 'hebrew':
+ case 'iso-8859-8':
+ case 'iso-8859-8-e':
+ case 'iso-ir-138':
+ case 'iso8859-8':
+ case 'iso88598':
+ case 'iso_8859-8':
+ case 'iso_8859-8:1988':
+ case 'visual':
+ return 'ISO-8859-8'
+ case 'csiso88598i':
+ case 'iso-8859-8-i':
+ case 'logical':
+ return 'ISO-8859-8-I'
+ case 'csisolatin6':
+ case 'iso-8859-10':
+ case 'iso-ir-157':
+ case 'iso8859-10':
+ case 'iso885910':
+ case 'l6':
+ case 'latin6':
+ return 'ISO-8859-10'
+ case 'iso-8859-13':
+ case 'iso8859-13':
+ case 'iso885913':
+ return 'ISO-8859-13'
+ case 'iso-8859-14':
+ case 'iso8859-14':
+ case 'iso885914':
+ return 'ISO-8859-14'
+ case 'csisolatin9':
+ case 'iso-8859-15':
+ case 'iso8859-15':
+ case 'iso885915':
+ case 'iso_8859-15':
+ case 'l9':
+ return 'ISO-8859-15'
+ case 'iso-8859-16':
+ return 'ISO-8859-16'
+ case 'cskoi8r':
+ case 'koi':
+ case 'koi8':
+ case 'koi8-r':
+ case 'koi8_r':
+ return 'KOI8-R'
+ case 'koi8-ru':
+ case 'koi8-u':
+ return 'KOI8-U'
+ case 'csmacintosh':
+ case 'mac':
+ case 'macintosh':
+ case 'x-mac-roman':
+ return 'macintosh'
+ case 'iso-8859-11':
+ case 'iso8859-11':
+ case 'iso885911':
+ case 'tis-620':
+ case 'windows-874':
+ return 'windows-874'
+ case 'cp1250':
+ case 'windows-1250':
+ case 'x-cp1250':
+ return 'windows-1250'
+ case 'cp1251':
+ case 'windows-1251':
+ case 'x-cp1251':
+ return 'windows-1251'
+ case 'ansi_x3.4-1968':
+ case 'ascii':
+ case 'cp1252':
+ case 'cp819':
+ case 'csisolatin1':
+ case 'ibm819':
+ case 'iso-8859-1':
+ case 'iso-ir-100':
+ case 'iso8859-1':
+ case 'iso88591':
+ case 'iso_8859-1':
+ case 'iso_8859-1:1987':
+ case 'l1':
+ case 'latin1':
+ case 'us-ascii':
+ case 'windows-1252':
+ case 'x-cp1252':
+ return 'windows-1252'
+ case 'cp1253':
+ case 'windows-1253':
+ case 'x-cp1253':
+ return 'windows-1253'
+ case 'cp1254':
+ case 'csisolatin5':
+ case 'iso-8859-9':
+ case 'iso-ir-148':
+ case 'iso8859-9':
+ case 'iso88599':
+ case 'iso_8859-9':
+ case 'iso_8859-9:1989':
+ case 'l5':
+ case 'latin5':
+ case 'windows-1254':
+ case 'x-cp1254':
+ return 'windows-1254'
+ case 'cp1255':
+ case 'windows-1255':
+ case 'x-cp1255':
+ return 'windows-1255'
+ case 'cp1256':
+ case 'windows-1256':
+ case 'x-cp1256':
+ return 'windows-1256'
+ case 'cp1257':
+ case 'windows-1257':
+ case 'x-cp1257':
+ return 'windows-1257'
+ case 'cp1258':
+ case 'windows-1258':
+ case 'x-cp1258':
+ return 'windows-1258'
+ case 'x-mac-cyrillic':
+ case 'x-mac-ukrainian':
+ return 'x-mac-cyrillic'
+ case 'chinese':
+ case 'csgb2312':
+ case 'csiso58gb231280':
+ case 'gb2312':
+ case 'gb_2312':
+ case 'gb_2312-80':
+ case 'gbk':
+ case 'iso-ir-58':
+ case 'x-gbk':
+ return 'GBK'
+ case 'gb18030':
+ return 'gb18030'
+ case 'big5':
+ case 'big5-hkscs':
+ case 'cn-big5':
+ case 'csbig5':
+ case 'x-x-big5':
+ return 'Big5'
+ case 'cseucpkdfmtjapanese':
+ case 'euc-jp':
+ case 'x-euc-jp':
+ return 'EUC-JP'
+ case 'csiso2022jp':
+ case 'iso-2022-jp':
+ return 'ISO-2022-JP'
+ case 'csshiftjis':
+ case 'ms932':
+ case 'ms_kanji':
+ case 'shift-jis':
+ case 'shift_jis':
+ case 'sjis':
+ case 'windows-31j':
+ case 'x-sjis':
+ return 'Shift_JIS'
+ case 'cseuckr':
+ case 'csksc56011987':
+ case 'euc-kr':
+ case 'iso-ir-149':
+ case 'korean':
+ case 'ks_c_5601-1987':
+ case 'ks_c_5601-1989':
+ case 'ksc5601':
+ case 'ksc_5601':
+ case 'windows-949':
+ return 'EUC-KR'
+ case 'csiso2022kr':
+ case 'hz-gb-2312':
+ case 'iso-2022-cn':
+ case 'iso-2022-cn-ext':
+ case 'iso-2022-kr':
+ case 'replacement':
+ return 'replacement'
+ case 'unicodefffe':
+ case 'utf-16be':
+ return 'UTF-16BE'
+ case 'csunicode':
+ case 'iso-10646-ucs-2':
+ case 'ucs-2':
+ case 'unicode':
+ case 'unicodefeff':
+ case 'utf-16':
+ case 'utf-16le':
+ return 'UTF-16LE'
+ case 'x-user-defined':
+ return 'x-user-defined'
+ default: return 'failure'
}
-
- return `${val}`
-}
-
-// Parsed accordingly to RFC 9110
-// https://www.rfc-editor.org/rfc/rfc9110#field.content-range
-function parseRangeHeader (range) {
- if (range == null || range === '') return { start: 0, end: null, size: null }
-
- const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
- return m
- ? {
- start: parseInt(m[1]),
- end: m[2] ? parseInt(m[2]) : null,
- size: m[3] ? parseInt(m[3]) : null
- }
- : null
}
-const kEnumerableProperty = Object.create(null)
-kEnumerableProperty.enumerable = true
-
module.exports = {
- kEnumerableProperty,
- nop,
- isDisturbed,
- isErrored,
- isReadable,
- toUSVString,
- isReadableAborted,
- isBlobLike,
- parseOrigin,
- parseURL,
- getServerName,
- isStream,
- isIterable,
- isAsyncIterable,
- isDestroyed,
- headerNameToString,
- parseRawHeaders,
- parseHeaders,
- parseKeepAliveTimeout,
- destroy,
- bodyLength,
- deepClone,
- ReadableStreamFrom,
- isBuffer,
- validateHandler,
- getSocketInfo,
- isFormDataLike,
- buildURL,
- throwIfAborted,
- addAbortListener,
- parseRangeHeader,
- nodeMajor,
- nodeMinor,
- nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),
- safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']
+ getEncoding
}
/***/ }),
-/***/ 52421:
+/***/ 30052:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const Dispatcher = __nccwpck_require__(20303)
const {
- ClientDestroyedError,
- ClientClosedError,
- InvalidArgumentError
-} = __nccwpck_require__(53959)
-const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(68031)
-
-const kDestroyed = Symbol('destroyed')
-const kClosed = Symbol('closed')
-const kOnDestroyed = Symbol('onDestroyed')
-const kOnClosed = Symbol('onClosed')
-const kInterceptedDispatch = Symbol('Intercepted Dispatch')
+ staticPropertyDescriptors,
+ readOperation,
+ fireAProgressEvent
+} = __nccwpck_require__(94273)
+const {
+ kState,
+ kError,
+ kResult,
+ kEvents,
+ kAborted
+} = __nccwpck_require__(52736)
+const { webidl } = __nccwpck_require__(94354)
+const { kEnumerableProperty } = __nccwpck_require__(89500)
-class DispatcherBase extends Dispatcher {
+class FileReader extends EventTarget {
constructor () {
super()
- this[kDestroyed] = false
- this[kOnDestroyed] = null
- this[kClosed] = false
- this[kOnClosed] = []
+ this[kState] = 'empty'
+ this[kResult] = null
+ this[kError] = null
+ this[kEvents] = {
+ loadend: null,
+ error: null,
+ abort: null,
+ load: null,
+ progress: null,
+ loadstart: null
+ }
}
- get destroyed () {
- return this[kDestroyed]
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
+ * @param {import('buffer').Blob} blob
+ */
+ readAsArrayBuffer (blob) {
+ webidl.brandCheck(this, FileReader)
- get closed () {
- return this[kClosed]
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })
- get interceptors () {
- return this[kInterceptors]
+ blob = webidl.converters.Blob(blob, { strict: false })
+
+ // The readAsArrayBuffer(blob) method, when invoked,
+ // must initiate a read operation for blob with ArrayBuffer.
+ readOperation(this, blob, 'ArrayBuffer')
}
- set interceptors (newInterceptors) {
- if (newInterceptors) {
- for (let i = newInterceptors.length - 1; i >= 0; i--) {
- const interceptor = this[kInterceptors][i]
- if (typeof interceptor !== 'function') {
- throw new InvalidArgumentError('interceptor must be an function')
- }
- }
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#readAsBinaryString
+ * @param {import('buffer').Blob} blob
+ */
+ readAsBinaryString (blob) {
+ webidl.brandCheck(this, FileReader)
- this[kInterceptors] = newInterceptors
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })
- close (callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- this.close((err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
+ blob = webidl.converters.Blob(blob, { strict: false })
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ // The readAsBinaryString(blob) method, when invoked,
+ // must initiate a read operation for blob with BinaryString.
+ readOperation(this, blob, 'BinaryString')
+ }
- if (this[kDestroyed]) {
- queueMicrotask(() => callback(new ClientDestroyedError(), null))
- return
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#readAsDataText
+ * @param {import('buffer').Blob} blob
+ * @param {string?} encoding
+ */
+ readAsText (blob, encoding = undefined) {
+ webidl.brandCheck(this, FileReader)
- if (this[kClosed]) {
- if (this[kOnClosed]) {
- this[kOnClosed].push(callback)
- } else {
- queueMicrotask(() => callback(null, null))
- }
- return
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })
- this[kClosed] = true
- this[kOnClosed].push(callback)
+ blob = webidl.converters.Blob(blob, { strict: false })
- const onClosed = () => {
- const callbacks = this[kOnClosed]
- this[kOnClosed] = null
- for (let i = 0; i < callbacks.length; i++) {
- callbacks[i](null, null)
- }
+ if (encoding !== undefined) {
+ encoding = webidl.converters.DOMString(encoding)
}
- // Should not error.
- this[kClose]()
- .then(() => this.destroy())
- .then(() => {
- queueMicrotask(onClosed)
- })
+ // The readAsText(blob, encoding) method, when invoked,
+ // must initiate a read operation for blob with Text and encoding.
+ readOperation(this, blob, 'Text', encoding)
}
- destroy (err, callback) {
- if (typeof err === 'function') {
- callback = err
- err = null
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
+ * @param {import('buffer').Blob} blob
+ */
+ readAsDataURL (blob) {
+ webidl.brandCheck(this, FileReader)
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- this.destroy(err, (err, data) => {
- return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
- })
- })
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ blob = webidl.converters.Blob(blob, { strict: false })
- if (this[kDestroyed]) {
- if (this[kOnDestroyed]) {
- this[kOnDestroyed].push(callback)
- } else {
- queueMicrotask(() => callback(null, null))
- }
+ // The readAsDataURL(blob) method, when invoked, must
+ // initiate a read operation for blob with DataURL.
+ readOperation(this, blob, 'DataURL')
+ }
+
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-abort
+ */
+ abort () {
+ // 1. If this's state is "empty" or if this's state is
+ // "done" set this's result to null and terminate
+ // this algorithm.
+ if (this[kState] === 'empty' || this[kState] === 'done') {
+ this[kResult] = null
return
}
- if (!err) {
- err = new ClientDestroyedError()
+ // 2. If this's state is "loading" set this's state to
+ // "done" and set this's result to null.
+ if (this[kState] === 'loading') {
+ this[kState] = 'done'
+ this[kResult] = null
}
- this[kDestroyed] = true
- this[kOnDestroyed] = this[kOnDestroyed] || []
- this[kOnDestroyed].push(callback)
-
- const onDestroyed = () => {
- const callbacks = this[kOnDestroyed]
- this[kOnDestroyed] = null
- for (let i = 0; i < callbacks.length; i++) {
- callbacks[i](null, null)
- }
- }
+ // 3. If there are any tasks from this on the file reading
+ // task source in an affiliated task queue, then remove
+ // those tasks from that task queue.
+ this[kAborted] = true
- // Should not error.
- this[kDestroy](err).then(() => {
- queueMicrotask(onDestroyed)
- })
- }
+ // 4. Terminate the algorithm for the read method being processed.
+ // TODO
- [kInterceptedDispatch] (opts, handler) {
- if (!this[kInterceptors] || this[kInterceptors].length === 0) {
- this[kInterceptedDispatch] = this[kDispatch]
- return this[kDispatch](opts, handler)
- }
+ // 5. Fire a progress event called abort at this.
+ fireAProgressEvent('abort', this)
- let dispatch = this[kDispatch].bind(this)
- for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
- dispatch = this[kInterceptors][i](dispatch)
+ // 6. If this's state is not "loading", fire a progress
+ // event called loadend at this.
+ if (this[kState] !== 'loading') {
+ fireAProgressEvent('loadend', this)
}
- this[kInterceptedDispatch] = dispatch
- return dispatch(opts, handler)
}
- dispatch (opts, handler) {
- if (!handler || typeof handler !== 'object') {
- throw new InvalidArgumentError('handler must be an object')
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
+ */
+ get readyState () {
+ webidl.brandCheck(this, FileReader)
+
+ switch (this[kState]) {
+ case 'empty': return this.EMPTY
+ case 'loading': return this.LOADING
+ case 'done': return this.DONE
}
+ }
- try {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('opts must be an object.')
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-result
+ */
+ get result () {
+ webidl.brandCheck(this, FileReader)
- if (this[kDestroyed] || this[kOnDestroyed]) {
- throw new ClientDestroyedError()
- }
+ // The result attribute’s getter, when invoked, must return
+ // this's result.
+ return this[kResult]
+ }
- if (this[kClosed]) {
- throw new ClientClosedError()
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-error
+ */
+ get error () {
+ webidl.brandCheck(this, FileReader)
- return this[kInterceptedDispatch](opts, handler)
- } catch (err) {
- if (typeof handler.onError !== 'function') {
- throw new InvalidArgumentError('invalid onError method')
- }
+ // The error attribute’s getter, when invoked, must return
+ // this's error.
+ return this[kError]
+ }
- handler.onError(err)
+ get onloadend () {
+ webidl.brandCheck(this, FileReader)
- return false
- }
+ return this[kEvents].loadend
}
-}
-module.exports = DispatcherBase
+ set onloadend (fn) {
+ webidl.brandCheck(this, FileReader)
+ if (this[kEvents].loadend) {
+ this.removeEventListener('loadend', this[kEvents].loadend)
+ }
-/***/ }),
+ if (typeof fn === 'function') {
+ this[kEvents].loadend = fn
+ this.addEventListener('loadend', fn)
+ } else {
+ this[kEvents].loadend = null
+ }
+ }
-/***/ 20303:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ get onerror () {
+ webidl.brandCheck(this, FileReader)
+ return this[kEvents].error
+ }
+ set onerror (fn) {
+ webidl.brandCheck(this, FileReader)
-const EventEmitter = __nccwpck_require__(24434)
+ if (this[kEvents].error) {
+ this.removeEventListener('error', this[kEvents].error)
+ }
-class Dispatcher extends EventEmitter {
- dispatch () {
- throw new Error('not implemented')
+ if (typeof fn === 'function') {
+ this[kEvents].error = fn
+ this.addEventListener('error', fn)
+ } else {
+ this[kEvents].error = null
+ }
}
- close () {
- throw new Error('not implemented')
- }
+ get onloadstart () {
+ webidl.brandCheck(this, FileReader)
- destroy () {
- throw new Error('not implemented')
+ return this[kEvents].loadstart
}
-}
-module.exports = Dispatcher
+ set onloadstart (fn) {
+ webidl.brandCheck(this, FileReader)
+ if (this[kEvents].loadstart) {
+ this.removeEventListener('loadstart', this[kEvents].loadstart)
+ }
-/***/ }),
+ if (typeof fn === 'function') {
+ this[kEvents].loadstart = fn
+ this.addEventListener('loadstart', fn)
+ } else {
+ this[kEvents].loadstart = null
+ }
+ }
-/***/ 37791:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ get onprogress () {
+ webidl.brandCheck(this, FileReader)
+ return this[kEvents].progress
+ }
+ set onprogress (fn) {
+ webidl.brandCheck(this, FileReader)
-const Busboy = __nccwpck_require__(75249)
-const util = __nccwpck_require__(89500)
-const {
- ReadableStreamFrom,
- isBlobLike,
- isReadableStreamLike,
- readableStreamClose,
- createDeferredPromise,
- fullyReadBody
-} = __nccwpck_require__(72847)
-const { FormData } = __nccwpck_require__(47453)
-const { kState } = __nccwpck_require__(63730)
-const { webidl } = __nccwpck_require__(94354)
-const { DOMException, structuredClone } = __nccwpck_require__(21234)
-const { Blob, File: NativeFile } = __nccwpck_require__(20181)
-const { kBodyUsed } = __nccwpck_require__(68031)
-const assert = __nccwpck_require__(42613)
-const { isErrored } = __nccwpck_require__(89500)
-const { isUint8Array, isArrayBuffer } = __nccwpck_require__(98253)
-const { File: UndiciFile } = __nccwpck_require__(17005)
-const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
+ if (this[kEvents].progress) {
+ this.removeEventListener('progress', this[kEvents].progress)
+ }
-let ReadableStream = globalThis.ReadableStream
+ if (typeof fn === 'function') {
+ this[kEvents].progress = fn
+ this.addEventListener('progress', fn)
+ } else {
+ this[kEvents].progress = null
+ }
+ }
-/** @type {globalThis['File']} */
-const File = NativeFile ?? UndiciFile
-const textEncoder = new TextEncoder()
-const textDecoder = new TextDecoder()
+ get onload () {
+ webidl.brandCheck(this, FileReader)
-// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
-function extractBody (object, keepalive = false) {
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ return this[kEvents].load
}
- // 1. Let stream be null.
- let stream = null
+ set onload (fn) {
+ webidl.brandCheck(this, FileReader)
- // 2. If object is a ReadableStream object, then set stream to object.
- if (object instanceof ReadableStream) {
- stream = object
- } else if (isBlobLike(object)) {
- // 3. Otherwise, if object is a Blob object, set stream to the
- // result of running object’s get stream.
- stream = object.stream()
- } else {
- // 4. Otherwise, set stream to a new ReadableStream object, and set
- // up stream.
- stream = new ReadableStream({
- async pull (controller) {
- controller.enqueue(
- typeof source === 'string' ? textEncoder.encode(source) : source
- )
- queueMicrotask(() => readableStreamClose(controller))
- },
- start () {},
- type: undefined
- })
+ if (this[kEvents].load) {
+ this.removeEventListener('load', this[kEvents].load)
+ }
+
+ if (typeof fn === 'function') {
+ this[kEvents].load = fn
+ this.addEventListener('load', fn)
+ } else {
+ this[kEvents].load = null
+ }
}
- // 5. Assert: stream is a ReadableStream object.
- assert(isReadableStreamLike(stream))
+ get onabort () {
+ webidl.brandCheck(this, FileReader)
- // 6. Let action be null.
- let action = null
+ return this[kEvents].abort
+ }
- // 7. Let source be null.
- let source = null
+ set onabort (fn) {
+ webidl.brandCheck(this, FileReader)
- // 8. Let length be null.
- let length = null
+ if (this[kEvents].abort) {
+ this.removeEventListener('abort', this[kEvents].abort)
+ }
- // 9. Let type be null.
- let type = null
+ if (typeof fn === 'function') {
+ this[kEvents].abort = fn
+ this.addEventListener('abort', fn)
+ } else {
+ this[kEvents].abort = null
+ }
+ }
+}
- // 10. Switch on object:
- if (typeof object === 'string') {
- // Set source to the UTF-8 encoding of object.
- // Note: setting source to a Uint8Array here breaks some mocking assumptions.
- source = object
+// https://w3c.github.io/FileAPI/#dom-filereader-empty
+FileReader.EMPTY = FileReader.prototype.EMPTY = 0
+// https://w3c.github.io/FileAPI/#dom-filereader-loading
+FileReader.LOADING = FileReader.prototype.LOADING = 1
+// https://w3c.github.io/FileAPI/#dom-filereader-done
+FileReader.DONE = FileReader.prototype.DONE = 2
- // Set type to `text/plain;charset=UTF-8`.
- type = 'text/plain;charset=UTF-8'
- } else if (object instanceof URLSearchParams) {
- // URLSearchParams
+Object.defineProperties(FileReader.prototype, {
+ EMPTY: staticPropertyDescriptors,
+ LOADING: staticPropertyDescriptors,
+ DONE: staticPropertyDescriptors,
+ readAsArrayBuffer: kEnumerableProperty,
+ readAsBinaryString: kEnumerableProperty,
+ readAsText: kEnumerableProperty,
+ readAsDataURL: kEnumerableProperty,
+ abort: kEnumerableProperty,
+ readyState: kEnumerableProperty,
+ result: kEnumerableProperty,
+ error: kEnumerableProperty,
+ onloadstart: kEnumerableProperty,
+ onprogress: kEnumerableProperty,
+ onload: kEnumerableProperty,
+ onabort: kEnumerableProperty,
+ onerror: kEnumerableProperty,
+ onloadend: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'FileReader',
+ writable: false,
+ enumerable: false,
+ configurable: true
+ }
+})
- // spec says to run application/x-www-form-urlencoded on body.list
- // this is implemented in Node.js as apart of an URLSearchParams instance toString method
- // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
- // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
+Object.defineProperties(FileReader, {
+ EMPTY: staticPropertyDescriptors,
+ LOADING: staticPropertyDescriptors,
+ DONE: staticPropertyDescriptors
+})
- // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
- source = object.toString()
+module.exports = {
+ FileReader
+}
- // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
- type = 'application/x-www-form-urlencoded;charset=UTF-8'
- } else if (isArrayBuffer(object)) {
- // BufferSource/ArrayBuffer
- // Set source to a copy of the bytes held by object.
- source = new Uint8Array(object.slice())
- } else if (ArrayBuffer.isView(object)) {
- // BufferSource/ArrayBufferView
+/***/ }),
- // Set source to a copy of the bytes held by object.
- source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
- } else if (util.isFormDataLike(object)) {
- const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`
- const prefix = `--${boundary}\r\nContent-Disposition: form-data`
+/***/ 92804:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- /*! formdata-polyfill. MIT License. Jimmy Wärting */
- const escape = (str) =>
- str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
- const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
- // Set action to this step: run the multipart/form-data
- // encoding algorithm, with object’s entry list and UTF-8.
- // - This ensures that the body is immutable and can't be changed afterwords
- // - That the content-length is calculated in advance.
- // - And that all parts are pre-encoded and ready to be sent.
- const blobParts = []
- const rn = new Uint8Array([13, 10]) // '\r\n'
- length = 0
- let hasUnknownSizeValue = false
+const { webidl } = __nccwpck_require__(94354)
- for (const [name, value] of object) {
- if (typeof value === 'string') {
- const chunk = textEncoder.encode(prefix +
- `; name="${escape(normalizeLinefeeds(name))}"` +
- `\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
- blobParts.push(chunk)
- length += chunk.byteLength
- } else {
- const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
- (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
- `Content-Type: ${
- value.type || 'application/octet-stream'
- }\r\n\r\n`)
- blobParts.push(chunk, value, rn)
- if (typeof value.size === 'number') {
- length += chunk.byteLength + value.size + rn.byteLength
- } else {
- hasUnknownSizeValue = true
- }
- }
- }
+const kState = Symbol('ProgressEvent state')
- const chunk = textEncoder.encode(`--${boundary}--`)
- blobParts.push(chunk)
- length += chunk.byteLength
- if (hasUnknownSizeValue) {
- length = null
- }
+/**
+ * @see https://xhr.spec.whatwg.org/#progressevent
+ */
+class ProgressEvent extends Event {
+ constructor (type, eventInitDict = {}) {
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
- // Set source to object.
- source = object
+ super(type, eventInitDict)
- action = async function * () {
- for (const part of blobParts) {
- if (part.stream) {
- yield * part.stream()
- } else {
- yield part
- }
- }
+ this[kState] = {
+ lengthComputable: eventInitDict.lengthComputable,
+ loaded: eventInitDict.loaded,
+ total: eventInitDict.total
}
+ }
- // Set type to `multipart/form-data; boundary=`,
- // followed by the multipart/form-data boundary string generated
- // by the multipart/form-data encoding algorithm.
- type = 'multipart/form-data; boundary=' + boundary
- } else if (isBlobLike(object)) {
- // Blob
+ get lengthComputable () {
+ webidl.brandCheck(this, ProgressEvent)
- // Set source to object.
- source = object
+ return this[kState].lengthComputable
+ }
- // Set length to object’s size.
- length = object.size
+ get loaded () {
+ webidl.brandCheck(this, ProgressEvent)
- // If object’s type attribute is not the empty byte sequence, set
- // type to its value.
- if (object.type) {
- type = object.type
- }
- } else if (typeof object[Symbol.asyncIterator] === 'function') {
- // If keepalive is true, then throw a TypeError.
- if (keepalive) {
- throw new TypeError('keepalive')
- }
+ return this[kState].loaded
+ }
- // If object is disturbed or locked, then throw a TypeError.
- if (util.isDisturbed(object) || object.locked) {
- throw new TypeError(
- 'Response body object should not be disturbed or locked'
- )
- }
+ get total () {
+ webidl.brandCheck(this, ProgressEvent)
- stream =
- object instanceof ReadableStream ? object : ReadableStreamFrom(object)
+ return this[kState].total
}
+}
- // 11. If source is a byte sequence, then set action to a
- // step that returns source and length to source’s length.
- if (typeof source === 'string' || util.isBuffer(source)) {
- length = Buffer.byteLength(source)
+webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
+ {
+ key: 'lengthComputable',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'loaded',
+ converter: webidl.converters['unsigned long long'],
+ defaultValue: 0
+ },
+ {
+ key: 'total',
+ converter: webidl.converters['unsigned long long'],
+ defaultValue: 0
+ },
+ {
+ key: 'bubbles',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'cancelable',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'composed',
+ converter: webidl.converters.boolean,
+ defaultValue: false
}
+])
- // 12. If action is non-null, then run these steps in in parallel:
- if (action != null) {
- // Run action.
- let iterator
- stream = new ReadableStream({
- async start () {
- iterator = action(object)[Symbol.asyncIterator]()
- },
- async pull (controller) {
- const { value, done } = await iterator.next()
- if (done) {
- // When running action is done, close stream.
- queueMicrotask(() => {
- controller.close()
- })
- } else {
- // Whenever one or more bytes are available and stream is not errored,
- // enqueue a Uint8Array wrapping an ArrayBuffer containing the available
- // bytes into stream.
- if (!isErrored(stream)) {
- controller.enqueue(new Uint8Array(value))
- }
- }
- return controller.desiredSize > 0
- },
- async cancel (reason) {
- await iterator.return()
- },
- type: undefined
- })
- }
+module.exports = {
+ ProgressEvent
+}
- // 13. Let body be a body whose stream is stream, source is source,
- // and length is length.
- const body = { stream, source, length }
- // 14. Return (body, type).
- return [body, type]
-}
+/***/ }),
-// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
-function safelyExtractBody (object, keepalive = false) {
- if (!ReadableStream) {
- // istanbul ignore next
- ReadableStream = (__nccwpck_require__(63774).ReadableStream)
- }
+/***/ 52736:
+/***/ ((module) => {
- // To safely extract a body and a `Content-Type` value from
- // a byte sequence or BodyInit object object, run these steps:
- // 1. If object is a ReadableStream object, then:
- if (object instanceof ReadableStream) {
- // Assert: object is neither disturbed nor locked.
- // istanbul ignore next
- assert(!util.isDisturbed(object), 'The body has already been consumed.')
- // istanbul ignore next
- assert(!object.locked, 'The stream is locked.')
- }
- // 2. Return the results of extracting object.
- return extractBody(object, keepalive)
+module.exports = {
+ kState: Symbol('FileReader state'),
+ kResult: Symbol('FileReader result'),
+ kError: Symbol('FileReader error'),
+ kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
+ kEvents: Symbol('FileReader events'),
+ kAborted: Symbol('FileReader aborted')
}
-function cloneBody (body) {
- // To clone a body body, run these steps:
- // https://fetch.spec.whatwg.org/#concept-body-clone
+/***/ }),
- // 1. Let « out1, out2 » be the result of teeing body’s stream.
- const [out1, out2] = body.stream.tee()
- const out2Clone = structuredClone(out2, { transfer: [out2] })
- // This, for whatever reasons, unrefs out2Clone which allows
- // the process to exit by itself.
- const [, finalClone] = out2Clone.tee()
+/***/ 94273:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const {
+ kState,
+ kError,
+ kResult,
+ kAborted,
+ kLastProgressEventFired
+} = __nccwpck_require__(52736)
+const { ProgressEvent } = __nccwpck_require__(92804)
+const { getEncoding } = __nccwpck_require__(68064)
+const { DOMException } = __nccwpck_require__(21234)
+const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(37246)
+const { types } = __nccwpck_require__(39023)
+const { StringDecoder } = __nccwpck_require__(13193)
+const { btoa } = __nccwpck_require__(20181)
+
+/** @type {PropertyDescriptor} */
+const staticPropertyDescriptors = {
+ enumerable: true,
+ writable: false,
+ configurable: false
+}
+
+/**
+ * @see https://w3c.github.io/FileAPI/#readOperation
+ * @param {import('./filereader').FileReader} fr
+ * @param {import('buffer').Blob} blob
+ * @param {string} type
+ * @param {string?} encodingName
+ */
+function readOperation (fr, blob, type, encodingName) {
+ // 1. If fr’s state is "loading", throw an InvalidStateError
+ // DOMException.
+ if (fr[kState] === 'loading') {
+ throw new DOMException('Invalid state', 'InvalidStateError')
+ }
- // 2. Set body’s stream to out1.
- body.stream = out1
+ // 2. Set fr’s state to "loading".
+ fr[kState] = 'loading'
- // 3. Return a body whose stream is out2 and other members are copied from body.
- return {
- stream: finalClone,
- length: body.length,
- source: body.source
- }
-}
+ // 3. Set fr’s result to null.
+ fr[kResult] = null
-async function * consumeBody (body) {
- if (body) {
- if (isUint8Array(body)) {
- yield body
- } else {
- const stream = body.stream
+ // 4. Set fr’s error to null.
+ fr[kError] = null
- if (util.isDisturbed(stream)) {
- throw new TypeError('The body has already been consumed.')
- }
+ // 5. Let stream be the result of calling get stream on blob.
+ /** @type {import('stream/web').ReadableStream} */
+ const stream = blob.stream()
- if (stream.locked) {
- throw new TypeError('The stream is locked.')
- }
+ // 6. Let reader be the result of getting a reader from stream.
+ const reader = stream.getReader()
- // Compat.
- stream[kBodyUsed] = true
+ // 7. Let bytes be an empty byte sequence.
+ /** @type {Uint8Array[]} */
+ const bytes = []
- yield * stream
- }
- }
-}
+ // 8. Let chunkPromise be the result of reading a chunk from
+ // stream with reader.
+ let chunkPromise = reader.read()
-function throwIfAborted (state) {
- if (state.aborted) {
- throw new DOMException('The operation was aborted.', 'AbortError')
- }
-}
+ // 9. Let isFirstChunk be true.
+ let isFirstChunk = true
-function bodyMixinMethods (instance) {
- const methods = {
- blob () {
- // The blob() method steps are to return the result of
- // running consume body with this and the following step
- // given a byte sequence bytes: return a Blob whose
- // contents are bytes and whose type attribute is this’s
- // MIME type.
- return specConsumeBody(this, (bytes) => {
- let mimeType = bodyMimeType(this)
+ // 10. In parallel, while true:
+ // Note: "In parallel" just means non-blocking
+ // Note 2: readOperation itself cannot be async as double
+ // reading the body would then reject the promise, instead
+ // of throwing an error.
+ ;(async () => {
+ while (!fr[kAborted]) {
+ // 1. Wait for chunkPromise to be fulfilled or rejected.
+ try {
+ const { done, value } = await chunkPromise
- if (mimeType === 'failure') {
- mimeType = ''
- } else if (mimeType) {
- mimeType = serializeAMimeType(mimeType)
+ // 2. If chunkPromise is fulfilled, and isFirstChunk is
+ // true, queue a task to fire a progress event called
+ // loadstart at fr.
+ if (isFirstChunk && !fr[kAborted]) {
+ queueMicrotask(() => {
+ fireAProgressEvent('loadstart', fr)
+ })
}
- // Return a Blob whose contents are bytes and type attribute
- // is mimeType.
- return new Blob([bytes], { type: mimeType })
- }, instance)
- },
+ // 3. Set isFirstChunk to false.
+ isFirstChunk = false
- arrayBuffer () {
- // The arrayBuffer() method steps are to return the result
- // of running consume body with this and the following step
- // given a byte sequence bytes: return a new ArrayBuffer
- // whose contents are bytes.
- return specConsumeBody(this, (bytes) => {
- return new Uint8Array(bytes).buffer
- }, instance)
- },
+ // 4. If chunkPromise is fulfilled with an object whose
+ // done property is false and whose value property is
+ // a Uint8Array object, run these steps:
+ if (!done && types.isUint8Array(value)) {
+ // 1. Let bs be the byte sequence represented by the
+ // Uint8Array object.
- text () {
- // The text() method steps are to return the result of running
- // consume body with this and UTF-8 decode.
- return specConsumeBody(this, utf8DecodeBytes, instance)
- },
+ // 2. Append bs to bytes.
+ bytes.push(value)
- json () {
- // The json() method steps are to return the result of running
- // consume body with this and parse JSON from bytes.
- return specConsumeBody(this, parseJSONFromBytes, instance)
- },
+ // 3. If roughly 50ms have passed since these steps
+ // were last invoked, queue a task to fire a
+ // progress event called progress at fr.
+ if (
+ (
+ fr[kLastProgressEventFired] === undefined ||
+ Date.now() - fr[kLastProgressEventFired] >= 50
+ ) &&
+ !fr[kAborted]
+ ) {
+ fr[kLastProgressEventFired] = Date.now()
+ queueMicrotask(() => {
+ fireAProgressEvent('progress', fr)
+ })
+ }
- async formData () {
- webidl.brandCheck(this, instance)
+ // 4. Set chunkPromise to the result of reading a
+ // chunk from stream with reader.
+ chunkPromise = reader.read()
+ } else if (done) {
+ // 5. Otherwise, if chunkPromise is fulfilled with an
+ // object whose done property is true, queue a task
+ // to run the following steps and abort this algorithm:
+ queueMicrotask(() => {
+ // 1. Set fr’s state to "done".
+ fr[kState] = 'done'
- throwIfAborted(this[kState])
+ // 2. Let result be the result of package data given
+ // bytes, type, blob’s type, and encodingName.
+ try {
+ const result = packageData(bytes, type, blob.type, encodingName)
- const contentType = this.headers.get('Content-Type')
+ // 4. Else:
- // If mimeType’s essence is "multipart/form-data", then:
- if (/multipart\/form-data/.test(contentType)) {
- const headers = {}
- for (const [key, value] of this.headers) headers[key.toLowerCase()] = value
+ if (fr[kAborted]) {
+ return
+ }
- const responseFormData = new FormData()
+ // 1. Set fr’s result to result.
+ fr[kResult] = result
- let busboy
+ // 2. Fire a progress event called load at the fr.
+ fireAProgressEvent('load', fr)
+ } catch (error) {
+ // 3. If package data threw an exception error:
- try {
- busboy = new Busboy({
- headers,
- preservePath: true
+ // 1. Set fr’s error to error.
+ fr[kError] = error
+
+ // 2. Fire a progress event called error at fr.
+ fireAProgressEvent('error', fr)
+ }
+
+ // 5. If fr’s state is not "loading", fire a progress
+ // event called loadend at the fr.
+ if (fr[kState] !== 'loading') {
+ fireAProgressEvent('loadend', fr)
+ }
})
- } catch (err) {
- throw new DOMException(`${err}`, 'AbortError')
- }
- busboy.on('field', (name, value) => {
- responseFormData.append(name, value)
- })
- busboy.on('file', (name, value, filename, encoding, mimeType) => {
- const chunks = []
+ break
+ }
+ } catch (error) {
+ if (fr[kAborted]) {
+ return
+ }
- if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {
- let base64chunk = ''
+ // 6. Otherwise, if chunkPromise is rejected with an
+ // error error, queue a task to run the following
+ // steps and abort this algorithm:
+ queueMicrotask(() => {
+ // 1. Set fr’s state to "done".
+ fr[kState] = 'done'
- value.on('data', (chunk) => {
- base64chunk += chunk.toString().replace(/[\r\n]/gm, '')
+ // 2. Set fr’s error to error.
+ fr[kError] = error
- const end = base64chunk.length - base64chunk.length % 4
- chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))
+ // 3. Fire a progress event called error at fr.
+ fireAProgressEvent('error', fr)
- base64chunk = base64chunk.slice(end)
- })
- value.on('end', () => {
- chunks.push(Buffer.from(base64chunk, 'base64'))
- responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
- })
- } else {
- value.on('data', (chunk) => {
- chunks.push(chunk)
- })
- value.on('end', () => {
- responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
- })
+ // 4. If fr’s state is not "loading", fire a progress
+ // event called loadend at fr.
+ if (fr[kState] !== 'loading') {
+ fireAProgressEvent('loadend', fr)
}
})
- const busboyResolve = new Promise((resolve, reject) => {
- busboy.on('finish', resolve)
- busboy.on('error', (err) => reject(new TypeError(err)))
- })
+ break
+ }
+ }
+ })()
+}
- if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)
- busboy.end()
- await busboyResolve
+/**
+ * @see https://w3c.github.io/FileAPI/#fire-a-progress-event
+ * @see https://dom.spec.whatwg.org/#concept-event-fire
+ * @param {string} e The name of the event
+ * @param {import('./filereader').FileReader} reader
+ */
+function fireAProgressEvent (e, reader) {
+ // The progress event e does not bubble. e.bubbles must be false
+ // The progress event e is NOT cancelable. e.cancelable must be false
+ const event = new ProgressEvent(e, {
+ bubbles: false,
+ cancelable: false
+ })
- return responseFormData
- } else if (/application\/x-www-form-urlencoded/.test(contentType)) {
- // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then:
+ reader.dispatchEvent(event)
+}
- // 1. Let entries be the result of parsing bytes.
- let entries
- try {
- let text = ''
- // application/x-www-form-urlencoded parser will keep the BOM.
- // https://url.spec.whatwg.org/#concept-urlencoded-parser
- // Note that streaming decoder is stateful and cannot be reused
- const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
+/**
+ * @see https://w3c.github.io/FileAPI/#blob-package-data
+ * @param {Uint8Array[]} bytes
+ * @param {string} type
+ * @param {string?} mimeType
+ * @param {string?} encodingName
+ */
+function packageData (bytes, type, mimeType, encodingName) {
+ // 1. A Blob has an associated package data algorithm, given
+ // bytes, a type, a optional mimeType, and a optional
+ // encodingName, which switches on type and runs the
+ // associated steps:
- for await (const chunk of consumeBody(this[kState].body)) {
- if (!isUint8Array(chunk)) {
- throw new TypeError('Expected Uint8Array chunk')
- }
- text += streamingDecoder.decode(chunk, { stream: true })
- }
- text += streamingDecoder.decode()
- entries = new URLSearchParams(text)
- } catch (err) {
- // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.
- // 2. If entries is failure, then throw a TypeError.
- throw Object.assign(new TypeError(), { cause: err })
- }
+ switch (type) {
+ case 'DataURL': {
+ // 1. Return bytes as a DataURL [RFC2397] subject to
+ // the considerations below:
+ // * Use mimeType as part of the Data URL if it is
+ // available in keeping with the Data URL
+ // specification [RFC2397].
+ // * If mimeType is not available return a Data URL
+ // without a media-type. [RFC2397].
- // 3. Return a new FormData object whose entries are entries.
- const formData = new FormData()
- for (const [name, value] of entries) {
- formData.append(name, value)
- }
- return formData
- } else {
- // Wait a tick before checking if the request has been aborted.
- // Otherwise, a TypeError can be thrown when an AbortError should.
- await Promise.resolve()
+ // https://datatracker.ietf.org/doc/html/rfc2397#section-3
+ // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
+ // mediatype := [ type "/" subtype ] *( ";" parameter )
+ // data := *urlchar
+ // parameter := attribute "=" value
+ let dataURL = 'data:'
- throwIfAborted(this[kState])
+ const parsed = parseMIMEType(mimeType || 'application/octet-stream')
- // Otherwise, throw a TypeError.
- throw webidl.errors.exception({
- header: `${instance.name}.formData`,
- message: 'Could not parse content as FormData.'
- })
+ if (parsed !== 'failure') {
+ dataURL += serializeAMimeType(parsed)
}
- }
- }
- return methods
-}
+ dataURL += ';base64,'
-function mixinBody (prototype) {
- Object.assign(prototype.prototype, bodyMixinMethods(prototype))
-}
+ const decoder = new StringDecoder('latin1')
-/**
- * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
- * @param {Response|Request} object
- * @param {(value: unknown) => unknown} convertBytesToJSValue
- * @param {Response|Request} instance
- */
-async function specConsumeBody (object, convertBytesToJSValue, instance) {
- webidl.brandCheck(object, instance)
+ for (const chunk of bytes) {
+ dataURL += btoa(decoder.write(chunk))
+ }
- throwIfAborted(object[kState])
+ dataURL += btoa(decoder.end())
- // 1. If object is unusable, then return a promise rejected
- // with a TypeError.
- if (bodyUnusable(object[kState].body)) {
- throw new TypeError('Body is unusable')
- }
+ return dataURL
+ }
+ case 'Text': {
+ // 1. Let encoding be failure
+ let encoding = 'failure'
- // 2. Let promise be a new promise.
- const promise = createDeferredPromise()
+ // 2. If the encodingName is present, set encoding to the
+ // result of getting an encoding from encodingName.
+ if (encodingName) {
+ encoding = getEncoding(encodingName)
+ }
- // 3. Let errorSteps given error be to reject promise with error.
- const errorSteps = (error) => promise.reject(error)
+ // 3. If encoding is failure, and mimeType is present:
+ if (encoding === 'failure' && mimeType) {
+ // 1. Let type be the result of parse a MIME type
+ // given mimeType.
+ const type = parseMIMEType(mimeType)
- // 4. Let successSteps given a byte sequence data be to resolve
- // promise with the result of running convertBytesToJSValue
- // with data. If that threw an exception, then run errorSteps
- // with that exception.
- const successSteps = (data) => {
- try {
- promise.resolve(convertBytesToJSValue(data))
- } catch (e) {
- errorSteps(e)
+ // 2. If type is not failure, set encoding to the result
+ // of getting an encoding from type’s parameters["charset"].
+ if (type !== 'failure') {
+ encoding = getEncoding(type.parameters.get('charset'))
+ }
+ }
+
+ // 4. If encoding is failure, then set encoding to UTF-8.
+ if (encoding === 'failure') {
+ encoding = 'UTF-8'
+ }
+
+ // 5. Decode bytes using fallback encoding encoding, and
+ // return the result.
+ return decode(bytes, encoding)
}
- }
+ case 'ArrayBuffer': {
+ // Return a new ArrayBuffer whose contents are bytes.
+ const sequence = combineByteSequences(bytes)
- // 5. If object’s body is null, then run successSteps with an
- // empty byte sequence.
- if (object[kState].body == null) {
- successSteps(new Uint8Array())
- return promise.promise
- }
+ return sequence.buffer
+ }
+ case 'BinaryString': {
+ // Return bytes as a binary string, in which every byte
+ // is represented by a code unit of equal value [0..255].
+ let binaryString = ''
- // 6. Otherwise, fully read object’s body given successSteps,
- // errorSteps, and object’s relevant global object.
- await fullyReadBody(object[kState].body, successSteps, errorSteps)
+ const decoder = new StringDecoder('latin1')
- // 7. Return promise.
- return promise.promise
-}
+ for (const chunk of bytes) {
+ binaryString += decoder.write(chunk)
+ }
-// https://fetch.spec.whatwg.org/#body-unusable
-function bodyUnusable (body) {
- // An object including the Body interface mixin is
- // said to be unusable if its body is non-null and
- // its body’s stream is disturbed or locked.
- return body != null && (body.stream.locked || util.isDisturbed(body.stream))
+ binaryString += decoder.end()
+
+ return binaryString
+ }
+ }
}
/**
- * @see https://encoding.spec.whatwg.org/#utf-8-decode
- * @param {Buffer} buffer
+ * @see https://encoding.spec.whatwg.org/#decode
+ * @param {Uint8Array[]} ioQueue
+ * @param {string} encoding
*/
-function utf8DecodeBytes (buffer) {
- if (buffer.length === 0) {
- return ''
- }
+function decode (ioQueue, encoding) {
+ const bytes = combineByteSequences(ioQueue)
- // 1. Let buffer be the result of peeking three bytes from
- // ioQueue, converted to a byte sequence.
+ // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
+ const BOMEncoding = BOMSniffing(bytes)
- // 2. If buffer is 0xEF 0xBB 0xBF, then read three
- // bytes from ioQueue. (Do nothing with those bytes.)
- if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
- buffer = buffer.subarray(3)
+ let slice = 0
+
+ // 2. If BOMEncoding is non-null:
+ if (BOMEncoding !== null) {
+ // 1. Set encoding to BOMEncoding.
+ encoding = BOMEncoding
+
+ // 2. Read three bytes from ioQueue, if BOMEncoding is
+ // UTF-8; otherwise read two bytes.
+ // (Do nothing with those bytes.)
+ slice = BOMEncoding === 'UTF-8' ? 3 : 2
}
- // 3. Process a queue with an instance of UTF-8’s
+ // 3. Process a queue with an instance of encoding’s
// decoder, ioQueue, output, and "replacement".
- const output = textDecoder.decode(buffer)
// 4. Return output.
- return output
+
+ const sliced = bytes.slice(slice)
+ return new TextDecoder(encoding).decode(sliced)
}
/**
- * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
- * @param {Uint8Array} bytes
+ * @see https://encoding.spec.whatwg.org/#bom-sniff
+ * @param {Uint8Array} ioQueue
*/
-function parseJSONFromBytes (bytes) {
- return JSON.parse(utf8DecodeBytes(bytes))
+function BOMSniffing (ioQueue) {
+ // 1. Let BOM be the result of peeking 3 bytes from ioQueue,
+ // converted to a byte sequence.
+ const [a, b, c] = ioQueue
+
+ // 2. For each of the rows in the table below, starting with
+ // the first one and going down, if BOM starts with the
+ // bytes given in the first column, then return the
+ // encoding given in the cell in the second column of that
+ // row. Otherwise, return null.
+ if (a === 0xEF && b === 0xBB && c === 0xBF) {
+ return 'UTF-8'
+ } else if (a === 0xFE && b === 0xFF) {
+ return 'UTF-16BE'
+ } else if (a === 0xFF && b === 0xFE) {
+ return 'UTF-16LE'
+ }
+
+ return null
}
/**
- * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
- * @param {import('./response').Response|import('./request').Request} object
+ * @param {Uint8Array[]} sequences
*/
-function bodyMimeType (object) {
- const { headersList } = object[kState]
- const contentType = headersList.get('content-type')
+function combineByteSequences (sequences) {
+ const size = sequences.reduce((a, b) => {
+ return a + b.byteLength
+ }, 0)
- if (contentType === null) {
- return 'failure'
- }
+ let offset = 0
- return parseMIMEType(contentType)
+ return sequences.reduce((a, b) => {
+ a.set(b, offset)
+ offset += b.byteLength
+ return a
+ }, new Uint8Array(size))
}
module.exports = {
- extractBody,
- safelyExtractBody,
- cloneBody,
- mixinBody
+ staticPropertyDescriptors,
+ readOperation,
+ fireAProgressEvent
}
/***/ }),
-/***/ 21234:
+/***/ 61481:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(28167)
-
-const corsSafeListedMethods = ['GET', 'HEAD', 'POST']
-const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
-
-const nullBodyStatus = [101, 204, 205, 304]
-
-const redirectStatus = [301, 302, 303, 307, 308]
-const redirectStatusSet = new Set(redirectStatus)
+// We include a version number for the Dispatcher API. In case of breaking changes,
+// this version number must be increased to avoid conflicts.
+const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
+const { InvalidArgumentError } = __nccwpck_require__(53959)
+const Agent = __nccwpck_require__(92121)
-// https://fetch.spec.whatwg.org/#block-bad-port
-const badPorts = [
- '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',
- '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',
- '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',
- '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',
- '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',
- '10080'
-]
+if (getGlobalDispatcher() === undefined) {
+ setGlobalDispatcher(new Agent())
+}
-const badPortsSet = new Set(badPorts)
+function setGlobalDispatcher (agent) {
+ if (!agent || typeof agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument agent must implement Agent')
+ }
+ Object.defineProperty(globalThis, globalDispatcher, {
+ value: agent,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
+}
-// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
-const referrerPolicy = [
- '',
- 'no-referrer',
- 'no-referrer-when-downgrade',
- 'same-origin',
- 'origin',
- 'strict-origin',
- 'origin-when-cross-origin',
- 'strict-origin-when-cross-origin',
- 'unsafe-url'
-]
-const referrerPolicySet = new Set(referrerPolicy)
+function getGlobalDispatcher () {
+ return globalThis[globalDispatcher]
+}
-const requestRedirect = ['follow', 'manual', 'error']
+module.exports = {
+ setGlobalDispatcher,
+ getGlobalDispatcher
+}
-const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
-const safeMethodsSet = new Set(safeMethods)
-const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']
+/***/ }),
-const requestCredentials = ['omit', 'same-origin', 'include']
+/***/ 41468:
+/***/ ((module) => {
-const requestCache = [
- 'default',
- 'no-store',
- 'reload',
- 'no-cache',
- 'force-cache',
- 'only-if-cached'
-]
-// https://fetch.spec.whatwg.org/#request-body-header-name
-const requestBodyHeader = [
- 'content-encoding',
- 'content-language',
- 'content-location',
- 'content-type',
- // See https://github.com/nodejs/undici/issues/2021
- // 'Content-Length' is a forbidden header name, which is typically
- // removed in the Headers implementation. However, undici doesn't
- // filter out headers, so we add it here.
- 'content-length'
-]
-// https://fetch.spec.whatwg.org/#enumdef-requestduplex
-const requestDuplex = [
- 'half'
-]
+module.exports = class DecoratorHandler {
+ constructor (handler) {
+ this.handler = handler
+ }
-// http://fetch.spec.whatwg.org/#forbidden-method
-const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']
-const forbiddenMethodsSet = new Set(forbiddenMethods)
+ onConnect (...args) {
+ return this.handler.onConnect(...args)
+ }
-const subresource = [
- 'audio',
- 'audioworklet',
- 'font',
- 'image',
- 'manifest',
- 'paintworklet',
- 'script',
- 'style',
- 'track',
- 'video',
- 'xslt',
- ''
-]
-const subresourceSet = new Set(subresource)
+ onError (...args) {
+ return this.handler.onError(...args)
+ }
-/** @type {globalThis['DOMException']} */
-const DOMException = globalThis.DOMException ?? (() => {
- // DOMException was only made a global in Node v17.0.0,
- // but fetch supports >= v16.8.
- try {
- atob('~')
- } catch (err) {
- return Object.getPrototypeOf(err).constructor
+ onUpgrade (...args) {
+ return this.handler.onUpgrade(...args)
}
-})()
-let channel
+ onHeaders (...args) {
+ return this.handler.onHeaders(...args)
+ }
-/** @type {globalThis['structuredClone']} */
-const structuredClone =
- globalThis.structuredClone ??
- // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js
- // structuredClone was added in v17.0.0, but fetch supports v16.8
- function structuredClone (value, options = undefined) {
- if (arguments.length === 0) {
- throw new TypeError('missing argument')
- }
+ onData (...args) {
+ return this.handler.onData(...args)
+ }
- if (!channel) {
- channel = new MessageChannel()
- }
- channel.port1.unref()
- channel.port2.unref()
- channel.port1.postMessage(value, options?.transfer)
- return receiveMessageOnPort(channel.port2).message
+ onComplete (...args) {
+ return this.handler.onComplete(...args)
}
-module.exports = {
- DOMException,
- structuredClone,
- subresource,
- forbiddenMethods,
- requestBodyHeader,
- referrerPolicy,
- requestRedirect,
- requestMode,
- requestCredentials,
- requestCache,
- redirectStatus,
- corsSafeListedMethods,
- nullBodyStatus,
- safeMethods,
- badPorts,
- requestDuplex,
- subresourceSet,
- badPortsSet,
- redirectStatusSet,
- corsSafeListedMethodsSet,
- safeMethodsSet,
- forbiddenMethodsSet,
- referrerPolicySet
+ onBodySent (...args) {
+ return this.handler.onBodySent(...args)
+ }
}
/***/ }),
-/***/ 37246:
+/***/ 8591:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+const util = __nccwpck_require__(89500)
+const { kBodyUsed } = __nccwpck_require__(68031)
const assert = __nccwpck_require__(42613)
-const { atob } = __nccwpck_require__(20181)
-const { isomorphicDecode } = __nccwpck_require__(72847)
+const { InvalidArgumentError } = __nccwpck_require__(53959)
+const EE = __nccwpck_require__(24434)
-const encoder = new TextEncoder()
+const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
-/**
- * @see https://mimesniff.spec.whatwg.org/#http-token-code-point
- */
-const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/
-const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line
-/**
- * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
- */
-const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line
+const kBody = Symbol('body')
-// https://fetch.spec.whatwg.org/#data-url-processor
-/** @param {URL} dataURL */
-function dataURLProcessor (dataURL) {
- // 1. Assert: dataURL’s scheme is "data".
- assert(dataURL.protocol === 'data:')
+class BodyAsyncIterable {
+ constructor (body) {
+ this[kBody] = body
+ this[kBodyUsed] = false
+ }
- // 2. Let input be the result of running the URL
- // serializer on dataURL with exclude fragment
- // set to true.
- let input = URLSerializer(dataURL, true)
+ async * [Symbol.asyncIterator] () {
+ assert(!this[kBodyUsed], 'disturbed')
+ this[kBodyUsed] = true
+ yield * this[kBody]
+ }
+}
- // 3. Remove the leading "data:" string from input.
- input = input.slice(5)
+class RedirectHandler {
+ constructor (dispatch, maxRedirections, opts, handler) {
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
+ }
- // 4. Let position point at the start of input.
- const position = { position: 0 }
+ util.validateHandler(handler, opts.method, opts.upgrade)
- // 5. Let mimeType be the result of collecting a
- // sequence of code points that are not equal
- // to U+002C (,), given position.
- let mimeType = collectASequenceOfCodePointsFast(
- ',',
- input,
- position
- )
+ this.dispatch = dispatch
+ this.location = null
+ this.abort = null
+ this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy
+ this.maxRedirections = maxRedirections
+ this.handler = handler
+ this.history = []
- // 6. Strip leading and trailing ASCII whitespace
- // from mimeType.
- // Undici implementation note: we need to store the
- // length because if the mimetype has spaces removed,
- // the wrong amount will be sliced from the input in
- // step #9
- const mimeTypeLength = mimeType.length
- mimeType = removeASCIIWhitespace(mimeType, true, true)
+ if (util.isStream(this.opts.body)) {
+ // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
+ // so that it can be dispatched again?
+ // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
+ if (util.bodyLength(this.opts.body) === 0) {
+ this.opts.body
+ .on('data', function () {
+ assert(false)
+ })
+ }
- // 7. If position is past the end of input, then
- // return failure
- if (position.position >= input.length) {
- return 'failure'
+ if (typeof this.opts.body.readableDidRead !== 'boolean') {
+ this.opts.body[kBodyUsed] = false
+ EE.prototype.on.call(this.opts.body, 'data', function () {
+ this[kBodyUsed] = true
+ })
+ }
+ } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {
+ // TODO (fix): We can't access ReadableStream internal state
+ // to determine whether or not it has been disturbed. This is just
+ // a workaround.
+ this.opts.body = new BodyAsyncIterable(this.opts.body)
+ } else if (
+ this.opts.body &&
+ typeof this.opts.body !== 'string' &&
+ !ArrayBuffer.isView(this.opts.body) &&
+ util.isIterable(this.opts.body)
+ ) {
+ // TODO: Should we allow re-using iterable if !this.opts.idempotent
+ // or through some other flag?
+ this.opts.body = new BodyAsyncIterable(this.opts.body)
+ }
}
- // 8. Advance position by 1.
- position.position++
+ onConnect (abort) {
+ this.abort = abort
+ this.handler.onConnect(abort, { history: this.history })
+ }
- // 9. Let encodedBody be the remainder of input.
- const encodedBody = input.slice(mimeTypeLength + 1)
+ onUpgrade (statusCode, headers, socket) {
+ this.handler.onUpgrade(statusCode, headers, socket)
+ }
- // 10. Let body be the percent-decoding of encodedBody.
- let body = stringPercentDecode(encodedBody)
+ onError (error) {
+ this.handler.onError(error)
+ }
- // 11. If mimeType ends with U+003B (;), followed by
- // zero or more U+0020 SPACE, followed by an ASCII
- // case-insensitive match for "base64", then:
- if (/;(\u0020){0,}base64$/i.test(mimeType)) {
- // 1. Let stringBody be the isomorphic decode of body.
- const stringBody = isomorphicDecode(body)
+ onHeaders (statusCode, headers, resume, statusText) {
+ this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)
+ ? null
+ : parseLocation(statusCode, headers)
- // 2. Set body to the forgiving-base64 decode of
- // stringBody.
- body = forgivingBase64(stringBody)
+ if (this.opts.origin) {
+ this.history.push(new URL(this.opts.path, this.opts.origin))
+ }
- // 3. If body is failure, then return failure.
- if (body === 'failure') {
- return 'failure'
+ if (!this.location) {
+ return this.handler.onHeaders(statusCode, headers, resume, statusText)
}
- // 4. Remove the last 6 code points from mimeType.
- mimeType = mimeType.slice(0, -6)
+ const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))
+ const path = search ? `${pathname}${search}` : pathname
- // 5. Remove trailing U+0020 SPACE code points from mimeType,
- // if any.
- mimeType = mimeType.replace(/(\u0020)+$/, '')
+ // Remove headers referring to the original URL.
+ // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.
+ // https://tools.ietf.org/html/rfc7231#section-6.4
+ this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)
+ this.opts.path = path
+ this.opts.origin = origin
+ this.opts.maxRedirections = 0
+ this.opts.query = null
- // 6. Remove the last U+003B (;) code point from mimeType.
- mimeType = mimeType.slice(0, -1)
+ // https://tools.ietf.org/html/rfc7231#section-6.4.4
+ // In case of HTTP 303, always replace method to be either HEAD or GET
+ if (statusCode === 303 && this.opts.method !== 'HEAD') {
+ this.opts.method = 'GET'
+ this.opts.body = null
+ }
}
- // 12. If mimeType starts with U+003B (;), then prepend
- // "text/plain" to mimeType.
- if (mimeType.startsWith(';')) {
- mimeType = 'text/plain' + mimeType
- }
+ onData (chunk) {
+ if (this.location) {
+ /*
+ https://tools.ietf.org/html/rfc7231#section-6.4
- // 13. Let mimeTypeRecord be the result of parsing
- // mimeType.
- let mimeTypeRecord = parseMIMEType(mimeType)
+ TLDR: undici always ignores 3xx response bodies.
- // 14. If mimeTypeRecord is failure, then set
- // mimeTypeRecord to text/plain;charset=US-ASCII.
- if (mimeTypeRecord === 'failure') {
- mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
- }
+ Redirection is used to serve the requested resource from another URL, so it is assumes that
+ no body is generated (and thus can be ignored). Even though generating a body is not prohibited.
- // 15. Return a new data: URL struct whose MIME
- // type is mimeTypeRecord and body is body.
- // https://fetch.spec.whatwg.org/#data-url-struct
- return { mimeType: mimeTypeRecord, body }
-}
+ For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually
+ (which means it's optional and not mandated) contain just an hyperlink to the value of
+ the Location response header, so the body can be ignored safely.
-// https://url.spec.whatwg.org/#concept-url-serializer
-/**
- * @param {URL} url
- * @param {boolean} excludeFragment
- */
-function URLSerializer (url, excludeFragment = false) {
- if (!excludeFragment) {
- return url.href
+ For status 300, which is "Multiple Choices", the spec mentions both generating a Location
+ response header AND a response body with the other possible location to follow.
+ Since the spec explicitily chooses not to specify a format for such body and leave it to
+ servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.
+ */
+ } else {
+ return this.handler.onData(chunk)
+ }
}
- const href = url.href
- const hashLength = url.hash.length
+ onComplete (trailers) {
+ if (this.location) {
+ /*
+ https://tools.ietf.org/html/rfc7231#section-6.4
- return hashLength === 0 ? href : href.substring(0, href.length - hashLength)
-}
+ TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections
+ and neither are useful if present.
-// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
-/**
- * @param {(char: string) => boolean} condition
- * @param {string} input
- * @param {{ position: number }} position
- */
-function collectASequenceOfCodePoints (condition, input, position) {
- // 1. Let result be the empty string.
- let result = ''
+ See comment on onData method above for more detailed informations.
+ */
- // 2. While position doesn’t point past the end of input and the
- // code point at position within input meets the condition condition:
- while (position.position < input.length && condition(input[position.position])) {
- // 1. Append that code point to the end of result.
- result += input[position.position]
+ this.location = null
+ this.abort = null
- // 2. Advance position by 1.
- position.position++
+ this.dispatch(this.opts, this)
+ } else {
+ this.handler.onComplete(trailers)
+ }
}
- // 3. Return result.
- return result
+ onBodySent (chunk) {
+ if (this.handler.onBodySent) {
+ this.handler.onBodySent(chunk)
+ }
+ }
}
-/**
- * A faster collectASequenceOfCodePoints that only works when comparing a single character.
- * @param {string} char
- * @param {string} input
- * @param {{ position: number }} position
- */
-function collectASequenceOfCodePointsFast (char, input, position) {
- const idx = input.indexOf(char, position.position)
- const start = position.position
-
- if (idx === -1) {
- position.position = input.length
- return input.slice(start)
+function parseLocation (statusCode, headers) {
+ if (redirectableStatusCodes.indexOf(statusCode) === -1) {
+ return null
}
- position.position = idx
- return input.slice(start, position.position)
+ for (let i = 0; i < headers.length; i += 2) {
+ if (headers[i].toString().toLowerCase() === 'location') {
+ return headers[i + 1]
+ }
+ }
}
-// https://url.spec.whatwg.org/#string-percent-decode
-/** @param {string} input */
-function stringPercentDecode (input) {
- // 1. Let bytes be the UTF-8 encoding of input.
- const bytes = encoder.encode(input)
+// https://tools.ietf.org/html/rfc7231#section-6.4.4
+function shouldRemoveHeader (header, removeContent, unknownOrigin) {
+ if (header.length === 4) {
+ return util.headerNameToString(header) === 'host'
+ }
+ if (removeContent && util.headerNameToString(header).startsWith('content-')) {
+ return true
+ }
+ if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
+ const name = util.headerNameToString(header)
+ return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'
+ }
+ return false
+}
- // 2. Return the percent-decoding of bytes.
- return percentDecode(bytes)
+// https://tools.ietf.org/html/rfc7231#section-6.4
+function cleanRequestHeaders (headers, removeContent, unknownOrigin) {
+ const ret = []
+ if (Array.isArray(headers)) {
+ for (let i = 0; i < headers.length; i += 2) {
+ if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
+ ret.push(headers[i], headers[i + 1])
+ }
+ }
+ } else if (headers && typeof headers === 'object') {
+ for (const key of Object.keys(headers)) {
+ if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
+ ret.push(key, headers[key])
+ }
+ }
+ } else {
+ assert(headers == null, 'headers must be an object or an array')
+ }
+ return ret
}
-// https://url.spec.whatwg.org/#percent-decode
-/** @param {Uint8Array} input */
-function percentDecode (input) {
- // 1. Let output be an empty byte sequence.
- /** @type {number[]} */
- const output = []
+module.exports = RedirectHandler
- // 2. For each byte byte in input:
- for (let i = 0; i < input.length; i++) {
- const byte = input[i]
- // 1. If byte is not 0x25 (%), then append byte to output.
- if (byte !== 0x25) {
- output.push(byte)
+/***/ }),
- // 2. Otherwise, if byte is 0x25 (%) and the next two bytes
- // after byte in input are not in the ranges
- // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),
- // and 0x61 (a) to 0x66 (f), all inclusive, append byte
- // to output.
- } else if (
- byte === 0x25 &&
- !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))
- ) {
- output.push(0x25)
+/***/ 49569:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 3. Otherwise:
- } else {
- // 1. Let bytePoint be the two bytes after byte in input,
- // decoded, and then interpreted as hexadecimal number.
- const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])
- const bytePoint = Number.parseInt(nextTwoBytes, 16)
+const assert = __nccwpck_require__(42613)
- // 2. Append a byte whose value is bytePoint to output.
- output.push(bytePoint)
+const { kRetryHandlerDefaultRetry } = __nccwpck_require__(68031)
+const { RequestRetryError } = __nccwpck_require__(53959)
+const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(89500)
- // 3. Skip the next two bytes in input.
- i += 2
- }
- }
+function calculateRetryAfterHeader (retryAfter) {
+ const current = Date.now()
+ const diff = new Date(retryAfter).getTime() - current
- // 3. Return output.
- return Uint8Array.from(output)
+ return diff
}
-// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
-/** @param {string} input */
-function parseMIMEType (input) {
- // 1. Remove any leading and trailing HTTP whitespace
- // from input.
- input = removeHTTPWhitespace(input, true, true)
+class RetryHandler {
+ constructor (opts, handlers) {
+ const { retryOptions, ...dispatchOpts } = opts
+ const {
+ // Retry scoped
+ retry: retryFn,
+ maxRetries,
+ maxTimeout,
+ minTimeout,
+ timeoutFactor,
+ // Response scoped
+ methods,
+ errorCodes,
+ retryAfter,
+ statusCodes
+ } = retryOptions ?? {}
- // 2. Let position be a position variable for input,
- // initially pointing at the start of input.
- const position = { position: 0 }
+ this.dispatch = handlers.dispatch
+ this.handler = handlers.handler
+ this.opts = dispatchOpts
+ this.abort = null
+ this.aborted = false
+ this.retryOpts = {
+ retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],
+ retryAfter: retryAfter ?? true,
+ maxTimeout: maxTimeout ?? 30 * 1000, // 30s,
+ timeout: minTimeout ?? 500, // .5s
+ timeoutFactor: timeoutFactor ?? 2,
+ maxRetries: maxRetries ?? 5,
+ // What errors we should retry
+ methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],
+ // Indicates which errors to retry
+ statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
+ // List of errors to retry
+ errorCodes: errorCodes ?? [
+ 'ECONNRESET',
+ 'ECONNREFUSED',
+ 'ENOTFOUND',
+ 'ENETDOWN',
+ 'ENETUNREACH',
+ 'EHOSTDOWN',
+ 'EHOSTUNREACH',
+ 'EPIPE'
+ ]
+ }
- // 3. Let type be the result of collecting a sequence
- // of code points that are not U+002F (/) from
- // input, given position.
- const type = collectASequenceOfCodePointsFast(
- '/',
- input,
- position
- )
+ this.retryCount = 0
+ this.start = 0
+ this.end = null
+ this.etag = null
+ this.resume = null
- // 4. If type is the empty string or does not solely
- // contain HTTP token code points, then return failure.
- // https://mimesniff.spec.whatwg.org/#http-token-code-point
- if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
- return 'failure'
+ // Handle possible onConnect duplication
+ this.handler.onConnect(reason => {
+ this.aborted = true
+ if (this.abort) {
+ this.abort(reason)
+ } else {
+ this.reason = reason
+ }
+ })
}
- // 5. If position is past the end of input, then return
- // failure
- if (position.position > input.length) {
- return 'failure'
+ onRequestSent () {
+ if (this.handler.onRequestSent) {
+ this.handler.onRequestSent()
+ }
}
- // 6. Advance position by 1. (This skips past U+002F (/).)
- position.position++
-
- // 7. Let subtype be the result of collecting a sequence of
- // code points that are not U+003B (;) from input, given
- // position.
- let subtype = collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
-
- // 8. Remove any trailing HTTP whitespace from subtype.
- subtype = removeHTTPWhitespace(subtype, false, true)
-
- // 9. If subtype is the empty string or does not solely
- // contain HTTP token code points, then return failure.
- if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
- return 'failure'
+ onUpgrade (statusCode, headers, socket) {
+ if (this.handler.onUpgrade) {
+ this.handler.onUpgrade(statusCode, headers, socket)
+ }
}
- const typeLowercase = type.toLowerCase()
- const subtypeLowercase = subtype.toLowerCase()
+ onConnect (abort) {
+ if (this.aborted) {
+ abort(this.reason)
+ } else {
+ this.abort = abort
+ }
+ }
- // 10. Let mimeType be a new MIME type record whose type
- // is type, in ASCII lowercase, and subtype is subtype,
- // in ASCII lowercase.
- // https://mimesniff.spec.whatwg.org/#mime-type
- const mimeType = {
- type: typeLowercase,
- subtype: subtypeLowercase,
- /** @type {Map} */
- parameters: new Map(),
- // https://mimesniff.spec.whatwg.org/#mime-type-essence
- essence: `${typeLowercase}/${subtypeLowercase}`
+ onBodySent (chunk) {
+ if (this.handler.onBodySent) return this.handler.onBodySent(chunk)
}
- // 11. While position is not past the end of input:
- while (position.position < input.length) {
- // 1. Advance position by 1. (This skips past U+003B (;).)
- position.position++
+ static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
+ const { statusCode, code, headers } = err
+ const { method, retryOptions } = opts
+ const {
+ maxRetries,
+ timeout,
+ maxTimeout,
+ timeoutFactor,
+ statusCodes,
+ errorCodes,
+ methods
+ } = retryOptions
+ let { counter, currentTimeout } = state
- // 2. Collect a sequence of code points that are HTTP
- // whitespace from input given position.
- collectASequenceOfCodePoints(
- // https://fetch.spec.whatwg.org/#http-whitespace
- char => HTTP_WHITESPACE_REGEX.test(char),
- input,
- position
- )
+ currentTimeout =
+ currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout
- // 3. Let parameterName be the result of collecting a
- // sequence of code points that are not U+003B (;)
- // or U+003D (=) from input, given position.
- let parameterName = collectASequenceOfCodePoints(
- (char) => char !== ';' && char !== '=',
- input,
- position
- )
+ // Any code that is not a Undici's originated and allowed to retry
+ if (
+ code &&
+ code !== 'UND_ERR_REQ_RETRY' &&
+ code !== 'UND_ERR_SOCKET' &&
+ !errorCodes.includes(code)
+ ) {
+ cb(err)
+ return
+ }
- // 4. Set parameterName to parameterName, in ASCII
- // lowercase.
- parameterName = parameterName.toLowerCase()
+ // If a set of method are provided and the current method is not in the list
+ if (Array.isArray(methods) && !methods.includes(method)) {
+ cb(err)
+ return
+ }
- // 5. If position is not past the end of input, then:
- if (position.position < input.length) {
- // 1. If the code point at position within input is
- // U+003B (;), then continue.
- if (input[position.position] === ';') {
- continue
- }
+ // If a set of status code are provided and the current status code is not in the list
+ if (
+ statusCode != null &&
+ Array.isArray(statusCodes) &&
+ !statusCodes.includes(statusCode)
+ ) {
+ cb(err)
+ return
+ }
- // 2. Advance position by 1. (This skips past U+003D (=).)
- position.position++
+ // If we reached the max number of retries
+ if (counter > maxRetries) {
+ cb(err)
+ return
}
- // 6. If position is past the end of input, then break.
- if (position.position > input.length) {
- break
+ let retryAfterHeader = headers != null && headers['retry-after']
+ if (retryAfterHeader) {
+ retryAfterHeader = Number(retryAfterHeader)
+ retryAfterHeader = isNaN(retryAfterHeader)
+ ? calculateRetryAfterHeader(retryAfterHeader)
+ : retryAfterHeader * 1e3 // Retry-After is in seconds
}
- // 7. Let parameterValue be null.
- let parameterValue = null
+ const retryTimeout =
+ retryAfterHeader > 0
+ ? Math.min(retryAfterHeader, maxTimeout)
+ : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout)
- // 8. If the code point at position within input is
- // U+0022 ("), then:
- if (input[position.position] === '"') {
- // 1. Set parameterValue to the result of collecting
- // an HTTP quoted string from input, given position
- // and the extract-value flag.
- parameterValue = collectAnHTTPQuotedString(input, position, true)
+ state.currentTimeout = retryTimeout
- // 2. Collect a sequence of code points that are not
- // U+003B (;) from input, given position.
- collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
+ setTimeout(() => cb(null), retryTimeout)
+ }
- // 9. Otherwise:
- } else {
- // 1. Set parameterValue to the result of collecting
- // a sequence of code points that are not U+003B (;)
- // from input, given position.
- parameterValue = collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const headers = parseHeaders(rawHeaders)
- // 2. Remove any trailing HTTP whitespace from parameterValue.
- parameterValue = removeHTTPWhitespace(parameterValue, false, true)
+ this.retryCount += 1
- // 3. If parameterValue is the empty string, then continue.
- if (parameterValue.length === 0) {
- continue
- }
+ if (statusCode >= 300) {
+ this.abort(
+ new RequestRetryError('Request failed', statusCode, {
+ headers,
+ count: this.retryCount
+ })
+ )
+ return false
}
- // 10. If all of the following are true
- // - parameterName is not the empty string
- // - parameterName solely contains HTTP token code points
- // - parameterValue solely contains HTTP quoted-string token code points
- // - mimeType’s parameters[parameterName] does not exist
- // then set mimeType’s parameters[parameterName] to parameterValue.
- if (
- parameterName.length !== 0 &&
- HTTP_TOKEN_CODEPOINTS.test(parameterName) &&
- (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&
- !mimeType.parameters.has(parameterName)
- ) {
- mimeType.parameters.set(parameterName, parameterValue)
- }
- }
+ // Checkpoint for resume from where we left it
+ if (this.resume != null) {
+ this.resume = null
- // 12. Return mimeType.
- return mimeType
-}
+ if (statusCode !== 206) {
+ return true
+ }
-// https://infra.spec.whatwg.org/#forgiving-base64-decode
-/** @param {string} data */
-function forgivingBase64 (data) {
- // 1. Remove all ASCII whitespace from data.
- data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line
+ const contentRange = parseRangeHeader(headers['content-range'])
+ // If no content range
+ if (!contentRange) {
+ this.abort(
+ new RequestRetryError('Content-Range mismatch', statusCode, {
+ headers,
+ count: this.retryCount
+ })
+ )
+ return false
+ }
- // 2. If data’s code point length divides by 4 leaving
- // no remainder, then:
- if (data.length % 4 === 0) {
- // 1. If data ends with one or two U+003D (=) code points,
- // then remove them from data.
- data = data.replace(/=?=$/, '')
- }
+ // Let's start with a weak etag check
+ if (this.etag != null && this.etag !== headers.etag) {
+ this.abort(
+ new RequestRetryError('ETag mismatch', statusCode, {
+ headers,
+ count: this.retryCount
+ })
+ )
+ return false
+ }
- // 3. If data’s code point length divides by 4 leaving
- // a remainder of 1, then return failure.
- if (data.length % 4 === 1) {
- return 'failure'
- }
+ const { start, size, end = size } = contentRange
- // 4. If data contains a code point that is not one of
- // U+002B (+)
- // U+002F (/)
- // ASCII alphanumeric
- // then return failure.
- if (/[^+/0-9A-Za-z]/.test(data)) {
- return 'failure'
- }
+ assert(this.start === start, 'content-range mismatch')
+ assert(this.end == null || this.end === end, 'content-range mismatch')
- const binary = atob(data)
- const bytes = new Uint8Array(binary.length)
+ this.resume = resume
+ return true
+ }
- for (let byte = 0; byte < binary.length; byte++) {
- bytes[byte] = binary.charCodeAt(byte)
- }
+ if (this.end == null) {
+ if (statusCode === 206) {
+ // First time we receive 206
+ const range = parseRangeHeader(headers['content-range'])
- return bytes
-}
+ if (range == null) {
+ return this.handler.onHeaders(
+ statusCode,
+ rawHeaders,
+ resume,
+ statusMessage
+ )
+ }
-// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
-// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string
-/**
- * @param {string} input
- * @param {{ position: number }} position
- * @param {boolean?} extractValue
- */
-function collectAnHTTPQuotedString (input, position, extractValue) {
- // 1. Let positionStart be position.
- const positionStart = position.position
+ const { start, size, end = size } = range
- // 2. Let value be the empty string.
- let value = ''
+ assert(
+ start != null && Number.isFinite(start) && this.start !== start,
+ 'content-range mismatch'
+ )
+ assert(Number.isFinite(start))
+ assert(
+ end != null && Number.isFinite(end) && this.end !== end,
+ 'invalid content-length'
+ )
- // 3. Assert: the code point at position within input
- // is U+0022 (").
- assert(input[position.position] === '"')
+ this.start = start
+ this.end = end
+ }
- // 4. Advance position by 1.
- position.position++
+ // We make our best to checkpoint the body for further range headers
+ if (this.end == null) {
+ const contentLength = headers['content-length']
+ this.end = contentLength != null ? Number(contentLength) : null
+ }
- // 5. While true:
- while (true) {
- // 1. Append the result of collecting a sequence of code points
- // that are not U+0022 (") or U+005C (\) from input, given
- // position, to value.
- value += collectASequenceOfCodePoints(
- (char) => char !== '"' && char !== '\\',
- input,
- position
- )
+ assert(Number.isFinite(this.start))
+ assert(
+ this.end == null || Number.isFinite(this.end),
+ 'invalid content-length'
+ )
- // 2. If position is past the end of input, then break.
- if (position.position >= input.length) {
- break
+ this.resume = resume
+ this.etag = headers.etag != null ? headers.etag : null
+
+ return this.handler.onHeaders(
+ statusCode,
+ rawHeaders,
+ resume,
+ statusMessage
+ )
}
- // 3. Let quoteOrBackslash be the code point at position within
- // input.
- const quoteOrBackslash = input[position.position]
+ const err = new RequestRetryError('Request failed', statusCode, {
+ headers,
+ count: this.retryCount
+ })
- // 4. Advance position by 1.
- position.position++
+ this.abort(err)
- // 5. If quoteOrBackslash is U+005C (\), then:
- if (quoteOrBackslash === '\\') {
- // 1. If position is past the end of input, then append
- // U+005C (\) to value and break.
- if (position.position >= input.length) {
- value += '\\'
- break
- }
+ return false
+ }
- // 2. Append the code point at position within input to value.
- value += input[position.position]
+ onData (chunk) {
+ this.start += chunk.length
+
+ return this.handler.onData(chunk)
+ }
+
+ onComplete (rawTrailers) {
+ this.retryCount = 0
+ return this.handler.onComplete(rawTrailers)
+ }
+
+ onError (err) {
+ if (this.aborted || isDisturbed(this.opts.body)) {
+ return this.handler.onError(err)
+ }
- // 3. Advance position by 1.
- position.position++
+ this.retryOpts.retry(
+ err,
+ {
+ state: { counter: this.retryCount++, currentTimeout: this.retryAfter },
+ opts: { retryOptions: this.retryOpts, ...this.opts }
+ },
+ onRetry.bind(this)
+ )
- // 6. Otherwise:
- } else {
- // 1. Assert: quoteOrBackslash is U+0022 (").
- assert(quoteOrBackslash === '"')
+ function onRetry (err) {
+ if (err != null || this.aborted || isDisturbed(this.opts.body)) {
+ return this.handler.onError(err)
+ }
- // 2. Break.
- break
+ if (this.start !== 0) {
+ this.opts = {
+ ...this.opts,
+ headers: {
+ ...this.opts.headers,
+ range: `bytes=${this.start}-${this.end ?? ''}`
+ }
+ }
+ }
+
+ try {
+ this.dispatch(this.opts, this)
+ } catch (err) {
+ this.handler.onError(err)
+ }
}
}
+}
- // 6. If the extract-value flag is set, then return value.
- if (extractValue) {
- return value
- }
+module.exports = RetryHandler
- // 7. Return the code points from positionStart to position,
- // inclusive, within input.
- return input.slice(positionStart, position.position)
-}
-/**
- * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
- */
-function serializeAMimeType (mimeType) {
- assert(mimeType !== 'failure')
- const { parameters, essence } = mimeType
+/***/ }),
- // 1. Let serialization be the concatenation of mimeType’s
- // type, U+002F (/), and mimeType’s subtype.
- let serialization = essence
+/***/ 99299:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. For each name → value of mimeType’s parameters:
- for (let [name, value] of parameters.entries()) {
- // 1. Append U+003B (;) to serialization.
- serialization += ';'
- // 2. Append name to serialization.
- serialization += name
- // 3. Append U+003D (=) to serialization.
- serialization += '='
+const RedirectHandler = __nccwpck_require__(8591)
- // 4. If value does not solely contain HTTP token code
- // points or value is the empty string, then:
- if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
- // 1. Precede each occurence of U+0022 (") or
- // U+005C (\) in value with U+005C (\).
- value = value.replace(/(\\|")/g, '\\$1')
+function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {
+ return (dispatch) => {
+ return function Intercept (opts, handler) {
+ const { maxRedirections = defaultMaxRedirections } = opts
- // 2. Prepend U+0022 (") to value.
- value = '"' + value
+ if (!maxRedirections) {
+ return dispatch(opts, handler)
+ }
- // 3. Append U+0022 (") to value.
- value += '"'
+ const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
+ opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
+ return dispatch(opts, redirectHandler)
}
-
- // 5. Append value to serialization.
- serialization += value
}
-
- // 3. Return serialization.
- return serialization
}
-/**
- * @see https://fetch.spec.whatwg.org/#http-whitespace
- * @param {string} char
- */
-function isHTTPWhiteSpace (char) {
- return char === '\r' || char === '\n' || char === '\t' || char === ' '
-}
+module.exports = createRedirectInterceptor
-/**
- * @see https://fetch.spec.whatwg.org/#http-whitespace
- * @param {string} str
- */
-function removeHTTPWhitespace (str, leading = true, trailing = true) {
- let lead = 0
- let trail = str.length - 1
- if (leading) {
- for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);
- }
+/***/ }),
- if (trailing) {
- for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);
- }
+/***/ 40748:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return str.slice(lead, trail + 1)
-}
-/**
- * @see https://infra.spec.whatwg.org/#ascii-whitespace
- * @param {string} char
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
+const utils_1 = __nccwpck_require__(34608);
+// C headers
+var ERROR;
+(function (ERROR) {
+ ERROR[ERROR["OK"] = 0] = "OK";
+ ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL";
+ ERROR[ERROR["STRICT"] = 2] = "STRICT";
+ ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED";
+ ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
+ ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
+ ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD";
+ ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL";
+ ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
+ ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION";
+ ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
+ ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
+ ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
+ ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS";
+ ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
+ ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
+ ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
+ ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
+ ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
+ ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
+ ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
+ ERROR[ERROR["PAUSED"] = 21] = "PAUSED";
+ ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
+ ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
+ ERROR[ERROR["USER"] = 24] = "USER";
+})(ERROR = exports.ERROR || (exports.ERROR = {}));
+var TYPE;
+(function (TYPE) {
+ TYPE[TYPE["BOTH"] = 0] = "BOTH";
+ TYPE[TYPE["REQUEST"] = 1] = "REQUEST";
+ TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE";
+})(TYPE = exports.TYPE || (exports.TYPE = {}));
+var FLAGS;
+(function (FLAGS) {
+ FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
+ FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
+ FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
+ FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED";
+ FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE";
+ FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
+ FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY";
+ FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING";
+ // 1 << 8 is unused
+ FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
+})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
+var LENIENT_FLAGS;
+(function (LENIENT_FLAGS) {
+ LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS";
+ LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
+ LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
+})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
+var METHODS;
+(function (METHODS) {
+ METHODS[METHODS["DELETE"] = 0] = "DELETE";
+ METHODS[METHODS["GET"] = 1] = "GET";
+ METHODS[METHODS["HEAD"] = 2] = "HEAD";
+ METHODS[METHODS["POST"] = 3] = "POST";
+ METHODS[METHODS["PUT"] = 4] = "PUT";
+ /* pathological */
+ METHODS[METHODS["CONNECT"] = 5] = "CONNECT";
+ METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS";
+ METHODS[METHODS["TRACE"] = 7] = "TRACE";
+ /* WebDAV */
+ METHODS[METHODS["COPY"] = 8] = "COPY";
+ METHODS[METHODS["LOCK"] = 9] = "LOCK";
+ METHODS[METHODS["MKCOL"] = 10] = "MKCOL";
+ METHODS[METHODS["MOVE"] = 11] = "MOVE";
+ METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND";
+ METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH";
+ METHODS[METHODS["SEARCH"] = 14] = "SEARCH";
+ METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK";
+ METHODS[METHODS["BIND"] = 16] = "BIND";
+ METHODS[METHODS["REBIND"] = 17] = "REBIND";
+ METHODS[METHODS["UNBIND"] = 18] = "UNBIND";
+ METHODS[METHODS["ACL"] = 19] = "ACL";
+ /* subversion */
+ METHODS[METHODS["REPORT"] = 20] = "REPORT";
+ METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY";
+ METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT";
+ METHODS[METHODS["MERGE"] = 23] = "MERGE";
+ /* upnp */
+ METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH";
+ METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY";
+ METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE";
+ METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
+ /* RFC-5789 */
+ METHODS[METHODS["PATCH"] = 28] = "PATCH";
+ METHODS[METHODS["PURGE"] = 29] = "PURGE";
+ /* CalDAV */
+ METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR";
+ /* RFC-2068, section 19.6.1.2 */
+ METHODS[METHODS["LINK"] = 31] = "LINK";
+ METHODS[METHODS["UNLINK"] = 32] = "UNLINK";
+ /* icecast */
+ METHODS[METHODS["SOURCE"] = 33] = "SOURCE";
+ /* RFC-7540, section 11.6 */
+ METHODS[METHODS["PRI"] = 34] = "PRI";
+ /* RFC-2326 RTSP */
+ METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE";
+ METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE";
+ METHODS[METHODS["SETUP"] = 37] = "SETUP";
+ METHODS[METHODS["PLAY"] = 38] = "PLAY";
+ METHODS[METHODS["PAUSE"] = 39] = "PAUSE";
+ METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN";
+ METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER";
+ METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER";
+ METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT";
+ METHODS[METHODS["RECORD"] = 44] = "RECORD";
+ /* RAOP */
+ METHODS[METHODS["FLUSH"] = 45] = "FLUSH";
+})(METHODS = exports.METHODS || (exports.METHODS = {}));
+exports.METHODS_HTTP = [
+ METHODS.DELETE,
+ METHODS.GET,
+ METHODS.HEAD,
+ METHODS.POST,
+ METHODS.PUT,
+ METHODS.CONNECT,
+ METHODS.OPTIONS,
+ METHODS.TRACE,
+ METHODS.COPY,
+ METHODS.LOCK,
+ METHODS.MKCOL,
+ METHODS.MOVE,
+ METHODS.PROPFIND,
+ METHODS.PROPPATCH,
+ METHODS.SEARCH,
+ METHODS.UNLOCK,
+ METHODS.BIND,
+ METHODS.REBIND,
+ METHODS.UNBIND,
+ METHODS.ACL,
+ METHODS.REPORT,
+ METHODS.MKACTIVITY,
+ METHODS.CHECKOUT,
+ METHODS.MERGE,
+ METHODS['M-SEARCH'],
+ METHODS.NOTIFY,
+ METHODS.SUBSCRIBE,
+ METHODS.UNSUBSCRIBE,
+ METHODS.PATCH,
+ METHODS.PURGE,
+ METHODS.MKCALENDAR,
+ METHODS.LINK,
+ METHODS.UNLINK,
+ METHODS.PRI,
+ // TODO(indutny): should we allow it with HTTP?
+ METHODS.SOURCE,
+];
+exports.METHODS_ICE = [
+ METHODS.SOURCE,
+];
+exports.METHODS_RTSP = [
+ METHODS.OPTIONS,
+ METHODS.DESCRIBE,
+ METHODS.ANNOUNCE,
+ METHODS.SETUP,
+ METHODS.PLAY,
+ METHODS.PAUSE,
+ METHODS.TEARDOWN,
+ METHODS.GET_PARAMETER,
+ METHODS.SET_PARAMETER,
+ METHODS.REDIRECT,
+ METHODS.RECORD,
+ METHODS.FLUSH,
+ // For AirPlay
+ METHODS.GET,
+ METHODS.POST,
+];
+exports.METHOD_MAP = utils_1.enumToMap(METHODS);
+exports.H_METHOD_MAP = {};
+Object.keys(exports.METHOD_MAP).forEach((key) => {
+ if (/^H/.test(key)) {
+ exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
+ }
+});
+var FINISH;
+(function (FINISH) {
+ FINISH[FINISH["SAFE"] = 0] = "SAFE";
+ FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
+ FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE";
+})(FINISH = exports.FINISH || (exports.FINISH = {}));
+exports.ALPHA = [];
+for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
+ // Upper case
+ exports.ALPHA.push(String.fromCharCode(i));
+ // Lower case
+ exports.ALPHA.push(String.fromCharCode(i + 0x20));
+}
+exports.NUM_MAP = {
+ 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
+ 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
+};
+exports.HEX_MAP = {
+ 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
+ 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
+ A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,
+ a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,
+};
+exports.NUM = [
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+];
+exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
+exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')'];
+exports.USERINFO_CHARS = exports.ALPHANUM
+ .concat(exports.MARK)
+ .concat(['%', ';', ':', '&', '=', '+', '$', ',']);
+// TODO(indutny): use RFC
+exports.STRICT_URL_CHAR = [
+ '!', '"', '$', '%', '&', '\'',
+ '(', ')', '*', '+', ',', '-', '.', '/',
+ ':', ';', '<', '=', '>',
+ '@', '[', '\\', ']', '^', '_',
+ '`',
+ '{', '|', '}', '~',
+].concat(exports.ALPHANUM);
+exports.URL_CHAR = exports.STRICT_URL_CHAR
+ .concat(['\t', '\f']);
+// All characters with 0x80 bit set to 1
+for (let i = 0x80; i <= 0xff; i++) {
+ exports.URL_CHAR.push(i);
+}
+exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);
+/* Tokens as defined by rfc 2616. Also lowercases them.
+ * token = 1*
+ * separators = "(" | ")" | "<" | ">" | "@"
+ * | "," | ";" | ":" | "\" | <">
+ * | "/" | "[" | "]" | "?" | "="
+ * | "{" | "}" | SP | HT
*/
-function isASCIIWhitespace (char) {
- return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' '
+exports.STRICT_TOKEN = [
+ '!', '#', '$', '%', '&', '\'',
+ '*', '+', '-', '.',
+ '^', '_', '`',
+ '|', '~',
+].concat(exports.ALPHANUM);
+exports.TOKEN = exports.STRICT_TOKEN.concat([' ']);
+/*
+ * Verify that a char is a valid visible (printable) US-ASCII
+ * character or %x80-FF
+ */
+exports.HEADER_CHARS = ['\t'];
+for (let i = 32; i <= 255; i++) {
+ if (i !== 127) {
+ exports.HEADER_CHARS.push(i);
+ }
}
+// ',' = \x44
+exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
+exports.MAJOR = exports.NUM_MAP;
+exports.MINOR = exports.MAJOR;
+var HEADER_STATE;
+(function (HEADER_STATE) {
+ HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL";
+ HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION";
+ HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
+ HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
+ HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
+ HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
+})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
+exports.SPECIAL_HEADERS = {
+ 'connection': HEADER_STATE.CONNECTION,
+ 'content-length': HEADER_STATE.CONTENT_LENGTH,
+ 'proxy-connection': HEADER_STATE.CONNECTION,
+ 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,
+ 'upgrade': HEADER_STATE.UPGRADE,
+};
+//# sourceMappingURL=constants.js.map
-/**
- * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
- */
-function removeASCIIWhitespace (str, leading = true, trailing = true) {
- let lead = 0
- let trail = str.length - 1
+/***/ }),
- if (leading) {
- for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);
- }
+/***/ 63922:
+/***/ ((module) => {
- if (trailing) {
- for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);
- }
+module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxs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NgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4ABgQGCAYMBhAGFAYYBhwGIAYkBigGLAYwBjQGOAY8BkAGRAZIBkwGUAZUBlgGXAZgBmQ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MDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAC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tBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2AhAgAEEgNgIMQQAhEAybAQsgAEEANgIAIBBBAWohAUEkIRALIAAgEDoAKSAAKAIEIRAgAEEANgIEIAAgECABEKuAgIAAIhANVCABIQEMPgsgAEEANgIAC0EAIRAgAEEANgIcIAAgBDYCFCAAQfGbgIAANgIQIABBBjYCD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AAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAABAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAIAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8='
- return str.slice(lead, trail + 1)
-}
-module.exports = {
- dataURLProcessor,
- URLSerializer,
- collectASequenceOfCodePoints,
- collectASequenceOfCodePointsFast,
- stringPercentDecode,
- parseMIMEType,
- collectAnHTTPQuotedString,
- serializeAMimeType
-}
+/***/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ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQIDBAUGBwgJCgsMD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DCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB7AELIAFBAWohAUEIIRAMyAMLIAFBAWoiASACRw0AC0EVIRAM3wMLQRUhEAzeAwsDQAJAIAEtAABB8LmAgABqLQAAIhBBAkYNACAQQX9qDgTeAewB4AHrAewBCyABQQFqIgEgAkcNAAtBGCEQDN0DCwJAIAEiASACRg0AIABBi4CAgAA2AgggACABNgIEIAEhAUEHIRAMxAMLQRkhEAzcAwsgAUEBaiEBDAILAkAgASIUIAJHDQBBGiEQDNsDCyAUIQECQCAULQAAQXNqDhTdAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAu4C7gLuAgDuAgtBACEQIABBADYCHCAAQa+LgIAANgIQIABBAjYCDCAAIBRBAWo2AhQM2gMLAkAgAS0AACIQQTtGDQAgEEENRw3oASABQQFqIQEM5QILIAFBAWohAQtBIiEQDL8DCwJAIAEiECACRw0AQRwhEA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A2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAylAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAg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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='
-/***/ 17005:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ }),
+/***/ 34608:
+/***/ ((__unused_webpack_module, exports) => {
-const { Blob, File: NativeFile } = __nccwpck_require__(20181)
-const { types } = __nccwpck_require__(39023)
-const { kState } = __nccwpck_require__(63730)
-const { isBlobLike } = __nccwpck_require__(72847)
-const { webidl } = __nccwpck_require__(94354)
-const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
-const { kEnumerableProperty } = __nccwpck_require__(89500)
-const encoder = new TextEncoder()
-class File extends Blob {
- constructor (fileBits, fileName, options = {}) {
- // The File constructor is invoked with two or three parameters, depending
- // on whether the optional dictionary parameter is used. When the File()
- // constructor is invoked, user agents must run the following steps:
- webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.enumToMap = void 0;
+function enumToMap(obj) {
+ const res = {};
+ Object.keys(obj).forEach((key) => {
+ const value = obj[key];
+ if (typeof value === 'number') {
+ res[key] = value;
+ }
+ });
+ return res;
+}
+exports.enumToMap = enumToMap;
+//# sourceMappingURL=utils.js.map
- fileBits = webidl.converters['sequence'](fileBits)
- fileName = webidl.converters.USVString(fileName)
- options = webidl.converters.FilePropertyBag(options)
+/***/ }),
- // 1. Let bytes be the result of processing blob parts given fileBits and
- // options.
- // Note: Blob handles this for us
+/***/ 77017:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Let n be the fileName argument to the constructor.
- const n = fileName
- // 3. Process FilePropertyBag dictionary argument by running the following
- // substeps:
- // 1. If the type member is provided and is not the empty string, let t
- // be set to the type dictionary member. If t contains any characters
- // outside the range U+0020 to U+007E, then set t to the empty string
- // and return from these substeps.
- // 2. Convert every character in t to ASCII lowercase.
- let t = options.type
- let d
+const { kClients } = __nccwpck_require__(68031)
+const Agent = __nccwpck_require__(92121)
+const {
+ kAgent,
+ kMockAgentSet,
+ kMockAgentGet,
+ kDispatches,
+ kIsMockActive,
+ kNetConnect,
+ kGetNetConnect,
+ kOptions,
+ kFactory
+} = __nccwpck_require__(52305)
+const MockClient = __nccwpck_require__(72361)
+const MockPool = __nccwpck_require__(36480)
+const { matchValue, buildMockOptions } = __nccwpck_require__(73193)
+const { InvalidArgumentError, UndiciError } = __nccwpck_require__(53959)
+const Dispatcher = __nccwpck_require__(20303)
+const Pluralizer = __nccwpck_require__(35773)
+const PendingInterceptorsFormatter = __nccwpck_require__(85738)
- // eslint-disable-next-line no-labels
- substep: {
- if (t) {
- t = parseMIMEType(t)
+class FakeWeakRef {
+ constructor (value) {
+ this.value = value
+ }
- if (t === 'failure') {
- t = ''
- // eslint-disable-next-line no-labels
- break substep
- }
+ deref () {
+ return this.value
+ }
+}
- t = serializeAMimeType(t).toLowerCase()
- }
+class MockAgent extends Dispatcher {
+ constructor (opts) {
+ super(opts)
- // 3. If the lastModified member is provided, let d be set to the
- // lastModified dictionary member. If it is not provided, set d to the
- // current date and time represented as the number of milliseconds since
- // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
- d = options.lastModified
+ this[kNetConnect] = true
+ this[kIsMockActive] = true
+
+ // Instantiate Agent and encapsulate
+ if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
}
+ const agent = opts && opts.agent ? opts.agent : new Agent(opts)
+ this[kAgent] = agent
- // 4. Return a new File object F such that:
- // F refers to the bytes byte sequence.
- // F.size is set to the number of total bytes in bytes.
- // F.name is set to n.
- // F.type is set to t.
- // F.lastModified is set to d.
+ this[kClients] = agent[kClients]
+ this[kOptions] = buildMockOptions(opts)
+ }
- super(processBlobParts(fileBits, options), { type: t })
- this[kState] = {
- name: n,
- lastModified: d,
- type: t
+ get (origin) {
+ let dispatcher = this[kMockAgentGet](origin)
+
+ if (!dispatcher) {
+ dispatcher = this[kFactory](origin)
+ this[kMockAgentSet](origin, dispatcher)
}
+ return dispatcher
}
- get name () {
- webidl.brandCheck(this, File)
-
- return this[kState].name
+ dispatch (opts, handler) {
+ // Call MockAgent.get to perform additional setup before dispatching as normal
+ this.get(opts.origin)
+ return this[kAgent].dispatch(opts, handler)
}
- get lastModified () {
- webidl.brandCheck(this, File)
+ async close () {
+ await this[kAgent].close()
+ this[kClients].clear()
+ }
- return this[kState].lastModified
+ deactivate () {
+ this[kIsMockActive] = false
}
- get type () {
- webidl.brandCheck(this, File)
+ activate () {
+ this[kIsMockActive] = true
+ }
- return this[kState].type
+ enableNetConnect (matcher) {
+ if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {
+ if (Array.isArray(this[kNetConnect])) {
+ this[kNetConnect].push(matcher)
+ } else {
+ this[kNetConnect] = [matcher]
+ }
+ } else if (typeof matcher === 'undefined') {
+ this[kNetConnect] = true
+ } else {
+ throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')
+ }
}
-}
-class FileLike {
- constructor (blobLike, fileName, options = {}) {
- // TODO: argument idl type check
+ disableNetConnect () {
+ this[kNetConnect] = false
+ }
- // The File constructor is invoked with two or three parameters, depending
- // on whether the optional dictionary parameter is used. When the File()
- // constructor is invoked, user agents must run the following steps:
+ // This is required to bypass issues caused by using global symbols - see:
+ // https://github.com/nodejs/undici/issues/1447
+ get isMockActive () {
+ return this[kIsMockActive]
+ }
- // 1. Let bytes be the result of processing blob parts given fileBits and
- // options.
+ [kMockAgentSet] (origin, dispatcher) {
+ this[kClients].set(origin, new FakeWeakRef(dispatcher))
+ }
- // 2. Let n be the fileName argument to the constructor.
- const n = fileName
+ [kFactory] (origin) {
+ const mockOptions = Object.assign({ agent: this }, this[kOptions])
+ return this[kOptions] && this[kOptions].connections === 1
+ ? new MockClient(origin, mockOptions)
+ : new MockPool(origin, mockOptions)
+ }
- // 3. Process FilePropertyBag dictionary argument by running the following
- // substeps:
+ [kMockAgentGet] (origin) {
+ // First check if we can immediately find it
+ const ref = this[kClients].get(origin)
+ if (ref) {
+ return ref.deref()
+ }
- // 1. If the type member is provided and is not the empty string, let t
- // be set to the type dictionary member. If t contains any characters
- // outside the range U+0020 to U+007E, then set t to the empty string
- // and return from these substeps.
- // TODO
- const t = options.type
+ // If the origin is not a string create a dummy parent pool and return to user
+ if (typeof origin !== 'string') {
+ const dispatcher = this[kFactory]('http://localhost:9999')
+ this[kMockAgentSet](origin, dispatcher)
+ return dispatcher
+ }
- // 2. Convert every character in t to ASCII lowercase.
- // TODO
+ // If we match, create a pool and assign the same dispatches
+ for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {
+ const nonExplicitDispatcher = nonExplicitRef.deref()
+ if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
+ const dispatcher = this[kFactory](origin)
+ this[kMockAgentSet](origin, dispatcher)
+ dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
+ return dispatcher
+ }
+ }
+ }
- // 3. If the lastModified member is provided, let d be set to the
- // lastModified dictionary member. If it is not provided, set d to the
- // current date and time represented as the number of milliseconds since
- // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
- const d = options.lastModified ?? Date.now()
+ [kGetNetConnect] () {
+ return this[kNetConnect]
+ }
- // 4. Return a new File object F such that:
- // F refers to the bytes byte sequence.
- // F.size is set to the number of total bytes in bytes.
- // F.name is set to n.
- // F.type is set to t.
- // F.lastModified is set to d.
+ pendingInterceptors () {
+ const mockAgentClients = this[kClients]
- this[kState] = {
- blobLike,
- name: n,
- type: t,
- lastModified: d
- }
+ return Array.from(mockAgentClients.entries())
+ .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin })))
+ .filter(({ pending }) => pending)
}
- stream (...args) {
- webidl.brandCheck(this, FileLike)
+ assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
+ const pending = this.pendingInterceptors()
- return this[kState].blobLike.stream(...args)
- }
+ if (pending.length === 0) {
+ return
+ }
- arrayBuffer (...args) {
- webidl.brandCheck(this, FileLike)
+ const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)
- return this[kState].blobLike.arrayBuffer(...args)
+ throw new UndiciError(`
+${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
+
+${pendingInterceptorsFormatter.format(pending)}
+`.trim())
}
+}
- slice (...args) {
- webidl.brandCheck(this, FileLike)
+module.exports = MockAgent
- return this[kState].blobLike.slice(...args)
- }
- text (...args) {
- webidl.brandCheck(this, FileLike)
+/***/ }),
- return this[kState].blobLike.text(...args)
- }
+/***/ 72361:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- get size () {
- webidl.brandCheck(this, FileLike)
- return this[kState].blobLike.size
- }
- get type () {
- webidl.brandCheck(this, FileLike)
+const { promisify } = __nccwpck_require__(39023)
+const Client = __nccwpck_require__(45513)
+const { buildMockDispatch } = __nccwpck_require__(73193)
+const {
+ kDispatches,
+ kMockAgent,
+ kClose,
+ kOriginalClose,
+ kOrigin,
+ kOriginalDispatch,
+ kConnected
+} = __nccwpck_require__(52305)
+const { MockInterceptor } = __nccwpck_require__(5843)
+const Symbols = __nccwpck_require__(68031)
+const { InvalidArgumentError } = __nccwpck_require__(53959)
- return this[kState].blobLike.type
- }
+/**
+ * MockClient provides an API that extends the Client to influence the mockDispatches.
+ */
+class MockClient extends Client {
+ constructor (origin, opts) {
+ super(origin, opts)
- get name () {
- webidl.brandCheck(this, FileLike)
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+ }
- return this[kState].name
+ this[kMockAgent] = opts.agent
+ this[kOrigin] = origin
+ this[kDispatches] = []
+ this[kConnected] = 1
+ this[kOriginalDispatch] = this.dispatch
+ this[kOriginalClose] = this.close.bind(this)
+
+ this.dispatch = buildMockDispatch.call(this)
+ this.close = this[kClose]
}
- get lastModified () {
- webidl.brandCheck(this, FileLike)
+ get [Symbols.kConnected] () {
+ return this[kConnected]
+ }
- return this[kState].lastModified
+ /**
+ * Sets up the base interceptor for mocking replies from undici.
+ */
+ intercept (opts) {
+ return new MockInterceptor(opts, this[kDispatches])
}
- get [Symbol.toStringTag] () {
- return 'File'
+ async [kClose] () {
+ await promisify(this[kOriginalClose])()
+ this[kConnected] = 0
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
}
}
-Object.defineProperties(File.prototype, {
- [Symbol.toStringTag]: {
- value: 'File',
- configurable: true
- },
- name: kEnumerableProperty,
- lastModified: kEnumerableProperty
-})
+module.exports = MockClient
-webidl.converters.Blob = webidl.interfaceConverter(Blob)
-webidl.converters.BlobPart = function (V, opts) {
- if (webidl.util.Type(V) === 'Object') {
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
- }
+/***/ }),
- if (
- ArrayBuffer.isView(V) ||
- types.isAnyArrayBuffer(V)
- ) {
- return webidl.converters.BufferSource(V, opts)
- }
+/***/ 12673:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { UndiciError } = __nccwpck_require__(53959)
+
+class MockNotMatchedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, MockNotMatchedError)
+ this.name = 'MockNotMatchedError'
+ this.message = message || 'The request does not match any registered mock dispatches'
+ this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
}
+}
- return webidl.converters.USVString(V, opts)
+module.exports = {
+ MockNotMatchedError
}
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.BlobPart
-)
-// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag
-webidl.converters.FilePropertyBag = webidl.dictionaryConverter([
- {
- key: 'lastModified',
- converter: webidl.converters['long long'],
- get defaultValue () {
- return Date.now()
- }
- },
- {
- key: 'type',
- converter: webidl.converters.DOMString,
- defaultValue: ''
- },
- {
- key: 'endings',
- converter: (value) => {
- value = webidl.converters.DOMString(value)
- value = value.toLowerCase()
+/***/ }),
- if (value !== 'native') {
- value = 'transparent'
- }
+/***/ 5843:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return value
- },
- defaultValue: 'transparent'
- }
-])
+
+
+const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(73193)
+const {
+ kDispatches,
+ kDispatchKey,
+ kDefaultHeaders,
+ kDefaultTrailers,
+ kContentLength,
+ kMockDispatch
+} = __nccwpck_require__(52305)
+const { InvalidArgumentError } = __nccwpck_require__(53959)
+const { buildURL } = __nccwpck_require__(89500)
/**
- * @see https://www.w3.org/TR/FileAPI/#process-blob-parts
- * @param {(NodeJS.TypedArray|Blob|string)[]} parts
- * @param {{ type: string, endings: string }} options
+ * Defines the scope API for an interceptor reply
*/
-function processBlobParts (parts, options) {
- // 1. Let bytes be an empty sequence of bytes.
- /** @type {NodeJS.TypedArray[]} */
- const bytes = []
+class MockScope {
+ constructor (mockDispatch) {
+ this[kMockDispatch] = mockDispatch
+ }
- // 2. For each element in parts:
- for (const element of parts) {
- // 1. If element is a USVString, run the following substeps:
- if (typeof element === 'string') {
- // 1. Let s be element.
- let s = element
+ /**
+ * Delay a reply by a set amount in ms.
+ */
+ delay (waitInMs) {
+ if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {
+ throw new InvalidArgumentError('waitInMs must be a valid integer > 0')
+ }
- // 2. If the endings member of options is "native", set s
- // to the result of converting line endings to native
- // of element.
- if (options.endings === 'native') {
- s = convertLineEndingsNative(s)
- }
+ this[kMockDispatch].delay = waitInMs
+ return this
+ }
- // 3. Append the result of UTF-8 encoding s to bytes.
- bytes.push(encoder.encode(s))
- } else if (
- types.isAnyArrayBuffer(element) ||
- types.isTypedArray(element)
- ) {
- // 2. If element is a BufferSource, get a copy of the
- // bytes held by the buffer source, and append those
- // bytes to bytes.
- if (!element.buffer) { // ArrayBuffer
- bytes.push(new Uint8Array(element))
- } else {
- bytes.push(
- new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
- )
- }
- } else if (isBlobLike(element)) {
- // 3. If element is a Blob, append the bytes it represents
- // to bytes.
- bytes.push(element)
- }
+ /**
+ * For a defined reply, never mark as consumed.
+ */
+ persist () {
+ this[kMockDispatch].persist = true
+ return this
}
- // 3. Return bytes.
- return bytes
+ /**
+ * Allow one to define a reply for a set amount of matching requests.
+ */
+ times (repeatTimes) {
+ if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
+ throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')
+ }
+
+ this[kMockDispatch].times = repeatTimes
+ return this
+ }
}
/**
- * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native
- * @param {string} s
+ * Defines an interceptor for a Mock
*/
-function convertLineEndingsNative (s) {
- // 1. Let native line ending be be the code point U+000A LF.
- let nativeLineEnding = '\n'
+class MockInterceptor {
+ constructor (opts, mockDispatches) {
+ if (typeof opts !== 'object') {
+ throw new InvalidArgumentError('opts must be an object')
+ }
+ if (typeof opts.path === 'undefined') {
+ throw new InvalidArgumentError('opts.path must be defined')
+ }
+ if (typeof opts.method === 'undefined') {
+ opts.method = 'GET'
+ }
+ // See https://github.com/nodejs/undici/issues/1245
+ // As per RFC 3986, clients are not supposed to send URI
+ // fragments to servers when they retrieve a document,
+ if (typeof opts.path === 'string') {
+ if (opts.query) {
+ opts.path = buildURL(opts.path, opts.query)
+ } else {
+ // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811
+ const parsedURL = new URL(opts.path, 'data://')
+ opts.path = parsedURL.pathname + parsedURL.search
+ }
+ }
+ if (typeof opts.method === 'string') {
+ opts.method = opts.method.toUpperCase()
+ }
- // 2. If the underlying platform’s conventions are to
- // represent newlines as a carriage return and line feed
- // sequence, set native line ending to the code point
- // U+000D CR followed by the code point U+000A LF.
- if (process.platform === 'win32') {
- nativeLineEnding = '\r\n'
+ this[kDispatchKey] = buildKey(opts)
+ this[kDispatches] = mockDispatches
+ this[kDefaultHeaders] = {}
+ this[kDefaultTrailers] = {}
+ this[kContentLength] = false
}
- return s.replace(/\r?\n/g, nativeLineEnding)
-}
-
-// If this function is moved to ./util.js, some tools (such as
-// rollup) will warn about circular dependencies. See:
-// https://github.com/nodejs/undici/issues/1629
-function isFileLike (object) {
- return (
- (NativeFile && object instanceof NativeFile) ||
- object instanceof File || (
- object &&
- (typeof object.stream === 'function' ||
- typeof object.arrayBuffer === 'function') &&
- object[Symbol.toStringTag] === 'File'
- )
- )
-}
+ createMockScopeDispatchData (statusCode, data, responseOptions = {}) {
+ const responseData = getResponseData(data)
+ const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}
+ const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }
+ const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }
-module.exports = { File, FileLike, isFileLike }
+ return { statusCode, data, headers, trailers }
+ }
+ validateReplyParameters (statusCode, data, responseOptions) {
+ if (typeof statusCode === 'undefined') {
+ throw new InvalidArgumentError('statusCode must be defined')
+ }
+ if (typeof data === 'undefined') {
+ throw new InvalidArgumentError('data must be defined')
+ }
+ if (typeof responseOptions !== 'object') {
+ throw new InvalidArgumentError('responseOptions must be an object')
+ }
+ }
-/***/ }),
+ /**
+ * Mock an undici request with a defined reply.
+ */
+ reply (replyData) {
+ // Values of reply aren't available right now as they
+ // can only be available when the reply callback is invoked.
+ if (typeof replyData === 'function') {
+ // We'll first wrap the provided callback in another function,
+ // this function will properly resolve the data from the callback
+ // when invoked.
+ const wrappedDefaultsCallback = (opts) => {
+ // Our reply options callback contains the parameter for statusCode, data and options.
+ const resolvedData = replyData(opts)
-/***/ 47453:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // Check if it is in the right format
+ if (typeof resolvedData !== 'object') {
+ throw new InvalidArgumentError('reply options callback must return an object')
+ }
+ const { statusCode, data = '', responseOptions = {} } = resolvedData
+ this.validateReplyParameters(statusCode, data, responseOptions)
+ // Since the values can be obtained immediately we return them
+ // from this higher order function that will be resolved later.
+ return {
+ ...this.createMockScopeDispatchData(statusCode, data, responseOptions)
+ }
+ }
+ // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)
+ return new MockScope(newMockDispatch)
+ }
-const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(72847)
-const { kState } = __nccwpck_require__(63730)
-const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(17005)
-const { webidl } = __nccwpck_require__(94354)
-const { Blob, File: NativeFile } = __nccwpck_require__(20181)
+ // We can have either one or three parameters, if we get here,
+ // we should have 1-3 parameters. So we spread the arguments of
+ // this function to obtain the parameters, since replyData will always
+ // just be the statusCode.
+ const [statusCode, data = '', responseOptions = {}] = [...arguments]
+ this.validateReplyParameters(statusCode, data, responseOptions)
-/** @type {globalThis['File']} */
-const File = NativeFile ?? UndiciFile
+ // Send in-already provided data like usual
+ const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions)
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)
+ return new MockScope(newMockDispatch)
+ }
-// https://xhr.spec.whatwg.org/#formdata
-class FormData {
- constructor (form) {
- if (form !== undefined) {
- throw webidl.errors.conversionFailed({
- prefix: 'FormData constructor',
- argument: 'Argument 1',
- types: ['undefined']
- })
+ /**
+ * Mock an undici request with a defined error.
+ */
+ replyWithError (error) {
+ if (typeof error === 'undefined') {
+ throw new InvalidArgumentError('error must be defined')
}
- this[kState] = []
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })
+ return new MockScope(newMockDispatch)
}
- append (name, value, filename = undefined) {
- webidl.brandCheck(this, FormData)
-
- webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })
-
- if (arguments.length === 3 && !isBlobLike(value)) {
- throw new TypeError(
- "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
- )
+ /**
+ * Set default reply headers on the interceptor for subsequent replies
+ */
+ defaultReplyHeaders (headers) {
+ if (typeof headers === 'undefined') {
+ throw new InvalidArgumentError('headers must be defined')
}
- // 1. Let value be value if given; otherwise blobValue.
+ this[kDefaultHeaders] = headers
+ return this
+ }
- name = webidl.converters.USVString(name)
- value = isBlobLike(value)
- ? webidl.converters.Blob(value, { strict: false })
- : webidl.converters.USVString(value)
- filename = arguments.length === 3
- ? webidl.converters.USVString(filename)
- : undefined
+ /**
+ * Set default reply trailers on the interceptor for subsequent replies
+ */
+ defaultReplyTrailers (trailers) {
+ if (typeof trailers === 'undefined') {
+ throw new InvalidArgumentError('trailers must be defined')
+ }
- // 2. Let entry be the result of creating an entry with
- // name, value, and filename if given.
- const entry = makeEntry(name, value, filename)
+ this[kDefaultTrailers] = trailers
+ return this
+ }
- // 3. Append entry to this’s entry list.
- this[kState].push(entry)
+ /**
+ * Set reply content length header for replies on the interceptor
+ */
+ replyContentLength () {
+ this[kContentLength] = true
+ return this
}
+}
- delete (name) {
- webidl.brandCheck(this, FormData)
+module.exports.MockInterceptor = MockInterceptor
+module.exports.MockScope = MockScope
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })
- name = webidl.converters.USVString(name)
+/***/ }),
- // The delete(name) method steps are to remove all entries whose name
- // is name from this’s entry list.
- this[kState] = this[kState].filter(entry => entry.name !== name)
- }
+/***/ 36480:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- get (name) {
- webidl.brandCheck(this, FormData)
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })
- name = webidl.converters.USVString(name)
+const { promisify } = __nccwpck_require__(39023)
+const Pool = __nccwpck_require__(44288)
+const { buildMockDispatch } = __nccwpck_require__(73193)
+const {
+ kDispatches,
+ kMockAgent,
+ kClose,
+ kOriginalClose,
+ kOrigin,
+ kOriginalDispatch,
+ kConnected
+} = __nccwpck_require__(52305)
+const { MockInterceptor } = __nccwpck_require__(5843)
+const Symbols = __nccwpck_require__(68031)
+const { InvalidArgumentError } = __nccwpck_require__(53959)
- // 1. If there is no entry whose name is name in this’s entry list,
- // then return null.
- const idx = this[kState].findIndex((entry) => entry.name === name)
- if (idx === -1) {
- return null
- }
+/**
+ * MockPool provides an API that extends the Pool to influence the mockDispatches.
+ */
+class MockPool extends Pool {
+ constructor (origin, opts) {
+ super(origin, opts)
- // 2. Return the value of the first entry whose name is name from
- // this’s entry list.
- return this[kState][idx].value
- }
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+ }
- getAll (name) {
- webidl.brandCheck(this, FormData)
+ this[kMockAgent] = opts.agent
+ this[kOrigin] = origin
+ this[kDispatches] = []
+ this[kConnected] = 1
+ this[kOriginalDispatch] = this.dispatch
+ this[kOriginalClose] = this.close.bind(this)
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })
+ this.dispatch = buildMockDispatch.call(this)
+ this.close = this[kClose]
+ }
- name = webidl.converters.USVString(name)
+ get [Symbols.kConnected] () {
+ return this[kConnected]
+ }
- // 1. If there is no entry whose name is name in this’s entry list,
- // then return the empty list.
- // 2. Return the values of all entries whose name is name, in order,
- // from this’s entry list.
- return this[kState]
- .filter((entry) => entry.name === name)
- .map((entry) => entry.value)
+ /**
+ * Sets up the base interceptor for mocking replies from undici.
+ */
+ intercept (opts) {
+ return new MockInterceptor(opts, this[kDispatches])
}
- has (name) {
- webidl.brandCheck(this, FormData)
+ async [kClose] () {
+ await promisify(this[kOriginalClose])()
+ this[kConnected] = 0
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
+ }
+}
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })
+module.exports = MockPool
- name = webidl.converters.USVString(name)
- // The has(name) method steps are to return true if there is an entry
- // whose name is name in this’s entry list; otherwise false.
- return this[kState].findIndex((entry) => entry.name === name) !== -1
- }
+/***/ }),
- set (name, value, filename = undefined) {
- webidl.brandCheck(this, FormData)
+/***/ 52305:
+/***/ ((module) => {
- webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })
- if (arguments.length === 3 && !isBlobLike(value)) {
- throw new TypeError(
- "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
- )
- }
- // The set(name, value) and set(name, blobValue, filename) method steps
- // are:
+module.exports = {
+ kAgent: Symbol('agent'),
+ kOptions: Symbol('options'),
+ kFactory: Symbol('factory'),
+ kDispatches: Symbol('dispatches'),
+ kDispatchKey: Symbol('dispatch key'),
+ kDefaultHeaders: Symbol('default headers'),
+ kDefaultTrailers: Symbol('default trailers'),
+ kContentLength: Symbol('content length'),
+ kMockAgent: Symbol('mock agent'),
+ kMockAgentSet: Symbol('mock agent set'),
+ kMockAgentGet: Symbol('mock agent get'),
+ kMockDispatch: Symbol('mock dispatch'),
+ kClose: Symbol('close'),
+ kOriginalClose: Symbol('original agent close'),
+ kOrigin: Symbol('origin'),
+ kIsMockActive: Symbol('is mock active'),
+ kNetConnect: Symbol('net connect'),
+ kGetNetConnect: Symbol('get net connect'),
+ kConnected: Symbol('connected')
+}
- // 1. Let value be value if given; otherwise blobValue.
- name = webidl.converters.USVString(name)
- value = isBlobLike(value)
- ? webidl.converters.Blob(value, { strict: false })
- : webidl.converters.USVString(value)
- filename = arguments.length === 3
- ? toUSVString(filename)
- : undefined
+/***/ }),
- // 2. Let entry be the result of creating an entry with name, value, and
- // filename if given.
- const entry = makeEntry(name, value, filename)
+/***/ 73193:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 3. If there are entries in this’s entry list whose name is name, then
- // replace the first such entry with entry and remove the others.
- const idx = this[kState].findIndex((entry) => entry.name === name)
- if (idx !== -1) {
- this[kState] = [
- ...this[kState].slice(0, idx),
- entry,
- ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
- ]
- } else {
- // 4. Otherwise, append entry to this’s entry list.
- this[kState].push(entry)
- }
- }
- entries () {
- webidl.brandCheck(this, FormData)
- return makeIterator(
- () => this[kState].map(pair => [pair.name, pair.value]),
- 'FormData',
- 'key+value'
- )
+const { MockNotMatchedError } = __nccwpck_require__(12673)
+const {
+ kDispatches,
+ kMockAgent,
+ kOriginalDispatch,
+ kOrigin,
+ kGetNetConnect
+} = __nccwpck_require__(52305)
+const { buildURL, nop } = __nccwpck_require__(89500)
+const { STATUS_CODES } = __nccwpck_require__(58611)
+const {
+ types: {
+ isPromise
}
+} = __nccwpck_require__(39023)
- keys () {
- webidl.brandCheck(this, FormData)
-
- return makeIterator(
- () => this[kState].map(pair => [pair.name, pair.value]),
- 'FormData',
- 'key'
- )
+function matchValue (match, value) {
+ if (typeof match === 'string') {
+ return match === value
}
-
- values () {
- webidl.brandCheck(this, FormData)
-
- return makeIterator(
- () => this[kState].map(pair => [pair.name, pair.value]),
- 'FormData',
- 'value'
- )
+ if (match instanceof RegExp) {
+ return match.test(value)
}
-
- /**
- * @param {(value: string, key: string, self: FormData) => void} callbackFn
- * @param {unknown} thisArg
- */
- forEach (callbackFn, thisArg = globalThis) {
- webidl.brandCheck(this, FormData)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })
-
- if (typeof callbackFn !== 'function') {
- throw new TypeError(
- "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."
- )
- }
-
- for (const [key, value] of this) {
- callbackFn.apply(thisArg, [value, key, this])
- }
+ if (typeof match === 'function') {
+ return match(value) === true
}
+ return false
}
-FormData.prototype[Symbol.iterator] = FormData.prototype.entries
-
-Object.defineProperties(FormData.prototype, {
- [Symbol.toStringTag]: {
- value: 'FormData',
- configurable: true
- }
-})
+function lowerCaseEntries (headers) {
+ return Object.fromEntries(
+ Object.entries(headers).map(([headerName, headerValue]) => {
+ return [headerName.toLocaleLowerCase(), headerValue]
+ })
+ )
+}
/**
- * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
- * @param {string} name
- * @param {string|Blob} value
- * @param {?string} filename
- * @returns
+ * @param {import('../../index').Headers|string[]|Record} headers
+ * @param {string} key
*/
-function makeEntry (name, value, filename) {
- // 1. Set name to the result of converting name into a scalar value string.
- // "To convert a string into a scalar value string, replace any surrogates
- // with U+FFFD."
- // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end
- name = Buffer.from(name).toString('utf8')
+function getHeaderByName (headers, key) {
+ if (Array.isArray(headers)) {
+ for (let i = 0; i < headers.length; i += 2) {
+ if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
+ return headers[i + 1]
+ }
+ }
- // 2. If value is a string, then set value to the result of converting
- // value into a scalar value string.
- if (typeof value === 'string') {
- value = Buffer.from(value).toString('utf8')
+ return undefined
+ } else if (typeof headers.get === 'function') {
+ return headers.get(key)
} else {
- // 3. Otherwise:
+ return lowerCaseEntries(headers)[key.toLocaleLowerCase()]
+ }
+}
- // 1. If value is not a File object, then set value to a new File object,
- // representing the same bytes, whose name attribute value is "blob"
- if (!isFileLike(value)) {
- value = value instanceof Blob
- ? new File([value], 'blob', { type: value.type })
- : new FileLike(value, 'blob', { type: value.type })
+/** @param {string[]} headers */
+function buildHeadersFromArray (headers) { // fetch HeadersList
+ const clone = headers.slice()
+ const entries = []
+ for (let index = 0; index < clone.length; index += 2) {
+ entries.push([clone[index], clone[index + 1]])
+ }
+ return Object.fromEntries(entries)
+}
+
+function matchHeaders (mockDispatch, headers) {
+ if (typeof mockDispatch.headers === 'function') {
+ if (Array.isArray(headers)) { // fetch HeadersList
+ headers = buildHeadersFromArray(headers)
}
+ return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
+ }
+ if (typeof mockDispatch.headers === 'undefined') {
+ return true
+ }
+ if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {
+ return false
+ }
- // 2. If filename is given, then set value to a new File object,
- // representing the same bytes, whose name attribute is filename.
- if (filename !== undefined) {
- /** @type {FilePropertyBag} */
- const options = {
- type: value.type,
- lastModified: value.lastModified
- }
+ for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {
+ const headerValue = getHeaderByName(headers, matchHeaderName)
- value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile
- ? new File([value], filename, options)
- : new FileLike(value, filename, options)
+ if (!matchValue(matchHeaderValue, headerValue)) {
+ return false
}
}
-
- // 4. Return an entry whose name is name and whose value is value.
- return { name, value }
+ return true
}
-module.exports = { FormData }
-
-
-/***/ }),
+function safeUrl (path) {
+ if (typeof path !== 'string') {
+ return path
+ }
-/***/ 62896:
-/***/ ((module) => {
+ const pathSegments = path.split('?')
+ if (pathSegments.length !== 2) {
+ return path
+ }
+ const qp = new URLSearchParams(pathSegments.pop())
+ qp.sort()
+ return [...pathSegments, qp.toString()].join('?')
+}
-// In case of breaking changes, increase the version
-// number to avoid conflicts.
-const globalOrigin = Symbol.for('undici.globalOrigin.1')
+function matchKey (mockDispatch, { path, method, body, headers }) {
+ const pathMatch = matchValue(mockDispatch.path, path)
+ const methodMatch = matchValue(mockDispatch.method, method)
+ const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true
+ const headersMatch = matchHeaders(mockDispatch, headers)
+ return pathMatch && methodMatch && bodyMatch && headersMatch
+}
-function getGlobalOrigin () {
- return globalThis[globalOrigin]
+function getResponseData (data) {
+ if (Buffer.isBuffer(data)) {
+ return data
+ } else if (typeof data === 'object') {
+ return JSON.stringify(data)
+ } else {
+ return data.toString()
+ }
}
-function setGlobalOrigin (newOrigin) {
- if (newOrigin === undefined) {
- Object.defineProperty(globalThis, globalOrigin, {
- value: undefined,
- writable: true,
- enumerable: false,
- configurable: false
- })
+function getMockDispatch (mockDispatches, key) {
+ const basePath = key.query ? buildURL(key.path, key.query) : key.path
+ const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
- return
+ // Match path
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
}
- const parsedURL = new URL(newOrigin)
+ // Match method
+ matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`)
+ }
- if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
- throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
+ // Match body
+ matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`)
}
- Object.defineProperty(globalThis, globalOrigin, {
- value: parsedURL,
- writable: true,
- enumerable: false,
- configurable: false
+ // Match headers
+ matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)
+ }
+
+ return matchedMockDispatches[0]
+}
+
+function addMockDispatch (mockDispatches, key, data) {
+ const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
+ const replyData = typeof data === 'function' ? { callback: data } : { ...data }
+ const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
+ mockDispatches.push(newMockDispatch)
+ return newMockDispatch
+}
+
+function deleteMockDispatch (mockDispatches, key) {
+ const index = mockDispatches.findIndex(dispatch => {
+ if (!dispatch.consumed) {
+ return false
+ }
+ return matchKey(dispatch, key)
})
+ if (index !== -1) {
+ mockDispatches.splice(index, 1)
+ }
}
-module.exports = {
- getGlobalOrigin,
- setGlobalOrigin
+function buildKey (opts) {
+ const { path, method, body, headers, query } = opts
+ return {
+ path,
+ method,
+ body,
+ headers,
+ query
+ }
}
-
-/***/ }),
-
-/***/ 12801:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-// https://github.com/Ethan-Arrowood/undici-fetch
-
-
-
-const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
-const { kGuard } = __nccwpck_require__(63730)
-const { kEnumerableProperty } = __nccwpck_require__(89500)
-const {
- makeIterator,
- isValidHeaderName,
- isValidHeaderValue
-} = __nccwpck_require__(72847)
-const { webidl } = __nccwpck_require__(94354)
-const assert = __nccwpck_require__(42613)
-
-const kHeadersMap = Symbol('headers map')
-const kHeadersSortedMap = Symbol('headers map sorted')
+function generateKeyValues (data) {
+ return Object.entries(data).reduce((keyValuePairs, [key, value]) => [
+ ...keyValuePairs,
+ Buffer.from(`${key}`),
+ Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)
+ ], [])
+}
/**
- * @param {number} code
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
+ * @param {number} statusCode
*/
-function isHTTPWhiteSpaceCharCode (code) {
- return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
+function getStatusText (statusCode) {
+ return STATUS_CODES[statusCode] || 'unknown'
+}
+
+async function getResponse (body) {
+ const buffers = []
+ for await (const data of body) {
+ buffers.push(data)
+ }
+ return Buffer.concat(buffers).toString('utf8')
}
/**
- * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
- * @param {string} potentialValue
+ * Mock dispatch function used to simulate undici dispatches
*/
-function headerValueNormalize (potentialValue) {
- // To normalize a byte sequence potentialValue, remove
- // any leading and trailing HTTP whitespace bytes from
- // potentialValue.
- let i = 0; let j = potentialValue.length
+function mockDispatch (opts, handler) {
+ // Get mock dispatch from built key
+ const key = buildKey(opts)
+ const mockDispatch = getMockDispatch(this[kDispatches], key)
- while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j
- while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i
+ mockDispatch.timesInvoked++
- return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)
-}
+ // Here's where we resolve a callback if a callback is present for the dispatch data.
+ if (mockDispatch.data.callback) {
+ mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }
+ }
-function fill (headers, object) {
- // To fill a Headers object headers with a given object object, run these steps:
+ // Parse mockDispatch data
+ const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch
+ const { timesInvoked, times } = mockDispatch
- // 1. If object is a sequence, then for each header in object:
- // Note: webidl conversion to array has already been done.
- if (Array.isArray(object)) {
- for (let i = 0; i < object.length; ++i) {
- const header = object[i]
- // 1. If header does not contain exactly two items, then throw a TypeError.
- if (header.length !== 2) {
- throw webidl.errors.exception({
- header: 'Headers constructor',
- message: `expected name/value pair to be length 2, found ${header.length}.`
- })
- }
+ // If it's used up and not persistent, mark as consumed
+ mockDispatch.consumed = !persist && timesInvoked >= times
+ mockDispatch.pending = timesInvoked < times
- // 2. Append (header’s first item, header’s second item) to headers.
- appendHeader(headers, header[0], header[1])
- }
- } else if (typeof object === 'object' && object !== null) {
- // Note: null should throw
+ // If specified, trigger dispatch error
+ if (error !== null) {
+ deleteMockDispatch(this[kDispatches], key)
+ handler.onError(error)
+ return true
+ }
- // 2. Otherwise, object is a record, then for each key → value in object,
- // append (key, value) to headers
- const keys = Object.keys(object)
- for (let i = 0; i < keys.length; ++i) {
- appendHeader(headers, keys[i], object[keys[i]])
- }
+ // Handle the request with a delay if necessary
+ if (typeof delay === 'number' && delay > 0) {
+ setTimeout(() => {
+ handleReply(this[kDispatches])
+ }, delay)
} else {
- throw webidl.errors.conversionFailed({
- prefix: 'Headers constructor',
- argument: 'Argument 1',
- types: ['sequence>', 'record']
- })
+ handleReply(this[kDispatches])
}
-}
-/**
- * @see https://fetch.spec.whatwg.org/#concept-headers-append
- */
-function appendHeader (headers, name, value) {
- // 1. Normalize value.
- value = headerValueNormalize(value)
+ function handleReply (mockDispatches, _data = data) {
+ // fetch's HeadersList is a 1D string array
+ const optsHeaders = Array.isArray(opts.headers)
+ ? buildHeadersFromArray(opts.headers)
+ : opts.headers
+ const body = typeof _data === 'function'
+ ? _data({ ...opts, headers: optsHeaders })
+ : _data
- // 2. If name is not a header name or value is not a
- // header value, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.append',
- value: name,
- type: 'header name'
- })
- } else if (!isValidHeaderValue(value)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.append',
- value,
- type: 'header value'
- })
- }
+ // util.types.isPromise is likely needed for jest.
+ if (isPromise(body)) {
+ // If handleReply is asynchronous, throwing an error
+ // in the callback will reject the promise, rather than
+ // synchronously throw the error, which breaks some tests.
+ // Rather, we wait for the callback to resolve if it is a
+ // promise, and then re-run handleReply with the new body.
+ body.then((newData) => handleReply(mockDispatches, newData))
+ return
+ }
- // 3. If headers’s guard is "immutable", then throw a TypeError.
- // 4. Otherwise, if headers’s guard is "request" and name is a
- // forbidden header name, return.
- // Note: undici does not implement forbidden header names
- if (headers[kGuard] === 'immutable') {
- throw new TypeError('immutable')
- } else if (headers[kGuard] === 'request-no-cors') {
- // 5. Otherwise, if headers’s guard is "request-no-cors":
- // TODO
- }
+ const responseData = getResponseData(body)
+ const responseHeaders = generateKeyValues(headers)
+ const responseTrailers = generateKeyValues(trailers)
- // 6. Otherwise, if headers’s guard is "response" and name is a
- // forbidden response-header name, return.
+ handler.abort = nop
+ handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))
+ handler.onData(Buffer.from(responseData))
+ handler.onComplete(responseTrailers)
+ deleteMockDispatch(mockDispatches, key)
+ }
- // 7. Append (name, value) to headers’s header list.
- return headers[kHeadersList].append(name, value)
+ function resume () {}
- // 8. If headers’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from headers
+ return true
}
-class HeadersList {
- /** @type {[string, string][]|null} */
- cookies = null
+function buildMockDispatch () {
+ const agent = this[kMockAgent]
+ const origin = this[kOrigin]
+ const originalDispatch = this[kOriginalDispatch]
- constructor (init) {
- if (init instanceof HeadersList) {
- this[kHeadersMap] = new Map(init[kHeadersMap])
- this[kHeadersSortedMap] = init[kHeadersSortedMap]
- this.cookies = init.cookies === null ? null : [...init.cookies]
+ return function dispatch (opts, handler) {
+ if (agent.isMockActive) {
+ try {
+ mockDispatch.call(this, opts, handler)
+ } catch (error) {
+ if (error instanceof MockNotMatchedError) {
+ const netConnect = agent[kGetNetConnect]()
+ if (netConnect === false) {
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)
+ }
+ if (checkNetConnect(netConnect, origin)) {
+ originalDispatch.call(this, opts, handler)
+ } else {
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)
+ }
+ } else {
+ throw error
+ }
+ }
} else {
- this[kHeadersMap] = new Map(init)
- this[kHeadersSortedMap] = null
+ originalDispatch.call(this, opts, handler)
}
}
+}
- // https://fetch.spec.whatwg.org/#header-list-contains
- contains (name) {
- // A header list list contains a header name name if list
- // contains a header whose name is a byte-case-insensitive
- // match for name.
- name = name.toLowerCase()
-
- return this[kHeadersMap].has(name)
+function checkNetConnect (netConnect, origin) {
+ const url = new URL(origin)
+ if (netConnect === true) {
+ return true
+ } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
+ return true
}
+ return false
+}
- clear () {
- this[kHeadersMap].clear()
- this[kHeadersSortedMap] = null
- this.cookies = null
+function buildMockOptions (opts) {
+ if (opts) {
+ const { agent, ...mockOptions } = opts
+ return mockOptions
}
+}
- // https://fetch.spec.whatwg.org/#concept-header-list-append
- append (name, value) {
- this[kHeadersSortedMap] = null
-
- // 1. If list contains name, then set name to the first such
- // header’s name.
- const lowercaseName = name.toLowerCase()
- const exists = this[kHeadersMap].get(lowercaseName)
-
- // 2. Append (name, value) to list.
- if (exists) {
- const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
- this[kHeadersMap].set(lowercaseName, {
- name: exists.name,
- value: `${exists.value}${delimiter}${value}`
- })
- } else {
- this[kHeadersMap].set(lowercaseName, { name, value })
- }
+module.exports = {
+ getResponseData,
+ getMockDispatch,
+ addMockDispatch,
+ deleteMockDispatch,
+ buildKey,
+ generateKeyValues,
+ matchValue,
+ getResponse,
+ getStatusText,
+ mockDispatch,
+ buildMockDispatch,
+ checkNetConnect,
+ buildMockOptions,
+ getHeaderByName
+}
- if (lowercaseName === 'set-cookie') {
- this.cookies ??= []
- this.cookies.push(value)
- }
- }
- // https://fetch.spec.whatwg.org/#concept-header-list-set
- set (name, value) {
- this[kHeadersSortedMap] = null
- const lowercaseName = name.toLowerCase()
+/***/ }),
- if (lowercaseName === 'set-cookie') {
- this.cookies = [value]
- }
+/***/ 85738:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 1. If list contains name, then set the value of
- // the first such header to value and remove the
- // others.
- // 2. Otherwise, append header (name, value) to list.
- this[kHeadersMap].set(lowercaseName, { name, value })
- }
- // https://fetch.spec.whatwg.org/#concept-header-list-delete
- delete (name) {
- this[kHeadersSortedMap] = null
- name = name.toLowerCase()
+const { Transform } = __nccwpck_require__(2203)
+const { Console } = __nccwpck_require__(64236)
- if (name === 'set-cookie') {
- this.cookies = null
- }
+/**
+ * Gets the output of `console.table(…)` as a string.
+ */
+module.exports = class PendingInterceptorsFormatter {
+ constructor ({ disableColors } = {}) {
+ this.transform = new Transform({
+ transform (chunk, _enc, cb) {
+ cb(null, chunk)
+ }
+ })
- this[kHeadersMap].delete(name)
+ this.logger = new Console({
+ stdout: this.transform,
+ inspectOptions: {
+ colors: !disableColors && !process.env.CI
+ }
+ })
}
- // https://fetch.spec.whatwg.org/#concept-header-list-get
- get (name) {
- const value = this[kHeadersMap].get(name.toLowerCase())
+ format (pendingInterceptors) {
+ const withPrettyHeaders = pendingInterceptors.map(
+ ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
+ Method: method,
+ Origin: origin,
+ Path: path,
+ 'Status code': statusCode,
+ Persistent: persist ? '✅' : '❌',
+ Invocations: timesInvoked,
+ Remaining: persist ? Infinity : times - timesInvoked
+ }))
- // 1. If list does not contain name, then return null.
- // 2. Return the values of all headers in list whose name
- // is a byte-case-insensitive match for name,
- // separated from each other by 0x2C 0x20, in order.
- return value === undefined ? null : value.value
+ this.logger.table(withPrettyHeaders)
+ return this.transform.read().toString()
}
+}
- * [Symbol.iterator] () {
- // use the lowercased name
- for (const [name, { value }] of this[kHeadersMap]) {
- yield [name, value]
- }
- }
- get entries () {
- const headers = {}
+/***/ }),
- if (this[kHeadersMap].size) {
- for (const { name, value } of this[kHeadersMap].values()) {
- headers[name] = value
- }
- }
+/***/ 35773:
+/***/ ((module) => {
- return headers
- }
-}
-// https://fetch.spec.whatwg.org/#headers-class
-class Headers {
- constructor (init = undefined) {
- if (init === kConstruct) {
- return
- }
- this[kHeadersList] = new HeadersList()
- // The new Headers(init) constructor steps are:
+const singulars = {
+ pronoun: 'it',
+ is: 'is',
+ was: 'was',
+ this: 'this'
+}
- // 1. Set this’s guard to "none".
- this[kGuard] = 'none'
+const plurals = {
+ pronoun: 'they',
+ is: 'are',
+ was: 'were',
+ this: 'these'
+}
- // 2. If init is given, then fill this with init.
- if (init !== undefined) {
- init = webidl.converters.HeadersInit(init)
- fill(this, init)
- }
+module.exports = class Pluralizer {
+ constructor (singular, plural) {
+ this.singular = singular
+ this.plural = plural
}
- // https://fetch.spec.whatwg.org/#dom-headers-append
- append (name, value) {
- webidl.brandCheck(this, Headers)
+ pluralize (count) {
+ const one = count === 1
+ const keys = one ? singulars : plurals
+ const noun = one ? this.singular : this.plural
+ return { ...keys, count, noun }
+ }
+}
- webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })
- name = webidl.converters.ByteString(name)
- value = webidl.converters.ByteString(value)
+/***/ }),
- return appendHeader(this, name, value)
- }
+/***/ 98721:
+/***/ ((module) => {
- // https://fetch.spec.whatwg.org/#dom-headers-delete
- delete (name) {
- webidl.brandCheck(this, Headers)
+/* eslint-disable */
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })
- name = webidl.converters.ByteString(name)
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.delete',
- value: name,
- type: 'header name'
- })
- }
+// Extracted from node/lib/internal/fixed_queue.js
- // 2. If this’s guard is "immutable", then throw a TypeError.
- // 3. Otherwise, if this’s guard is "request" and name is a
- // forbidden header name, return.
- // 4. Otherwise, if this’s guard is "request-no-cors", name
- // is not a no-CORS-safelisted request-header name, and
- // name is not a privileged no-CORS request-header name,
- // return.
- // 5. Otherwise, if this’s guard is "response" and name is
- // a forbidden response-header name, return.
- // Note: undici does not implement forbidden header names
- if (this[kGuard] === 'immutable') {
- throw new TypeError('immutable')
- } else if (this[kGuard] === 'request-no-cors') {
- // TODO
- }
+// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.
+const kSize = 2048;
+const kMask = kSize - 1;
- // 6. If this’s header list does not contain name, then
- // return.
- if (!this[kHeadersList].contains(name)) {
- return
- }
+// The FixedQueue is implemented as a singly-linked list of fixed-size
+// circular buffers. It looks something like this:
+//
+// head tail
+// | |
+// v v
+// +-----------+ <-----\ +-----------+ <------\ +-----------+
+// | [null] | \----- | next | \------- | next |
+// +-----------+ +-----------+ +-----------+
+// | item | <-- bottom | item | <-- bottom | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | bottom --> | item |
+// | item | | item | | item |
+// | ... | | ... | | ... |
+// | item | | item | | item |
+// | item | | item | | item |
+// | [empty] | <-- top | item | | item |
+// | [empty] | | item | | item |
+// | [empty] | | [empty] | <-- top top --> | [empty] |
+// +-----------+ +-----------+ +-----------+
+//
+// Or, if there is only one circular buffer, it looks something
+// like either of these:
+//
+// head tail head tail
+// | | | |
+// v v v v
+// +-----------+ +-----------+
+// | [null] | | [null] |
+// +-----------+ +-----------+
+// | [empty] | | item |
+// | [empty] | | item |
+// | item | <-- bottom top --> | [empty] |
+// | item | | [empty] |
+// | [empty] | <-- top bottom --> | item |
+// | [empty] | | item |
+// +-----------+ +-----------+
+//
+// Adding a value means moving `top` forward by one, removing means
+// moving `bottom` forward by one. After reaching the end, the queue
+// wraps around.
+//
+// When `top === bottom` the current queue is empty and when
+// `top + 1 === bottom` it's full. This wastes a single space of storage
+// but allows much quicker checks.
- // 7. Delete name from this’s header list.
- // 8. If this’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from this.
- this[kHeadersList].delete(name)
+class FixedCircularBuffer {
+ constructor() {
+ this.bottom = 0;
+ this.top = 0;
+ this.list = new Array(kSize);
+ this.next = null;
}
- // https://fetch.spec.whatwg.org/#dom-headers-get
- get (name) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })
-
- name = webidl.converters.ByteString(name)
+ isEmpty() {
+ return this.top === this.bottom;
+ }
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.get',
- value: name,
- type: 'header name'
- })
- }
+ isFull() {
+ return ((this.top + 1) & kMask) === this.bottom;
+ }
- // 2. Return the result of getting name from this’s header
- // list.
- return this[kHeadersList].get(name)
+ push(data) {
+ this.list[this.top] = data;
+ this.top = (this.top + 1) & kMask;
}
- // https://fetch.spec.whatwg.org/#dom-headers-has
- has (name) {
- webidl.brandCheck(this, Headers)
+ shift() {
+ const nextItem = this.list[this.bottom];
+ if (nextItem === undefined)
+ return null;
+ this.list[this.bottom] = undefined;
+ this.bottom = (this.bottom + 1) & kMask;
+ return nextItem;
+ }
+}
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })
+module.exports = class FixedQueue {
+ constructor() {
+ this.head = this.tail = new FixedCircularBuffer();
+ }
- name = webidl.converters.ByteString(name)
+ isEmpty() {
+ return this.head.isEmpty();
+ }
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.has',
- value: name,
- type: 'header name'
- })
+ push(data) {
+ if (this.head.isFull()) {
+ // Head is full: Creates a new queue, sets the old queue's `.next` to it,
+ // and sets it as the new main queue.
+ this.head = this.head.next = new FixedCircularBuffer();
}
-
- // 2. Return true if this’s header list contains name;
- // otherwise false.
- return this[kHeadersList].contains(name)
+ this.head.push(data);
}
- // https://fetch.spec.whatwg.org/#dom-headers-set
- set (name, value) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })
-
- name = webidl.converters.ByteString(name)
- value = webidl.converters.ByteString(value)
-
- // 1. Normalize value.
- value = headerValueNormalize(value)
-
- // 2. If name is not a header name or value is not a
- // header value, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.set',
- value: name,
- type: 'header name'
- })
- } else if (!isValidHeaderValue(value)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.set',
- value,
- type: 'header value'
- })
+ shift() {
+ const tail = this.tail;
+ const next = tail.shift();
+ if (tail.isEmpty() && tail.next !== null) {
+ // If there is another queue, it forms the new tail.
+ this.tail = tail.next;
}
+ return next;
+ }
+};
- // 3. If this’s guard is "immutable", then throw a TypeError.
- // 4. Otherwise, if this’s guard is "request" and name is a
- // forbidden header name, return.
- // 5. Otherwise, if this’s guard is "request-no-cors" and
- // name/value is not a no-CORS-safelisted request-header,
- // return.
- // 6. Otherwise, if this’s guard is "response" and name is a
- // forbidden response-header name, return.
- // Note: undici does not implement forbidden header names
- if (this[kGuard] === 'immutable') {
- throw new TypeError('immutable')
- } else if (this[kGuard] === 'request-no-cors') {
- // TODO
- }
- // 7. Set (name, value) in this’s header list.
- // 8. If this’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from this
- this[kHeadersList].set(name, value)
- }
+/***/ }),
- // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
- getSetCookie () {
- webidl.brandCheck(this, Headers)
+/***/ 18804:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 1. If this’s header list does not contain `Set-Cookie`, then return « ».
- // 2. Return the values of all headers in this’s header list whose name is
- // a byte-case-insensitive match for `Set-Cookie`, in order.
- const list = this[kHeadersList].cookies
- if (list) {
- return [...list]
- }
+const DispatcherBase = __nccwpck_require__(52421)
+const FixedQueue = __nccwpck_require__(98721)
+const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(68031)
+const PoolStats = __nccwpck_require__(29218)
- return []
- }
+const kClients = Symbol('clients')
+const kNeedDrain = Symbol('needDrain')
+const kQueue = Symbol('queue')
+const kClosedResolve = Symbol('closed resolve')
+const kOnDrain = Symbol('onDrain')
+const kOnConnect = Symbol('onConnect')
+const kOnDisconnect = Symbol('onDisconnect')
+const kOnConnectionError = Symbol('onConnectionError')
+const kGetDispatcher = Symbol('get dispatcher')
+const kAddClient = Symbol('add client')
+const kRemoveClient = Symbol('remove client')
+const kStats = Symbol('stats')
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- get [kHeadersSortedMap] () {
- if (this[kHeadersList][kHeadersSortedMap]) {
- return this[kHeadersList][kHeadersSortedMap]
- }
+class PoolBase extends DispatcherBase {
+ constructor () {
+ super()
- // 1. Let headers be an empty list of headers with the key being the name
- // and value the value.
- const headers = []
+ this[kQueue] = new FixedQueue()
+ this[kClients] = []
+ this[kQueued] = 0
- // 2. Let names be the result of convert header names to a sorted-lowercase
- // set with all the names of the headers in list.
- const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)
- const cookies = this[kHeadersList].cookies
+ const pool = this
- // 3. For each name of names:
- for (let i = 0; i < names.length; ++i) {
- const [name, value] = names[i]
- // 1. If name is `set-cookie`, then:
- if (name === 'set-cookie') {
- // 1. Let values be a list of all values of headers in list whose name
- // is a byte-case-insensitive match for name, in order.
+ this[kOnDrain] = function onDrain (origin, targets) {
+ const queue = pool[kQueue]
- // 2. For each value of values:
- // 1. Append (name, value) to headers.
- for (let j = 0; j < cookies.length; ++j) {
- headers.push([name, cookies[j]])
+ let needDrain = false
+
+ while (!needDrain) {
+ const item = queue.shift()
+ if (!item) {
+ break
}
- } else {
- // 2. Otherwise:
+ pool[kQueued]--
+ needDrain = !this.dispatch(item.opts, item.handler)
+ }
- // 1. Let value be the result of getting name from list.
+ this[kNeedDrain] = needDrain
- // 2. Assert: value is non-null.
- assert(value !== null)
+ if (!this[kNeedDrain] && pool[kNeedDrain]) {
+ pool[kNeedDrain] = false
+ pool.emit('drain', origin, [pool, ...targets])
+ }
- // 3. Append (name, value) to headers.
- headers.push([name, value])
+ if (pool[kClosedResolve] && queue.isEmpty()) {
+ Promise
+ .all(pool[kClients].map(c => c.close()))
+ .then(pool[kClosedResolve])
}
}
- this[kHeadersList][kHeadersSortedMap] = headers
-
- // 4. Return headers.
- return headers
- }
+ this[kOnConnect] = (origin, targets) => {
+ pool.emit('connect', origin, [pool, ...targets])
+ }
- keys () {
- webidl.brandCheck(this, Headers)
+ this[kOnDisconnect] = (origin, targets, err) => {
+ pool.emit('disconnect', origin, [pool, ...targets], err)
+ }
- if (this[kGuard] === 'immutable') {
- const value = this[kHeadersSortedMap]
- return makeIterator(() => value, 'Headers',
- 'key')
+ this[kOnConnectionError] = (origin, targets, err) => {
+ pool.emit('connectionError', origin, [pool, ...targets], err)
}
- return makeIterator(
- () => [...this[kHeadersSortedMap].values()],
- 'Headers',
- 'key'
- )
+ this[kStats] = new PoolStats(this)
}
- values () {
- webidl.brandCheck(this, Headers)
-
- if (this[kGuard] === 'immutable') {
- const value = this[kHeadersSortedMap]
- return makeIterator(() => value, 'Headers',
- 'value')
- }
+ get [kBusy] () {
+ return this[kNeedDrain]
+ }
- return makeIterator(
- () => [...this[kHeadersSortedMap].values()],
- 'Headers',
- 'value'
- )
+ get [kConnected] () {
+ return this[kClients].filter(client => client[kConnected]).length
}
- entries () {
- webidl.brandCheck(this, Headers)
+ get [kFree] () {
+ return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length
+ }
- if (this[kGuard] === 'immutable') {
- const value = this[kHeadersSortedMap]
- return makeIterator(() => value, 'Headers',
- 'key+value')
+ get [kPending] () {
+ let ret = this[kQueued]
+ for (const { [kPending]: pending } of this[kClients]) {
+ ret += pending
}
-
- return makeIterator(
- () => [...this[kHeadersSortedMap].values()],
- 'Headers',
- 'key+value'
- )
+ return ret
}
- /**
- * @param {(value: string, key: string, self: Headers) => void} callbackFn
- * @param {unknown} thisArg
- */
- forEach (callbackFn, thisArg = globalThis) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })
-
- if (typeof callbackFn !== 'function') {
- throw new TypeError(
- "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
- )
+ get [kRunning] () {
+ let ret = 0
+ for (const { [kRunning]: running } of this[kClients]) {
+ ret += running
}
+ return ret
+ }
- for (const [key, value] of this) {
- callbackFn.apply(thisArg, [value, key, this])
+ get [kSize] () {
+ let ret = this[kQueued]
+ for (const { [kSize]: size } of this[kClients]) {
+ ret += size
}
+ return ret
}
- [Symbol.for('nodejs.util.inspect.custom')] () {
- webidl.brandCheck(this, Headers)
-
- return this[kHeadersList]
+ get stats () {
+ return this[kStats]
}
-}
-
-Headers.prototype[Symbol.iterator] = Headers.prototype.entries
-Object.defineProperties(Headers.prototype, {
- append: kEnumerableProperty,
- delete: kEnumerableProperty,
- get: kEnumerableProperty,
- has: kEnumerableProperty,
- set: kEnumerableProperty,
- getSetCookie: kEnumerableProperty,
- keys: kEnumerableProperty,
- values: kEnumerableProperty,
- entries: kEnumerableProperty,
- forEach: kEnumerableProperty,
- [Symbol.iterator]: { enumerable: false },
- [Symbol.toStringTag]: {
- value: 'Headers',
- configurable: true
+ async [kClose] () {
+ if (this[kQueue].isEmpty()) {
+ return Promise.all(this[kClients].map(c => c.close()))
+ } else {
+ return new Promise((resolve) => {
+ this[kClosedResolve] = resolve
+ })
+ }
}
-})
-webidl.converters.HeadersInit = function (V) {
- if (webidl.util.Type(V) === 'Object') {
- if (V[Symbol.iterator]) {
- return webidl.converters['sequence>'](V)
+ async [kDestroy] (err) {
+ while (true) {
+ const item = this[kQueue].shift()
+ if (!item) {
+ break
+ }
+ item.handler.onError(err)
}
- return webidl.converters['record'](V)
+ return Promise.all(this[kClients].map(c => c.destroy(err)))
}
- throw webidl.errors.conversionFailed({
- prefix: 'Headers constructor',
- argument: 'Argument 1',
- types: ['sequence>', 'record']
- })
-}
-
-module.exports = {
- fill,
- Headers,
- HeadersList
-}
-
-
-/***/ }),
-
-/***/ 11503:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-// https://github.com/Ethan-Arrowood/undici-fetch
-
-
+ [kDispatch] (opts, handler) {
+ const dispatcher = this[kGetDispatcher]()
-const {
- Response,
- makeNetworkError,
- makeAppropriateNetworkError,
- filterResponse,
- makeResponse
-} = __nccwpck_require__(89928)
-const { Headers } = __nccwpck_require__(12801)
-const { Request, makeRequest } = __nccwpck_require__(2630)
-const zlib = __nccwpck_require__(43106)
-const {
- bytesMatch,
- makePolicyContainer,
- clonePolicyContainer,
- requestBadPort,
- TAOCheck,
- appendRequestOriginHeader,
- responseLocationURL,
- requestCurrentURL,
- setRequestReferrerPolicyOnRedirect,
- tryUpgradeRequestToAPotentiallyTrustworthyURL,
- createOpaqueTimingInfo,
- appendFetchMetadata,
- corsCheck,
- crossOriginResourcePolicyCheck,
- determineRequestsReferrer,
- coarsenedSharedCurrentTime,
- createDeferredPromise,
- isBlobLike,
- sameOrigin,
- isCancelled,
- isAborted,
- isErrorLike,
- fullyReadBody,
- readableStreamClose,
- isomorphicEncode,
- urlIsLocal,
- urlIsHttpHttpsScheme,
- urlHasHttpsScheme
-} = __nccwpck_require__(72847)
-const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
-const assert = __nccwpck_require__(42613)
-const { safelyExtractBody } = __nccwpck_require__(37791)
-const {
- redirectStatusSet,
- nullBodyStatus,
- safeMethodsSet,
- requestBodyHeader,
- subresourceSet,
- DOMException
-} = __nccwpck_require__(21234)
-const { kHeadersList } = __nccwpck_require__(68031)
-const EE = __nccwpck_require__(24434)
-const { Readable, pipeline } = __nccwpck_require__(2203)
-const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(89500)
-const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(37246)
-const { TransformStream } = __nccwpck_require__(63774)
-const { getGlobalDispatcher } = __nccwpck_require__(61481)
-const { webidl } = __nccwpck_require__(94354)
-const { STATUS_CODES } = __nccwpck_require__(58611)
-const GET_OR_HEAD = ['GET', 'HEAD']
+ if (!dispatcher) {
+ this[kNeedDrain] = true
+ this[kQueue].push({ opts, handler })
+ this[kQueued]++
+ } else if (!dispatcher.dispatch(opts, handler)) {
+ dispatcher[kNeedDrain] = true
+ this[kNeedDrain] = !this[kGetDispatcher]()
+ }
-/** @type {import('buffer').resolveObjectURL} */
-let resolveObjectURL
-let ReadableStream = globalThis.ReadableStream
+ return !this[kNeedDrain]
+ }
-class Fetch extends EE {
- constructor (dispatcher) {
- super()
+ [kAddClient] (client) {
+ client
+ .on('drain', this[kOnDrain])
+ .on('connect', this[kOnConnect])
+ .on('disconnect', this[kOnDisconnect])
+ .on('connectionError', this[kOnConnectionError])
- this.dispatcher = dispatcher
- this.connection = null
- this.dump = false
- this.state = 'ongoing'
- // 2 terminated listeners get added per request,
- // but only 1 gets removed. If there are 20 redirects,
- // 21 listeners will be added.
- // See https://github.com/nodejs/undici/issues/1711
- // TODO (fix): Find and fix root cause for leaked listener.
- this.setMaxListeners(21)
- }
+ this[kClients].push(client)
- terminate (reason) {
- if (this.state !== 'ongoing') {
- return
+ if (this[kNeedDrain]) {
+ process.nextTick(() => {
+ if (this[kNeedDrain]) {
+ this[kOnDrain](client[kUrl], [this, client])
+ }
+ })
}
- this.state = 'terminated'
- this.connection?.destroy(reason)
- this.emit('terminated', reason)
+ return this
}
- // https://fetch.spec.whatwg.org/#fetch-controller-abort
- abort (error) {
- if (this.state !== 'ongoing') {
- return
- }
-
- // 1. Set controller’s state to "aborted".
- this.state = 'aborted'
+ [kRemoveClient] (client) {
+ client.close(() => {
+ const idx = this[kClients].indexOf(client)
+ if (idx !== -1) {
+ this[kClients].splice(idx, 1)
+ }
+ })
- // 2. Let fallbackError be an "AbortError" DOMException.
- // 3. Set error to fallbackError if it is not given.
- if (!error) {
- error = new DOMException('The operation was aborted.', 'AbortError')
- }
+ this[kNeedDrain] = this[kClients].some(dispatcher => (
+ !dispatcher[kNeedDrain] &&
+ dispatcher.closed !== true &&
+ dispatcher.destroyed !== true
+ ))
+ }
+}
- // 4. Let serializedError be StructuredSerialize(error).
- // If that threw an exception, catch it, and let
- // serializedError be StructuredSerialize(fallbackError).
+module.exports = {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+}
- // 5. Set controller’s serialized abort reason to serializedError.
- this.serializedAbortReason = error
- this.connection?.destroy(error)
- this.emit('terminated', error)
- }
-}
+/***/ }),
-// https://fetch.spec.whatwg.org/#fetch-method
-function fetch (input, init = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
+/***/ 29218:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 1. Let p be a new promise.
- const p = createDeferredPromise()
+const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(68031)
+const kPool = Symbol('pool')
- // 2. Let requestObject be the result of invoking the initial value of
- // Request as constructor with input and init as arguments. If this throws
- // an exception, reject p with it and return p.
- let requestObject
+class PoolStats {
+ constructor (pool) {
+ this[kPool] = pool
+ }
- try {
- requestObject = new Request(input, init)
- } catch (e) {
- p.reject(e)
- return p.promise
+ get connected () {
+ return this[kPool][kConnected]
}
- // 3. Let request be requestObject’s request.
- const request = requestObject[kState]
+ get free () {
+ return this[kPool][kFree]
+ }
- // 4. If requestObject’s signal’s aborted flag is set, then:
- if (requestObject.signal.aborted) {
- // 1. Abort the fetch() call with p, request, null, and
- // requestObject’s signal’s abort reason.
- abortFetch(p, request, null, requestObject.signal.reason)
+ get pending () {
+ return this[kPool][kPending]
+ }
- // 2. Return p.
- return p.promise
+ get queued () {
+ return this[kPool][kQueued]
}
- // 5. Let globalObject be request’s client’s global object.
- const globalObject = request.client.globalObject
+ get running () {
+ return this[kPool][kRunning]
+ }
- // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
- // request’s service-workers mode to "none".
- if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
- request.serviceWorkers = 'none'
+ get size () {
+ return this[kPool][kSize]
}
+}
- // 7. Let responseObject be null.
- let responseObject = null
+module.exports = PoolStats
- // 8. Let relevantRealm be this’s relevant Realm.
- const relevantRealm = null
- // 9. Let locallyAborted be false.
- let locallyAborted = false
+/***/ }),
- // 10. Let controller be null.
- let controller = null
+/***/ 44288:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 11. Add the following abort steps to requestObject’s signal:
- addAbortListener(
- requestObject.signal,
- () => {
- // 1. Set locallyAborted to true.
- locallyAborted = true
- // 2. Assert: controller is non-null.
- assert(controller != null)
- // 3. Abort controller with requestObject’s signal’s abort reason.
- controller.abort(requestObject.signal.reason)
+const {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kGetDispatcher
+} = __nccwpck_require__(18804)
+const Client = __nccwpck_require__(45513)
+const {
+ InvalidArgumentError
+} = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { kUrl, kInterceptors } = __nccwpck_require__(68031)
+const buildConnector = __nccwpck_require__(91332)
- // 4. Abort the fetch() call with p, request, responseObject,
- // and requestObject’s signal’s abort reason.
- abortFetch(p, request, responseObject, requestObject.signal.reason)
- }
- )
+const kOptions = Symbol('options')
+const kConnections = Symbol('connections')
+const kFactory = Symbol('factory')
- // 12. Let handleFetchDone given response response be to finalize and
- // report timing with response, globalObject, and "fetch".
- const handleFetchDone = (response) =>
- finalizeAndReportTiming(response, 'fetch')
+function defaultFactory (origin, opts) {
+ return new Client(origin, opts)
+}
- // 13. Set controller to the result of calling fetch given request,
- // with processResponseEndOfBody set to handleFetchDone, and processResponse
- // given response being these substeps:
+class Pool extends PoolBase {
+ constructor (origin, {
+ connections,
+ factory = defaultFactory,
+ connect,
+ connectTimeout,
+ tls,
+ maxCachedSessions,
+ socketPath,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ allowH2,
+ ...options
+ } = {}) {
+ super()
- const processResponse = (response) => {
- // 1. If locallyAborted is true, terminate these substeps.
- if (locallyAborted) {
- return Promise.resolve()
+ if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
+ throw new InvalidArgumentError('invalid connections')
}
- // 2. If response’s aborted flag is set, then:
- if (response.aborted) {
- // 1. Let deserializedError be the result of deserialize a serialized
- // abort reason given controller’s serialized abort reason and
- // relevantRealm.
-
- // 2. Abort the fetch() call with p, request, responseObject, and
- // deserializedError.
-
- abortFetch(p, request, responseObject, controller.serializedAbortReason)
- return Promise.resolve()
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
}
- // 3. If response is a network error, then reject p with a TypeError
- // and terminate these substeps.
- if (response.type === 'error') {
- p.reject(
- Object.assign(new TypeError('fetch failed'), { cause: response.error })
- )
- return Promise.resolve()
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
}
- // 4. Set responseObject to the result of creating a Response object,
- // given response, "immutable", and relevantRealm.
- responseObject = new Response()
- responseObject[kState] = response
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kHeadersList] = response.headersList
- responseObject[kHeaders][kGuard] = 'immutable'
- responseObject[kHeaders][kRealm] = relevantRealm
+ if (typeof connect !== 'function') {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
+ ...connect
+ })
+ }
- // 5. Resolve p with responseObject.
- p.resolve(responseObject)
+ this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)
+ ? options.interceptors.Pool
+ : []
+ this[kConnections] = connections || null
+ this[kUrl] = util.parseOrigin(origin)
+ this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
+ this[kOptions].interceptors = options.interceptors
+ ? { ...options.interceptors }
+ : undefined
+ this[kFactory] = factory
}
- controller = fetching({
- request,
- processResponseEndOfBody: handleFetchDone,
- processResponse,
- dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
- })
+ [kGetDispatcher] () {
+ let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])
- // 14. Return p.
- return p.promise
-}
+ if (dispatcher) {
+ return dispatcher
+ }
-// https://fetch.spec.whatwg.org/#finalize-and-report-timing
-function finalizeAndReportTiming (response, initiatorType = 'other') {
- // 1. If response is an aborted network error, then return.
- if (response.type === 'error' && response.aborted) {
- return
- }
+ if (!this[kConnections] || this[kClients].length < this[kConnections]) {
+ dispatcher = this[kFactory](this[kUrl], this[kOptions])
+ this[kAddClient](dispatcher)
+ }
- // 2. If response’s URL list is null or empty, then return.
- if (!response.urlList?.length) {
- return
+ return dispatcher
}
+}
- // 3. Let originalURL be response’s URL list[0].
- const originalURL = response.urlList[0]
-
- // 4. Let timingInfo be response’s timing info.
- let timingInfo = response.timingInfo
-
- // 5. Let cacheState be response’s cache state.
- let cacheState = response.cacheState
+module.exports = Pool
- // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
- if (!urlIsHttpHttpsScheme(originalURL)) {
- return
- }
- // 7. If timingInfo is null, then return.
- if (timingInfo === null) {
- return
- }
+/***/ }),
- // 8. If response’s timing allow passed flag is not set, then:
- if (!response.timingAllowPassed) {
- // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
- timingInfo = createOpaqueTimingInfo({
- startTime: timingInfo.startTime
- })
+/***/ 79276:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Set cacheState to the empty string.
- cacheState = ''
- }
- // 9. Set timingInfo’s end time to the coarsened shared current time
- // given global’s relevant settings object’s cross-origin isolated
- // capability.
- // TODO: given global’s relevant settings object’s cross-origin isolated
- // capability?
- timingInfo.endTime = coarsenedSharedCurrentTime()
- // 10. Set response’s timing info to timingInfo.
- response.timingInfo = timingInfo
+const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(68031)
+const { URL } = __nccwpck_require__(87016)
+const Agent = __nccwpck_require__(92121)
+const Pool = __nccwpck_require__(44288)
+const DispatcherBase = __nccwpck_require__(52421)
+const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(53959)
+const buildConnector = __nccwpck_require__(91332)
- // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
- // global, and cacheState.
- markResourceTiming(
- timingInfo,
- originalURL,
- initiatorType,
- globalThis,
- cacheState
- )
-}
+const kAgent = Symbol('proxy agent')
+const kClient = Symbol('proxy client')
+const kProxyHeaders = Symbol('proxy headers')
+const kRequestTls = Symbol('request tls settings')
+const kProxyTls = Symbol('proxy tls settings')
+const kConnectEndpoint = Symbol('connect endpoint function')
-// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
-function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {
- if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {
- performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)
- }
+function defaultProtocolPort (protocol) {
+ return protocol === 'https:' ? 443 : 80
}
-// https://fetch.spec.whatwg.org/#abort-fetch
-function abortFetch (p, request, responseObject, error) {
- // Note: AbortSignal.reason was added in node v17.2.0
- // which would give us an undefined error to reject with.
- // Remove this once node v16 is no longer supported.
- if (!error) {
- error = new DOMException('The operation was aborted.', 'AbortError')
- }
-
- // 1. Reject promise with error.
- p.reject(error)
-
- // 2. If request’s body is not null and is readable, then cancel request’s
- // body with error.
- if (request.body != null && isReadable(request.body?.stream)) {
- request.body.stream.cancel(error).catch((err) => {
- if (err.code === 'ERR_INVALID_STATE') {
- // Node bug?
- return
- }
- throw err
- })
+function buildProxyOptions (opts) {
+ if (typeof opts === 'string') {
+ opts = { uri: opts }
}
- // 3. If responseObject is null, then return.
- if (responseObject == null) {
- return
+ if (!opts || !opts.uri) {
+ throw new InvalidArgumentError('Proxy opts.uri is mandatory')
}
- // 4. Let response be responseObject’s response.
- const response = responseObject[kState]
-
- // 5. If response’s body is not null and is readable, then error response’s
- // body with error.
- if (response.body != null && isReadable(response.body?.stream)) {
- response.body.stream.cancel(error).catch((err) => {
- if (err.code === 'ERR_INVALID_STATE') {
- // Node bug?
- return
- }
- throw err
- })
+ return {
+ uri: opts.uri,
+ protocol: opts.protocol || 'https'
}
}
-// https://fetch.spec.whatwg.org/#fetching
-function fetching ({
- request,
- processRequestBodyChunkLength,
- processRequestEndOfBody,
- processResponse,
- processResponseEndOfBody,
- processResponseConsumeBody,
- useParallelQueue = false,
- dispatcher // undici
-}) {
- // 1. Let taskDestination be null.
- let taskDestination = null
-
- // 2. Let crossOriginIsolatedCapability be false.
- let crossOriginIsolatedCapability = false
-
- // 3. If request’s client is non-null, then:
- if (request.client != null) {
- // 1. Set taskDestination to request’s client’s global object.
- taskDestination = request.client.globalObject
-
- // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
- // isolated capability.
- crossOriginIsolatedCapability =
- request.client.crossOriginIsolatedCapability
- }
+function defaultFactory (origin, opts) {
+ return new Pool(origin, opts)
+}
- // 4. If useParallelQueue is true, then set taskDestination to the result of
- // starting a new parallel queue.
- // TODO
+class ProxyAgent extends DispatcherBase {
+ constructor (opts) {
+ super(opts)
+ this[kProxy] = buildProxyOptions(opts)
+ this[kAgent] = new Agent(opts)
+ this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
+ ? opts.interceptors.ProxyAgent
+ : []
- // 5. Let timingInfo be a new fetch timing info whose start time and
- // post-redirect start time are the coarsened shared current time given
- // crossOriginIsolatedCapability.
- const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
- const timingInfo = createOpaqueTimingInfo({
- startTime: currenTime
- })
+ if (typeof opts === 'string') {
+ opts = { uri: opts }
+ }
- // 6. Let fetchParams be a new fetch params whose
- // request is request,
- // timing info is timingInfo,
- // process request body chunk length is processRequestBodyChunkLength,
- // process request end-of-body is processRequestEndOfBody,
- // process response is processResponse,
- // process response consume body is processResponseConsumeBody,
- // process response end-of-body is processResponseEndOfBody,
- // task destination is taskDestination,
- // and cross-origin isolated capability is crossOriginIsolatedCapability.
- const fetchParams = {
- controller: new Fetch(dispatcher),
- request,
- timingInfo,
- processRequestBodyChunkLength,
- processRequestEndOfBody,
- processResponse,
- processResponseConsumeBody,
- processResponseEndOfBody,
- taskDestination,
- crossOriginIsolatedCapability
- }
+ if (!opts || !opts.uri) {
+ throw new InvalidArgumentError('Proxy opts.uri is mandatory')
+ }
- // 7. If request’s body is a byte sequence, then set request’s body to
- // request’s body as a body.
- // NOTE: Since fetching is only called from fetch, body should already be
- // extracted.
- assert(!request.body || request.body.stream)
+ const { clientFactory = defaultFactory } = opts
- // 8. If request’s window is "client", then set request’s window to request’s
- // client, if request’s client’s global object is a Window object; otherwise
- // "no-window".
- if (request.window === 'client') {
- // TODO: What if request.client is null?
- request.window =
- request.client?.globalObject?.constructor?.name === 'Window'
- ? request.client
- : 'no-window'
- }
+ if (typeof clientFactory !== 'function') {
+ throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
+ }
- // 9. If request’s origin is "client", then set request’s origin to request’s
- // client’s origin.
- if (request.origin === 'client') {
- // TODO: What if request.client is null?
- request.origin = request.client?.origin
- }
+ this[kRequestTls] = opts.requestTls
+ this[kProxyTls] = opts.proxyTls
+ this[kProxyHeaders] = opts.headers || {}
- // 10. If all of the following conditions are true:
- // TODO
+ const resolvedUrl = new URL(opts.uri)
+ const { origin, port, host, username, password } = resolvedUrl
- // 11. If request’s policy container is "client", then:
- if (request.policyContainer === 'client') {
- // 1. If request’s client is non-null, then set request’s policy
- // container to a clone of request’s client’s policy container. [HTML]
- if (request.client != null) {
- request.policyContainer = clonePolicyContainer(
- request.client.policyContainer
- )
- } else {
- // 2. Otherwise, set request’s policy container to a new policy
- // container.
- request.policyContainer = makePolicyContainer()
+ if (opts.auth && opts.token) {
+ throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
+ } else if (opts.auth) {
+ /* @deprecated in favour of opts.token */
+ this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
+ } else if (opts.token) {
+ this[kProxyHeaders]['proxy-authorization'] = opts.token
+ } else if (username && password) {
+ this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
}
- }
-
- // 12. If request’s header list does not contain `Accept`, then:
- if (!request.headersList.contains('accept')) {
- // 1. Let value be `*/*`.
- const value = '*/*'
-
- // 2. A user agent should set value to the first matching statement, if
- // any, switching on request’s destination:
- // "document"
- // "frame"
- // "iframe"
- // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
- // "image"
- // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
- // "style"
- // `text/css,*/*;q=0.1`
- // TODO
- // 3. Append `Accept`/value to request’s header list.
- request.headersList.append('accept', value)
+ const connect = buildConnector({ ...opts.proxyTls })
+ this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
+ this[kClient] = clientFactory(resolvedUrl, { connect })
+ this[kAgent] = new Agent({
+ ...opts,
+ connect: async (opts, callback) => {
+ let requestedHost = opts.host
+ if (!opts.port) {
+ requestedHost += `:${defaultProtocolPort(opts.protocol)}`
+ }
+ try {
+ const { socket, statusCode } = await this[kClient].connect({
+ origin,
+ port,
+ path: requestedHost,
+ signal: opts.signal,
+ headers: {
+ ...this[kProxyHeaders],
+ host
+ }
+ })
+ if (statusCode !== 200) {
+ socket.on('error', () => {}).destroy()
+ callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
+ }
+ if (opts.protocol !== 'https:') {
+ callback(null, socket)
+ return
+ }
+ let servername
+ if (this[kRequestTls]) {
+ servername = this[kRequestTls].servername
+ } else {
+ servername = opts.servername
+ }
+ this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
+ } catch (err) {
+ callback(err)
+ }
+ }
+ })
}
- // 13. If request’s header list does not contain `Accept-Language`, then
- // user agents should append `Accept-Language`/an appropriate value to
- // request’s header list.
- if (!request.headersList.contains('accept-language')) {
- request.headersList.append('accept-language', '*')
+ dispatch (opts, handler) {
+ const { host } = new URL(opts.origin)
+ const headers = buildHeaders(opts.headers)
+ throwIfProxyAuthIsSent(headers)
+ return this[kAgent].dispatch(
+ {
+ ...opts,
+ headers: {
+ ...headers,
+ host
+ }
+ },
+ handler
+ )
}
- // 14. If request’s priority is null, then use request’s initiator and
- // destination appropriately in setting request’s priority to a
- // user-agent-defined object.
- if (request.priority === null) {
- // TODO
+ async [kClose] () {
+ await this[kAgent].close()
+ await this[kClient].close()
}
- // 15. If request is a subresource request, then:
- if (subresourceSet.has(request.destination)) {
- // TODO
+ async [kDestroy] () {
+ await this[kAgent].destroy()
+ await this[kClient].destroy()
}
-
- // 16. Run main fetch given fetchParams.
- mainFetch(fetchParams)
- .catch(err => {
- fetchParams.controller.terminate(err)
- })
-
- // 17. Return fetchParam's controller
- return fetchParams.controller
}
-// https://fetch.spec.whatwg.org/#concept-main-fetch
-async function mainFetch (fetchParams, recursive = false) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+/**
+ * @param {string[] | Record} headers
+ * @returns {Record}
+ */
+function buildHeaders (headers) {
+ // When using undici.fetch, the headers list is stored
+ // as an array.
+ if (Array.isArray(headers)) {
+ /** @type {Record} */
+ const headersPair = {}
- // 2. Let response be null.
- let response = null
+ for (let i = 0; i < headers.length; i += 2) {
+ headersPair[headers[i]] = headers[i + 1]
+ }
- // 3. If request’s local-URLs-only flag is set and request’s current URL is
- // not local, then set response to a network error.
- if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
- response = makeNetworkError('local URLs only')
+ return headersPair
}
- // 4. Run report Content Security Policy violations for request.
- // TODO
-
- // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
- tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
+ return headers
+}
- // 6. If should request be blocked due to a bad port, should fetching request
- // be blocked as mixed content, or should request be blocked by Content
- // Security Policy returns blocked, then set response to a network error.
- if (requestBadPort(request) === 'blocked') {
- response = makeNetworkError('bad port')
+/**
+ * @param {Record} headers
+ *
+ * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
+ * Nevertheless, it was changed and to avoid a security vulnerability by end users
+ * this check was created.
+ * It should be removed in the next major version for performance reasons
+ */
+function throwIfProxyAuthIsSent (headers) {
+ const existProxyAuth = headers && Object.keys(headers)
+ .find((key) => key.toLowerCase() === 'proxy-authorization')
+ if (existProxyAuth) {
+ throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
}
- // TODO: should fetching request be blocked as mixed content?
- // TODO: should request be blocked by Content Security Policy?
+}
- // 7. If request’s referrer policy is the empty string, then set request’s
- // referrer policy to request’s policy container’s referrer policy.
- if (request.referrerPolicy === '') {
- request.referrerPolicy = request.policyContainer.referrerPolicy
- }
+module.exports = ProxyAgent
- // 8. If request’s referrer is not "no-referrer", then set request’s
- // referrer to the result of invoking determine request’s referrer.
- if (request.referrer !== 'no-referrer') {
- request.referrer = determineRequestsReferrer(request)
- }
- // 9. Set request’s current URL’s scheme to "https" if all of the following
- // conditions are true:
- // - request’s current URL’s scheme is "http"
- // - request’s current URL’s host is a domain
- // - Matching request’s current URL’s host per Known HSTS Host Domain Name
- // Matching results in either a superdomain match with an asserted
- // includeSubDomains directive or a congruent match (with or without an
- // asserted includeSubDomains directive). [HSTS]
- // TODO
+/***/ }),
- // 10. If recursive is false, then run the remaining steps in parallel.
- // TODO
+/***/ 82576:
+/***/ ((module) => {
- // 11. If response is null, then set response to the result of running
- // the steps corresponding to the first matching statement:
- if (response === null) {
- response = await (async () => {
- const currentURL = requestCurrentURL(request)
- if (
- // - request’s current URL’s origin is same origin with request’s origin,
- // and request’s response tainting is "basic"
- (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
- // request’s current URL’s scheme is "data"
- (currentURL.protocol === 'data:') ||
- // - request’s mode is "navigate" or "websocket"
- (request.mode === 'navigate' || request.mode === 'websocket')
- ) {
- // 1. Set request’s response tainting to "basic".
- request.responseTainting = 'basic'
- // 2. Return the result of running scheme fetch given fetchParams.
- return await schemeFetch(fetchParams)
- }
+let fastNow = Date.now()
+let fastNowTimeout
- // request’s mode is "same-origin"
- if (request.mode === 'same-origin') {
- // 1. Return a network error.
- return makeNetworkError('request mode cannot be "same-origin"')
- }
+const fastTimers = []
- // request’s mode is "no-cors"
- if (request.mode === 'no-cors') {
- // 1. If request’s redirect mode is not "follow", then return a network
- // error.
- if (request.redirect !== 'follow') {
- return makeNetworkError(
- 'redirect mode cannot be "follow" for "no-cors" request'
- )
- }
+function onTimeout () {
+ fastNow = Date.now()
- // 2. Set request’s response tainting to "opaque".
- request.responseTainting = 'opaque'
+ let len = fastTimers.length
+ let idx = 0
+ while (idx < len) {
+ const timer = fastTimers[idx]
- // 3. Return the result of running scheme fetch given fetchParams.
- return await schemeFetch(fetchParams)
- }
+ if (timer.state === 0) {
+ timer.state = fastNow + timer.delay
+ } else if (timer.state > 0 && fastNow >= timer.state) {
+ timer.state = -1
+ timer.callback(timer.opaque)
+ }
- // request’s current URL’s scheme is not an HTTP(S) scheme
- if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
- // Return a network error.
- return makeNetworkError('URL scheme must be a HTTP(S) scheme')
+ if (timer.state === -1) {
+ timer.state = -2
+ if (idx !== len - 1) {
+ fastTimers[idx] = fastTimers.pop()
+ } else {
+ fastTimers.pop()
}
+ len -= 1
+ } else {
+ idx += 1
+ }
+ }
- // - request’s use-CORS-preflight flag is set
- // - request’s unsafe-request flag is set and either request’s method is
- // not a CORS-safelisted method or CORS-unsafe request-header names with
- // request’s header list is not empty
- // 1. Set request’s response tainting to "cors".
- // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
- // given fetchParams and true.
- // 3. If corsWithPreflightResponse is a network error, then clear cache
- // entries using request.
- // 4. Return corsWithPreflightResponse.
- // TODO
-
- // Otherwise
- // 1. Set request’s response tainting to "cors".
- request.responseTainting = 'cors'
+ if (fastTimers.length > 0) {
+ refreshTimeout()
+ }
+}
- // 2. Return the result of running HTTP fetch given fetchParams.
- return await httpFetch(fetchParams)
- })()
+function refreshTimeout () {
+ if (fastNowTimeout && fastNowTimeout.refresh) {
+ fastNowTimeout.refresh()
+ } else {
+ clearTimeout(fastNowTimeout)
+ fastNowTimeout = setTimeout(onTimeout, 1e3)
+ if (fastNowTimeout.unref) {
+ fastNowTimeout.unref()
+ }
}
+}
- // 12. If recursive is true, then return response.
- if (recursive) {
- return response
+class Timeout {
+ constructor (callback, delay, opaque) {
+ this.callback = callback
+ this.delay = delay
+ this.opaque = opaque
+
+ // -2 not in timer list
+ // -1 in timer list but inactive
+ // 0 in timer list waiting for time
+ // > 0 in timer list waiting for time to expire
+ this.state = -2
+
+ this.refresh()
}
- // 13. If response is not a network error and response is not a filtered
- // response, then:
- if (response.status !== 0 && !response.internalResponse) {
- // If request’s response tainting is "cors", then:
- if (request.responseTainting === 'cors') {
- // 1. Let headerNames be the result of extracting header list values
- // given `Access-Control-Expose-Headers` and response’s header list.
- // TODO
- // 2. If request’s credentials mode is not "include" and headerNames
- // contains `*`, then set response’s CORS-exposed header-name list to
- // all unique header names in response’s header list.
- // TODO
- // 3. Otherwise, if headerNames is not null or failure, then set
- // response’s CORS-exposed header-name list to headerNames.
- // TODO
+ refresh () {
+ if (this.state === -2) {
+ fastTimers.push(this)
+ if (!fastNowTimeout || fastTimers.length === 1) {
+ refreshTimeout()
+ }
}
- // Set response to the following filtered response with response as its
- // internal response, depending on request’s response tainting:
- if (request.responseTainting === 'basic') {
- response = filterResponse(response, 'basic')
- } else if (request.responseTainting === 'cors') {
- response = filterResponse(response, 'cors')
- } else if (request.responseTainting === 'opaque') {
- response = filterResponse(response, 'opaque')
+ this.state = 0
+ }
+
+ clear () {
+ this.state = -1
+ }
+}
+
+module.exports = {
+ setTimeout (callback, delay, opaque) {
+ return delay < 1e3
+ ? setTimeout(callback, delay, opaque)
+ : new Timeout(callback, delay, opaque)
+ },
+ clearTimeout (timeout) {
+ if (timeout instanceof Timeout) {
+ timeout.clear()
} else {
- assert(false)
+ clearTimeout(timeout)
}
}
+}
- // 14. Let internalResponse be response, if response is a network error,
- // and response’s internal response otherwise.
- let internalResponse =
- response.status === 0 ? response : response.internalResponse
- // 15. If internalResponse’s URL list is empty, then set it to a clone of
- // request’s URL list.
- if (internalResponse.urlList.length === 0) {
- internalResponse.urlList.push(...request.urlList)
- }
+/***/ }),
- // 16. If request’s timing allow failed flag is unset, then set
- // internalResponse’s timing allow passed flag.
- if (!request.timingAllowFailed) {
- response.timingAllowPassed = true
- }
+/***/ 96114:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 17. If response is not a network error and any of the following returns
- // blocked
- // - should internalResponse to request be blocked as mixed content
- // - should internalResponse to request be blocked by Content Security Policy
- // - should internalResponse to request be blocked due to its MIME type
- // - should internalResponse to request be blocked due to nosniff
- // TODO
- // 18. If response’s type is "opaque", internalResponse’s status is 206,
- // internalResponse’s range-requested flag is set, and request’s header
- // list does not contain `Range`, then set response and internalResponse
- // to a network error.
- if (
- response.type === 'opaque' &&
- internalResponse.status === 206 &&
- internalResponse.rangeRequested &&
- !request.headers.contains('range')
- ) {
- response = internalResponse = makeNetworkError()
- }
- // 19. If response is not a network error and either request’s method is
- // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
- // set internalResponse’s body to null and disregard any enqueuing toward
- // it (if any).
- if (
- response.status !== 0 &&
- (request.method === 'HEAD' ||
- request.method === 'CONNECT' ||
- nullBodyStatus.includes(internalResponse.status))
- ) {
- internalResponse.body = null
- fetchParams.controller.dump = true
- }
+const diagnosticsChannel = __nccwpck_require__(31637)
+const { uid, states } = __nccwpck_require__(90077)
+const {
+ kReadyState,
+ kSentClose,
+ kByteParser,
+ kReceivedClose
+} = __nccwpck_require__(97945)
+const { fireEvent, failWebsocketConnection } = __nccwpck_require__(95506)
+const { CloseEvent } = __nccwpck_require__(47115)
+const { makeRequest } = __nccwpck_require__(2630)
+const { fetching } = __nccwpck_require__(11503)
+const { Headers } = __nccwpck_require__(12801)
+const { getGlobalDispatcher } = __nccwpck_require__(61481)
+const { kHeadersList } = __nccwpck_require__(68031)
- // 20. If request’s integrity metadata is not the empty string, then:
- if (request.integrity) {
- // 1. Let processBodyError be this step: run fetch finale given fetchParams
- // and a network error.
- const processBodyError = (reason) =>
- fetchFinale(fetchParams, makeNetworkError(reason))
+const channels = {}
+channels.open = diagnosticsChannel.channel('undici:websocket:open')
+channels.close = diagnosticsChannel.channel('undici:websocket:close')
+channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')
- // 2. If request’s response tainting is "opaque", or response’s body is null,
- // then run processBodyError and abort these steps.
- if (request.responseTainting === 'opaque' || response.body == null) {
- processBodyError(response.error)
- return
- }
+/** @type {import('crypto')} */
+let crypto
+try {
+ crypto = __nccwpck_require__(76982)
+} catch {
- // 3. Let processBody given bytes be these steps:
- const processBody = (bytes) => {
- // 1. If bytes do not match request’s integrity metadata,
- // then run processBodyError and abort these steps. [SRI]
- if (!bytesMatch(bytes, request.integrity)) {
- processBodyError('integrity mismatch')
- return
- }
+}
- // 2. Set response’s body to bytes as a body.
- response.body = safelyExtractBody(bytes)[0]
+/**
+ * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
+ * @param {URL} url
+ * @param {string|string[]} protocols
+ * @param {import('./websocket').WebSocket} ws
+ * @param {(response: any) => void} onEstablish
+ * @param {Partial} options
+ */
+function establishWebSocketConnection (url, protocols, ws, onEstablish, options) {
+ // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s
+ // scheme is "ws", and to "https" otherwise.
+ const requestURL = url
- // 3. Run fetch finale given fetchParams and response.
- fetchFinale(fetchParams, response)
- }
+ requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
- // 4. Fully read response’s body given processBody and processBodyError.
- await fullyReadBody(response.body, processBody, processBodyError)
- } else {
- // 21. Otherwise, run fetch finale given fetchParams and response.
- fetchFinale(fetchParams, response)
+ // 2. Let request be a new request, whose URL is requestURL, client is client,
+ // service-workers mode is "none", referrer is "no-referrer", mode is
+ // "websocket", credentials mode is "include", cache mode is "no-store" ,
+ // and redirect mode is "error".
+ const request = makeRequest({
+ urlList: [requestURL],
+ serviceWorkers: 'none',
+ referrer: 'no-referrer',
+ mode: 'websocket',
+ credentials: 'include',
+ cache: 'no-store',
+ redirect: 'error'
+ })
+
+ // Note: undici extension, allow setting custom headers.
+ if (options.headers) {
+ const headersList = new Headers(options.headers)[kHeadersList]
+
+ request.headersList = headersList
}
-}
-// https://fetch.spec.whatwg.org/#concept-scheme-fetch
-// given a fetch params fetchParams
-function schemeFetch (fetchParams) {
- // Note: since the connection is destroyed on redirect, which sets fetchParams to a
- // cancelled state, we do not want this condition to trigger *unless* there have been
- // no redirects. See https://github.com/nodejs/undici/issues/1776
- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
- return Promise.resolve(makeAppropriateNetworkError(fetchParams))
+ // 3. Append (`Upgrade`, `websocket`) to request’s header list.
+ // 4. Append (`Connection`, `Upgrade`) to request’s header list.
+ // Note: both of these are handled by undici currently.
+ // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
+
+ // 5. Let keyValue be a nonce consisting of a randomly selected
+ // 16-byte value that has been forgiving-base64-encoded and
+ // isomorphic encoded.
+ const keyValue = crypto.randomBytes(16).toString('base64')
+
+ // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
+ // header list.
+ request.headersList.append('sec-websocket-key', keyValue)
+
+ // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
+ // header list.
+ request.headersList.append('sec-websocket-version', '13')
+
+ // 8. For each protocol in protocols, combine
+ // (`Sec-WebSocket-Protocol`, protocol) in request’s header
+ // list.
+ for (const protocol of protocols) {
+ request.headersList.append('sec-websocket-protocol', protocol)
}
- // 2. Let request be fetchParams’s request.
- const { request } = fetchParams
+ // 9. Let permessageDeflate be a user-agent defined
+ // "permessage-deflate" extension header value.
+ // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
+ // TODO: enable once permessage-deflate is supported
+ const permessageDeflate = '' // 'permessage-deflate; 15'
- const { protocol: scheme } = requestCurrentURL(request)
+ // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
+ // request’s header list.
+ // request.headersList.append('sec-websocket-extensions', permessageDeflate)
- // 3. Switch on request’s current URL’s scheme and run the associated steps:
- switch (scheme) {
- case 'about:': {
- // If request’s current URL’s path is the string "blank", then return a new response
- // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
- // and body is the empty byte sequence as a body.
+ // 11. Fetch request with useParallelQueue set to true, and
+ // processResponse given response being these steps:
+ const controller = fetching({
+ request,
+ useParallelQueue: true,
+ dispatcher: options.dispatcher ?? getGlobalDispatcher(),
+ processResponse (response) {
+ // 1. If response is a network error or its status is not 101,
+ // fail the WebSocket connection.
+ if (response.type === 'error' || response.status !== 101) {
+ failWebsocketConnection(ws, 'Received network error or non-101 status code.')
+ return
+ }
- // Otherwise, return a network error.
- return Promise.resolve(makeNetworkError('about scheme is not supported'))
- }
- case 'blob:': {
- if (!resolveObjectURL) {
- resolveObjectURL = (__nccwpck_require__(20181).resolveObjectURL)
+ // 2. If protocols is not the empty list and extracting header
+ // list values given `Sec-WebSocket-Protocol` and response’s
+ // header list results in null, failure, or the empty byte
+ // sequence, then fail the WebSocket connection.
+ if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
+ failWebsocketConnection(ws, 'Server did not respond with sent protocols.')
+ return
}
- // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
- const blobURLEntry = requestCurrentURL(request)
+ // 3. Follow the requirements stated step 2 to step 6, inclusive,
+ // of the last set of steps in section 4.1 of The WebSocket
+ // Protocol to validate response. This either results in fail
+ // the WebSocket connection or the WebSocket connection is
+ // established.
- // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
- // Buffer.resolveObjectURL does not ignore URL queries.
- if (blobURLEntry.search.length !== 0) {
- return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
+ // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
+ // header field contains a value that is not an ASCII case-
+ // insensitive match for the value "websocket", the client MUST
+ // _Fail the WebSocket Connection_.
+ if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
+ failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".')
+ return
}
- const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())
-
- // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
- // object is not a Blob object, then return a network error.
- if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {
- return Promise.resolve(makeNetworkError('invalid method'))
+ // 3. If the response lacks a |Connection| header field or the
+ // |Connection| header field doesn't contain a token that is an
+ // ASCII case-insensitive match for the value "Upgrade", the client
+ // MUST _Fail the WebSocket Connection_.
+ if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
+ failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".')
+ return
}
- // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.
- const bodyWithType = safelyExtractBody(blobURLEntryObject)
-
- // 4. Let body be bodyWithType’s body.
- const body = bodyWithType[0]
+ // 4. If the response lacks a |Sec-WebSocket-Accept| header field or
+ // the |Sec-WebSocket-Accept| contains a value other than the
+ // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
+ // Key| (as a string, not base64-decoded) with the string "258EAFA5-
+ // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
+ // trailing whitespace, the client MUST _Fail the WebSocket
+ // Connection_.
+ const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
+ const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
+ if (secWSAccept !== digest) {
+ failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
+ return
+ }
- // 5. Let length be body’s length, serialized and isomorphic encoded.
- const length = isomorphicEncode(`${body.length}`)
+ // 5. If the response includes a |Sec-WebSocket-Extensions| header
+ // field and this header field indicates the use of an extension
+ // that was not present in the client's handshake (the server has
+ // indicated an extension not requested by the client), the client
+ // MUST _Fail the WebSocket Connection_. (The parsing of this
+ // header field to determine which extensions are requested is
+ // discussed in Section 9.1.)
+ const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
- // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.
- const type = bodyWithType[1] ?? ''
+ if (secExtension !== null && secExtension !== permessageDeflate) {
+ failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')
+ return
+ }
- // 7. Return a new response whose status message is `OK`, header list is
- // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.
- const response = makeResponse({
- statusText: 'OK',
- headersList: [
- ['content-length', { name: 'Content-Length', value: length }],
- ['content-type', { name: 'Content-Type', value: type }]
- ]
- })
+ // 6. If the response includes a |Sec-WebSocket-Protocol| header field
+ // and this header field indicates the use of a subprotocol that was
+ // not present in the client's handshake (the server has indicated a
+ // subprotocol not requested by the client), the client MUST _Fail
+ // the WebSocket Connection_.
+ const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
- response.body = body
+ if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {
+ failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
+ return
+ }
- return Promise.resolve(response)
- }
- case 'data:': {
- // 1. Let dataURLStruct be the result of running the
- // data: URL processor on request’s current URL.
- const currentURL = requestCurrentURL(request)
- const dataURLStruct = dataURLProcessor(currentURL)
+ response.socket.on('data', onSocketData)
+ response.socket.on('close', onSocketClose)
+ response.socket.on('error', onSocketError)
- // 2. If dataURLStruct is failure, then return a
- // network error.
- if (dataURLStruct === 'failure') {
- return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
+ if (channels.open.hasSubscribers) {
+ channels.open.publish({
+ address: response.socket.address(),
+ protocol: secProtocol,
+ extensions: secExtension
+ })
}
- // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
- const mimeType = serializeAMimeType(dataURLStruct.mimeType)
-
- // 4. Return a response whose status message is `OK`,
- // header list is « (`Content-Type`, mimeType) »,
- // and body is dataURLStruct’s body as a body.
- return Promise.resolve(makeResponse({
- statusText: 'OK',
- headersList: [
- ['content-type', { name: 'Content-Type', value: mimeType }]
- ],
- body: safelyExtractBody(dataURLStruct.body)[0]
- }))
- }
- case 'file:': {
- // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
- // When in doubt, return a network error.
- return Promise.resolve(makeNetworkError('not implemented... yet...'))
+ onEstablish(response)
}
- case 'http:':
- case 'https:': {
- // Return the result of running HTTP fetch given fetchParams.
+ })
- return httpFetch(fetchParams)
- .catch((err) => makeNetworkError(err))
- }
- default: {
- return Promise.resolve(makeNetworkError('unknown scheme'))
- }
- }
+ return controller
}
-// https://fetch.spec.whatwg.org/#finalize-response
-function finalizeResponse (fetchParams, response) {
- // 1. Set fetchParams’s request’s done flag.
- fetchParams.request.done = true
-
- // 2, If fetchParams’s process response done is not null, then queue a fetch
- // task to run fetchParams’s process response done given response, with
- // fetchParams’s task destination.
- if (fetchParams.processResponseDone != null) {
- queueMicrotask(() => fetchParams.processResponseDone(response))
+/**
+ * @param {Buffer} chunk
+ */
+function onSocketData (chunk) {
+ if (!this.ws[kByteParser].write(chunk)) {
+ this.pause()
}
}
-// https://fetch.spec.whatwg.org/#fetch-finale
-function fetchFinale (fetchParams, response) {
- // 1. If response is a network error, then:
- if (response.type === 'error') {
- // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».
- response.urlList = [fetchParams.request.urlList[0]]
+/**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
+ */
+function onSocketClose () {
+ const { ws } = this
- // 2. Set response’s timing info to the result of creating an opaque timing
- // info for fetchParams’s timing info.
- response.timingInfo = createOpaqueTimingInfo({
- startTime: fetchParams.timingInfo.startTime
- })
- }
+ // If the TCP connection was closed after the
+ // WebSocket closing handshake was completed, the WebSocket connection
+ // is said to have been closed _cleanly_.
+ const wasClean = ws[kSentClose] && ws[kReceivedClose]
- // 2. Let processResponseEndOfBody be the following steps:
- const processResponseEndOfBody = () => {
- // 1. Set fetchParams’s request’s done flag.
- fetchParams.request.done = true
+ let code = 1005
+ let reason = ''
- // If fetchParams’s process response end-of-body is not null,
- // then queue a fetch task to run fetchParams’s process response
- // end-of-body given response with fetchParams’s task destination.
- if (fetchParams.processResponseEndOfBody != null) {
- queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
- }
- }
+ const result = ws[kByteParser].closingInfo
- // 3. If fetchParams’s process response is non-null, then queue a fetch task
- // to run fetchParams’s process response given response, with fetchParams’s
- // task destination.
- if (fetchParams.processResponse != null) {
- queueMicrotask(() => fetchParams.processResponse(response))
+ if (result) {
+ code = result.code ?? 1005
+ reason = result.reason
+ } else if (!ws[kSentClose]) {
+ // If _The WebSocket
+ // Connection is Closed_ and no Close control frame was received by the
+ // endpoint (such as could occur if the underlying transport connection
+ // is lost), _The WebSocket Connection Close Code_ is considered to be
+ // 1006.
+ code = 1006
}
- // 4. If response’s body is null, then run processResponseEndOfBody.
- if (response.body == null) {
- processResponseEndOfBody()
- } else {
- // 5. Otherwise:
+ // 1. Change the ready state to CLOSED (3).
+ ws[kReadyState] = states.CLOSED
- // 1. Let transformStream be a new a TransformStream.
+ // 2. If the user agent was required to fail the WebSocket
+ // connection, or if the WebSocket connection was closed
+ // after being flagged as full, fire an event named error
+ // at the WebSocket object.
+ // TODO
- // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,
- // enqueues chunk in transformStream.
- const identityTransformAlgorithm = (chunk, controller) => {
- controller.enqueue(chunk)
- }
+ // 3. Fire an event named close at the WebSocket object,
+ // using CloseEvent, with the wasClean attribute
+ // initialized to true if the connection closed cleanly
+ // and false otherwise, the code attribute initialized to
+ // the WebSocket connection close code, and the reason
+ // attribute initialized to the result of applying UTF-8
+ // decode without BOM to the WebSocket connection close
+ // reason.
+ fireEvent('close', ws, CloseEvent, {
+ wasClean, code, reason
+ })
- // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm
- // and flushAlgorithm set to processResponseEndOfBody.
- const transformStream = new TransformStream({
- start () {},
- transform: identityTransformAlgorithm,
- flush: processResponseEndOfBody
- }, {
- size () {
- return 1
- }
- }, {
- size () {
- return 1
- }
+ if (channels.close.hasSubscribers) {
+ channels.close.publish({
+ websocket: ws,
+ code,
+ reason
})
-
- // 4. Set response’s body to the result of piping response’s body through transformStream.
- response.body = { stream: response.body.stream.pipeThrough(transformStream) }
}
+}
- // 6. If fetchParams’s process response consume body is non-null, then:
- if (fetchParams.processResponseConsumeBody != null) {
- // 1. Let processBody given nullOrBytes be this step: run fetchParams’s
- // process response consume body given response and nullOrBytes.
- const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)
+function onSocketError (error) {
+ const { ws } = this
- // 2. Let processBodyError be this step: run fetchParams’s process
- // response consume body given response and failure.
- const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)
+ ws[kReadyState] = states.CLOSING
- // 3. If response’s body is null, then queue a fetch task to run processBody
- // given null, with fetchParams’s task destination.
- if (response.body == null) {
- queueMicrotask(() => processBody(null))
- } else {
- // 4. Otherwise, fully read response’s body given processBody, processBodyError,
- // and fetchParams’s task destination.
- return fullyReadBody(response.body, processBody, processBodyError)
- }
- return Promise.resolve()
+ if (channels.socketError.hasSubscribers) {
+ channels.socketError.publish(error)
}
-}
-// https://fetch.spec.whatwg.org/#http-fetch
-async function httpFetch (fetchParams) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+ this.destroy()
+}
- // 2. Let response be null.
- let response = null
+module.exports = {
+ establishWebSocketConnection
+}
- // 3. Let actualResponse be null.
- let actualResponse = null
- // 4. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
+/***/ }),
- // 5. If request’s service-workers mode is "all", then:
- if (request.serviceWorkers === 'all') {
- // TODO
- }
+/***/ 90077:
+/***/ ((module) => {
- // 6. If response is null, then:
- if (response === null) {
- // 1. If makeCORSPreflight is true and one of these conditions is true:
- // TODO
- // 2. If request’s redirect mode is "follow", then set request’s
- // service-workers mode to "none".
- if (request.redirect === 'follow') {
- request.serviceWorkers = 'none'
- }
- // 3. Set response and actualResponse to the result of running
- // HTTP-network-or-cache fetch given fetchParams.
- actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
+// This is a Globally Unique Identifier unique used
+// to validate that the endpoint accepts websocket
+// connections.
+// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3
+const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
- // 4. If request’s response tainting is "cors" and a CORS check
- // for request and response returns failure, then return a network error.
- if (
- request.responseTainting === 'cors' &&
- corsCheck(request, response) === 'failure'
- ) {
- return makeNetworkError('cors failure')
- }
+/** @type {PropertyDescriptor} */
+const staticPropertyDescriptors = {
+ enumerable: true,
+ writable: false,
+ configurable: false
+}
- // 5. If the TAO check for request and response returns failure, then set
- // request’s timing allow failed flag.
- if (TAOCheck(request, response) === 'failure') {
- request.timingAllowFailed = true
- }
- }
+const states = {
+ CONNECTING: 0,
+ OPEN: 1,
+ CLOSING: 2,
+ CLOSED: 3
+}
- // 7. If either request’s response tainting or response’s type
- // is "opaque", and the cross-origin resource policy check with
- // request’s origin, request’s client, request’s destination,
- // and actualResponse returns blocked, then return a network error.
- if (
- (request.responseTainting === 'opaque' || response.type === 'opaque') &&
- crossOriginResourcePolicyCheck(
- request.origin,
- request.client,
- request.destination,
- actualResponse
- ) === 'blocked'
- ) {
- return makeNetworkError('blocked')
- }
+const opcodes = {
+ CONTINUATION: 0x0,
+ TEXT: 0x1,
+ BINARY: 0x2,
+ CLOSE: 0x8,
+ PING: 0x9,
+ PONG: 0xA
+}
- // 8. If actualResponse’s status is a redirect status, then:
- if (redirectStatusSet.has(actualResponse.status)) {
- // 1. If actualResponse’s status is not 303, request’s body is not null,
- // and the connection uses HTTP/2, then user agents may, and are even
- // encouraged to, transmit an RST_STREAM frame.
- // See, https://github.com/whatwg/fetch/issues/1288
- if (request.redirect !== 'manual') {
- fetchParams.controller.connection.destroy()
- }
+const maxUnsigned16Bit = 2 ** 16 - 1 // 65535
- // 2. Switch on request’s redirect mode:
- if (request.redirect === 'error') {
- // Set response to a network error.
- response = makeNetworkError('unexpected redirect')
- } else if (request.redirect === 'manual') {
- // Set response to an opaque-redirect filtered response whose internal
- // response is actualResponse.
- // NOTE(spec): On the web this would return an `opaqueredirect` response,
- // but that doesn't make sense server side.
- // See https://github.com/nodejs/undici/issues/1193.
- response = actualResponse
- } else if (request.redirect === 'follow') {
- // Set response to the result of running HTTP-redirect fetch given
- // fetchParams and response.
- response = await httpRedirectFetch(fetchParams, response)
- } else {
- assert(false)
- }
- }
+const parserStates = {
+ INFO: 0,
+ PAYLOADLENGTH_16: 2,
+ PAYLOADLENGTH_64: 3,
+ READ_DATA: 4
+}
- // 9. Set response’s timing info to timingInfo.
- response.timingInfo = timingInfo
+const emptyBuffer = Buffer.allocUnsafe(0)
- // 10. Return response.
- return response
+module.exports = {
+ uid,
+ staticPropertyDescriptors,
+ states,
+ opcodes,
+ maxUnsigned16Bit,
+ parserStates,
+ emptyBuffer
}
-// https://fetch.spec.whatwg.org/#http-redirect-fetch
-function httpRedirectFetch (fetchParams, response) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
-
- // 2. Let actualResponse be response, if response is not a filtered response,
- // and response’s internal response otherwise.
- const actualResponse = response.internalResponse
- ? response.internalResponse
- : response
- // 3. Let locationURL be actualResponse’s location URL given request’s current
- // URL’s fragment.
- let locationURL
+/***/ }),
- try {
- locationURL = responseLocationURL(
- actualResponse,
- requestCurrentURL(request).hash
- )
+/***/ 47115:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 4. If locationURL is null, then return response.
- if (locationURL == null) {
- return response
- }
- } catch (err) {
- // 5. If locationURL is failure, then return a network error.
- return Promise.resolve(makeNetworkError(err))
- }
- // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
- // error.
- if (!urlIsHttpHttpsScheme(locationURL)) {
- return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
- }
- // 7. If request’s redirect count is 20, then return a network error.
- if (request.redirectCount === 20) {
- return Promise.resolve(makeNetworkError('redirect count exceeded'))
- }
+const { webidl } = __nccwpck_require__(94354)
+const { kEnumerableProperty } = __nccwpck_require__(89500)
+const { MessagePort } = __nccwpck_require__(28167)
- // 8. Increase request’s redirect count by 1.
- request.redirectCount += 1
+/**
+ * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
+ */
+class MessageEvent extends Event {
+ #eventInit
- // 9. If request’s mode is "cors", locationURL includes credentials, and
- // request’s origin is not same origin with locationURL’s origin, then return
- // a network error.
- if (
- request.mode === 'cors' &&
- (locationURL.username || locationURL.password) &&
- !sameOrigin(request, locationURL)
- ) {
- return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
- }
+ constructor (type, eventInitDict = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' })
- // 10. If request’s response tainting is "cors" and locationURL includes
- // credentials, then return a network error.
- if (
- request.responseTainting === 'cors' &&
- (locationURL.username || locationURL.password)
- ) {
- return Promise.resolve(makeNetworkError(
- 'URL cannot contain credentials for request mode "cors"'
- ))
- }
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.MessageEventInit(eventInitDict)
- // 11. If actualResponse’s status is not 303, request’s body is non-null,
- // and request’s body’s source is null, then return a network error.
- if (
- actualResponse.status !== 303 &&
- request.body != null &&
- request.body.source == null
- ) {
- return Promise.resolve(makeNetworkError())
- }
+ super(type, eventInitDict)
- // 12. If one of the following is true
- // - actualResponse’s status is 301 or 302 and request’s method is `POST`
- // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
- if (
- ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
- (actualResponse.status === 303 &&
- !GET_OR_HEAD.includes(request.method))
- ) {
- // then:
- // 1. Set request’s method to `GET` and request’s body to null.
- request.method = 'GET'
- request.body = null
+ this.#eventInit = eventInitDict
+ }
- // 2. For each headerName of request-body-header name, delete headerName from
- // request’s header list.
- for (const headerName of requestBodyHeader) {
- request.headersList.delete(headerName)
- }
+ get data () {
+ webidl.brandCheck(this, MessageEvent)
+
+ return this.#eventInit.data
}
- // 13. If request’s current URL’s origin is not same origin with locationURL’s
- // origin, then for each headerName of CORS non-wildcard request-header name,
- // delete headerName from request’s header list.
- if (!sameOrigin(requestCurrentURL(request), locationURL)) {
- // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
- request.headersList.delete('authorization')
+ get origin () {
+ webidl.brandCheck(this, MessageEvent)
- // https://fetch.spec.whatwg.org/#authentication-entries
- request.headersList.delete('proxy-authorization', true)
+ return this.#eventInit.origin
+ }
- // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
- request.headersList.delete('cookie')
- request.headersList.delete('host')
+ get lastEventId () {
+ webidl.brandCheck(this, MessageEvent)
+
+ return this.#eventInit.lastEventId
}
- // 14. If request’s body is non-null, then set request’s body to the first return
- // value of safely extracting request’s body’s source.
- if (request.body != null) {
- assert(request.body.source != null)
- request.body = safelyExtractBody(request.body.source)[0]
+ get source () {
+ webidl.brandCheck(this, MessageEvent)
+
+ return this.#eventInit.source
}
- // 15. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
+ get ports () {
+ webidl.brandCheck(this, MessageEvent)
- // 16. Set timingInfo’s redirect end time and post-redirect start time to the
- // coarsened shared current time given fetchParams’s cross-origin isolated
- // capability.
- timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
- coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
+ if (!Object.isFrozen(this.#eventInit.ports)) {
+ Object.freeze(this.#eventInit.ports)
+ }
- // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
- // redirect start time to timingInfo’s start time.
- if (timingInfo.redirectStartTime === 0) {
- timingInfo.redirectStartTime = timingInfo.startTime
+ return this.#eventInit.ports
}
- // 18. Append locationURL to request’s URL list.
- request.urlList.push(locationURL)
+ initMessageEvent (
+ type,
+ bubbles = false,
+ cancelable = false,
+ data = null,
+ origin = '',
+ lastEventId = '',
+ source = null,
+ ports = []
+ ) {
+ webidl.brandCheck(this, MessageEvent)
- // 19. Invoke set request’s referrer policy on redirect on request and
- // actualResponse.
- setRequestReferrerPolicyOnRedirect(request, actualResponse)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' })
- // 20. Return the result of running main fetch given fetchParams and true.
- return mainFetch(fetchParams, true)
+ return new MessageEvent(type, {
+ bubbles, cancelable, data, origin, lastEventId, source, ports
+ })
+ }
}
-// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
-async function httpNetworkOrCacheFetch (
- fetchParams,
- isAuthenticationFetch = false,
- isNewConnectionFetch = false
-) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
-
- // 2. Let httpFetchParams be null.
- let httpFetchParams = null
+/**
+ * @see https://websockets.spec.whatwg.org/#the-closeevent-interface
+ */
+class CloseEvent extends Event {
+ #eventInit
- // 3. Let httpRequest be null.
- let httpRequest = null
+ constructor (type, eventInitDict = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' })
- // 4. Let response be null.
- let response = null
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.CloseEventInit(eventInitDict)
- // 5. Let storedResponse be null.
- // TODO: cache
+ super(type, eventInitDict)
- // 6. Let httpCache be null.
- const httpCache = null
+ this.#eventInit = eventInitDict
+ }
- // 7. Let the revalidatingFlag be unset.
- const revalidatingFlag = false
+ get wasClean () {
+ webidl.brandCheck(this, CloseEvent)
- // 8. Run these steps, but abort when the ongoing fetch is terminated:
+ return this.#eventInit.wasClean
+ }
- // 1. If request’s window is "no-window" and request’s redirect mode is
- // "error", then set httpFetchParams to fetchParams and httpRequest to
- // request.
- if (request.window === 'no-window' && request.redirect === 'error') {
- httpFetchParams = fetchParams
- httpRequest = request
- } else {
- // Otherwise:
+ get code () {
+ webidl.brandCheck(this, CloseEvent)
- // 1. Set httpRequest to a clone of request.
- httpRequest = makeRequest(request)
+ return this.#eventInit.code
+ }
- // 2. Set httpFetchParams to a copy of fetchParams.
- httpFetchParams = { ...fetchParams }
+ get reason () {
+ webidl.brandCheck(this, CloseEvent)
- // 3. Set httpFetchParams’s request to httpRequest.
- httpFetchParams.request = httpRequest
+ return this.#eventInit.reason
}
+}
- // 3. Let includeCredentials be true if one of
- const includeCredentials =
- request.credentials === 'include' ||
- (request.credentials === 'same-origin' &&
- request.responseTainting === 'basic')
+// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
+class ErrorEvent extends Event {
+ #eventInit
- // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
- // body is non-null; otherwise null.
- const contentLength = httpRequest.body ? httpRequest.body.length : null
+ constructor (type, eventInitDict) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' })
- // 5. Let contentLengthHeaderValue be null.
- let contentLengthHeaderValue = null
+ super(type, eventInitDict)
- // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
- // `PUT`, then set contentLengthHeaderValue to `0`.
- if (
- httpRequest.body == null &&
- ['POST', 'PUT'].includes(httpRequest.method)
- ) {
- contentLengthHeaderValue = '0'
- }
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})
- // 7. If contentLength is non-null, then set contentLengthHeaderValue to
- // contentLength, serialized and isomorphic encoded.
- if (contentLength != null) {
- contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
+ this.#eventInit = eventInitDict
}
- // 8. If contentLengthHeaderValue is non-null, then append
- // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
- // list.
- if (contentLengthHeaderValue != null) {
- httpRequest.headersList.append('content-length', contentLengthHeaderValue)
+ get message () {
+ webidl.brandCheck(this, ErrorEvent)
+
+ return this.#eventInit.message
}
- // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
- // contentLengthHeaderValue) to httpRequest’s header list.
+ get filename () {
+ webidl.brandCheck(this, ErrorEvent)
- // 10. If contentLength is non-null and httpRequest’s keepalive is true,
- // then:
- if (contentLength != null && httpRequest.keepalive) {
- // NOTE: keepalive is a noop outside of browser context.
+ return this.#eventInit.filename
}
- // 11. If httpRequest’s referrer is a URL, then append
- // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
- // to httpRequest’s header list.
- if (httpRequest.referrer instanceof URL) {
- httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))
- }
+ get lineno () {
+ webidl.brandCheck(this, ErrorEvent)
- // 12. Append a request `Origin` header for httpRequest.
- appendRequestOriginHeader(httpRequest)
+ return this.#eventInit.lineno
+ }
- // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
- appendFetchMetadata(httpRequest)
+ get colno () {
+ webidl.brandCheck(this, ErrorEvent)
- // 14. If httpRequest’s header list does not contain `User-Agent`, then
- // user agents should append `User-Agent`/default `User-Agent` value to
- // httpRequest’s header list.
- if (!httpRequest.headersList.contains('user-agent')) {
- httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')
+ return this.#eventInit.colno
}
- // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
- // list contains `If-Modified-Since`, `If-None-Match`,
- // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
- // httpRequest’s cache mode to "no-store".
- if (
- httpRequest.cache === 'default' &&
- (httpRequest.headersList.contains('if-modified-since') ||
- httpRequest.headersList.contains('if-none-match') ||
- httpRequest.headersList.contains('if-unmodified-since') ||
- httpRequest.headersList.contains('if-match') ||
- httpRequest.headersList.contains('if-range'))
- ) {
- httpRequest.cache = 'no-store'
- }
+ get error () {
+ webidl.brandCheck(this, ErrorEvent)
- // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
- // no-cache cache-control header modification flag is unset, and
- // httpRequest’s header list does not contain `Cache-Control`, then append
- // `Cache-Control`/`max-age=0` to httpRequest’s header list.
- if (
- httpRequest.cache === 'no-cache' &&
- !httpRequest.preventNoCacheCacheControlHeaderModification &&
- !httpRequest.headersList.contains('cache-control')
- ) {
- httpRequest.headersList.append('cache-control', 'max-age=0')
+ return this.#eventInit.error
}
+}
- // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
- if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
- // 1. If httpRequest’s header list does not contain `Pragma`, then append
- // `Pragma`/`no-cache` to httpRequest’s header list.
- if (!httpRequest.headersList.contains('pragma')) {
- httpRequest.headersList.append('pragma', 'no-cache')
- }
+Object.defineProperties(MessageEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'MessageEvent',
+ configurable: true
+ },
+ data: kEnumerableProperty,
+ origin: kEnumerableProperty,
+ lastEventId: kEnumerableProperty,
+ source: kEnumerableProperty,
+ ports: kEnumerableProperty,
+ initMessageEvent: kEnumerableProperty
+})
- // 2. If httpRequest’s header list does not contain `Cache-Control`,
- // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
- if (!httpRequest.headersList.contains('cache-control')) {
- httpRequest.headersList.append('cache-control', 'no-cache')
- }
- }
+Object.defineProperties(CloseEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'CloseEvent',
+ configurable: true
+ },
+ reason: kEnumerableProperty,
+ code: kEnumerableProperty,
+ wasClean: kEnumerableProperty
+})
- // 18. If httpRequest’s header list contains `Range`, then append
- // `Accept-Encoding`/`identity` to httpRequest’s header list.
- if (httpRequest.headersList.contains('range')) {
- httpRequest.headersList.append('accept-encoding', 'identity')
+Object.defineProperties(ErrorEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'ErrorEvent',
+ configurable: true
+ },
+ message: kEnumerableProperty,
+ filename: kEnumerableProperty,
+ lineno: kEnumerableProperty,
+ colno: kEnumerableProperty,
+ error: kEnumerableProperty
+})
+
+webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)
+
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.MessagePort
+)
+
+const eventInit = [
+ {
+ key: 'bubbles',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'cancelable',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'composed',
+ converter: webidl.converters.boolean,
+ defaultValue: false
}
+]
- // 19. Modify httpRequest’s header list per HTTP. Do not append a given
- // header if httpRequest’s header list contains that header’s name.
- // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
- if (!httpRequest.headersList.contains('accept-encoding')) {
- if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
- httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')
- } else {
- httpRequest.headersList.append('accept-encoding', 'gzip, deflate')
+webidl.converters.MessageEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: 'data',
+ converter: webidl.converters.any,
+ defaultValue: null
+ },
+ {
+ key: 'origin',
+ converter: webidl.converters.USVString,
+ defaultValue: ''
+ },
+ {
+ key: 'lastEventId',
+ converter: webidl.converters.DOMString,
+ defaultValue: ''
+ },
+ {
+ key: 'source',
+ // Node doesn't implement WindowProxy or ServiceWorker, so the only
+ // valid value for source is a MessagePort.
+ converter: webidl.nullableConverter(webidl.converters.MessagePort),
+ defaultValue: null
+ },
+ {
+ key: 'ports',
+ converter: webidl.converters['sequence'],
+ get defaultValue () {
+ return []
}
}
+])
- httpRequest.headersList.delete('host')
+webidl.converters.CloseEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: 'wasClean',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'code',
+ converter: webidl.converters['unsigned short'],
+ defaultValue: 0
+ },
+ {
+ key: 'reason',
+ converter: webidl.converters.USVString,
+ defaultValue: ''
+ }
+])
- // 20. If includeCredentials is true, then:
- if (includeCredentials) {
- // 1. If the user agent is not configured to block cookies for httpRequest
- // (see section 7 of [COOKIES]), then:
- // TODO: credentials
- // 2. If httpRequest’s header list does not contain `Authorization`, then:
- // TODO: credentials
+webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: 'message',
+ converter: webidl.converters.DOMString,
+ defaultValue: ''
+ },
+ {
+ key: 'filename',
+ converter: webidl.converters.USVString,
+ defaultValue: ''
+ },
+ {
+ key: 'lineno',
+ converter: webidl.converters['unsigned long'],
+ defaultValue: 0
+ },
+ {
+ key: 'colno',
+ converter: webidl.converters['unsigned long'],
+ defaultValue: 0
+ },
+ {
+ key: 'error',
+ converter: webidl.converters.any
}
+])
- // 21. If there’s a proxy-authentication entry, use it as appropriate.
- // TODO: proxy-authentication
+module.exports = {
+ MessageEvent,
+ CloseEvent,
+ ErrorEvent
+}
- // 22. Set httpCache to the result of determining the HTTP cache
- // partition, given httpRequest.
- // TODO: cache
- // 23. If httpCache is null, then set httpRequest’s cache mode to
- // "no-store".
- if (httpCache == null) {
- httpRequest.cache = 'no-store'
- }
+/***/ }),
- // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
- // then:
- if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {
- // TODO: cache
+/***/ 42697:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { maxUnsigned16Bit } = __nccwpck_require__(90077)
+
+/** @type {import('crypto')} */
+let crypto
+try {
+ crypto = __nccwpck_require__(76982)
+} catch {
+
+}
+
+class WebsocketFrameSend {
+ /**
+ * @param {Buffer|undefined} data
+ */
+ constructor (data) {
+ this.frameData = data
+ this.maskKey = crypto.randomBytes(4)
}
- // 9. If aborted, then return the appropriate network error for fetchParams.
- // TODO
+ createFrame (opcode) {
+ const bodyLength = this.frameData?.byteLength ?? 0
- // 10. If response is null, then:
- if (response == null) {
- // 1. If httpRequest’s cache mode is "only-if-cached", then return a
- // network error.
- if (httpRequest.mode === 'only-if-cached') {
- return makeNetworkError('only if cached')
+ /** @type {number} */
+ let payloadLength = bodyLength // 0-125
+ let offset = 6
+
+ if (bodyLength > maxUnsigned16Bit) {
+ offset += 8 // payload length is next 8 bytes
+ payloadLength = 127
+ } else if (bodyLength > 125) {
+ offset += 2 // payload length is next 2 bytes
+ payloadLength = 126
}
- // 2. Let forwardResponse be the result of running HTTP-network fetch
- // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
- const forwardResponse = await httpNetworkFetch(
- httpFetchParams,
- includeCredentials,
- isNewConnectionFetch
- )
+ const buffer = Buffer.allocUnsafe(bodyLength + offset)
- // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
- // in the range 200 to 399, inclusive, invalidate appropriate stored
- // responses in httpCache, as per the "Invalidation" chapter of HTTP
- // Caching, and set storedResponse to null. [HTTP-CACHING]
- if (
- !safeMethodsSet.has(httpRequest.method) &&
- forwardResponse.status >= 200 &&
- forwardResponse.status <= 399
- ) {
- // TODO: cache
- }
+ // Clear first 2 bytes, everything else is overwritten
+ buffer[0] = buffer[1] = 0
+ buffer[0] |= 0x80 // FIN
+ buffer[0] = (buffer[0] & 0xF0) + opcode // opcode
- // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
- // then:
- if (revalidatingFlag && forwardResponse.status === 304) {
- // TODO: cache
+ /*! ws. MIT License. Einar Otto Stangvik */
+ buffer[offset - 4] = this.maskKey[0]
+ buffer[offset - 3] = this.maskKey[1]
+ buffer[offset - 2] = this.maskKey[2]
+ buffer[offset - 1] = this.maskKey[3]
+
+ buffer[1] = payloadLength
+
+ if (payloadLength === 126) {
+ buffer.writeUInt16BE(bodyLength, 2)
+ } else if (payloadLength === 127) {
+ // Clear extended payload length
+ buffer[2] = buffer[3] = 0
+ buffer.writeUIntBE(bodyLength, 4, 6)
}
- // 5. If response is null, then:
- if (response == null) {
- // 1. Set response to forwardResponse.
- response = forwardResponse
+ buffer[1] |= 0x80 // MASK
- // 2. Store httpRequest and forwardResponse in httpCache, as per the
- // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
- // TODO: cache
+ // mask body
+ for (let i = 0; i < bodyLength; i++) {
+ buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]
}
+
+ return buffer
}
+}
- // 11. Set response’s URL list to a clone of httpRequest’s URL list.
- response.urlList = [...httpRequest.urlList]
+module.exports = {
+ WebsocketFrameSend
+}
- // 12. If httpRequest’s header list contains `Range`, then set response’s
- // range-requested flag.
- if (httpRequest.headersList.contains('range')) {
- response.rangeRequested = true
- }
- // 13. Set response’s request-includes-credentials to includeCredentials.
- response.requestIncludesCredentials = includeCredentials
+/***/ }),
- // 14. If response’s status is 401, httpRequest’s response tainting is not
- // "cors", includeCredentials is true, and request’s window is an environment
- // settings object, then:
- // TODO
+/***/ 13607:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 15. If response’s status is 407, then:
- if (response.status === 407) {
- // 1. If request’s window is "no-window", then return a network error.
- if (request.window === 'no-window') {
- return makeNetworkError()
- }
- // 2. ???
- // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams)) {
- return makeAppropriateNetworkError(fetchParams)
- }
+const { Writable } = __nccwpck_require__(2203)
+const diagnosticsChannel = __nccwpck_require__(31637)
+const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(90077)
+const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(97945)
+const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(95506)
+const { WebsocketFrameSend } = __nccwpck_require__(42697)
- // 4. Prompt the end user as appropriate in request’s window and store
- // the result as a proxy-authentication entry. [HTTP-AUTH]
- // TODO: Invoke some kind of callback?
+// This code was influenced by ws released under the MIT license.
+// Copyright (c) 2011 Einar Otto Stangvik
+// Copyright (c) 2013 Arnout Kazemier and contributors
+// Copyright (c) 2016 Luigi Pinca and contributors
- // 5. Set response to the result of running HTTP-network-or-cache fetch given
- // fetchParams.
- // TODO
- return makeNetworkError('proxy authentication required')
- }
+const channels = {}
+channels.ping = diagnosticsChannel.channel('undici:websocket:ping')
+channels.pong = diagnosticsChannel.channel('undici:websocket:pong')
- // 16. If all of the following are true
- if (
- // response’s status is 421
- response.status === 421 &&
- // isNewConnectionFetch is false
- !isNewConnectionFetch &&
- // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
- (request.body == null || request.body.source != null)
- ) {
- // then:
+class ByteParser extends Writable {
+ #buffers = []
+ #byteOffset = 0
- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams)) {
- return makeAppropriateNetworkError(fetchParams)
- }
+ #state = parserStates.INFO
- // 2. Set response to the result of running HTTP-network-or-cache
- // fetch given fetchParams, isAuthenticationFetch, and true.
+ #info = {}
+ #fragments = []
- // TODO (spec): The spec doesn't specify this but we need to cancel
- // the active response before we can start a new one.
- // https://github.com/whatwg/fetch/issues/1293
- fetchParams.controller.connection.destroy()
+ constructor (ws) {
+ super()
- response = await httpNetworkOrCacheFetch(
- fetchParams,
- isAuthenticationFetch,
- true
- )
+ this.ws = ws
}
- // 17. If isAuthenticationFetch is true, then create an authentication entry
- if (isAuthenticationFetch) {
- // TODO
+ /**
+ * @param {Buffer} chunk
+ * @param {() => void} callback
+ */
+ _write (chunk, _, callback) {
+ this.#buffers.push(chunk)
+ this.#byteOffset += chunk.length
+
+ this.run(callback)
}
- // 18. Return response.
- return response
-}
+ /**
+ * Runs whenever a new chunk is received.
+ * Callback is called whenever there are no more chunks buffering,
+ * or not enough bytes are buffered to parse.
+ */
+ run (callback) {
+ while (true) {
+ if (this.#state === parserStates.INFO) {
+ // If there aren't enough bytes to parse the payload length, etc.
+ if (this.#byteOffset < 2) {
+ return callback()
+ }
-// https://fetch.spec.whatwg.org/#http-network-fetch
-async function httpNetworkFetch (
- fetchParams,
- includeCredentials = false,
- forceNewConnection = false
-) {
- assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
+ const buffer = this.consume(2)
- fetchParams.controller.connection = {
- abort: null,
- destroyed: false,
- destroy (err) {
- if (!this.destroyed) {
- this.destroyed = true
- this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
- }
- }
- }
+ this.#info.fin = (buffer[0] & 0x80) !== 0
+ this.#info.opcode = buffer[0] & 0x0F
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+ // If we receive a fragmented message, we use the type of the first
+ // frame to parse the full message as binary/text, when it's terminated
+ this.#info.originalOpcode ??= this.#info.opcode
- // 2. Let response be null.
- let response = null
+ this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION
- // 3. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
+ if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) {
+ // Only text and binary frames can be fragmented
+ failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')
+ return
+ }
- // 4. Let httpCache be the result of determining the HTTP cache partition,
- // given request.
- // TODO: cache
- const httpCache = null
+ const payloadLength = buffer[1] & 0x7F
- // 5. If httpCache is null, then set request’s cache mode to "no-store".
- if (httpCache == null) {
- request.cache = 'no-store'
- }
+ if (payloadLength <= 125) {
+ this.#info.payloadLength = payloadLength
+ this.#state = parserStates.READ_DATA
+ } else if (payloadLength === 126) {
+ this.#state = parserStates.PAYLOADLENGTH_16
+ } else if (payloadLength === 127) {
+ this.#state = parserStates.PAYLOADLENGTH_64
+ }
- // 6. Let networkPartitionKey be the result of determining the network
- // partition key given request.
- // TODO
+ if (this.#info.fragmented && payloadLength > 125) {
+ // A fragmented frame can't be fragmented itself
+ failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')
+ return
+ } else if (
+ (this.#info.opcode === opcodes.PING ||
+ this.#info.opcode === opcodes.PONG ||
+ this.#info.opcode === opcodes.CLOSE) &&
+ payloadLength > 125
+ ) {
+ // Control frames can have a payload length of 125 bytes MAX
+ failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.')
+ return
+ } else if (this.#info.opcode === opcodes.CLOSE) {
+ if (payloadLength === 1) {
+ failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')
+ return
+ }
- // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
- // "no".
- const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
+ const body = this.consume(payloadLength)
- // 8. Switch on request’s mode:
- if (request.mode === 'websocket') {
- // Let connection be the result of obtaining a WebSocket connection,
- // given request’s current URL.
- // TODO
- } else {
- // Let connection be the result of obtaining a connection, given
- // networkPartitionKey, request’s current URL’s origin,
- // includeCredentials, and forceNewConnection.
- // TODO
- }
+ this.#info.closeInfo = this.parseCloseBody(false, body)
- // 9. Run these steps, but abort when the ongoing fetch is terminated:
+ if (!this.ws[kSentClose]) {
+ // If an endpoint receives a Close frame and did not previously send a
+ // Close frame, the endpoint MUST send a Close frame in response. (When
+ // sending a Close frame in response, the endpoint typically echos the
+ // status code it received.)
+ const body = Buffer.allocUnsafe(2)
+ body.writeUInt16BE(this.#info.closeInfo.code, 0)
+ const closeFrame = new WebsocketFrameSend(body)
- // 1. If connection is failure, then return a network error.
+ this.ws[kResponse].socket.write(
+ closeFrame.createFrame(opcodes.CLOSE),
+ (err) => {
+ if (!err) {
+ this.ws[kSentClose] = true
+ }
+ }
+ )
+ }
- // 2. Set timingInfo’s final connection timing info to the result of
- // calling clamp and coarsen connection timing info with connection’s
- // timing info, timingInfo’s post-redirect start time, and fetchParams’s
- // cross-origin isolated capability.
+ // Upon either sending or receiving a Close control frame, it is said
+ // that _The WebSocket Closing Handshake is Started_ and that the
+ // WebSocket connection is in the CLOSING state.
+ this.ws[kReadyState] = states.CLOSING
+ this.ws[kReceivedClose] = true
- // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
- // and request’s body’s source is null, then append (`Transfer-Encoding`,
- // `chunked`) to request’s header list.
+ this.end()
- // 4. Set timingInfo’s final network-request start time to the coarsened
- // shared current time given fetchParams’s cross-origin isolated
- // capability.
+ return
+ } else if (this.#info.opcode === opcodes.PING) {
+ // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
+ // response, unless it already received a Close frame.
+ // A Pong frame sent in response to a Ping frame must have identical
+ // "Application data"
- // 5. Set response to the result of making an HTTP request over connection
- // using request with the following caveats:
+ const body = this.consume(payloadLength)
- // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
- // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
+ if (!this.ws[kReceivedClose]) {
+ const frame = new WebsocketFrameSend(body)
- // - If request’s body is non-null, and request’s body’s source is null,
- // then the user agent may have a buffer of up to 64 kibibytes and store
- // a part of request’s body in that buffer. If the user agent reads from
- // request’s body beyond that buffer’s size and the user agent needs to
- // resend request, then instead return a network error.
+ this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))
- // - Set timingInfo’s final network-response start time to the coarsened
- // shared current time given fetchParams’s cross-origin isolated capability,
- // immediately after the user agent’s HTTP parser receives the first byte
- // of the response (e.g., frame header bytes for HTTP/2 or response status
- // line for HTTP/1.x).
+ if (channels.ping.hasSubscribers) {
+ channels.ping.publish({
+ payload: body
+ })
+ }
+ }
- // - Wait until all the headers are transmitted.
+ this.#state = parserStates.INFO
- // - Any responses whose status is in the range 100 to 199, inclusive,
- // and is not 101, are to be ignored, except for the purposes of setting
- // timingInfo’s final network-response start time above.
+ if (this.#byteOffset > 0) {
+ continue
+ } else {
+ callback()
+ return
+ }
+ } else if (this.#info.opcode === opcodes.PONG) {
+ // A Pong frame MAY be sent unsolicited. This serves as a
+ // unidirectional heartbeat. A response to an unsolicited Pong frame is
+ // not expected.
- // - If request’s header list contains `Transfer-Encoding`/`chunked` and
- // response is transferred via HTTP/1.0 or older, then return a network
- // error.
+ const body = this.consume(payloadLength)
- // - If the HTTP request results in a TLS client certificate dialog, then:
+ if (channels.pong.hasSubscribers) {
+ channels.pong.publish({
+ payload: body
+ })
+ }
- // 1. If request’s window is an environment settings object, make the
- // dialog available in request’s window.
+ if (this.#byteOffset > 0) {
+ continue
+ } else {
+ callback()
+ return
+ }
+ }
+ } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
+ if (this.#byteOffset < 2) {
+ return callback()
+ }
- // 2. Otherwise, return a network error.
+ const buffer = this.consume(2)
- // To transmit request’s body body, run these steps:
- let requestBody = null
- // 1. If body is null and fetchParams’s process request end-of-body is
- // non-null, then queue a fetch task given fetchParams’s process request
- // end-of-body and fetchParams’s task destination.
- if (request.body == null && fetchParams.processRequestEndOfBody) {
- queueMicrotask(() => fetchParams.processRequestEndOfBody())
- } else if (request.body != null) {
- // 2. Otherwise, if body is non-null:
+ this.#info.payloadLength = buffer.readUInt16BE(0)
+ this.#state = parserStates.READ_DATA
+ } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
+ if (this.#byteOffset < 8) {
+ return callback()
+ }
- // 1. Let processBodyChunk given bytes be these steps:
- const processBodyChunk = async function * (bytes) {
- // 1. If the ongoing fetch is terminated, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
+ const buffer = this.consume(8)
+ const upper = buffer.readUInt32BE(0)
- // 2. Run this step in parallel: transmit bytes.
- yield bytes
+ // 2^31 is the maxinimum bytes an arraybuffer can contain
+ // on 32-bit systems. Although, on 64-bit systems, this is
+ // 2^53-1 bytes.
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length
+ // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275
+ // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e
+ if (upper > 2 ** 31 - 1) {
+ failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')
+ return
+ }
- // 3. If fetchParams’s process request body is non-null, then run
- // fetchParams’s process request body given bytes’s length.
- fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
- }
+ const lower = buffer.readUInt32BE(4)
- // 2. Let processEndOfBody be these steps:
- const processEndOfBody = () => {
- // 1. If fetchParams is canceled, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
+ this.#info.payloadLength = (upper << 8) + lower
+ this.#state = parserStates.READ_DATA
+ } else if (this.#state === parserStates.READ_DATA) {
+ if (this.#byteOffset < this.#info.payloadLength) {
+ // If there is still more data in this chunk that needs to be read
+ return callback()
+ } else if (this.#byteOffset >= this.#info.payloadLength) {
+ // If the server sent multiple frames in a single chunk
+
+ const body = this.consume(this.#info.payloadLength)
+
+ this.#fragments.push(body)
+
+ // If the frame is unfragmented, or a fragmented frame was terminated,
+ // a message was received
+ if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) {
+ const fullMessage = Buffer.concat(this.#fragments)
+
+ websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage)
+
+ this.#info = {}
+ this.#fragments.length = 0
+ }
+
+ this.#state = parserStates.INFO
+ }
}
- // 2. If fetchParams’s process request end-of-body is non-null,
- // then run fetchParams’s process request end-of-body.
- if (fetchParams.processRequestEndOfBody) {
- fetchParams.processRequestEndOfBody()
+ if (this.#byteOffset > 0) {
+ continue
+ } else {
+ callback()
+ break
}
}
+ }
- // 3. Let processBodyError given e be these steps:
- const processBodyError = (e) => {
- // 1. If fetchParams is canceled, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
+ /**
+ * Take n bytes from the buffered Buffers
+ * @param {number} n
+ * @returns {Buffer|null}
+ */
+ consume (n) {
+ if (n > this.#byteOffset) {
+ return null
+ } else if (n === 0) {
+ return emptyBuffer
+ }
- // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
- if (e.name === 'AbortError') {
- fetchParams.controller.abort()
+ if (this.#buffers[0].length === n) {
+ this.#byteOffset -= this.#buffers[0].length
+ return this.#buffers.shift()
+ }
+
+ const buffer = Buffer.allocUnsafe(n)
+ let offset = 0
+
+ while (offset !== n) {
+ const next = this.#buffers[0]
+ const { length } = next
+
+ if (length + offset === n) {
+ buffer.set(this.#buffers.shift(), offset)
+ break
+ } else if (length + offset > n) {
+ buffer.set(next.subarray(0, n - offset), offset)
+ this.#buffers[0] = next.subarray(n - offset)
+ break
} else {
- fetchParams.controller.terminate(e)
+ buffer.set(this.#buffers.shift(), offset)
+ offset += next.length
}
}
- // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
- // processBodyError, and fetchParams’s task destination.
- requestBody = (async function * () {
- try {
- for await (const bytes of request.body.stream) {
- yield * processBodyChunk(bytes)
- }
- processEndOfBody()
- } catch (err) {
- processBodyError(err)
- }
- })()
- }
+ this.#byteOffset -= n
- try {
- // socket is only provided for websockets
- const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
+ return buffer
+ }
- if (socket) {
- response = makeResponse({ status, statusText, headersList, socket })
- } else {
- const iterator = body[Symbol.asyncIterator]()
- fetchParams.controller.next = () => iterator.next()
+ parseCloseBody (onlyCode, data) {
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
+ /** @type {number|undefined} */
+ let code
- response = makeResponse({ status, statusText, headersList })
+ if (data.length >= 2) {
+ // _The WebSocket Connection Close Code_ is
+ // defined as the status code (Section 7.4) contained in the first Close
+ // control frame received by the application
+ code = data.readUInt16BE(0)
}
- } catch (err) {
- // 10. If aborted, then:
- if (err.name === 'AbortError') {
- // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
- fetchParams.controller.connection.destroy()
- // 2. Return the appropriate network error for fetchParams.
- return makeAppropriateNetworkError(fetchParams, err)
+ if (onlyCode) {
+ if (!isValidStatusCode(code)) {
+ return null
+ }
+
+ return { code }
}
- return makeNetworkError(err)
- }
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
+ /** @type {Buffer} */
+ let reason = data.subarray(2)
- // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
- // if it is suspended.
- const pullAlgorithm = () => {
- fetchParams.controller.resume()
- }
+ // Remove BOM
+ if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {
+ reason = reason.subarray(3)
+ }
- // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
- // controller with reason, given reason.
- const cancelAlgorithm = (reason) => {
- fetchParams.controller.abort(reason)
- }
+ if (code !== undefined && !isValidStatusCode(code)) {
+ return null
+ }
- // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
- // the user agent.
- // TODO
+ try {
+ // TODO: optimize this
+ reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)
+ } catch {
+ return null
+ }
- // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
- // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
- // TODO
+ return { code, reason }
+ }
- // 15. Let stream be a new ReadableStream.
- // 16. Set up stream with pullAlgorithm set to pullAlgorithm,
- // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to
- // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ get closingInfo () {
+ return this.#info.closeInfo
}
+}
- const stream = new ReadableStream(
- {
- async start (controller) {
- fetchParams.controller.controller = controller
- },
- async pull (controller) {
- await pullAlgorithm(controller)
- },
- async cancel (reason) {
- await cancelAlgorithm(reason)
- }
- },
- {
- highWaterMark: 0,
- size () {
- return 1
- }
- }
- )
+module.exports = {
+ ByteParser
+}
- // 17. Run these steps, but abort when the ongoing fetch is terminated:
- // 1. Set response’s body to a new body whose stream is stream.
- response.body = { stream }
+/***/ }),
- // 2. If response is not a network error and request’s cache mode is
- // not "no-store", then update response in httpCache for request.
- // TODO
+/***/ 97945:
+/***/ ((module) => {
- // 3. If includeCredentials is true and the user agent is not configured
- // to block cookies for request (see section 7 of [COOKIES]), then run the
- // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
- // the value of each header whose name is a byte-case-insensitive match for
- // `Set-Cookie` in response’s header list, if any, and request’s current URL.
- // TODO
- // 18. If aborted, then:
- // TODO
- // 19. Run these steps in parallel:
+module.exports = {
+ kWebSocketURL: Symbol('url'),
+ kReadyState: Symbol('ready state'),
+ kController: Symbol('controller'),
+ kResponse: Symbol('response'),
+ kBinaryType: Symbol('binary type'),
+ kSentClose: Symbol('sent close'),
+ kReceivedClose: Symbol('received close'),
+ kByteParser: Symbol('byte parser')
+}
- // 1. Run these steps, but abort when fetchParams is canceled:
- fetchParams.controller.on('terminated', onAborted)
- fetchParams.controller.resume = async () => {
- // 1. While true
- while (true) {
- // 1-3. See onData...
- // 4. Set bytes to the result of handling content codings given
- // codings and bytes.
- let bytes
- let isFailure
- try {
- const { done, value } = await fetchParams.controller.next()
+/***/ }),
- if (isAborted(fetchParams)) {
- break
- }
+/***/ 95506:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- bytes = done ? undefined : value
- } catch (err) {
- if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
- // zlib doesn't like empty streams.
- bytes = undefined
- } else {
- bytes = err
- // err may be propagated from the result of calling readablestream.cancel,
- // which might not be an error. https://github.com/nodejs/undici/issues/2009
- isFailure = true
- }
- }
- if (bytes === undefined) {
- // 2. Otherwise, if the bytes transmission for response’s message
- // body is done normally and stream is readable, then close
- // stream, finalize response for fetchParams and response, and
- // abort these in-parallel steps.
- readableStreamClose(fetchParams.controller.controller)
+const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(97945)
+const { states, opcodes } = __nccwpck_require__(90077)
+const { MessageEvent, ErrorEvent } = __nccwpck_require__(47115)
- finalizeResponse(fetchParams, response)
+/* globals Blob */
- return
- }
+/**
+ * @param {import('./websocket').WebSocket} ws
+ */
+function isEstablished (ws) {
+ // If the server's response is validated as provided for above, it is
+ // said that _The WebSocket Connection is Established_ and that the
+ // WebSocket Connection is in the OPEN state.
+ return ws[kReadyState] === states.OPEN
+}
- // 5. Increase timingInfo’s decoded body size by bytes’s length.
- timingInfo.decodedBodySize += bytes?.byteLength ?? 0
+/**
+ * @param {import('./websocket').WebSocket} ws
+ */
+function isClosing (ws) {
+ // Upon either sending or receiving a Close control frame, it is said
+ // that _The WebSocket Closing Handshake is Started_ and that the
+ // WebSocket connection is in the CLOSING state.
+ return ws[kReadyState] === states.CLOSING
+}
- // 6. If bytes is failure, then terminate fetchParams’s controller.
- if (isFailure) {
- fetchParams.controller.terminate(bytes)
- return
- }
+/**
+ * @param {import('./websocket').WebSocket} ws
+ */
+function isClosed (ws) {
+ return ws[kReadyState] === states.CLOSED
+}
- // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
- // into stream.
- fetchParams.controller.controller.enqueue(new Uint8Array(bytes))
+/**
+ * @see https://dom.spec.whatwg.org/#concept-event-fire
+ * @param {string} e
+ * @param {EventTarget} target
+ * @param {EventInit | undefined} eventInitDict
+ */
+function fireEvent (e, target, eventConstructor = Event, eventInitDict) {
+ // 1. If eventConstructor is not given, then let eventConstructor be Event.
- // 8. If stream is errored, then terminate the ongoing fetch.
- if (isErrored(stream)) {
- fetchParams.controller.terminate()
- return
- }
+ // 2. Let event be the result of creating an event given eventConstructor,
+ // in the relevant realm of target.
+ // 3. Initialize event’s type attribute to e.
+ const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap
- // 9. If stream doesn’t need more data ask the user agent to suspend
- // the ongoing fetch.
- if (!fetchParams.controller.controller.desiredSize) {
- return
- }
- }
+ // 4. Initialize any other IDL attributes of event as described in the
+ // invocation of this algorithm.
+
+ // 5. Return the result of dispatching event at target, with legacy target
+ // override flag set if set.
+ target.dispatchEvent(event)
+}
+
+/**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ * @param {import('./websocket').WebSocket} ws
+ * @param {number} type Opcode
+ * @param {Buffer} data application data
+ */
+function websocketMessageReceived (ws, type, data) {
+ // 1. If ready state is not OPEN (1), then return.
+ if (ws[kReadyState] !== states.OPEN) {
+ return
}
- // 2. If aborted, then:
- function onAborted (reason) {
- // 2. If fetchParams is aborted, then:
- if (isAborted(fetchParams)) {
- // 1. Set response’s aborted flag.
- response.aborted = true
+ // 2. Let dataForEvent be determined by switching on type and binary type:
+ let dataForEvent
- // 2. If stream is readable, then error stream with the result of
- // deserialize a serialized abort reason given fetchParams’s
- // controller’s serialized abort reason and an
- // implementation-defined realm.
- if (isReadable(stream)) {
- fetchParams.controller.controller.error(
- fetchParams.controller.serializedAbortReason
- )
- }
+ if (type === opcodes.TEXT) {
+ // -> type indicates that the data is Text
+ // a new DOMString containing data
+ try {
+ dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)
+ } catch {
+ failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
+ return
+ }
+ } else if (type === opcodes.BINARY) {
+ if (ws[kBinaryType] === 'blob') {
+ // -> type indicates that the data is Binary and binary type is "blob"
+ // a new Blob object, created in the relevant Realm of the WebSocket
+ // object, that represents data as its raw data
+ dataForEvent = new Blob([data])
} else {
- // 3. Otherwise, if stream is readable, error stream with a TypeError.
- if (isReadable(stream)) {
- fetchParams.controller.controller.error(new TypeError('terminated', {
- cause: isErrorLike(reason) ? reason : undefined
- }))
- }
+ // -> type indicates that the data is Binary and binary type is "arraybuffer"
+ // a new ArrayBuffer object, created in the relevant Realm of the
+ // WebSocket object, whose contents are data
+ dataForEvent = new Uint8Array(data).buffer
}
-
- // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
- // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
- fetchParams.controller.connection.destroy()
}
- // 20. Return response.
- return response
-
- async function dispatch ({ body }) {
- const url = requestCurrentURL(request)
- /** @type {import('../..').Agent} */
- const agent = fetchParams.controller.dispatcher
-
- return new Promise((resolve, reject) => agent.dispatch(
- {
- path: url.pathname + url.search,
- origin: url.origin,
- method: request.method,
- body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
- headers: request.headersList.entries,
- maxRedirections: 0,
- upgrade: request.mode === 'websocket' ? 'websocket' : undefined
- },
- {
- body: null,
- abort: null,
+ // 3. Fire an event named message at the WebSocket object, using MessageEvent,
+ // with the origin attribute initialized to the serialization of the WebSocket
+ // object’s url's origin, and the data attribute initialized to dataForEvent.
+ fireEvent('message', ws, MessageEvent, {
+ origin: ws[kWebSocketURL].origin,
+ data: dataForEvent
+ })
+}
- onConnect (abort) {
- // TODO (fix): Do we need connection here?
- const { connection } = fetchParams.controller
+/**
+ * @see https://datatracker.ietf.org/doc/html/rfc6455
+ * @see https://datatracker.ietf.org/doc/html/rfc2616
+ * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
+ * @param {string} protocol
+ */
+function isValidSubprotocol (protocol) {
+ // If present, this value indicates one
+ // or more comma-separated subprotocol the client wishes to speak,
+ // ordered by preference. The elements that comprise this value
+ // MUST be non-empty strings with characters in the range U+0021 to
+ // U+007E not including separator characters as defined in
+ // [RFC2616] and MUST all be unique strings.
+ if (protocol.length === 0) {
+ return false
+ }
- if (connection.destroyed) {
- abort(new DOMException('The operation was aborted.', 'AbortError'))
- } else {
- fetchParams.controller.on('terminated', abort)
- this.abort = connection.abort = abort
- }
- },
+ for (const char of protocol) {
+ const code = char.charCodeAt(0)
- onHeaders (status, headersList, resume, statusText) {
- if (status < 200) {
- return
- }
+ if (
+ code < 0x21 ||
+ code > 0x7E ||
+ char === '(' ||
+ char === ')' ||
+ char === '<' ||
+ char === '>' ||
+ char === '@' ||
+ char === ',' ||
+ char === ';' ||
+ char === ':' ||
+ char === '\\' ||
+ char === '"' ||
+ char === '/' ||
+ char === '[' ||
+ char === ']' ||
+ char === '?' ||
+ char === '=' ||
+ char === '{' ||
+ char === '}' ||
+ code === 32 || // SP
+ code === 9 // HT
+ ) {
+ return false
+ }
+ }
- let codings = []
- let location = ''
+ return true
+}
- const headers = new Headers()
+/**
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
+ * @param {number} code
+ */
+function isValidStatusCode (code) {
+ if (code >= 1000 && code < 1015) {
+ return (
+ code !== 1004 && // reserved
+ code !== 1005 && // "MUST NOT be set as a status code"
+ code !== 1006 // "MUST NOT be set as a status code"
+ )
+ }
- // For H2, the headers are a plain JS object
- // We distinguish between them and iterate accordingly
- if (Array.isArray(headersList)) {
- for (let n = 0; n < headersList.length; n += 2) {
- const key = headersList[n + 0].toString('latin1')
- const val = headersList[n + 1].toString('latin1')
- if (key.toLowerCase() === 'content-encoding') {
- // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
- // "All content-coding values are case-insensitive..."
- codings = val.toLowerCase().split(',').map((x) => x.trim())
- } else if (key.toLowerCase() === 'location') {
- location = val
- }
+ return code >= 3000 && code <= 4999
+}
- headers[kHeadersList].append(key, val)
- }
- } else {
- const keys = Object.keys(headersList)
- for (const key of keys) {
- const val = headersList[key]
- if (key.toLowerCase() === 'content-encoding') {
- // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
- // "All content-coding values are case-insensitive..."
- codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()
- } else if (key.toLowerCase() === 'location') {
- location = val
- }
+/**
+ * @param {import('./websocket').WebSocket} ws
+ * @param {string|undefined} reason
+ */
+function failWebsocketConnection (ws, reason) {
+ const { [kController]: controller, [kResponse]: response } = ws
- headers[kHeadersList].append(key, val)
- }
- }
+ controller.abort()
- this.body = new Readable({ read: resume })
+ if (response?.socket && !response.socket.destroyed) {
+ response.socket.destroy()
+ }
- const decoders = []
+ if (reason) {
+ fireEvent('error', ws, ErrorEvent, {
+ error: new Error(reason)
+ })
+ }
+}
- const willFollow = request.redirect === 'follow' &&
- location &&
- redirectStatusSet.has(status)
+module.exports = {
+ isEstablished,
+ isClosing,
+ isClosed,
+ fireEvent,
+ isValidSubprotocol,
+ isValidStatusCode,
+ failWebsocketConnection,
+ websocketMessageReceived
+}
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
- if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
- for (const coding of codings) {
- // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
- if (coding === 'x-gzip' || coding === 'gzip') {
- decoders.push(zlib.createGunzip({
- // Be less strict when decoding compressed responses, since sometimes
- // servers send slightly invalid responses that are still accepted
- // by common browsers.
- // Always using Z_SYNC_FLUSH is what cURL does.
- flush: zlib.constants.Z_SYNC_FLUSH,
- finishFlush: zlib.constants.Z_SYNC_FLUSH
- }))
- } else if (coding === 'deflate') {
- decoders.push(zlib.createInflate())
- } else if (coding === 'br') {
- decoders.push(zlib.createBrotliDecompress())
- } else {
- decoders.length = 0
- break
- }
- }
- }
- resolve({
- status,
- statusText,
- headersList: headers[kHeadersList],
- body: decoders.length
- ? pipeline(this.body, ...decoders, () => { })
- : this.body.on('error', () => {})
- })
+/***/ }),
- return true
- },
+/***/ 90551:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- onData (chunk) {
- if (fetchParams.controller.dump) {
- return
- }
- // 1. If one or more bytes have been transmitted from response’s
- // message body, then:
- // 1. Let bytes be the transmitted bytes.
- const bytes = chunk
+const { webidl } = __nccwpck_require__(94354)
+const { DOMException } = __nccwpck_require__(21234)
+const { URLSerializer } = __nccwpck_require__(37246)
+const { getGlobalOrigin } = __nccwpck_require__(62896)
+const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(90077)
+const {
+ kWebSocketURL,
+ kReadyState,
+ kController,
+ kBinaryType,
+ kResponse,
+ kSentClose,
+ kByteParser
+} = __nccwpck_require__(97945)
+const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(95506)
+const { establishWebSocketConnection } = __nccwpck_require__(96114)
+const { WebsocketFrameSend } = __nccwpck_require__(42697)
+const { ByteParser } = __nccwpck_require__(13607)
+const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(89500)
+const { getGlobalDispatcher } = __nccwpck_require__(61481)
+const { types } = __nccwpck_require__(39023)
- // 2. Let codings be the result of extracting header list values
- // given `Content-Encoding` and response’s header list.
- // See pullAlgorithm.
+let experimentalWarned = false
- // 3. Increase timingInfo’s encoded body size by bytes’s length.
- timingInfo.encodedBodySize += bytes.byteLength
+// https://websockets.spec.whatwg.org/#interface-definition
+class WebSocket extends EventTarget {
+ #events = {
+ open: null,
+ error: null,
+ close: null,
+ message: null
+ }
- // 4. See pullAlgorithm...
+ #bufferedAmount = 0
+ #protocol = ''
+ #extensions = ''
- return this.body.push(bytes)
- },
+ /**
+ * @param {string} url
+ * @param {string|string[]} protocols
+ */
+ constructor (url, protocols = []) {
+ super()
- onComplete () {
- if (this.abort) {
- fetchParams.controller.off('terminated', this.abort)
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' })
- fetchParams.controller.ended = true
+ if (!experimentalWarned) {
+ experimentalWarned = true
+ process.emitWarning('WebSockets are experimental, expect them to change at any time.', {
+ code: 'UNDICI-WS'
+ })
+ }
- this.body.push(null)
- },
+ const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols)
- onError (error) {
- if (this.abort) {
- fetchParams.controller.off('terminated', this.abort)
- }
+ url = webidl.converters.USVString(url)
+ protocols = options.protocols
- this.body?.destroy(error)
+ // 1. Let baseURL be this's relevant settings object's API base URL.
+ const baseURL = getGlobalOrigin()
- fetchParams.controller.terminate(error)
+ // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.
+ let urlRecord
- reject(error)
- },
+ try {
+ urlRecord = new URL(url, baseURL)
+ } catch (e) {
+ // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
+ throw new DOMException(e, 'SyntaxError')
+ }
- onUpgrade (status, headersList, socket) {
- if (status !== 101) {
- return
- }
+ // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
+ if (urlRecord.protocol === 'http:') {
+ urlRecord.protocol = 'ws:'
+ } else if (urlRecord.protocol === 'https:') {
+ // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
+ urlRecord.protocol = 'wss:'
+ }
- const headers = new Headers()
+ // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
+ if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {
+ throw new DOMException(
+ `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,
+ 'SyntaxError'
+ )
+ }
- for (let n = 0; n < headersList.length; n += 2) {
- const key = headersList[n + 0].toString('latin1')
- const val = headersList[n + 1].toString('latin1')
+ // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError"
+ // DOMException.
+ if (urlRecord.hash || urlRecord.href.endsWith('#')) {
+ throw new DOMException('Got fragment', 'SyntaxError')
+ }
- headers[kHeadersList].append(key, val)
- }
+ // 8. If protocols is a string, set protocols to a sequence consisting
+ // of just that string.
+ if (typeof protocols === 'string') {
+ protocols = [protocols]
+ }
- resolve({
- status,
- statusText: STATUS_CODES[status],
- headersList: headers[kHeadersList],
- socket
- })
+ // 9. If any of the values in protocols occur more than once or otherwise
+ // fail to match the requirements for elements that comprise the value
+ // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket
+ // protocol, then throw a "SyntaxError" DOMException.
+ if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {
+ throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
+ }
- return true
- }
- }
- ))
- }
-}
+ if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {
+ throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
+ }
-module.exports = {
- fetch,
- Fetch,
- fetching,
- finalizeAndReportTiming
-}
+ // 10. Set this's url to urlRecord.
+ this[kWebSocketURL] = new URL(urlRecord.href)
+ // 11. Let client be this's relevant settings object.
-/***/ }),
+ // 12. Run this step in parallel:
-/***/ 2630:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 1. Establish a WebSocket connection given urlRecord, protocols,
+ // and client.
+ this[kController] = establishWebSocketConnection(
+ urlRecord,
+ protocols,
+ this,
+ (response) => this.#onConnectionEstablished(response),
+ options
+ )
-/* globals AbortController */
+ // Each WebSocket object has an associated ready state, which is a
+ // number representing the state of the connection. Initially it must
+ // be CONNECTING (0).
+ this[kReadyState] = WebSocket.CONNECTING
+ // The extensions attribute must initially return the empty string.
+ // The protocol attribute must initially return the empty string.
-const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(37791)
-const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(12801)
-const { FinalizationRegistry } = __nccwpck_require__(90022)()
-const util = __nccwpck_require__(89500)
-const {
- isValidHTTPToken,
- sameOrigin,
- normalizeMethod,
- makePolicyContainer,
- normalizeMethodRecord
-} = __nccwpck_require__(72847)
-const {
- forbiddenMethodsSet,
- corsSafeListedMethodsSet,
- referrerPolicy,
- requestRedirect,
- requestMode,
- requestCredentials,
- requestCache,
- requestDuplex
-} = __nccwpck_require__(21234)
-const { kEnumerableProperty } = util
-const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(63730)
-const { webidl } = __nccwpck_require__(94354)
-const { getGlobalOrigin } = __nccwpck_require__(62896)
-const { URLSerializer } = __nccwpck_require__(37246)
-const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
-const assert = __nccwpck_require__(42613)
-const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(24434)
+ // Each WebSocket object has an associated binary type, which is a
+ // BinaryType. Initially it must be "blob".
+ this[kBinaryType] = 'blob'
+ }
-let TransformStream = globalThis.TransformStream
+ /**
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-close
+ * @param {number|undefined} code
+ * @param {string|undefined} reason
+ */
+ close (code = undefined, reason = undefined) {
+ webidl.brandCheck(this, WebSocket)
-const kAbortController = Symbol('abortController')
+ if (code !== undefined) {
+ code = webidl.converters['unsigned short'](code, { clamp: true })
+ }
-const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
- signal.removeEventListener('abort', abort)
-})
+ if (reason !== undefined) {
+ reason = webidl.converters.USVString(reason)
+ }
-// https://fetch.spec.whatwg.org/#request-class
-class Request {
- // https://fetch.spec.whatwg.org/#dom-request
- constructor (input, init = {}) {
- if (input === kConstruct) {
- return
+ // 1. If code is present, but is neither an integer equal to 1000 nor an
+ // integer in the range 3000 to 4999, inclusive, throw an
+ // "InvalidAccessError" DOMException.
+ if (code !== undefined) {
+ if (code !== 1000 && (code < 3000 || code > 4999)) {
+ throw new DOMException('invalid code', 'InvalidAccessError')
+ }
}
- webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })
+ let reasonByteLength = 0
- input = webidl.converters.RequestInfo(input)
- init = webidl.converters.RequestInit(init)
+ // 2. If reason is present, then run these substeps:
+ if (reason !== undefined) {
+ // 1. Let reasonBytes be the result of encoding reason.
+ // 2. If reasonBytes is longer than 123 bytes, then throw a
+ // "SyntaxError" DOMException.
+ reasonByteLength = Buffer.byteLength(reason)
- // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
- this[kRealm] = {
- settingsObject: {
- baseUrl: getGlobalOrigin(),
- get origin () {
- return this.baseUrl?.origin
- },
- policyContainer: makePolicyContainer()
+ if (reasonByteLength > 123) {
+ throw new DOMException(
+ `Reason must be less than 123 bytes; received ${reasonByteLength}`,
+ 'SyntaxError'
+ )
}
}
- // 1. Let request be null.
- let request = null
-
- // 2. Let fallbackMode be null.
- let fallbackMode = null
+ // 3. Run the first matching steps from the following list:
+ if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) {
+ // If this's ready state is CLOSING (2) or CLOSED (3)
+ // Do nothing.
+ } else if (!isEstablished(this)) {
+ // If the WebSocket connection is not yet established
+ // Fail the WebSocket connection and set this's ready state
+ // to CLOSING (2).
+ failWebsocketConnection(this, 'Connection was closed before it was established.')
+ this[kReadyState] = WebSocket.CLOSING
+ } else if (!isClosing(this)) {
+ // If the WebSocket closing handshake has not yet been started
+ // Start the WebSocket closing handshake and set this's ready
+ // state to CLOSING (2).
+ // - If neither code nor reason is present, the WebSocket Close
+ // message must not have a body.
+ // - If code is present, then the status code to use in the
+ // WebSocket Close message must be the integer given by code.
+ // - If reason is also present, then reasonBytes must be
+ // provided in the Close message after the status code.
- // 3. Let baseURL be this’s relevant settings object’s API base URL.
- const baseUrl = this[kRealm].settingsObject.baseUrl
+ const frame = new WebsocketFrameSend()
- // 4. Let signal be null.
- let signal = null
+ // If neither code nor reason is present, the WebSocket Close
+ // message must not have a body.
- // 5. If input is a string, then:
- if (typeof input === 'string') {
- // 1. Let parsedURL be the result of parsing input with baseURL.
- // 2. If parsedURL is failure, then throw a TypeError.
- let parsedURL
- try {
- parsedURL = new URL(input, baseUrl)
- } catch (err) {
- throw new TypeError('Failed to parse URL from ' + input, { cause: err })
+ // If code is present, then the status code to use in the
+ // WebSocket Close message must be the integer given by code.
+ if (code !== undefined && reason === undefined) {
+ frame.frameData = Buffer.allocUnsafe(2)
+ frame.frameData.writeUInt16BE(code, 0)
+ } else if (code !== undefined && reason !== undefined) {
+ // If reason is also present, then reasonBytes must be
+ // provided in the Close message after the status code.
+ frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
+ frame.frameData.writeUInt16BE(code, 0)
+ // the body MAY contain UTF-8-encoded data with value /reason/
+ frame.frameData.write(reason, 2, 'utf-8')
+ } else {
+ frame.frameData = emptyBuffer
}
- // 3. If parsedURL includes credentials, then throw a TypeError.
- if (parsedURL.username || parsedURL.password) {
- throw new TypeError(
- 'Request cannot be constructed from a URL that includes credentials: ' +
- input
- )
- }
+ /** @type {import('stream').Duplex} */
+ const socket = this[kResponse].socket
- // 4. Set request to a new request whose URL is parsedURL.
- request = makeRequest({ urlList: [parsedURL] })
+ socket.write(frame.createFrame(opcodes.CLOSE), (err) => {
+ if (!err) {
+ this[kSentClose] = true
+ }
+ })
- // 5. Set fallbackMode to "cors".
- fallbackMode = 'cors'
+ // Upon either sending or receiving a Close control frame, it is said
+ // that _The WebSocket Closing Handshake is Started_ and that the
+ // WebSocket connection is in the CLOSING state.
+ this[kReadyState] = states.CLOSING
} else {
- // 6. Otherwise:
+ // Otherwise
+ // Set this's ready state to CLOSING (2).
+ this[kReadyState] = WebSocket.CLOSING
+ }
+ }
- // 7. Assert: input is a Request object.
- assert(input instanceof Request)
+ /**
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-send
+ * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
+ */
+ send (data) {
+ webidl.brandCheck(this, WebSocket)
- // 8. Set request to input’s request.
- request = input[kState]
+ webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' })
- // 9. Set signal to input’s signal.
- signal = input[kSignal]
- }
+ data = webidl.converters.WebSocketSendData(data)
- // 7. Let origin be this’s relevant settings object’s origin.
- const origin = this[kRealm].settingsObject.origin
+ // 1. If this's ready state is CONNECTING, then throw an
+ // "InvalidStateError" DOMException.
+ if (this[kReadyState] === WebSocket.CONNECTING) {
+ throw new DOMException('Sent before connected.', 'InvalidStateError')
+ }
- // 8. Let window be "client".
- let window = 'client'
+ // 2. Run the appropriate set of steps from the following list:
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
- // 9. If request’s window is an environment settings object and its origin
- // is same origin with origin, then set window to request’s window.
- if (
- request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
- sameOrigin(request.window, origin)
- ) {
- window = request.window
+ if (!isEstablished(this) || isClosing(this)) {
+ return
}
- // 10. If init["window"] exists and is non-null, then throw a TypeError.
- if (init.window != null) {
- throw new TypeError(`'window' option '${window}' must be null`)
- }
+ /** @type {import('stream').Duplex} */
+ const socket = this[kResponse].socket
- // 11. If init["window"] exists, then set window to "no-window".
- if ('window' in init) {
- window = 'no-window'
- }
+ // If data is a string
+ if (typeof data === 'string') {
+ // If the WebSocket connection is established and the WebSocket
+ // closing handshake has not yet started, then the user agent
+ // must send a WebSocket Message comprised of the data argument
+ // using a text frame opcode; if the data cannot be sent, e.g.
+ // because it would need to be buffered but the buffer is full,
+ // the user agent must flag the WebSocket as full and then close
+ // the WebSocket connection. Any invocation of this method with a
+ // string argument that does not throw an exception must increase
+ // the bufferedAmount attribute by the number of bytes needed to
+ // express the argument as UTF-8.
- // 12. Set request to a new request with the following properties:
- request = makeRequest({
- // URL request’s URL.
- // undici implementation note: this is set as the first item in request's urlList in makeRequest
- // method request’s method.
- method: request.method,
- // header list A copy of request’s header list.
- // undici implementation note: headersList is cloned in makeRequest
- headersList: request.headersList,
- // unsafe-request flag Set.
- unsafeRequest: request.unsafeRequest,
- // client This’s relevant settings object.
- client: this[kRealm].settingsObject,
- // window window.
- window,
- // priority request’s priority.
- priority: request.priority,
- // origin request’s origin. The propagation of the origin is only significant for navigation requests
- // being handled by a service worker. In this scenario a request can have an origin that is different
- // from the current client.
- origin: request.origin,
- // referrer request’s referrer.
- referrer: request.referrer,
- // referrer policy request’s referrer policy.
- referrerPolicy: request.referrerPolicy,
- // mode request’s mode.
- mode: request.mode,
- // credentials mode request’s credentials mode.
- credentials: request.credentials,
- // cache mode request’s cache mode.
- cache: request.cache,
- // redirect mode request’s redirect mode.
- redirect: request.redirect,
- // integrity metadata request’s integrity metadata.
- integrity: request.integrity,
- // keepalive request’s keepalive.
- keepalive: request.keepalive,
- // reload-navigation flag request’s reload-navigation flag.
- reloadNavigation: request.reloadNavigation,
- // history-navigation flag request’s history-navigation flag.
- historyNavigation: request.historyNavigation,
- // URL list A clone of request’s URL list.
- urlList: [...request.urlList]
- })
+ const value = Buffer.from(data)
+ const frame = new WebsocketFrameSend(value)
+ const buffer = frame.createFrame(opcodes.TEXT)
- const initHasKey = Object.keys(init).length !== 0
+ this.#bufferedAmount += value.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= value.byteLength
+ })
+ } else if (types.isArrayBuffer(data)) {
+ // If the WebSocket connection is established, and the WebSocket
+ // closing handshake has not yet started, then the user agent must
+ // send a WebSocket Message comprised of data using a binary frame
+ // opcode; if the data cannot be sent, e.g. because it would need
+ // to be buffered but the buffer is full, the user agent must flag
+ // the WebSocket as full and then close the WebSocket connection.
+ // The data to be sent is the data stored in the buffer described
+ // by the ArrayBuffer object. Any invocation of this method with an
+ // ArrayBuffer argument that does not throw an exception must
+ // increase the bufferedAmount attribute by the length of the
+ // ArrayBuffer in bytes.
- // 13. If init is not empty, then:
- if (initHasKey) {
- // 1. If request’s mode is "navigate", then set it to "same-origin".
- if (request.mode === 'navigate') {
- request.mode = 'same-origin'
- }
+ const value = Buffer.from(data)
+ const frame = new WebsocketFrameSend(value)
+ const buffer = frame.createFrame(opcodes.BINARY)
- // 2. Unset request’s reload-navigation flag.
- request.reloadNavigation = false
+ this.#bufferedAmount += value.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= value.byteLength
+ })
+ } else if (ArrayBuffer.isView(data)) {
+ // If the WebSocket connection is established, and the WebSocket
+ // closing handshake has not yet started, then the user agent must
+ // send a WebSocket Message comprised of data using a binary frame
+ // opcode; if the data cannot be sent, e.g. because it would need to
+ // be buffered but the buffer is full, the user agent must flag the
+ // WebSocket as full and then close the WebSocket connection. The
+ // data to be sent is the data stored in the section of the buffer
+ // described by the ArrayBuffer object that data references. Any
+ // invocation of this method with this kind of argument that does
+ // not throw an exception must increase the bufferedAmount attribute
+ // by the length of data’s buffer in bytes.
- // 3. Unset request’s history-navigation flag.
- request.historyNavigation = false
+ const ab = Buffer.from(data, data.byteOffset, data.byteLength)
- // 4. Set request’s origin to "client".
- request.origin = 'client'
+ const frame = new WebsocketFrameSend(ab)
+ const buffer = frame.createFrame(opcodes.BINARY)
- // 5. Set request’s referrer to "client"
- request.referrer = 'client'
+ this.#bufferedAmount += ab.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= ab.byteLength
+ })
+ } else if (isBlobLike(data)) {
+ // If the WebSocket connection is established, and the WebSocket
+ // closing handshake has not yet started, then the user agent must
+ // send a WebSocket Message comprised of data using a binary frame
+ // opcode; if the data cannot be sent, e.g. because it would need to
+ // be buffered but the buffer is full, the user agent must flag the
+ // WebSocket as full and then close the WebSocket connection. The data
+ // to be sent is the raw data represented by the Blob object. Any
+ // invocation of this method with a Blob argument that does not throw
+ // an exception must increase the bufferedAmount attribute by the size
+ // of the Blob object’s raw data, in bytes.
- // 6. Set request’s referrer policy to the empty string.
- request.referrerPolicy = ''
+ const frame = new WebsocketFrameSend()
- // 7. Set request’s URL to request’s current URL.
- request.url = request.urlList[request.urlList.length - 1]
+ data.arrayBuffer().then((ab) => {
+ const value = Buffer.from(ab)
+ frame.frameData = value
+ const buffer = frame.createFrame(opcodes.BINARY)
- // 8. Set request’s URL list to « request’s URL ».
- request.urlList = [request.url]
+ this.#bufferedAmount += value.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= value.byteLength
+ })
+ })
}
+ }
- // 14. If init["referrer"] exists, then:
- if (init.referrer !== undefined) {
- // 1. Let referrer be init["referrer"].
- const referrer = init.referrer
+ get readyState () {
+ webidl.brandCheck(this, WebSocket)
- // 2. If referrer is the empty string, then set request’s referrer to "no-referrer".
- if (referrer === '') {
- request.referrer = 'no-referrer'
- } else {
- // 1. Let parsedReferrer be the result of parsing referrer with
- // baseURL.
- // 2. If parsedReferrer is failure, then throw a TypeError.
- let parsedReferrer
- try {
- parsedReferrer = new URL(referrer, baseUrl)
- } catch (err) {
- throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
- }
+ // The readyState getter steps are to return this's ready state.
+ return this[kReadyState]
+ }
- // 3. If one of the following is true
- // - parsedReferrer’s scheme is "about" and path is the string "client"
- // - parsedReferrer’s origin is not same origin with origin
- // then set request’s referrer to "client".
- if (
- (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||
- (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl))
- ) {
- request.referrer = 'client'
- } else {
- // 4. Otherwise, set request’s referrer to parsedReferrer.
- request.referrer = parsedReferrer
- }
- }
- }
+ get bufferedAmount () {
+ webidl.brandCheck(this, WebSocket)
+
+ return this.#bufferedAmount
+ }
+
+ get url () {
+ webidl.brandCheck(this, WebSocket)
+
+ // The url getter steps are to return this's url, serialized.
+ return URLSerializer(this[kWebSocketURL])
+ }
+
+ get extensions () {
+ webidl.brandCheck(this, WebSocket)
+
+ return this.#extensions
+ }
+
+ get protocol () {
+ webidl.brandCheck(this, WebSocket)
+
+ return this.#protocol
+ }
- // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
- // to it.
- if (init.referrerPolicy !== undefined) {
- request.referrerPolicy = init.referrerPolicy
+ get onopen () {
+ webidl.brandCheck(this, WebSocket)
+
+ return this.#events.open
+ }
+
+ set onopen (fn) {
+ webidl.brandCheck(this, WebSocket)
+
+ if (this.#events.open) {
+ this.removeEventListener('open', this.#events.open)
}
- // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
- let mode
- if (init.mode !== undefined) {
- mode = init.mode
+ if (typeof fn === 'function') {
+ this.#events.open = fn
+ this.addEventListener('open', fn)
} else {
- mode = fallbackMode
+ this.#events.open = null
}
+ }
- // 17. If mode is "navigate", then throw a TypeError.
- if (mode === 'navigate') {
- throw webidl.errors.exception({
- header: 'Request constructor',
- message: 'invalid request mode navigate.'
- })
- }
+ get onerror () {
+ webidl.brandCheck(this, WebSocket)
- // 18. If mode is non-null, set request’s mode to mode.
- if (mode != null) {
- request.mode = mode
- }
+ return this.#events.error
+ }
- // 19. If init["credentials"] exists, then set request’s credentials mode
- // to it.
- if (init.credentials !== undefined) {
- request.credentials = init.credentials
- }
+ set onerror (fn) {
+ webidl.brandCheck(this, WebSocket)
- // 18. If init["cache"] exists, then set request’s cache mode to it.
- if (init.cache !== undefined) {
- request.cache = init.cache
+ if (this.#events.error) {
+ this.removeEventListener('error', this.#events.error)
}
- // 21. If request’s cache mode is "only-if-cached" and request’s mode is
- // not "same-origin", then throw a TypeError.
- if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
- throw new TypeError(
- "'only-if-cached' can be set only with 'same-origin' mode"
- )
+ if (typeof fn === 'function') {
+ this.#events.error = fn
+ this.addEventListener('error', fn)
+ } else {
+ this.#events.error = null
}
+ }
- // 22. If init["redirect"] exists, then set request’s redirect mode to it.
- if (init.redirect !== undefined) {
- request.redirect = init.redirect
- }
+ get onclose () {
+ webidl.brandCheck(this, WebSocket)
- // 23. If init["integrity"] exists, then set request’s integrity metadata to it.
- if (init.integrity != null) {
- request.integrity = String(init.integrity)
+ return this.#events.close
+ }
+
+ set onclose (fn) {
+ webidl.brandCheck(this, WebSocket)
+
+ if (this.#events.close) {
+ this.removeEventListener('close', this.#events.close)
}
- // 24. If init["keepalive"] exists, then set request’s keepalive to it.
- if (init.keepalive !== undefined) {
- request.keepalive = Boolean(init.keepalive)
+ if (typeof fn === 'function') {
+ this.#events.close = fn
+ this.addEventListener('close', fn)
+ } else {
+ this.#events.close = null
}
+ }
- // 25. If init["method"] exists, then:
- if (init.method !== undefined) {
- // 1. Let method be init["method"].
- let method = init.method
+ get onmessage () {
+ webidl.brandCheck(this, WebSocket)
- // 2. If method is not a method or method is a forbidden method, then
- // throw a TypeError.
- if (!isValidHTTPToken(method)) {
- throw new TypeError(`'${method}' is not a valid HTTP method.`)
- }
+ return this.#events.message
+ }
- if (forbiddenMethodsSet.has(method.toUpperCase())) {
- throw new TypeError(`'${method}' HTTP method is unsupported.`)
- }
+ set onmessage (fn) {
+ webidl.brandCheck(this, WebSocket)
- // 3. Normalize method.
- method = normalizeMethodRecord[method] ?? normalizeMethod(method)
+ if (this.#events.message) {
+ this.removeEventListener('message', this.#events.message)
+ }
- // 4. Set request’s method to method.
- request.method = method
+ if (typeof fn === 'function') {
+ this.#events.message = fn
+ this.addEventListener('message', fn)
+ } else {
+ this.#events.message = null
}
+ }
- // 26. If init["signal"] exists, then set signal to it.
- if (init.signal !== undefined) {
- signal = init.signal
+ get binaryType () {
+ webidl.brandCheck(this, WebSocket)
+
+ return this[kBinaryType]
+ }
+
+ set binaryType (type) {
+ webidl.brandCheck(this, WebSocket)
+
+ if (type !== 'blob' && type !== 'arraybuffer') {
+ this[kBinaryType] = 'blob'
+ } else {
+ this[kBinaryType] = type
}
+ }
- // 27. Set this’s request to request.
- this[kState] = request
+ /**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ */
+ #onConnectionEstablished (response) {
+ // processResponse is called when the "response’s header list has been received and initialized."
+ // once this happens, the connection is open
+ this[kResponse] = response
- // 28. Set this’s signal to a new AbortSignal object with this’s relevant
- // Realm.
- // TODO: could this be simplified with AbortSignal.any
- // (https://dom.spec.whatwg.org/#dom-abortsignal-any)
- const ac = new AbortController()
- this[kSignal] = ac.signal
- this[kSignal][kRealm] = this[kRealm]
+ const parser = new ByteParser(this)
+ parser.on('drain', function onParserDrain () {
+ this.ws[kResponse].socket.resume()
+ })
- // 29. If signal is not null, then make this’s signal follow signal.
- if (signal != null) {
- if (
- !signal ||
- typeof signal.aborted !== 'boolean' ||
- typeof signal.addEventListener !== 'function'
- ) {
- throw new TypeError(
- "Failed to construct 'Request': member signal is not of type AbortSignal."
- )
- }
+ response.socket.ws = this
+ this[kByteParser] = parser
- if (signal.aborted) {
- ac.abort(signal.reason)
- } else {
- // Keep a strong ref to ac while request object
- // is alive. This is needed to prevent AbortController
- // from being prematurely garbage collected.
- // See, https://github.com/nodejs/undici/issues/1926.
- this[kAbortController] = ac
+ // 1. Change the ready state to OPEN (1).
+ this[kReadyState] = states.OPEN
- const acRef = new WeakRef(ac)
- const abort = function () {
- const ac = acRef.deref()
- if (ac !== undefined) {
- ac.abort(this.reason)
- }
- }
+ // 2. Change the extensions attribute’s value to the extensions in use, if
+ // it is not the null value.
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
+ const extensions = response.headersList.get('sec-websocket-extensions')
- // Third-party AbortControllers may not work with these.
- // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
- try {
- // If the max amount of listeners is equal to the default, increase it
- // This is only available in node >= v19.9.0
- if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
- setMaxListeners(100, signal)
- } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
- setMaxListeners(100, signal)
- }
- } catch {}
+ if (extensions !== null) {
+ this.#extensions = extensions
+ }
- util.addAbortListener(signal, abort)
- requestFinalizer.register(ac, { signal, abort })
- }
+ // 3. Change the protocol attribute’s value to the subprotocol in use, if
+ // it is not the null value.
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9
+ const protocol = response.headersList.get('sec-websocket-protocol')
+
+ if (protocol !== null) {
+ this.#protocol = protocol
}
- // 30. Set this’s headers to a new Headers object with this’s relevant
- // Realm, whose header list is request’s header list and guard is
- // "request".
- this[kHeaders] = new Headers(kConstruct)
- this[kHeaders][kHeadersList] = request.headersList
- this[kHeaders][kGuard] = 'request'
- this[kHeaders][kRealm] = this[kRealm]
+ // 4. Fire an event named open at the WebSocket object.
+ fireEvent('open', this)
+ }
+}
- // 31. If this’s request’s mode is "no-cors", then:
- if (mode === 'no-cors') {
- // 1. If this’s request’s method is not a CORS-safelisted method,
- // then throw a TypeError.
- if (!corsSafeListedMethodsSet.has(request.method)) {
- throw new TypeError(
- `'${request.method} is unsupported in no-cors mode.`
- )
- }
+// https://websockets.spec.whatwg.org/#dom-websocket-connecting
+WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING
+// https://websockets.spec.whatwg.org/#dom-websocket-open
+WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN
+// https://websockets.spec.whatwg.org/#dom-websocket-closing
+WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING
+// https://websockets.spec.whatwg.org/#dom-websocket-closed
+WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED
- // 2. Set this’s headers’s guard to "request-no-cors".
- this[kHeaders][kGuard] = 'request-no-cors'
- }
+Object.defineProperties(WebSocket.prototype, {
+ CONNECTING: staticPropertyDescriptors,
+ OPEN: staticPropertyDescriptors,
+ CLOSING: staticPropertyDescriptors,
+ CLOSED: staticPropertyDescriptors,
+ url: kEnumerableProperty,
+ readyState: kEnumerableProperty,
+ bufferedAmount: kEnumerableProperty,
+ onopen: kEnumerableProperty,
+ onerror: kEnumerableProperty,
+ onclose: kEnumerableProperty,
+ close: kEnumerableProperty,
+ onmessage: kEnumerableProperty,
+ binaryType: kEnumerableProperty,
+ send: kEnumerableProperty,
+ extensions: kEnumerableProperty,
+ protocol: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'WebSocket',
+ writable: false,
+ enumerable: false,
+ configurable: true
+ }
+})
- // 32. If init is not empty, then:
- if (initHasKey) {
- /** @type {HeadersList} */
- const headersList = this[kHeaders][kHeadersList]
- // 1. Let headers be a copy of this’s headers and its associated header
- // list.
- // 2. If init["headers"] exists, then set headers to init["headers"].
- const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)
+Object.defineProperties(WebSocket, {
+ CONNECTING: staticPropertyDescriptors,
+ OPEN: staticPropertyDescriptors,
+ CLOSING: staticPropertyDescriptors,
+ CLOSED: staticPropertyDescriptors
+})
- // 3. Empty this’s headers’s header list.
- headersList.clear()
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.DOMString
+)
- // 4. If headers is a Headers object, then for each header in its header
- // list, append header’s name/header’s value to this’s headers.
- if (headers instanceof HeadersList) {
- for (const [key, val] of headers) {
- headersList.append(key, val)
- }
- // Note: Copy the `set-cookie` meta-data.
- headersList.cookies = headers.cookies
- } else {
- // 5. Otherwise, fill this’s headers with headers.
- fillHeaders(this[kHeaders], headers)
- }
- }
+webidl.converters['DOMString or sequence'] = function (V) {
+ if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {
+ return webidl.converters['sequence'](V)
+ }
- // 33. Let inputBody be input’s request’s body if input is a Request
- // object; otherwise null.
- const inputBody = input instanceof Request ? input[kState].body : null
+ return webidl.converters.DOMString(V)
+}
- // 34. If either init["body"] exists and is non-null or inputBody is
- // non-null, and request’s method is `GET` or `HEAD`, then throw a
- // TypeError.
- if (
- (init.body != null || inputBody != null) &&
- (request.method === 'GET' || request.method === 'HEAD')
- ) {
- throw new TypeError('Request with GET/HEAD method cannot have body.')
+// This implements the propsal made in https://github.com/whatwg/websockets/issues/42
+webidl.converters.WebSocketInit = webidl.dictionaryConverter([
+ {
+ key: 'protocols',
+ converter: webidl.converters['DOMString or sequence'],
+ get defaultValue () {
+ return []
+ }
+ },
+ {
+ key: 'dispatcher',
+ converter: (V) => V,
+ get defaultValue () {
+ return getGlobalDispatcher()
}
+ },
+ {
+ key: 'headers',
+ converter: webidl.nullableConverter(webidl.converters.HeadersInit)
+ }
+])
- // 35. Let initBody be null.
- let initBody = null
+webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {
+ if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {
+ return webidl.converters.WebSocketInit(V)
+ }
- // 36. If init["body"] exists and is non-null, then:
- if (init.body != null) {
- // 1. Let Content-Type be null.
- // 2. Set initBody and Content-Type to the result of extracting
- // init["body"], with keepalive set to request’s keepalive.
- const [extractedBody, contentType] = extractBody(
- init.body,
- request.keepalive
- )
- initBody = extractedBody
+ return { protocols: webidl.converters['DOMString or sequence'](V) }
+}
- // 3, If Content-Type is non-null and this’s headers’s header list does
- // not contain `Content-Type`, then append `Content-Type`/Content-Type to
- // this’s headers.
- if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) {
- this[kHeaders].append('content-type', contentType)
- }
+webidl.converters.WebSocketSendData = function (V) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
}
- // 37. Let inputOrInitBody be initBody if it is non-null; otherwise
- // inputBody.
- const inputOrInitBody = initBody ?? inputBody
+ if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) {
+ return webidl.converters.BufferSource(V)
+ }
+ }
- // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is
- // null, then:
- if (inputOrInitBody != null && inputOrInitBody.source == null) {
- // 1. If initBody is non-null and init["duplex"] does not exist,
- // then throw a TypeError.
- if (initBody != null && init.duplex == null) {
- throw new TypeError('RequestInit: duplex option is required when sending a body.')
- }
+ return webidl.converters.USVString(V)
+}
- // 2. If this’s request’s mode is neither "same-origin" nor "cors",
- // then throw a TypeError.
- if (request.mode !== 'same-origin' && request.mode !== 'cors') {
- throw new TypeError(
- 'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
- )
- }
+module.exports = {
+ WebSocket
+}
- // 3. Set this’s request’s use-CORS-preflight flag.
- request.useCORSPreflightFlag = true
- }
- // 39. Let finalBody be inputOrInitBody.
- let finalBody = inputOrInitBody
+/***/ }),
- // 40. If initBody is null and inputBody is non-null, then:
- if (initBody == null && inputBody != null) {
- // 1. If input is unusable, then throw a TypeError.
- if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {
- throw new TypeError(
- 'Cannot construct a Request with a Request object that has already been used.'
- )
- }
+/***/ 49367:
+/***/ ((__unused_webpack_module, exports) => {
- // 2. Set finalBody to the result of creating a proxy for inputBody.
- if (!TransformStream) {
- TransformStream = (__nccwpck_require__(63774).TransformStream)
- }
- // https://streams.spec.whatwg.org/#readablestream-create-a-proxy
- const identityTransform = new TransformStream()
- inputBody.stream.pipeThrough(identityTransform)
- finalBody = {
- source: inputBody.source,
- length: inputBody.length,
- stream: identityTransform.readable
- }
- }
- // 41. Set this’s request’s body to finalBody.
- this[kState].body = finalBody
- }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
- // Returns request’s HTTP method, which is "GET" by default.
- get method () {
- webidl.brandCheck(this, Request)
+function getUserAgent() {
+ if (typeof navigator === "object" && "userAgent" in navigator) {
+ return navigator.userAgent;
+ }
- // The method getter steps are to return this’s request’s method.
- return this[kState].method
+ if (typeof process === "object" && process.version !== undefined) {
+ return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
}
- // Returns the URL of request as a string.
- get url () {
- webidl.brandCheck(this, Request)
+ return "";
+}
- // The url getter steps are to return this’s request’s URL, serialized.
- return URLSerializer(this[kState].url)
- }
+exports.getUserAgent = getUserAgent;
+//# sourceMappingURL=index.js.map
- // Returns a Headers object consisting of the headers associated with request.
- // Note that headers added in the network layer by the user agent will not
- // be accounted for in this object, e.g., the "Host" header.
- get headers () {
- webidl.brandCheck(this, Request)
- // The headers getter steps are to return this’s headers.
- return this[kHeaders]
- }
+/***/ }),
- // Returns the kind of resource requested by request, e.g., "document"
- // or "script".
- get destination () {
- webidl.brandCheck(this, Request)
+/***/ 68776:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // The destination getter are to return this’s request’s destination.
- return this[kState].destination
+
+const iconvLite = __nccwpck_require__(43368);
+const supportedNames = __nccwpck_require__(67944);
+const labelsToNames = __nccwpck_require__(6225);
+
+const supportedNamesSet = new Set(supportedNames);
+
+// https://encoding.spec.whatwg.org/#concept-encoding-get
+exports.labelToName = label => {
+ label = String(label).trim().toLowerCase();
+
+ return labelsToNames[label] || null;
+};
+
+// https://encoding.spec.whatwg.org/#decode
+exports.decode = (uint8Array, fallbackEncodingName) => {
+ let encoding = fallbackEncodingName;
+ if (!exports.isSupported(encoding)) {
+ throw new RangeError(`"${encoding}" is not a supported encoding name`);
}
- // Returns the referrer of request. Its value can be a same-origin URL if
- // explicitly set in init, the empty string to indicate no referrer, and
- // "about:client" when defaulting to the global’s default. This is used
- // during fetching to determine the value of the `Referer` header of the
- // request being made.
- get referrer () {
- webidl.brandCheck(this, Request)
+ const bomEncoding = exports.getBOMEncoding(uint8Array);
+ if (bomEncoding !== null) {
+ encoding = bomEncoding;
+ // iconv-lite will strip BOMs for us, so no need to do the extra byte removal that the spec does.
+ // Note that we won't end up in the x-user-defined case when there's a bomEncoding.
+ }
- // 1. If this’s request’s referrer is "no-referrer", then return the
- // empty string.
- if (this[kState].referrer === 'no-referrer') {
- return ''
+ if (encoding === "x-user-defined") {
+ // https://encoding.spec.whatwg.org/#x-user-defined-decoder
+ let result = "";
+ for (const byte of uint8Array) {
+ if (byte <= 0x7F) {
+ result += String.fromCodePoint(byte);
+ } else {
+ result += String.fromCodePoint(0xF780 + byte - 0x80);
+ }
}
+ return result;
+ }
- // 2. If this’s request’s referrer is "client", then return
- // "about:client".
- if (this[kState].referrer === 'client') {
- return 'about:client'
- }
+ return iconvLite.decode(uint8Array, encoding);
+};
- // Return this’s request’s referrer, serialized.
- return this[kState].referrer.toString()
+// https://github.com/whatwg/html/issues/1910#issuecomment-254017369
+exports.getBOMEncoding = uint8Array => {
+ if (uint8Array[0] === 0xFE && uint8Array[1] === 0xFF) {
+ return "UTF-16BE";
+ } else if (uint8Array[0] === 0xFF && uint8Array[1] === 0xFE) {
+ return "UTF-16LE";
+ } else if (uint8Array[0] === 0xEF && uint8Array[1] === 0xBB && uint8Array[2] === 0xBF) {
+ return "UTF-8";
}
- // Returns the referrer policy associated with request.
- // This is used during fetching to compute the value of the request’s
- // referrer.
- get referrerPolicy () {
- webidl.brandCheck(this, Request)
+ return null;
+};
- // The referrerPolicy getter steps are to return this’s request’s referrer policy.
- return this[kState].referrerPolicy
- }
+exports.isSupported = name => {
+ return supportedNamesSet.has(String(name));
+};
- // Returns the mode associated with request, which is a string indicating
- // whether the request will use CORS, or will be restricted to same-origin
- // URLs.
- get mode () {
- webidl.brandCheck(this, Request)
- // The mode getter steps are to return this’s request’s mode.
- return this[kState].mode
- }
+/***/ }),
- // Returns the credentials mode associated with request,
- // which is a string indicating whether credentials will be sent with the
- // request always, never, or only when sent to a same-origin URL.
- get credentials () {
- // The credentials getter steps are to return this’s request’s credentials mode.
- return this[kState].credentials
- }
+/***/ 54849:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // Returns the cache mode associated with request,
- // which is a string indicating how the request will
- // interact with the browser’s cache when fetching.
- get cache () {
- webidl.brandCheck(this, Request)
- // The cache getter steps are to return this’s request’s cache mode.
- return this[kState].cache
- }
+const {
+ asciiLowercase,
+ solelyContainsHTTPTokenCodePoints,
+ soleyContainsHTTPQuotedStringTokenCodePoints
+} = __nccwpck_require__(74694);
- // Returns the redirect mode associated with request,
- // which is a string indicating how redirects for the
- // request will be handled during fetching. A request
- // will follow redirects by default.
- get redirect () {
- webidl.brandCheck(this, Request)
+module.exports = class MIMETypeParameters {
+ constructor(map) {
+ this._map = map;
+ }
- // The redirect getter steps are to return this’s request’s redirect mode.
- return this[kState].redirect
+ get size() {
+ return this._map.size;
}
- // Returns request’s subresource integrity metadata, which is a
- // cryptographic hash of the resource being fetched. Its value
- // consists of multiple hashes separated by whitespace. [SRI]
- get integrity () {
- webidl.brandCheck(this, Request)
+ get(name) {
+ name = asciiLowercase(String(name));
+ return this._map.get(name);
+ }
- // The integrity getter steps are to return this’s request’s integrity
- // metadata.
- return this[kState].integrity
+ has(name) {
+ name = asciiLowercase(String(name));
+ return this._map.has(name);
}
- // Returns a boolean indicating whether or not request can outlive the
- // global in which it was created.
- get keepalive () {
- webidl.brandCheck(this, Request)
+ set(name, value) {
+ name = asciiLowercase(String(name));
+ value = String(value);
- // The keepalive getter steps are to return this’s request’s keepalive.
- return this[kState].keepalive
- }
+ if (!solelyContainsHTTPTokenCodePoints(name)) {
+ throw new Error(`Invalid MIME type parameter name "${name}": only HTTP token code points are valid.`);
+ }
+ if (!soleyContainsHTTPQuotedStringTokenCodePoints(value)) {
+ throw new Error(`Invalid MIME type parameter value "${value}": only HTTP quoted-string token code points are ` +
+ `valid.`);
+ }
- // Returns a boolean indicating whether or not request is for a reload
- // navigation.
- get isReloadNavigation () {
- webidl.brandCheck(this, Request)
+ return this._map.set(name, value);
+ }
- // The isReloadNavigation getter steps are to return true if this’s
- // request’s reload-navigation flag is set; otherwise false.
- return this[kState].reloadNavigation
+ clear() {
+ this._map.clear();
}
- // Returns a boolean indicating whether or not request is for a history
- // navigation (a.k.a. back-foward navigation).
- get isHistoryNavigation () {
- webidl.brandCheck(this, Request)
+ delete(name) {
+ name = asciiLowercase(String(name));
+ return this._map.delete(name);
+ }
- // The isHistoryNavigation getter steps are to return true if this’s request’s
- // history-navigation flag is set; otherwise false.
- return this[kState].historyNavigation
+ forEach(callbackFn, thisArg) {
+ this._map.forEach(callbackFn, thisArg);
}
- // Returns the signal associated with request, which is an AbortSignal
- // object indicating whether or not request has been aborted, and its
- // abort event handler.
- get signal () {
- webidl.brandCheck(this, Request)
+ keys() {
+ return this._map.keys();
+ }
- // The signal getter steps are to return this’s signal.
- return this[kSignal]
+ values() {
+ return this._map.values();
}
- get body () {
- webidl.brandCheck(this, Request)
+ entries() {
+ return this._map.entries();
+ }
- return this[kState].body ? this[kState].body.stream : null
+ [Symbol.iterator]() {
+ return this._map[Symbol.iterator]();
}
+};
- get bodyUsed () {
- webidl.brandCheck(this, Request)
- return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
- }
+/***/ }),
- get duplex () {
- webidl.brandCheck(this, Request)
+/***/ 79836:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return 'half'
- }
- // Returns a clone of request.
- clone () {
- webidl.brandCheck(this, Request)
+const MIMETypeParameters = __nccwpck_require__(54849);
+const parse = __nccwpck_require__(94276);
+const serialize = __nccwpck_require__(15363);
+const {
+ asciiLowercase,
+ solelyContainsHTTPTokenCodePoints
+} = __nccwpck_require__(74694);
- // 1. If this is unusable, then throw a TypeError.
- if (this.bodyUsed || this.body?.locked) {
- throw new TypeError('unusable')
+module.exports = class MIMEType {
+ constructor(string) {
+ string = String(string);
+ const result = parse(string);
+ if (result === null) {
+ throw new Error(`Could not parse MIME type string "${string}"`);
}
- // 2. Let clonedRequest be the result of cloning this’s request.
- const clonedRequest = cloneRequest(this[kState])
-
- // 3. Let clonedRequestObject be the result of creating a Request object,
- // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
- const clonedRequestObject = new Request(kConstruct)
- clonedRequestObject[kState] = clonedRequest
- clonedRequestObject[kRealm] = this[kRealm]
- clonedRequestObject[kHeaders] = new Headers(kConstruct)
- clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList
- clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]
- clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]
+ this._type = result.type;
+ this._subtype = result.subtype;
+ this._parameters = new MIMETypeParameters(result.parameters);
+ }
- // 4. Make clonedRequestObject’s signal follow this’s signal.
- const ac = new AbortController()
- if (this.signal.aborted) {
- ac.abort(this.signal.reason)
- } else {
- util.addAbortListener(
- this.signal,
- () => {
- ac.abort(this.signal.reason)
- }
- )
+ static parse(string) {
+ try {
+ return new this(string);
+ } catch (e) {
+ return null;
}
- clonedRequestObject[kSignal] = ac.signal
-
- // 4. Return clonedRequestObject.
- return clonedRequestObject
}
-}
-mixinBody(Request)
+ get essence() {
+ return `${this.type}/${this.subtype}`;
+ }
-function makeRequest (init) {
- // https://fetch.spec.whatwg.org/#requests
- const request = {
- method: 'GET',
- localURLsOnly: false,
- unsafeRequest: false,
- body: null,
- client: null,
- reservedClient: null,
- replacesClientId: '',
- window: 'client',
- keepalive: false,
- serviceWorkers: 'all',
- initiator: '',
- destination: '',
- priority: null,
- origin: 'client',
- policyContainer: 'client',
- referrer: 'client',
- referrerPolicy: '',
- mode: 'no-cors',
- useCORSPreflightFlag: false,
- credentials: 'same-origin',
- useCredentials: false,
- cache: 'default',
- redirect: 'follow',
- integrity: '',
- cryptoGraphicsNonceMetadata: '',
- parserMetadata: '',
- reloadNavigation: false,
- historyNavigation: false,
- userActivation: false,
- taintedOrigin: false,
- redirectCount: 0,
- responseTainting: 'basic',
- preventNoCacheCacheControlHeaderModification: false,
- done: false,
- timingAllowFailed: false,
- ...init,
- headersList: init.headersList
- ? new HeadersList(init.headersList)
- : new HeadersList()
+ get type() {
+ return this._type;
}
- request.url = request.urlList[0]
- return request
-}
-// https://fetch.spec.whatwg.org/#concept-request-clone
-function cloneRequest (request) {
- // To clone a request request, run these steps:
+ set type(value) {
+ value = asciiLowercase(String(value));
- // 1. Let newRequest be a copy of request, except for its body.
- const newRequest = makeRequest({ ...request, body: null })
+ if (value.length === 0) {
+ throw new Error("Invalid type: must be a non-empty string");
+ }
+ if (!solelyContainsHTTPTokenCodePoints(value)) {
+ throw new Error(`Invalid type ${value}: must contain only HTTP token code points`);
+ }
- // 2. If request’s body is non-null, set newRequest’s body to the
- // result of cloning request’s body.
- if (request.body != null) {
- newRequest.body = cloneBody(request.body)
+ this._type = value;
}
- // 3. Return newRequest.
- return newRequest
-}
-
-Object.defineProperties(Request.prototype, {
- method: kEnumerableProperty,
- url: kEnumerableProperty,
- headers: kEnumerableProperty,
- redirect: kEnumerableProperty,
- clone: kEnumerableProperty,
- signal: kEnumerableProperty,
- duplex: kEnumerableProperty,
- destination: kEnumerableProperty,
- body: kEnumerableProperty,
- bodyUsed: kEnumerableProperty,
- isHistoryNavigation: kEnumerableProperty,
- isReloadNavigation: kEnumerableProperty,
- keepalive: kEnumerableProperty,
- integrity: kEnumerableProperty,
- cache: kEnumerableProperty,
- credentials: kEnumerableProperty,
- attribute: kEnumerableProperty,
- referrerPolicy: kEnumerableProperty,
- referrer: kEnumerableProperty,
- mode: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'Request',
- configurable: true
+ get subtype() {
+ return this._subtype;
}
-})
-webidl.converters.Request = webidl.interfaceConverter(
- Request
-)
+ set subtype(value) {
+ value = asciiLowercase(String(value));
-// https://fetch.spec.whatwg.org/#requestinfo
-webidl.converters.RequestInfo = function (V) {
- if (typeof V === 'string') {
- return webidl.converters.USVString(V)
- }
+ if (value.length === 0) {
+ throw new Error("Invalid subtype: must be a non-empty string");
+ }
+ if (!solelyContainsHTTPTokenCodePoints(value)) {
+ throw new Error(`Invalid subtype ${value}: must contain only HTTP token code points`);
+ }
- if (V instanceof Request) {
- return webidl.converters.Request(V)
+ this._subtype = value;
}
- return webidl.converters.USVString(V)
-}
-
-webidl.converters.AbortSignal = webidl.interfaceConverter(
- AbortSignal
-)
+ get parameters() {
+ return this._parameters;
+ }
-// https://fetch.spec.whatwg.org/#requestinit
-webidl.converters.RequestInit = webidl.dictionaryConverter([
- {
- key: 'method',
- converter: webidl.converters.ByteString
- },
- {
- key: 'headers',
- converter: webidl.converters.HeadersInit
- },
- {
- key: 'body',
- converter: webidl.nullableConverter(
- webidl.converters.BodyInit
- )
- },
- {
- key: 'referrer',
- converter: webidl.converters.USVString
- },
- {
- key: 'referrerPolicy',
- converter: webidl.converters.DOMString,
- // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
- allowedValues: referrerPolicy
- },
- {
- key: 'mode',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#concept-request-mode
- allowedValues: requestMode
- },
- {
- key: 'credentials',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestcredentials
- allowedValues: requestCredentials
- },
- {
- key: 'cache',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestcache
- allowedValues: requestCache
- },
- {
- key: 'redirect',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestredirect
- allowedValues: requestRedirect
- },
- {
- key: 'integrity',
- converter: webidl.converters.DOMString
- },
- {
- key: 'keepalive',
- converter: webidl.converters.boolean
- },
- {
- key: 'signal',
- converter: webidl.nullableConverter(
- (signal) => webidl.converters.AbortSignal(
- signal,
- { strict: false }
- )
- )
- },
- {
- key: 'window',
- converter: webidl.converters.any
- },
- {
- key: 'duplex',
- converter: webidl.converters.DOMString,
- allowedValues: requestDuplex
+ toString() {
+ // The serialize function works on both "MIME type records" (i.e. the results of parse) and on this class, since
+ // this class's interface is identical.
+ return serialize(this);
}
-])
-module.exports = { Request, makeRequest }
+ isJavaScript({ prohibitParameters = false } = {}) {
+ switch (this._type) {
+ case "text": {
+ switch (this._subtype) {
+ case "ecmascript":
+ case "javascript":
+ case "javascript1.0":
+ case "javascript1.1":
+ case "javascript1.2":
+ case "javascript1.3":
+ case "javascript1.4":
+ case "javascript1.5":
+ case "jscript":
+ case "livescript":
+ case "x-ecmascript":
+ case "x-javascript": {
+ return !prohibitParameters || this._parameters.size === 0;
+ }
+ default: {
+ return false;
+ }
+ }
+ }
+ case "application": {
+ switch (this._subtype) {
+ case "ecmascript":
+ case "javascript":
+ case "x-ecmascript":
+ case "x-javascript": {
+ return !prohibitParameters || this._parameters.size === 0;
+ }
+ default: {
+ return false;
+ }
+ }
+ }
+ default: {
+ return false;
+ }
+ }
+ }
+ isXML() {
+ return (this._subtype === "xml" && (this._type === "text" || this._type === "application")) ||
+ this._subtype.endsWith("+xml");
+ }
+ isHTML() {
+ return this._subtype === "html" && this._type === "text";
+ }
+};
/***/ }),
-/***/ 89928:
+/***/ 94276:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const { Headers, HeadersList, fill } = __nccwpck_require__(12801)
-const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(37791)
-const util = __nccwpck_require__(89500)
-const { kEnumerableProperty } = util
-const {
- isValidReasonPhrase,
- isCancelled,
- isAborted,
- isBlobLike,
- serializeJavascriptValueToJSONString,
- isErrorLike,
- isomorphicEncode
-} = __nccwpck_require__(72847)
const {
- redirectStatusSet,
- nullBodyStatus,
- DOMException
-} = __nccwpck_require__(21234)
-const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
-const { webidl } = __nccwpck_require__(94354)
-const { FormData } = __nccwpck_require__(47453)
-const { getGlobalOrigin } = __nccwpck_require__(62896)
-const { URLSerializer } = __nccwpck_require__(37246)
-const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
-const assert = __nccwpck_require__(42613)
-const { types } = __nccwpck_require__(39023)
-
-const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(63774).ReadableStream)
-const textEncoder = new TextEncoder('utf-8')
+ removeLeadingAndTrailingHTTPWhitespace,
+ removeTrailingHTTPWhitespace,
+ isHTTPWhitespaceChar,
+ solelyContainsHTTPTokenCodePoints,
+ soleyContainsHTTPQuotedStringTokenCodePoints,
+ asciiLowercase,
+ collectAnHTTPQuotedString
+} = __nccwpck_require__(74694);
-// https://fetch.spec.whatwg.org/#response-class
-class Response {
- // Creates network error Response.
- static error () {
- // TODO
- const relevantRealm = { settingsObject: {} }
+module.exports = input => {
+ input = removeLeadingAndTrailingHTTPWhitespace(input);
- // The static error() method steps are to return the result of creating a
- // Response object, given a new network error, "immutable", and this’s
- // relevant Realm.
- const responseObject = new Response()
- responseObject[kState] = makeNetworkError()
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList
- responseObject[kHeaders][kGuard] = 'immutable'
- responseObject[kHeaders][kRealm] = relevantRealm
- return responseObject
+ let position = 0;
+ let type = "";
+ while (position < input.length && input[position] !== "/") {
+ type += input[position];
+ ++position;
}
- // https://fetch.spec.whatwg.org/#dom-response-json
- static json (data, init = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })
-
- if (init !== null) {
- init = webidl.converters.ResponseInit(init)
- }
+ if (type.length === 0 || !solelyContainsHTTPTokenCodePoints(type)) {
+ return null;
+ }
- // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
- const bytes = textEncoder.encode(
- serializeJavascriptValueToJSONString(data)
- )
+ if (position >= input.length) {
+ return null;
+ }
- // 2. Let body be the result of extracting bytes.
- const body = extractBody(bytes)
+ // Skips past "/"
+ ++position;
- // 3. Let responseObject be the result of creating a Response object, given a new response,
- // "response", and this’s relevant Realm.
- const relevantRealm = { settingsObject: {} }
- const responseObject = new Response()
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kGuard] = 'response'
- responseObject[kHeaders][kRealm] = relevantRealm
+ let subtype = "";
+ while (position < input.length && input[position] !== ";") {
+ subtype += input[position];
+ ++position;
+ }
- // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
- initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
+ subtype = removeTrailingHTTPWhitespace(subtype);
- // 5. Return responseObject.
- return responseObject
+ if (subtype.length === 0 || !solelyContainsHTTPTokenCodePoints(subtype)) {
+ return null;
}
- // Creates a redirect Response that redirects to url with status status.
- static redirect (url, status = 302) {
- const relevantRealm = { settingsObject: {} }
+ const mimeType = {
+ type: asciiLowercase(type),
+ subtype: asciiLowercase(subtype),
+ parameters: new Map()
+ };
- webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })
+ while (position < input.length) {
+ // Skip past ";"
+ ++position;
- url = webidl.converters.USVString(url)
- status = webidl.converters['unsigned short'](status)
+ while (isHTTPWhitespaceChar(input[position])) {
+ ++position;
+ }
- // 1. Let parsedURL be the result of parsing url with current settings
- // object’s API base URL.
- // 2. If parsedURL is failure, then throw a TypeError.
- // TODO: base-URL?
- let parsedURL
- try {
- parsedURL = new URL(url, getGlobalOrigin())
- } catch (err) {
- throw Object.assign(new TypeError('Failed to parse URL from ' + url), {
- cause: err
- })
+ let parameterName = "";
+ while (position < input.length && input[position] !== ";" && input[position] !== "=") {
+ parameterName += input[position];
+ ++position;
}
+ parameterName = asciiLowercase(parameterName);
- // 3. If status is not a redirect status, then throw a RangeError.
- if (!redirectStatusSet.has(status)) {
- throw new RangeError('Invalid status code ' + status)
+ if (position < input.length) {
+ if (input[position] === ";") {
+ continue;
+ }
+
+ // Skip past "="
+ ++position;
}
- // 4. Let responseObject be the result of creating a Response object,
- // given a new response, "immutable", and this’s relevant Realm.
- const responseObject = new Response()
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kGuard] = 'immutable'
- responseObject[kHeaders][kRealm] = relevantRealm
+ let parameterValue = null;
+ if (input[position] === "\"") {
+ [parameterValue, position] = collectAnHTTPQuotedString(input, position);
- // 5. Set responseObject’s response’s status to status.
- responseObject[kState].status = status
+ while (position < input.length && input[position] !== ";") {
+ ++position;
+ }
+ } else {
+ parameterValue = "";
+ while (position < input.length && input[position] !== ";") {
+ parameterValue += input[position];
+ ++position;
+ }
- // 6. Let value be parsedURL, serialized and isomorphic encoded.
- const value = isomorphicEncode(URLSerializer(parsedURL))
+ parameterValue = removeTrailingHTTPWhitespace(parameterValue);
- // 7. Append `Location`/value to responseObject’s response’s header list.
- responseObject[kState].headersList.append('location', value)
+ if (parameterValue === "") {
+ continue;
+ }
+ }
- // 8. Return responseObject.
- return responseObject
+ if (parameterName.length > 0 &&
+ solelyContainsHTTPTokenCodePoints(parameterName) &&
+ soleyContainsHTTPQuotedStringTokenCodePoints(parameterValue) &&
+ !mimeType.parameters.has(parameterName)) {
+ mimeType.parameters.set(parameterName, parameterValue);
+ }
}
- // https://fetch.spec.whatwg.org/#dom-response
- constructor (body = null, init = {}) {
- if (body !== null) {
- body = webidl.converters.BodyInit(body)
- }
+ return mimeType;
+};
- init = webidl.converters.ResponseInit(init)
- // TODO
- this[kRealm] = { settingsObject: {} }
+/***/ }),
- // 1. Set this’s response to a new response.
- this[kState] = makeResponse({})
+/***/ 15363:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Set this’s headers to a new Headers object with this’s relevant
- // Realm, whose header list is this’s response’s header list and guard
- // is "response".
- this[kHeaders] = new Headers(kConstruct)
- this[kHeaders][kGuard] = 'response'
- this[kHeaders][kHeadersList] = this[kState].headersList
- this[kHeaders][kRealm] = this[kRealm]
- // 3. Let bodyWithType be null.
- let bodyWithType = null
+const { solelyContainsHTTPTokenCodePoints } = __nccwpck_require__(74694);
- // 4. If body is non-null, then set bodyWithType to the result of extracting body.
- if (body != null) {
- const [extractedBody, type] = extractBody(body)
- bodyWithType = { body: extractedBody, type }
- }
+module.exports = mimeType => {
+ let serialization = `${mimeType.type}/${mimeType.subtype}`;
- // 5. Perform initialize a response given this, init, and bodyWithType.
- initializeResponse(this, init, bodyWithType)
+ if (mimeType.parameters.size === 0) {
+ return serialization;
}
- // Returns response’s type, e.g., "cors".
- get type () {
- webidl.brandCheck(this, Response)
+ for (let [name, value] of mimeType.parameters) {
+ serialization += ";";
+ serialization += name;
+ serialization += "=";
- // The type getter steps are to return this’s response’s type.
- return this[kState].type
+ if (!solelyContainsHTTPTokenCodePoints(value) || value.length === 0) {
+ value = value.replace(/(["\\])/ug, "\\$1");
+ value = `"${value}"`;
+ }
+
+ serialization += value;
}
- // Returns response’s URL, if it has one; otherwise the empty string.
- get url () {
- webidl.brandCheck(this, Response)
+ return serialization;
+};
- const urlList = this[kState].urlList
- // The url getter steps are to return the empty string if this’s
- // response’s URL is null; otherwise this’s response’s URL,
- // serialized with exclude fragment set to true.
- const url = urlList[urlList.length - 1] ?? null
+/***/ }),
- if (url === null) {
- return ''
- }
+/***/ 74694:
+/***/ ((__unused_webpack_module, exports) => {
- return URLSerializer(url, true)
- }
- // Returns whether response was obtained through a redirect.
- get redirected () {
- webidl.brandCheck(this, Response)
- // The redirected getter steps are to return true if this’s response’s URL
- // list has more than one item; otherwise false.
- return this[kState].urlList.length > 1
- }
+exports.removeLeadingAndTrailingHTTPWhitespace = string => {
+ return string.replace(/^[ \t\n\r]+/u, "").replace(/[ \t\n\r]+$/u, "");
+};
- // Returns response’s status.
- get status () {
- webidl.brandCheck(this, Response)
+exports.removeTrailingHTTPWhitespace = string => {
+ return string.replace(/[ \t\n\r]+$/u, "");
+};
- // The status getter steps are to return this’s response’s status.
- return this[kState].status
- }
+exports.isHTTPWhitespaceChar = char => {
+ return char === " " || char === "\t" || char === "\n" || char === "\r";
+};
- // Returns whether response’s status is an ok status.
- get ok () {
- webidl.brandCheck(this, Response)
+exports.solelyContainsHTTPTokenCodePoints = string => {
+ return /^[-!#$%&'*+.^_`|~A-Za-z0-9]*$/u.test(string);
+};
- // The ok getter steps are to return true if this’s response’s status is an
- // ok status; otherwise false.
- return this[kState].status >= 200 && this[kState].status <= 299
- }
+exports.soleyContainsHTTPQuotedStringTokenCodePoints = string => {
+ return /^[\t\u0020-\u007E\u0080-\u00FF]*$/u.test(string);
+};
- // Returns response’s status message.
- get statusText () {
- webidl.brandCheck(this, Response)
+exports.asciiLowercase = string => {
+ return string.replace(/[A-Z]/ug, l => l.toLowerCase());
+};
- // The statusText getter steps are to return this’s response’s status
- // message.
- return this[kState].statusText
- }
+// This variant only implements it with the extract-value flag set.
+exports.collectAnHTTPQuotedString = (input, position) => {
+ let value = "";
- // Returns response’s headers as Headers.
- get headers () {
- webidl.brandCheck(this, Response)
+ position++;
- // The headers getter steps are to return this’s headers.
- return this[kHeaders]
- }
+ while (true) {
+ while (position < input.length && input[position] !== "\"" && input[position] !== "\\") {
+ value += input[position];
+ ++position;
+ }
- get body () {
- webidl.brandCheck(this, Response)
+ if (position >= input.length) {
+ break;
+ }
- return this[kState].body ? this[kState].body.stream : null
- }
+ const quoteOrBackslash = input[position];
+ ++position;
- get bodyUsed () {
- webidl.brandCheck(this, Response)
+ if (quoteOrBackslash === "\\") {
+ if (position >= input.length) {
+ value += "\\";
+ break;
+ }
- return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
+ value += input[position];
+ ++position;
+ } else {
+ break;
+ }
}
- // Returns a clone of response.
- clone () {
- webidl.brandCheck(this, Response)
+ return [value, position];
+};
- // 1. If this is unusable, then throw a TypeError.
- if (this.bodyUsed || (this.body && this.body.locked)) {
- throw webidl.errors.exception({
- header: 'Response.clone',
- message: 'Body has already been consumed.'
- })
- }
- // 2. Let clonedResponse be the result of cloning this’s response.
- const clonedResponse = cloneResponse(this[kState])
+/***/ }),
- // 3. Return the result of creating a Response object, given
- // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
- const clonedResponseObject = new Response()
- clonedResponseObject[kState] = clonedResponse
- clonedResponseObject[kRealm] = this[kRealm]
- clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList
- clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]
- clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]
+/***/ 27460:
+/***/ ((module) => {
- return clonedResponseObject
+// Returns a wrapper function that returns a wrapped callback
+// The wrapper function should do some stuff, and return a
+// presumably different callback function.
+// This makes sure that own properties are retained, so that
+// decorations and such are not lost along the way.
+module.exports = wrappy
+function wrappy (fn, cb) {
+ if (fn && cb) return wrappy(fn)(cb)
+
+ if (typeof fn !== 'function')
+ throw new TypeError('need wrapper function')
+
+ Object.keys(fn).forEach(function (k) {
+ wrapper[k] = fn[k]
+ })
+
+ return wrapper
+
+ function wrapper() {
+ var args = new Array(arguments.length)
+ for (var i = 0; i < args.length; i++) {
+ args[i] = arguments[i]
+ }
+ var ret = fn.apply(this, args)
+ var cb = args[args.length-1]
+ if (typeof ret === 'function' && ret !== cb) {
+ Object.keys(cb).forEach(function (k) {
+ ret[k] = cb[k]
+ })
+ }
+ return ret
}
}
-mixinBody(Response)
-Object.defineProperties(Response.prototype, {
- type: kEnumerableProperty,
- url: kEnumerableProperty,
- status: kEnumerableProperty,
- ok: kEnumerableProperty,
- redirected: kEnumerableProperty,
- statusText: kEnumerableProperty,
- headers: kEnumerableProperty,
- clone: kEnumerableProperty,
- body: kEnumerableProperty,
- bodyUsed: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'Response',
- configurable: true
- }
-})
+/***/ }),
-Object.defineProperties(Response, {
- json: kEnumerableProperty,
- redirect: kEnumerableProperty,
- error: kEnumerableProperty
-})
+/***/ 73700:
+/***/ ((module) => {
-// https://fetch.spec.whatwg.org/#concept-response-clone
-function cloneResponse (response) {
- // To clone a response response, run these steps:
+module.exports = eval("require")("osx-temperature-sensor");
- // 1. If response is a filtered response, then return a new identical
- // filtered response whose internal response is a clone of response’s
- // internal response.
- if (response.internalResponse) {
- return filterResponse(
- cloneResponse(response.internalResponse),
- response.type
- )
- }
- // 2. Let newResponse be a copy of response, except for its body.
- const newResponse = makeResponse({ ...response, body: null })
+/***/ }),
- // 3. If response’s body is non-null, then set newResponse’s body to the
- // result of cloning response’s body.
- if (response.body != null) {
- newResponse.body = cloneBody(response.body)
- }
+/***/ 52704:
+/***/ ((module) => {
- // 4. Return newResponse.
- return newResponse
-}
+module.exports = eval("require")("supports-color");
-function makeResponse (init) {
- return {
- aborted: false,
- rangeRequested: false,
- timingAllowPassed: false,
- requestIncludesCredentials: false,
- type: 'default',
- status: 200,
- timingInfo: null,
- cacheState: '',
- statusText: '',
- ...init,
- headersList: init.headersList
- ? new HeadersList(init.headersList)
- : new HeadersList(),
- urlList: init.urlList ? [...init.urlList] : []
- }
-}
-function makeNetworkError (reason) {
- const isError = isErrorLike(reason)
- return makeResponse({
- type: 'error',
- status: 0,
- error: isError
- ? reason
- : new Error(reason ? String(reason) : reason),
- aborted: reason && reason.name === 'AbortError'
- })
-}
+/***/ }),
-function makeFilteredResponse (response, state) {
- state = {
- internalResponse: response,
- ...state
- }
+/***/ 42613:
+/***/ ((module) => {
- return new Proxy(response, {
- get (target, p) {
- return p in state ? state[p] : target[p]
- },
- set (target, p, value) {
- assert(!(p in state))
- target[p] = value
- return true
- }
- })
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert");
-// https://fetch.spec.whatwg.org/#concept-filtered-response
-function filterResponse (response, type) {
- // Set response to the following filtered response with response as its
- // internal response, depending on request’s response tainting:
- if (type === 'basic') {
- // A basic filtered response is a filtered response whose type is "basic"
- // and header list excludes any headers in internal response’s header list
- // whose name is a forbidden response-header name.
+/***/ }),
- // Note: undici does not implement forbidden response-header names
- return makeFilteredResponse(response, {
- type: 'basic',
- headersList: response.headersList
- })
- } else if (type === 'cors') {
- // A CORS filtered response is a filtered response whose type is "cors"
- // and header list excludes any headers in internal response’s header
- // list whose name is not a CORS-safelisted response-header name, given
- // internal response’s CORS-exposed header-name list.
+/***/ 90290:
+/***/ ((module) => {
- // Note: undici does not implement CORS-safelisted response-header names
- return makeFilteredResponse(response, {
- type: 'cors',
- headersList: response.headersList
- })
- } else if (type === 'opaque') {
- // An opaque filtered response is a filtered response whose type is
- // "opaque", URL list is the empty list, status is 0, status message
- // is the empty byte sequence, header list is empty, and body is null.
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks");
- return makeFilteredResponse(response, {
- type: 'opaque',
- urlList: Object.freeze([]),
- status: 0,
- statusText: '',
- body: null
- })
- } else if (type === 'opaqueredirect') {
- // An opaque-redirect filtered response is a filtered response whose type
- // is "opaqueredirect", status is 0, status message is the empty byte
- // sequence, header list is empty, and body is null.
+/***/ }),
+
+/***/ 20181:
+/***/ ((module) => {
+
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer");
+
+/***/ }),
+
+/***/ 35317:
+/***/ ((module) => {
- return makeFilteredResponse(response, {
- type: 'opaqueredirect',
- status: 0,
- statusText: '',
- headersList: [],
- body: null
- })
- } else {
- assert(false)
- }
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process");
-// https://fetch.spec.whatwg.org/#appropriate-network-error
-function makeAppropriateNetworkError (fetchParams, err = null) {
- // 1. Assert: fetchParams is canceled.
- assert(isCancelled(fetchParams))
+/***/ }),
- // 2. Return an aborted network error if fetchParams is aborted;
- // otherwise return a network error.
- return isAborted(fetchParams)
- ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))
- : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))
-}
+/***/ 64236:
+/***/ ((module) => {
-// https://whatpr.org/fetch/1392.html#initialize-a-response
-function initializeResponse (response, init, body) {
- // 1. If init["status"] is not in the range 200 to 599, inclusive, then
- // throw a RangeError.
- if (init.status !== null && (init.status < 200 || init.status > 599)) {
- throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console");
- // 2. If init["statusText"] does not match the reason-phrase token production,
- // then throw a TypeError.
- if ('statusText' in init && init.statusText != null) {
- // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:
- // reason-phrase = *( HTAB / SP / VCHAR / obs-text )
- if (!isValidReasonPhrase(String(init.statusText))) {
- throw new TypeError('Invalid statusText')
- }
- }
+/***/ }),
- // 3. Set response’s response’s status to init["status"].
- if ('status' in init && init.status != null) {
- response[kState].status = init.status
- }
+/***/ 76982:
+/***/ ((module) => {
- // 4. Set response’s response’s status message to init["statusText"].
- if ('statusText' in init && init.statusText != null) {
- response[kState].statusText = init.statusText
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto");
- // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
- if ('headers' in init && init.headers != null) {
- fill(response[kHeaders], init.headers)
- }
+/***/ }),
- // 6. If body was given, then:
- if (body) {
- // 1. If response's status is a null body status, then throw a TypeError.
- if (nullBodyStatus.includes(response.status)) {
- throw webidl.errors.exception({
- header: 'Response constructor',
- message: 'Invalid response status code ' + response.status
- })
- }
+/***/ 31637:
+/***/ ((module) => {
- // 2. Set response's body to body's body.
- response[kState].body = body.body
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel");
- // 3. If body's type is non-null and response's header list does not contain
- // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.
- if (body.type != null && !response[kState].headersList.contains('Content-Type')) {
- response[kState].headersList.append('content-type', body.type)
- }
- }
-}
+/***/ }),
-webidl.converters.ReadableStream = webidl.interfaceConverter(
- ReadableStream
-)
+/***/ 24434:
+/***/ ((module) => {
-webidl.converters.FormData = webidl.interfaceConverter(
- FormData
-)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events");
-webidl.converters.URLSearchParams = webidl.interfaceConverter(
- URLSearchParams
-)
+/***/ }),
-// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
-webidl.converters.XMLHttpRequestBodyInit = function (V) {
- if (typeof V === 'string') {
- return webidl.converters.USVString(V)
- }
+/***/ 79896:
+/***/ ((module) => {
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");
- if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {
- return webidl.converters.BufferSource(V)
- }
+/***/ }),
- if (util.isFormDataLike(V)) {
- return webidl.converters.FormData(V, { strict: false })
- }
+/***/ 58611:
+/***/ ((module) => {
- if (V instanceof URLSearchParams) {
- return webidl.converters.URLSearchParams(V)
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http");
- return webidl.converters.DOMString(V)
-}
+/***/ }),
-// https://fetch.spec.whatwg.org/#bodyinit
-webidl.converters.BodyInit = function (V) {
- if (V instanceof ReadableStream) {
- return webidl.converters.ReadableStream(V)
- }
+/***/ 85675:
+/***/ ((module) => {
- // Note: the spec doesn't include async iterables,
- // this is an undici extension.
- if (V?.[Symbol.asyncIterator]) {
- return V
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2");
- return webidl.converters.XMLHttpRequestBodyInit(V)
-}
+/***/ }),
-webidl.converters.ResponseInit = webidl.dictionaryConverter([
- {
- key: 'status',
- converter: webidl.converters['unsigned short'],
- defaultValue: 200
- },
- {
- key: 'statusText',
- converter: webidl.converters.ByteString,
- defaultValue: ''
- },
- {
- key: 'headers',
- converter: webidl.converters.HeadersInit
- }
-])
+/***/ 65692:
+/***/ ((module) => {
-module.exports = {
- makeNetworkError,
- makeResponse,
- makeAppropriateNetworkError,
- filterResponse,
- Response,
- cloneResponse
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https");
+
+/***/ }),
+
+/***/ 69278:
+/***/ ((module) => {
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net");
/***/ }),
-/***/ 63730:
+/***/ 34589:
/***/ ((module) => {
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:assert");
+/***/ }),
-module.exports = {
- kUrl: Symbol('url'),
- kHeaders: Symbol('headers'),
- kSignal: Symbol('signal'),
- kState: Symbol('state'),
- kGuard: Symbol('guard'),
- kRealm: Symbol('realm')
-}
+/***/ 16698:
+/***/ ((module) => {
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:async_hooks");
/***/ }),
-/***/ 72847:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 4573:
+/***/ ((module) => {
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer");
+/***/ }),
-const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(21234)
-const { getGlobalOrigin } = __nccwpck_require__(62896)
-const { performance } = __nccwpck_require__(82987)
-const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(89500)
-const assert = __nccwpck_require__(42613)
-const { isUint8Array } = __nccwpck_require__(98253)
+/***/ 37540:
+/***/ ((module) => {
-let supportedHashes = []
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:console");
-// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
-/** @type {import('crypto')|undefined} */
-let crypto
+/***/ }),
-try {
- crypto = __nccwpck_require__(76982)
- const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
- supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
-/* c8 ignore next 3 */
-} catch {
-}
+/***/ 77598:
+/***/ ((module) => {
-function responseURL (response) {
- // https://fetch.spec.whatwg.org/#responses
- // A response has an associated URL. It is a pointer to the last URL
- // in response’s URL list and null if response’s URL list is empty.
- const urlList = response.urlList
- const length = urlList.length
- return length === 0 ? null : urlList[length - 1].toString()
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto");
-// https://fetch.spec.whatwg.org/#concept-response-location-url
-function responseLocationURL (response, requestFragment) {
- // 1. If response’s status is not a redirect status, then return null.
- if (!redirectStatusSet.has(response.status)) {
- return null
- }
+/***/ }),
- // 2. Let location be the result of extracting header list values given
- // `Location` and response’s header list.
- let location = response.headersList.get('location')
+/***/ 53053:
+/***/ ((module) => {
- // 3. If location is a header value, then set location to the result of
- // parsing location with response’s URL.
- if (location !== null && isValidHeaderValue(location)) {
- location = new URL(location, responseURL(response))
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:diagnostics_channel");
- // 4. If location is a URL whose fragment is null, then set location’s
- // fragment to requestFragment.
- if (location && !location.hash) {
- location.hash = requestFragment
- }
+/***/ }),
- // 5. Return location.
- return location
-}
+/***/ 78474:
+/***/ ((module) => {
-/** @returns {URL} */
-function requestCurrentURL (request) {
- return request.urlList[request.urlList.length - 1]
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events");
-function requestBadPort (request) {
- // 1. Let url be request’s current URL.
- const url = requestCurrentURL(request)
+/***/ }),
- // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,
- // then return blocked.
- if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
- return 'blocked'
- }
+/***/ 37067:
+/***/ ((module) => {
- // 3. Return allowed.
- return 'allowed'
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http");
-function isErrorLike (object) {
- return object instanceof Error || (
- object?.constructor?.name === 'Error' ||
- object?.constructor?.name === 'DOMException'
- )
-}
+/***/ }),
-// Check whether |statusText| is a ByteString and
-// matches the Reason-Phrase token production.
-// RFC 2616: https://tools.ietf.org/html/rfc2616
-// RFC 7230: https://tools.ietf.org/html/rfc7230
-// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )"
-// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116
-function isValidReasonPhrase (statusText) {
- for (let i = 0; i < statusText.length; ++i) {
- const c = statusText.charCodeAt(i)
- if (
- !(
- (
- c === 0x09 || // HTAB
- (c >= 0x20 && c <= 0x7e) || // SP / VCHAR
- (c >= 0x80 && c <= 0xff)
- ) // obs-text
- )
- ) {
- return false
- }
- }
- return true
-}
+/***/ 32467:
+/***/ ((module) => {
-/**
- * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
- * @param {number} c
- */
-function isTokenCharCode (c) {
- switch (c) {
- case 0x22:
- case 0x28:
- case 0x29:
- case 0x2c:
- case 0x2f:
- case 0x3a:
- case 0x3b:
- case 0x3c:
- case 0x3d:
- case 0x3e:
- case 0x3f:
- case 0x40:
- case 0x5b:
- case 0x5c:
- case 0x5d:
- case 0x7b:
- case 0x7d:
- // DQUOTE and "(),/:;<=>?@[\]{}"
- return false
- default:
- // VCHAR %x21-7E
- return c >= 0x21 && c <= 0x7e
- }
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http2");
-/**
- * @param {string} characters
- */
-function isValidHTTPToken (characters) {
- if (characters.length === 0) {
- return false
- }
- for (let i = 0; i < characters.length; ++i) {
- if (!isTokenCharCode(characters.charCodeAt(i))) {
- return false
- }
- }
- return true
-}
+/***/ }),
-/**
- * @see https://fetch.spec.whatwg.org/#header-name
- * @param {string} potentialValue
- */
-function isValidHeaderName (potentialValue) {
- return isValidHTTPToken(potentialValue)
-}
+/***/ 44708:
+/***/ ((module) => {
-/**
- * @see https://fetch.spec.whatwg.org/#header-value
- * @param {string} potentialValue
- */
-function isValidHeaderValue (potentialValue) {
- // - Has no leading or trailing HTTP tab or space bytes.
- // - Contains no 0x00 (NUL) or HTTP newline bytes.
- if (
- potentialValue.startsWith('\t') ||
- potentialValue.startsWith(' ') ||
- potentialValue.endsWith('\t') ||
- potentialValue.endsWith(' ')
- ) {
- return false
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:https");
- if (
- potentialValue.includes('\0') ||
- potentialValue.includes('\r') ||
- potentialValue.includes('\n')
- ) {
- return false
- }
+/***/ }),
- return true
-}
+/***/ 77030:
+/***/ ((module) => {
-// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
-function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
- // Given a request request and a response actualResponse, this algorithm
- // updates request’s referrer policy according to the Referrer-Policy
- // header (if any) in actualResponse.
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net");
- // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
- // from a Referrer-Policy header on actualResponse.
+/***/ }),
- // 8.1 Parse a referrer policy from a Referrer-Policy header
- // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
- const { headersList } = actualResponse
- // 2. Let policy be the empty string.
- // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.
- // 4. Return policy.
- const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')
+/***/ 48161:
+/***/ ((module) => {
- // Note: As the referrer-policy can contain multiple policies
- // separated by comma, we need to loop through all of them
- // and pick the first valid one.
- // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy
- let policy = ''
- if (policyHeader.length > 0) {
- // The right-most policy takes precedence.
- // The left-most policy is the fallback.
- for (let i = policyHeader.length; i !== 0; i--) {
- const token = policyHeader[i - 1].trim()
- if (referrerPolicyTokens.has(token)) {
- policy = token
- break
- }
- }
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:os");
- // 2. If policy is not the empty string, then set request’s referrer policy to policy.
- if (policy !== '') {
- request.referrerPolicy = policy
- }
-}
+/***/ }),
-// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
-function crossOriginResourcePolicyCheck () {
- // TODO
- return 'allowed'
-}
+/***/ 643:
+/***/ ((module) => {
-// https://fetch.spec.whatwg.org/#concept-cors-check
-function corsCheck () {
- // TODO
- return 'success'
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:perf_hooks");
-// https://fetch.spec.whatwg.org/#concept-tao-check
-function TAOCheck () {
- // TODO
- return 'success'
-}
+/***/ }),
-function appendFetchMetadata (httpRequest) {
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
- // TODO
+/***/ 1708:
+/***/ ((module) => {
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:process");
- // 1. Assert: r’s url is a potentially trustworthy URL.
- // TODO
+/***/ }),
- // 2. Let header be a Structured Header whose value is a token.
- let header = null
+/***/ 41792:
+/***/ ((module) => {
- // 3. Set header’s value to r’s mode.
- header = httpRequest.mode
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:querystring");
- // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
- httpRequest.headersList.set('sec-fetch-mode', header)
+/***/ }),
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
- // TODO
+/***/ 57075:
+/***/ ((module) => {
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
- // TODO
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream");
-// https://fetch.spec.whatwg.org/#append-a-request-origin-header
-function appendRequestOriginHeader (request) {
- // 1. Let serializedOrigin be the result of byte-serializing a request origin with request.
- let serializedOrigin = request.origin
+/***/ }),
- // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list.
- if (request.responseTainting === 'cors' || request.mode === 'websocket') {
- if (serializedOrigin) {
- request.headersList.append('origin', serializedOrigin)
- }
+/***/ 41692:
+/***/ ((module) => {
- // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
- } else if (request.method !== 'GET' && request.method !== 'HEAD') {
- // 1. Switch on request’s referrer policy:
- switch (request.referrerPolicy) {
- case 'no-referrer':
- // Set serializedOrigin to `null`.
- serializedOrigin = null
- break
- case 'no-referrer-when-downgrade':
- case 'strict-origin':
- case 'strict-origin-when-cross-origin':
- // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`.
- if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
- serializedOrigin = null
- }
- break
- case 'same-origin':
- // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`.
- if (!sameOrigin(request, requestCurrentURL(request))) {
- serializedOrigin = null
- }
- break
- default:
- // Do nothing.
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:tls");
- if (serializedOrigin) {
- // 2. Append (`Origin`, serializedOrigin) to request’s header list.
- request.headersList.append('origin', serializedOrigin)
- }
- }
-}
+/***/ }),
-function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
- // TODO
- return performance.now()
-}
+/***/ 73136:
+/***/ ((module) => {
-// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
-function createOpaqueTimingInfo (timingInfo) {
- return {
- startTime: timingInfo.startTime ?? 0,
- redirectStartTime: 0,
- redirectEndTime: 0,
- postRedirectStartTime: timingInfo.startTime ?? 0,
- finalServiceWorkerStartTime: 0,
- finalNetworkResponseStartTime: 0,
- finalNetworkRequestStartTime: 0,
- endTime: 0,
- encodedBodySize: 0,
- decodedBodySize: 0,
- finalConnectionTimingInfo: null
- }
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:url");
-// https://html.spec.whatwg.org/multipage/origin.html#policy-container
-function makePolicyContainer () {
- // Note: the fetch spec doesn't make use of embedder policy or CSP list
- return {
- referrerPolicy: 'strict-origin-when-cross-origin'
- }
-}
+/***/ }),
-// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
-function clonePolicyContainer (policyContainer) {
- return {
- referrerPolicy: policyContainer.referrerPolicy
- }
-}
+/***/ 57975:
+/***/ ((module) => {
-// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
-function determineRequestsReferrer (request) {
- // 1. Let policy be request's referrer policy.
- const policy = request.referrerPolicy
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util");
- // Note: policy cannot (shouldn't) be null or an empty string.
- assert(policy)
+/***/ }),
- // 2. Let environment be request’s client.
+/***/ 73429:
+/***/ ((module) => {
- let referrerSource = null
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util/types");
- // 3. Switch on request’s referrer:
- if (request.referrer === 'client') {
- // Note: node isn't a browser and doesn't implement document/iframes,
- // so we bypass this step and replace it with our own.
+/***/ }),
- const globalOrigin = getGlobalOrigin()
+/***/ 75919:
+/***/ ((module) => {
- if (!globalOrigin || globalOrigin.origin === 'null') {
- return 'no-referrer'
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:worker_threads");
- // note: we need to clone it as it's mutated
- referrerSource = new URL(globalOrigin)
- } else if (request.referrer instanceof URL) {
- // Let referrerSource be request’s referrer.
- referrerSource = request.referrer
- }
+/***/ }),
- // 4. Let request’s referrerURL be the result of stripping referrerSource for
- // use as a referrer.
- let referrerURL = stripURLForReferrer(referrerSource)
+/***/ 38522:
+/***/ ((module) => {
- // 5. Let referrerOrigin be the result of stripping referrerSource for use as
- // a referrer, with the origin-only flag set to true.
- const referrerOrigin = stripURLForReferrer(referrerSource, true)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:zlib");
- // 6. If the result of serializing referrerURL is a string whose length is
- // greater than 4096, set referrerURL to referrerOrigin.
- if (referrerURL.toString().length > 4096) {
- referrerURL = referrerOrigin
- }
+/***/ }),
- const areSameOrigin = sameOrigin(request, referrerURL)
- const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
- !isURLPotentiallyTrustworthy(request.url)
+/***/ 70857:
+/***/ ((module) => {
- // 8. Execute the switch statements corresponding to the value of policy:
- switch (policy) {
- case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
- case 'unsafe-url': return referrerURL
- case 'same-origin':
- return areSameOrigin ? referrerOrigin : 'no-referrer'
- case 'origin-when-cross-origin':
- return areSameOrigin ? referrerURL : referrerOrigin
- case 'strict-origin-when-cross-origin': {
- const currentURL = requestCurrentURL(request)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os");
- // 1. If the origin of referrerURL and the origin of request’s current
- // URL are the same, then return referrerURL.
- if (sameOrigin(referrerURL, currentURL)) {
- return referrerURL
- }
+/***/ }),
- // 2. If referrerURL is a potentially trustworthy URL and request’s
- // current URL is not a potentially trustworthy URL, then return no
- // referrer.
- if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
- return 'no-referrer'
- }
+/***/ 16928:
+/***/ ((module) => {
- // 3. Return referrerOrigin.
- return referrerOrigin
- }
- case 'strict-origin': // eslint-disable-line
- /**
- * 1. If referrerURL is a potentially trustworthy URL and
- * request’s current URL is not a potentially trustworthy URL,
- * then return no referrer.
- * 2. Return referrerOrigin
- */
- case 'no-referrer-when-downgrade': // eslint-disable-line
- /**
- * 1. If referrerURL is a potentially trustworthy URL and
- * request’s current URL is not a potentially trustworthy URL,
- * then return no referrer.
- * 2. Return referrerOrigin
- */
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");
- default: // eslint-disable-line
- return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
- }
-}
+/***/ }),
-/**
- * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
- * @param {URL} url
- * @param {boolean|undefined} originOnly
- */
-function stripURLForReferrer (url, originOnly) {
- // 1. Assert: url is a URL.
- assert(url instanceof URL)
+/***/ 82987:
+/***/ ((module) => {
- // 2. If url’s scheme is a local scheme, then return no referrer.
- if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
- return 'no-referrer'
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks");
- // 3. Set url’s username to the empty string.
- url.username = ''
+/***/ }),
- // 4. Set url’s password to the empty string.
- url.password = ''
+/***/ 83480:
+/***/ ((module) => {
- // 5. Set url’s fragment to null.
- url.hash = ''
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring");
- // 6. If the origin-only flag is true, then:
- if (originOnly) {
- // 1. Set url’s path to « the empty string ».
- url.pathname = ''
+/***/ }),
- // 2. Set url’s query to null.
- url.search = ''
- }
+/***/ 2203:
+/***/ ((module) => {
- // 7. Return url.
- return url
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream");
-function isURLPotentiallyTrustworthy (url) {
- if (!(url instanceof URL)) {
- return false
- }
+/***/ }),
- // If child of about, return true
- if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
- return true
- }
+/***/ 63774:
+/***/ ((module) => {
- // If scheme is data, return true
- if (url.protocol === 'data:') return true
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web");
- // If file, return true
- if (url.protocol === 'file:') return true
+/***/ }),
- return isOriginPotentiallyTrustworthy(url.origin)
+/***/ 13193:
+/***/ ((module) => {
- function isOriginPotentiallyTrustworthy (origin) {
- // If origin is explicitly null, return false
- if (origin == null || origin === 'null') return false
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder");
- const originAsURL = new URL(origin)
+/***/ }),
- // If secure, return true
- if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
- return true
- }
+/***/ 53557:
+/***/ ((module) => {
- // If localhost or variants, return true
- if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
- (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
- (originAsURL.hostname.endsWith('.localhost'))) {
- return true
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers");
- // If any other, return false
- return false
- }
-}
+/***/ }),
-/**
- * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
- * @param {Uint8Array} bytes
- * @param {string} metadataList
- */
-function bytesMatch (bytes, metadataList) {
- // If node is not built with OpenSSL support, we cannot check
- // a request's integrity, so allow it by default (the spec will
- // allow requests if an invalid hash is given, as precedence).
- /* istanbul ignore if: only if node is built with --without-ssl */
- if (crypto === undefined) {
- return true
- }
+/***/ 64756:
+/***/ ((module) => {
- // 1. Let parsedMetadata be the result of parsing metadataList.
- const parsedMetadata = parseMetadata(metadataList)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls");
- // 2. If parsedMetadata is no metadata, return true.
- if (parsedMetadata === 'no metadata') {
- return true
- }
+/***/ }),
- // 3. If response is not eligible for integrity validation, return false.
- // TODO
+/***/ 52018:
+/***/ ((module) => {
- // 4. If parsedMetadata is the empty set, return true.
- if (parsedMetadata.length === 0) {
- return true
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty");
- // 5. Let metadata be the result of getting the strongest
- // metadata from parsedMetadata.
- const strongest = getStrongestMetadata(parsedMetadata)
- const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)
+/***/ }),
- // 6. For each item in metadata:
- for (const item of metadata) {
- // 1. Let algorithm be the alg component of item.
- const algorithm = item.algo
+/***/ 87016:
+/***/ ((module) => {
- // 2. Let expectedValue be the val component of item.
- const expectedValue = item.hash
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url");
- // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e
- // "be liberal with padding". This is annoying, and it's not even in the spec.
+/***/ }),
- // 3. Let actualValue be the result of applying algorithm to bytes.
- let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
+/***/ 39023:
+/***/ ((module) => {
- if (actualValue[actualValue.length - 1] === '=') {
- if (actualValue[actualValue.length - 2] === '=') {
- actualValue = actualValue.slice(0, -2)
- } else {
- actualValue = actualValue.slice(0, -1)
- }
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util");
- // 4. If actualValue is a case-sensitive match for expectedValue,
- // return true.
- if (compareBase64Mixed(actualValue, expectedValue)) {
- return true
- }
- }
+/***/ }),
- // 7. Return false.
- return false
-}
+/***/ 98253:
+/***/ ((module) => {
-// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options
-// https://www.w3.org/TR/CSP2/#source-list-syntax
-// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1
-const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types");
+
+/***/ }),
+
+/***/ 28167:
+/***/ ((module) => {
+
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads");
+
+/***/ }),
+
+/***/ 43106:
+/***/ ((module) => {
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib");
+
+/***/ }),
+
+/***/ 85276:
+/***/ ((__unused_webpack_module, exports) => {
+
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AbortError = void 0;
/**
- * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
- * @param {string} metadata
+ * This error is thrown when an asynchronous operation has been aborted.
+ * Check for this error by testing the `name` that the name property of the
+ * error matches `"AbortError"`.
+ *
+ * @example
+ * ```ts
+ * const controller = new AbortController();
+ * controller.abort();
+ * try {
+ * doAsyncWork(controller.signal)
+ * } catch (e) {
+ * if (e.name === 'AbortError') {
+ * // handle abort error here.
+ * }
+ * }
+ * ```
*/
-function parseMetadata (metadata) {
- // 1. Let result be the empty set.
- /** @type {{ algo: string, hash: string }[]} */
- const result = []
+class AbortError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
+ }
+}
+exports.AbortError = AbortError;
+//# sourceMappingURL=AbortError.js.map
- // 2. Let empty be equal to true.
- let empty = true
+/***/ }),
- // 3. For each token returned by splitting metadata on spaces:
- for (const token of metadata.split(' ')) {
- // 1. Set empty to false.
- empty = false
+/***/ 92242:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. Parse token as a hash-with-options.
- const parsedToken = parseHashWithOptions.exec(token)
- // 3. If token does not parse, continue to the next token.
- if (
- parsedToken === null ||
- parsedToken.groups === undefined ||
- parsedToken.groups.algo === undefined
- ) {
- // Note: Chromium blocks the request at this point, but Firefox
- // gives a warning that an invalid integrity was given. The
- // correct behavior is to ignore these, and subsequently not
- // check the integrity of the resource.
- continue
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AbortError = void 0;
+var AbortError_js_1 = __nccwpck_require__(85276);
+Object.defineProperty(exports, "AbortError", ({ enumerable: true, get: function () { return AbortError_js_1.AbortError; } }));
+//# sourceMappingURL=index.js.map
- // 4. Let algorithm be the hash-algo component of token.
- const algorithm = parsedToken.groups.algo.toLowerCase()
+/***/ }),
- // 5. If algorithm is a hash function recognized by the user
- // agent, add the parsed token to result.
- if (supportedHashes.includes(algorithm)) {
- result.push(parsedToken.groups)
- }
- }
+/***/ 21746:
+/***/ ((__unused_webpack_module, exports) => {
- // 4. Return no metadata if empty is true, otherwise return result.
- if (empty === true) {
- return 'no metadata'
- }
- return result
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureKeyCredential = void 0;
+/**
+ * A static-key-based credential that supports updating
+ * the underlying key value.
+ */
+class AzureKeyCredential {
+ /**
+ * The value of the key to be used in authentication
+ */
+ get key() {
+ return this._key;
+ }
+ /**
+ * Create an instance of an AzureKeyCredential for use
+ * with a service client.
+ *
+ * @param key - The initial value of the key to use in authentication
+ */
+ constructor(key) {
+ if (!key) {
+ throw new Error("key must be a non-empty string");
+ }
+ this._key = key;
+ }
+ /**
+ * Change the value of the key.
+ *
+ * Updates will take effect upon the next request after
+ * updating the key value.
+ *
+ * @param newKey - The new key value to be used
+ */
+ update(newKey) {
+ this._key = newKey;
+ }
}
+exports.AzureKeyCredential = AzureKeyCredential;
+//# sourceMappingURL=azureKeyCredential.js.map
+/***/ }),
+
+/***/ 37859:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureNamedKeyCredential = void 0;
+exports.isNamedKeyCredential = isNamedKeyCredential;
+const core_util_1 = __nccwpck_require__(30991);
/**
- * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList
+ * A static name/key-based credential that supports updating
+ * the underlying name and key values.
*/
-function getStrongestMetadata (metadataList) {
- // Let algorithm be the algo component of the first item in metadataList.
- // Can be sha256
- let algorithm = metadataList[0].algo
- // If the algorithm is sha512, then it is the strongest
- // and we can return immediately
- if (algorithm[3] === '5') {
- return algorithm
- }
-
- for (let i = 1; i < metadataList.length; ++i) {
- const metadata = metadataList[i]
- // If the algorithm is sha512, then it is the strongest
- // and we can break the loop immediately
- if (metadata.algo[3] === '5') {
- algorithm = 'sha512'
- break
- // If the algorithm is sha384, then a potential sha256 or sha384 is ignored
- } else if (algorithm[3] === '3') {
- continue
- // algorithm is sha256, check if algorithm is sha384 and if so, set it as
- // the strongest
- } else if (metadata.algo[3] === '3') {
- algorithm = 'sha384'
+class AzureNamedKeyCredential {
+ /**
+ * The value of the key to be used in authentication.
+ */
+ get key() {
+ return this._key;
+ }
+ /**
+ * The value of the name to be used in authentication.
+ */
+ get name() {
+ return this._name;
+ }
+ /**
+ * Create an instance of an AzureNamedKeyCredential for use
+ * with a service client.
+ *
+ * @param name - The initial value of the name to use in authentication.
+ * @param key - The initial value of the key to use in authentication.
+ */
+ constructor(name, key) {
+ if (!name || !key) {
+ throw new TypeError("name and key must be non-empty strings");
+ }
+ this._name = name;
+ this._key = key;
+ }
+ /**
+ * Change the value of the key.
+ *
+ * Updates will take effect upon the next request after
+ * updating the key value.
+ *
+ * @param newName - The new name value to be used.
+ * @param newKey - The new key value to be used.
+ */
+ update(newName, newKey) {
+ if (!newName || !newKey) {
+ throw new TypeError("newName and newKey must be non-empty strings");
+ }
+ this._name = newName;
+ this._key = newKey;
}
- }
- return algorithm
}
+exports.AzureNamedKeyCredential = AzureNamedKeyCredential;
+/**
+ * Tests an object to determine whether it implements NamedKeyCredential.
+ *
+ * @param credential - The assumed NamedKeyCredential to be tested.
+ */
+function isNamedKeyCredential(credential) {
+ return ((0, core_util_1.isObjectWithProperties)(credential, ["name", "key"]) &&
+ typeof credential.key === "string" &&
+ typeof credential.name === "string");
+}
+//# sourceMappingURL=azureNamedKeyCredential.js.map
-function filterMetadataListByAlgorithm (metadataList, algorithm) {
- if (metadataList.length === 1) {
- return metadataList
- }
-
- let pos = 0
- for (let i = 0; i < metadataList.length; ++i) {
- if (metadataList[i].algo === algorithm) {
- metadataList[pos++] = metadataList[i]
- }
- }
+/***/ }),
- metadataList.length = pos
+/***/ 52372:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return metadataList
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureSASCredential = void 0;
+exports.isSASCredential = isSASCredential;
+const core_util_1 = __nccwpck_require__(30991);
/**
- * Compares two base64 strings, allowing for base64url
- * in the second string.
- *
-* @param {string} actualValue always base64
- * @param {string} expectedValue base64 or base64url
- * @returns {boolean}
+ * A static-signature-based credential that supports updating
+ * the underlying signature value.
*/
-function compareBase64Mixed (actualValue, expectedValue) {
- if (actualValue.length !== expectedValue.length) {
- return false
- }
- for (let i = 0; i < actualValue.length; ++i) {
- if (actualValue[i] !== expectedValue[i]) {
- if (
- (actualValue[i] === '+' && expectedValue[i] === '-') ||
- (actualValue[i] === '/' && expectedValue[i] === '_')
- ) {
- continue
- }
- return false
+class AzureSASCredential {
+ /**
+ * The value of the shared access signature to be used in authentication
+ */
+ get signature() {
+ return this._signature;
+ }
+ /**
+ * Create an instance of an AzureSASCredential for use
+ * with a service client.
+ *
+ * @param signature - The initial value of the shared access signature to use in authentication
+ */
+ constructor(signature) {
+ if (!signature) {
+ throw new Error("shared access signature must be a non-empty string");
+ }
+ this._signature = signature;
+ }
+ /**
+ * Change the value of the signature.
+ *
+ * Updates will take effect upon the next request after
+ * updating the signature value.
+ *
+ * @param newSignature - The new shared access signature value to be used
+ */
+ update(newSignature) {
+ if (!newSignature) {
+ throw new Error("shared access signature must be a non-empty string");
+ }
+ this._signature = newSignature;
}
- }
-
- return true
-}
-
-// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
-function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
- // TODO
}
-
+exports.AzureSASCredential = AzureSASCredential;
/**
- * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
- * @param {URL} A
- * @param {URL} B
+ * Tests an object to determine whether it implements SASCredential.
+ *
+ * @param credential - The assumed SASCredential to be tested.
*/
-function sameOrigin (A, B) {
- // 1. If A and B are the same opaque origin, then return true.
- if (A.origin === B.origin && A.origin === 'null') {
- return true
- }
-
- // 2. If A and B are both tuple origins and their schemes,
- // hosts, and port are identical, then return true.
- if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
- return true
- }
-
- // 3. Return false.
- return false
+function isSASCredential(credential) {
+ return ((0, core_util_1.isObjectWithProperties)(credential, ["signature"]) && typeof credential.signature === "string");
}
+//# sourceMappingURL=azureSASCredential.js.map
-function createDeferredPromise () {
- let res
- let rej
- const promise = new Promise((resolve, reject) => {
- res = resolve
- rej = reject
- })
+/***/ }),
- return { promise, resolve: res, reject: rej }
-}
+/***/ 15269:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-function isAborted (fetchParams) {
- return fetchParams.controller.state === 'aborted'
-}
-function isCancelled (fetchParams) {
- return fetchParams.controller.state === 'aborted' ||
- fetchParams.controller.state === 'terminated'
-}
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isTokenCredential = exports.isSASCredential = exports.AzureSASCredential = exports.isNamedKeyCredential = exports.AzureNamedKeyCredential = exports.isKeyCredential = exports.AzureKeyCredential = void 0;
+var azureKeyCredential_js_1 = __nccwpck_require__(21746);
+Object.defineProperty(exports, "AzureKeyCredential", ({ enumerable: true, get: function () { return azureKeyCredential_js_1.AzureKeyCredential; } }));
+var keyCredential_js_1 = __nccwpck_require__(67415);
+Object.defineProperty(exports, "isKeyCredential", ({ enumerable: true, get: function () { return keyCredential_js_1.isKeyCredential; } }));
+var azureNamedKeyCredential_js_1 = __nccwpck_require__(37859);
+Object.defineProperty(exports, "AzureNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.AzureNamedKeyCredential; } }));
+Object.defineProperty(exports, "isNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.isNamedKeyCredential; } }));
+var azureSASCredential_js_1 = __nccwpck_require__(52372);
+Object.defineProperty(exports, "AzureSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.AzureSASCredential; } }));
+Object.defineProperty(exports, "isSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.isSASCredential; } }));
+var tokenCredential_js_1 = __nccwpck_require__(64381);
+Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, get: function () { return tokenCredential_js_1.isTokenCredential; } }));
+//# sourceMappingURL=index.js.map
-const normalizeMethodRecord = {
- delete: 'DELETE',
- DELETE: 'DELETE',
- get: 'GET',
- GET: 'GET',
- head: 'HEAD',
- HEAD: 'HEAD',
- options: 'OPTIONS',
- OPTIONS: 'OPTIONS',
- post: 'POST',
- POST: 'POST',
- put: 'PUT',
- PUT: 'PUT'
-}
+/***/ }),
+
+/***/ 67415:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
-Object.setPrototypeOf(normalizeMethodRecord, null)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isKeyCredential = isKeyCredential;
+const core_util_1 = __nccwpck_require__(30991);
/**
- * @see https://fetch.spec.whatwg.org/#concept-method-normalize
- * @param {string} method
+ * Tests an object to determine whether it implements KeyCredential.
+ *
+ * @param credential - The assumed KeyCredential to be tested.
*/
-function normalizeMethod (method) {
- return normalizeMethodRecord[method.toLowerCase()] ?? method
+function isKeyCredential(credential) {
+ return (0, core_util_1.isObjectWithProperties)(credential, ["key"]) && typeof credential.key === "string";
}
+//# sourceMappingURL=keyCredential.js.map
-// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
-function serializeJavascriptValueToJSONString (value) {
- // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
- const result = JSON.stringify(value)
+/***/ }),
- // 2. If result is undefined, then throw a TypeError.
- if (result === undefined) {
- throw new TypeError('Value is not JSON serializable')
- }
+/***/ 64381:
+/***/ ((__unused_webpack_module, exports) => {
- // 3. Assert: result is a string.
- assert(typeof result === 'string')
- // 4. Return result.
- return result
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isBearerToken = isBearerToken;
+exports.isPopToken = isPopToken;
+exports.isTokenCredential = isTokenCredential;
+/**
+ * @internal
+ * @param accessToken - Access token
+ * @returns Whether a token is bearer type or not
+ */
+function isBearerToken(accessToken) {
+ return !accessToken.tokenType || accessToken.tokenType === "Bearer";
}
-
-// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
-const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
-
/**
- * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
- * @param {() => unknown[]} iterator
- * @param {string} name name of the instance
- * @param {'key'|'value'|'key+value'} kind
+ * @internal
+ * @param accessToken - Access token
+ * @returns Whether a token is Pop token or not
*/
-function makeIterator (iterator, name, kind) {
- const object = {
- index: 0,
- kind,
- target: iterator
- }
-
- const i = {
- next () {
- // 1. Let interface be the interface for which the iterator prototype object exists.
-
- // 2. Let thisValue be the this value.
-
- // 3. Let object be ? ToObject(thisValue).
-
- // 4. If object is a platform object, then perform a security
- // check, passing:
-
- // 5. If object is not a default iterator object for interface,
- // then throw a TypeError.
- if (Object.getPrototypeOf(this) !== i) {
- throw new TypeError(
- `'next' called on an object that does not implement interface ${name} Iterator.`
- )
- }
-
- // 6. Let index be object’s index.
- // 7. Let kind be object’s kind.
- // 8. Let values be object’s target's value pairs to iterate over.
- const { index, kind, target } = object
- const values = target()
-
- // 9. Let len be the length of values.
- const len = values.length
-
- // 10. If index is greater than or equal to len, then return
- // CreateIterResultObject(undefined, true).
- if (index >= len) {
- return { value: undefined, done: true }
- }
+function isPopToken(accessToken) {
+ return accessToken.tokenType === "pop";
+}
+/**
+ * Tests an object to determine whether it implements TokenCredential.
+ *
+ * @param credential - The assumed TokenCredential to be tested.
+ */
+function isTokenCredential(credential) {
+ // Check for an object with a 'getToken' function and possibly with
+ // a 'signRequest' function. We do this check to make sure that
+ // a ServiceClientCredentials implementor (like TokenClientCredentials
+ // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
+ // it doesn't actually implement TokenCredential also.
+ const castCredential = credential;
+ return (castCredential &&
+ typeof castCredential.getToken === "function" &&
+ (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
+}
+//# sourceMappingURL=tokenCredential.js.map
- // 11. Let pair be the entry in values at index index.
- const pair = values[index]
+/***/ }),
- // 12. Set object’s index to index + 1.
- object.index = index + 1
+/***/ 85110:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 13. Return the iterator result for pair and kind.
- return iteratorResult(pair, kind)
- },
- // The class string of an iterator prototype object for a given interface is the
- // result of concatenating the identifier of the interface and the string " Iterator".
- [Symbol.toStringTag]: `${name} Iterator`
- }
- // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.
- Object.setPrototypeOf(i, esIteratorPrototype)
- // esIteratorPrototype needs to be the prototype of i
- // which is the prototype of an empty object. Yes, it's confusing.
- return Object.setPrototypeOf({}, i)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.authorizeRequestOnClaimChallenge = exports.parseCAEChallenge = void 0;
+const log_js_1 = __nccwpck_require__(75630);
+const base64_js_1 = __nccwpck_require__(59793);
+/**
+ * Converts: `Bearer a="b", c="d", Bearer d="e", f="g"`.
+ * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.
+ *
+ * @internal
+ */
+function parseCAEChallenge(challenges) {
+ const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x);
+ return bearerChallenges.map((challenge) => {
+ const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x);
+ const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="')));
+ // Key-value pairs to plain object:
+ return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
+ });
}
-
-// https://webidl.spec.whatwg.org/#iterator-result
-function iteratorResult (pair, kind) {
- let result
-
- // 1. Let result be a value determined by the value of kind:
- switch (kind) {
- case 'key': {
- // 1. Let idlKey be pair’s key.
- // 2. Let key be the result of converting idlKey to an
- // ECMAScript value.
- // 3. result is key.
- result = pair[0]
- break
+exports.parseCAEChallenge = parseCAEChallenge;
+/**
+ * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:
+ * [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).
+ *
+ * Call the `bearerTokenAuthenticationPolicy` with the following options:
+ *
+ * ```ts
+ * import { bearerTokenAuthenticationPolicy } from "@azure/core-rest-pipeline";
+ * import { authorizeRequestOnClaimChallenge } from "@azure/core-client";
+ *
+ * const bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy({
+ * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge
+ * });
+ * ```
+ *
+ * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.
+ * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.
+ *
+ * Example challenge with claims:
+ *
+ * ```
+ * Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
+ * error_description="User session has been revoked",
+ * claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
+ * ```
+ */
+async function authorizeRequestOnClaimChallenge(onChallengeOptions) {
+ const { scopes, response } = onChallengeOptions;
+ const logger = onChallengeOptions.logger || log_js_1.logger;
+ const challenge = response.headers.get("WWW-Authenticate");
+ if (!challenge) {
+ logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`);
+ return false;
}
- case 'value': {
- // 1. Let idlValue be pair’s value.
- // 2. Let value be the result of converting idlValue to
- // an ECMAScript value.
- // 3. result is value.
- result = pair[1]
- break
+ const challenges = parseCAEChallenge(challenge) || [];
+ const parsedChallenge = challenges.find((x) => x.claims);
+ if (!parsedChallenge) {
+ logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`);
+ return false;
}
- case 'key+value': {
- // 1. Let idlKey be pair’s key.
- // 2. Let idlValue be pair’s value.
- // 3. Let key be the result of converting idlKey to an
- // ECMAScript value.
- // 4. Let value be the result of converting idlValue to
- // an ECMAScript value.
- // 5. Let array be ! ArrayCreate(2).
- // 6. Call ! CreateDataProperty(array, "0", key).
- // 7. Call ! CreateDataProperty(array, "1", value).
- // 8. result is array.
- result = pair
- break
+ const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, {
+ claims: (0, base64_js_1.decodeStringToString)(parsedChallenge.claims),
+ });
+ if (!accessToken) {
+ return false;
}
- }
-
- // 2. Return CreateIterResultObject(result, false).
- return { value: result, done: false }
+ onChallengeOptions.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
+ return true;
}
+exports.authorizeRequestOnClaimChallenge = authorizeRequestOnClaimChallenge;
+//# sourceMappingURL=authorizeRequestOnClaimChallenge.js.map
-/**
- * @see https://fetch.spec.whatwg.org/#body-fully-read
- */
-async function fullyReadBody (body, processBody, processBodyError) {
- // 1. If taskDestination is null, then set taskDestination to
- // the result of starting a new parallel queue.
-
- // 2. Let successSteps given a byte sequence bytes be to queue a
- // fetch task to run processBody given bytes, with taskDestination.
- const successSteps = processBody
-
- // 3. Let errorSteps be to queue a fetch task to run processBodyError,
- // with taskDestination.
- const errorSteps = processBodyError
+/***/ }),
- // 4. Let reader be the result of getting a reader for body’s stream.
- // If that threw an exception, then run errorSteps with that
- // exception and return.
- let reader
+/***/ 75794:
+/***/ ((__unused_webpack_module, exports) => {
- try {
- reader = body.stream.getReader()
- } catch (e) {
- errorSteps(e)
- return
- }
- // 5. Read all bytes from reader, given successSteps and errorSteps.
- try {
- const result = await readAllBytes(reader)
- successSteps(result)
- } catch (e) {
- errorSteps(e)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.authorizeRequestOnTenantChallenge = void 0;
+/**
+ * A set of constants used internally when processing requests.
+ */
+const Constants = {
+ DefaultScope: "/.default",
+ /**
+ * Defines constants for use with HTTP headers.
+ */
+ HeaderConstants: {
+ /**
+ * The Authorization header.
+ */
+ AUTHORIZATION: "authorization",
+ },
+};
+function isUuid(text) {
+ return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text);
}
-
-/** @type {ReadableStream} */
-let ReadableStream = globalThis.ReadableStream
-
-function isReadableStreamLike (stream) {
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(63774).ReadableStream)
- }
-
- return stream instanceof ReadableStream || (
- stream[Symbol.toStringTag] === 'ReadableStream' &&
- typeof stream.tee === 'function'
- )
+/**
+ * Defines a callback to handle auth challenge for Storage APIs.
+ * This implements the bearer challenge process described here: https://docs.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge
+ * Handling has specific features for storage that departs to the general AAD challenge docs.
+ **/
+const authorizeRequestOnTenantChallenge = async (challengeOptions) => {
+ const requestOptions = requestToOptions(challengeOptions.request);
+ const challenge = getChallenge(challengeOptions.response);
+ if (challenge) {
+ const challengeInfo = parseChallenge(challenge);
+ const challengeScopes = buildScopes(challengeOptions, challengeInfo);
+ const tenantId = extractTenantId(challengeInfo);
+ if (!tenantId) {
+ return false;
+ }
+ const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId }));
+ if (!accessToken) {
+ return false;
+ }
+ challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}`);
+ return true;
+ }
+ return false;
+};
+exports.authorizeRequestOnTenantChallenge = authorizeRequestOnTenantChallenge;
+/**
+ * Extracts the tenant id from the challenge information
+ * The tenant id is contained in the authorization_uri as the first
+ * path part.
+ */
+function extractTenantId(challengeInfo) {
+ const parsedAuthUri = new URL(challengeInfo.authorization_uri);
+ const pathSegments = parsedAuthUri.pathname.split("/");
+ const tenantId = pathSegments[1];
+ if (tenantId && isUuid(tenantId)) {
+ return tenantId;
+ }
+ return undefined;
}
-
-const MAXIMUM_ARGUMENT_LENGTH = 65535
-
/**
- * @see https://infra.spec.whatwg.org/#isomorphic-decode
- * @param {number[]|Uint8Array} input
+ * Builds the authentication scopes based on the information that comes in the
+ * challenge information. Scopes url is present in the resource_id, if it is empty
+ * we keep using the original scopes.
*/
-function isomorphicDecode (input) {
- // 1. To isomorphic decode a byte sequence input, return a string whose code point
- // length is equal to input’s length and whose code points have the same values
- // as the values of input’s bytes, in the same order.
-
- if (input.length < MAXIMUM_ARGUMENT_LENGTH) {
- return String.fromCharCode(...input)
- }
-
- return input.reduce((previous, current) => previous + String.fromCharCode(current), '')
+function buildScopes(challengeOptions, challengeInfo) {
+ if (!challengeInfo.resource_id) {
+ return challengeOptions.scopes;
+ }
+ const challengeScopes = new URL(challengeInfo.resource_id);
+ challengeScopes.pathname = Constants.DefaultScope;
+ let scope = challengeScopes.toString();
+ if (scope === "https://disk.azure.com/.default") {
+ // the extra slash is required by the service
+ scope = "https://disk.azure.com//.default";
+ }
+ return [scope];
}
-
/**
- * @param {ReadableStreamController} controller
+ * We will retrieve the challenge only if the response status code was 401,
+ * and if the response contained the header "WWW-Authenticate" with a non-empty value.
*/
-function readableStreamClose (controller) {
- try {
- controller.close()
- } catch (err) {
- // TODO: add comment explaining why this error occurs.
- if (!err.message.includes('Controller is already closed')) {
- throw err
+function getChallenge(response) {
+ const challenge = response.headers.get("WWW-Authenticate");
+ if (response.status === 401 && challenge) {
+ return challenge;
}
- }
+ return;
}
-
/**
- * @see https://infra.spec.whatwg.org/#isomorphic-encode
- * @param {string} input
+ * Converts: `Bearer a="b" c="d"`.
+ * Into: `[ { a: 'b', c: 'd' }]`.
+ *
+ * @internal
*/
-function isomorphicEncode (input) {
- // 1. Assert: input contains no code points greater than U+00FF.
- for (let i = 0; i < input.length; i++) {
- assert(input.charCodeAt(i) <= 0xFF)
- }
-
- // 2. Return a byte sequence whose length is equal to input’s code
- // point length and whose bytes have the same values as the
- // values of input’s code points, in the same order
- return input
+function parseChallenge(challenge) {
+ const bearerChallenge = challenge.slice("Bearer ".length);
+ const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x);
+ const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("=")));
+ // Key-value pairs to plain object:
+ return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
}
-
/**
- * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
- * @see https://streams.spec.whatwg.org/#read-loop
- * @param {ReadableStreamDefaultReader} reader
+ * Extracts the options form a Pipeline Request for later re-use
*/
-async function readAllBytes (reader) {
- const bytes = []
- let byteLength = 0
-
- while (true) {
- const { done, value: chunk } = await reader.read()
-
- if (done) {
- // 1. Call successSteps with bytes.
- return Buffer.concat(bytes, byteLength)
- }
+function requestToOptions(request) {
+ return {
+ abortSignal: request.abortSignal,
+ requestOptions: {
+ timeout: request.timeout,
+ },
+ tracingOptions: request.tracingOptions,
+ };
+}
+//# sourceMappingURL=authorizeRequestOnTenantChallenge.js.map
- // 1. If chunk is not a Uint8Array object, call failureSteps
- // with a TypeError and abort these steps.
- if (!isUint8Array(chunk)) {
- throw new TypeError('Received non-Uint8Array chunk')
- }
+/***/ }),
- // 2. Append the bytes represented by chunk to bytes.
- bytes.push(chunk)
- byteLength += chunk.length
+/***/ 59793:
+/***/ ((__unused_webpack_module, exports) => {
- // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
- }
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.decodeStringToString = exports.decodeString = exports.encodeByteArray = exports.encodeString = void 0;
/**
- * @see https://fetch.spec.whatwg.org/#is-local
- * @param {URL} url
+ * Encodes a string in base64 format.
+ * @param value - the string to encode
+ * @internal
*/
-function urlIsLocal (url) {
- assert('protocol' in url) // ensure it's a url object
-
- const protocol = url.protocol
-
- return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
+function encodeString(value) {
+ return Buffer.from(value).toString("base64");
}
-
+exports.encodeString = encodeString;
/**
- * @param {string|URL} url
+ * Encodes a byte array in base64 format.
+ * @param value - the Uint8Aray to encode
+ * @internal
*/
-function urlHasHttpsScheme (url) {
- if (typeof url === 'string') {
- return url.startsWith('https:')
- }
-
- return url.protocol === 'https:'
+function encodeByteArray(value) {
+ const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer);
+ return bufferValue.toString("base64");
}
-
+exports.encodeByteArray = encodeByteArray;
/**
- * @see https://fetch.spec.whatwg.org/#http-scheme
- * @param {URL} url
+ * Decodes a base64 string into a byte array.
+ * @param value - the base64 string to decode
+ * @internal
*/
-function urlIsHttpHttpsScheme (url) {
- assert('protocol' in url) // ensure it's a url object
-
- const protocol = url.protocol
-
- return protocol === 'http:' || protocol === 'https:'
+function decodeString(value) {
+ return Buffer.from(value, "base64");
}
-
+exports.decodeString = decodeString;
/**
- * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.
+ * Decodes a base64 string into a string.
+ * @param value - the base64 string to decode
+ * @internal
*/
-const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))
-
-module.exports = {
- isAborted,
- isCancelled,
- createDeferredPromise,
- ReadableStreamFrom,
- toUSVString,
- tryUpgradeRequestToAPotentiallyTrustworthyURL,
- coarsenedSharedCurrentTime,
- determineRequestsReferrer,
- makePolicyContainer,
- clonePolicyContainer,
- appendFetchMetadata,
- appendRequestOriginHeader,
- TAOCheck,
- corsCheck,
- crossOriginResourcePolicyCheck,
- createOpaqueTimingInfo,
- setRequestReferrerPolicyOnRedirect,
- isValidHTTPToken,
- requestBadPort,
- requestCurrentURL,
- responseURL,
- responseLocationURL,
- isBlobLike,
- isURLPotentiallyTrustworthy,
- isValidReasonPhrase,
- sameOrigin,
- normalizeMethod,
- serializeJavascriptValueToJSONString,
- makeIterator,
- isValidHeaderName,
- isValidHeaderValue,
- hasOwn,
- isErrorLike,
- fullyReadBody,
- bytesMatch,
- isReadableStreamLike,
- readableStreamClose,
- isomorphicEncode,
- isomorphicDecode,
- urlIsLocal,
- urlHasHttpsScheme,
- urlIsHttpHttpsScheme,
- readAllBytes,
- normalizeMethodRecord,
- parseMetadata
+function decodeStringToString(value) {
+ return Buffer.from(value, "base64").toString();
}
-
+exports.decodeStringToString = decodeStringToString;
+//# sourceMappingURL=base64.js.map
/***/ }),
-/***/ 94354:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { types } = __nccwpck_require__(39023)
-const { hasOwn, toUSVString } = __nccwpck_require__(72847)
+/***/ 21795:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-/** @type {import('../../types/webidl').Webidl} */
-const webidl = {}
-webidl.converters = {}
-webidl.util = {}
-webidl.errors = {}
-webidl.errors.exception = function (message) {
- return new TypeError(`${message.header}: ${message.message}`)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.deserializationPolicy = exports.deserializationPolicyName = void 0;
+const interfaces_js_1 = __nccwpck_require__(35590);
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+const serializer_js_1 = __nccwpck_require__(66774);
+const operationHelpers_js_1 = __nccwpck_require__(17036);
+const defaultJsonContentTypes = ["application/json", "text/json"];
+const defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
+/**
+ * The programmatic identifier of the deserializationPolicy.
+ */
+exports.deserializationPolicyName = "deserializationPolicy";
+/**
+ * This policy handles parsing out responses according to OperationSpecs on the request.
+ */
+function deserializationPolicy(options = {}) {
+ var _a, _b, _c, _d, _e, _f, _g;
+ const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes;
+ const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes;
+ const parseXML = options.parseXML;
+ const serializerOptions = options.serializerOptions;
+ const updatedOptions = {
+ xml: {
+ rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "",
+ includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false,
+ xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : interfaces_js_1.XML_CHARKEY,
+ },
+ };
+ return {
+ name: exports.deserializationPolicyName,
+ async sendRequest(request, next) {
+ const response = await next(request);
+ return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML);
+ },
+ };
}
-
-webidl.errors.conversionFailed = function (context) {
- const plural = context.types.length === 1 ? '' : ' one of'
- const message =
- `${context.argument} could not be converted to` +
- `${plural}: ${context.types.join(', ')}.`
-
- return webidl.errors.exception({
- header: context.prefix,
- message
- })
+exports.deserializationPolicy = deserializationPolicy;
+function getOperationResponseMap(parsedResponse) {
+ let result;
+ const request = parsedResponse.request;
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
+ if (operationSpec) {
+ if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) {
+ result = operationSpec.responses[parsedResponse.status];
+ }
+ else {
+ result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse);
+ }
+ }
+ return result;
}
-
-webidl.errors.invalidArgument = function (context) {
- return webidl.errors.exception({
- header: context.prefix,
- message: `"${context.value}" is an invalid ${context.type}.`
- })
+function shouldDeserializeResponse(parsedResponse) {
+ const request = parsedResponse.request;
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize;
+ let result;
+ if (shouldDeserialize === undefined) {
+ result = true;
+ }
+ else if (typeof shouldDeserialize === "boolean") {
+ result = shouldDeserialize;
+ }
+ else {
+ result = shouldDeserialize(parsedResponse);
+ }
+ return result;
}
-
-// https://webidl.spec.whatwg.org/#implements
-webidl.brandCheck = function (V, I, opts = undefined) {
- if (opts?.strict !== false && !(V instanceof I)) {
- throw new TypeError('Illegal invocation')
- } else {
- return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]
- }
+async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) {
+ const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML);
+ if (!shouldDeserializeResponse(parsedResponse)) {
+ return parsedResponse;
+ }
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(parsedResponse.request);
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
+ if (!operationSpec || !operationSpec.responses) {
+ return parsedResponse;
+ }
+ const responseSpec = getOperationResponseMap(parsedResponse);
+ const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options);
+ if (error) {
+ throw error;
+ }
+ else if (shouldReturnResponse) {
+ return parsedResponse;
+ }
+ // An operation response spec does exist for current status code, so
+ // use it to deserialize the response.
+ if (responseSpec) {
+ if (responseSpec.bodyMapper) {
+ let valueToDeserialize = parsedResponse.parsedBody;
+ if (operationSpec.isXML && responseSpec.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
+ valueToDeserialize =
+ typeof valueToDeserialize === "object"
+ ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
+ : [];
+ }
+ try {
+ parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options);
+ }
+ catch (deserializeError) {
+ const restError = new core_rest_pipeline_1.RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, {
+ statusCode: parsedResponse.status,
+ request: parsedResponse.request,
+ response: parsedResponse,
+ });
+ throw restError;
+ }
+ }
+ else if (operationSpec.httpMethod === "HEAD") {
+ // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
+ parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
+ }
+ if (responseSpec.headersMapper) {
+ parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true });
+ }
+ }
+ return parsedResponse;
+}
+function isOperationSpecEmpty(operationSpec) {
+ const expectedStatusCodes = Object.keys(operationSpec.responses);
+ return (expectedStatusCodes.length === 0 ||
+ (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
+}
+function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) {
+ var _a;
+ const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;
+ const isExpectedStatusCode = isOperationSpecEmpty(operationSpec)
+ ? isSuccessByStatus
+ : !!responseSpec;
+ if (isExpectedStatusCode) {
+ if (responseSpec) {
+ if (!responseSpec.isError) {
+ return { error: null, shouldReturnResponse: false };
+ }
+ }
+ else {
+ return { error: null, shouldReturnResponse: false };
+ }
+ }
+ const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default;
+ const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status))
+ ? `Unexpected status code: ${parsedResponse.status}`
+ : parsedResponse.bodyAsText;
+ const error = new core_rest_pipeline_1.RestError(initialErrorMessage, {
+ statusCode: parsedResponse.status,
+ request: parsedResponse.request,
+ response: parsedResponse,
+ });
+ // If the item failed but there's no error spec or default spec to deserialize the error,
+ // we should fail so we just throw the parsed response
+ if (!errorResponseSpec) {
+ throw error;
+ }
+ const defaultBodyMapper = errorResponseSpec.bodyMapper;
+ const defaultHeadersMapper = errorResponseSpec.headersMapper;
+ try {
+ // If error response has a body, try to deserialize it using default body mapper.
+ // Then try to extract error code & message from it
+ if (parsedResponse.parsedBody) {
+ const parsedBody = parsedResponse.parsedBody;
+ let deserializedError;
+ if (defaultBodyMapper) {
+ let valueToDeserialize = parsedBody;
+ if (operationSpec.isXML && defaultBodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
+ valueToDeserialize = [];
+ const elementName = defaultBodyMapper.xmlElementName;
+ if (typeof parsedBody === "object" && elementName) {
+ valueToDeserialize = parsedBody[elementName];
+ }
+ }
+ deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options);
+ }
+ const internalError = parsedBody.error || deserializedError || parsedBody;
+ error.code = internalError.code;
+ if (internalError.message) {
+ error.message = internalError.message;
+ }
+ if (defaultBodyMapper) {
+ error.response.parsedBody = deserializedError;
+ }
+ }
+ // If error response has headers, try to deserialize it using default header mapper
+ if (parsedResponse.headers && defaultHeadersMapper) {
+ error.response.parsedHeaders =
+ operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders");
+ }
+ }
+ catch (defaultError) {
+ error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`;
+ }
+ return { error, shouldReturnResponse: false };
+}
+async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
+ var _a;
+ if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) &&
+ operationResponse.bodyAsText) {
+ const text = operationResponse.bodyAsText;
+ const contentType = operationResponse.headers.get("Content-Type") || "";
+ const contentComponents = !contentType
+ ? []
+ : contentType.split(";").map((component) => component.toLowerCase());
+ try {
+ if (contentComponents.length === 0 ||
+ contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) {
+ operationResponse.parsedBody = JSON.parse(text);
+ return operationResponse;
+ }
+ else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) {
+ if (!parseXML) {
+ throw new Error("Parsing XML not supported.");
+ }
+ const body = await parseXML(text, opts.xml);
+ operationResponse.parsedBody = body;
+ return operationResponse;
+ }
+ }
+ catch (err) {
+ const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;
+ const errCode = err.code || core_rest_pipeline_1.RestError.PARSE_ERROR;
+ const e = new core_rest_pipeline_1.RestError(msg, {
+ code: errCode,
+ statusCode: operationResponse.status,
+ request: operationResponse.request,
+ response: operationResponse,
+ });
+ throw e;
+ }
+ }
+ return operationResponse;
}
+//# sourceMappingURL=deserializationPolicy.js.map
-webidl.argumentLengthCheck = function ({ length }, min, ctx) {
- if (length < min) {
- throw webidl.errors.exception({
- message: `${min} argument${min !== 1 ? 's' : ''} required, ` +
- `but${length ? ' only' : ''} ${length} found.`,
- ...ctx
- })
- }
-}
+/***/ }),
-webidl.illegalConstructor = function () {
- throw webidl.errors.exception({
- header: 'TypeError',
- message: 'Illegal constructor'
- })
-}
+/***/ 64663:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
-webidl.util.Type = function (V) {
- switch (typeof V) {
- case 'undefined': return 'Undefined'
- case 'boolean': return 'Boolean'
- case 'string': return 'String'
- case 'symbol': return 'Symbol'
- case 'number': return 'Number'
- case 'bigint': return 'BigInt'
- case 'function':
- case 'object': {
- if (V === null) {
- return 'Null'
- }
- return 'Object'
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getCachedDefaultHttpClient = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+let cachedHttpClient;
+function getCachedDefaultHttpClient() {
+ if (!cachedHttpClient) {
+ cachedHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)();
}
- }
+ return cachedHttpClient;
}
+exports.getCachedDefaultHttpClient = getCachedDefaultHttpClient;
+//# sourceMappingURL=httpClientCache.js.map
-// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
-webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {
- let upperBound
- let lowerBound
-
- // 1. If bitLength is 64, then:
- if (bitLength === 64) {
- // 1. Let upperBound be 2^53 − 1.
- upperBound = Math.pow(2, 53) - 1
-
- // 2. If signedness is "unsigned", then let lowerBound be 0.
- if (signedness === 'unsigned') {
- lowerBound = 0
- } else {
- // 3. Otherwise let lowerBound be −2^53 + 1.
- lowerBound = Math.pow(-2, 53) + 1
- }
- } else if (signedness === 'unsigned') {
- // 2. Otherwise, if signedness is "unsigned", then:
-
- // 1. Let lowerBound be 0.
- lowerBound = 0
-
- // 2. Let upperBound be 2^bitLength − 1.
- upperBound = Math.pow(2, bitLength) - 1
- } else {
- // 3. Otherwise:
-
- // 1. Let lowerBound be -2^bitLength − 1.
- lowerBound = Math.pow(-2, bitLength) - 1
-
- // 2. Let upperBound be 2^bitLength − 1 − 1.
- upperBound = Math.pow(2, bitLength - 1) - 1
- }
-
- // 4. Let x be ? ToNumber(V).
- let x = Number(V)
+/***/ }),
- // 5. If x is −0, then set x to +0.
- if (x === 0) {
- x = 0
- }
+/***/ 6868:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 6. If the conversion is to an IDL type associated
- // with the [EnforceRange] extended attribute, then:
- if (opts.enforceRange === true) {
- // 1. If x is NaN, +∞, or −∞, then throw a TypeError.
- if (
- Number.isNaN(x) ||
- x === Number.POSITIVE_INFINITY ||
- x === Number.NEGATIVE_INFINITY
- ) {
- throw webidl.errors.exception({
- header: 'Integer conversion',
- message: `Could not convert ${V} to an integer.`
- })
- }
- // 2. Set x to IntegerPart(x).
- x = webidl.util.IntegerPart(x)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.authorizeRequestOnTenantChallenge = exports.authorizeRequestOnClaimChallenge = exports.serializationPolicyName = exports.serializationPolicy = exports.deserializationPolicyName = exports.deserializationPolicy = exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.createClientPipeline = exports.ServiceClient = exports.MapperTypeNames = exports.createSerializer = void 0;
+var serializer_js_1 = __nccwpck_require__(66774);
+Object.defineProperty(exports, "createSerializer", ({ enumerable: true, get: function () { return serializer_js_1.createSerializer; } }));
+Object.defineProperty(exports, "MapperTypeNames", ({ enumerable: true, get: function () { return serializer_js_1.MapperTypeNames; } }));
+var serviceClient_js_1 = __nccwpck_require__(22732);
+Object.defineProperty(exports, "ServiceClient", ({ enumerable: true, get: function () { return serviceClient_js_1.ServiceClient; } }));
+var pipeline_js_1 = __nccwpck_require__(64524);
+Object.defineProperty(exports, "createClientPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createClientPipeline; } }));
+var interfaces_js_1 = __nccwpck_require__(35590);
+Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_ATTRKEY; } }));
+Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_CHARKEY; } }));
+var deserializationPolicy_js_1 = __nccwpck_require__(21795);
+Object.defineProperty(exports, "deserializationPolicy", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicy; } }));
+Object.defineProperty(exports, "deserializationPolicyName", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicyName; } }));
+var serializationPolicy_js_1 = __nccwpck_require__(87054);
+Object.defineProperty(exports, "serializationPolicy", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicy; } }));
+Object.defineProperty(exports, "serializationPolicyName", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicyName; } }));
+var authorizeRequestOnClaimChallenge_js_1 = __nccwpck_require__(85110);
+Object.defineProperty(exports, "authorizeRequestOnClaimChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnClaimChallenge_js_1.authorizeRequestOnClaimChallenge; } }));
+var authorizeRequestOnTenantChallenge_js_1 = __nccwpck_require__(75794);
+Object.defineProperty(exports, "authorizeRequestOnTenantChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnTenantChallenge_js_1.authorizeRequestOnTenantChallenge; } }));
+//# sourceMappingURL=index.js.map
- // 3. If x < lowerBound or x > upperBound, then
- // throw a TypeError.
- if (x < lowerBound || x > upperBound) {
- throw webidl.errors.exception({
- header: 'Integer conversion',
- message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
- })
- }
+/***/ }),
- // 4. Return x.
- return x
- }
+/***/ 91030:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 7. If x is not NaN and the conversion is to an IDL
- // type associated with the [Clamp] extended
- // attribute, then:
- if (!Number.isNaN(x) && opts.clamp === true) {
- // 1. Set x to min(max(x, lowerBound), upperBound).
- x = Math.min(Math.max(x, lowerBound), upperBound)
- // 2. Round x to the nearest integer, choosing the
- // even integer if it lies halfway between two,
- // and choosing +0 rather than −0.
- if (Math.floor(x) % 2 === 0) {
- x = Math.floor(x)
- } else {
- x = Math.ceil(x)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getPathStringFromParameter = exports.getStreamingResponseStatusCodes = void 0;
+const serializer_js_1 = __nccwpck_require__(66774);
+/**
+ * Gets the list of status codes for streaming responses.
+ * @internal
+ */
+function getStreamingResponseStatusCodes(operationSpec) {
+ const result = new Set();
+ for (const statusCode in operationSpec.responses) {
+ const operationResponse = operationSpec.responses[statusCode];
+ if (operationResponse.bodyMapper &&
+ operationResponse.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Stream) {
+ result.add(Number(statusCode));
+ }
}
-
- // 3. Return x.
- return x
- }
-
- // 8. If x is NaN, +0, +∞, or −∞, then return +0.
- if (
- Number.isNaN(x) ||
- (x === 0 && Object.is(0, x)) ||
- x === Number.POSITIVE_INFINITY ||
- x === Number.NEGATIVE_INFINITY
- ) {
- return 0
- }
-
- // 9. Set x to IntegerPart(x).
- x = webidl.util.IntegerPart(x)
-
- // 10. Set x to x modulo 2^bitLength.
- x = x % Math.pow(2, bitLength)
-
- // 11. If signedness is "signed" and x ≥ 2^bitLength − 1,
- // then return x − 2^bitLength.
- if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
- return x - Math.pow(2, bitLength)
- }
-
- // 12. Otherwise, return x.
- return x
-}
-
-// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
-webidl.util.IntegerPart = function (n) {
- // 1. Let r be floor(abs(n)).
- const r = Math.floor(Math.abs(n))
-
- // 2. If n < 0, then return -1 × r.
- if (n < 0) {
- return -1 * r
- }
-
- // 3. Otherwise, return r.
- return r
+ return result;
}
-
-// https://webidl.spec.whatwg.org/#es-sequence
-webidl.sequenceConverter = function (converter) {
- return (V) => {
- // 1. If Type(V) is not Object, throw a TypeError.
- if (webidl.util.Type(V) !== 'Object') {
- throw webidl.errors.exception({
- header: 'Sequence',
- message: `Value of type ${webidl.util.Type(V)} is not an Object.`
- })
+exports.getStreamingResponseStatusCodes = getStreamingResponseStatusCodes;
+/**
+ * Get the path to this parameter's value as a dotted string (a.b.c).
+ * @param parameter - The parameter to get the path string for.
+ * @returns The path to this parameter's value as a dotted string.
+ * @internal
+ */
+function getPathStringFromParameter(parameter) {
+ const { parameterPath, mapper } = parameter;
+ let result;
+ if (typeof parameterPath === "string") {
+ result = parameterPath;
}
-
- // 2. Let method be ? GetMethod(V, @@iterator).
- /** @type {Generator} */
- const method = V?.[Symbol.iterator]?.()
- const seq = []
-
- // 3. If method is undefined, throw a TypeError.
- if (
- method === undefined ||
- typeof method.next !== 'function'
- ) {
- throw webidl.errors.exception({
- header: 'Sequence',
- message: 'Object is not an iterator.'
- })
+ else if (Array.isArray(parameterPath)) {
+ result = parameterPath.join(".");
}
-
- // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
- while (true) {
- const { done, value } = method.next()
-
- if (done) {
- break
- }
-
- seq.push(converter(value))
+ else {
+ result = mapper.serializedName;
}
-
- return seq
- }
+ return result;
}
+exports.getPathStringFromParameter = getPathStringFromParameter;
+//# sourceMappingURL=interfaceHelpers.js.map
-// https://webidl.spec.whatwg.org/#es-to-record
-webidl.recordConverter = function (keyConverter, valueConverter) {
- return (O) => {
- // 1. If Type(O) is not Object, throw a TypeError.
- if (webidl.util.Type(O) !== 'Object') {
- throw webidl.errors.exception({
- header: 'Record',
- message: `Value of type ${webidl.util.Type(O)} is not an Object.`
- })
- }
+/***/ }),
- // 2. Let result be a new empty instance of record.
- const result = {}
+/***/ 35590:
+/***/ ((__unused_webpack_module, exports) => {
- if (!types.isProxy(O)) {
- // Object.keys only returns enumerable properties
- const keys = Object.keys(O)
- for (const key of keys) {
- // 1. Let typedKey be key converted to an IDL value of type K.
- const typedKey = keyConverter(key)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0;
+/**
+ * Default key used to access the XML attributes.
+ */
+exports.XML_ATTRKEY = "$";
+/**
+ * Default key used to access the XML value content.
+ */
+exports.XML_CHARKEY = "_";
+//# sourceMappingURL=interfaces.js.map
- // 2. Let value be ? Get(O, key).
- // 3. Let typedValue be value converted to an IDL value of type V.
- const typedValue = valueConverter(O[key])
+/***/ }),
- // 4. Set result[typedKey] to typedValue.
- result[typedKey] = typedValue
- }
+/***/ 75630:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5. Return result.
- return result
- }
- // 3. Let keys be ? O.[[OwnPropertyKeys]]().
- const keys = Reflect.ownKeys(O)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logger = void 0;
+const logger_1 = __nccwpck_require__(50143);
+exports.logger = (0, logger_1.createClientLogger)("core-client");
+//# sourceMappingURL=log.js.map
- // 4. For each key of keys.
- for (const key of keys) {
- // 1. Let desc be ? O.[[GetOwnProperty]](key).
- const desc = Reflect.getOwnPropertyDescriptor(O, key)
+/***/ }),
- // 2. If desc is not undefined and desc.[[Enumerable]] is true:
- if (desc?.enumerable) {
- // 1. Let typedKey be key converted to an IDL value of type K.
- const typedKey = keyConverter(key)
+/***/ 17036:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. Let value be ? Get(O, key).
- // 3. Let typedValue be value converted to an IDL value of type V.
- const typedValue = valueConverter(O[key])
- // 4. Set result[typedKey] to typedValue.
- result[typedKey] = typedValue
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getOperationRequestInfo = exports.getOperationArgumentValueFromParameter = void 0;
+const state_js_1 = __nccwpck_require__(35077);
+/**
+ * @internal
+ * Retrieves the value to use for a given operation argument
+ * @param operationArguments - The arguments passed from the generated client
+ * @param parameter - The parameter description
+ * @param fallbackObject - If something isn't found in the arguments bag, look here.
+ * Generally used to look at the service client properties.
+ */
+function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) {
+ let parameterPath = parameter.parameterPath;
+ const parameterMapper = parameter.mapper;
+ let value;
+ if (typeof parameterPath === "string") {
+ parameterPath = [parameterPath];
}
-
- // 5. Return result.
- return result
- }
-}
-
-webidl.interfaceConverter = function (i) {
- return (V, opts = {}) => {
- if (opts.strict !== false && !(V instanceof i)) {
- throw webidl.errors.exception({
- header: i.name,
- message: `Expected ${V} to be an instance of ${i.name}.`
- })
+ if (Array.isArray(parameterPath)) {
+ if (parameterPath.length > 0) {
+ if (parameterMapper.isConstant) {
+ value = parameterMapper.defaultValue;
+ }
+ else {
+ let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
+ if (!propertySearchResult.propertyFound && fallbackObject) {
+ propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath);
+ }
+ let useDefaultValue = false;
+ if (!propertySearchResult.propertyFound) {
+ useDefaultValue =
+ parameterMapper.required ||
+ (parameterPath[0] === "options" && parameterPath.length === 2);
+ }
+ value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
+ }
+ }
}
-
- return V
- }
-}
-
-webidl.dictionaryConverter = function (converters) {
- return (dictionary) => {
- const type = webidl.util.Type(dictionary)
- const dict = {}
-
- if (type === 'Null' || type === 'Undefined') {
- return dict
- } else if (type !== 'Object') {
- throw webidl.errors.exception({
- header: 'Dictionary',
- message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
- })
+ else {
+ if (parameterMapper.required) {
+ value = {};
+ }
+ for (const propertyName in parameterPath) {
+ const propertyMapper = parameterMapper.type.modelProperties[propertyName];
+ const propertyPath = parameterPath[propertyName];
+ const propertyValue = getOperationArgumentValueFromParameter(operationArguments, {
+ parameterPath: propertyPath,
+ mapper: propertyMapper,
+ }, fallbackObject);
+ if (propertyValue !== undefined) {
+ if (!value) {
+ value = {};
+ }
+ value[propertyName] = propertyValue;
+ }
+ }
}
-
- for (const options of converters) {
- const { key, defaultValue, required, converter } = options
-
- if (required === true) {
- if (!hasOwn(dictionary, key)) {
- throw webidl.errors.exception({
- header: 'Dictionary',
- message: `Missing required key "${key}".`
- })
+ return value;
+}
+exports.getOperationArgumentValueFromParameter = getOperationArgumentValueFromParameter;
+function getPropertyFromParameterPath(parent, parameterPath) {
+ const result = { propertyFound: false };
+ let i = 0;
+ for (; i < parameterPath.length; ++i) {
+ const parameterPathPart = parameterPath[i];
+ // Make sure to check inherited properties too, so don't use hasOwnProperty().
+ if (parent && parameterPathPart in parent) {
+ parent = parent[parameterPathPart];
}
- }
-
- let value = dictionary[key]
- const hasDefault = hasOwn(options, 'defaultValue')
-
- // Only use defaultValue if value is undefined and
- // a defaultValue options was provided.
- if (hasDefault && value !== null) {
- value = value ?? defaultValue
- }
-
- // A key can be optional and have no default value.
- // When this happens, do not perform a conversion,
- // and do not assign the key a value.
- if (required || hasDefault || value !== undefined) {
- value = converter(value)
-
- if (
- options.allowedValues &&
- !options.allowedValues.includes(value)
- ) {
- throw webidl.errors.exception({
- header: 'Dictionary',
- message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
- })
+ else {
+ break;
}
-
- dict[key] = value
- }
}
-
- return dict
- }
+ if (i === parameterPath.length) {
+ result.propertyValue = parent;
+ result.propertyFound = true;
+ }
+ return result;
}
-
-webidl.nullableConverter = function (converter) {
- return (V) => {
- if (V === null) {
- return V
+const originalRequestSymbol = Symbol.for("@azure/core-client original request");
+function hasOriginalRequest(request) {
+ return originalRequestSymbol in request;
+}
+function getOperationRequestInfo(request) {
+ if (hasOriginalRequest(request)) {
+ return getOperationRequestInfo(request[originalRequestSymbol]);
+ }
+ let info = state_js_1.state.operationRequestMap.get(request);
+ if (!info) {
+ info = {};
+ state_js_1.state.operationRequestMap.set(request, info);
}
-
- return converter(V)
- }
+ return info;
}
+exports.getOperationRequestInfo = getOperationRequestInfo;
+//# sourceMappingURL=operationHelpers.js.map
-// https://webidl.spec.whatwg.org/#es-DOMString
-webidl.converters.DOMString = function (V, opts = {}) {
- // 1. If V is null and the conversion is to an IDL type
- // associated with the [LegacyNullToEmptyString]
- // extended attribute, then return the DOMString value
- // that represents the empty string.
- if (V === null && opts.legacyNullToEmptyString) {
- return ''
- }
-
- // 2. Let x be ? ToString(V).
- if (typeof V === 'symbol') {
- throw new TypeError('Could not convert argument of type symbol to string.')
- }
+/***/ }),
- // 3. Return the IDL DOMString value that represents the
- // same sequence of code units as the one the
- // ECMAScript String value x represents.
- return String(V)
-}
+/***/ 64524:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// https://webidl.spec.whatwg.org/#es-ByteString
-webidl.converters.ByteString = function (V) {
- // 1. Let x be ? ToString(V).
- // Note: DOMString converter perform ? ToString(V)
- const x = webidl.converters.DOMString(V)
- // 2. If the value of any element of x is greater than
- // 255, then throw a TypeError.
- for (let index = 0; index < x.length; index++) {
- if (x.charCodeAt(index) > 255) {
- throw new TypeError(
- 'Cannot convert argument to a ByteString because the character at ' +
- `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
- )
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createClientPipeline = void 0;
+const deserializationPolicy_js_1 = __nccwpck_require__(21795);
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+const serializationPolicy_js_1 = __nccwpck_require__(87054);
+/**
+ * Creates a new Pipeline for use with a Service Client.
+ * Adds in deserializationPolicy by default.
+ * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential.
+ * @param options - Options to customize the created pipeline.
+ */
+function createClientPipeline(options = {}) {
+ const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options !== null && options !== void 0 ? options : {});
+ if (options.credentialOptions) {
+ pipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({
+ credential: options.credentialOptions.credential,
+ scopes: options.credentialOptions.credentialScopes,
+ }));
}
- }
-
- // 3. Return an IDL ByteString value whose length is the
- // length of x, and where the value of each element is
- // the value of the corresponding element of x.
- return x
+ pipeline.addPolicy((0, serializationPolicy_js_1.serializationPolicy)(options.serializationOptions), { phase: "Serialize" });
+ pipeline.addPolicy((0, deserializationPolicy_js_1.deserializationPolicy)(options.deserializationOptions), {
+ phase: "Deserialize",
+ });
+ return pipeline;
}
+exports.createClientPipeline = createClientPipeline;
+//# sourceMappingURL=pipeline.js.map
-// https://webidl.spec.whatwg.org/#es-USVString
-webidl.converters.USVString = toUSVString
+/***/ }),
-// https://webidl.spec.whatwg.org/#es-boolean
-webidl.converters.boolean = function (V) {
- // 1. Let x be the result of computing ToBoolean(V).
- const x = Boolean(V)
+/***/ 87054:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. Return the IDL boolean value that is the one that represents
- // the same truth value as the ECMAScript Boolean value x.
- return x
-}
-// https://webidl.spec.whatwg.org/#es-any
-webidl.converters.any = function (V) {
- return V
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.serializeRequestBody = exports.serializeHeaders = exports.serializationPolicy = exports.serializationPolicyName = void 0;
+const interfaces_js_1 = __nccwpck_require__(35590);
+const operationHelpers_js_1 = __nccwpck_require__(17036);
+const serializer_js_1 = __nccwpck_require__(66774);
+const interfaceHelpers_js_1 = __nccwpck_require__(91030);
+/**
+ * The programmatic identifier of the serializationPolicy.
+ */
+exports.serializationPolicyName = "serializationPolicy";
+/**
+ * This policy handles assembling the request body and headers using
+ * an OperationSpec and OperationArguments on the request.
+ */
+function serializationPolicy(options = {}) {
+ const stringifyXML = options.stringifyXML;
+ return {
+ name: exports.serializationPolicyName,
+ async sendRequest(request, next) {
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
+ const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments;
+ if (operationSpec && operationArguments) {
+ serializeHeaders(request, operationArguments, operationSpec);
+ serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);
+ }
+ return next(request);
+ },
+ };
}
-
-// https://webidl.spec.whatwg.org/#es-long-long
-webidl.converters['long long'] = function (V) {
- // 1. Let x be ? ConvertToInt(V, 64, "signed").
- const x = webidl.util.ConvertToInt(V, 64, 'signed')
-
- // 2. Return the IDL long long value that represents
- // the same numeric value as x.
- return x
+exports.serializationPolicy = serializationPolicy;
+/**
+ * @internal
+ */
+function serializeHeaders(request, operationArguments, operationSpec) {
+ var _a, _b;
+ if (operationSpec.headerParameters) {
+ for (const headerParameter of operationSpec.headerParameters) {
+ let headerValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, headerParameter);
+ if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {
+ headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter));
+ const headerCollectionPrefix = headerParameter.mapper
+ .headerCollectionPrefix;
+ if (headerCollectionPrefix) {
+ for (const key of Object.keys(headerValue)) {
+ request.headers.set(headerCollectionPrefix + key, headerValue[key]);
+ }
+ }
+ else {
+ request.headers.set(headerParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter), headerValue);
+ }
+ }
+ }
+ }
+ const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders;
+ if (customHeaders) {
+ for (const customHeaderName of Object.keys(customHeaders)) {
+ request.headers.set(customHeaderName, customHeaders[customHeaderName]);
+ }
+ }
+}
+exports.serializeHeaders = serializeHeaders;
+/**
+ * @internal
+ */
+function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () {
+ throw new Error("XML serialization unsupported!");
+}) {
+ var _a, _b, _c, _d, _e;
+ const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions;
+ const updatedOptions = {
+ xml: {
+ rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "",
+ includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false,
+ xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : interfaces_js_1.XML_CHARKEY,
+ },
+ };
+ const xmlCharKey = updatedOptions.xml.xmlCharKey;
+ if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
+ request.body = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, operationSpec.requestBody);
+ const bodyMapper = operationSpec.requestBody.mapper;
+ const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper;
+ const typeName = bodyMapper.type.name;
+ try {
+ if ((request.body !== undefined && request.body !== null) ||
+ (nullable && request.body === null) ||
+ required) {
+ const requestBodyParameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(operationSpec.requestBody);
+ request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions);
+ const isStream = typeName === serializer_js_1.MapperTypeNames.Stream;
+ if (operationSpec.isXML) {
+ const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
+ const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions);
+ if (typeName === serializer_js_1.MapperTypeNames.Sequence) {
+ request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey });
+ }
+ else if (!isStream) {
+ request.body = stringifyXML(value, {
+ rootName: xmlName || serializedName,
+ xmlCharKey,
+ });
+ }
+ }
+ else if (typeName === serializer_js_1.MapperTypeNames.String &&
+ (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) {
+ // the String serializer has validated that request body is a string
+ // so just send the string.
+ return;
+ }
+ else if (!isStream) {
+ request.body = JSON.stringify(request.body);
+ }
+ }
+ }
+ catch (error) {
+ throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`);
+ }
+ }
+ else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
+ request.formData = {};
+ for (const formDataParameter of operationSpec.formDataParameters) {
+ const formDataParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, formDataParameter);
+ if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
+ const formDataParameterPropertyName = formDataParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter);
+ request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter), updatedOptions);
+ }
+ }
+ }
+}
+exports.serializeRequestBody = serializeRequestBody;
+/**
+ * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself
+ */
+function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) {
+ // Composite and Sequence schemas already got their root namespace set during serialization
+ // We just need to add xmlns to the other schema types
+ if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
+ const result = {};
+ result[options.xml.xmlCharKey] = serializedValue;
+ result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
+ return result;
+ }
+ return serializedValue;
+}
+function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) {
+ if (!Array.isArray(obj)) {
+ obj = [obj];
+ }
+ if (!xmlNamespaceKey || !xmlNamespace) {
+ return { [elementName]: obj };
+ }
+ const result = { [elementName]: obj };
+ result[interfaces_js_1.XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
+ return result;
}
+//# sourceMappingURL=serializationPolicy.js.map
-// https://webidl.spec.whatwg.org/#es-unsigned-long-long
-webidl.converters['unsigned long long'] = function (V) {
- // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
- const x = webidl.util.ConvertToInt(V, 64, 'unsigned')
+/***/ }),
- // 2. Return the IDL unsigned long long value that
- // represents the same numeric value as x.
- return x
-}
+/***/ 66774:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// https://webidl.spec.whatwg.org/#es-unsigned-long
-webidl.converters['unsigned long'] = function (V) {
- // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
- const x = webidl.util.ConvertToInt(V, 32, 'unsigned')
- // 2. Return the IDL unsigned long value that
- // represents the same numeric value as x.
- return x
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.MapperTypeNames = exports.createSerializer = void 0;
+const tslib_1 = __nccwpck_require__(94176);
+const base64 = tslib_1.__importStar(__nccwpck_require__(59793));
+const interfaces_js_1 = __nccwpck_require__(35590);
+const utils_js_1 = __nccwpck_require__(7805);
+class SerializerImpl {
+ constructor(modelMappers = {}, isXML = false) {
+ this.modelMappers = modelMappers;
+ this.isXML = isXML;
+ }
+ /**
+ * @deprecated Removing the constraints validation on client side.
+ */
+ validateConstraints(mapper, value, objectName) {
+ const failValidation = (constraintName, constraintValue) => {
+ throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`);
+ };
+ if (mapper.constraints && value !== undefined && value !== null) {
+ const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints;
+ if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {
+ failValidation("ExclusiveMaximum", ExclusiveMaximum);
+ }
+ if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {
+ failValidation("ExclusiveMinimum", ExclusiveMinimum);
+ }
+ if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {
+ failValidation("InclusiveMaximum", InclusiveMaximum);
+ }
+ if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {
+ failValidation("InclusiveMinimum", InclusiveMinimum);
+ }
+ if (MaxItems !== undefined && value.length > MaxItems) {
+ failValidation("MaxItems", MaxItems);
+ }
+ if (MaxLength !== undefined && value.length > MaxLength) {
+ failValidation("MaxLength", MaxLength);
+ }
+ if (MinItems !== undefined && value.length < MinItems) {
+ failValidation("MinItems", MinItems);
+ }
+ if (MinLength !== undefined && value.length < MinLength) {
+ failValidation("MinLength", MinLength);
+ }
+ if (MultipleOf !== undefined && value % MultipleOf !== 0) {
+ failValidation("MultipleOf", MultipleOf);
+ }
+ if (Pattern) {
+ const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
+ if (typeof value !== "string" || value.match(pattern) === null) {
+ failValidation("Pattern", Pattern);
+ }
+ }
+ if (UniqueItems &&
+ value.some((item, i, ar) => ar.indexOf(item) !== i)) {
+ failValidation("UniqueItems", UniqueItems);
+ }
+ }
+ }
+ /**
+ * Serialize the given object based on its metadata defined in the mapper
+ *
+ * @param mapper - The mapper which defines the metadata of the serializable object
+ *
+ * @param object - A valid Javascript object to be serialized
+ *
+ * @param objectName - Name of the serialized object
+ *
+ * @param options - additional options to serialization
+ *
+ * @returns A valid serialized Javascript object
+ */
+ serialize(mapper, object, objectName, options = { xml: {} }) {
+ var _a, _b, _c;
+ const updatedOptions = {
+ xml: {
+ rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
+ includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
+ xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
+ },
+ };
+ let payload = {};
+ const mapperType = mapper.type.name;
+ if (!objectName) {
+ objectName = mapper.serializedName;
+ }
+ if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = [];
+ }
+ if (mapper.isConstant) {
+ object = mapper.defaultValue;
+ }
+ // This table of allowed values should help explain
+ // the mapper.required and mapper.nullable properties.
+ // X means "neither undefined or null are allowed".
+ // || required
+ // || true | false
+ // nullable || ==========================
+ // true || null | undefined/null
+ // false || X | undefined
+ // undefined || X | undefined/null
+ const { required, nullable } = mapper;
+ if (required && nullable && object === undefined) {
+ throw new Error(`${objectName} cannot be undefined.`);
+ }
+ if (required && !nullable && (object === undefined || object === null)) {
+ throw new Error(`${objectName} cannot be null or undefined.`);
+ }
+ if (!required && nullable === false && object === null) {
+ throw new Error(`${objectName} cannot be null.`);
+ }
+ if (object === undefined || object === null) {
+ payload = object;
+ }
+ else {
+ if (mapperType.match(/^any$/i) !== null) {
+ payload = object;
+ }
+ else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
+ payload = serializeBasicTypes(mapperType, objectName, object);
+ }
+ else if (mapperType.match(/^Enum$/i) !== null) {
+ const enumMapper = mapper;
+ payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
+ }
+ else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
+ payload = serializeDateTypes(mapperType, object, objectName);
+ }
+ else if (mapperType.match(/^ByteArray$/i) !== null) {
+ payload = serializeByteArrayType(objectName, object);
+ }
+ else if (mapperType.match(/^Base64Url$/i) !== null) {
+ payload = serializeBase64UrlType(objectName, object);
+ }
+ else if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ else if (mapperType.match(/^Dictionary$/i) !== null) {
+ payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ else if (mapperType.match(/^Composite$/i) !== null) {
+ payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ }
+ return payload;
+ }
+ /**
+ * Deserialize the given object based on its metadata defined in the mapper
+ *
+ * @param mapper - The mapper which defines the metadata of the serializable object
+ *
+ * @param responseBody - A valid Javascript entity to be deserialized
+ *
+ * @param objectName - Name of the deserialized object
+ *
+ * @param options - Controls behavior of XML parser and builder.
+ *
+ * @returns A valid deserialized Javascript object
+ */
+ deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
+ var _a, _b, _c, _d;
+ const updatedOptions = {
+ xml: {
+ rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
+ includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
+ xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
+ },
+ ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false,
+ };
+ if (responseBody === undefined || responseBody === null) {
+ if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
+ // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
+ // between the list being empty versus being missing,
+ // so let's do the more user-friendly thing and return an empty list.
+ responseBody = [];
+ }
+ // specifically check for undefined as default value can be a falsey value `0, "", false, null`
+ if (mapper.defaultValue !== undefined) {
+ responseBody = mapper.defaultValue;
+ }
+ return responseBody;
+ }
+ let payload;
+ const mapperType = mapper.type.name;
+ if (!objectName) {
+ objectName = mapper.serializedName;
+ }
+ if (mapperType.match(/^Composite$/i) !== null) {
+ payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ else {
+ if (this.isXML) {
+ const xmlCharKey = updatedOptions.xml.xmlCharKey;
+ /**
+ * If the mapper specifies this as a non-composite type value but the responseBody contains
+ * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties,
+ * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property.
+ */
+ if (responseBody[interfaces_js_1.XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {
+ responseBody = responseBody[xmlCharKey];
+ }
+ }
+ if (mapperType.match(/^Number$/i) !== null) {
+ payload = parseFloat(responseBody);
+ if (isNaN(payload)) {
+ payload = responseBody;
+ }
+ }
+ else if (mapperType.match(/^Boolean$/i) !== null) {
+ if (responseBody === "true") {
+ payload = true;
+ }
+ else if (responseBody === "false") {
+ payload = false;
+ }
+ else {
+ payload = responseBody;
+ }
+ }
+ else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
+ payload = responseBody;
+ }
+ else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
+ payload = new Date(responseBody);
+ }
+ else if (mapperType.match(/^UnixTime$/i) !== null) {
+ payload = unixTimeToDate(responseBody);
+ }
+ else if (mapperType.match(/^ByteArray$/i) !== null) {
+ payload = base64.decodeString(responseBody);
+ }
+ else if (mapperType.match(/^Base64Url$/i) !== null) {
+ payload = base64UrlToByteArray(responseBody);
+ }
+ else if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ else if (mapperType.match(/^Dictionary$/i) !== null) {
+ payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ }
+ if (mapper.isConstant) {
+ payload = mapper.defaultValue;
+ }
+ return payload;
+ }
}
-
-// https://webidl.spec.whatwg.org/#es-unsigned-short
-webidl.converters['unsigned short'] = function (V, opts) {
- // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
- const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)
-
- // 2. Return the IDL unsigned short value that represents
- // the same numeric value as x.
- return x
+/**
+ * Method that creates and returns a Serializer.
+ * @param modelMappers - Known models to map
+ * @param isXML - If XML should be supported
+ */
+function createSerializer(modelMappers = {}, isXML = false) {
+ return new SerializerImpl(modelMappers, isXML);
}
-
-// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
-webidl.converters.ArrayBuffer = function (V, opts = {}) {
- // 1. If Type(V) is not Object, or V does not have an
- // [[ArrayBufferData]] internal slot, then throw a
- // TypeError.
- // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
- // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances
- if (
- webidl.util.Type(V) !== 'Object' ||
- !types.isAnyArrayBuffer(V)
- ) {
- throw webidl.errors.conversionFailed({
- prefix: `${V}`,
- argument: `${V}`,
- types: ['ArrayBuffer']
- })
- }
-
- // 2. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V) is true, then throw a
- // TypeError.
- if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
-
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V) is true, then throw a
- // TypeError.
- // Note: resizable ArrayBuffers are currently a proposal.
-
- // 4. Return the IDL ArrayBuffer value that is a
- // reference to the same object as V.
- return V
+exports.createSerializer = createSerializer;
+function trimEnd(str, ch) {
+ let len = str.length;
+ while (len - 1 >= 0 && str[len - 1] === ch) {
+ --len;
+ }
+ return str.substr(0, len);
}
-
-webidl.converters.TypedArray = function (V, T, opts = {}) {
- // 1. Let T be the IDL type V is being converted to.
-
- // 2. If Type(V) is not Object, or V does not have a
- // [[TypedArrayName]] internal slot with a value
- // equal to T’s name, then throw a TypeError.
- if (
- webidl.util.Type(V) !== 'Object' ||
- !types.isTypedArray(V) ||
- V.constructor.name !== T.name
- ) {
- throw webidl.errors.conversionFailed({
- prefix: `${T.name}`,
- argument: `${V}`,
- types: [T.name]
- })
- }
-
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
-
- // 4. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- // Note: resizable array buffers are currently a proposal
-
- // 5. Return the IDL value of type T that is a reference
- // to the same object as V.
- return V
+function bufferToBase64Url(buffer) {
+ if (!buffer) {
+ return undefined;
+ }
+ if (!(buffer instanceof Uint8Array)) {
+ throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
+ }
+ // Uint8Array to Base64.
+ const str = base64.encodeByteArray(buffer);
+ // Base64 to Base64Url.
+ return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
}
-
-webidl.converters.DataView = function (V, opts = {}) {
- // 1. If Type(V) is not Object, or V does not have a
- // [[DataView]] internal slot, then throw a TypeError.
- if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {
- throw webidl.errors.exception({
- header: 'DataView',
- message: 'Object is not a DataView.'
- })
- }
-
- // 2. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,
- // then throw a TypeError.
- if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
-
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- // Note: resizable ArrayBuffers are currently a proposal
-
- // 4. Return the IDL DataView value that is a reference
- // to the same object as V.
- return V
+function base64UrlToByteArray(str) {
+ if (!str) {
+ return undefined;
+ }
+ if (str && typeof str.valueOf() !== "string") {
+ throw new Error("Please provide an input of type string for converting to Uint8Array");
+ }
+ // Base64Url to Base64.
+ str = str.replace(/-/g, "+").replace(/_/g, "/");
+ // Base64 to Uint8Array.
+ return base64.decodeString(str);
}
-
-// https://webidl.spec.whatwg.org/#BufferSource
-webidl.converters.BufferSource = function (V, opts = {}) {
- if (types.isAnyArrayBuffer(V)) {
- return webidl.converters.ArrayBuffer(V, opts)
- }
-
- if (types.isTypedArray(V)) {
- return webidl.converters.TypedArray(V, V.constructor)
- }
-
- if (types.isDataView(V)) {
- return webidl.converters.DataView(V, opts)
- }
-
- throw new TypeError(`Could not convert ${V} to a BufferSource.`)
+function splitSerializeName(prop) {
+ const classes = [];
+ let partialclass = "";
+ if (prop) {
+ const subwords = prop.split(".");
+ for (const item of subwords) {
+ if (item.charAt(item.length - 1) === "\\") {
+ partialclass += item.substr(0, item.length - 1) + ".";
+ }
+ else {
+ partialclass += item;
+ classes.push(partialclass);
+ partialclass = "";
+ }
+ }
+ }
+ return classes;
}
-
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.ByteString
-)
-
-webidl.converters['sequence>'] = webidl.sequenceConverter(
- webidl.converters['sequence']
-)
-
-webidl.converters['record'] = webidl.recordConverter(
- webidl.converters.ByteString,
- webidl.converters.ByteString
-)
-
-module.exports = {
- webidl
+function dateToUnixTime(d) {
+ if (!d) {
+ return undefined;
+ }
+ if (typeof d.valueOf() === "string") {
+ d = new Date(d);
+ }
+ return Math.floor(d.getTime() / 1000);
}
-
-
-/***/ }),
-
-/***/ 68064:
-/***/ ((module) => {
-
-
-
-/**
- * @see https://encoding.spec.whatwg.org/#concept-encoding-get
- * @param {string|undefined} label
- */
-function getEncoding (label) {
- if (!label) {
- return 'failure'
- }
-
- // 1. Remove any leading and trailing ASCII whitespace from label.
- // 2. If label is an ASCII case-insensitive match for any of the
- // labels listed in the table below, then return the
- // corresponding encoding; otherwise return failure.
- switch (label.trim().toLowerCase()) {
- case 'unicode-1-1-utf-8':
- case 'unicode11utf8':
- case 'unicode20utf8':
- case 'utf-8':
- case 'utf8':
- case 'x-unicode20utf8':
- return 'UTF-8'
- case '866':
- case 'cp866':
- case 'csibm866':
- case 'ibm866':
- return 'IBM866'
- case 'csisolatin2':
- case 'iso-8859-2':
- case 'iso-ir-101':
- case 'iso8859-2':
- case 'iso88592':
- case 'iso_8859-2':
- case 'iso_8859-2:1987':
- case 'l2':
- case 'latin2':
- return 'ISO-8859-2'
- case 'csisolatin3':
- case 'iso-8859-3':
- case 'iso-ir-109':
- case 'iso8859-3':
- case 'iso88593':
- case 'iso_8859-3':
- case 'iso_8859-3:1988':
- case 'l3':
- case 'latin3':
- return 'ISO-8859-3'
- case 'csisolatin4':
- case 'iso-8859-4':
- case 'iso-ir-110':
- case 'iso8859-4':
- case 'iso88594':
- case 'iso_8859-4':
- case 'iso_8859-4:1988':
- case 'l4':
- case 'latin4':
- return 'ISO-8859-4'
- case 'csisolatincyrillic':
- case 'cyrillic':
- case 'iso-8859-5':
- case 'iso-ir-144':
- case 'iso8859-5':
- case 'iso88595':
- case 'iso_8859-5':
- case 'iso_8859-5:1988':
- return 'ISO-8859-5'
- case 'arabic':
- case 'asmo-708':
- case 'csiso88596e':
- case 'csiso88596i':
- case 'csisolatinarabic':
- case 'ecma-114':
- case 'iso-8859-6':
- case 'iso-8859-6-e':
- case 'iso-8859-6-i':
- case 'iso-ir-127':
- case 'iso8859-6':
- case 'iso88596':
- case 'iso_8859-6':
- case 'iso_8859-6:1987':
- return 'ISO-8859-6'
- case 'csisolatingreek':
- case 'ecma-118':
- case 'elot_928':
- case 'greek':
- case 'greek8':
- case 'iso-8859-7':
- case 'iso-ir-126':
- case 'iso8859-7':
- case 'iso88597':
- case 'iso_8859-7':
- case 'iso_8859-7:1987':
- case 'sun_eu_greek':
- return 'ISO-8859-7'
- case 'csiso88598e':
- case 'csisolatinhebrew':
- case 'hebrew':
- case 'iso-8859-8':
- case 'iso-8859-8-e':
- case 'iso-ir-138':
- case 'iso8859-8':
- case 'iso88598':
- case 'iso_8859-8':
- case 'iso_8859-8:1988':
- case 'visual':
- return 'ISO-8859-8'
- case 'csiso88598i':
- case 'iso-8859-8-i':
- case 'logical':
- return 'ISO-8859-8-I'
- case 'csisolatin6':
- case 'iso-8859-10':
- case 'iso-ir-157':
- case 'iso8859-10':
- case 'iso885910':
- case 'l6':
- case 'latin6':
- return 'ISO-8859-10'
- case 'iso-8859-13':
- case 'iso8859-13':
- case 'iso885913':
- return 'ISO-8859-13'
- case 'iso-8859-14':
- case 'iso8859-14':
- case 'iso885914':
- return 'ISO-8859-14'
- case 'csisolatin9':
- case 'iso-8859-15':
- case 'iso8859-15':
- case 'iso885915':
- case 'iso_8859-15':
- case 'l9':
- return 'ISO-8859-15'
- case 'iso-8859-16':
- return 'ISO-8859-16'
- case 'cskoi8r':
- case 'koi':
- case 'koi8':
- case 'koi8-r':
- case 'koi8_r':
- return 'KOI8-R'
- case 'koi8-ru':
- case 'koi8-u':
- return 'KOI8-U'
- case 'csmacintosh':
- case 'mac':
- case 'macintosh':
- case 'x-mac-roman':
- return 'macintosh'
- case 'iso-8859-11':
- case 'iso8859-11':
- case 'iso885911':
- case 'tis-620':
- case 'windows-874':
- return 'windows-874'
- case 'cp1250':
- case 'windows-1250':
- case 'x-cp1250':
- return 'windows-1250'
- case 'cp1251':
- case 'windows-1251':
- case 'x-cp1251':
- return 'windows-1251'
- case 'ansi_x3.4-1968':
- case 'ascii':
- case 'cp1252':
- case 'cp819':
- case 'csisolatin1':
- case 'ibm819':
- case 'iso-8859-1':
- case 'iso-ir-100':
- case 'iso8859-1':
- case 'iso88591':
- case 'iso_8859-1':
- case 'iso_8859-1:1987':
- case 'l1':
- case 'latin1':
- case 'us-ascii':
- case 'windows-1252':
- case 'x-cp1252':
- return 'windows-1252'
- case 'cp1253':
- case 'windows-1253':
- case 'x-cp1253':
- return 'windows-1253'
- case 'cp1254':
- case 'csisolatin5':
- case 'iso-8859-9':
- case 'iso-ir-148':
- case 'iso8859-9':
- case 'iso88599':
- case 'iso_8859-9':
- case 'iso_8859-9:1989':
- case 'l5':
- case 'latin5':
- case 'windows-1254':
- case 'x-cp1254':
- return 'windows-1254'
- case 'cp1255':
- case 'windows-1255':
- case 'x-cp1255':
- return 'windows-1255'
- case 'cp1256':
- case 'windows-1256':
- case 'x-cp1256':
- return 'windows-1256'
- case 'cp1257':
- case 'windows-1257':
- case 'x-cp1257':
- return 'windows-1257'
- case 'cp1258':
- case 'windows-1258':
- case 'x-cp1258':
- return 'windows-1258'
- case 'x-mac-cyrillic':
- case 'x-mac-ukrainian':
- return 'x-mac-cyrillic'
- case 'chinese':
- case 'csgb2312':
- case 'csiso58gb231280':
- case 'gb2312':
- case 'gb_2312':
- case 'gb_2312-80':
- case 'gbk':
- case 'iso-ir-58':
- case 'x-gbk':
- return 'GBK'
- case 'gb18030':
- return 'gb18030'
- case 'big5':
- case 'big5-hkscs':
- case 'cn-big5':
- case 'csbig5':
- case 'x-x-big5':
- return 'Big5'
- case 'cseucpkdfmtjapanese':
- case 'euc-jp':
- case 'x-euc-jp':
- return 'EUC-JP'
- case 'csiso2022jp':
- case 'iso-2022-jp':
- return 'ISO-2022-JP'
- case 'csshiftjis':
- case 'ms932':
- case 'ms_kanji':
- case 'shift-jis':
- case 'shift_jis':
- case 'sjis':
- case 'windows-31j':
- case 'x-sjis':
- return 'Shift_JIS'
- case 'cseuckr':
- case 'csksc56011987':
- case 'euc-kr':
- case 'iso-ir-149':
- case 'korean':
- case 'ks_c_5601-1987':
- case 'ks_c_5601-1989':
- case 'ksc5601':
- case 'ksc_5601':
- case 'windows-949':
- return 'EUC-KR'
- case 'csiso2022kr':
- case 'hz-gb-2312':
- case 'iso-2022-cn':
- case 'iso-2022-cn-ext':
- case 'iso-2022-kr':
- case 'replacement':
- return 'replacement'
- case 'unicodefffe':
- case 'utf-16be':
- return 'UTF-16BE'
- case 'csunicode':
- case 'iso-10646-ucs-2':
- case 'ucs-2':
- case 'unicode':
- case 'unicodefeff':
- case 'utf-16':
- case 'utf-16le':
- return 'UTF-16LE'
- case 'x-user-defined':
- return 'x-user-defined'
- default: return 'failure'
- }
+function unixTimeToDate(n) {
+ if (!n) {
+ return undefined;
+ }
+ return new Date(n * 1000);
}
-
-module.exports = {
- getEncoding
+function serializeBasicTypes(typeName, objectName, value) {
+ if (value !== null && value !== undefined) {
+ if (typeName.match(/^Number$/i) !== null) {
+ if (typeof value !== "number") {
+ throw new Error(`${objectName} with value ${value} must be of type number.`);
+ }
+ }
+ else if (typeName.match(/^String$/i) !== null) {
+ if (typeof value.valueOf() !== "string") {
+ throw new Error(`${objectName} with value "${value}" must be of type string.`);
+ }
+ }
+ else if (typeName.match(/^Uuid$/i) !== null) {
+ if (!(typeof value.valueOf() === "string" && (0, utils_js_1.isValidUuid)(value))) {
+ throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`);
+ }
+ }
+ else if (typeName.match(/^Boolean$/i) !== null) {
+ if (typeof value !== "boolean") {
+ throw new Error(`${objectName} with value ${value} must be of type boolean.`);
+ }
+ }
+ else if (typeName.match(/^Stream$/i) !== null) {
+ const objectType = typeof value;
+ if (objectType !== "string" &&
+ typeof value.pipe !== "function" && // NodeJS.ReadableStream
+ typeof value.tee !== "function" && // browser ReadableStream
+ !(value instanceof ArrayBuffer) &&
+ !ArrayBuffer.isView(value) &&
+ // File objects count as a type of Blob, so we want to use instanceof explicitly
+ !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) &&
+ objectType !== "function") {
+ throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`);
+ }
+ }
+ }
+ return value;
}
-
-
-/***/ }),
-
-/***/ 30052:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- staticPropertyDescriptors,
- readOperation,
- fireAProgressEvent
-} = __nccwpck_require__(94273)
-const {
- kState,
- kError,
- kResult,
- kEvents,
- kAborted
-} = __nccwpck_require__(52736)
-const { webidl } = __nccwpck_require__(94354)
-const { kEnumerableProperty } = __nccwpck_require__(89500)
-
-class FileReader extends EventTarget {
- constructor () {
- super()
-
- this[kState] = 'empty'
- this[kResult] = null
- this[kError] = null
- this[kEvents] = {
- loadend: null,
- error: null,
- abort: null,
- load: null,
- progress: null,
- loadstart: null
+function serializeEnumType(objectName, allowedValues, value) {
+ if (!allowedValues) {
+ throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);
}
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
- * @param {import('buffer').Blob} blob
- */
- readAsArrayBuffer (blob) {
- webidl.brandCheck(this, FileReader)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })
-
- blob = webidl.converters.Blob(blob, { strict: false })
-
- // The readAsArrayBuffer(blob) method, when invoked,
- // must initiate a read operation for blob with ArrayBuffer.
- readOperation(this, blob, 'ArrayBuffer')
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#readAsBinaryString
- * @param {import('buffer').Blob} blob
- */
- readAsBinaryString (blob) {
- webidl.brandCheck(this, FileReader)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })
-
- blob = webidl.converters.Blob(blob, { strict: false })
-
- // The readAsBinaryString(blob) method, when invoked,
- // must initiate a read operation for blob with BinaryString.
- readOperation(this, blob, 'BinaryString')
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#readAsDataText
- * @param {import('buffer').Blob} blob
- * @param {string?} encoding
- */
- readAsText (blob, encoding = undefined) {
- webidl.brandCheck(this, FileReader)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })
-
- blob = webidl.converters.Blob(blob, { strict: false })
-
- if (encoding !== undefined) {
- encoding = webidl.converters.DOMString(encoding)
+ const isPresent = allowedValues.some((item) => {
+ if (typeof item.valueOf() === "string") {
+ return item.toLowerCase() === value.toLowerCase();
+ }
+ return item === value;
+ });
+ if (!isPresent) {
+ throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`);
}
-
- // The readAsText(blob, encoding) method, when invoked,
- // must initiate a read operation for blob with Text and encoding.
- readOperation(this, blob, 'Text', encoding)
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
- * @param {import('buffer').Blob} blob
- */
- readAsDataURL (blob) {
- webidl.brandCheck(this, FileReader)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })
-
- blob = webidl.converters.Blob(blob, { strict: false })
-
- // The readAsDataURL(blob) method, when invoked, must
- // initiate a read operation for blob with DataURL.
- readOperation(this, blob, 'DataURL')
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-abort
- */
- abort () {
- // 1. If this's state is "empty" or if this's state is
- // "done" set this's result to null and terminate
- // this algorithm.
- if (this[kState] === 'empty' || this[kState] === 'done') {
- this[kResult] = null
- return
+ return value;
+}
+function serializeByteArrayType(objectName, value) {
+ if (value !== undefined && value !== null) {
+ if (!(value instanceof Uint8Array)) {
+ throw new Error(`${objectName} must be of type Uint8Array.`);
+ }
+ value = base64.encodeByteArray(value);
}
-
- // 2. If this's state is "loading" set this's state to
- // "done" and set this's result to null.
- if (this[kState] === 'loading') {
- this[kState] = 'done'
- this[kResult] = null
+ return value;
+}
+function serializeBase64UrlType(objectName, value) {
+ if (value !== undefined && value !== null) {
+ if (!(value instanceof Uint8Array)) {
+ throw new Error(`${objectName} must be of type Uint8Array.`);
+ }
+ value = bufferToBase64Url(value);
+ }
+ return value;
+}
+function serializeDateTypes(typeName, value, objectName) {
+ if (value !== undefined && value !== null) {
+ if (typeName.match(/^Date$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
+ }
+ value =
+ value instanceof Date
+ ? value.toISOString().substring(0, 10)
+ : new Date(value).toISOString().substring(0, 10);
+ }
+ else if (typeName.match(/^DateTime$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
+ }
+ value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
+ }
+ else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
+ }
+ value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
+ }
+ else if (typeName.match(/^UnixTime$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +
+ `for it to be serialized in UnixTime/Epoch format.`);
+ }
+ value = dateToUnixTime(value);
+ }
+ else if (typeName.match(/^TimeSpan$/i) !== null) {
+ if (!(0, utils_js_1.isDuration)(value)) {
+ throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`);
+ }
+ }
+ }
+ return value;
+}
+function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) {
+ var _a;
+ if (!Array.isArray(object)) {
+ throw new Error(`${objectName} must be of type Array.`);
+ }
+ let elementType = mapper.type.element;
+ if (!elementType || typeof elementType !== "object") {
+ throw new Error(`element" metadata for an Array must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}.`);
+ }
+ // Quirk: Composite mappers referenced by `element` might
+ // not have *all* properties declared (like uberParent),
+ // so let's try to look up the full definition by name.
+ if (elementType.type.name === "Composite" && elementType.type.className) {
+ elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType;
+ }
+ const tempArray = [];
+ for (let i = 0; i < object.length; i++) {
+ const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
+ if (isXml && elementType.xmlNamespace) {
+ const xmlnsKey = elementType.xmlNamespacePrefix
+ ? `xmlns:${elementType.xmlNamespacePrefix}`
+ : "xmlns";
+ if (elementType.type.name === "Composite") {
+ tempArray[i] = Object.assign({}, serializedValue);
+ tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
+ }
+ else {
+ tempArray[i] = {};
+ tempArray[i][options.xml.xmlCharKey] = serializedValue;
+ tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
+ }
+ }
+ else {
+ tempArray[i] = serializedValue;
+ }
+ }
+ return tempArray;
+}
+function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) {
+ if (typeof object !== "object") {
+ throw new Error(`${objectName} must be of type object.`);
+ }
+ const valueType = mapper.type.value;
+ if (!valueType || typeof valueType !== "object") {
+ throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}.`);
+ }
+ const tempDictionary = {};
+ for (const key of Object.keys(object)) {
+ const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
+ // If the element needs an XML namespace we need to add it within the $ property
+ tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
+ }
+ // Add the namespace to the root element if needed
+ if (isXml && mapper.xmlNamespace) {
+ const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
+ const result = tempDictionary;
+ result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
+ return result;
+ }
+ return tempDictionary;
+}
+/**
+ * Resolves the additionalProperties property from a referenced mapper
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ * @param objectName - name of the object being serialized
+ */
+function resolveAdditionalProperties(serializer, mapper, objectName) {
+ const additionalProperties = mapper.type.additionalProperties;
+ if (!additionalProperties && mapper.type.className) {
+ const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
+ return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties;
+ }
+ return additionalProperties;
+}
+/**
+ * Finds the mapper referenced by className
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ * @param objectName - name of the object being serialized
+ */
+function resolveReferencedMapper(serializer, mapper, objectName) {
+ const className = mapper.type.className;
+ if (!className) {
+ throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`);
+ }
+ return serializer.modelMappers[className];
+}
+/**
+ * Resolves a composite mapper's modelProperties.
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ */
+function resolveModelProperties(serializer, mapper, objectName) {
+ let modelProps = mapper.type.modelProperties;
+ if (!modelProps) {
+ const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
+ if (!modelMapper) {
+ throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
+ }
+ modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties;
+ if (!modelProps) {
+ throw new Error(`modelProperties cannot be null or undefined in the ` +
+ `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`);
+ }
+ }
+ return modelProps;
+}
+function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) {
+ if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
+ mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
+ }
+ if (object !== undefined && object !== null) {
+ const payload = {};
+ const modelProps = resolveModelProperties(serializer, mapper, objectName);
+ for (const key of Object.keys(modelProps)) {
+ const propertyMapper = modelProps[key];
+ if (propertyMapper.readOnly) {
+ continue;
+ }
+ let propName;
+ let parentObject = payload;
+ if (serializer.isXML) {
+ if (propertyMapper.xmlIsWrapped) {
+ propName = propertyMapper.xmlName;
+ }
+ else {
+ propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
+ }
+ }
+ else {
+ const paths = splitSerializeName(propertyMapper.serializedName);
+ propName = paths.pop();
+ for (const pathName of paths) {
+ const childObject = parentObject[pathName];
+ if ((childObject === undefined || childObject === null) &&
+ ((object[key] !== undefined && object[key] !== null) ||
+ propertyMapper.defaultValue !== undefined)) {
+ parentObject[pathName] = {};
+ }
+ parentObject = parentObject[pathName];
+ }
+ }
+ if (parentObject !== undefined && parentObject !== null) {
+ if (isXml && mapper.xmlNamespace) {
+ const xmlnsKey = mapper.xmlNamespacePrefix
+ ? `xmlns:${mapper.xmlNamespacePrefix}`
+ : "xmlns";
+ parentObject[interfaces_js_1.XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[interfaces_js_1.XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace });
+ }
+ const propertyObjectName = propertyMapper.serializedName !== ""
+ ? objectName + "." + propertyMapper.serializedName
+ : objectName;
+ let toSerialize = object[key];
+ const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
+ if (polymorphicDiscriminator &&
+ polymorphicDiscriminator.clientName === key &&
+ (toSerialize === undefined || toSerialize === null)) {
+ toSerialize = mapper.serializedName;
+ }
+ const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options);
+ if (serializedValue !== undefined && propName !== undefined && propName !== null) {
+ const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
+ if (isXml && propertyMapper.xmlIsAttribute) {
+ // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.
+ // This keeps things simple while preventing name collision
+ // with names in user documents.
+ parentObject[interfaces_js_1.XML_ATTRKEY] = parentObject[interfaces_js_1.XML_ATTRKEY] || {};
+ parentObject[interfaces_js_1.XML_ATTRKEY][propName] = serializedValue;
+ }
+ else if (isXml && propertyMapper.xmlIsWrapped) {
+ parentObject[propName] = { [propertyMapper.xmlElementName]: value };
+ }
+ else {
+ parentObject[propName] = value;
+ }
+ }
+ }
+ }
+ const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
+ if (additionalPropertiesMapper) {
+ const propNames = Object.keys(modelProps);
+ for (const clientPropName in object) {
+ const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
+ if (isAdditionalProperty) {
+ payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options);
+ }
+ }
+ }
+ return payload;
+ }
+ return object;
+}
+function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) {
+ if (!isXml || !propertyMapper.xmlNamespace) {
+ return serializedValue;
+ }
+ const xmlnsKey = propertyMapper.xmlNamespacePrefix
+ ? `xmlns:${propertyMapper.xmlNamespacePrefix}`
+ : "xmlns";
+ const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
+ if (["Composite"].includes(propertyMapper.type.name)) {
+ if (serializedValue[interfaces_js_1.XML_ATTRKEY]) {
+ return serializedValue;
+ }
+ else {
+ const result = Object.assign({}, serializedValue);
+ result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
+ return result;
+ }
+ }
+ const result = {};
+ result[options.xml.xmlCharKey] = serializedValue;
+ result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
+ return result;
+}
+function isSpecialXmlProperty(propertyName, options) {
+ return [interfaces_js_1.XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
+}
+function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
+ var _a, _b;
+ const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : interfaces_js_1.XML_CHARKEY;
+ if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
+ mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
+ }
+ const modelProps = resolveModelProperties(serializer, mapper, objectName);
+ let instance = {};
+ const handledPropertyNames = [];
+ for (const key of Object.keys(modelProps)) {
+ const propertyMapper = modelProps[key];
+ const paths = splitSerializeName(modelProps[key].serializedName);
+ handledPropertyNames.push(paths[0]);
+ const { serializedName, xmlName, xmlElementName } = propertyMapper;
+ let propertyObjectName = objectName;
+ if (serializedName !== "" && serializedName !== undefined) {
+ propertyObjectName = objectName + "." + serializedName;
+ }
+ const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
+ if (headerCollectionPrefix) {
+ const dictionary = {};
+ for (const headerKey of Object.keys(responseBody)) {
+ if (headerKey.startsWith(headerCollectionPrefix)) {
+ dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options);
+ }
+ handledPropertyNames.push(headerKey);
+ }
+ instance[key] = dictionary;
+ }
+ else if (serializer.isXML) {
+ if (propertyMapper.xmlIsAttribute && responseBody[interfaces_js_1.XML_ATTRKEY]) {
+ instance[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options);
+ }
+ else if (propertyMapper.xmlIsMsText) {
+ if (responseBody[xmlCharKey] !== undefined) {
+ instance[key] = responseBody[xmlCharKey];
+ }
+ else if (typeof responseBody === "string") {
+ // The special case where xml parser parses "content" into JSON of
+ // `{ name: "content"}` instead of `{ name: { "_": "content" }}`
+ instance[key] = responseBody;
+ }
+ }
+ else {
+ const propertyName = xmlElementName || xmlName || serializedName;
+ if (propertyMapper.xmlIsWrapped) {
+ /* a list of wrapped by
+ For the xml example below
+
+ ...
+ ...
+
+ the responseBody has
+ {
+ Cors: {
+ CorsRule: [{...}, {...}]
+ }
+ }
+ xmlName is "Cors" and xmlElementName is"CorsRule".
+ */
+ const wrapped = responseBody[xmlName];
+ const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : [];
+ instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options);
+ handledPropertyNames.push(xmlName);
+ }
+ else {
+ const property = responseBody[propertyName];
+ instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
+ handledPropertyNames.push(propertyName);
+ }
+ }
+ }
+ else {
+ // deserialize the property if it is present in the provided responseBody instance
+ let propertyInstance;
+ let res = responseBody;
+ // traversing the object step by step.
+ let steps = 0;
+ for (const item of paths) {
+ if (!res)
+ break;
+ steps++;
+ res = res[item];
+ }
+ // only accept null when reaching the last position of object otherwise it would be undefined
+ if (res === null && steps < paths.length) {
+ res = undefined;
+ }
+ propertyInstance = res;
+ const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
+ // checking that the model property name (key)(ex: "fishtype") and the
+ // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
+ // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
+ // is a better approach. The generator is not consistent with escaping '\.' in the
+ // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
+ // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
+ // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
+ // the transformation of model property name (ex: "fishtype") is done consistently.
+ // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
+ if (polymorphicDiscriminator &&
+ key === polymorphicDiscriminator.clientName &&
+ (propertyInstance === undefined || propertyInstance === null)) {
+ propertyInstance = mapper.serializedName;
+ }
+ let serializedValue;
+ // paging
+ if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
+ propertyInstance = responseBody[key];
+ const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
+ // Copy over any properties that have already been added into the instance, where they do
+ // not exist on the newly de-serialized array
+ for (const [k, v] of Object.entries(instance)) {
+ if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
+ arrayInstance[k] = v;
+ }
+ }
+ instance = arrayInstance;
+ }
+ else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
+ serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
+ instance[key] = serializedValue;
+ }
+ }
}
-
- // 3. If there are any tasks from this on the file reading
- // task source in an affiliated task queue, then remove
- // those tasks from that task queue.
- this[kAborted] = true
-
- // 4. Terminate the algorithm for the read method being processed.
- // TODO
-
- // 5. Fire a progress event called abort at this.
- fireAProgressEvent('abort', this)
-
- // 6. If this's state is not "loading", fire a progress
- // event called loadend at this.
- if (this[kState] !== 'loading') {
- fireAProgressEvent('loadend', this)
+ const additionalPropertiesMapper = mapper.type.additionalProperties;
+ if (additionalPropertiesMapper) {
+ const isAdditionalProperty = (responsePropName) => {
+ for (const clientPropName in modelProps) {
+ const paths = splitSerializeName(modelProps[clientPropName].serializedName);
+ if (paths[0] === responsePropName) {
+ return false;
+ }
+ }
+ return true;
+ };
+ for (const responsePropName in responseBody) {
+ if (isAdditionalProperty(responsePropName)) {
+ instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options);
+ }
+ }
}
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
- */
- get readyState () {
- webidl.brandCheck(this, FileReader)
-
- switch (this[kState]) {
- case 'empty': return this.EMPTY
- case 'loading': return this.LOADING
- case 'done': return this.DONE
+ else if (responseBody && !options.ignoreUnknownProperties) {
+ for (const key of Object.keys(responseBody)) {
+ if (instance[key] === undefined &&
+ !handledPropertyNames.includes(key) &&
+ !isSpecialXmlProperty(key, options)) {
+ instance[key] = responseBody[key];
+ }
+ }
}
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-result
- */
- get result () {
- webidl.brandCheck(this, FileReader)
-
- // The result attribute’s getter, when invoked, must return
- // this's result.
- return this[kResult]
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-error
- */
- get error () {
- webidl.brandCheck(this, FileReader)
-
- // The error attribute’s getter, when invoked, must return
- // this's error.
- return this[kError]
- }
-
- get onloadend () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].loadend
- }
-
- set onloadend (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].loadend) {
- this.removeEventListener('loadend', this[kEvents].loadend)
+ return instance;
+}
+function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) {
+ /* jshint validthis: true */
+ const value = mapper.type.value;
+ if (!value || typeof value !== "object") {
+ throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}`);
}
-
- if (typeof fn === 'function') {
- this[kEvents].loadend = fn
- this.addEventListener('loadend', fn)
- } else {
- this[kEvents].loadend = null
+ if (responseBody) {
+ const tempDictionary = {};
+ for (const key of Object.keys(responseBody)) {
+ tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
+ }
+ return tempDictionary;
}
- }
-
- get onerror () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].error
- }
-
- set onerror (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].error) {
- this.removeEventListener('error', this[kEvents].error)
+ return responseBody;
+}
+function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) {
+ var _a;
+ let element = mapper.type.element;
+ if (!element || typeof element !== "object") {
+ throw new Error(`element" metadata for an Array must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}`);
}
-
- if (typeof fn === 'function') {
- this[kEvents].error = fn
- this.addEventListener('error', fn)
- } else {
- this[kEvents].error = null
+ if (responseBody) {
+ if (!Array.isArray(responseBody)) {
+ // xml2js will interpret a single element array as just the element, so force it to be an array
+ responseBody = [responseBody];
+ }
+ // Quirk: Composite mappers referenced by `element` might
+ // not have *all* properties declared (like uberParent),
+ // so let's try to look up the full definition by name.
+ if (element.type.name === "Composite" && element.type.className) {
+ element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element;
+ }
+ const tempArray = [];
+ for (let i = 0; i < responseBody.length; i++) {
+ tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options);
+ }
+ return tempArray;
}
- }
-
- get onloadstart () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].loadstart
- }
-
- set onloadstart (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].loadstart) {
- this.removeEventListener('loadstart', this[kEvents].loadstart)
+ return responseBody;
+}
+function getIndexDiscriminator(discriminators, discriminatorValue, typeName) {
+ const typeNamesToCheck = [typeName];
+ while (typeNamesToCheck.length) {
+ const currentName = typeNamesToCheck.shift();
+ const indexDiscriminator = discriminatorValue === currentName
+ ? discriminatorValue
+ : currentName + "." + discriminatorValue;
+ if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
+ return discriminators[indexDiscriminator];
+ }
+ else {
+ for (const [name, mapper] of Object.entries(discriminators)) {
+ if (name.startsWith(currentName + ".") &&
+ mapper.type.uberParent === currentName &&
+ mapper.type.className) {
+ typeNamesToCheck.push(mapper.type.className);
+ }
+ }
+ }
}
-
- if (typeof fn === 'function') {
- this[kEvents].loadstart = fn
- this.addEventListener('loadstart', fn)
- } else {
- this[kEvents].loadstart = null
+ return undefined;
+}
+function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
+ var _a;
+ const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
+ if (polymorphicDiscriminator) {
+ let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
+ if (discriminatorName) {
+ // The serializedName might have \\, which we just want to ignore
+ if (polymorphicPropertyName === "serializedName") {
+ discriminatorName = discriminatorName.replace(/\\/gi, "");
+ }
+ const discriminatorValue = object[discriminatorName];
+ const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className;
+ if (typeof discriminatorValue === "string" && typeName) {
+ const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName);
+ if (polymorphicMapper) {
+ mapper = polymorphicMapper;
+ }
+ }
+ }
}
- }
+ return mapper;
+}
+function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
+ return (mapper.type.polymorphicDiscriminator ||
+ getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
+ getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
+}
+function getPolymorphicDiscriminatorSafely(serializer, typeName) {
+ return (typeName &&
+ serializer.modelMappers[typeName] &&
+ serializer.modelMappers[typeName].type.polymorphicDiscriminator);
+}
+/**
+ * Known types of Mappers
+ */
+exports.MapperTypeNames = {
+ Base64Url: "Base64Url",
+ Boolean: "Boolean",
+ ByteArray: "ByteArray",
+ Composite: "Composite",
+ Date: "Date",
+ DateTime: "DateTime",
+ DateTimeRfc1123: "DateTimeRfc1123",
+ Dictionary: "Dictionary",
+ Enum: "Enum",
+ Number: "Number",
+ Object: "Object",
+ Sequence: "Sequence",
+ String: "String",
+ Stream: "Stream",
+ TimeSpan: "TimeSpan",
+ UnixTime: "UnixTime",
+};
+//# sourceMappingURL=serializer.js.map
- get onprogress () {
- webidl.brandCheck(this, FileReader)
+/***/ }),
- return this[kEvents].progress
- }
+/***/ 22732:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- set onprogress (fn) {
- webidl.brandCheck(this, FileReader)
- if (this[kEvents].progress) {
- this.removeEventListener('progress', this[kEvents].progress)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ServiceClient = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+const pipeline_js_1 = __nccwpck_require__(64524);
+const utils_js_1 = __nccwpck_require__(7805);
+const httpClientCache_js_1 = __nccwpck_require__(64663);
+const operationHelpers_js_1 = __nccwpck_require__(17036);
+const urlHelpers_js_1 = __nccwpck_require__(36580);
+const interfaceHelpers_js_1 = __nccwpck_require__(91030);
+const log_js_1 = __nccwpck_require__(75630);
+/**
+ * Initializes a new instance of the ServiceClient.
+ */
+class ServiceClient {
+ /**
+ * The ServiceClient constructor
+ * @param credential - The credentials used for authentication with the service.
+ * @param options - The service client options that govern the behavior of the client.
+ */
+ constructor(options = {}) {
+ var _a, _b;
+ this._requestContentType = options.requestContentType;
+ this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri;
+ if (options.baseUri) {
+ log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
+ }
+ this._allowInsecureConnection = options.allowInsecureConnection;
+ this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)();
+ this.pipeline = options.pipeline || createDefaultPipeline(options);
+ if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) {
+ for (const { policy, position } of options.additionalPolicies) {
+ // Sign happens after Retry and is commonly needed to occur
+ // before policies that intercept post-retry.
+ const afterPhase = position === "perRetry" ? "Sign" : undefined;
+ this.pipeline.addPolicy(policy, {
+ afterPhase,
+ });
+ }
+ }
}
-
- if (typeof fn === 'function') {
- this[kEvents].progress = fn
- this.addEventListener('progress', fn)
- } else {
- this[kEvents].progress = null
+ /**
+ * Send the provided httpRequest.
+ */
+ async sendRequest(request) {
+ return this.pipeline.sendRequest(this._httpClient, request);
}
- }
-
- get onload () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].load
- }
-
- set onload (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].load) {
- this.removeEventListener('load', this[kEvents].load)
+ /**
+ * Send an HTTP request that is populated using the provided OperationSpec.
+ * @typeParam T - The typed result of the request, based on the OperationSpec.
+ * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.
+ * @param operationSpec - The OperationSpec to use to populate the httpRequest.
+ */
+ async sendOperationRequest(operationArguments, operationSpec) {
+ const endpoint = operationSpec.baseUrl || this._endpoint;
+ if (!endpoint) {
+ throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.");
+ }
+ // Templatized URLs sometimes reference properties on the ServiceClient child class,
+ // so we have to pass `this` below in order to search these properties if they're
+ // not part of OperationArguments
+ const url = (0, urlHelpers_js_1.getRequestUrl)(endpoint, operationSpec, operationArguments, this);
+ const request = (0, core_rest_pipeline_1.createPipelineRequest)({
+ url,
+ });
+ request.method = operationSpec.httpMethod;
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ operationInfo.operationSpec = operationSpec;
+ operationInfo.operationArguments = operationArguments;
+ const contentType = operationSpec.contentType || this._requestContentType;
+ if (contentType && operationSpec.requestBody) {
+ request.headers.set("Content-Type", contentType);
+ }
+ const options = operationArguments.options;
+ if (options) {
+ const requestOptions = options.requestOptions;
+ if (requestOptions) {
+ if (requestOptions.timeout) {
+ request.timeout = requestOptions.timeout;
+ }
+ if (requestOptions.onUploadProgress) {
+ request.onUploadProgress = requestOptions.onUploadProgress;
+ }
+ if (requestOptions.onDownloadProgress) {
+ request.onDownloadProgress = requestOptions.onDownloadProgress;
+ }
+ if (requestOptions.shouldDeserialize !== undefined) {
+ operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;
+ }
+ if (requestOptions.allowInsecureConnection) {
+ request.allowInsecureConnection = true;
+ }
+ }
+ if (options.abortSignal) {
+ request.abortSignal = options.abortSignal;
+ }
+ if (options.tracingOptions) {
+ request.tracingOptions = options.tracingOptions;
+ }
+ }
+ if (this._allowInsecureConnection) {
+ request.allowInsecureConnection = true;
+ }
+ if (request.streamResponseStatusCodes === undefined) {
+ request.streamResponseStatusCodes = (0, interfaceHelpers_js_1.getStreamingResponseStatusCodes)(operationSpec);
+ }
+ try {
+ const rawResponse = await this.sendRequest(request);
+ const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]);
+ if (options === null || options === void 0 ? void 0 : options.onResponse) {
+ options.onResponse(rawResponse, flatResponse);
+ }
+ return flatResponse;
+ }
+ catch (error) {
+ if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) {
+ const rawResponse = error.response;
+ const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]);
+ error.details = flatResponse;
+ if (options === null || options === void 0 ? void 0 : options.onResponse) {
+ options.onResponse(rawResponse, flatResponse, error);
+ }
+ }
+ throw error;
+ }
}
-
- if (typeof fn === 'function') {
- this[kEvents].load = fn
- this.addEventListener('load', fn)
- } else {
- this[kEvents].load = null
+}
+exports.ServiceClient = ServiceClient;
+function createDefaultPipeline(options) {
+ const credentialScopes = getCredentialScopes(options);
+ const credentialOptions = options.credential && credentialScopes
+ ? { credentialScopes, credential: options.credential }
+ : undefined;
+ return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions }));
+}
+function getCredentialScopes(options) {
+ if (options.credentialScopes) {
+ return options.credentialScopes;
}
- }
-
- get onabort () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].abort
- }
-
- set onabort (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].abort) {
- this.removeEventListener('abort', this[kEvents].abort)
+ if (options.endpoint) {
+ return `${options.endpoint}/.default`;
}
-
- if (typeof fn === 'function') {
- this[kEvents].abort = fn
- this.addEventListener('abort', fn)
- } else {
- this[kEvents].abort = null
+ if (options.baseUri) {
+ return `${options.baseUri}/.default`;
}
- }
-}
-
-// https://w3c.github.io/FileAPI/#dom-filereader-empty
-FileReader.EMPTY = FileReader.prototype.EMPTY = 0
-// https://w3c.github.io/FileAPI/#dom-filereader-loading
-FileReader.LOADING = FileReader.prototype.LOADING = 1
-// https://w3c.github.io/FileAPI/#dom-filereader-done
-FileReader.DONE = FileReader.prototype.DONE = 2
-
-Object.defineProperties(FileReader.prototype, {
- EMPTY: staticPropertyDescriptors,
- LOADING: staticPropertyDescriptors,
- DONE: staticPropertyDescriptors,
- readAsArrayBuffer: kEnumerableProperty,
- readAsBinaryString: kEnumerableProperty,
- readAsText: kEnumerableProperty,
- readAsDataURL: kEnumerableProperty,
- abort: kEnumerableProperty,
- readyState: kEnumerableProperty,
- result: kEnumerableProperty,
- error: kEnumerableProperty,
- onloadstart: kEnumerableProperty,
- onprogress: kEnumerableProperty,
- onload: kEnumerableProperty,
- onabort: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onloadend: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'FileReader',
- writable: false,
- enumerable: false,
- configurable: true
- }
-})
-
-Object.defineProperties(FileReader, {
- EMPTY: staticPropertyDescriptors,
- LOADING: staticPropertyDescriptors,
- DONE: staticPropertyDescriptors
-})
-
-module.exports = {
- FileReader
+ if (options.credential && !options.credentialScopes) {
+ throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`);
+ }
+ return undefined;
}
-
+//# sourceMappingURL=serviceClient.js.map
/***/ }),
-/***/ 92804:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { webidl } = __nccwpck_require__(94354)
+/***/ 35077:
+/***/ ((__unused_webpack_module, exports) => {
-const kState = Symbol('ProgressEvent state')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.state = void 0;
/**
- * @see https://xhr.spec.whatwg.org/#progressevent
+ * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports.
*/
-class ProgressEvent extends Event {
- constructor (type, eventInitDict = {}) {
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
-
- super(type, eventInitDict)
-
- this[kState] = {
- lengthComputable: eventInitDict.lengthComputable,
- loaded: eventInitDict.loaded,
- total: eventInitDict.total
- }
- }
-
- get lengthComputable () {
- webidl.brandCheck(this, ProgressEvent)
-
- return this[kState].lengthComputable
- }
+exports.state = {
+ operationRequestMap: new WeakMap(),
+};
+//# sourceMappingURL=state-cjs.cjs.map
- get loaded () {
- webidl.brandCheck(this, ProgressEvent)
+/***/ }),
- return this[kState].loaded
- }
+/***/ 36580:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- get total () {
- webidl.brandCheck(this, ProgressEvent)
- return this[kState].total
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.appendQueryParams = exports.getRequestUrl = void 0;
+const operationHelpers_js_1 = __nccwpck_require__(17036);
+const interfaceHelpers_js_1 = __nccwpck_require__(91030);
+const CollectionFormatToDelimiterMap = {
+ CSV: ",",
+ SSV: " ",
+ Multi: "Multi",
+ TSV: "\t",
+ Pipes: "|",
+};
+function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) {
+ const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject);
+ let isAbsolutePath = false;
+ let requestUrl = replaceAll(baseUri, urlReplacements);
+ if (operationSpec.path) {
+ let path = replaceAll(operationSpec.path, urlReplacements);
+ // QUIRK: sometimes we get a path component like /{nextLink}
+ // which may be a fully formed URL with a leading /. In that case, we should
+ // remove the leading /
+ if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) {
+ path = path.substring(1);
+ }
+ // QUIRK: sometimes we get a path component like {nextLink}
+ // which may be a fully formed URL. In that case, we should
+ // ignore the baseUri.
+ if (isAbsoluteUrl(path)) {
+ requestUrl = path;
+ isAbsolutePath = true;
+ }
+ else {
+ requestUrl = appendPath(requestUrl, path);
+ }
+ }
+ const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject);
+ /**
+ * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`
+ * is an absolute path. This ensures that existing query parameter values in `requestUrl`
+ * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it
+ * is still being built so there is nothing to overwrite.
+ */
+ requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);
+ return requestUrl;
}
-
-webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
- {
- key: 'lengthComputable',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'loaded',
- converter: webidl.converters['unsigned long long'],
- defaultValue: 0
- },
- {
- key: 'total',
- converter: webidl.converters['unsigned long long'],
- defaultValue: 0
- },
- {
- key: 'bubbles',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'cancelable',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'composed',
- converter: webidl.converters.boolean,
- defaultValue: false
- }
-])
-
-module.exports = {
- ProgressEvent
+exports.getRequestUrl = getRequestUrl;
+function replaceAll(input, replacements) {
+ let result = input;
+ for (const [searchValue, replaceValue] of replacements) {
+ result = result.split(searchValue).join(replaceValue);
+ }
+ return result;
}
-
-
-/***/ }),
-
-/***/ 52736:
-/***/ ((module) => {
-
-
-
-module.exports = {
- kState: Symbol('FileReader state'),
- kResult: Symbol('FileReader result'),
- kError: Symbol('FileReader error'),
- kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
- kEvents: Symbol('FileReader events'),
- kAborted: Symbol('FileReader aborted')
+function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
+ var _a;
+ const result = new Map();
+ if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) {
+ for (const urlParameter of operationSpec.urlParameters) {
+ let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject);
+ const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter);
+ urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString);
+ if (!urlParameter.skipEncoding) {
+ urlParameterValue = encodeURIComponent(urlParameterValue);
+ }
+ result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue);
+ }
+ }
+ return result;
}
-
-
-/***/ }),
-
-/***/ 94273:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- kState,
- kError,
- kResult,
- kAborted,
- kLastProgressEventFired
-} = __nccwpck_require__(52736)
-const { ProgressEvent } = __nccwpck_require__(92804)
-const { getEncoding } = __nccwpck_require__(68064)
-const { DOMException } = __nccwpck_require__(21234)
-const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(37246)
-const { types } = __nccwpck_require__(39023)
-const { StringDecoder } = __nccwpck_require__(13193)
-const { btoa } = __nccwpck_require__(20181)
-
-/** @type {PropertyDescriptor} */
-const staticPropertyDescriptors = {
- enumerable: true,
- writable: false,
- configurable: false
+function isAbsoluteUrl(url) {
+ return url.includes("://");
}
-
-/**
- * @see https://w3c.github.io/FileAPI/#readOperation
- * @param {import('./filereader').FileReader} fr
- * @param {import('buffer').Blob} blob
- * @param {string} type
- * @param {string?} encodingName
- */
-function readOperation (fr, blob, type, encodingName) {
- // 1. If fr’s state is "loading", throw an InvalidStateError
- // DOMException.
- if (fr[kState] === 'loading') {
- throw new DOMException('Invalid state', 'InvalidStateError')
- }
-
- // 2. Set fr’s state to "loading".
- fr[kState] = 'loading'
-
- // 3. Set fr’s result to null.
- fr[kResult] = null
-
- // 4. Set fr’s error to null.
- fr[kError] = null
-
- // 5. Let stream be the result of calling get stream on blob.
- /** @type {import('stream/web').ReadableStream} */
- const stream = blob.stream()
-
- // 6. Let reader be the result of getting a reader from stream.
- const reader = stream.getReader()
-
- // 7. Let bytes be an empty byte sequence.
- /** @type {Uint8Array[]} */
- const bytes = []
-
- // 8. Let chunkPromise be the result of reading a chunk from
- // stream with reader.
- let chunkPromise = reader.read()
-
- // 9. Let isFirstChunk be true.
- let isFirstChunk = true
-
- // 10. In parallel, while true:
- // Note: "In parallel" just means non-blocking
- // Note 2: readOperation itself cannot be async as double
- // reading the body would then reject the promise, instead
- // of throwing an error.
- ;(async () => {
- while (!fr[kAborted]) {
- // 1. Wait for chunkPromise to be fulfilled or rejected.
- try {
- const { done, value } = await chunkPromise
-
- // 2. If chunkPromise is fulfilled, and isFirstChunk is
- // true, queue a task to fire a progress event called
- // loadstart at fr.
- if (isFirstChunk && !fr[kAborted]) {
- queueMicrotask(() => {
- fireAProgressEvent('loadstart', fr)
- })
+function appendPath(url, pathToAppend) {
+ if (!pathToAppend) {
+ return url;
+ }
+ const parsedUrl = new URL(url);
+ let newPath = parsedUrl.pathname;
+ if (!newPath.endsWith("/")) {
+ newPath = `${newPath}/`;
+ }
+ if (pathToAppend.startsWith("/")) {
+ pathToAppend = pathToAppend.substring(1);
+ }
+ const searchStart = pathToAppend.indexOf("?");
+ if (searchStart !== -1) {
+ const path = pathToAppend.substring(0, searchStart);
+ const search = pathToAppend.substring(searchStart + 1);
+ newPath = newPath + path;
+ if (search) {
+ parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;
}
+ }
+ else {
+ newPath = newPath + pathToAppend;
+ }
+ parsedUrl.pathname = newPath;
+ return parsedUrl.toString();
+}
+function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
+ var _a;
+ const result = new Map();
+ const sequenceParams = new Set();
+ if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) {
+ for (const queryParameter of operationSpec.queryParameters) {
+ if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
+ sequenceParams.add(queryParameter.mapper.serializedName);
+ }
+ let queryParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, queryParameter, fallbackObject);
+ if ((queryParameterValue !== undefined && queryParameterValue !== null) ||
+ queryParameter.mapper.required) {
+ queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter));
+ const delimiter = queryParameter.collectionFormat
+ ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]
+ : "";
+ if (Array.isArray(queryParameterValue)) {
+ // replace null and undefined
+ queryParameterValue = queryParameterValue.map((item) => {
+ if (item === null || item === undefined) {
+ return "";
+ }
+ return item;
+ });
+ }
+ if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) {
+ continue;
+ }
+ else if (Array.isArray(queryParameterValue) &&
+ (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) {
+ queryParameterValue = queryParameterValue.join(delimiter);
+ }
+ if (!queryParameter.skipEncoding) {
+ if (Array.isArray(queryParameterValue)) {
+ queryParameterValue = queryParameterValue.map((item) => {
+ return encodeURIComponent(item);
+ });
+ }
+ else {
+ queryParameterValue = encodeURIComponent(queryParameterValue);
+ }
+ }
+ // Join pipes and CSV *after* encoding, or the server will be upset.
+ if (Array.isArray(queryParameterValue) &&
+ (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) {
+ queryParameterValue = queryParameterValue.join(delimiter);
+ }
+ result.set(queryParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter), queryParameterValue);
+ }
+ }
+ }
+ return {
+ queryParams: result,
+ sequenceParams,
+ };
+}
+function simpleParseQueryParams(queryString) {
+ const result = new Map();
+ if (!queryString || queryString[0] !== "?") {
+ return result;
+ }
+ // remove the leading ?
+ queryString = queryString.slice(1);
+ const pairs = queryString.split("&");
+ for (const pair of pairs) {
+ const [name, value] = pair.split("=", 2);
+ const existingValue = result.get(name);
+ if (existingValue) {
+ if (Array.isArray(existingValue)) {
+ existingValue.push(value);
+ }
+ else {
+ result.set(name, [existingValue, value]);
+ }
+ }
+ else {
+ result.set(name, value);
+ }
+ }
+ return result;
+}
+/** @internal */
+function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) {
+ if (queryParams.size === 0) {
+ return url;
+ }
+ const parsedUrl = new URL(url);
+ // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which
+ // can change their meaning to the server, such as in the case of a SAS signature.
+ // To avoid accidentally un-encoding a query param, we parse the key/values ourselves
+ const combinedParams = simpleParseQueryParams(parsedUrl.search);
+ for (const [name, value] of queryParams) {
+ const existingValue = combinedParams.get(name);
+ if (Array.isArray(existingValue)) {
+ if (Array.isArray(value)) {
+ existingValue.push(...value);
+ const valueSet = new Set(existingValue);
+ combinedParams.set(name, Array.from(valueSet));
+ }
+ else {
+ existingValue.push(value);
+ }
+ }
+ else if (existingValue) {
+ if (Array.isArray(value)) {
+ value.unshift(existingValue);
+ }
+ else if (sequenceParams.has(name)) {
+ combinedParams.set(name, [existingValue, value]);
+ }
+ if (!noOverwrite) {
+ combinedParams.set(name, value);
+ }
+ }
+ else {
+ combinedParams.set(name, value);
+ }
+ }
+ const searchPieces = [];
+ for (const [name, value] of combinedParams) {
+ if (typeof value === "string") {
+ searchPieces.push(`${name}=${value}`);
+ }
+ else if (Array.isArray(value)) {
+ // QUIRK: If we get an array of values, include multiple key/value pairs
+ for (const subValue of value) {
+ searchPieces.push(`${name}=${subValue}`);
+ }
+ }
+ else {
+ searchPieces.push(`${name}=${value}`);
+ }
+ }
+ // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.
+ parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
+ return parsedUrl.toString();
+}
+exports.appendQueryParams = appendQueryParams;
+//# sourceMappingURL=urlHelpers.js.map
- // 3. Set isFirstChunk to false.
- isFirstChunk = false
-
- // 4. If chunkPromise is fulfilled with an object whose
- // done property is false and whose value property is
- // a Uint8Array object, run these steps:
- if (!done && types.isUint8Array(value)) {
- // 1. Let bs be the byte sequence represented by the
- // Uint8Array object.
-
- // 2. Append bs to bytes.
- bytes.push(value)
-
- // 3. If roughly 50ms have passed since these steps
- // were last invoked, queue a task to fire a
- // progress event called progress at fr.
- if (
- (
- fr[kLastProgressEventFired] === undefined ||
- Date.now() - fr[kLastProgressEventFired] >= 50
- ) &&
- !fr[kAborted]
- ) {
- fr[kLastProgressEventFired] = Date.now()
- queueMicrotask(() => {
- fireAProgressEvent('progress', fr)
- })
- }
-
- // 4. Set chunkPromise to the result of reading a
- // chunk from stream with reader.
- chunkPromise = reader.read()
- } else if (done) {
- // 5. Otherwise, if chunkPromise is fulfilled with an
- // object whose done property is true, queue a task
- // to run the following steps and abort this algorithm:
- queueMicrotask(() => {
- // 1. Set fr’s state to "done".
- fr[kState] = 'done'
-
- // 2. Let result be the result of package data given
- // bytes, type, blob’s type, and encodingName.
- try {
- const result = packageData(bytes, type, blob.type, encodingName)
+/***/ }),
- // 4. Else:
+/***/ 7805:
+/***/ ((__unused_webpack_module, exports) => {
- if (fr[kAborted]) {
- return
- }
- // 1. Set fr’s result to result.
- fr[kResult] = result
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.flattenResponse = exports.isValidUuid = exports.isDuration = exports.isPrimitiveBody = void 0;
+/**
+ * A type guard for a primitive response body.
+ * @param value - Value to test
+ *
+ * @internal
+ */
+function isPrimitiveBody(value, mapperTypeName) {
+ return (mapperTypeName !== "Composite" &&
+ mapperTypeName !== "Dictionary" &&
+ (typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean" ||
+ (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !==
+ null ||
+ value === undefined ||
+ value === null));
+}
+exports.isPrimitiveBody = isPrimitiveBody;
+const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
+/**
+ * Returns true if the given string is in ISO 8601 format.
+ * @param value - The value to be validated for ISO 8601 duration format.
+ * @internal
+ */
+function isDuration(value) {
+ return validateISODuration.test(value);
+}
+exports.isDuration = isDuration;
+const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
+/**
+ * Returns true if the provided uuid is valid.
+ *
+ * @param uuid - The uuid that needs to be validated.
+ *
+ * @internal
+ */
+function isValidUuid(uuid) {
+ return validUuidRegex.test(uuid);
+}
+exports.isValidUuid = isValidUuid;
+/**
+ * Maps the response as follows:
+ * - wraps the response body if needed (typically if its type is primitive).
+ * - returns null if the combination of the headers and the body is empty.
+ * - otherwise, returns the combination of the headers and the body.
+ *
+ * @param responseObject - a representation of the parsed response
+ * @returns the response that will be returned to the user which can be null and/or wrapped
+ *
+ * @internal
+ */
+function handleNullableResponseAndWrappableBody(responseObject) {
+ const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body);
+ if (responseObject.hasNullableType &&
+ Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
+ return responseObject.shouldWrapBody ? { body: null } : null;
+ }
+ else {
+ return responseObject.shouldWrapBody
+ ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody;
+ }
+}
+/**
+ * Take a `FullOperationResponse` and turn it into a flat
+ * response object to hand back to the consumer.
+ * @param fullResponse - The processed response from the operation request
+ * @param responseSpec - The response map from the OperationSpec
+ *
+ * @internal
+ */
+function flattenResponse(fullResponse, responseSpec) {
+ var _a, _b;
+ const parsedHeaders = fullResponse.parsedHeaders;
+ // head methods never have a body, but we return a boolean set to body property
+ // to indicate presence/absence of the resource
+ if (fullResponse.request.method === "HEAD") {
+ return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody });
+ }
+ const bodyMapper = responseSpec && responseSpec.bodyMapper;
+ const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable);
+ const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name;
+ /** If the body is asked for, we look at the expected body type to handle it */
+ if (expectedBodyTypeName === "Stream") {
+ return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody });
+ }
+ const modelProperties = (expectedBodyTypeName === "Composite" &&
+ bodyMapper.type.modelProperties) ||
+ {};
+ const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === "");
+ if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
+ const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : [];
+ for (const key of Object.keys(modelProperties)) {
+ if (modelProperties[key].serializedName) {
+ arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key];
+ }
+ }
+ if (parsedHeaders) {
+ for (const key of Object.keys(parsedHeaders)) {
+ arrayResponse[key] = parsedHeaders[key];
+ }
+ }
+ return isNullable &&
+ !fullResponse.parsedBody &&
+ !parsedHeaders &&
+ Object.getOwnPropertyNames(modelProperties).length === 0
+ ? null
+ : arrayResponse;
+ }
+ return handleNullableResponseAndWrappableBody({
+ body: fullResponse.parsedBody,
+ headers: parsedHeaders,
+ hasNullableType: isNullable,
+ shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),
+ });
+}
+exports.flattenResponse = flattenResponse;
+//# sourceMappingURL=utils.js.map
- // 2. Fire a progress event called load at the fr.
- fireAProgressEvent('load', fr)
- } catch (error) {
- // 3. If package data threw an exception error:
+/***/ }),
- // 1. Set fr’s error to error.
- fr[kError] = error
+/***/ 39448:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. Fire a progress event called error at fr.
- fireAProgressEvent('error', fr)
- }
- // 5. If fr’s state is not "loading", fire a progress
- // event called loadend at the fr.
- if (fr[kState] !== 'loading') {
- fireAProgressEvent('loadend', fr)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ExtendedServiceClient = void 0;
+const disableKeepAlivePolicy_js_1 = __nccwpck_require__(56531);
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+const core_client_1 = __nccwpck_require__(6868);
+const response_js_1 = __nccwpck_require__(79093);
+/**
+ * Client to provide compatability between core V1 & V2.
+ */
+class ExtendedServiceClient extends core_client_1.ServiceClient {
+ constructor(options) {
+ var _a, _b;
+ super(options);
+ if (((_a = options.keepAliveOptions) === null || _a === void 0 ? void 0 : _a.enable) === false &&
+ !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) {
+ this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)());
+ }
+ if (((_b = options.redirectOptions) === null || _b === void 0 ? void 0 : _b.handleRedirects) === false) {
+ this.pipeline.removePolicy({
+ name: core_rest_pipeline_1.redirectPolicyName,
+ });
+ }
+ }
+ /**
+ * Compatible send operation request function.
+ *
+ * @param operationArguments - Operation arguments
+ * @param operationSpec - Operation Spec
+ * @returns
+ */
+ async sendOperationRequest(operationArguments, operationSpec) {
+ var _a;
+ const userProvidedCallBack = (_a = operationArguments === null || operationArguments === void 0 ? void 0 : operationArguments.options) === null || _a === void 0 ? void 0 : _a.onResponse;
+ let lastResponse;
+ function onResponse(rawResponse, flatResponse, error) {
+ lastResponse = rawResponse;
+ if (userProvidedCallBack) {
+ userProvidedCallBack(rawResponse, flatResponse, error);
}
- })
-
- break
}
- } catch (error) {
- if (fr[kAborted]) {
- return
+ operationArguments.options = Object.assign(Object.assign({}, operationArguments.options), { onResponse });
+ const result = await super.sendOperationRequest(operationArguments, operationSpec);
+ if (lastResponse) {
+ Object.defineProperty(result, "_response", {
+ value: (0, response_js_1.toCompatResponse)(lastResponse),
+ });
}
+ return result;
+ }
+}
+exports.ExtendedServiceClient = ExtendedServiceClient;
+//# sourceMappingURL=extendedClient.js.map
- // 6. Otherwise, if chunkPromise is rejected with an
- // error error, queue a task to run the following
- // steps and abort this algorithm:
- queueMicrotask(() => {
- // 1. Set fr’s state to "done".
- fr[kState] = 'done'
-
- // 2. Set fr’s error to error.
- fr[kError] = error
-
- // 3. Fire a progress event called error at fr.
- fireAProgressEvent('error', fr)
+/***/ }),
- // 4. If fr’s state is not "loading", fire a progress
- // event called loadend at fr.
- if (fr[kState] !== 'loading') {
- fireAProgressEvent('loadend', fr)
- }
- })
+/***/ 22842:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- break
- }
- }
- })()
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.convertHttpClient = void 0;
+const response_js_1 = __nccwpck_require__(79093);
+const util_js_1 = __nccwpck_require__(46);
/**
- * @see https://w3c.github.io/FileAPI/#fire-a-progress-event
- * @see https://dom.spec.whatwg.org/#concept-event-fire
- * @param {string} e The name of the event
- * @param {import('./filereader').FileReader} reader
+ * Converts a RequestPolicy based HttpClient to a PipelineRequest based HttpClient.
+ * @param requestPolicyClient - A HttpClient compatible with core-http
+ * @returns A HttpClient compatible with core-rest-pipeline
*/
-function fireAProgressEvent (e, reader) {
- // The progress event e does not bubble. e.bubbles must be false
- // The progress event e is NOT cancelable. e.cancelable must be false
- const event = new ProgressEvent(e, {
- bubbles: false,
- cancelable: false
- })
-
- reader.dispatchEvent(event)
+function convertHttpClient(requestPolicyClient) {
+ return {
+ sendRequest: async (request) => {
+ const response = await requestPolicyClient.sendRequest((0, util_js_1.toWebResourceLike)(request, { createProxy: true }));
+ return (0, response_js_1.toPipelineResponse)(response);
+ },
+ };
}
+exports.convertHttpClient = convertHttpClient;
+//# sourceMappingURL=httpClientAdapter.js.map
-/**
- * @see https://w3c.github.io/FileAPI/#blob-package-data
- * @param {Uint8Array[]} bytes
- * @param {string} type
- * @param {string?} mimeType
- * @param {string?} encodingName
- */
-function packageData (bytes, type, mimeType, encodingName) {
- // 1. A Blob has an associated package data algorithm, given
- // bytes, a type, a optional mimeType, and a optional
- // encodingName, which switches on type and runs the
- // associated steps:
+/***/ }),
- switch (type) {
- case 'DataURL': {
- // 1. Return bytes as a DataURL [RFC2397] subject to
- // the considerations below:
- // * Use mimeType as part of the Data URL if it is
- // available in keeping with the Data URL
- // specification [RFC2397].
- // * If mimeType is not available return a Data URL
- // without a media-type. [RFC2397].
+/***/ 14508:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // https://datatracker.ietf.org/doc/html/rfc2397#section-3
- // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
- // mediatype := [ type "/" subtype ] *( ";" parameter )
- // data := *urlchar
- // parameter := attribute "=" value
- let dataURL = 'data:'
- const parsed = parseMIMEType(mimeType || 'application/octet-stream')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toHttpHeadersLike = exports.convertHttpClient = exports.disableKeepAlivePolicyName = exports.HttpPipelineLogLevel = exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.ExtendedServiceClient = void 0;
+/**
+ * A Shim Library that provides compatibility between Core V1 & V2 Packages.
+ *
+ * @packageDocumentation
+ */
+var extendedClient_js_1 = __nccwpck_require__(39448);
+Object.defineProperty(exports, "ExtendedServiceClient", ({ enumerable: true, get: function () { return extendedClient_js_1.ExtendedServiceClient; } }));
+var requestPolicyFactoryPolicy_js_1 = __nccwpck_require__(15190);
+Object.defineProperty(exports, "requestPolicyFactoryPolicyName", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.requestPolicyFactoryPolicyName; } }));
+Object.defineProperty(exports, "createRequestPolicyFactoryPolicy", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.createRequestPolicyFactoryPolicy; } }));
+Object.defineProperty(exports, "HttpPipelineLogLevel", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.HttpPipelineLogLevel; } }));
+var disableKeepAlivePolicy_js_1 = __nccwpck_require__(56531);
+Object.defineProperty(exports, "disableKeepAlivePolicyName", ({ enumerable: true, get: function () { return disableKeepAlivePolicy_js_1.disableKeepAlivePolicyName; } }));
+var httpClientAdapter_js_1 = __nccwpck_require__(22842);
+Object.defineProperty(exports, "convertHttpClient", ({ enumerable: true, get: function () { return httpClientAdapter_js_1.convertHttpClient; } }));
+var util_js_1 = __nccwpck_require__(46);
+Object.defineProperty(exports, "toHttpHeadersLike", ({ enumerable: true, get: function () { return util_js_1.toHttpHeadersLike; } }));
+//# sourceMappingURL=index.js.map
- if (parsed !== 'failure') {
- dataURL += serializeAMimeType(parsed)
- }
+/***/ }),
- dataURL += ';base64,'
+/***/ 56531:
+/***/ ((__unused_webpack_module, exports) => {
- const decoder = new StringDecoder('latin1')
- for (const chunk of bytes) {
- dataURL += btoa(decoder.write(chunk))
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.pipelineContainsDisableKeepAlivePolicy = exports.createDisableKeepAlivePolicy = exports.disableKeepAlivePolicyName = void 0;
+exports.disableKeepAlivePolicyName = "DisableKeepAlivePolicy";
+function createDisableKeepAlivePolicy() {
+ return {
+ name: exports.disableKeepAlivePolicyName,
+ async sendRequest(request, next) {
+ request.disableKeepAlive = true;
+ return next(request);
+ },
+ };
+}
+exports.createDisableKeepAlivePolicy = createDisableKeepAlivePolicy;
+/**
+ * @internal
+ */
+function pipelineContainsDisableKeepAlivePolicy(pipeline) {
+ return pipeline.getOrderedPolicies().some((policy) => policy.name === exports.disableKeepAlivePolicyName);
+}
+exports.pipelineContainsDisableKeepAlivePolicy = pipelineContainsDisableKeepAlivePolicy;
+//# sourceMappingURL=disableKeepAlivePolicy.js.map
- dataURL += btoa(decoder.end())
+/***/ }),
- return dataURL
- }
- case 'Text': {
- // 1. Let encoding be failure
- let encoding = 'failure'
+/***/ 15190:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. If the encodingName is present, set encoding to the
- // result of getting an encoding from encodingName.
- if (encodingName) {
- encoding = getEncoding(encodingName)
- }
- // 3. If encoding is failure, and mimeType is present:
- if (encoding === 'failure' && mimeType) {
- // 1. Let type be the result of parse a MIME type
- // given mimeType.
- const type = parseMIMEType(mimeType)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.HttpPipelineLogLevel = void 0;
+const util_js_1 = __nccwpck_require__(46);
+const response_js_1 = __nccwpck_require__(79093);
+/**
+ * An enum for compatibility with RequestPolicy
+ */
+var HttpPipelineLogLevel;
+(function (HttpPipelineLogLevel) {
+ HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
+})(HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = HttpPipelineLogLevel = {}));
+const mockRequestPolicyOptions = {
+ log(_logLevel, _message) {
+ /* do nothing */
+ },
+ shouldLog(_logLevel) {
+ return false;
+ },
+};
+/**
+ * The name of the RequestPolicyFactoryPolicy
+ */
+exports.requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy";
+/**
+ * A policy that wraps policies written for core-http.
+ * @param factories - An array of `RequestPolicyFactory` objects from a core-http pipeline
+ */
+function createRequestPolicyFactoryPolicy(factories) {
+ const orderedFactories = factories.slice().reverse();
+ return {
+ name: exports.requestPolicyFactoryPolicyName,
+ async sendRequest(request, next) {
+ let httpPipeline = {
+ async sendRequest(httpRequest) {
+ const response = await next((0, util_js_1.toPipelineRequest)(httpRequest));
+ return (0, response_js_1.toCompatResponse)(response, { createProxy: true });
+ },
+ };
+ for (const factory of orderedFactories) {
+ httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions);
+ }
+ const webResourceLike = (0, util_js_1.toWebResourceLike)(request, { createProxy: true });
+ const response = await httpPipeline.sendRequest(webResourceLike);
+ return (0, response_js_1.toPipelineResponse)(response);
+ },
+ };
+}
+exports.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy;
+//# sourceMappingURL=requestPolicyFactoryPolicy.js.map
- // 2. If type is not failure, set encoding to the result
- // of getting an encoding from type’s parameters["charset"].
- if (type !== 'failure') {
- encoding = getEncoding(type.parameters.get('charset'))
- }
- }
+/***/ }),
- // 4. If encoding is failure, then set encoding to UTF-8.
- if (encoding === 'failure') {
- encoding = 'UTF-8'
- }
+/***/ 79093:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5. Decode bytes using fallback encoding encoding, and
- // return the result.
- return decode(bytes, encoding)
- }
- case 'ArrayBuffer': {
- // Return a new ArrayBuffer whose contents are bytes.
- const sequence = combineByteSequences(bytes)
- return sequence.buffer
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toPipelineResponse = exports.toCompatResponse = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+const util_js_1 = __nccwpck_require__(46);
+const originalResponse = Symbol("Original FullOperationResponse");
+/**
+ * A helper to convert response objects from the new pipeline back to the old one.
+ * @param response - A response object from core-client.
+ * @returns A response compatible with `HttpOperationResponse` from core-http.
+ */
+function toCompatResponse(response, options) {
+ let request = (0, util_js_1.toWebResourceLike)(response.request);
+ let headers = (0, util_js_1.toHttpHeadersLike)(response.headers);
+ if (options === null || options === void 0 ? void 0 : options.createProxy) {
+ return new Proxy(response, {
+ get(target, prop, receiver) {
+ if (prop === "headers") {
+ return headers;
+ }
+ else if (prop === "request") {
+ return request;
+ }
+ else if (prop === originalResponse) {
+ return response;
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ set(target, prop, value, receiver) {
+ if (prop === "headers") {
+ headers = value;
+ }
+ else if (prop === "request") {
+ request = value;
+ }
+ return Reflect.set(target, prop, value, receiver);
+ },
+ });
}
- case 'BinaryString': {
- // Return bytes as a binary string, in which every byte
- // is represented by a code unit of equal value [0..255].
- let binaryString = ''
+ else {
+ return Object.assign(Object.assign({}, response), { request,
+ headers });
+ }
+}
+exports.toCompatResponse = toCompatResponse;
+/**
+ * A helper to convert back to a PipelineResponse
+ * @param compatResponse - A response compatible with `HttpOperationResponse` from core-http.
+ */
+function toPipelineResponse(compatResponse) {
+ const extendedCompatResponse = compatResponse;
+ const response = extendedCompatResponse[originalResponse];
+ const headers = (0, core_rest_pipeline_1.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true }));
+ if (response) {
+ response.headers = headers;
+ return response;
+ }
+ else {
+ return Object.assign(Object.assign({}, compatResponse), { headers, request: (0, util_js_1.toPipelineRequest)(compatResponse.request) });
+ }
+}
+exports.toPipelineResponse = toPipelineResponse;
+//# sourceMappingURL=response.js.map
- const decoder = new StringDecoder('latin1')
+/***/ }),
- for (const chunk of bytes) {
- binaryString += decoder.write(chunk)
- }
+/***/ 46:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- binaryString += decoder.end()
- return binaryString
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.HttpHeaders = exports.toHttpHeadersLike = exports.toWebResourceLike = exports.toPipelineRequest = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+// We use a custom symbol to cache a reference to the original request without
+// exposing it on the public interface.
+const originalRequestSymbol = Symbol("Original PipelineRequest");
+// Symbol.for() will return the same symbol if it's already been created
+// This particular one is used in core-client to handle the case of when a request is
+// cloned but we need to retrieve the OperationSpec and OperationArguments from the
+// original request.
+const originalClientRequestSymbol = Symbol.for("@azure/core-client original request");
+function toPipelineRequest(webResource, options = {}) {
+ const compatWebResource = webResource;
+ const request = compatWebResource[originalRequestSymbol];
+ const headers = (0, core_rest_pipeline_1.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true }));
+ if (request) {
+ request.headers = headers;
+ return request;
+ }
+ else {
+ const newRequest = (0, core_rest_pipeline_1.createPipelineRequest)({
+ url: webResource.url,
+ method: webResource.method,
+ headers,
+ withCredentials: webResource.withCredentials,
+ timeout: webResource.timeout,
+ requestId: webResource.requestId,
+ abortSignal: webResource.abortSignal,
+ body: webResource.body,
+ formData: webResource.formData,
+ disableKeepAlive: !!webResource.keepAlive,
+ onDownloadProgress: webResource.onDownloadProgress,
+ onUploadProgress: webResource.onUploadProgress,
+ proxySettings: webResource.proxySettings,
+ streamResponseStatusCodes: webResource.streamResponseStatusCodes,
+ });
+ if (options.originalRequest) {
+ newRequest[originalClientRequestSymbol] =
+ options.originalRequest;
+ }
+ return newRequest;
}
- }
}
-
+exports.toPipelineRequest = toPipelineRequest;
+function toWebResourceLike(request, options) {
+ var _a;
+ const originalRequest = (_a = options === null || options === void 0 ? void 0 : options.originalRequest) !== null && _a !== void 0 ? _a : request;
+ const webResource = {
+ url: request.url,
+ method: request.method,
+ headers: toHttpHeadersLike(request.headers),
+ withCredentials: request.withCredentials,
+ timeout: request.timeout,
+ requestId: request.headers.get("x-ms-client-request-id") || request.requestId,
+ abortSignal: request.abortSignal,
+ body: request.body,
+ formData: request.formData,
+ keepAlive: !!request.disableKeepAlive,
+ onDownloadProgress: request.onDownloadProgress,
+ onUploadProgress: request.onUploadProgress,
+ proxySettings: request.proxySettings,
+ streamResponseStatusCodes: request.streamResponseStatusCodes,
+ clone() {
+ throw new Error("Cannot clone a non-proxied WebResourceLike");
+ },
+ prepare() {
+ throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat");
+ },
+ validateRequestProperties() {
+ /** do nothing */
+ },
+ };
+ if (options === null || options === void 0 ? void 0 : options.createProxy) {
+ return new Proxy(webResource, {
+ get(target, prop, receiver) {
+ if (prop === originalRequestSymbol) {
+ return request;
+ }
+ else if (prop === "clone") {
+ return () => {
+ return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), {
+ createProxy: true,
+ originalRequest,
+ });
+ };
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ set(target, prop, value, receiver) {
+ if (prop === "keepAlive") {
+ request.disableKeepAlive = !value;
+ }
+ const passThroughProps = [
+ "url",
+ "method",
+ "withCredentials",
+ "timeout",
+ "requestId",
+ "abortSignal",
+ "body",
+ "formData",
+ "onDownloadProgress",
+ "onUploadProgress",
+ "proxySettings",
+ "streamResponseStatusCodes",
+ ];
+ if (typeof prop === "string" && passThroughProps.includes(prop)) {
+ request[prop] = value;
+ }
+ return Reflect.set(target, prop, value, receiver);
+ },
+ });
+ }
+ else {
+ return webResource;
+ }
+}
+exports.toWebResourceLike = toWebResourceLike;
/**
- * @see https://encoding.spec.whatwg.org/#decode
- * @param {Uint8Array[]} ioQueue
- * @param {string} encoding
+ * Converts HttpHeaders from core-rest-pipeline to look like
+ * HttpHeaders from core-http.
+ * @param headers - HttpHeaders from core-rest-pipeline
+ * @returns HttpHeaders as they looked in core-http
*/
-function decode (ioQueue, encoding) {
- const bytes = combineByteSequences(ioQueue)
-
- // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
- const BOMEncoding = BOMSniffing(bytes)
-
- let slice = 0
-
- // 2. If BOMEncoding is non-null:
- if (BOMEncoding !== null) {
- // 1. Set encoding to BOMEncoding.
- encoding = BOMEncoding
-
- // 2. Read three bytes from ioQueue, if BOMEncoding is
- // UTF-8; otherwise read two bytes.
- // (Do nothing with those bytes.)
- slice = BOMEncoding === 'UTF-8' ? 3 : 2
- }
-
- // 3. Process a queue with an instance of encoding’s
- // decoder, ioQueue, output, and "replacement".
-
- // 4. Return output.
-
- const sliced = bytes.slice(slice)
- return new TextDecoder(encoding).decode(sliced)
+function toHttpHeadersLike(headers) {
+ return new HttpHeaders(headers.toJSON({ preserveCase: true }));
}
-
+exports.toHttpHeadersLike = toHttpHeadersLike;
/**
- * @see https://encoding.spec.whatwg.org/#bom-sniff
- * @param {Uint8Array} ioQueue
+ * A collection of HttpHeaders that can be sent with a HTTP request.
*/
-function BOMSniffing (ioQueue) {
- // 1. Let BOM be the result of peeking 3 bytes from ioQueue,
- // converted to a byte sequence.
- const [a, b, c] = ioQueue
-
- // 2. For each of the rows in the table below, starting with
- // the first one and going down, if BOM starts with the
- // bytes given in the first column, then return the
- // encoding given in the cell in the second column of that
- // row. Otherwise, return null.
- if (a === 0xEF && b === 0xBB && c === 0xBF) {
- return 'UTF-8'
- } else if (a === 0xFE && b === 0xFF) {
- return 'UTF-16BE'
- } else if (a === 0xFF && b === 0xFE) {
- return 'UTF-16LE'
- }
-
- return null
+function getHeaderKey(headerName) {
+ return headerName.toLowerCase();
}
-
/**
- * @param {Uint8Array[]} sequences
+ * A collection of HTTP header key/value pairs.
*/
-function combineByteSequences (sequences) {
- const size = sequences.reduce((a, b) => {
- return a + b.byteLength
- }, 0)
-
- let offset = 0
-
- return sequences.reduce((a, b) => {
- a.set(b, offset)
- offset += b.byteLength
- return a
- }, new Uint8Array(size))
-}
-
-module.exports = {
- staticPropertyDescriptors,
- readOperation,
- fireAProgressEvent
+class HttpHeaders {
+ constructor(rawHeaders) {
+ this._headersMap = {};
+ if (rawHeaders) {
+ for (const headerName in rawHeaders) {
+ this.set(headerName, rawHeaders[headerName]);
+ }
+ }
+ }
+ /**
+ * Set a header in this collection with the provided name and value. The name is
+ * case-insensitive.
+ * @param headerName - The name of the header to set. This value is case-insensitive.
+ * @param headerValue - The value of the header to set.
+ */
+ set(headerName, headerValue) {
+ this._headersMap[getHeaderKey(headerName)] = {
+ name: headerName,
+ value: headerValue.toString(),
+ };
+ }
+ /**
+ * Get the header value for the provided header name, or undefined if no header exists in this
+ * collection with the provided name.
+ * @param headerName - The name of the header.
+ */
+ get(headerName) {
+ const header = this._headersMap[getHeaderKey(headerName)];
+ return !header ? undefined : header.value;
+ }
+ /**
+ * Get whether or not this header collection contains a header entry for the provided header name.
+ */
+ contains(headerName) {
+ return !!this._headersMap[getHeaderKey(headerName)];
+ }
+ /**
+ * Remove the header with the provided headerName. Return whether or not the header existed and
+ * was removed.
+ * @param headerName - The name of the header to remove.
+ */
+ remove(headerName) {
+ const result = this.contains(headerName);
+ delete this._headersMap[getHeaderKey(headerName)];
+ return result;
+ }
+ /**
+ * Get the headers that are contained this collection as an object.
+ */
+ rawHeaders() {
+ return this.toJson({ preserveCase: true });
+ }
+ /**
+ * Get the headers that are contained in this collection as an array.
+ */
+ headersArray() {
+ const headers = [];
+ for (const headerKey in this._headersMap) {
+ headers.push(this._headersMap[headerKey]);
+ }
+ return headers;
+ }
+ /**
+ * Get the header names that are contained in this collection.
+ */
+ headerNames() {
+ const headerNames = [];
+ const headers = this.headersArray();
+ for (let i = 0; i < headers.length; ++i) {
+ headerNames.push(headers[i].name);
+ }
+ return headerNames;
+ }
+ /**
+ * Get the header values that are contained in this collection.
+ */
+ headerValues() {
+ const headerValues = [];
+ const headers = this.headersArray();
+ for (let i = 0; i < headers.length; ++i) {
+ headerValues.push(headers[i].value);
+ }
+ return headerValues;
+ }
+ /**
+ * Get the JSON object representation of this HTTP header collection.
+ */
+ toJson(options = {}) {
+ const result = {};
+ if (options.preserveCase) {
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ result[header.name] = header.value;
+ }
+ }
+ else {
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ result[getHeaderKey(header.name)] = header.value;
+ }
+ }
+ return result;
+ }
+ /**
+ * Get the string representation of this HTTP header collection.
+ */
+ toString() {
+ return JSON.stringify(this.toJson({ preserveCase: true }));
+ }
+ /**
+ * Create a deep clone/copy of this HttpHeaders collection.
+ */
+ clone() {
+ const resultPreservingCasing = {};
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ resultPreservingCasing[header.name] = header.value;
+ }
+ return new HttpHeaders(resultPreservingCasing);
+ }
}
-
+exports.HttpHeaders = HttpHeaders;
+//# sourceMappingURL=util.js.map
/***/ }),
-/***/ 61481:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 27826:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// We include a version number for the Dispatcher API. In case of breaking changes,
-// this version number must be increased to avoid conflicts.
-const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-const Agent = __nccwpck_require__(92121)
-if (getGlobalDispatcher() === undefined) {
- setGlobalDispatcher(new Agent())
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.pollHttpOperation = exports.isOperationError = exports.getResourceLocation = exports.getOperationStatus = exports.getOperationLocation = exports.initHttpOperation = exports.getStatusFromInitialResponse = exports.getErrorFromResponse = exports.parseRetryAfter = exports.inferLroMode = void 0;
+const operation_js_1 = __nccwpck_require__(26588);
+const logger_js_1 = __nccwpck_require__(80692);
+function getOperationLocationPollingUrl(inputs) {
+ const { azureAsyncOperation, operationLocation } = inputs;
+ return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
}
-
-function setGlobalDispatcher (agent) {
- if (!agent || typeof agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument agent must implement Agent')
- }
- Object.defineProperty(globalThis, globalDispatcher, {
- value: agent,
- writable: true,
- enumerable: false,
- configurable: false
- })
+function getLocationHeader(rawResponse) {
+ return rawResponse.headers["location"];
}
-
-function getGlobalDispatcher () {
- return globalThis[globalDispatcher]
+function getOperationLocationHeader(rawResponse) {
+ return rawResponse.headers["operation-location"];
}
-
-module.exports = {
- setGlobalDispatcher,
- getGlobalDispatcher
+function getAzureAsyncOperationHeader(rawResponse) {
+ return rawResponse.headers["azure-asyncoperation"];
}
-
-
-/***/ }),
-
-/***/ 41468:
-/***/ ((module) => {
-
-
-
-module.exports = class DecoratorHandler {
- constructor (handler) {
- this.handler = handler
- }
-
- onConnect (...args) {
- return this.handler.onConnect(...args)
- }
-
- onError (...args) {
- return this.handler.onError(...args)
- }
-
- onUpgrade (...args) {
- return this.handler.onUpgrade(...args)
- }
-
- onHeaders (...args) {
- return this.handler.onHeaders(...args)
- }
-
- onData (...args) {
- return this.handler.onData(...args)
- }
-
- onComplete (...args) {
- return this.handler.onComplete(...args)
- }
-
- onBodySent (...args) {
- return this.handler.onBodySent(...args)
- }
+function findResourceLocation(inputs) {
+ var _a;
+ const { location, requestMethod, requestPath, resourceLocationConfig } = inputs;
+ switch (requestMethod) {
+ case "PUT": {
+ return requestPath;
+ }
+ case "DELETE": {
+ return undefined;
+ }
+ case "PATCH": {
+ return (_a = getDefault()) !== null && _a !== void 0 ? _a : requestPath;
+ }
+ default: {
+ return getDefault();
+ }
+ }
+ function getDefault() {
+ switch (resourceLocationConfig) {
+ case "azure-async-operation": {
+ return undefined;
+ }
+ case "original-uri": {
+ return requestPath;
+ }
+ case "location":
+ default: {
+ return location;
+ }
+ }
+ }
}
-
-
-/***/ }),
-
-/***/ 8591:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const util = __nccwpck_require__(89500)
-const { kBodyUsed } = __nccwpck_require__(68031)
-const assert = __nccwpck_require__(42613)
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-const EE = __nccwpck_require__(24434)
-
-const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
-
-const kBody = Symbol('body')
-
-class BodyAsyncIterable {
- constructor (body) {
- this[kBody] = body
- this[kBodyUsed] = false
- }
-
- async * [Symbol.asyncIterator] () {
- assert(!this[kBodyUsed], 'disturbed')
- this[kBodyUsed] = true
- yield * this[kBody]
- }
+function inferLroMode(inputs) {
+ const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs;
+ const operationLocation = getOperationLocationHeader(rawResponse);
+ const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse);
+ const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation });
+ const location = getLocationHeader(rawResponse);
+ const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase();
+ if (pollingUrl !== undefined) {
+ return {
+ mode: "OperationLocation",
+ operationLocation: pollingUrl,
+ resourceLocation: findResourceLocation({
+ requestMethod: normalizedRequestMethod,
+ location,
+ requestPath,
+ resourceLocationConfig,
+ }),
+ };
+ }
+ else if (location !== undefined) {
+ return {
+ mode: "ResourceLocation",
+ operationLocation: location,
+ };
+ }
+ else if (normalizedRequestMethod === "PUT" && requestPath) {
+ return {
+ mode: "Body",
+ operationLocation: requestPath,
+ };
+ }
+ else {
+ return undefined;
+ }
}
-
-class RedirectHandler {
- constructor (dispatch, maxRedirections, opts, handler) {
- if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
+exports.inferLroMode = inferLroMode;
+function transformStatus(inputs) {
+ const { status, statusCode } = inputs;
+ if (typeof status !== "string" && status !== undefined) {
+ throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`);
}
-
- util.validateHandler(handler, opts.method, opts.upgrade)
-
- this.dispatch = dispatch
- this.location = null
- this.abort = null
- this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy
- this.maxRedirections = maxRedirections
- this.handler = handler
- this.history = []
-
- if (util.isStream(this.opts.body)) {
- // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
- // so that it can be dispatched again?
- // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
- if (util.bodyLength(this.opts.body) === 0) {
- this.opts.body
- .on('data', function () {
- assert(false)
- })
- }
-
- if (typeof this.opts.body.readableDidRead !== 'boolean') {
- this.opts.body[kBodyUsed] = false
- EE.prototype.on.call(this.opts.body, 'data', function () {
- this[kBodyUsed] = true
- })
- }
- } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {
- // TODO (fix): We can't access ReadableStream internal state
- // to determine whether or not it has been disturbed. This is just
- // a workaround.
- this.opts.body = new BodyAsyncIterable(this.opts.body)
- } else if (
- this.opts.body &&
- typeof this.opts.body !== 'string' &&
- !ArrayBuffer.isView(this.opts.body) &&
- util.isIterable(this.opts.body)
- ) {
- // TODO: Should we allow re-using iterable if !this.opts.idempotent
- // or through some other flag?
- this.opts.body = new BodyAsyncIterable(this.opts.body)
+ switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) {
+ case undefined:
+ return toOperationStatus(statusCode);
+ case "succeeded":
+ return "succeeded";
+ case "failed":
+ return "failed";
+ case "running":
+ case "accepted":
+ case "started":
+ case "canceling":
+ case "cancelling":
+ return "running";
+ case "canceled":
+ case "cancelled":
+ return "canceled";
+ default: {
+ logger_js_1.logger.verbose(`LRO: unrecognized operation status: ${status}`);
+ return status;
+ }
}
- }
-
- onConnect (abort) {
- this.abort = abort
- this.handler.onConnect(abort, { history: this.history })
- }
-
- onUpgrade (statusCode, headers, socket) {
- this.handler.onUpgrade(statusCode, headers, socket)
- }
-
- onError (error) {
- this.handler.onError(error)
- }
-
- onHeaders (statusCode, headers, resume, statusText) {
- this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)
- ? null
- : parseLocation(statusCode, headers)
-
- if (this.opts.origin) {
- this.history.push(new URL(this.opts.path, this.opts.origin))
+}
+function getStatus(rawResponse) {
+ var _a;
+ const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
+ return transformStatus({ status, statusCode: rawResponse.statusCode });
+}
+function getProvisioningState(rawResponse) {
+ var _a, _b;
+ const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
+ const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
+ return transformStatus({ status, statusCode: rawResponse.statusCode });
+}
+function toOperationStatus(statusCode) {
+ if (statusCode === 202) {
+ return "running";
}
-
- if (!this.location) {
- return this.handler.onHeaders(statusCode, headers, resume, statusText)
+ else if (statusCode < 300) {
+ return "succeeded";
}
-
- const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))
- const path = search ? `${pathname}${search}` : pathname
-
- // Remove headers referring to the original URL.
- // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.
- // https://tools.ietf.org/html/rfc7231#section-6.4
- this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)
- this.opts.path = path
- this.opts.origin = origin
- this.opts.maxRedirections = 0
- this.opts.query = null
-
- // https://tools.ietf.org/html/rfc7231#section-6.4.4
- // In case of HTTP 303, always replace method to be either HEAD or GET
- if (statusCode === 303 && this.opts.method !== 'HEAD') {
- this.opts.method = 'GET'
- this.opts.body = null
+ else {
+ return "failed";
}
- }
-
- onData (chunk) {
- if (this.location) {
- /*
- https://tools.ietf.org/html/rfc7231#section-6.4
-
- TLDR: undici always ignores 3xx response bodies.
-
- Redirection is used to serve the requested resource from another URL, so it is assumes that
- no body is generated (and thus can be ignored). Even though generating a body is not prohibited.
-
- For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually
- (which means it's optional and not mandated) contain just an hyperlink to the value of
- the Location response header, so the body can be ignored safely.
-
- For status 300, which is "Multiple Choices", the spec mentions both generating a Location
- response header AND a response body with the other possible location to follow.
- Since the spec explicitily chooses not to specify a format for such body and leave it to
- servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.
- */
- } else {
- return this.handler.onData(chunk)
+}
+function parseRetryAfter({ rawResponse }) {
+ const retryAfter = rawResponse.headers["retry-after"];
+ if (retryAfter !== undefined) {
+ // Retry-After header value is either in HTTP date format, or in seconds
+ const retryAfterInSeconds = parseInt(retryAfter);
+ return isNaN(retryAfterInSeconds)
+ ? calculatePollingIntervalFromDate(new Date(retryAfter))
+ : retryAfterInSeconds * 1000;
}
- }
-
- onComplete (trailers) {
- if (this.location) {
- /*
- https://tools.ietf.org/html/rfc7231#section-6.4
-
- TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections
- and neither are useful if present.
-
- See comment on onData method above for more detailed informations.
- */
-
- this.location = null
- this.abort = null
-
- this.dispatch(this.opts, this)
- } else {
- this.handler.onComplete(trailers)
+ return undefined;
+}
+exports.parseRetryAfter = parseRetryAfter;
+function getErrorFromResponse(response) {
+ const error = accessBodyProperty(response, "error");
+ if (!error) {
+ logger_js_1.logger.warning(`The long-running operation failed but there is no error property in the response's body`);
+ return;
}
- }
-
- onBodySent (chunk) {
- if (this.handler.onBodySent) {
- this.handler.onBodySent(chunk)
+ if (!error.code || !error.message) {
+ logger_js_1.logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`);
+ return;
}
- }
+ return error;
}
-
-function parseLocation (statusCode, headers) {
- if (redirectableStatusCodes.indexOf(statusCode) === -1) {
- return null
- }
-
- for (let i = 0; i < headers.length; i += 2) {
- if (headers[i].toString().toLowerCase() === 'location') {
- return headers[i + 1]
+exports.getErrorFromResponse = getErrorFromResponse;
+function calculatePollingIntervalFromDate(retryAfterDate) {
+ const timeNow = Math.floor(new Date().getTime());
+ const retryAfterTime = retryAfterDate.getTime();
+ if (timeNow < retryAfterTime) {
+ return retryAfterTime - timeNow;
}
- }
+ return undefined;
}
-
-// https://tools.ietf.org/html/rfc7231#section-6.4.4
-function shouldRemoveHeader (header, removeContent, unknownOrigin) {
- if (header.length === 4) {
- return util.headerNameToString(header) === 'host'
- }
- if (removeContent && util.headerNameToString(header).startsWith('content-')) {
- return true
- }
- if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
- const name = util.headerNameToString(header)
- return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'
- }
- return false
+function getStatusFromInitialResponse(inputs) {
+ const { response, state, operationLocation } = inputs;
+ function helper() {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case undefined:
+ return toOperationStatus(response.rawResponse.statusCode);
+ case "Body":
+ return getOperationStatus(response, state);
+ default:
+ return "running";
+ }
+ }
+ const status = helper();
+ return status === "running" && operationLocation === undefined ? "succeeded" : status;
}
-
-// https://tools.ietf.org/html/rfc7231#section-6.4
-function cleanRequestHeaders (headers, removeContent, unknownOrigin) {
- const ret = []
- if (Array.isArray(headers)) {
- for (let i = 0; i < headers.length; i += 2) {
- if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
- ret.push(headers[i], headers[i + 1])
- }
+exports.getStatusFromInitialResponse = getStatusFromInitialResponse;
+/**
+ * Initiates the long-running operation.
+ */
+async function initHttpOperation(inputs) {
+ const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs;
+ return (0, operation_js_1.initOperation)({
+ init: async () => {
+ const response = await lro.sendInitialRequest();
+ const config = inferLroMode({
+ rawResponse: response.rawResponse,
+ requestPath: lro.requestPath,
+ requestMethod: lro.requestMethod,
+ resourceLocationConfig,
+ });
+ return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+ },
+ stateProxy,
+ processResult: processResult
+ ? ({ flatResponse }, state) => processResult(flatResponse, state)
+ : ({ flatResponse }) => flatResponse,
+ getOperationStatus: getStatusFromInitialResponse,
+ setErrorAsResult,
+ });
+}
+exports.initHttpOperation = initHttpOperation;
+function getOperationLocation({ rawResponse }, state) {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case "OperationLocation": {
+ return getOperationLocationPollingUrl({
+ operationLocation: getOperationLocationHeader(rawResponse),
+ azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse),
+ });
+ }
+ case "ResourceLocation": {
+ return getLocationHeader(rawResponse);
+ }
+ case "Body":
+ default: {
+ return undefined;
+ }
}
- } else if (headers && typeof headers === 'object') {
- for (const key of Object.keys(headers)) {
- if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
- ret.push(key, headers[key])
- }
+}
+exports.getOperationLocation = getOperationLocation;
+function getOperationStatus({ rawResponse }, state) {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case "OperationLocation": {
+ return getStatus(rawResponse);
+ }
+ case "ResourceLocation": {
+ return toOperationStatus(rawResponse.statusCode);
+ }
+ case "Body": {
+ return getProvisioningState(rawResponse);
+ }
+ default:
+ throw new Error(`Internal error: Unexpected operation mode: ${mode}`);
}
- } else {
- assert(headers == null, 'headers must be an object or an array')
- }
- return ret
}
-
-module.exports = RedirectHandler
-
-
-/***/ }),
-
-/***/ 49569:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const assert = __nccwpck_require__(42613)
-
-const { kRetryHandlerDefaultRetry } = __nccwpck_require__(68031)
-const { RequestRetryError } = __nccwpck_require__(53959)
-const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(89500)
-
-function calculateRetryAfterHeader (retryAfter) {
- const current = Date.now()
- const diff = new Date(retryAfter).getTime() - current
-
- return diff
+exports.getOperationStatus = getOperationStatus;
+function accessBodyProperty({ flatResponse, rawResponse }, prop) {
+ var _a, _b;
+ return (_a = flatResponse === null || flatResponse === void 0 ? void 0 : flatResponse[prop]) !== null && _a !== void 0 ? _a : (_b = rawResponse.body) === null || _b === void 0 ? void 0 : _b[prop];
}
-
-class RetryHandler {
- constructor (opts, handlers) {
- const { retryOptions, ...dispatchOpts } = opts
- const {
- // Retry scoped
- retry: retryFn,
- maxRetries,
- maxTimeout,
- minTimeout,
- timeoutFactor,
- // Response scoped
- methods,
- errorCodes,
- retryAfter,
- statusCodes
- } = retryOptions ?? {}
-
- this.dispatch = handlers.dispatch
- this.handler = handlers.handler
- this.opts = dispatchOpts
- this.abort = null
- this.aborted = false
- this.retryOpts = {
- retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],
- retryAfter: retryAfter ?? true,
- maxTimeout: maxTimeout ?? 30 * 1000, // 30s,
- timeout: minTimeout ?? 500, // .5s
- timeoutFactor: timeoutFactor ?? 2,
- maxRetries: maxRetries ?? 5,
- // What errors we should retry
- methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],
- // Indicates which errors to retry
- statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
- // List of errors to retry
- errorCodes: errorCodes ?? [
- 'ECONNRESET',
- 'ECONNREFUSED',
- 'ENOTFOUND',
- 'ENETDOWN',
- 'ENETUNREACH',
- 'EHOSTDOWN',
- 'EHOSTUNREACH',
- 'EPIPE'
- ]
+function getResourceLocation(res, state) {
+ const loc = accessBodyProperty(res, "resourceLocation");
+ if (loc && typeof loc === "string") {
+ state.config.resourceLocation = loc;
}
+ return state.config.resourceLocation;
+}
+exports.getResourceLocation = getResourceLocation;
+function isOperationError(e) {
+ return e.name === "RestError";
+}
+exports.isOperationError = isOperationError;
+/** Polls the long-running operation. */
+async function pollHttpOperation(inputs) {
+ const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs;
+ return (0, operation_js_1.pollOperation)({
+ state,
+ stateProxy,
+ setDelay,
+ processResult: processResult
+ ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState)
+ : ({ flatResponse }) => flatResponse,
+ getError: getErrorFromResponse,
+ updateState,
+ getPollingInterval: parseRetryAfter,
+ getOperationLocation,
+ getOperationStatus,
+ isOperationError,
+ getResourceLocation,
+ options,
+ /**
+ * The expansion here is intentional because `lro` could be an object that
+ * references an inner this, so we need to preserve a reference to it.
+ */
+ poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions),
+ setErrorAsResult,
+ });
+}
+exports.pollHttpOperation = pollHttpOperation;
+//# sourceMappingURL=operation.js.map
- this.retryCount = 0
- this.start = 0
- this.end = null
- this.etag = null
- this.resume = null
+/***/ }),
- // Handle possible onConnect duplication
- this.handler.onConnect(reason => {
- this.aborted = true
- if (this.abort) {
- this.abort(reason)
- } else {
- this.reason = reason
- }
- })
- }
+/***/ 74681:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- onRequestSent () {
- if (this.handler.onRequestSent) {
- this.handler.onRequestSent()
- }
- }
- onUpgrade (statusCode, headers, socket) {
- if (this.handler.onUpgrade) {
- this.handler.onUpgrade(statusCode, headers, socket)
- }
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createHttpPoller = void 0;
+const operation_js_1 = __nccwpck_require__(27826);
+const poller_js_1 = __nccwpck_require__(81327);
+/**
+ * Creates a poller that can be used to poll a long-running operation.
+ * @param lro - Description of the long-running operation
+ * @param options - options to configure the poller
+ * @returns an initialized poller
+ */
+async function createHttpPoller(lro, options) {
+ const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {};
+ return (0, poller_js_1.buildCreatePoller)({
+ getStatusFromInitialResponse: operation_js_1.getStatusFromInitialResponse,
+ getStatusFromPollResponse: operation_js_1.getOperationStatus,
+ isOperationError: operation_js_1.isOperationError,
+ getOperationLocation: operation_js_1.getOperationLocation,
+ getResourceLocation: operation_js_1.getResourceLocation,
+ getPollingInterval: operation_js_1.parseRetryAfter,
+ getError: operation_js_1.getErrorFromResponse,
+ resolveOnUnsuccessful,
+ })({
+ init: async () => {
+ const response = await lro.sendInitialRequest();
+ const config = (0, operation_js_1.inferLroMode)({
+ rawResponse: response.rawResponse,
+ requestPath: lro.requestPath,
+ requestMethod: lro.requestMethod,
+ resourceLocationConfig,
+ });
+ return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+ },
+ poll: lro.sendPollRequest,
+ }, {
+ intervalInMs,
+ withOperationLocation,
+ restoreFrom,
+ updateState,
+ processResult: processResult
+ ? ({ flatResponse }, state) => processResult(flatResponse, state)
+ : ({ flatResponse }) => flatResponse,
+ });
+}
+exports.createHttpPoller = createHttpPoller;
+//# sourceMappingURL=poller.js.map
+
+/***/ }),
- onConnect (abort) {
- if (this.aborted) {
- abort(this.reason)
- } else {
- this.abort = abort
- }
- }
+/***/ 1814:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- onBodySent (chunk) {
- if (this.handler.onBodySent) return this.handler.onBodySent(chunk)
- }
- static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
- const { statusCode, code, headers } = err
- const { method, retryOptions } = opts
- const {
- maxRetries,
- timeout,
- maxTimeout,
- timeoutFactor,
- statusCodes,
- errorCodes,
- methods
- } = retryOptions
- let { counter, currentTimeout } = state
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createHttpPoller = void 0;
+const tslib_1 = __nccwpck_require__(94176);
+var poller_js_1 = __nccwpck_require__(74681);
+Object.defineProperty(exports, "createHttpPoller", ({ enumerable: true, get: function () { return poller_js_1.createHttpPoller; } }));
+/**
+ * This can be uncommented to expose the protocol-agnostic poller
+ */
+// export {
+// BuildCreatePollerOptions,
+// Operation,
+// CreatePollerOptions,
+// OperationConfig,
+// RestorableOperationState,
+// } from "./poller/models";
+// export { buildCreatePoller } from "./poller/poller";
+/** legacy */
+tslib_1.__exportStar(__nccwpck_require__(5618), exports);
+tslib_1.__exportStar(__nccwpck_require__(25796), exports);
+tslib_1.__exportStar(__nccwpck_require__(67130), exports);
+//# sourceMappingURL=index.js.map
- currentTimeout =
- currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout
+/***/ }),
- // Any code that is not a Undici's originated and allowed to retry
- if (
- code &&
- code !== 'UND_ERR_REQ_RETRY' &&
- code !== 'UND_ERR_SOCKET' &&
- !errorCodes.includes(code)
- ) {
- cb(err)
- return
- }
+/***/ 5618:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // If a set of method are provided and the current method is not in the list
- if (Array.isArray(methods) && !methods.includes(method)) {
- cb(err)
- return
- }
- // If a set of status code are provided and the current status code is not in the list
- if (
- statusCode != null &&
- Array.isArray(statusCodes) &&
- !statusCodes.includes(statusCode)
- ) {
- cb(err)
- return
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.LroEngine = void 0;
+var lroEngine_js_1 = __nccwpck_require__(24203);
+Object.defineProperty(exports, "LroEngine", ({ enumerable: true, get: function () { return lroEngine_js_1.LroEngine; } }));
+//# sourceMappingURL=index.js.map
- // If we reached the max number of retries
- if (counter > maxRetries) {
- cb(err)
- return
- }
+/***/ }),
- let retryAfterHeader = headers != null && headers['retry-after']
- if (retryAfterHeader) {
- retryAfterHeader = Number(retryAfterHeader)
- retryAfterHeader = isNaN(retryAfterHeader)
- ? calculateRetryAfterHeader(retryAfterHeader)
- : retryAfterHeader * 1e3 // Retry-After is in seconds
- }
+/***/ 24203:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- const retryTimeout =
- retryAfterHeader > 0
- ? Math.min(retryAfterHeader, maxTimeout)
- : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout)
- state.currentTimeout = retryTimeout
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.LroEngine = void 0;
+const operation_js_1 = __nccwpck_require__(52175);
+const constants_js_1 = __nccwpck_require__(94288);
+const poller_js_1 = __nccwpck_require__(25796);
+const operation_js_2 = __nccwpck_require__(26588);
+/**
+ * The LRO Engine, a class that performs polling.
+ */
+class LroEngine extends poller_js_1.Poller {
+ constructor(lro, options) {
+ const { intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {};
+ const state = resumeFrom
+ ? (0, operation_js_2.deserializeState)(resumeFrom)
+ : {};
+ const operation = new operation_js_1.GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone);
+ super(operation);
+ this.resolveOnUnsuccessful = resolveOnUnsuccessful;
+ this.config = { intervalInMs: intervalInMs };
+ operation.setPollerConfig(this.config);
+ }
+ /**
+ * The method used by the poller to wait before attempting to update its operation.
+ */
+ delay() {
+ return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs));
+ }
+}
+exports.LroEngine = LroEngine;
+//# sourceMappingURL=lroEngine.js.map
- setTimeout(() => cb(null), retryTimeout)
- }
+/***/ }),
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const headers = parseHeaders(rawHeaders)
+/***/ 52175:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this.retryCount += 1
- if (statusCode >= 300) {
- this.abort(
- new RequestRetryError('Request failed', statusCode, {
- headers,
- count: this.retryCount
- })
- )
- return false
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.GenericPollOperation = void 0;
+const operation_js_1 = __nccwpck_require__(27826);
+const logger_js_1 = __nccwpck_require__(80692);
+const createStateProxy = () => ({
+ initState: (config) => ({ config, isStarted: true }),
+ setCanceled: (state) => (state.isCancelled = true),
+ setError: (state, error) => (state.error = error),
+ setResult: (state, result) => (state.result = result),
+ setRunning: (state) => (state.isStarted = true),
+ setSucceeded: (state) => (state.isCompleted = true),
+ setFailed: () => {
+ /** empty body */
+ },
+ getError: (state) => state.error,
+ getResult: (state) => state.result,
+ isCanceled: (state) => !!state.isCancelled,
+ isFailed: (state) => !!state.error,
+ isRunning: (state) => !!state.isStarted,
+ isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error),
+});
+class GenericPollOperation {
+ constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) {
+ this.state = state;
+ this.lro = lro;
+ this.setErrorAsResult = setErrorAsResult;
+ this.lroResourceLocationConfig = lroResourceLocationConfig;
+ this.processResult = processResult;
+ this.updateState = updateState;
+ this.isDone = isDone;
+ }
+ setPollerConfig(pollerConfig) {
+ this.pollerConfig = pollerConfig;
+ }
+ async update(options) {
+ var _a;
+ const stateProxy = createStateProxy();
+ if (!this.state.isStarted) {
+ this.state = Object.assign(Object.assign({}, this.state), (await (0, operation_js_1.initHttpOperation)({
+ lro: this.lro,
+ stateProxy,
+ resourceLocationConfig: this.lroResourceLocationConfig,
+ processResult: this.processResult,
+ setErrorAsResult: this.setErrorAsResult,
+ })));
+ }
+ const updateState = this.updateState;
+ const isDone = this.isDone;
+ if (!this.state.isCompleted && this.state.error === undefined) {
+ await (0, operation_js_1.pollHttpOperation)({
+ lro: this.lro,
+ state: this.state,
+ stateProxy,
+ processResult: this.processResult,
+ updateState: updateState
+ ? (state, { rawResponse }) => updateState(state, rawResponse)
+ : undefined,
+ isDone: isDone
+ ? ({ flatResponse }, state) => isDone(flatResponse, state)
+ : undefined,
+ options,
+ setDelay: (intervalInMs) => {
+ this.pollerConfig.intervalInMs = intervalInMs;
+ },
+ setErrorAsResult: this.setErrorAsResult,
+ });
+ }
+ (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state);
+ return this;
+ }
+ async cancel() {
+ logger_js_1.logger.error("`cancelOperation` is deprecated because it wasn't implemented");
+ return this;
+ }
+ /**
+ * Serializes the Poller operation.
+ */
+ toString() {
+ return JSON.stringify({
+ state: this.state,
+ });
}
+}
+exports.GenericPollOperation = GenericPollOperation;
+//# sourceMappingURL=operation.js.map
- // Checkpoint for resume from where we left it
- if (this.resume != null) {
- this.resume = null
+/***/ }),
- if (statusCode !== 206) {
- return true
- }
+/***/ 67130:
+/***/ ((__unused_webpack_module, exports) => {
- const contentRange = parseRangeHeader(headers['content-range'])
- // If no content range
- if (!contentRange) {
- this.abort(
- new RequestRetryError('Content-Range mismatch', statusCode, {
- headers,
- count: this.retryCount
- })
- )
- return false
- }
- // Let's start with a weak etag check
- if (this.etag != null && this.etag !== headers.etag) {
- this.abort(
- new RequestRetryError('ETag mismatch', statusCode, {
- headers,
- count: this.retryCount
- })
- )
- return false
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+//# sourceMappingURL=pollOperation.js.map
- const { start, size, end = size } = contentRange
+/***/ }),
- assert(this.start === start, 'content-range mismatch')
- assert(this.end == null || this.end === end, 'content-range mismatch')
+/***/ 25796:
+/***/ ((__unused_webpack_module, exports) => {
- this.resume = resume
- return true
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Poller = exports.PollerCancelledError = exports.PollerStoppedError = void 0;
+/**
+ * When a poller is manually stopped through the `stopPolling` method,
+ * the poller will be rejected with an instance of the PollerStoppedError.
+ */
+class PollerStoppedError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "PollerStoppedError";
+ Object.setPrototypeOf(this, PollerStoppedError.prototype);
+ }
+}
+exports.PollerStoppedError = PollerStoppedError;
+/**
+ * When the operation is cancelled, the poller will be rejected with an instance
+ * of the PollerCancelledError.
+ */
+class PollerCancelledError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "PollerCancelledError";
+ Object.setPrototypeOf(this, PollerCancelledError.prototype);
+ }
+}
+exports.PollerCancelledError = PollerCancelledError;
+/**
+ * A class that represents the definition of a program that polls through consecutive requests
+ * until it reaches a state of completion.
+ *
+ * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed.
+ * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes.
+ * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation.
+ *
+ * ```ts
+ * const poller = new MyPoller();
+ *
+ * // Polling just once:
+ * await poller.poll();
+ *
+ * // We can try to cancel the request here, by calling:
+ * //
+ * // await poller.cancelOperation();
+ * //
+ *
+ * // Getting the final result:
+ * const result = await poller.pollUntilDone();
+ * ```
+ *
+ * The Poller is defined by two types, a type representing the state of the poller, which
+ * must include a basic set of properties from `PollOperationState`,
+ * and a return type defined by `TResult`, which can be anything.
+ *
+ * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having
+ * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type.
+ *
+ * ```ts
+ * class Client {
+ * public async makePoller: PollerLike {
+ * const poller = new MyPoller({});
+ * // It might be preferred to return the poller after the first request is made,
+ * // so that some information can be obtained right away.
+ * await poller.poll();
+ * return poller;
+ * }
+ * }
+ *
+ * const poller: PollerLike = myClient.makePoller();
+ * ```
+ *
+ * A poller can be created through its constructor, then it can be polled until it's completed.
+ * At any point in time, the state of the poller can be obtained without delay through the getOperationState method.
+ * At any point in time, the intermediate forms of the result type can be requested without delay.
+ * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned.
+ *
+ * ```ts
+ * const poller = myClient.makePoller();
+ * const state: MyOperationState = poller.getOperationState();
+ *
+ * // The intermediate result can be obtained at any time.
+ * const result: MyResult | undefined = poller.getResult();
+ *
+ * // The final result can only be obtained after the poller finishes.
+ * const result: MyResult = await poller.pollUntilDone();
+ * ```
+ *
+ */
+// eslint-disable-next-line no-use-before-define
+class Poller {
+ /**
+ * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`.
+ *
+ * When writing an implementation of a Poller, this implementation needs to deal with the initialization
+ * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's
+ * operation has already been defined, at least its basic properties. The code below shows how to approach
+ * the definition of the constructor of a new custom poller.
+ *
+ * ```ts
+ * export class MyPoller extends Poller {
+ * constructor({
+ * // Anything you might need outside of the basics
+ * }) {
+ * let state: MyOperationState = {
+ * privateProperty: private,
+ * publicProperty: public,
+ * };
+ *
+ * const operation = {
+ * state,
+ * update,
+ * cancel,
+ * toString
+ * }
+ *
+ * // Sending the operation to the parent's constructor.
+ * super(operation);
+ *
+ * // You can assign more local properties here.
+ * }
+ * }
+ * ```
+ *
+ * Inside of this constructor, a new promise is created. This will be used to
+ * tell the user when the poller finishes (see `pollUntilDone()`). The promise's
+ * resolve and reject methods are also used internally to control when to resolve
+ * or reject anyone waiting for the poller to finish.
+ *
+ * The constructor of a custom implementation of a poller is where any serialized version of
+ * a previous poller's operation should be deserialized into the operation sent to the
+ * base constructor. For example:
+ *
+ * ```ts
+ * export class MyPoller extends Poller {
+ * constructor(
+ * baseOperation: string | undefined
+ * ) {
+ * let state: MyOperationState = {};
+ * if (baseOperation) {
+ * state = {
+ * ...JSON.parse(baseOperation).state,
+ * ...state
+ * };
+ * }
+ * const operation = {
+ * state,
+ * // ...
+ * }
+ * super(operation);
+ * }
+ * }
+ * ```
+ *
+ * @param operation - Must contain the basic properties of `PollOperation`.
+ */
+ constructor(operation) {
+ /** controls whether to throw an error if the operation failed or was canceled. */
+ this.resolveOnUnsuccessful = false;
+ this.stopped = true;
+ this.pollProgressCallbacks = [];
+ this.operation = operation;
+ this.promise = new Promise((resolve, reject) => {
+ this.resolve = resolve;
+ this.reject = reject;
+ });
+ // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown.
+ // The above warning would get thrown if `poller.poll` is called, it returns an error,
+ // and pullUntilDone did not have a .catch or await try/catch on it's return value.
+ this.promise.catch(() => {
+ /* intentionally blank */
+ });
+ }
+ /**
+ * Starts a loop that will break only if the poller is done
+ * or if the poller is stopped.
+ */
+ async startPolling(pollOptions = {}) {
+ if (this.stopped) {
+ this.stopped = false;
+ }
+ while (!this.isStopped() && !this.isDone()) {
+ await this.poll(pollOptions);
+ await this.delay();
+ }
+ }
+ /**
+ * pollOnce does one polling, by calling to the update method of the underlying
+ * poll operation to make any relevant change effective.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ async pollOnce(options = {}) {
+ if (!this.isDone()) {
+ this.operation = await this.operation.update({
+ abortSignal: options.abortSignal,
+ fireProgress: this.fireProgress.bind(this),
+ });
+ }
+ this.processUpdatedState();
+ }
+ /**
+ * fireProgress calls the functions passed in via onProgress the method of the poller.
+ *
+ * It loops over all of the callbacks received from onProgress, and executes them, sending them
+ * the current operation state.
+ *
+ * @param state - The current operation state.
+ */
+ fireProgress(state) {
+ for (const callback of this.pollProgressCallbacks) {
+ callback(state);
+ }
+ }
+ /**
+ * Invokes the underlying operation's cancel method.
+ */
+ async cancelOnce(options = {}) {
+ this.operation = await this.operation.cancel(options);
+ }
+ /**
+ * Returns a promise that will resolve once a single polling request finishes.
+ * It does this by calling the update method of the Poller's operation.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ poll(options = {}) {
+ if (!this.pollOncePromise) {
+ this.pollOncePromise = this.pollOnce(options);
+ const clearPollOncePromise = () => {
+ this.pollOncePromise = undefined;
+ };
+ this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject);
+ }
+ return this.pollOncePromise;
}
-
- if (this.end == null) {
- if (statusCode === 206) {
- // First time we receive 206
- const range = parseRangeHeader(headers['content-range'])
-
- if (range == null) {
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
+ processUpdatedState() {
+ if (this.operation.state.error) {
+ this.stopped = true;
+ if (!this.resolveOnUnsuccessful) {
+ this.reject(this.operation.state.error);
+ throw this.operation.state.error;
+ }
+ }
+ if (this.operation.state.isCancelled) {
+ this.stopped = true;
+ if (!this.resolveOnUnsuccessful) {
+ const error = new PollerCancelledError("Operation was canceled");
+ this.reject(error);
+ throw error;
+ }
+ }
+ if (this.isDone() && this.resolve) {
+ // If the poller has finished polling, this means we now have a result.
+ // However, it can be the case that TResult is instantiated to void, so
+ // we are not expecting a result anyway. To assert that we might not
+ // have a result eventually after finishing polling, we cast the result
+ // to TResult.
+ this.resolve(this.getResult());
}
-
- const { start, size, end = size } = range
-
- assert(
- start != null && Number.isFinite(start) && this.start !== start,
- 'content-range mismatch'
- )
- assert(Number.isFinite(start))
- assert(
- end != null && Number.isFinite(end) && this.end !== end,
- 'invalid content-length'
- )
-
- this.start = start
- this.end = end
- }
-
- // We make our best to checkpoint the body for further range headers
- if (this.end == null) {
- const contentLength = headers['content-length']
- this.end = contentLength != null ? Number(contentLength) : null
- }
-
- assert(Number.isFinite(this.start))
- assert(
- this.end == null || Number.isFinite(this.end),
- 'invalid content-length'
- )
-
- this.resume = resume
- this.etag = headers.etag != null ? headers.etag : null
-
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
}
-
- const err = new RequestRetryError('Request failed', statusCode, {
- headers,
- count: this.retryCount
- })
-
- this.abort(err)
-
- return false
- }
-
- onData (chunk) {
- this.start += chunk.length
-
- return this.handler.onData(chunk)
- }
-
- onComplete (rawTrailers) {
- this.retryCount = 0
- return this.handler.onComplete(rawTrailers)
- }
-
- onError (err) {
- if (this.aborted || isDisturbed(this.opts.body)) {
- return this.handler.onError(err)
+ /**
+ * Returns a promise that will resolve once the underlying operation is completed.
+ */
+ async pollUntilDone(pollOptions = {}) {
+ if (this.stopped) {
+ this.startPolling(pollOptions).catch(this.reject);
+ }
+ // This is needed because the state could have been updated by
+ // `cancelOperation`, e.g. the operation is canceled or an error occurred.
+ this.processUpdatedState();
+ return this.promise;
}
-
- this.retryOpts.retry(
- err,
- {
- state: { counter: this.retryCount++, currentTimeout: this.retryAfter },
- opts: { retryOptions: this.retryOpts, ...this.opts }
- },
- onRetry.bind(this)
- )
-
- function onRetry (err) {
- if (err != null || this.aborted || isDisturbed(this.opts.body)) {
- return this.handler.onError(err)
- }
-
- if (this.start !== 0) {
- this.opts = {
- ...this.opts,
- headers: {
- ...this.opts.headers,
- range: `bytes=${this.start}-${this.end ?? ''}`
- }
+ /**
+ * Invokes the provided callback after each polling is completed,
+ * sending the current state of the poller's operation.
+ *
+ * It returns a method that can be used to stop receiving updates on the given callback function.
+ */
+ onProgress(callback) {
+ this.pollProgressCallbacks.push(callback);
+ return () => {
+ this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback);
+ };
+ }
+ /**
+ * Returns true if the poller has finished polling.
+ */
+ isDone() {
+ const state = this.operation.state;
+ return Boolean(state.isCompleted || state.isCancelled || state.error);
+ }
+ /**
+ * Stops the poller from continuing to poll.
+ */
+ stopPolling() {
+ if (!this.stopped) {
+ this.stopped = true;
+ if (this.reject) {
+ this.reject(new PollerStoppedError("This poller is already stopped"));
+ }
}
- }
-
- try {
- this.dispatch(this.opts, this)
- } catch (err) {
- this.handler.onError(err)
- }
}
- }
-}
-
-module.exports = RetryHandler
-
-
-/***/ }),
-
-/***/ 99299:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const RedirectHandler = __nccwpck_require__(8591)
-
-function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {
- return (dispatch) => {
- return function Intercept (opts, handler) {
- const { maxRedirections = defaultMaxRedirections } = opts
-
- if (!maxRedirections) {
- return dispatch(opts, handler)
- }
-
- const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
- opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
- return dispatch(opts, redirectHandler)
+ /**
+ * Returns true if the poller is stopped.
+ */
+ isStopped() {
+ return this.stopped;
}
- }
-}
-
-module.exports = createRedirectInterceptor
-
-
-/***/ }),
-
-/***/ 40748:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
-const utils_1 = __nccwpck_require__(34608);
-// C headers
-var ERROR;
-(function (ERROR) {
- ERROR[ERROR["OK"] = 0] = "OK";
- ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL";
- ERROR[ERROR["STRICT"] = 2] = "STRICT";
- ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED";
- ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
- ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
- ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD";
- ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL";
- ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
- ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION";
- ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
- ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
- ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
- ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS";
- ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
- ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
- ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
- ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
- ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
- ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
- ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
- ERROR[ERROR["PAUSED"] = 21] = "PAUSED";
- ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
- ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
- ERROR[ERROR["USER"] = 24] = "USER";
-})(ERROR = exports.ERROR || (exports.ERROR = {}));
-var TYPE;
-(function (TYPE) {
- TYPE[TYPE["BOTH"] = 0] = "BOTH";
- TYPE[TYPE["REQUEST"] = 1] = "REQUEST";
- TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE";
-})(TYPE = exports.TYPE || (exports.TYPE = {}));
-var FLAGS;
-(function (FLAGS) {
- FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
- FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
- FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
- FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED";
- FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE";
- FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
- FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY";
- FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING";
- // 1 << 8 is unused
- FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
-})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
-var LENIENT_FLAGS;
-(function (LENIENT_FLAGS) {
- LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS";
- LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
- LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
-})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
-var METHODS;
-(function (METHODS) {
- METHODS[METHODS["DELETE"] = 0] = "DELETE";
- METHODS[METHODS["GET"] = 1] = "GET";
- METHODS[METHODS["HEAD"] = 2] = "HEAD";
- METHODS[METHODS["POST"] = 3] = "POST";
- METHODS[METHODS["PUT"] = 4] = "PUT";
- /* pathological */
- METHODS[METHODS["CONNECT"] = 5] = "CONNECT";
- METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS";
- METHODS[METHODS["TRACE"] = 7] = "TRACE";
- /* WebDAV */
- METHODS[METHODS["COPY"] = 8] = "COPY";
- METHODS[METHODS["LOCK"] = 9] = "LOCK";
- METHODS[METHODS["MKCOL"] = 10] = "MKCOL";
- METHODS[METHODS["MOVE"] = 11] = "MOVE";
- METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND";
- METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH";
- METHODS[METHODS["SEARCH"] = 14] = "SEARCH";
- METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK";
- METHODS[METHODS["BIND"] = 16] = "BIND";
- METHODS[METHODS["REBIND"] = 17] = "REBIND";
- METHODS[METHODS["UNBIND"] = 18] = "UNBIND";
- METHODS[METHODS["ACL"] = 19] = "ACL";
- /* subversion */
- METHODS[METHODS["REPORT"] = 20] = "REPORT";
- METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY";
- METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT";
- METHODS[METHODS["MERGE"] = 23] = "MERGE";
- /* upnp */
- METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH";
- METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY";
- METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE";
- METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
- /* RFC-5789 */
- METHODS[METHODS["PATCH"] = 28] = "PATCH";
- METHODS[METHODS["PURGE"] = 29] = "PURGE";
- /* CalDAV */
- METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR";
- /* RFC-2068, section 19.6.1.2 */
- METHODS[METHODS["LINK"] = 31] = "LINK";
- METHODS[METHODS["UNLINK"] = 32] = "UNLINK";
- /* icecast */
- METHODS[METHODS["SOURCE"] = 33] = "SOURCE";
- /* RFC-7540, section 11.6 */
- METHODS[METHODS["PRI"] = 34] = "PRI";
- /* RFC-2326 RTSP */
- METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE";
- METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE";
- METHODS[METHODS["SETUP"] = 37] = "SETUP";
- METHODS[METHODS["PLAY"] = 38] = "PLAY";
- METHODS[METHODS["PAUSE"] = 39] = "PAUSE";
- METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN";
- METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER";
- METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER";
- METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT";
- METHODS[METHODS["RECORD"] = 44] = "RECORD";
- /* RAOP */
- METHODS[METHODS["FLUSH"] = 45] = "FLUSH";
-})(METHODS = exports.METHODS || (exports.METHODS = {}));
-exports.METHODS_HTTP = [
- METHODS.DELETE,
- METHODS.GET,
- METHODS.HEAD,
- METHODS.POST,
- METHODS.PUT,
- METHODS.CONNECT,
- METHODS.OPTIONS,
- METHODS.TRACE,
- METHODS.COPY,
- METHODS.LOCK,
- METHODS.MKCOL,
- METHODS.MOVE,
- METHODS.PROPFIND,
- METHODS.PROPPATCH,
- METHODS.SEARCH,
- METHODS.UNLOCK,
- METHODS.BIND,
- METHODS.REBIND,
- METHODS.UNBIND,
- METHODS.ACL,
- METHODS.REPORT,
- METHODS.MKACTIVITY,
- METHODS.CHECKOUT,
- METHODS.MERGE,
- METHODS['M-SEARCH'],
- METHODS.NOTIFY,
- METHODS.SUBSCRIBE,
- METHODS.UNSUBSCRIBE,
- METHODS.PATCH,
- METHODS.PURGE,
- METHODS.MKCALENDAR,
- METHODS.LINK,
- METHODS.UNLINK,
- METHODS.PRI,
- // TODO(indutny): should we allow it with HTTP?
- METHODS.SOURCE,
-];
-exports.METHODS_ICE = [
- METHODS.SOURCE,
-];
-exports.METHODS_RTSP = [
- METHODS.OPTIONS,
- METHODS.DESCRIBE,
- METHODS.ANNOUNCE,
- METHODS.SETUP,
- METHODS.PLAY,
- METHODS.PAUSE,
- METHODS.TEARDOWN,
- METHODS.GET_PARAMETER,
- METHODS.SET_PARAMETER,
- METHODS.REDIRECT,
- METHODS.RECORD,
- METHODS.FLUSH,
- // For AirPlay
- METHODS.GET,
- METHODS.POST,
-];
-exports.METHOD_MAP = utils_1.enumToMap(METHODS);
-exports.H_METHOD_MAP = {};
-Object.keys(exports.METHOD_MAP).forEach((key) => {
- if (/^H/.test(key)) {
- exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
+ /**
+ * Attempts to cancel the underlying operation.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * If it's called again before it finishes, it will throw an error.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ cancelOperation(options = {}) {
+ if (!this.cancelPromise) {
+ this.cancelPromise = this.cancelOnce(options);
+ }
+ else if (options.abortSignal) {
+ throw new Error("A cancel request is currently pending");
+ }
+ return this.cancelPromise;
}
-});
-var FINISH;
-(function (FINISH) {
- FINISH[FINISH["SAFE"] = 0] = "SAFE";
- FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
- FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE";
-})(FINISH = exports.FINISH || (exports.FINISH = {}));
-exports.ALPHA = [];
-for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
- // Upper case
- exports.ALPHA.push(String.fromCharCode(i));
- // Lower case
- exports.ALPHA.push(String.fromCharCode(i + 0x20));
-}
-exports.NUM_MAP = {
- 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
- 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
-};
-exports.HEX_MAP = {
- 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
- 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
- A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,
- a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,
-};
-exports.NUM = [
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
-];
-exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
-exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')'];
-exports.USERINFO_CHARS = exports.ALPHANUM
- .concat(exports.MARK)
- .concat(['%', ';', ':', '&', '=', '+', '$', ',']);
-// TODO(indutny): use RFC
-exports.STRICT_URL_CHAR = [
- '!', '"', '$', '%', '&', '\'',
- '(', ')', '*', '+', ',', '-', '.', '/',
- ':', ';', '<', '=', '>',
- '@', '[', '\\', ']', '^', '_',
- '`',
- '{', '|', '}', '~',
-].concat(exports.ALPHANUM);
-exports.URL_CHAR = exports.STRICT_URL_CHAR
- .concat(['\t', '\f']);
-// All characters with 0x80 bit set to 1
-for (let i = 0x80; i <= 0xff; i++) {
- exports.URL_CHAR.push(i);
-}
-exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);
-/* Tokens as defined by rfc 2616. Also lowercases them.
- * token = 1*
- * separators = "(" | ")" | "<" | ">" | "@"
- * | "," | ";" | ":" | "\" | <">
- * | "/" | "[" | "]" | "?" | "="
- * | "{" | "}" | SP | HT
- */
-exports.STRICT_TOKEN = [
- '!', '#', '$', '%', '&', '\'',
- '*', '+', '-', '.',
- '^', '_', '`',
- '|', '~',
-].concat(exports.ALPHANUM);
-exports.TOKEN = exports.STRICT_TOKEN.concat([' ']);
-/*
- * Verify that a char is a valid visible (printable) US-ASCII
- * character or %x80-FF
- */
-exports.HEADER_CHARS = ['\t'];
-for (let i = 32; i <= 255; i++) {
- if (i !== 127) {
- exports.HEADER_CHARS.push(i);
+ /**
+ * Returns the state of the operation.
+ *
+ * Even though TState will be the same type inside any of the methods of any extension of the Poller class,
+ * implementations of the pollers can customize what's shared with the public by writing their own
+ * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller
+ * and a public type representing a safe to share subset of the properties of the internal state.
+ * Their definition of getOperationState can then return their public type.
+ *
+ * Example:
+ *
+ * ```ts
+ * // Let's say we have our poller's operation state defined as:
+ * interface MyOperationState extends PollOperationState {
+ * privateProperty?: string;
+ * publicProperty?: string;
+ * }
+ *
+ * // To allow us to have a true separation of public and private state, we have to define another interface:
+ * interface PublicState extends PollOperationState {
+ * publicProperty?: string;
+ * }
+ *
+ * // Then, we define our Poller as follows:
+ * export class MyPoller extends Poller {
+ * // ... More content is needed here ...
+ *
+ * public getOperationState(): PublicState {
+ * const state: PublicState = this.operation.state;
+ * return {
+ * // Properties from PollOperationState
+ * isStarted: state.isStarted,
+ * isCompleted: state.isCompleted,
+ * isCancelled: state.isCancelled,
+ * error: state.error,
+ * result: state.result,
+ *
+ * // The only other property needed by PublicState.
+ * publicProperty: state.publicProperty
+ * }
+ * }
+ * }
+ * ```
+ *
+ * You can see this in the tests of this repository, go to the file:
+ * `../test/utils/testPoller.ts`
+ * and look for the getOperationState implementation.
+ */
+ getOperationState() {
+ return this.operation.state;
+ }
+ /**
+ * Returns the result value of the operation,
+ * regardless of the state of the poller.
+ * It can return undefined or an incomplete form of the final TResult value
+ * depending on the implementation.
+ */
+ getResult() {
+ const state = this.operation.state;
+ return state.result;
+ }
+ /**
+ * Returns a serialized version of the poller's operation
+ * by invoking the operation's toString method.
+ */
+ toString() {
+ return this.operation.toString();
}
}
-// ',' = \x44
-exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
-exports.MAJOR = exports.NUM_MAP;
-exports.MINOR = exports.MAJOR;
-var HEADER_STATE;
-(function (HEADER_STATE) {
- HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL";
- HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION";
- HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
- HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
- HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE";
- HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
- HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
- HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
- HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
-})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
-exports.SPECIAL_HEADERS = {
- 'connection': HEADER_STATE.CONNECTION,
- 'content-length': HEADER_STATE.CONTENT_LENGTH,
- 'proxy-connection': HEADER_STATE.CONNECTION,
- 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,
- 'upgrade': HEADER_STATE.UPGRADE,
-};
-//# sourceMappingURL=constants.js.map
+exports.Poller = Poller;
+//# sourceMappingURL=poller.js.map
/***/ }),
-/***/ 63922:
-/***/ ((module) => {
+/***/ 80692:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ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MGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSElKzwHOAUvNAUzMAU1OT1BRUlNUVVZXWFlaW1xdXl9gYWJj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EhEAwWC0EBIRAMFQtBrwEhEAwUC0GwASEQDBMLQbEBIRAMEgtBswEhEAwRC0GyASEQDBALQbQBIRAMDwtBtQEhEAwOC0G2ASEQDA0LQbcBIRAMDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAC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CHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2AhAgAEEgNgIMQQAhEAybAQsgAEEANgIAIBBBAWohAUEkIRALIAA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.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logger = void 0;
+const logger_1 = __nccwpck_require__(50143);
+/**
+ * The `@azure/logger` configuration for this package.
+ * @internal
+ */
+exports.logger = (0, logger_1.createClientLogger)("core-lro");
+//# sourceMappingURL=logger.js.map
/***/ }),
-/***/ 53742:
-/***/ ((module) => {
+/***/ 94288:
+/***/ ((__unused_webpack_module, exports) => {
-module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh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wEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAC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HDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB7AELIAFBAWohAUEIIRAMyAMLIAFBAWoiASACRw0AC0EVIRAM3wMLQRUhEAzeAwsDQAJAIAEtAABB8LmAgABqLQAAIhBBAkYNACAQQX9qDgTeAewB4AHrAewBCyABQQFqIgEgAkcNAAtBGCEQDN0DCwJAIAEiASACRg0AIABBi4CAgAA2AgggACABNgIEIAEhAUEHIRAMxAMLQRkhEAzcAwsgAUEBaiEBDAILAkAgASIUIAJHDQBBGiEQDNsDCyAUIQECQCAULQAAQXNqDhTdAu4C7gLuA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AALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBA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DAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.terminalStates = exports.POLL_INTERVAL_IN_MS = void 0;
+/**
+ * The default time interval to wait before sending the next polling request.
+ */
+exports.POLL_INTERVAL_IN_MS = 2000;
+/**
+ * The closed set of terminal states.
+ */
+exports.terminalStates = ["succeeded", "canceled", "failed"];
+//# sourceMappingURL=constants.js.map
/***/ }),
-/***/ 34608:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 26588:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.enumToMap = void 0;
-function enumToMap(obj) {
- const res = {};
- Object.keys(obj).forEach((key) => {
- const value = obj[key];
- if (typeof value === 'number') {
- res[key] = value;
+exports.pollOperation = exports.initOperation = exports.deserializeState = void 0;
+const logger_js_1 = __nccwpck_require__(80692);
+const constants_js_1 = __nccwpck_require__(94288);
+/**
+ * Deserializes the state
+ */
+function deserializeState(serializedState) {
+ try {
+ return JSON.parse(serializedState).state;
+ }
+ catch (e) {
+ throw new Error(`Unable to deserialize input state: ${serializedState}`);
+ }
+}
+exports.deserializeState = deserializeState;
+function setStateError(inputs) {
+ const { state, stateProxy, isOperationError } = inputs;
+ return (error) => {
+ if (isOperationError(error)) {
+ stateProxy.setError(state, error);
+ stateProxy.setFailed(state);
}
- });
- return res;
+ throw error;
+ };
}
-exports.enumToMap = enumToMap;
-//# sourceMappingURL=utils.js.map
-
-/***/ }),
-
-/***/ 77017:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { kClients } = __nccwpck_require__(68031)
-const Agent = __nccwpck_require__(92121)
-const {
- kAgent,
- kMockAgentSet,
- kMockAgentGet,
- kDispatches,
- kIsMockActive,
- kNetConnect,
- kGetNetConnect,
- kOptions,
- kFactory
-} = __nccwpck_require__(52305)
-const MockClient = __nccwpck_require__(72361)
-const MockPool = __nccwpck_require__(36480)
-const { matchValue, buildMockOptions } = __nccwpck_require__(73193)
-const { InvalidArgumentError, UndiciError } = __nccwpck_require__(53959)
-const Dispatcher = __nccwpck_require__(20303)
-const Pluralizer = __nccwpck_require__(35773)
-const PendingInterceptorsFormatter = __nccwpck_require__(85738)
-
-class FakeWeakRef {
- constructor (value) {
- this.value = value
- }
-
- deref () {
- return this.value
- }
+function appendReadableErrorMessage(currentMessage, innerMessage) {
+ let message = currentMessage;
+ if (message.slice(-1) !== ".") {
+ message = message + ".";
+ }
+ return message + " " + innerMessage;
}
-
-class MockAgent extends Dispatcher {
- constructor (opts) {
- super(opts)
-
- this[kNetConnect] = true
- this[kIsMockActive] = true
-
- // Instantiate Agent and encapsulate
- if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+function simplifyError(err) {
+ let message = err.message;
+ let code = err.code;
+ let curErr = err;
+ while (curErr.innererror) {
+ curErr = curErr.innererror;
+ code = curErr.code;
+ message = appendReadableErrorMessage(message, curErr.message);
}
- const agent = opts && opts.agent ? opts.agent : new Agent(opts)
- this[kAgent] = agent
-
- this[kClients] = agent[kClients]
- this[kOptions] = buildMockOptions(opts)
- }
-
- get (origin) {
- let dispatcher = this[kMockAgentGet](origin)
-
- if (!dispatcher) {
- dispatcher = this[kFactory](origin)
- this[kMockAgentSet](origin, dispatcher)
+ return {
+ code,
+ message,
+ };
+}
+function processOperationStatus(result) {
+ const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result;
+ switch (status) {
+ case "succeeded": {
+ stateProxy.setSucceeded(state);
+ break;
+ }
+ case "failed": {
+ const err = getError === null || getError === void 0 ? void 0 : getError(response);
+ let postfix = "";
+ if (err) {
+ const { code, message } = simplifyError(err);
+ postfix = `. ${code}. ${message}`;
+ }
+ const errStr = `The long-running operation has failed${postfix}`;
+ stateProxy.setError(state, new Error(errStr));
+ stateProxy.setFailed(state);
+ logger_js_1.logger.warning(errStr);
+ break;
+ }
+ case "canceled": {
+ stateProxy.setCanceled(state);
+ break;
+ }
}
- return dispatcher
- }
+ if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) ||
+ (isDone === undefined &&
+ ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) {
+ stateProxy.setResult(state, buildResult({
+ response,
+ state,
+ processResult,
+ }));
+ }
+}
+function buildResult(inputs) {
+ const { processResult, response, state } = inputs;
+ return processResult ? processResult(response, state) : response;
+}
+/**
+ * Initiates the long-running operation.
+ */
+async function initOperation(inputs) {
+ const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs;
+ const { operationLocation, resourceLocation, metadata, response } = await init();
+ if (operationLocation)
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
+ const config = {
+ metadata,
+ operationLocation,
+ resourceLocation,
+ };
+ logger_js_1.logger.verbose(`LRO: Operation description:`, config);
+ const state = stateProxy.initState(config);
+ const status = getOperationStatus({ response, state, operationLocation });
+ processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult });
+ return state;
+}
+exports.initOperation = initOperation;
+async function pollOperationHelper(inputs) {
+ const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs;
+ const response = await poll(operationLocation, options).catch(setStateError({
+ state,
+ stateProxy,
+ isOperationError,
+ }));
+ const status = getOperationStatus(response, state);
+ logger_js_1.logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${constants_js_1.terminalStates.includes(status) ? "Stopped" : "Running"}`);
+ if (status === "succeeded") {
+ const resourceLocation = getResourceLocation(response, state);
+ if (resourceLocation !== undefined) {
+ return {
+ response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })),
+ status,
+ };
+ }
+ }
+ return { response, status };
+}
+/** Polls the long-running operation. */
+async function pollOperation(inputs) {
+ const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult, } = inputs;
+ const { operationLocation } = state.config;
+ if (operationLocation !== undefined) {
+ const { response, status } = await pollOperationHelper({
+ poll,
+ getOperationStatus,
+ state,
+ stateProxy,
+ operationLocation,
+ getResourceLocation,
+ isOperationError,
+ options,
+ });
+ processOperationStatus({
+ status,
+ response,
+ state,
+ stateProxy,
+ isDone,
+ processResult,
+ getError,
+ setErrorAsResult,
+ });
+ if (!constants_js_1.terminalStates.includes(status)) {
+ const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response);
+ if (intervalInMs)
+ setDelay(intervalInMs);
+ const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state);
+ if (location !== undefined) {
+ const isUpdated = operationLocation !== location;
+ state.config.operationLocation = location;
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated);
+ }
+ else
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
+ }
+ updateState === null || updateState === void 0 ? void 0 : updateState(state, response);
+ }
+}
+exports.pollOperation = pollOperation;
+//# sourceMappingURL=operation.js.map
- dispatch (opts, handler) {
- // Call MockAgent.get to perform additional setup before dispatching as normal
- this.get(opts.origin)
- return this[kAgent].dispatch(opts, handler)
- }
+/***/ }),
- async close () {
- await this[kAgent].close()
- this[kClients].clear()
- }
+/***/ 81327:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- deactivate () {
- this[kIsMockActive] = false
- }
- activate () {
- this[kIsMockActive] = true
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.buildCreatePoller = void 0;
+const operation_js_1 = __nccwpck_require__(26588);
+const constants_js_1 = __nccwpck_require__(94288);
+const core_util_1 = __nccwpck_require__(30991);
+const createStateProxy = () => ({
+ /**
+ * The state at this point is created to be of type OperationState.
+ * It will be updated later to be of type TState when the
+ * customer-provided callback, `updateState`, is called during polling.
+ */
+ initState: (config) => ({ status: "running", config }),
+ setCanceled: (state) => (state.status = "canceled"),
+ setError: (state, error) => (state.error = error),
+ setResult: (state, result) => (state.result = result),
+ setRunning: (state) => (state.status = "running"),
+ setSucceeded: (state) => (state.status = "succeeded"),
+ setFailed: (state) => (state.status = "failed"),
+ getError: (state) => state.error,
+ getResult: (state) => state.result,
+ isCanceled: (state) => state.status === "canceled",
+ isFailed: (state) => state.status === "failed",
+ isRunning: (state) => state.status === "running",
+ isSucceeded: (state) => state.status === "succeeded",
+});
+/**
+ * Returns a poller factory.
+ */
+function buildCreatePoller(inputs) {
+ const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, getError, resolveOnUnsuccessful, } = inputs;
+ return async ({ init, poll }, options) => {
+ const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, restoreFrom, } = options || {};
+ const stateProxy = createStateProxy();
+ const withOperationLocation = withOperationLocationCallback
+ ? (() => {
+ let called = false;
+ return (operationLocation, isUpdated) => {
+ if (isUpdated)
+ withOperationLocationCallback(operationLocation);
+ else if (!called)
+ withOperationLocationCallback(operationLocation);
+ called = true;
+ };
+ })()
+ : undefined;
+ const state = restoreFrom
+ ? (0, operation_js_1.deserializeState)(restoreFrom)
+ : await (0, operation_js_1.initOperation)({
+ init,
+ stateProxy,
+ processResult,
+ getOperationStatus: getStatusFromInitialResponse,
+ withOperationLocation,
+ setErrorAsResult: !resolveOnUnsuccessful,
+ });
+ let resultPromise;
+ const abortController = new AbortController();
+ const handlers = new Map();
+ const handleProgressEvents = async () => handlers.forEach((h) => h(state));
+ const cancelErrMsg = "Operation was canceled";
+ let currentPollIntervalInMs = intervalInMs;
+ const poller = {
+ getOperationState: () => state,
+ getResult: () => state.result,
+ isDone: () => ["succeeded", "failed", "canceled"].includes(state.status),
+ isStopped: () => resultPromise === undefined,
+ stopPolling: () => {
+ abortController.abort();
+ },
+ toString: () => JSON.stringify({
+ state,
+ }),
+ onProgress: (callback) => {
+ const s = Symbol();
+ handlers.set(s, callback);
+ return () => handlers.delete(s);
+ },
+ pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => {
+ const { abortSignal: inputAbortSignal } = pollOptions || {};
+ // In the future we can use AbortSignal.any() instead
+ function abortListener() {
+ abortController.abort();
+ }
+ const abortSignal = abortController.signal;
+ if (inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.aborted) {
+ abortController.abort();
+ }
+ else if (!abortSignal.aborted) {
+ inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.addEventListener("abort", abortListener, { once: true });
+ }
+ try {
+ if (!poller.isDone()) {
+ await poller.poll({ abortSignal });
+ while (!poller.isDone()) {
+ await (0, core_util_1.delay)(currentPollIntervalInMs, { abortSignal });
+ await poller.poll({ abortSignal });
+ }
+ }
+ }
+ finally {
+ inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.removeEventListener("abort", abortListener);
+ }
+ if (resolveOnUnsuccessful) {
+ return poller.getResult();
+ }
+ else {
+ switch (state.status) {
+ case "succeeded":
+ return poller.getResult();
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ case "notStarted":
+ case "running":
+ throw new Error(`Polling completed without succeeding or failing`);
+ }
+ }
+ })().finally(() => {
+ resultPromise = undefined;
+ }))),
+ async poll(pollOptions) {
+ if (resolveOnUnsuccessful) {
+ if (poller.isDone())
+ return;
+ }
+ else {
+ switch (state.status) {
+ case "succeeded":
+ return;
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ }
+ }
+ await (0, operation_js_1.pollOperation)({
+ poll,
+ state,
+ stateProxy,
+ getOperationLocation,
+ isOperationError,
+ withOperationLocation,
+ getPollingInterval,
+ getOperationStatus: getStatusFromPollResponse,
+ getResourceLocation,
+ processResult,
+ getError,
+ updateState,
+ options: pollOptions,
+ setDelay: (pollIntervalInMs) => {
+ currentPollIntervalInMs = pollIntervalInMs;
+ },
+ setErrorAsResult: !resolveOnUnsuccessful,
+ });
+ await handleProgressEvents();
+ if (!resolveOnUnsuccessful) {
+ switch (state.status) {
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ }
+ }
+ },
+ };
+ return poller;
+ };
+}
+exports.buildCreatePoller = buildCreatePoller;
+//# sourceMappingURL=poller.js.map
- enableNetConnect (matcher) {
- if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {
- if (Array.isArray(this[kNetConnect])) {
- this[kNetConnect].push(matcher)
- } else {
- this[kNetConnect] = [matcher]
- }
- } else if (typeof matcher === 'undefined') {
- this[kNetConnect] = true
- } else {
- throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')
- }
- }
+/***/ }),
- disableNetConnect () {
- this[kNetConnect] = false
- }
+/***/ 91791:
+/***/ ((__unused_webpack_module, exports) => {
- // This is required to bypass issues caused by using global symbols - see:
- // https://github.com/nodejs/undici/issues/1447
- get isMockActive () {
- return this[kIsMockActive]
- }
- [kMockAgentSet] (origin, dispatcher) {
- this[kClients].set(origin, new FakeWeakRef(dispatcher))
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.DEFAULT_RETRY_POLICY_COUNT = exports.SDK_VERSION = void 0;
+exports.SDK_VERSION = "1.18.1";
+exports.DEFAULT_RETRY_POLICY_COUNT = 3;
+//# sourceMappingURL=constants.js.map
- [kFactory] (origin) {
- const mockOptions = Object.assign({ agent: this }, this[kOptions])
- return this[kOptions] && this[kOptions].connections === 1
- ? new MockClient(origin, mockOptions)
- : new MockPool(origin, mockOptions)
- }
+/***/ }),
- [kMockAgentGet] (origin) {
- // First check if we can immediately find it
- const ref = this[kClients].get(origin)
- if (ref) {
- return ref.deref()
- }
+/***/ 1130:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // If the origin is not a string create a dummy parent pool and return to user
- if (typeof origin !== 'string') {
- const dispatcher = this[kFactory]('http://localhost:9999')
- this[kMockAgentSet](origin, dispatcher)
- return dispatcher
- }
- // If we match, create a pool and assign the same dispatches
- for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {
- const nonExplicitDispatcher = nonExplicitRef.deref()
- if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
- const dispatcher = this[kFactory](origin)
- this[kMockAgentSet](origin, dispatcher)
- dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
- return dispatcher
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPipelineFromOptions = createPipelineFromOptions;
+const logPolicy_js_1 = __nccwpck_require__(19937);
+const pipeline_js_1 = __nccwpck_require__(37050);
+const redirectPolicy_js_1 = __nccwpck_require__(86947);
+const userAgentPolicy_js_1 = __nccwpck_require__(69795);
+const multipartPolicy_js_1 = __nccwpck_require__(77915);
+const decompressResponsePolicy_js_1 = __nccwpck_require__(13299);
+const defaultRetryPolicy_js_1 = __nccwpck_require__(47494);
+const formDataPolicy_js_1 = __nccwpck_require__(37997);
+const core_util_1 = __nccwpck_require__(30991);
+const proxyPolicy_js_1 = __nccwpck_require__(73723);
+const setClientRequestIdPolicy_js_1 = __nccwpck_require__(63866);
+const tlsPolicy_js_1 = __nccwpck_require__(39370);
+const tracingPolicy_js_1 = __nccwpck_require__(14113);
+/**
+ * Create a new pipeline with a default set of customizable policies.
+ * @param options - Options to configure a custom pipeline.
+ */
+function createPipelineFromOptions(options) {
+ var _a;
+ const pipeline = (0, pipeline_js_1.createEmptyPipeline)();
+ if (core_util_1.isNodeLike) {
+ if (options.tlsOptions) {
+ pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions));
+ }
+ pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions));
+ pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)());
}
- }
-
- [kGetNetConnect] () {
- return this[kNetConnect]
- }
-
- pendingInterceptors () {
- const mockAgentClients = this[kClients]
-
- return Array.from(mockAgentClients.entries())
- .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin })))
- .filter(({ pending }) => pending)
- }
-
- assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
- const pending = this.pendingInterceptors()
-
- if (pending.length === 0) {
- return
+ pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] });
+ pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions));
+ pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName));
+ // The multipart policy is added after policies with no phase, so that
+ // policies can be added between it and formDataPolicy to modify
+ // properties (e.g., making the boundary constant in recorded tests).
+ pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" });
+ pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" });
+ pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), {
+ afterPhase: "Retry",
+ });
+ if (core_util_1.isNodeLike) {
+ // Both XHR and Fetch expect to handle redirects automatically,
+ // so only include this policy when we're in Node.
+ pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" });
}
-
- const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)
-
- throw new UndiciError(`
-${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
-
-${pendingInterceptorsFormatter.format(pending)}
-`.trim())
- }
+ pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" });
+ return pipeline;
}
-
-module.exports = MockAgent
-
+//# sourceMappingURL=createPipelineFromOptions.js.map
/***/ }),
-/***/ 72361:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 55316:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const { promisify } = __nccwpck_require__(39023)
-const Client = __nccwpck_require__(45513)
-const { buildMockDispatch } = __nccwpck_require__(73193)
-const {
- kDispatches,
- kMockAgent,
- kClose,
- kOriginalClose,
- kOrigin,
- kOriginalDispatch,
- kConnected
-} = __nccwpck_require__(52305)
-const { MockInterceptor } = __nccwpck_require__(5843)
-const Symbols = __nccwpck_require__(68031)
-const { InvalidArgumentError } = __nccwpck_require__(53959)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createDefaultHttpClient = createDefaultHttpClient;
+const nodeHttpClient_js_1 = __nccwpck_require__(56583);
/**
- * MockClient provides an API that extends the Client to influence the mockDispatches.
+ * Create the correct HttpClient for the current environment.
*/
-class MockClient extends Client {
- constructor (origin, opts) {
- super(origin, opts)
-
- if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
- }
-
- this[kMockAgent] = opts.agent
- this[kOrigin] = origin
- this[kDispatches] = []
- this[kConnected] = 1
- this[kOriginalDispatch] = this.dispatch
- this[kOriginalClose] = this.close.bind(this)
-
- this.dispatch = buildMockDispatch.call(this)
- this.close = this[kClose]
- }
-
- get [Symbols.kConnected] () {
- return this[kConnected]
- }
-
- /**
- * Sets up the base interceptor for mocking replies from undici.
- */
- intercept (opts) {
- return new MockInterceptor(opts, this[kDispatches])
- }
-
- async [kClose] () {
- await promisify(this[kOriginalClose])()
- this[kConnected] = 0
- this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
- }
+function createDefaultHttpClient() {
+ return (0, nodeHttpClient_js_1.createNodeHttpClient)();
}
-
-module.exports = MockClient
-
+//# sourceMappingURL=defaultHttpClient.js.map
/***/ }),
-/***/ 12673:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { UndiciError } = __nccwpck_require__(53959)
+/***/ 30596:
+/***/ ((__unused_webpack_module, exports) => {
-class MockNotMatchedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, MockNotMatchedError)
- this.name = 'MockNotMatchedError'
- this.message = message || 'The request does not match any registered mock dispatches'
- this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
- }
-}
-module.exports = {
- MockNotMatchedError
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createHttpHeaders = createHttpHeaders;
+function normalizeName(name) {
+ return name.toLowerCase();
}
-
-
-/***/ }),
-
-/***/ 5843:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(73193)
-const {
- kDispatches,
- kDispatchKey,
- kDefaultHeaders,
- kDefaultTrailers,
- kContentLength,
- kMockDispatch
-} = __nccwpck_require__(52305)
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-const { buildURL } = __nccwpck_require__(89500)
-
-/**
- * Defines the scope API for an interceptor reply
- */
-class MockScope {
- constructor (mockDispatch) {
- this[kMockDispatch] = mockDispatch
- }
-
- /**
- * Delay a reply by a set amount in ms.
- */
- delay (waitInMs) {
- if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {
- throw new InvalidArgumentError('waitInMs must be a valid integer > 0')
- }
-
- this[kMockDispatch].delay = waitInMs
- return this
- }
-
- /**
- * For a defined reply, never mark as consumed.
- */
- persist () {
- this[kMockDispatch].persist = true
- return this
- }
-
- /**
- * Allow one to define a reply for a set amount of matching requests.
- */
- times (repeatTimes) {
- if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
- throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')
+function* headerIterator(map) {
+ for (const entry of map.values()) {
+ yield [entry.name, entry.value];
}
-
- this[kMockDispatch].times = repeatTimes
- return this
- }
}
-
-/**
- * Defines an interceptor for a Mock
- */
-class MockInterceptor {
- constructor (opts, mockDispatches) {
- if (typeof opts !== 'object') {
- throw new InvalidArgumentError('opts must be an object')
- }
- if (typeof opts.path === 'undefined') {
- throw new InvalidArgumentError('opts.path must be defined')
- }
- if (typeof opts.method === 'undefined') {
- opts.method = 'GET'
- }
- // See https://github.com/nodejs/undici/issues/1245
- // As per RFC 3986, clients are not supposed to send URI
- // fragments to servers when they retrieve a document,
- if (typeof opts.path === 'string') {
- if (opts.query) {
- opts.path = buildURL(opts.path, opts.query)
- } else {
- // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811
- const parsedURL = new URL(opts.path, 'data://')
- opts.path = parsedURL.pathname + parsedURL.search
- }
+class HttpHeadersImpl {
+ constructor(rawHeaders) {
+ this._headersMap = new Map();
+ if (rawHeaders) {
+ for (const headerName of Object.keys(rawHeaders)) {
+ this.set(headerName, rawHeaders[headerName]);
+ }
+ }
}
- if (typeof opts.method === 'string') {
- opts.method = opts.method.toUpperCase()
+ /**
+ * Set a header in this collection with the provided name and value. The name is
+ * case-insensitive.
+ * @param name - The name of the header to set. This value is case-insensitive.
+ * @param value - The value of the header to set.
+ */
+ set(name, value) {
+ this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
}
-
- this[kDispatchKey] = buildKey(opts)
- this[kDispatches] = mockDispatches
- this[kDefaultHeaders] = {}
- this[kDefaultTrailers] = {}
- this[kContentLength] = false
- }
-
- createMockScopeDispatchData (statusCode, data, responseOptions = {}) {
- const responseData = getResponseData(data)
- const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}
- const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }
- const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }
-
- return { statusCode, data, headers, trailers }
- }
-
- validateReplyParameters (statusCode, data, responseOptions) {
- if (typeof statusCode === 'undefined') {
- throw new InvalidArgumentError('statusCode must be defined')
+ /**
+ * Get the header value for the provided header name, or undefined if no header exists in this
+ * collection with the provided name.
+ * @param name - The name of the header. This value is case-insensitive.
+ */
+ get(name) {
+ var _a;
+ return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value;
}
- if (typeof data === 'undefined') {
- throw new InvalidArgumentError('data must be defined')
+ /**
+ * Get whether or not this header collection contains a header entry for the provided header name.
+ * @param name - The name of the header to set. This value is case-insensitive.
+ */
+ has(name) {
+ return this._headersMap.has(normalizeName(name));
}
- if (typeof responseOptions !== 'object') {
- throw new InvalidArgumentError('responseOptions must be an object')
+ /**
+ * Remove the header with the provided headerName.
+ * @param name - The name of the header to remove.
+ */
+ delete(name) {
+ this._headersMap.delete(normalizeName(name));
}
- }
-
- /**
- * Mock an undici request with a defined reply.
- */
- reply (replyData) {
- // Values of reply aren't available right now as they
- // can only be available when the reply callback is invoked.
- if (typeof replyData === 'function') {
- // We'll first wrap the provided callback in another function,
- // this function will properly resolve the data from the callback
- // when invoked.
- const wrappedDefaultsCallback = (opts) => {
- // Our reply options callback contains the parameter for statusCode, data and options.
- const resolvedData = replyData(opts)
-
- // Check if it is in the right format
- if (typeof resolvedData !== 'object') {
- throw new InvalidArgumentError('reply options callback must return an object')
+ /**
+ * Get the JSON object representation of this HTTP header collection.
+ */
+ toJSON(options = {}) {
+ const result = {};
+ if (options.preserveCase) {
+ for (const entry of this._headersMap.values()) {
+ result[entry.name] = entry.value;
+ }
}
-
- const { statusCode, data = '', responseOptions = {} } = resolvedData
- this.validateReplyParameters(statusCode, data, responseOptions)
- // Since the values can be obtained immediately we return them
- // from this higher order function that will be resolved later.
- return {
- ...this.createMockScopeDispatchData(statusCode, data, responseOptions)
+ else {
+ for (const [normalizedName, entry] of this._headersMap) {
+ result[normalizedName] = entry.value;
+ }
}
- }
-
- // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)
- return new MockScope(newMockDispatch)
- }
-
- // We can have either one or three parameters, if we get here,
- // we should have 1-3 parameters. So we spread the arguments of
- // this function to obtain the parameters, since replyData will always
- // just be the statusCode.
- const [statusCode, data = '', responseOptions = {}] = [...arguments]
- this.validateReplyParameters(statusCode, data, responseOptions)
-
- // Send in-already provided data like usual
- const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions)
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)
- return new MockScope(newMockDispatch)
- }
-
- /**
- * Mock an undici request with a defined error.
- */
- replyWithError (error) {
- if (typeof error === 'undefined') {
- throw new InvalidArgumentError('error must be defined')
- }
-
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })
- return new MockScope(newMockDispatch)
- }
-
- /**
- * Set default reply headers on the interceptor for subsequent replies
- */
- defaultReplyHeaders (headers) {
- if (typeof headers === 'undefined') {
- throw new InvalidArgumentError('headers must be defined')
+ return result;
}
-
- this[kDefaultHeaders] = headers
- return this
- }
-
- /**
- * Set default reply trailers on the interceptor for subsequent replies
- */
- defaultReplyTrailers (trailers) {
- if (typeof trailers === 'undefined') {
- throw new InvalidArgumentError('trailers must be defined')
+ /**
+ * Get the string representation of this HTTP header collection.
+ */
+ toString() {
+ return JSON.stringify(this.toJSON({ preserveCase: true }));
+ }
+ /**
+ * Iterate over tuples of header [name, value] pairs.
+ */
+ [Symbol.iterator]() {
+ return headerIterator(this._headersMap);
}
-
- this[kDefaultTrailers] = trailers
- return this
- }
-
- /**
- * Set reply content length header for replies on the interceptor
- */
- replyContentLength () {
- this[kContentLength] = true
- return this
- }
}
-
-module.exports.MockInterceptor = MockInterceptor
-module.exports.MockScope = MockScope
-
-
-/***/ }),
-
-/***/ 36480:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { promisify } = __nccwpck_require__(39023)
-const Pool = __nccwpck_require__(44288)
-const { buildMockDispatch } = __nccwpck_require__(73193)
-const {
- kDispatches,
- kMockAgent,
- kClose,
- kOriginalClose,
- kOrigin,
- kOriginalDispatch,
- kConnected
-} = __nccwpck_require__(52305)
-const { MockInterceptor } = __nccwpck_require__(5843)
-const Symbols = __nccwpck_require__(68031)
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-
/**
- * MockPool provides an API that extends the Pool to influence the mockDispatches.
+ * Creates an object that satisfies the `HttpHeaders` interface.
+ * @param rawHeaders - A simple object representing initial headers
*/
-class MockPool extends Pool {
- constructor (origin, opts) {
- super(origin, opts)
+function createHttpHeaders(rawHeaders) {
+ return new HttpHeadersImpl(rawHeaders);
+}
+//# sourceMappingURL=httpHeaders.js.map
- if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
- }
+/***/ }),
- this[kMockAgent] = opts.agent
- this[kOrigin] = origin
- this[kDispatches] = []
- this[kConnected] = 1
- this[kOriginalDispatch] = this.dispatch
- this[kOriginalClose] = this.close.bind(this)
+/***/ 95582:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this.dispatch = buildMockDispatch.call(this)
- this.close = this[kClose]
- }
- get [Symbols.kConnected] () {
- return this[kConnected]
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createFileFromStream = exports.createFile = exports.auxiliaryAuthenticationHeaderPolicyName = exports.auxiliaryAuthenticationHeaderPolicy = exports.ndJsonPolicyName = exports.ndJsonPolicy = exports.bearerTokenAuthenticationPolicyName = exports.bearerTokenAuthenticationPolicy = exports.formDataPolicyName = exports.formDataPolicy = exports.tlsPolicyName = exports.tlsPolicy = exports.userAgentPolicyName = exports.userAgentPolicy = exports.defaultRetryPolicy = exports.tracingPolicyName = exports.tracingPolicy = exports.retryPolicy = exports.throttlingRetryPolicyName = exports.throttlingRetryPolicy = exports.systemErrorRetryPolicyName = exports.systemErrorRetryPolicy = exports.redirectPolicyName = exports.redirectPolicy = exports.getDefaultProxySettings = exports.proxyPolicyName = exports.proxyPolicy = exports.multipartPolicyName = exports.multipartPolicy = exports.logPolicyName = exports.logPolicy = exports.setClientRequestIdPolicyName = exports.setClientRequestIdPolicy = exports.exponentialRetryPolicyName = exports.exponentialRetryPolicy = exports.decompressResponsePolicyName = exports.decompressResponsePolicy = exports.isRestError = exports.RestError = exports.createPipelineRequest = exports.createHttpHeaders = exports.createDefaultHttpClient = exports.createPipelineFromOptions = exports.createEmptyPipeline = void 0;
+var pipeline_js_1 = __nccwpck_require__(37050);
+Object.defineProperty(exports, "createEmptyPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createEmptyPipeline; } }));
+var createPipelineFromOptions_js_1 = __nccwpck_require__(1130);
+Object.defineProperty(exports, "createPipelineFromOptions", ({ enumerable: true, get: function () { return createPipelineFromOptions_js_1.createPipelineFromOptions; } }));
+var defaultHttpClient_js_1 = __nccwpck_require__(55316);
+Object.defineProperty(exports, "createDefaultHttpClient", ({ enumerable: true, get: function () { return defaultHttpClient_js_1.createDefaultHttpClient; } }));
+var httpHeaders_js_1 = __nccwpck_require__(30596);
+Object.defineProperty(exports, "createHttpHeaders", ({ enumerable: true, get: function () { return httpHeaders_js_1.createHttpHeaders; } }));
+var pipelineRequest_js_1 = __nccwpck_require__(82425);
+Object.defineProperty(exports, "createPipelineRequest", ({ enumerable: true, get: function () { return pipelineRequest_js_1.createPipelineRequest; } }));
+var restError_js_1 = __nccwpck_require__(97558);
+Object.defineProperty(exports, "RestError", ({ enumerable: true, get: function () { return restError_js_1.RestError; } }));
+Object.defineProperty(exports, "isRestError", ({ enumerable: true, get: function () { return restError_js_1.isRestError; } }));
+var decompressResponsePolicy_js_1 = __nccwpck_require__(13299);
+Object.defineProperty(exports, "decompressResponsePolicy", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicy; } }));
+Object.defineProperty(exports, "decompressResponsePolicyName", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicyName; } }));
+var exponentialRetryPolicy_js_1 = __nccwpck_require__(43048);
+Object.defineProperty(exports, "exponentialRetryPolicy", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicy; } }));
+Object.defineProperty(exports, "exponentialRetryPolicyName", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; } }));
+var setClientRequestIdPolicy_js_1 = __nccwpck_require__(63866);
+Object.defineProperty(exports, "setClientRequestIdPolicy", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicy; } }));
+Object.defineProperty(exports, "setClientRequestIdPolicyName", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicyName; } }));
+var logPolicy_js_1 = __nccwpck_require__(19937);
+Object.defineProperty(exports, "logPolicy", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicy; } }));
+Object.defineProperty(exports, "logPolicyName", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicyName; } }));
+var multipartPolicy_js_1 = __nccwpck_require__(77915);
+Object.defineProperty(exports, "multipartPolicy", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicy; } }));
+Object.defineProperty(exports, "multipartPolicyName", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicyName; } }));
+var proxyPolicy_js_1 = __nccwpck_require__(73723);
+Object.defineProperty(exports, "proxyPolicy", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicy; } }));
+Object.defineProperty(exports, "proxyPolicyName", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicyName; } }));
+Object.defineProperty(exports, "getDefaultProxySettings", ({ enumerable: true, get: function () { return proxyPolicy_js_1.getDefaultProxySettings; } }));
+var redirectPolicy_js_1 = __nccwpck_require__(86947);
+Object.defineProperty(exports, "redirectPolicy", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicy; } }));
+Object.defineProperty(exports, "redirectPolicyName", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicyName; } }));
+var systemErrorRetryPolicy_js_1 = __nccwpck_require__(14298);
+Object.defineProperty(exports, "systemErrorRetryPolicy", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; } }));
+Object.defineProperty(exports, "systemErrorRetryPolicyName", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; } }));
+var throttlingRetryPolicy_js_1 = __nccwpck_require__(96352);
+Object.defineProperty(exports, "throttlingRetryPolicy", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicy; } }));
+Object.defineProperty(exports, "throttlingRetryPolicyName", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; } }));
+var retryPolicy_js_1 = __nccwpck_require__(85001);
+Object.defineProperty(exports, "retryPolicy", ({ enumerable: true, get: function () { return retryPolicy_js_1.retryPolicy; } }));
+var tracingPolicy_js_1 = __nccwpck_require__(14113);
+Object.defineProperty(exports, "tracingPolicy", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicy; } }));
+Object.defineProperty(exports, "tracingPolicyName", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicyName; } }));
+var defaultRetryPolicy_js_1 = __nccwpck_require__(47494);
+Object.defineProperty(exports, "defaultRetryPolicy", ({ enumerable: true, get: function () { return defaultRetryPolicy_js_1.defaultRetryPolicy; } }));
+var userAgentPolicy_js_1 = __nccwpck_require__(69795);
+Object.defineProperty(exports, "userAgentPolicy", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicy; } }));
+Object.defineProperty(exports, "userAgentPolicyName", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicyName; } }));
+var tlsPolicy_js_1 = __nccwpck_require__(39370);
+Object.defineProperty(exports, "tlsPolicy", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicy; } }));
+Object.defineProperty(exports, "tlsPolicyName", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicyName; } }));
+var formDataPolicy_js_1 = __nccwpck_require__(37997);
+Object.defineProperty(exports, "formDataPolicy", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicy; } }));
+Object.defineProperty(exports, "formDataPolicyName", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicyName; } }));
+var bearerTokenAuthenticationPolicy_js_1 = __nccwpck_require__(42081);
+Object.defineProperty(exports, "bearerTokenAuthenticationPolicy", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicy; } }));
+Object.defineProperty(exports, "bearerTokenAuthenticationPolicyName", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicyName; } }));
+var ndJsonPolicy_js_1 = __nccwpck_require__(7303);
+Object.defineProperty(exports, "ndJsonPolicy", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicy; } }));
+Object.defineProperty(exports, "ndJsonPolicyName", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicyName; } }));
+var auxiliaryAuthenticationHeaderPolicy_js_1 = __nccwpck_require__(7250);
+Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicy", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicy; } }));
+Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicyName", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicyName; } }));
+var file_js_1 = __nccwpck_require__(8581);
+Object.defineProperty(exports, "createFile", ({ enumerable: true, get: function () { return file_js_1.createFile; } }));
+Object.defineProperty(exports, "createFileFromStream", ({ enumerable: true, get: function () { return file_js_1.createFileFromStream; } }));
+//# sourceMappingURL=index.js.map
- /**
- * Sets up the base interceptor for mocking replies from undici.
- */
- intercept (opts) {
- return new MockInterceptor(opts, this[kDispatches])
- }
+/***/ }),
- async [kClose] () {
- await promisify(this[kOriginalClose])()
- this[kConnected] = 0
- this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
- }
-}
+/***/ 58564:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = MockPool
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logger = void 0;
+const logger_1 = __nccwpck_require__(50143);
+exports.logger = (0, logger_1.createClientLogger)("core-rest-pipeline");
+//# sourceMappingURL=log.js.map
/***/ }),
-/***/ 52305:
-/***/ ((module) => {
-
+/***/ 56583:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = {
- kAgent: Symbol('agent'),
- kOptions: Symbol('options'),
- kFactory: Symbol('factory'),
- kDispatches: Symbol('dispatches'),
- kDispatchKey: Symbol('dispatch key'),
- kDefaultHeaders: Symbol('default headers'),
- kDefaultTrailers: Symbol('default trailers'),
- kContentLength: Symbol('content length'),
- kMockAgent: Symbol('mock agent'),
- kMockAgentSet: Symbol('mock agent set'),
- kMockAgentGet: Symbol('mock agent get'),
- kMockDispatch: Symbol('mock dispatch'),
- kClose: Symbol('close'),
- kOriginalClose: Symbol('original agent close'),
- kOrigin: Symbol('origin'),
- kIsMockActive: Symbol('is mock active'),
- kNetConnect: Symbol('net connect'),
- kGetNetConnect: Symbol('get net connect'),
- kConnected: Symbol('connected')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getBodyLength = getBodyLength;
+exports.createNodeHttpClient = createNodeHttpClient;
+const tslib_1 = __nccwpck_require__(94176);
+const http = tslib_1.__importStar(__nccwpck_require__(37067));
+const https = tslib_1.__importStar(__nccwpck_require__(44708));
+const zlib = tslib_1.__importStar(__nccwpck_require__(38522));
+const node_stream_1 = __nccwpck_require__(57075);
+const abort_controller_1 = __nccwpck_require__(92242);
+const httpHeaders_js_1 = __nccwpck_require__(30596);
+const restError_js_1 = __nccwpck_require__(97558);
+const log_js_1 = __nccwpck_require__(58564);
+const DEFAULT_TLS_SETTINGS = {};
+function isReadableStream(body) {
+ return body && typeof body.pipe === "function";
+}
+function isStreamComplete(stream) {
+ if (stream.readable === false) {
+ return Promise.resolve();
+ }
+ return new Promise((resolve) => {
+ const handler = () => {
+ resolve();
+ stream.removeListener("close", handler);
+ stream.removeListener("end", handler);
+ stream.removeListener("error", handler);
+ };
+ stream.on("close", handler);
+ stream.on("end", handler);
+ stream.on("error", handler);
+ });
+}
+function isArrayBuffer(body) {
+ return body && typeof body.byteLength === "number";
+}
+class ReportTransform extends node_stream_1.Transform {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
+ _transform(chunk, _encoding, callback) {
+ this.push(chunk);
+ this.loadedBytes += chunk.length;
+ try {
+ this.progressCallback({ loadedBytes: this.loadedBytes });
+ callback();
+ }
+ catch (e) {
+ callback(e);
+ }
+ }
+ constructor(progressCallback) {
+ super();
+ this.loadedBytes = 0;
+ this.progressCallback = progressCallback;
+ }
+}
+/**
+ * A HttpClient implementation that uses Node's "https" module to send HTTPS requests.
+ * @internal
+ */
+class NodeHttpClient {
+ constructor() {
+ this.cachedHttpsAgents = new WeakMap();
+ }
+ /**
+ * Makes a request over an underlying transport layer and returns the response.
+ * @param request - The request to be made.
+ */
+ async sendRequest(request) {
+ var _a, _b, _c;
+ const abortController = new AbortController();
+ let abortListener;
+ if (request.abortSignal) {
+ if (request.abortSignal.aborted) {
+ throw new abort_controller_1.AbortError("The operation was aborted.");
+ }
+ abortListener = (event) => {
+ if (event.type === "abort") {
+ abortController.abort();
+ }
+ };
+ request.abortSignal.addEventListener("abort", abortListener);
+ }
+ if (request.timeout > 0) {
+ setTimeout(() => {
+ abortController.abort();
+ }, request.timeout);
+ }
+ const acceptEncoding = request.headers.get("Accept-Encoding");
+ const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate"));
+ let body = typeof request.body === "function" ? request.body() : request.body;
+ if (body && !request.headers.has("Content-Length")) {
+ const bodyLength = getBodyLength(body);
+ if (bodyLength !== null) {
+ request.headers.set("Content-Length", bodyLength);
+ }
+ }
+ let responseStream;
+ try {
+ if (body && request.onUploadProgress) {
+ const onUploadProgress = request.onUploadProgress;
+ const uploadReportStream = new ReportTransform(onUploadProgress);
+ uploadReportStream.on("error", (e) => {
+ log_js_1.logger.error("Error in upload progress", e);
+ });
+ if (isReadableStream(body)) {
+ body.pipe(uploadReportStream);
+ }
+ else {
+ uploadReportStream.end(body);
+ }
+ body = uploadReportStream;
+ }
+ const res = await this.makeRequest(request, abortController, body);
+ const headers = getResponseHeaders(res);
+ const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
+ const response = {
+ status,
+ headers,
+ request,
+ };
+ // Responses to HEAD must not have a body.
+ // If they do return a body, that body must be ignored.
+ if (request.method === "HEAD") {
+ // call resume() and not destroy() to avoid closing the socket
+ // and losing keep alive
+ res.resume();
+ return response;
+ }
+ responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
+ const onDownloadProgress = request.onDownloadProgress;
+ if (onDownloadProgress) {
+ const downloadReportStream = new ReportTransform(onDownloadProgress);
+ downloadReportStream.on("error", (e) => {
+ log_js_1.logger.error("Error in download progress", e);
+ });
+ responseStream.pipe(downloadReportStream);
+ responseStream = downloadReportStream;
+ }
+ if (
+ // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
+ ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) ||
+ ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))) {
+ response.readableStreamBody = responseStream;
+ }
+ else {
+ response.bodyAsText = await streamToText(responseStream);
+ }
+ return response;
+ }
+ finally {
+ // clean up event listener
+ if (request.abortSignal && abortListener) {
+ let uploadStreamDone = Promise.resolve();
+ if (isReadableStream(body)) {
+ uploadStreamDone = isStreamComplete(body);
+ }
+ let downloadStreamDone = Promise.resolve();
+ if (isReadableStream(responseStream)) {
+ downloadStreamDone = isStreamComplete(responseStream);
+ }
+ Promise.all([uploadStreamDone, downloadStreamDone])
+ .then(() => {
+ var _a;
+ // eslint-disable-next-line promise/always-return
+ if (abortListener) {
+ (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
+ }
+ })
+ .catch((e) => {
+ log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e);
+ });
+ }
+ }
+ }
+ makeRequest(request, abortController, body) {
+ var _a;
+ const url = new URL(request.url);
+ const isInsecure = url.protocol !== "https:";
+ if (isInsecure && !request.allowInsecureConnection) {
+ throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
+ }
+ const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure);
+ const options = {
+ agent,
+ hostname: url.hostname,
+ path: `${url.pathname}${url.search}`,
+ port: url.port,
+ method: request.method,
+ headers: request.headers.toJSON({ preserveCase: true }),
+ };
+ return new Promise((resolve, reject) => {
+ const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve);
+ req.once("error", (err) => {
+ var _a;
+ reject(new restError_js_1.RestError(err.message, { code: (_a = err.code) !== null && _a !== void 0 ? _a : restError_js_1.RestError.REQUEST_SEND_ERROR, request }));
+ });
+ abortController.signal.addEventListener("abort", () => {
+ const abortError = new abort_controller_1.AbortError("The operation was aborted.");
+ req.destroy(abortError);
+ reject(abortError);
+ });
+ if (body && isReadableStream(body)) {
+ body.pipe(req);
+ }
+ else if (body) {
+ if (typeof body === "string" || Buffer.isBuffer(body)) {
+ req.end(body);
+ }
+ else if (isArrayBuffer(body)) {
+ req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
+ }
+ else {
+ log_js_1.logger.error("Unrecognized body type", body);
+ reject(new restError_js_1.RestError("Unrecognized body type"));
+ }
+ }
+ else {
+ // streams don't like "undefined" being passed as data
+ req.end();
+ }
+ });
+ }
+ getOrCreateAgent(request, isInsecure) {
+ var _a;
+ const disableKeepAlive = request.disableKeepAlive;
+ // Handle Insecure requests first
+ if (isInsecure) {
+ if (disableKeepAlive) {
+ // keepAlive:false is the default so we don't need a custom Agent
+ return http.globalAgent;
+ }
+ if (!this.cachedHttpAgent) {
+ // If there is no cached agent create a new one and cache it.
+ this.cachedHttpAgent = new http.Agent({ keepAlive: true });
+ }
+ return this.cachedHttpAgent;
+ }
+ else {
+ if (disableKeepAlive && !request.tlsSettings) {
+ // When there are no tlsSettings and keepAlive is false
+ // we don't need a custom agent
+ return https.globalAgent;
+ }
+ // We use the tlsSettings to index cached clients
+ const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS;
+ // Get the cached agent or create a new one with the
+ // provided values for keepAlive and tlsSettings
+ let agent = this.cachedHttpsAgents.get(tlsSettings);
+ if (agent && agent.options.keepAlive === !disableKeepAlive) {
+ return agent;
+ }
+ log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent");
+ agent = new https.Agent(Object.assign({
+ // keepAlive is true if disableKeepAlive is false.
+ keepAlive: !disableKeepAlive }, tlsSettings));
+ this.cachedHttpsAgents.set(tlsSettings, agent);
+ return agent;
+ }
+ }
+}
+function getResponseHeaders(res) {
+ const headers = (0, httpHeaders_js_1.createHttpHeaders)();
+ for (const header of Object.keys(res.headers)) {
+ const value = res.headers[header];
+ if (Array.isArray(value)) {
+ if (value.length > 0) {
+ headers.set(header, value[0]);
+ }
+ }
+ else if (value) {
+ headers.set(header, value);
+ }
+ }
+ return headers;
+}
+function getDecodedResponseStream(stream, headers) {
+ const contentEncoding = headers.get("Content-Encoding");
+ if (contentEncoding === "gzip") {
+ const unzip = zlib.createGunzip();
+ stream.pipe(unzip);
+ return unzip;
+ }
+ else if (contentEncoding === "deflate") {
+ const inflate = zlib.createInflate();
+ stream.pipe(inflate);
+ return inflate;
+ }
+ return stream;
+}
+function streamToText(stream) {
+ return new Promise((resolve, reject) => {
+ const buffer = [];
+ stream.on("data", (chunk) => {
+ if (Buffer.isBuffer(chunk)) {
+ buffer.push(chunk);
+ }
+ else {
+ buffer.push(Buffer.from(chunk));
+ }
+ });
+ stream.on("end", () => {
+ resolve(Buffer.concat(buffer).toString("utf8"));
+ });
+ stream.on("error", (e) => {
+ if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") {
+ reject(e);
+ }
+ else {
+ reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, {
+ code: restError_js_1.RestError.PARSE_ERROR,
+ }));
+ }
+ });
+ });
}
-
+/** @internal */
+function getBodyLength(body) {
+ if (!body) {
+ return 0;
+ }
+ else if (Buffer.isBuffer(body)) {
+ return body.length;
+ }
+ else if (isReadableStream(body)) {
+ return null;
+ }
+ else if (isArrayBuffer(body)) {
+ return body.byteLength;
+ }
+ else if (typeof body === "string") {
+ return Buffer.from(body).length;
+ }
+ else {
+ return null;
+ }
+}
+/**
+ * Create a new HttpClient instance for the NodeJS environment.
+ * @internal
+ */
+function createNodeHttpClient() {
+ return new NodeHttpClient();
+}
+//# sourceMappingURL=nodeHttpClient.js.map
/***/ }),
-/***/ 73193:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { MockNotMatchedError } = __nccwpck_require__(12673)
-const {
- kDispatches,
- kMockAgent,
- kOriginalDispatch,
- kOrigin,
- kGetNetConnect
-} = __nccwpck_require__(52305)
-const { buildURL, nop } = __nccwpck_require__(89500)
-const { STATUS_CODES } = __nccwpck_require__(58611)
-const {
- types: {
- isPromise
- }
-} = __nccwpck_require__(39023)
-
-function matchValue (match, value) {
- if (typeof match === 'string') {
- return match === value
- }
- if (match instanceof RegExp) {
- return match.test(value)
- }
- if (typeof match === 'function') {
- return match(value) === true
- }
- return false
-}
+/***/ 37050:
+/***/ ((__unused_webpack_module, exports) => {
-function lowerCaseEntries (headers) {
- return Object.fromEntries(
- Object.entries(headers).map(([headerName, headerValue]) => {
- return [headerName.toLocaleLowerCase(), headerValue]
- })
- )
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createEmptyPipeline = createEmptyPipeline;
+const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
/**
- * @param {import('../../index').Headers|string[]|Record} headers
- * @param {string} key
+ * A private implementation of Pipeline.
+ * Do not export this class from the package.
+ * @internal
*/
-function getHeaderByName (headers, key) {
- if (Array.isArray(headers)) {
- for (let i = 0; i < headers.length; i += 2) {
- if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
- return headers[i + 1]
- }
+class HttpPipeline {
+ constructor(policies) {
+ var _a;
+ this._policies = [];
+ this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : [];
+ this._orderedPolicies = undefined;
}
-
- return undefined
- } else if (typeof headers.get === 'function') {
- return headers.get(key)
- } else {
- return lowerCaseEntries(headers)[key.toLocaleLowerCase()]
- }
-}
-
-/** @param {string[]} headers */
-function buildHeadersFromArray (headers) { // fetch HeadersList
- const clone = headers.slice()
- const entries = []
- for (let index = 0; index < clone.length; index += 2) {
- entries.push([clone[index], clone[index + 1]])
- }
- return Object.fromEntries(entries)
-}
-
-function matchHeaders (mockDispatch, headers) {
- if (typeof mockDispatch.headers === 'function') {
- if (Array.isArray(headers)) { // fetch HeadersList
- headers = buildHeadersFromArray(headers)
+ addPolicy(policy, options = {}) {
+ if (options.phase && options.afterPhase) {
+ throw new Error("Policies inside a phase cannot specify afterPhase.");
+ }
+ if (options.phase && !ValidPhaseNames.has(options.phase)) {
+ throw new Error(`Invalid phase name: ${options.phase}`);
+ }
+ if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {
+ throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);
+ }
+ this._policies.push({
+ policy,
+ options,
+ });
+ this._orderedPolicies = undefined;
}
- return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
- }
- if (typeof mockDispatch.headers === 'undefined') {
- return true
- }
- if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {
- return false
- }
-
- for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {
- const headerValue = getHeaderByName(headers, matchHeaderName)
-
- if (!matchValue(matchHeaderValue, headerValue)) {
- return false
+ removePolicy(options) {
+ const removedPolicies = [];
+ this._policies = this._policies.filter((policyDescriptor) => {
+ if ((options.name && policyDescriptor.policy.name === options.name) ||
+ (options.phase && policyDescriptor.options.phase === options.phase)) {
+ removedPolicies.push(policyDescriptor.policy);
+ return false;
+ }
+ else {
+ return true;
+ }
+ });
+ this._orderedPolicies = undefined;
+ return removedPolicies;
}
- }
- return true
+ sendRequest(httpClient, request) {
+ const policies = this.getOrderedPolicies();
+ const pipeline = policies.reduceRight((next, policy) => {
+ return (req) => {
+ return policy.sendRequest(req, next);
+ };
+ }, (req) => httpClient.sendRequest(req));
+ return pipeline(request);
+ }
+ getOrderedPolicies() {
+ if (!this._orderedPolicies) {
+ this._orderedPolicies = this.orderPolicies();
+ }
+ return this._orderedPolicies;
+ }
+ clone() {
+ return new HttpPipeline(this._policies);
+ }
+ static create() {
+ return new HttpPipeline();
+ }
+ orderPolicies() {
+ /**
+ * The goal of this method is to reliably order pipeline policies
+ * based on their declared requirements when they were added.
+ *
+ * Order is first determined by phase:
+ *
+ * 1. Serialize Phase
+ * 2. Policies not in a phase
+ * 3. Deserialize Phase
+ * 4. Retry Phase
+ * 5. Sign Phase
+ *
+ * Within each phase, policies are executed in the order
+ * they were added unless they were specified to execute
+ * before/after other policies or after a particular phase.
+ *
+ * To determine the final order, we will walk the policy list
+ * in phase order multiple times until all dependencies are
+ * satisfied.
+ *
+ * `afterPolicies` are the set of policies that must be
+ * executed before a given policy. This requirement is
+ * considered satisfied when each of the listed policies
+ * have been scheduled.
+ *
+ * `beforePolicies` are the set of policies that must be
+ * executed after a given policy. Since this dependency
+ * can be expressed by converting it into a equivalent
+ * `afterPolicies` declarations, they are normalized
+ * into that form for simplicity.
+ *
+ * An `afterPhase` dependency is considered satisfied when all
+ * policies in that phase have scheduled.
+ *
+ */
+ const result = [];
+ // Track all policies we know about.
+ const policyMap = new Map();
+ function createPhase(name) {
+ return {
+ name,
+ policies: new Set(),
+ hasRun: false,
+ hasAfterPolicies: false,
+ };
+ }
+ // Track policies for each phase.
+ const serializePhase = createPhase("Serialize");
+ const noPhase = createPhase("None");
+ const deserializePhase = createPhase("Deserialize");
+ const retryPhase = createPhase("Retry");
+ const signPhase = createPhase("Sign");
+ // a list of phases in order
+ const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
+ // Small helper function to map phase name to each Phase
+ function getPhase(phase) {
+ if (phase === "Retry") {
+ return retryPhase;
+ }
+ else if (phase === "Serialize") {
+ return serializePhase;
+ }
+ else if (phase === "Deserialize") {
+ return deserializePhase;
+ }
+ else if (phase === "Sign") {
+ return signPhase;
+ }
+ else {
+ return noPhase;
+ }
+ }
+ // First walk each policy and create a node to track metadata.
+ for (const descriptor of this._policies) {
+ const policy = descriptor.policy;
+ const options = descriptor.options;
+ const policyName = policy.name;
+ if (policyMap.has(policyName)) {
+ throw new Error("Duplicate policy names not allowed in pipeline");
+ }
+ const node = {
+ policy,
+ dependsOn: new Set(),
+ dependants: new Set(),
+ };
+ if (options.afterPhase) {
+ node.afterPhase = getPhase(options.afterPhase);
+ node.afterPhase.hasAfterPolicies = true;
+ }
+ policyMap.set(policyName, node);
+ const phase = getPhase(options.phase);
+ phase.policies.add(node);
+ }
+ // Now that each policy has a node, connect dependency references.
+ for (const descriptor of this._policies) {
+ const { policy, options } = descriptor;
+ const policyName = policy.name;
+ const node = policyMap.get(policyName);
+ if (!node) {
+ throw new Error(`Missing node for policy ${policyName}`);
+ }
+ if (options.afterPolicies) {
+ for (const afterPolicyName of options.afterPolicies) {
+ const afterNode = policyMap.get(afterPolicyName);
+ if (afterNode) {
+ // Linking in both directions helps later
+ // when we want to notify dependants.
+ node.dependsOn.add(afterNode);
+ afterNode.dependants.add(node);
+ }
+ }
+ }
+ if (options.beforePolicies) {
+ for (const beforePolicyName of options.beforePolicies) {
+ const beforeNode = policyMap.get(beforePolicyName);
+ if (beforeNode) {
+ // To execute before another node, make it
+ // depend on the current node.
+ beforeNode.dependsOn.add(node);
+ node.dependants.add(beforeNode);
+ }
+ }
+ }
+ }
+ function walkPhase(phase) {
+ phase.hasRun = true;
+ // Sets iterate in insertion order
+ for (const node of phase.policies) {
+ if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
+ // If this node is waiting on a phase to complete,
+ // we need to skip it for now.
+ // Even if the phase is empty, we should wait for it
+ // to be walked to avoid re-ordering policies.
+ continue;
+ }
+ if (node.dependsOn.size === 0) {
+ // If there's nothing else we're waiting for, we can
+ // add this policy to the result list.
+ result.push(node.policy);
+ // Notify anything that depends on this policy that
+ // the policy has been scheduled.
+ for (const dependant of node.dependants) {
+ dependant.dependsOn.delete(node);
+ }
+ policyMap.delete(node.policy.name);
+ phase.policies.delete(node);
+ }
+ }
+ }
+ function walkPhases() {
+ for (const phase of orderedPhases) {
+ walkPhase(phase);
+ // if the phase isn't complete
+ if (phase.policies.size > 0 && phase !== noPhase) {
+ if (!noPhase.hasRun) {
+ // Try running noPhase to see if that unblocks this phase next tick.
+ // This can happen if a phase that happens before noPhase
+ // is waiting on a noPhase policy to complete.
+ walkPhase(noPhase);
+ }
+ // Don't proceed to the next phase until this phase finishes.
+ return;
+ }
+ if (phase.hasAfterPolicies) {
+ // Run any policies unblocked by this phase
+ walkPhase(noPhase);
+ }
+ }
+ }
+ // Iterate until we've put every node in the result list.
+ let iteration = 0;
+ while (policyMap.size > 0) {
+ iteration++;
+ const initialResultLength = result.length;
+ // Keep walking each phase in order until we can order every node.
+ walkPhases();
+ // The result list *should* get at least one larger each time
+ // after the first full pass.
+ // Otherwise, we're going to loop forever.
+ if (result.length <= initialResultLength && iteration > 1) {
+ throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
+ }
+ }
+ return result;
+ }
+}
+/**
+ * Creates a totally empty pipeline.
+ * Useful for testing or creating a custom one.
+ */
+function createEmptyPipeline() {
+ return HttpPipeline.create();
}
+//# sourceMappingURL=pipeline.js.map
-function safeUrl (path) {
- if (typeof path !== 'string') {
- return path
- }
+/***/ }),
- const pathSegments = path.split('?')
+/***/ 82425:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (pathSegments.length !== 2) {
- return path
- }
- const qp = new URLSearchParams(pathSegments.pop())
- qp.sort()
- return [...pathSegments, qp.toString()].join('?')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPipelineRequest = createPipelineRequest;
+const httpHeaders_js_1 = __nccwpck_require__(30596);
+const core_util_1 = __nccwpck_require__(30991);
+class PipelineRequestImpl {
+ constructor(options) {
+ var _a, _b, _c, _d, _e, _f, _g;
+ this.url = options.url;
+ this.body = options.body;
+ this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)();
+ this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET";
+ this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0;
+ this.multipartBody = options.multipartBody;
+ this.formData = options.formData;
+ this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false;
+ this.proxySettings = options.proxySettings;
+ this.streamResponseStatusCodes = options.streamResponseStatusCodes;
+ this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false;
+ this.abortSignal = options.abortSignal;
+ this.tracingOptions = options.tracingOptions;
+ this.onUploadProgress = options.onUploadProgress;
+ this.onDownloadProgress = options.onDownloadProgress;
+ this.requestId = options.requestId || (0, core_util_1.randomUUID)();
+ this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false;
+ this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false;
+ }
}
-
-function matchKey (mockDispatch, { path, method, body, headers }) {
- const pathMatch = matchValue(mockDispatch.path, path)
- const methodMatch = matchValue(mockDispatch.method, method)
- const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true
- const headersMatch = matchHeaders(mockDispatch, headers)
- return pathMatch && methodMatch && bodyMatch && headersMatch
+/**
+ * Creates a new pipeline request with the given options.
+ * This method is to allow for the easy setting of default values and not required.
+ * @param options - The options to create the request with.
+ */
+function createPipelineRequest(options) {
+ return new PipelineRequestImpl(options);
}
+//# sourceMappingURL=pipelineRequest.js.map
-function getResponseData (data) {
- if (Buffer.isBuffer(data)) {
- return data
- } else if (typeof data === 'object') {
- return JSON.stringify(data)
- } else {
- return data.toString()
- }
-}
+/***/ }),
-function getMockDispatch (mockDispatches, key) {
- const basePath = key.query ? buildURL(key.path, key.query) : key.path
- const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
+/***/ 7250:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // Match path
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
- }
- // Match method
- matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.auxiliaryAuthenticationHeaderPolicyName = void 0;
+exports.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy;
+const tokenCycler_js_1 = __nccwpck_require__(82534);
+const log_js_1 = __nccwpck_require__(58564);
+/**
+ * The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
+ */
+exports.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
+const AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
+async function sendAuthorizeRequest(options) {
+ var _a, _b;
+ const { scopes, getAccessToken, request } = options;
+ const getTokenOptions = {
+ abortSignal: request.abortSignal,
+ tracingOptions: request.tracingOptions,
+ };
+ return (_b = (_a = (await getAccessToken(scopes, getTokenOptions))) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : "";
+}
+/**
+ * A policy for external tokens to `x-ms-authorization-auxiliary` header.
+ * This header will be used when creating a cross-tenant application we may need to handle authentication requests
+ * for resources that are in different tenants.
+ * You could see [ARM docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
+ */
+function auxiliaryAuthenticationHeaderPolicy(options) {
+ const { credentials, scopes } = options;
+ const logger = options.logger || log_js_1.logger;
+ const tokenCyclerMap = new WeakMap();
+ return {
+ name: exports.auxiliaryAuthenticationHeaderPolicyName,
+ async sendRequest(request, next) {
+ if (!request.url.toLowerCase().startsWith("https://")) {
+ throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
+ }
+ if (!credentials || credentials.length === 0) {
+ logger.info(`${exports.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
+ return next(request);
+ }
+ const tokenPromises = [];
+ for (const credential of credentials) {
+ let getAccessToken = tokenCyclerMap.get(credential);
+ if (!getAccessToken) {
+ getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential);
+ tokenCyclerMap.set(credential, getAccessToken);
+ }
+ tokenPromises.push(sendAuthorizeRequest({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ getAccessToken,
+ logger,
+ }));
+ }
+ const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
+ if (auxiliaryTokens.length === 0) {
+ logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
+ return next(request);
+ }
+ request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=auxiliaryAuthenticationHeaderPolicy.js.map
- // Match body
- matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`)
- }
+/***/ }),
- // Match headers
- matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)
- }
+/***/ 42081:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return matchedMockDispatches[0]
-}
-function addMockDispatch (mockDispatches, key, data) {
- const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
- const replyData = typeof data === 'function' ? { callback: data } : { ...data }
- const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
- mockDispatches.push(newMockDispatch)
- return newMockDispatch
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.bearerTokenAuthenticationPolicyName = void 0;
+exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy;
+exports.parseChallenges = parseChallenges;
+const tokenCycler_js_1 = __nccwpck_require__(82534);
+const log_js_1 = __nccwpck_require__(58564);
+const restError_js_1 = __nccwpck_require__(97558);
+/**
+ * The programmatic identifier of the bearerTokenAuthenticationPolicy.
+ */
+exports.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
+/**
+ * Try to send the given request.
+ *
+ * When a response is received, returns a tuple of the response received and, if the response was received
+ * inside a thrown RestError, the RestError that was thrown.
+ *
+ * Otherwise, if an error was thrown while sending the request that did not provide an underlying response, it
+ * will be rethrown.
+ */
+async function trySendRequest(request, next) {
+ try {
+ return [await next(request), undefined];
+ }
+ catch (e) {
+ if ((0, restError_js_1.isRestError)(e) && e.response) {
+ return [e.response, e];
+ }
+ else {
+ throw e;
+ }
+ }
}
-
-function deleteMockDispatch (mockDispatches, key) {
- const index = mockDispatches.findIndex(dispatch => {
- if (!dispatch.consumed) {
- return false
+/**
+ * Default authorize request handler
+ */
+async function defaultAuthorizeRequest(options) {
+ const { scopes, getAccessToken, request } = options;
+ // Enable CAE true by default
+ const getTokenOptions = {
+ abortSignal: request.abortSignal,
+ tracingOptions: request.tracingOptions,
+ enableCae: true,
+ };
+ const accessToken = await getAccessToken(scopes, getTokenOptions);
+ if (accessToken) {
+ options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
}
- return matchKey(dispatch, key)
- })
- if (index !== -1) {
- mockDispatches.splice(index, 1)
- }
}
-
-function buildKey (opts) {
- const { path, method, body, headers, query } = opts
- return {
- path,
- method,
- body,
- headers,
- query
- }
+/**
+ * We will retrieve the challenge only if the response status code was 401,
+ * and if the response contained the header "WWW-Authenticate" with a non-empty value.
+ */
+function isChallengeResponse(response) {
+ return response.status === 401 && response.headers.has("WWW-Authenticate");
}
-
-function generateKeyValues (data) {
- return Object.entries(data).reduce((keyValuePairs, [key, value]) => [
- ...keyValuePairs,
- Buffer.from(`${key}`),
- Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)
- ], [])
+/**
+ * Re-authorize the request for CAE challenge.
+ * The response containing the challenge is `options.response`.
+ * If this method returns true, the underlying request will be sent once again.
+ */
+async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) {
+ var _a;
+ const { scopes } = onChallengeOptions;
+ const accessToken = await onChallengeOptions.getAccessToken(scopes, {
+ enableCae: true,
+ claims: caeClaims,
+ });
+ if (!accessToken) {
+ return false;
+ }
+ onChallengeOptions.request.headers.set("Authorization", `${(_a = accessToken.tokenType) !== null && _a !== void 0 ? _a : "Bearer"} ${accessToken.token}`);
+ return true;
}
-
/**
- * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
- * @param {number} statusCode
+ * A policy that can request a token from a TokenCredential implementation and
+ * then apply it to the Authorization header of a request as a Bearer token.
*/
-function getStatusText (statusCode) {
- return STATUS_CODES[statusCode] || 'unknown'
+function bearerTokenAuthenticationPolicy(options) {
+ var _a, _b, _c;
+ const { credential, scopes, challengeCallbacks } = options;
+ const logger = options.logger || log_js_1.logger;
+ const callbacks = {
+ authorizeRequest: (_b = (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) === null || _a === void 0 ? void 0 : _a.bind(challengeCallbacks)) !== null && _b !== void 0 ? _b : defaultAuthorizeRequest,
+ authorizeRequestOnChallenge: (_c = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge) === null || _c === void 0 ? void 0 : _c.bind(challengeCallbacks),
+ };
+ // This function encapsulates the entire process of reliably retrieving the token
+ // The options are left out of the public API until there's demand to configure this.
+ // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`
+ // in order to pass through the `options` object.
+ const getAccessToken = credential
+ ? (0, tokenCycler_js_1.createTokenCycler)(credential /* , options */)
+ : () => Promise.resolve(null);
+ return {
+ name: exports.bearerTokenAuthenticationPolicyName,
+ /**
+ * If there's no challenge parameter:
+ * - It will try to retrieve the token using the cache, or the credential's getToken.
+ * - Then it will try the next policy with or without the retrieved token.
+ *
+ * It uses the challenge parameters to:
+ * - Skip a first attempt to get the token from the credential if there's no cached token,
+ * since it expects the token to be retrievable only after the challenge.
+ * - Prepare the outgoing request if the `prepareRequest` method has been provided.
+ * - Send an initial request to receive the challenge if it fails.
+ * - Process a challenge if the response contains it.
+ * - Retrieve a token with the challenge information, then re-send the request.
+ */
+ async sendRequest(request, next) {
+ if (!request.url.toLowerCase().startsWith("https://")) {
+ throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
+ }
+ await callbacks.authorizeRequest({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ getAccessToken,
+ logger,
+ });
+ let response;
+ let error;
+ let shouldSendRequest;
+ [response, error] = await trySendRequest(request, next);
+ if (isChallengeResponse(response)) {
+ let claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
+ // Handle CAE by default when receive CAE claim
+ if (claims) {
+ let parsedClaim;
+ // Return the response immediately if claims is not a valid base64 encoded string
+ try {
+ parsedClaim = atob(claims);
+ }
+ catch (e) {
+ logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
+ return response;
+ }
+ shouldSendRequest = await authorizeRequestOnCaeChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ response,
+ request,
+ getAccessToken,
+ logger,
+ }, parsedClaim);
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ }
+ else if (callbacks.authorizeRequestOnChallenge) {
+ // Handle custom challenges when client provides custom callback
+ shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ response,
+ getAccessToken,
+ logger,
+ });
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ // If we get another CAE Claim, we will handle it by default and return whatever value we receive for this
+ if (isChallengeResponse(response)) {
+ claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
+ if (claims) {
+ let parsedClaim;
+ try {
+ parsedClaim = atob(claims);
+ }
+ catch (e) {
+ logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
+ return response;
+ }
+ shouldSendRequest = await authorizeRequestOnCaeChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ response,
+ request,
+ getAccessToken,
+ logger,
+ }, parsedClaim);
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ }
+ }
+ }
+ }
+ if (error) {
+ throw error;
+ }
+ else {
+ return response;
+ }
+ },
+ };
}
-
-async function getResponse (body) {
- const buffers = []
- for await (const data of body) {
- buffers.push(data)
- }
- return Buffer.concat(buffers).toString('utf8')
+/**
+ * Converts: `Bearer a="b", c="d", Pop e="f", g="h"`.
+ * Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`.
+ *
+ * @internal
+ */
+function parseChallenges(challenges) {
+ // Challenge regex seperates the string to individual challenges with different schemes in the format `Scheme a="b", c=d`
+ // The challenge regex captures parameteres with either quotes values or unquoted values
+ const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g;
+ // Parameter regex captures the claims group removed from the scheme in the format `a="b"` and `c="d"`
+ // CAE challenge always have quoted parameters. For more reference, https://learn.microsoft.com/entra/identity-platform/claims-challenge
+ const paramRegex = /(\w+)="([^"]*)"/g;
+ const parsedChallenges = [];
+ let match;
+ // Iterate over each challenge match
+ while ((match = challengeRegex.exec(challenges)) !== null) {
+ const scheme = match[1];
+ const paramsString = match[2];
+ const params = {};
+ let paramMatch;
+ // Iterate over each parameter match
+ while ((paramMatch = paramRegex.exec(paramsString)) !== null) {
+ params[paramMatch[1]] = paramMatch[2];
+ }
+ parsedChallenges.push({ scheme, params });
+ }
+ return parsedChallenges;
}
-
/**
- * Mock dispatch function used to simulate undici dispatches
+ * Parse a pipeline response and look for a CAE challenge with "Bearer" scheme
+ * Return the value in the header without parsing the challenge
+ * @internal
*/
-function mockDispatch (opts, handler) {
- // Get mock dispatch from built key
- const key = buildKey(opts)
- const mockDispatch = getMockDispatch(this[kDispatches], key)
-
- mockDispatch.timesInvoked++
-
- // Here's where we resolve a callback if a callback is present for the dispatch data.
- if (mockDispatch.data.callback) {
- mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }
- }
-
- // Parse mockDispatch data
- const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch
- const { timesInvoked, times } = mockDispatch
-
- // If it's used up and not persistent, mark as consumed
- mockDispatch.consumed = !persist && timesInvoked >= times
- mockDispatch.pending = timesInvoked < times
+function getCaeChallengeClaims(challenges) {
+ var _a;
+ if (!challenges) {
+ return;
+ }
+ // Find all challenges present in the header
+ const parsedChallenges = parseChallenges(challenges);
+ return (_a = parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")) === null || _a === void 0 ? void 0 : _a.params.claims;
+}
+//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map
- // If specified, trigger dispatch error
- if (error !== null) {
- deleteMockDispatch(this[kDispatches], key)
- handler.onError(error)
- return true
- }
+/***/ }),
- // Handle the request with a delay if necessary
- if (typeof delay === 'number' && delay > 0) {
- setTimeout(() => {
- handleReply(this[kDispatches])
- }, delay)
- } else {
- handleReply(this[kDispatches])
- }
+/***/ 13299:
+/***/ ((__unused_webpack_module, exports) => {
- function handleReply (mockDispatches, _data = data) {
- // fetch's HeadersList is a 1D string array
- const optsHeaders = Array.isArray(opts.headers)
- ? buildHeadersFromArray(opts.headers)
- : opts.headers
- const body = typeof _data === 'function'
- ? _data({ ...opts, headers: optsHeaders })
- : _data
- // util.types.isPromise is likely needed for jest.
- if (isPromise(body)) {
- // If handleReply is asynchronous, throwing an error
- // in the callback will reject the promise, rather than
- // synchronously throw the error, which breaks some tests.
- // Rather, we wait for the callback to resolve if it is a
- // promise, and then re-run handleReply with the new body.
- body.then((newData) => handleReply(mockDispatches, newData))
- return
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.decompressResponsePolicyName = void 0;
+exports.decompressResponsePolicy = decompressResponsePolicy;
+/**
+ * The programmatic identifier of the decompressResponsePolicy.
+ */
+exports.decompressResponsePolicyName = "decompressResponsePolicy";
+/**
+ * A policy to enable response decompression according to Accept-Encoding header
+ * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
+ */
+function decompressResponsePolicy() {
+ return {
+ name: exports.decompressResponsePolicyName,
+ async sendRequest(request, next) {
+ // HEAD requests have no body
+ if (request.method !== "HEAD") {
+ request.headers.set("Accept-Encoding", "gzip,deflate");
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=decompressResponsePolicy.js.map
- const responseData = getResponseData(body)
- const responseHeaders = generateKeyValues(headers)
- const responseTrailers = generateKeyValues(trailers)
+/***/ }),
- handler.abort = nop
- handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))
- handler.onData(Buffer.from(responseData))
- handler.onComplete(responseTrailers)
- deleteMockDispatch(mockDispatches, key)
- }
+/***/ 47494:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- function resume () {}
- return true
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.defaultRetryPolicyName = void 0;
+exports.defaultRetryPolicy = defaultRetryPolicy;
+const exponentialRetryStrategy_js_1 = __nccwpck_require__(34750);
+const throttlingRetryStrategy_js_1 = __nccwpck_require__(40288);
+const retryPolicy_js_1 = __nccwpck_require__(85001);
+const constants_js_1 = __nccwpck_require__(91791);
+/**
+ * Name of the {@link defaultRetryPolicy}
+ */
+exports.defaultRetryPolicyName = "defaultRetryPolicy";
+/**
+ * A policy that retries according to three strategies:
+ * - When the server sends a 429 response with a Retry-After header.
+ * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
+ * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
+ */
+function defaultRetryPolicy(options = {}) {
+ var _a;
+ return {
+ name: exports.defaultRetryPolicyName,
+ sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
}
+//# sourceMappingURL=defaultRetryPolicy.js.map
-function buildMockDispatch () {
- const agent = this[kMockAgent]
- const origin = this[kOrigin]
- const originalDispatch = this[kOriginalDispatch]
-
- return function dispatch (opts, handler) {
- if (agent.isMockActive) {
- try {
- mockDispatch.call(this, opts, handler)
- } catch (error) {
- if (error instanceof MockNotMatchedError) {
- const netConnect = agent[kGetNetConnect]()
- if (netConnect === false) {
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)
- }
- if (checkNetConnect(netConnect, origin)) {
- originalDispatch.call(this, opts, handler)
- } else {
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)
- }
- } else {
- throw error
- }
- }
- } else {
- originalDispatch.call(this, opts, handler)
- }
- }
-}
+/***/ }),
-function checkNetConnect (netConnect, origin) {
- const url = new URL(origin)
- if (netConnect === true) {
- return true
- } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
- return true
- }
- return false
-}
+/***/ 43048:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-function buildMockOptions (opts) {
- if (opts) {
- const { agent, ...mockOptions } = opts
- return mockOptions
- }
-}
-module.exports = {
- getResponseData,
- getMockDispatch,
- addMockDispatch,
- deleteMockDispatch,
- buildKey,
- generateKeyValues,
- matchValue,
- getResponse,
- getStatusText,
- mockDispatch,
- buildMockDispatch,
- checkNetConnect,
- buildMockOptions,
- getHeaderByName
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.exponentialRetryPolicyName = void 0;
+exports.exponentialRetryPolicy = exponentialRetryPolicy;
+const exponentialRetryStrategy_js_1 = __nccwpck_require__(34750);
+const retryPolicy_js_1 = __nccwpck_require__(85001);
+const constants_js_1 = __nccwpck_require__(91791);
+/**
+ * The programmatic identifier of the exponentialRetryPolicy.
+ */
+exports.exponentialRetryPolicyName = "exponentialRetryPolicy";
+/**
+ * A policy that attempts to retry requests while introducing an exponentially increasing delay.
+ * @param options - Options that configure retry logic.
+ */
+function exponentialRetryPolicy(options = {}) {
+ var _a;
+ return (0, retryPolicy_js_1.retryPolicy)([
+ (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })),
+ ], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ });
}
-
+//# sourceMappingURL=exponentialRetryPolicy.js.map
/***/ }),
-/***/ 85738:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 37997:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const { Transform } = __nccwpck_require__(2203)
-const { Console } = __nccwpck_require__(64236)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.formDataPolicyName = void 0;
+exports.formDataPolicy = formDataPolicy;
+const core_util_1 = __nccwpck_require__(30991);
+const httpHeaders_js_1 = __nccwpck_require__(30596);
/**
- * Gets the output of `console.table(…)` as a string.
+ * The programmatic identifier of the formDataPolicy.
*/
-module.exports = class PendingInterceptorsFormatter {
- constructor ({ disableColors } = {}) {
- this.transform = new Transform({
- transform (chunk, _enc, cb) {
- cb(null, chunk)
- }
- })
+exports.formDataPolicyName = "formDataPolicy";
+function formDataToFormDataMap(formData) {
+ var _a;
+ const formDataMap = {};
+ for (const [key, value] of formData.entries()) {
+ (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : (formDataMap[key] = []);
+ formDataMap[key].push(value);
+ }
+ return formDataMap;
+}
+/**
+ * A policy that encodes FormData on the request into the body.
+ */
+function formDataPolicy() {
+ return {
+ name: exports.formDataPolicyName,
+ async sendRequest(request, next) {
+ if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) {
+ request.formData = formDataToFormDataMap(request.body);
+ request.body = undefined;
+ }
+ if (request.formData) {
+ const contentType = request.headers.get("Content-Type");
+ if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
+ request.body = wwwFormUrlEncode(request.formData);
+ }
+ else {
+ await prepareFormData(request.formData, request);
+ }
+ request.formData = undefined;
+ }
+ return next(request);
+ },
+ };
+}
+function wwwFormUrlEncode(formData) {
+ const urlSearchParams = new URLSearchParams();
+ for (const [key, value] of Object.entries(formData)) {
+ if (Array.isArray(value)) {
+ for (const subValue of value) {
+ urlSearchParams.append(key, subValue.toString());
+ }
+ }
+ else {
+ urlSearchParams.append(key, value.toString());
+ }
+ }
+ return urlSearchParams.toString();
+}
+async function prepareFormData(formData, request) {
+ // validate content type (multipart/form-data)
+ const contentType = request.headers.get("Content-Type");
+ if (contentType && !contentType.startsWith("multipart/form-data")) {
+ // content type is specified and is not multipart/form-data. Exit.
+ return;
+ }
+ request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data");
+ // set body to MultipartRequestBody using content from FormDataMap
+ const parts = [];
+ for (const [fieldName, values] of Object.entries(formData)) {
+ for (const value of Array.isArray(values) ? values : [values]) {
+ if (typeof value === "string") {
+ parts.push({
+ headers: (0, httpHeaders_js_1.createHttpHeaders)({
+ "Content-Disposition": `form-data; name="${fieldName}"`,
+ }),
+ body: (0, core_util_1.stringToUint8Array)(value, "utf-8"),
+ });
+ }
+ else if (value === undefined || value === null || typeof value !== "object") {
+ throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`);
+ }
+ else {
+ // using || instead of ?? here since if value.name is empty we should create a file name
+ const fileName = value.name || "blob";
+ const headers = (0, httpHeaders_js_1.createHttpHeaders)();
+ headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
+ // again, || is used since an empty value.type means the content type is unset
+ headers.set("Content-Type", value.type || "application/octet-stream");
+ parts.push({
+ headers,
+ body: value,
+ });
+ }
+ }
+ }
+ request.multipartBody = { parts };
+}
+//# sourceMappingURL=formDataPolicy.js.map
- this.logger = new Console({
- stdout: this.transform,
- inspectOptions: {
- colors: !disableColors && !process.env.CI
- }
- })
- }
+/***/ }),
- format (pendingInterceptors) {
- const withPrettyHeaders = pendingInterceptors.map(
- ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
- Method: method,
- Origin: origin,
- Path: path,
- 'Status code': statusCode,
- Persistent: persist ? '✅' : '❌',
- Invocations: timesInvoked,
- Remaining: persist ? Infinity : times - timesInvoked
- }))
+/***/ 19937:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this.logger.table(withPrettyHeaders)
- return this.transform.read().toString()
- }
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logPolicyName = void 0;
+exports.logPolicy = logPolicy;
+const log_js_1 = __nccwpck_require__(58564);
+const sanitizer_js_1 = __nccwpck_require__(44720);
+/**
+ * The programmatic identifier of the logPolicy.
+ */
+exports.logPolicyName = "logPolicy";
+/**
+ * A policy that logs all requests and responses.
+ * @param options - Options to configure logPolicy.
+ */
+function logPolicy(options = {}) {
+ var _a;
+ const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info;
+ const sanitizer = new sanitizer_js_1.Sanitizer({
+ additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,
+ additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
+ });
+ return {
+ name: exports.logPolicyName,
+ async sendRequest(request, next) {
+ if (!logger.enabled) {
+ return next(request);
+ }
+ logger(`Request: ${sanitizer.sanitize(request)}`);
+ const response = await next(request);
+ logger(`Response status code: ${response.status}`);
+ logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
+ return response;
+ },
+ };
+}
+//# sourceMappingURL=logPolicy.js.map
/***/ }),
-/***/ 35773:
-/***/ ((module) => {
-
+/***/ 77915:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const singulars = {
- pronoun: 'it',
- is: 'is',
- was: 'was',
- this: 'this'
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.multipartPolicyName = void 0;
+exports.multipartPolicy = multipartPolicy;
+const core_util_1 = __nccwpck_require__(30991);
+const concat_js_1 = __nccwpck_require__(85307);
+const typeGuards_js_1 = __nccwpck_require__(24449);
+function generateBoundary() {
+ return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`;
}
-
-const plurals = {
- pronoun: 'they',
- is: 'are',
- was: 'were',
- this: 'these'
+function encodeHeaders(headers) {
+ let result = "";
+ for (const [key, value] of headers) {
+ result += `${key}: ${value}\r\n`;
+ }
+ return result;
}
-
-module.exports = class Pluralizer {
- constructor (singular, plural) {
- this.singular = singular
- this.plural = plural
- }
-
- pluralize (count) {
- const one = count === 1
- const keys = one ? singulars : plurals
- const noun = one ? this.singular : this.plural
- return { ...keys, count, noun }
- }
+function getLength(source) {
+ if (source instanceof Uint8Array) {
+ return source.byteLength;
+ }
+ else if ((0, typeGuards_js_1.isBlob)(source)) {
+ // if was created using createFile then -1 means we have an unknown size
+ return source.size === -1 ? undefined : source.size;
+ }
+ else {
+ return undefined;
+ }
}
-
+function getTotalLength(sources) {
+ let total = 0;
+ for (const source of sources) {
+ const partLength = getLength(source);
+ if (partLength === undefined) {
+ return undefined;
+ }
+ else {
+ total += partLength;
+ }
+ }
+ return total;
+}
+async function buildRequestBody(request, parts, boundary) {
+ const sources = [
+ (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"),
+ ...parts.flatMap((part) => [
+ (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
+ (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"),
+ (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
+ part.body,
+ (0, core_util_1.stringToUint8Array)(`\r\n--${boundary}`, "utf-8"),
+ ]),
+ (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8"),
+ ];
+ const contentLength = getTotalLength(sources);
+ if (contentLength) {
+ request.headers.set("Content-Length", contentLength);
+ }
+ request.body = await (0, concat_js_1.concat)(sources);
+}
+/**
+ * Name of multipart policy
+ */
+exports.multipartPolicyName = "multipartPolicy";
+const maxBoundaryLength = 70;
+const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
+function assertValidBoundary(boundary) {
+ if (boundary.length > maxBoundaryLength) {
+ throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
+ }
+ if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
+ throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
+ }
+}
+/**
+ * Pipeline policy for multipart requests
+ */
+function multipartPolicy() {
+ return {
+ name: exports.multipartPolicyName,
+ async sendRequest(request, next) {
+ var _a;
+ if (!request.multipartBody) {
+ return next(request);
+ }
+ if (request.body) {
+ throw new Error("multipartBody and regular body cannot be set at the same time");
+ }
+ let boundary = request.multipartBody.boundary;
+ const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed";
+ const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
+ if (!parsedHeader) {
+ throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
+ }
+ const [, contentType, parsedBoundary] = parsedHeader;
+ if (parsedBoundary && boundary && parsedBoundary !== boundary) {
+ throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
+ }
+ boundary !== null && boundary !== void 0 ? boundary : (boundary = parsedBoundary);
+ if (boundary) {
+ assertValidBoundary(boundary);
+ }
+ else {
+ boundary = generateBoundary();
+ }
+ request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
+ await buildRequestBody(request, request.multipartBody.parts, boundary);
+ request.multipartBody = undefined;
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=multipartPolicy.js.map
/***/ }),
-/***/ 98721:
-/***/ ((module) => {
-
-/* eslint-disable */
-
-
-
-// Extracted from node/lib/internal/fixed_queue.js
-
-// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.
-const kSize = 2048;
-const kMask = kSize - 1;
+/***/ 7303:
+/***/ ((__unused_webpack_module, exports) => {
-// The FixedQueue is implemented as a singly-linked list of fixed-size
-// circular buffers. It looks something like this:
-//
-// head tail
-// | |
-// v v
-// +-----------+ <-----\ +-----------+ <------\ +-----------+
-// | [null] | \----- | next | \------- | next |
-// +-----------+ +-----------+ +-----------+
-// | item | <-- bottom | item | <-- bottom | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | bottom --> | item |
-// | item | | item | | item |
-// | ... | | ... | | ... |
-// | item | | item | | item |
-// | item | | item | | item |
-// | [empty] | <-- top | item | | item |
-// | [empty] | | item | | item |
-// | [empty] | | [empty] | <-- top top --> | [empty] |
-// +-----------+ +-----------+ +-----------+
-//
-// Or, if there is only one circular buffer, it looks something
-// like either of these:
-//
-// head tail head tail
-// | | | |
-// v v v v
-// +-----------+ +-----------+
-// | [null] | | [null] |
-// +-----------+ +-----------+
-// | [empty] | | item |
-// | [empty] | | item |
-// | item | <-- bottom top --> | [empty] |
-// | item | | [empty] |
-// | [empty] | <-- top bottom --> | item |
-// | [empty] | | item |
-// +-----------+ +-----------+
-//
-// Adding a value means moving `top` forward by one, removing means
-// moving `bottom` forward by one. After reaching the end, the queue
-// wraps around.
-//
-// When `top === bottom` the current queue is empty and when
-// `top + 1 === bottom` it's full. This wastes a single space of storage
-// but allows much quicker checks.
-class FixedCircularBuffer {
- constructor() {
- this.bottom = 0;
- this.top = 0;
- this.list = new Array(kSize);
- this.next = null;
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ndJsonPolicyName = void 0;
+exports.ndJsonPolicy = ndJsonPolicy;
+/**
+ * The programmatic identifier of the ndJsonPolicy.
+ */
+exports.ndJsonPolicyName = "ndJsonPolicy";
+/**
+ * ndJsonPolicy is a policy used to control keep alive settings for every request.
+ */
+function ndJsonPolicy() {
+ return {
+ name: exports.ndJsonPolicyName,
+ async sendRequest(request, next) {
+ // There currently isn't a good way to bypass the serializer
+ if (typeof request.body === "string" && request.body.startsWith("[")) {
+ const body = JSON.parse(request.body);
+ if (Array.isArray(body)) {
+ request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
+ }
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=ndJsonPolicy.js.map
- isEmpty() {
- return this.top === this.bottom;
- }
+/***/ }),
- isFull() {
- return ((this.top + 1) & kMask) === this.bottom;
- }
+/***/ 73723:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- push(data) {
- this.list[this.top] = data;
- this.top = (this.top + 1) & kMask;
- }
- shift() {
- const nextItem = this.list[this.bottom];
- if (nextItem === undefined)
- return null;
- this.list[this.bottom] = undefined;
- this.bottom = (this.bottom + 1) & kMask;
- return nextItem;
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.globalNoProxyList = exports.proxyPolicyName = void 0;
+exports.loadNoProxy = loadNoProxy;
+exports.getDefaultProxySettings = getDefaultProxySettings;
+exports.proxyPolicy = proxyPolicy;
+const https_proxy_agent_1 = __nccwpck_require__(54129);
+const http_proxy_agent_1 = __nccwpck_require__(31286);
+const log_js_1 = __nccwpck_require__(58564);
+const HTTPS_PROXY = "HTTPS_PROXY";
+const HTTP_PROXY = "HTTP_PROXY";
+const ALL_PROXY = "ALL_PROXY";
+const NO_PROXY = "NO_PROXY";
+/**
+ * The programmatic identifier of the proxyPolicy.
+ */
+exports.proxyPolicyName = "proxyPolicy";
+/**
+ * Stores the patterns specified in NO_PROXY environment variable.
+ * @internal
+ */
+exports.globalNoProxyList = [];
+let noProxyListLoaded = false;
+/** A cache of whether a host should bypass the proxy. */
+const globalBypassedMap = new Map();
+function getEnvironmentValue(name) {
+ if (process.env[name]) {
+ return process.env[name];
+ }
+ else if (process.env[name.toLowerCase()]) {
+ return process.env[name.toLowerCase()];
+ }
+ return undefined;
}
-
-module.exports = class FixedQueue {
- constructor() {
- this.head = this.tail = new FixedCircularBuffer();
- }
-
- isEmpty() {
- return this.head.isEmpty();
- }
-
- push(data) {
- if (this.head.isFull()) {
- // Head is full: Creates a new queue, sets the old queue's `.next` to it,
- // and sets it as the new main queue.
- this.head = this.head.next = new FixedCircularBuffer();
+function loadEnvironmentProxyValue() {
+ if (!process) {
+ return undefined;
+ }
+ const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
+ const allProxy = getEnvironmentValue(ALL_PROXY);
+ const httpProxy = getEnvironmentValue(HTTP_PROXY);
+ return httpsProxy || allProxy || httpProxy;
+}
+/**
+ * Check whether the host of a given `uri` matches any pattern in the no proxy list.
+ * If there's a match, any request sent to the same host shouldn't have the proxy settings set.
+ * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210
+ */
+function isBypassed(uri, noProxyList, bypassedMap) {
+ if (noProxyList.length === 0) {
+ return false;
+ }
+ const host = new URL(uri).hostname;
+ if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) {
+ return bypassedMap.get(host);
+ }
+ let isBypassedFlag = false;
+ for (const pattern of noProxyList) {
+ if (pattern[0] === ".") {
+ // This should match either domain it self or any subdomain or host
+ // .foo.com will match foo.com it self or *.foo.com
+ if (host.endsWith(pattern)) {
+ isBypassedFlag = true;
+ }
+ else {
+ if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
+ isBypassedFlag = true;
+ }
+ }
+ }
+ else {
+ if (host === pattern) {
+ isBypassedFlag = true;
+ }
+ }
}
- this.head.push(data);
- }
-
- shift() {
- const tail = this.tail;
- const next = tail.shift();
- if (tail.isEmpty() && tail.next !== null) {
- // If there is another queue, it forms the new tail.
- this.tail = tail.next;
+ bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag);
+ return isBypassedFlag;
+}
+function loadNoProxy() {
+ const noProxy = getEnvironmentValue(NO_PROXY);
+ noProxyListLoaded = true;
+ if (noProxy) {
+ return noProxy
+ .split(",")
+ .map((item) => item.trim())
+ .filter((item) => item.length);
}
- return next;
- }
-};
-
-
-/***/ }),
-
-/***/ 18804:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const DispatcherBase = __nccwpck_require__(52421)
-const FixedQueue = __nccwpck_require__(98721)
-const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(68031)
-const PoolStats = __nccwpck_require__(29218)
-
-const kClients = Symbol('clients')
-const kNeedDrain = Symbol('needDrain')
-const kQueue = Symbol('queue')
-const kClosedResolve = Symbol('closed resolve')
-const kOnDrain = Symbol('onDrain')
-const kOnConnect = Symbol('onConnect')
-const kOnDisconnect = Symbol('onDisconnect')
-const kOnConnectionError = Symbol('onConnectionError')
-const kGetDispatcher = Symbol('get dispatcher')
-const kAddClient = Symbol('add client')
-const kRemoveClient = Symbol('remove client')
-const kStats = Symbol('stats')
-
-class PoolBase extends DispatcherBase {
- constructor () {
- super()
-
- this[kQueue] = new FixedQueue()
- this[kClients] = []
- this[kQueued] = 0
-
- const pool = this
-
- this[kOnDrain] = function onDrain (origin, targets) {
- const queue = pool[kQueue]
-
- let needDrain = false
-
- while (!needDrain) {
- const item = queue.shift()
- if (!item) {
- break
+ return [];
+}
+/**
+ * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
+ * If no argument is given, it attempts to parse a proxy URL from the environment
+ * variables `HTTPS_PROXY` or `HTTP_PROXY`.
+ * @param proxyUrl - The url of the proxy to use. May contain authentication information.
+ * @deprecated - Internally this method is no longer necessary when setting proxy information.
+ */
+function getDefaultProxySettings(proxyUrl) {
+ if (!proxyUrl) {
+ proxyUrl = loadEnvironmentProxyValue();
+ if (!proxyUrl) {
+ return undefined;
}
- pool[kQueued]--
- needDrain = !this.dispatch(item.opts, item.handler)
- }
-
- this[kNeedDrain] = needDrain
-
- if (!this[kNeedDrain] && pool[kNeedDrain]) {
- pool[kNeedDrain] = false
- pool.emit('drain', origin, [pool, ...targets])
- }
-
- if (pool[kClosedResolve] && queue.isEmpty()) {
- Promise
- .all(pool[kClients].map(c => c.close()))
- .then(pool[kClosedResolve])
- }
}
-
- this[kOnConnect] = (origin, targets) => {
- pool.emit('connect', origin, [pool, ...targets])
+ const parsedUrl = new URL(proxyUrl);
+ const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
+ return {
+ host: schema + parsedUrl.hostname,
+ port: Number.parseInt(parsedUrl.port || "80"),
+ username: parsedUrl.username,
+ password: parsedUrl.password,
+ };
+}
+/**
+ * This method attempts to parse a proxy URL from the environment
+ * variables `HTTPS_PROXY` or `HTTP_PROXY`.
+ */
+function getDefaultProxySettingsInternal() {
+ const envProxy = loadEnvironmentProxyValue();
+ return envProxy ? new URL(envProxy) : undefined;
+}
+function getUrlFromProxySettings(settings) {
+ let parsedProxyUrl;
+ try {
+ parsedProxyUrl = new URL(settings.host);
}
-
- this[kOnDisconnect] = (origin, targets, err) => {
- pool.emit('disconnect', origin, [pool, ...targets], err)
+ catch (_a) {
+ throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`);
}
-
- this[kOnConnectionError] = (origin, targets, err) => {
- pool.emit('connectionError', origin, [pool, ...targets], err)
+ parsedProxyUrl.port = String(settings.port);
+ if (settings.username) {
+ parsedProxyUrl.username = settings.username;
}
-
- this[kStats] = new PoolStats(this)
- }
-
- get [kBusy] () {
- return this[kNeedDrain]
- }
-
- get [kConnected] () {
- return this[kClients].filter(client => client[kConnected]).length
- }
-
- get [kFree] () {
- return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length
- }
-
- get [kPending] () {
- let ret = this[kQueued]
- for (const { [kPending]: pending } of this[kClients]) {
- ret += pending
+ if (settings.password) {
+ parsedProxyUrl.password = settings.password;
}
- return ret
- }
-
- get [kRunning] () {
- let ret = 0
- for (const { [kRunning]: running } of this[kClients]) {
- ret += running
+ return parsedProxyUrl;
+}
+function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) {
+ // Custom Agent should take precedence so if one is present
+ // we should skip to avoid overwriting it.
+ if (request.agent) {
+ return;
}
- return ret
- }
-
- get [kSize] () {
- let ret = this[kQueued]
- for (const { [kSize]: size } of this[kClients]) {
- ret += size
+ const url = new URL(request.url);
+ const isInsecure = url.protocol !== "https:";
+ if (request.tlsSettings) {
+ log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
}
- return ret
- }
-
- get stats () {
- return this[kStats]
- }
-
- async [kClose] () {
- if (this[kQueue].isEmpty()) {
- return Promise.all(this[kClients].map(c => c.close()))
- } else {
- return new Promise((resolve) => {
- this[kClosedResolve] = resolve
- })
+ const headers = request.headers.toJSON();
+ if (isInsecure) {
+ if (!cachedAgents.httpProxyAgent) {
+ cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers });
+ }
+ request.agent = cachedAgents.httpProxyAgent;
}
- }
-
- async [kDestroy] (err) {
- while (true) {
- const item = this[kQueue].shift()
- if (!item) {
- break
- }
- item.handler.onError(err)
+ else {
+ if (!cachedAgents.httpsProxyAgent) {
+ cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers });
+ }
+ request.agent = cachedAgents.httpsProxyAgent;
}
-
- return Promise.all(this[kClients].map(c => c.destroy(err)))
- }
-
- [kDispatch] (opts, handler) {
- const dispatcher = this[kGetDispatcher]()
-
- if (!dispatcher) {
- this[kNeedDrain] = true
- this[kQueue].push({ opts, handler })
- this[kQueued]++
- } else if (!dispatcher.dispatch(opts, handler)) {
- dispatcher[kNeedDrain] = true
- this[kNeedDrain] = !this[kGetDispatcher]()
+}
+/**
+ * A policy that allows one to apply proxy settings to all requests.
+ * If not passed static settings, they will be retrieved from the HTTPS_PROXY
+ * or HTTP_PROXY environment variables.
+ * @param proxySettings - ProxySettings to use on each request.
+ * @param options - additional settings, for example, custom NO_PROXY patterns
+ */
+function proxyPolicy(proxySettings, options) {
+ if (!noProxyListLoaded) {
+ exports.globalNoProxyList.push(...loadNoProxy());
}
+ const defaultProxy = proxySettings
+ ? getUrlFromProxySettings(proxySettings)
+ : getDefaultProxySettingsInternal();
+ const cachedAgents = {};
+ return {
+ name: exports.proxyPolicyName,
+ async sendRequest(request, next) {
+ var _a;
+ if (!request.proxySettings &&
+ defaultProxy &&
+ !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? undefined : globalBypassedMap)) {
+ setProxyAgentOnRequest(request, cachedAgents, defaultProxy);
+ }
+ else if (request.proxySettings) {
+ setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings));
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=proxyPolicy.js.map
- return !this[kNeedDrain]
- }
+/***/ }),
- [kAddClient] (client) {
- client
- .on('drain', this[kOnDrain])
- .on('connect', this[kOnConnect])
- .on('disconnect', this[kOnDisconnect])
- .on('connectionError', this[kOnConnectionError])
+/***/ 86947:
+/***/ ((__unused_webpack_module, exports) => {
- this[kClients].push(client)
- if (this[kNeedDrain]) {
- process.nextTick(() => {
- if (this[kNeedDrain]) {
- this[kOnDrain](client[kUrl], [this, client])
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.redirectPolicyName = void 0;
+exports.redirectPolicy = redirectPolicy;
+/**
+ * The programmatic identifier of the redirectPolicy.
+ */
+exports.redirectPolicyName = "redirectPolicy";
+/**
+ * Methods that are allowed to follow redirects 301 and 302
+ */
+const allowedRedirect = ["GET", "HEAD"];
+/**
+ * A policy to follow Location headers from the server in order
+ * to support server-side redirection.
+ * In the browser, this policy is not used.
+ * @param options - Options to control policy behavior.
+ */
+function redirectPolicy(options = {}) {
+ const { maxRetries = 20 } = options;
+ return {
+ name: exports.redirectPolicyName,
+ async sendRequest(request, next) {
+ const response = await next(request);
+ return handleRedirect(next, response, maxRetries);
+ },
+ };
+}
+async function handleRedirect(next, response, maxRetries, currentRetries = 0) {
+ const { request, status, headers } = response;
+ const locationHeader = headers.get("location");
+ if (locationHeader &&
+ (status === 300 ||
+ (status === 301 && allowedRedirect.includes(request.method)) ||
+ (status === 302 && allowedRedirect.includes(request.method)) ||
+ (status === 303 && request.method === "POST") ||
+ status === 307) &&
+ currentRetries < maxRetries) {
+ const url = new URL(locationHeader, request.url);
+ request.url = url.toString();
+ // POST request with Status code 303 should be converted into a
+ // redirected GET request if the redirect url is present in the location header
+ if (status === 303) {
+ request.method = "GET";
+ request.headers.delete("Content-Length");
+ delete request.body;
}
- })
+ request.headers.delete("Authorization");
+ const res = await next(request);
+ return handleRedirect(next, res, maxRetries, currentRetries + 1);
}
+ return response;
+}
+//# sourceMappingURL=redirectPolicy.js.map
- return this
- }
+/***/ }),
- [kRemoveClient] (client) {
- client.close(() => {
- const idx = this[kClients].indexOf(client)
- if (idx !== -1) {
- this[kClients].splice(idx, 1)
- }
- })
+/***/ 85001:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this[kNeedDrain] = this[kClients].some(dispatcher => (
- !dispatcher[kNeedDrain] &&
- dispatcher.closed !== true &&
- dispatcher.destroyed !== true
- ))
- }
-}
-module.exports = {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kGetDispatcher
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.retryPolicy = retryPolicy;
+const helpers_js_1 = __nccwpck_require__(94982);
+const logger_1 = __nccwpck_require__(50143);
+const abort_controller_1 = __nccwpck_require__(92242);
+const constants_js_1 = __nccwpck_require__(91791);
+const retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy");
+/**
+ * The programmatic identifier of the retryPolicy.
+ */
+const retryPolicyName = "retryPolicy";
+/**
+ * retryPolicy is a generic policy to enable retrying requests when certain conditions are met
+ */
+function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) {
+ const logger = options.logger || retryPolicyLogger;
+ return {
+ name: retryPolicyName,
+ async sendRequest(request, next) {
+ var _a, _b;
+ let response;
+ let responseError;
+ let retryCount = -1;
+ // eslint-disable-next-line no-constant-condition
+ retryRequest: while (true) {
+ retryCount += 1;
+ response = undefined;
+ responseError = undefined;
+ try {
+ logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);
+ response = await next(request);
+ logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);
+ }
+ catch (e) {
+ logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);
+ // RestErrors are valid targets for the retry strategies.
+ // If none of the retry strategies can work with them, they will be thrown later in this policy.
+ // If the received error is not a RestError, it is immediately thrown.
+ responseError = e;
+ if (!e || responseError.name !== "RestError") {
+ throw e;
+ }
+ response = responseError.response;
+ }
+ if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) {
+ logger.error(`Retry ${retryCount}: Request aborted.`);
+ const abortError = new abort_controller_1.AbortError();
+ throw abortError;
+ }
+ if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) {
+ logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
+ if (responseError) {
+ throw responseError;
+ }
+ else if (response) {
+ return response;
+ }
+ else {
+ throw new Error("Maximum retries reached with no response or error to throw");
+ }
+ }
+ logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
+ strategiesLoop: for (const strategy of strategies) {
+ const strategyLogger = strategy.logger || retryPolicyLogger;
+ strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
+ const modifiers = strategy.retry({
+ retryCount,
+ response,
+ responseError,
+ });
+ if (modifiers.skipStrategy) {
+ strategyLogger.info(`Retry ${retryCount}: Skipped.`);
+ continue strategiesLoop;
+ }
+ const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;
+ if (errorToThrow) {
+ strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow);
+ throw errorToThrow;
+ }
+ if (retryAfterInMs || retryAfterInMs === 0) {
+ strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`);
+ await (0, helpers_js_1.delay)(retryAfterInMs, undefined, { abortSignal: request.abortSignal });
+ continue retryRequest;
+ }
+ if (redirectTo) {
+ strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
+ request.url = redirectTo;
+ continue retryRequest;
+ }
+ }
+ if (responseError) {
+ logger.info(`None of the retry strategies could work with the received error. Throwing it.`);
+ throw responseError;
+ }
+ if (response) {
+ logger.info(`None of the retry strategies could work with the received response. Returning it.`);
+ return response;
+ }
+ // If all the retries skip and there's no response,
+ // we're still in the retry loop, so a new request will be sent
+ // until `maxRetries` is reached.
+ }
+ },
+ };
}
-
+//# sourceMappingURL=retryPolicy.js.map
/***/ }),
-/***/ 29218:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 63866:
+/***/ ((__unused_webpack_module, exports) => {
-const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(68031)
-const kPool = Symbol('pool')
-class PoolStats {
- constructor (pool) {
- this[kPool] = pool
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.setClientRequestIdPolicyName = void 0;
+exports.setClientRequestIdPolicy = setClientRequestIdPolicy;
+/**
+ * The programmatic identifier of the setClientRequestIdPolicy.
+ */
+exports.setClientRequestIdPolicyName = "setClientRequestIdPolicy";
+/**
+ * Each PipelineRequest gets a unique id upon creation.
+ * This policy passes that unique id along via an HTTP header to enable better
+ * telemetry and tracing.
+ * @param requestIdHeaderName - The name of the header to pass the request ID to.
+ */
+function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
+ return {
+ name: exports.setClientRequestIdPolicyName,
+ async sendRequest(request, next) {
+ if (!request.headers.has(requestIdHeaderName)) {
+ request.headers.set(requestIdHeaderName, request.requestId);
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=setClientRequestIdPolicy.js.map
- get connected () {
- return this[kPool][kConnected]
- }
+/***/ }),
- get free () {
- return this[kPool][kFree]
- }
+/***/ 14298:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- get pending () {
- return this[kPool][kPending]
- }
- get queued () {
- return this[kPool][kQueued]
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.systemErrorRetryPolicyName = void 0;
+exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
+const exponentialRetryStrategy_js_1 = __nccwpck_require__(34750);
+const retryPolicy_js_1 = __nccwpck_require__(85001);
+const constants_js_1 = __nccwpck_require__(91791);
+/**
+ * Name of the {@link systemErrorRetryPolicy}
+ */
+exports.systemErrorRetryPolicyName = "systemErrorRetryPolicy";
+/**
+ * A retry policy that specifically seeks to handle errors in the
+ * underlying transport layer (e.g. DNS lookup failures) rather than
+ * retryable error codes from the server itself.
+ * @param options - Options that customize the policy.
+ */
+function systemErrorRetryPolicy(options = {}) {
+ var _a;
+ return {
+ name: exports.systemErrorRetryPolicyName,
+ sendRequest: (0, retryPolicy_js_1.retryPolicy)([
+ (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })),
+ ], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
+}
+//# sourceMappingURL=systemErrorRetryPolicy.js.map
- get running () {
- return this[kPool][kRunning]
- }
+/***/ }),
- get size () {
- return this[kPool][kSize]
- }
-}
+/***/ 96352:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = PoolStats
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.throttlingRetryPolicyName = void 0;
+exports.throttlingRetryPolicy = throttlingRetryPolicy;
+const throttlingRetryStrategy_js_1 = __nccwpck_require__(40288);
+const retryPolicy_js_1 = __nccwpck_require__(85001);
+const constants_js_1 = __nccwpck_require__(91791);
+/**
+ * Name of the {@link throttlingRetryPolicy}
+ */
+exports.throttlingRetryPolicyName = "throttlingRetryPolicy";
+/**
+ * A policy that retries when the server sends a 429 response with a Retry-After header.
+ *
+ * To learn more, please refer to
+ * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
+ * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
+ * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
+ *
+ * @param options - Options that configure retry logic.
+ */
+function throttlingRetryPolicy(options = {}) {
+ var _a;
+ return {
+ name: exports.throttlingRetryPolicyName,
+ sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
+}
+//# sourceMappingURL=throttlingRetryPolicy.js.map
/***/ }),
-/***/ 44288:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+/***/ 39370:
+/***/ ((__unused_webpack_module, exports) => {
-const {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kGetDispatcher
-} = __nccwpck_require__(18804)
-const Client = __nccwpck_require__(45513)
-const {
- InvalidArgumentError
-} = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { kUrl, kInterceptors } = __nccwpck_require__(68031)
-const buildConnector = __nccwpck_require__(91332)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.tlsPolicyName = void 0;
+exports.tlsPolicy = tlsPolicy;
+/**
+ * Name of the TLS Policy
+ */
+exports.tlsPolicyName = "tlsPolicy";
+/**
+ * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
+ */
+function tlsPolicy(tlsSettings) {
+ return {
+ name: exports.tlsPolicyName,
+ sendRequest: async (req, next) => {
+ // Users may define a request tlsSettings, honor those over the client level one
+ if (!req.tlsSettings) {
+ req.tlsSettings = tlsSettings;
+ }
+ return next(req);
+ },
+ };
+}
+//# sourceMappingURL=tlsPolicy.js.map
-const kOptions = Symbol('options')
-const kConnections = Symbol('connections')
-const kFactory = Symbol('factory')
+/***/ }),
-function defaultFactory (origin, opts) {
- return new Client(origin, opts)
-}
+/***/ 14113:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-class Pool extends PoolBase {
- constructor (origin, {
- connections,
- factory = defaultFactory,
- connect,
- connectTimeout,
- tls,
- maxCachedSessions,
- socketPath,
- autoSelectFamily,
- autoSelectFamilyAttemptTimeout,
- allowH2,
- ...options
- } = {}) {
- super()
- if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
- throw new InvalidArgumentError('invalid connections')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.tracingPolicyName = void 0;
+exports.tracingPolicy = tracingPolicy;
+const core_tracing_1 = __nccwpck_require__(7651);
+const constants_js_1 = __nccwpck_require__(91791);
+const userAgent_js_1 = __nccwpck_require__(87747);
+const log_js_1 = __nccwpck_require__(58564);
+const core_util_1 = __nccwpck_require__(30991);
+const restError_js_1 = __nccwpck_require__(97558);
+const sanitizer_js_1 = __nccwpck_require__(44720);
+/**
+ * The programmatic identifier of the tracingPolicy.
+ */
+exports.tracingPolicyName = "tracingPolicy";
+/**
+ * A simple policy to create OpenTelemetry Spans for each request made by the pipeline
+ * that has SpanOptions with a parent.
+ * Requests made without a parent Span will not be recorded.
+ * @param options - Options to configure the telemetry logged by the tracing policy.
+ */
+function tracingPolicy(options = {}) {
+ const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
+ const sanitizer = new sanitizer_js_1.Sanitizer({
+ additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
+ });
+ const tracingClient = tryCreateTracingClient();
+ return {
+ name: exports.tracingPolicyName,
+ async sendRequest(request, next) {
+ var _a;
+ if (!tracingClient) {
+ return next(request);
+ }
+ const userAgent = await userAgentPromise;
+ const spanAttributes = {
+ "http.url": sanitizer.sanitizeUrl(request.url),
+ "http.method": request.method,
+ "http.user_agent": userAgent,
+ requestId: request.requestId,
+ };
+ if (userAgent) {
+ spanAttributes["http.user_agent"] = userAgent;
+ }
+ const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {};
+ if (!span || !tracingContext) {
+ return next(request);
+ }
+ try {
+ const response = await tracingClient.withContext(tracingContext, next, request);
+ tryProcessResponse(span, response);
+ return response;
+ }
+ catch (err) {
+ tryProcessError(span, err);
+ throw err;
+ }
+ },
+ };
+}
+function tryCreateTracingClient() {
+ try {
+ return (0, core_tracing_1.createTracingClient)({
+ namespace: "",
+ packageName: "@azure/core-rest-pipeline",
+ packageVersion: constants_js_1.SDK_VERSION,
+ });
}
-
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
+ catch (e) {
+ log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`);
+ return undefined;
}
-
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
+}
+function tryCreateSpan(tracingClient, request, spanAttributes) {
+ try {
+ // As per spec, we do not need to differentiate between HTTP and HTTPS in span name.
+ const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
+ spanKind: "client",
+ spanAttributes,
+ });
+ // If the span is not recording, don't do any more work.
+ if (!span.isRecording()) {
+ span.end();
+ return undefined;
+ }
+ // set headers
+ const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
+ for (const [key, value] of Object.entries(headers)) {
+ request.headers.set(key, value);
+ }
+ return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
}
-
- if (typeof connect !== 'function') {
- connect = buildConnector({
- ...tls,
- maxCachedSessions,
- allowH2,
- socketPath,
- timeout: connectTimeout,
- ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
- ...connect
- })
+ catch (e) {
+ log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
+ return undefined;
}
-
- this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)
- ? options.interceptors.Pool
- : []
- this[kConnections] = connections || null
- this[kUrl] = util.parseOrigin(origin)
- this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
- this[kOptions].interceptors = options.interceptors
- ? { ...options.interceptors }
- : undefined
- this[kFactory] = factory
- }
-
- [kGetDispatcher] () {
- let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])
-
- if (dispatcher) {
- return dispatcher
+}
+function tryProcessError(span, error) {
+ try {
+ span.setStatus({
+ status: "error",
+ error: (0, core_util_1.isError)(error) ? error : undefined,
+ });
+ if ((0, restError_js_1.isRestError)(error) && error.statusCode) {
+ span.setAttribute("http.status_code", error.statusCode);
+ }
+ span.end();
}
-
- if (!this[kConnections] || this[kClients].length < this[kConnections]) {
- dispatcher = this[kFactory](this[kUrl], this[kOptions])
- this[kAddClient](dispatcher)
+ catch (e) {
+ log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
}
-
- return dispatcher
- }
}
-
-module.exports = Pool
-
+function tryProcessResponse(span, response) {
+ try {
+ span.setAttribute("http.status_code", response.status);
+ const serviceRequestId = response.headers.get("x-ms-request-id");
+ if (serviceRequestId) {
+ span.setAttribute("serviceRequestId", serviceRequestId);
+ }
+ span.setStatus({
+ status: "success",
+ });
+ span.end();
+ }
+ catch (e) {
+ log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
+ }
+}
+//# sourceMappingURL=tracingPolicy.js.map
/***/ }),
-/***/ 79276:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 69795:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.userAgentPolicyName = void 0;
+exports.userAgentPolicy = userAgentPolicy;
+const userAgent_js_1 = __nccwpck_require__(87747);
+const UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)();
+/**
+ * The programmatic identifier of the userAgentPolicy.
+ */
+exports.userAgentPolicyName = "userAgentPolicy";
+/**
+ * A policy that sets the User-Agent header (or equivalent) to reflect
+ * the library version.
+ * @param options - Options to customize the user agent value.
+ */
+function userAgentPolicy(options = {}) {
+ const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
+ return {
+ name: exports.userAgentPolicyName,
+ async sendRequest(request, next) {
+ if (!request.headers.has(UserAgentHeaderName)) {
+ request.headers.set(UserAgentHeaderName, await userAgentValue);
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=userAgentPolicy.js.map
+
+/***/ }),
-const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(68031)
-const { URL } = __nccwpck_require__(87016)
-const Agent = __nccwpck_require__(92121)
-const Pool = __nccwpck_require__(44288)
-const DispatcherBase = __nccwpck_require__(52421)
-const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(53959)
-const buildConnector = __nccwpck_require__(91332)
+/***/ 97558:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const kAgent = Symbol('proxy agent')
-const kClient = Symbol('proxy client')
-const kProxyHeaders = Symbol('proxy headers')
-const kRequestTls = Symbol('request tls settings')
-const kProxyTls = Symbol('proxy tls settings')
-const kConnectEndpoint = Symbol('connect endpoint function')
-function defaultProtocolPort (protocol) {
- return protocol === 'https:' ? 443 : 80
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RestError = void 0;
+exports.isRestError = isRestError;
+const core_util_1 = __nccwpck_require__(30991);
+const inspect_js_1 = __nccwpck_require__(84111);
+const sanitizer_js_1 = __nccwpck_require__(44720);
+const errorSanitizer = new sanitizer_js_1.Sanitizer();
+/**
+ * A custom error type for failed pipeline requests.
+ */
+class RestError extends Error {
+ constructor(message, options = {}) {
+ super(message);
+ this.name = "RestError";
+ this.code = options.code;
+ this.statusCode = options.statusCode;
+ // The request and response may contain sensitive information in the headers or body.
+ // To help prevent this sensitive information being accidentally logged, the request and response
+ // properties are marked as non-enumerable here. This prevents them showing up in the output of
+ // JSON.stringify and console.log.
+ Object.defineProperty(this, "request", { value: options.request, enumerable: false });
+ Object.defineProperty(this, "response", { value: options.response, enumerable: false });
+ Object.setPrototypeOf(this, RestError.prototype);
+ }
+ /**
+ * Logging method for util.inspect in Node
+ */
+ [inspect_js_1.custom]() {
+ // Extract non-enumerable properties and add them back. This is OK since in this output the request and
+ // response get sanitized.
+ return `RestError: ${this.message} \n ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`;
+ }
}
+exports.RestError = RestError;
+/**
+ * Something went wrong when making the request.
+ * This means the actual request failed for some reason,
+ * such as a DNS issue or the connection being lost.
+ */
+RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
+/**
+ * This means that parsing the response from the server failed.
+ * It may have been malformed.
+ */
+RestError.PARSE_ERROR = "PARSE_ERROR";
+/**
+ * Typeguard for RestError
+ * @param e - Something caught by a catch clause.
+ */
+function isRestError(e) {
+ if (e instanceof RestError) {
+ return true;
+ }
+ return (0, core_util_1.isError)(e) && e.name === "RestError";
+}
+//# sourceMappingURL=restError.js.map
-function buildProxyOptions (opts) {
- if (typeof opts === 'string') {
- opts = { uri: opts }
- }
+/***/ }),
- if (!opts || !opts.uri) {
- throw new InvalidArgumentError('Proxy opts.uri is mandatory')
- }
+/***/ 34750:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return {
- uri: opts.uri,
- protocol: opts.protocol || 'https'
- }
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.exponentialRetryStrategy = exponentialRetryStrategy;
+exports.isExponentialRetryResponse = isExponentialRetryResponse;
+exports.isSystemError = isSystemError;
+const core_util_1 = __nccwpck_require__(30991);
+const throttlingRetryStrategy_js_1 = __nccwpck_require__(40288);
+// intervals are in milliseconds
+const DEFAULT_CLIENT_RETRY_INTERVAL = 1000;
+const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;
+/**
+ * A retry strategy that retries with an exponentially increasing delay in these two cases:
+ * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
+ * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505).
+ */
+function exponentialRetryStrategy(options = {}) {
+ var _a, _b;
+ const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL;
+ const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
+ return {
+ name: "exponentialRetryStrategy",
+ retry({ retryCount, response, responseError }) {
+ const matchedSystemError = isSystemError(responseError);
+ const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;
+ const isExponential = isExponentialRetryResponse(response);
+ const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;
+ const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential);
+ if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {
+ return { skipStrategy: true };
+ }
+ if (responseError && !matchedSystemError && !isExponential) {
+ return { errorToThrow: responseError };
+ }
+ return (0, core_util_1.calculateRetryDelay)(retryCount, {
+ retryDelayInMs: retryInterval,
+ maxRetryDelayInMs: maxRetryInterval,
+ });
+ },
+ };
+}
+/**
+ * A response is a retry response if it has status codes:
+ * - 408, or
+ * - Greater or equal than 500, except for 501 and 505.
+ */
+function isExponentialRetryResponse(response) {
+ return Boolean(response &&
+ response.status !== undefined &&
+ (response.status >= 500 || response.status === 408) &&
+ response.status !== 501 &&
+ response.status !== 505);
+}
+/**
+ * Determines whether an error from a pipeline response was triggered in the network layer.
+ */
+function isSystemError(err) {
+ if (!err) {
+ return false;
+ }
+ return (err.code === "ETIMEDOUT" ||
+ err.code === "ESOCKETTIMEDOUT" ||
+ err.code === "ECONNREFUSED" ||
+ err.code === "ECONNRESET" ||
+ err.code === "ENOENT" ||
+ err.code === "ENOTFOUND");
}
+//# sourceMappingURL=exponentialRetryStrategy.js.map
-function defaultFactory (origin, opts) {
- return new Pool(origin, opts)
-}
+/***/ }),
-class ProxyAgent extends DispatcherBase {
- constructor (opts) {
- super(opts)
- this[kProxy] = buildProxyOptions(opts)
- this[kAgent] = new Agent(opts)
- this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
- ? opts.interceptors.ProxyAgent
- : []
+/***/ 40288:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (typeof opts === 'string') {
- opts = { uri: opts }
- }
- if (!opts || !opts.uri) {
- throw new InvalidArgumentError('Proxy opts.uri is mandatory')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isThrottlingRetryResponse = isThrottlingRetryResponse;
+exports.throttlingRetryStrategy = throttlingRetryStrategy;
+const helpers_js_1 = __nccwpck_require__(94982);
+/**
+ * The header that comes back from Azure services representing
+ * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry).
+ */
+const RetryAfterHeader = "Retry-After";
+/**
+ * The headers that come back from Azure services representing
+ * the amount of time (minimum) to wait to retry.
+ *
+ * "retry-after-ms", "x-ms-retry-after-ms" : milliseconds
+ * "Retry-After" : seconds or timestamp
+ */
+const AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader];
+/**
+ * A response is a throttling retry response if it has a throttling status code (429 or 503),
+ * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
+ *
+ * Returns the `retryAfterInMs` value if the response is a throttling retry response.
+ * If not throttling retry response, returns `undefined`.
+ *
+ * @internal
+ */
+function getRetryAfterInMs(response) {
+ if (!(response && [429, 503].includes(response.status)))
+ return undefined;
+ try {
+ // Headers: "retry-after-ms", "x-ms-retry-after-ms", "Retry-After"
+ for (const header of AllRetryAfterHeaders) {
+ const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header);
+ if (retryAfterValue === 0 || retryAfterValue) {
+ // "Retry-After" header ==> seconds
+ // "retry-after-ms", "x-ms-retry-after-ms" headers ==> milli-seconds
+ const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1;
+ return retryAfterValue * multiplyingFactor; // in milli-seconds
+ }
+ }
+ // RetryAfterHeader ("Retry-After") has a special case where it might be formatted as a date instead of a number of seconds
+ const retryAfterHeader = response.headers.get(RetryAfterHeader);
+ if (!retryAfterHeader)
+ return;
+ const date = Date.parse(retryAfterHeader);
+ const diff = date - Date.now();
+ // negative diff would mean a date in the past, so retry asap with 0 milliseconds
+ return Number.isFinite(diff) ? Math.max(0, diff) : undefined;
}
-
- const { clientFactory = defaultFactory } = opts
-
- if (typeof clientFactory !== 'function') {
- throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
+ catch (_a) {
+ return undefined;
}
+}
+/**
+ * A response is a retry response if it has a throttling status code (429 or 503),
+ * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
+ */
+function isThrottlingRetryResponse(response) {
+ return Number.isFinite(getRetryAfterInMs(response));
+}
+function throttlingRetryStrategy() {
+ return {
+ name: "throttlingRetryStrategy",
+ retry({ response }) {
+ const retryAfterInMs = getRetryAfterInMs(response);
+ if (!Number.isFinite(retryAfterInMs)) {
+ return { skipStrategy: true };
+ }
+ return {
+ retryAfterInMs,
+ };
+ },
+ };
+}
+//# sourceMappingURL=throttlingRetryStrategy.js.map
- this[kRequestTls] = opts.requestTls
- this[kProxyTls] = opts.proxyTls
- this[kProxyHeaders] = opts.headers || {}
+/***/ }),
- const resolvedUrl = new URL(opts.uri)
- const { origin, port, host, username, password } = resolvedUrl
+/***/ 85307:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (opts.auth && opts.token) {
- throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
- } else if (opts.auth) {
- /* @deprecated in favour of opts.token */
- this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
- } else if (opts.token) {
- this[kProxyHeaders]['proxy-authorization'] = opts.token
- } else if (username && password) {
- this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
- }
- const connect = buildConnector({ ...opts.proxyTls })
- this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
- this[kClient] = clientFactory(resolvedUrl, { connect })
- this[kAgent] = new Agent({
- ...opts,
- connect: async (opts, callback) => {
- let requestedHost = opts.host
- if (!opts.port) {
- requestedHost += `:${defaultProtocolPort(opts.protocol)}`
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.concat = concat;
+const tslib_1 = __nccwpck_require__(94176);
+const node_stream_1 = __nccwpck_require__(57075);
+const typeGuards_js_1 = __nccwpck_require__(24449);
+const file_js_1 = __nccwpck_require__(8581);
+function streamAsyncIterator() {
+ return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() {
+ const reader = this.getReader();
try {
- const { socket, statusCode } = await this[kClient].connect({
- origin,
- port,
- path: requestedHost,
- signal: opts.signal,
- headers: {
- ...this[kProxyHeaders],
- host
+ while (true) {
+ const { done, value } = yield tslib_1.__await(reader.read());
+ if (done) {
+ return yield tslib_1.__await(void 0);
+ }
+ yield yield tslib_1.__await(value);
}
- })
- if (statusCode !== 200) {
- socket.on('error', () => {}).destroy()
- callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
- }
- if (opts.protocol !== 'https:') {
- callback(null, socket)
- return
- }
- let servername
- if (this[kRequestTls]) {
- servername = this[kRequestTls].servername
- } else {
- servername = opts.servername
- }
- this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
- } catch (err) {
- callback(err)
}
- }
- })
- }
-
- dispatch (opts, handler) {
- const { host } = new URL(opts.origin)
- const headers = buildHeaders(opts.headers)
- throwIfProxyAuthIsSent(headers)
- return this[kAgent].dispatch(
- {
- ...opts,
- headers: {
- ...headers,
- host
+ finally {
+ reader.releaseLock();
}
- },
- handler
- )
- }
-
- async [kClose] () {
- await this[kAgent].close()
- await this[kClient].close()
- }
-
- async [kDestroy] () {
- await this[kAgent].destroy()
- await this[kClient].destroy()
- }
+ });
}
-
-/**
- * @param {string[] | Record} headers
- * @returns {Record}
- */
-function buildHeaders (headers) {
- // When using undici.fetch, the headers list is stored
- // as an array.
- if (Array.isArray(headers)) {
- /** @type {Record} */
- const headersPair = {}
-
- for (let i = 0; i < headers.length; i += 2) {
- headersPair[headers[i]] = headers[i + 1]
+function makeAsyncIterable(webStream) {
+ if (!webStream[Symbol.asyncIterator]) {
+ webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);
+ }
+ if (!webStream.values) {
+ webStream.values = streamAsyncIterator.bind(webStream);
+ }
+}
+function ensureNodeStream(stream) {
+ if (stream instanceof ReadableStream) {
+ makeAsyncIterable(stream);
+ return node_stream_1.Readable.fromWeb(stream);
+ }
+ else {
+ return stream;
+ }
+}
+function toStream(source) {
+ if (source instanceof Uint8Array) {
+ return node_stream_1.Readable.from(Buffer.from(source));
+ }
+ else if ((0, typeGuards_js_1.isBlob)(source)) {
+ return toStream((0, file_js_1.getRawContent)(source));
+ }
+ else {
+ return ensureNodeStream(source);
}
-
- return headersPair
- }
-
- return headers
}
-
/**
- * @param {Record} headers
+ * Utility function that concatenates a set of binary inputs into one combined output.
*
- * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
- * Nevertheless, it was changed and to avoid a security vulnerability by end users
- * this check was created.
- * It should be removed in the next major version for performance reasons
+ * @param sources - array of sources for the concatenation
+ * @returns - in Node, a (() =\> NodeJS.ReadableStream) which, when read, produces a concatenation of all the inputs.
+ * In browser, returns a `Blob` representing all the concatenated inputs.
+ *
+ * @internal
*/
-function throwIfProxyAuthIsSent (headers) {
- const existProxyAuth = headers && Object.keys(headers)
- .find((key) => key.toLowerCase() === 'proxy-authorization')
- if (existProxyAuth) {
- throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
- }
+async function concat(sources) {
+ return function () {
+ const streams = sources.map((x) => (typeof x === "function" ? x() : x)).map(toStream);
+ return node_stream_1.Readable.from((function () {
+ return tslib_1.__asyncGenerator(this, arguments, function* () {
+ var _a, e_1, _b, _c;
+ for (const stream of streams) {
+ try {
+ for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) {
+ _c = stream_1_1.value;
+ _d = false;
+ const chunk = _c;
+ yield yield tslib_1.__await(chunk);
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1));
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ }
+ });
+ })());
+ };
}
-
-module.exports = ProxyAgent
-
+//# sourceMappingURL=concat.js.map
/***/ }),
-/***/ 82576:
-/***/ ((module) => {
-
-
-
-let fastNow = Date.now()
-let fastNowTimeout
-
-const fastTimers = []
-
-function onTimeout () {
- fastNow = Date.now()
+/***/ 8581:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- let len = fastTimers.length
- let idx = 0
- while (idx < len) {
- const timer = fastTimers[idx]
- if (timer.state === 0) {
- timer.state = fastNow + timer.delay
- } else if (timer.state > 0 && fastNow >= timer.state) {
- timer.state = -1
- timer.callback(timer.opaque)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getRawContent = getRawContent;
+exports.createFileFromStream = createFileFromStream;
+exports.createFile = createFile;
+const core_util_1 = __nccwpck_require__(30991);
+const typeGuards_js_1 = __nccwpck_require__(24449);
+const unimplementedMethods = {
+ arrayBuffer: () => {
+ throw new Error("Not implemented");
+ },
+ slice: () => {
+ throw new Error("Not implemented");
+ },
+ text: () => {
+ throw new Error("Not implemented");
+ },
+};
+/**
+ * Private symbol used as key on objects created using createFile containing the
+ * original source of the file object.
+ *
+ * This is used in Node to access the original Node stream without using Blob#stream, which
+ * returns a web stream. This is done to avoid a couple of bugs to do with Blob#stream and
+ * Readable#to/fromWeb in Node versions we support:
+ * - https://github.com/nodejs/node/issues/42694 (fixed in Node 18.14)
+ * - https://github.com/nodejs/node/issues/48916 (fixed in Node 20.6)
+ *
+ * Once these versions are no longer supported, we may be able to stop doing this.
+ *
+ * @internal
+ */
+const rawContent = Symbol("rawContent");
+function hasRawContent(x) {
+ return typeof x[rawContent] === "function";
+}
+/**
+ * Extract the raw content from a given blob-like object. If the input was created using createFile
+ * or createFileFromStream, the exact content passed into createFile/createFileFromStream will be used.
+ * For true instances of Blob and File, returns the blob's content as a Web ReadableStream.
+ *
+ * @internal
+ */
+function getRawContent(blob) {
+ if (hasRawContent(blob)) {
+ return blob[rawContent]();
}
-
- if (timer.state === -1) {
- timer.state = -2
- if (idx !== len - 1) {
- fastTimers[idx] = fastTimers.pop()
- } else {
- fastTimers.pop()
- }
- len -= 1
- } else {
- idx += 1
+ else {
+ return blob.stream();
}
- }
-
- if (fastTimers.length > 0) {
- refreshTimeout()
- }
}
-
-function refreshTimeout () {
- if (fastNowTimeout && fastNowTimeout.refresh) {
- fastNowTimeout.refresh()
- } else {
- clearTimeout(fastNowTimeout)
- fastNowTimeout = setTimeout(onTimeout, 1e3)
- if (fastNowTimeout.unref) {
- fastNowTimeout.unref()
- }
- }
+/**
+ * Create an object that implements the File interface. This object is intended to be
+ * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
+ * other situations.
+ *
+ * Use this function to:
+ * - Create a File object for use in RequestBodyType.formData in environments where the
+ * global File object is unavailable.
+ * - Create a File-like object from a readable stream without reading the stream into memory.
+ *
+ * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is
+ * passed in a request's form data map, the stream will not be read into memory
+ * and instead will be streamed when the request is made. In the event of a retry, the
+ * stream needs to be read again, so this callback SHOULD return a fresh stream if possible.
+ * @param name - the name of the file.
+ * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
+ */
+function createFileFromStream(stream, name, options = {}) {
+ var _a, _b, _c, _d;
+ return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => {
+ const s = stream();
+ if ((0, typeGuards_js_1.isNodeReadableStream)(s)) {
+ throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.");
+ }
+ return s;
+ }, [rawContent]: stream });
}
-
-class Timeout {
- constructor (callback, delay, opaque) {
- this.callback = callback
- this.delay = delay
- this.opaque = opaque
-
- // -2 not in timer list
- // -1 in timer list but inactive
- // 0 in timer list waiting for time
- // > 0 in timer list waiting for time to expire
- this.state = -2
-
- this.refresh()
- }
-
- refresh () {
- if (this.state === -2) {
- fastTimers.push(this)
- if (!fastNowTimeout || fastTimers.length === 1) {
- refreshTimeout()
- }
+/**
+ * Create an object that implements the File interface. This object is intended to be
+ * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
+ * other situations.
+ *
+ * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.
+ *
+ * @param content - the content of the file as a Uint8Array in memory.
+ * @param name - the name of the file.
+ * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
+ */
+function createFile(content, name, options = {}) {
+ var _a, _b, _c;
+ if (core_util_1.isNodeLike) {
+ return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content });
}
-
- this.state = 0
- }
-
- clear () {
- this.state = -1
- }
-}
-
-module.exports = {
- setTimeout (callback, delay, opaque) {
- return delay < 1e3
- ? setTimeout(callback, delay, opaque)
- : new Timeout(callback, delay, opaque)
- },
- clearTimeout (timeout) {
- if (timeout instanceof Timeout) {
- timeout.clear()
- } else {
- clearTimeout(timeout)
+ else {
+ return new File([content], name, options);
}
- }
}
+//# sourceMappingURL=file.js.map
+/***/ }),
-/***/ }),
-
-/***/ 96114:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const diagnosticsChannel = __nccwpck_require__(31637)
-const { uid, states } = __nccwpck_require__(90077)
-const {
- kReadyState,
- kSentClose,
- kByteParser,
- kReceivedClose
-} = __nccwpck_require__(97945)
-const { fireEvent, failWebsocketConnection } = __nccwpck_require__(95506)
-const { CloseEvent } = __nccwpck_require__(47115)
-const { makeRequest } = __nccwpck_require__(2630)
-const { fetching } = __nccwpck_require__(11503)
-const { Headers } = __nccwpck_require__(12801)
-const { getGlobalDispatcher } = __nccwpck_require__(61481)
-const { kHeadersList } = __nccwpck_require__(68031)
-
-const channels = {}
-channels.open = diagnosticsChannel.channel('undici:websocket:open')
-channels.close = diagnosticsChannel.channel('undici:websocket:close')
-channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')
-
-/** @type {import('crypto')} */
-let crypto
-try {
- crypto = __nccwpck_require__(76982)
-} catch {
+/***/ 94982:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.delay = delay;
+exports.parseHeaderValueAsNumber = parseHeaderValueAsNumber;
+const abort_controller_1 = __nccwpck_require__(92242);
+const StandardAbortMessage = "The operation was aborted.";
/**
- * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
- * @param {URL} url
- * @param {string|string[]} protocols
- * @param {import('./websocket').WebSocket} ws
- * @param {(response: any) => void} onEstablish
- * @param {Partial} options
+ * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds.
+ * @param delayInMs - The number of milliseconds to be delayed.
+ * @param value - The value to be resolved with after a timeout of t milliseconds.
+ * @param options - The options for delay - currently abort options
+ * - abortSignal - The abortSignal associated with containing operation.
+ * - abortErrorMsg - The abort error message associated with containing operation.
+ * @returns Resolved promise
*/
-function establishWebSocketConnection (url, protocols, ws, onEstablish, options) {
- // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s
- // scheme is "ws", and to "https" otherwise.
- const requestURL = url
-
- requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
-
- // 2. Let request be a new request, whose URL is requestURL, client is client,
- // service-workers mode is "none", referrer is "no-referrer", mode is
- // "websocket", credentials mode is "include", cache mode is "no-store" ,
- // and redirect mode is "error".
- const request = makeRequest({
- urlList: [requestURL],
- serviceWorkers: 'none',
- referrer: 'no-referrer',
- mode: 'websocket',
- credentials: 'include',
- cache: 'no-store',
- redirect: 'error'
- })
-
- // Note: undici extension, allow setting custom headers.
- if (options.headers) {
- const headersList = new Headers(options.headers)[kHeadersList]
-
- request.headersList = headersList
- }
-
- // 3. Append (`Upgrade`, `websocket`) to request’s header list.
- // 4. Append (`Connection`, `Upgrade`) to request’s header list.
- // Note: both of these are handled by undici currently.
- // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
+function delay(delayInMs, value, options) {
+ return new Promise((resolve, reject) => {
+ let timer = undefined;
+ let onAborted = undefined;
+ const rejectOnAbort = () => {
+ return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage));
+ };
+ const removeListeners = () => {
+ if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) {
+ options.abortSignal.removeEventListener("abort", onAborted);
+ }
+ };
+ onAborted = () => {
+ if (timer) {
+ clearTimeout(timer);
+ }
+ removeListeners();
+ return rejectOnAbort();
+ };
+ if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) {
+ return rejectOnAbort();
+ }
+ timer = setTimeout(() => {
+ removeListeners();
+ resolve(value);
+ }, delayInMs);
+ if (options === null || options === void 0 ? void 0 : options.abortSignal) {
+ options.abortSignal.addEventListener("abort", onAborted);
+ }
+ });
+}
+/**
+ * @internal
+ * @returns the parsed value or undefined if the parsed value is invalid.
+ */
+function parseHeaderValueAsNumber(response, headerName) {
+ const value = response.headers.get(headerName);
+ if (!value)
+ return;
+ const valueAsNum = Number(value);
+ if (Number.isNaN(valueAsNum))
+ return;
+ return valueAsNum;
+}
+//# sourceMappingURL=helpers.js.map
- // 5. Let keyValue be a nonce consisting of a randomly selected
- // 16-byte value that has been forgiving-base64-encoded and
- // isomorphic encoded.
- const keyValue = crypto.randomBytes(16).toString('base64')
+/***/ }),
- // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
- // header list.
- request.headersList.append('sec-websocket-key', keyValue)
+/***/ 84111:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
- // header list.
- request.headersList.append('sec-websocket-version', '13')
- // 8. For each protocol in protocols, combine
- // (`Sec-WebSocket-Protocol`, protocol) in request’s header
- // list.
- for (const protocol of protocols) {
- request.headersList.append('sec-websocket-protocol', protocol)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.custom = void 0;
+const node_util_1 = __nccwpck_require__(57975);
+exports.custom = node_util_1.inspect.custom;
+//# sourceMappingURL=inspect.js.map
- // 9. Let permessageDeflate be a user-agent defined
- // "permessage-deflate" extension header value.
- // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
- // TODO: enable once permessage-deflate is supported
- const permessageDeflate = '' // 'permessage-deflate; 15'
+/***/ }),
- // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
- // request’s header list.
- // request.headersList.append('sec-websocket-extensions', permessageDeflate)
+/***/ 44720:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 11. Fetch request with useParallelQueue set to true, and
- // processResponse given response being these steps:
- const controller = fetching({
- request,
- useParallelQueue: true,
- dispatcher: options.dispatcher ?? getGlobalDispatcher(),
- processResponse (response) {
- // 1. If response is a network error or its status is not 101,
- // fail the WebSocket connection.
- if (response.type === 'error' || response.status !== 101) {
- failWebsocketConnection(ws, 'Received network error or non-101 status code.')
- return
- }
- // 2. If protocols is not the empty list and extracting header
- // list values given `Sec-WebSocket-Protocol` and response’s
- // header list results in null, failure, or the empty byte
- // sequence, then fail the WebSocket connection.
- if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
- failWebsocketConnection(ws, 'Server did not respond with sent protocols.')
- return
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Sanitizer = void 0;
+const core_util_1 = __nccwpck_require__(30991);
+const RedactedString = "REDACTED";
+// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts
+const defaultAllowedHeaderNames = [
+ "x-ms-client-request-id",
+ "x-ms-return-client-request-id",
+ "x-ms-useragent",
+ "x-ms-correlation-request-id",
+ "x-ms-request-id",
+ "client-request-id",
+ "ms-cv",
+ "return-client-request-id",
+ "traceparent",
+ "Access-Control-Allow-Credentials",
+ "Access-Control-Allow-Headers",
+ "Access-Control-Allow-Methods",
+ "Access-Control-Allow-Origin",
+ "Access-Control-Expose-Headers",
+ "Access-Control-Max-Age",
+ "Access-Control-Request-Headers",
+ "Access-Control-Request-Method",
+ "Origin",
+ "Accept",
+ "Accept-Encoding",
+ "Cache-Control",
+ "Connection",
+ "Content-Length",
+ "Content-Type",
+ "Date",
+ "ETag",
+ "Expires",
+ "If-Match",
+ "If-Modified-Since",
+ "If-None-Match",
+ "If-Unmodified-Since",
+ "Last-Modified",
+ "Pragma",
+ "Request-Id",
+ "Retry-After",
+ "Server",
+ "Transfer-Encoding",
+ "User-Agent",
+ "WWW-Authenticate",
+];
+const defaultAllowedQueryParameters = ["api-version"];
+/**
+ * @internal
+ */
+class Sanitizer {
+ constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) {
+ allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
+ allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
+ this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
+ this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
+ }
+ sanitize(obj) {
+ const seen = new Set();
+ return JSON.stringify(obj, (key, value) => {
+ // Ensure Errors include their interesting non-enumerable members
+ if (value instanceof Error) {
+ return Object.assign(Object.assign({}, value), { name: value.name, message: value.message });
+ }
+ if (key === "headers") {
+ return this.sanitizeHeaders(value);
+ }
+ else if (key === "url") {
+ return this.sanitizeUrl(value);
+ }
+ else if (key === "query") {
+ return this.sanitizeQuery(value);
+ }
+ else if (key === "body") {
+ // Don't log the request body
+ return undefined;
+ }
+ else if (key === "response") {
+ // Don't log response again
+ return undefined;
+ }
+ else if (key === "operationSpec") {
+ // When using sendOperationRequest, the request carries a massive
+ // field with the autorest spec. No need to log it.
+ return undefined;
+ }
+ else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) {
+ if (seen.has(value)) {
+ return "[Circular]";
+ }
+ seen.add(value);
+ }
+ return value;
+ }, 2);
+ }
+ sanitizeUrl(value) {
+ if (typeof value !== "string" || value === null || value === "") {
+ return value;
+ }
+ const url = new URL(value);
+ if (!url.search) {
+ return value;
+ }
+ for (const [key] of url.searchParams) {
+ if (!this.allowedQueryParameters.has(key.toLowerCase())) {
+ url.searchParams.set(key, RedactedString);
+ }
+ }
+ return url.toString();
+ }
+ sanitizeHeaders(obj) {
+ const sanitized = {};
+ for (const key of Object.keys(obj)) {
+ if (this.allowedHeaderNames.has(key.toLowerCase())) {
+ sanitized[key] = obj[key];
+ }
+ else {
+ sanitized[key] = RedactedString;
+ }
+ }
+ return sanitized;
+ }
+ sanitizeQuery(value) {
+ if (typeof value !== "object" || value === null) {
+ return value;
+ }
+ const sanitized = {};
+ for (const k of Object.keys(value)) {
+ if (this.allowedQueryParameters.has(k.toLowerCase())) {
+ sanitized[k] = value[k];
+ }
+ else {
+ sanitized[k] = RedactedString;
+ }
+ }
+ return sanitized;
+ }
+}
+exports.Sanitizer = Sanitizer;
+//# sourceMappingURL=sanitizer.js.map
- // 3. Follow the requirements stated step 2 to step 6, inclusive,
- // of the last set of steps in section 4.1 of The WebSocket
- // Protocol to validate response. This either results in fail
- // the WebSocket connection or the WebSocket connection is
- // established.
+/***/ }),
- // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
- // header field contains a value that is not an ASCII case-
- // insensitive match for the value "websocket", the client MUST
- // _Fail the WebSocket Connection_.
- if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
- failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".')
- return
- }
+/***/ 82534:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 3. If the response lacks a |Connection| header field or the
- // |Connection| header field doesn't contain a token that is an
- // ASCII case-insensitive match for the value "Upgrade", the client
- // MUST _Fail the WebSocket Connection_.
- if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
- failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".')
- return
- }
- // 4. If the response lacks a |Sec-WebSocket-Accept| header field or
- // the |Sec-WebSocket-Accept| contains a value other than the
- // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
- // Key| (as a string, not base64-decoded) with the string "258EAFA5-
- // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
- // trailing whitespace, the client MUST _Fail the WebSocket
- // Connection_.
- const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
- const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
- if (secWSAccept !== digest) {
- failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
- return
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.DEFAULT_CYCLER_OPTIONS = void 0;
+exports.createTokenCycler = createTokenCycler;
+const helpers_js_1 = __nccwpck_require__(94982);
+// Default options for the cycler if none are provided
+exports.DEFAULT_CYCLER_OPTIONS = {
+ forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires
+ retryIntervalInMs: 3000, // Allow refresh attempts every 3s
+ refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry
+};
+/**
+ * Converts an an unreliable access token getter (which may resolve with null)
+ * into an AccessTokenGetter by retrying the unreliable getter in a regular
+ * interval.
+ *
+ * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.
+ * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.
+ * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.
+ * @returns - A promise that, if it resolves, will resolve with an access token.
+ */
+async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
+ // This wrapper handles exceptions gracefully as long as we haven't exceeded
+ // the timeout.
+ async function tryGetAccessToken() {
+ if (Date.now() < refreshTimeout) {
+ try {
+ return await getAccessToken();
+ }
+ catch (_a) {
+ return null;
+ }
+ }
+ else {
+ const finalToken = await getAccessToken();
+ // Timeout is up, so throw if it's still null
+ if (finalToken === null) {
+ throw new Error("Failed to refresh access token.");
+ }
+ return finalToken;
+ }
+ }
+ let token = await tryGetAccessToken();
+ while (token === null) {
+ await (0, helpers_js_1.delay)(retryIntervalInMs);
+ token = await tryGetAccessToken();
+ }
+ return token;
+}
+/**
+ * Creates a token cycler from a credential, scopes, and optional settings.
+ *
+ * A token cycler represents a way to reliably retrieve a valid access token
+ * from a TokenCredential. It will handle initializing the token, refreshing it
+ * when it nears expiration, and synchronizes refresh attempts to avoid
+ * concurrency hazards.
+ *
+ * @param credential - the underlying TokenCredential that provides the access
+ * token
+ * @param tokenCyclerOptions - optionally override default settings for the cycler
+ *
+ * @returns - a function that reliably produces a valid access token
+ */
+function createTokenCycler(credential, tokenCyclerOptions) {
+ let refreshWorker = null;
+ let token = null;
+ let tenantId;
+ const options = Object.assign(Object.assign({}, exports.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions);
+ /**
+ * This little holder defines several predicates that we use to construct
+ * the rules of refreshing the token.
+ */
+ const cycler = {
+ /**
+ * Produces true if a refresh job is currently in progress.
+ */
+ get isRefreshing() {
+ return refreshWorker !== null;
+ },
+ /**
+ * Produces true if the cycler SHOULD refresh (we are within the refresh
+ * window and not already refreshing)
+ */
+ get shouldRefresh() {
+ var _a;
+ if (cycler.isRefreshing) {
+ return false;
+ }
+ if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) {
+ return true;
+ }
+ return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now();
+ },
+ /**
+ * Produces true if the cycler MUST refresh (null or nearly-expired
+ * token).
+ */
+ get mustRefresh() {
+ return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now());
+ },
+ };
+ /**
+ * Starts a refresh job or returns the existing job if one is already
+ * running.
+ */
+ function refresh(scopes, getTokenOptions) {
+ var _a;
+ if (!cycler.isRefreshing) {
+ // We bind `scopes` here to avoid passing it around a lot
+ const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
+ // Take advantage of promise chaining to insert an assignment to `token`
+ // before the refresh can be considered done.
+ refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs,
+ // If we don't have a token, then we should timeout immediately
+ (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now())
+ .then((_token) => {
+ refreshWorker = null;
+ token = _token;
+ tenantId = getTokenOptions.tenantId;
+ return token;
+ })
+ .catch((reason) => {
+ // We also should reset the refresher if we enter a failed state. All
+ // existing awaiters will throw, but subsequent requests will start a
+ // new retry chain.
+ refreshWorker = null;
+ token = null;
+ tenantId = undefined;
+ throw reason;
+ });
+ }
+ return refreshWorker;
+ }
+ return async (scopes, tokenOptions) => {
+ //
+ // Simple rules:
+ // - If we MUST refresh, then return the refresh task, blocking
+ // the pipeline until a token is available.
+ // - If we SHOULD refresh, then run refresh but don't return it
+ // (we can still use the cached token).
+ // - Return the token, since it's fine if we didn't return in
+ // step 1.
+ //
+ const hasClaimChallenge = Boolean(tokenOptions.claims);
+ const tenantIdChanged = tenantId !== tokenOptions.tenantId;
+ if (hasClaimChallenge) {
+ // If we've received a claim, we know the existing token isn't valid
+ // We want to clear it so that that refresh worker won't use the old expiration time as a timeout
+ token = null;
+ }
+ // If the tenantId passed in token options is different to the one we have
+ // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to
+ // refresh the token with the new tenantId or token.
+ const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
+ if (mustRefresh) {
+ return refresh(scopes, tokenOptions);
+ }
+ if (cycler.shouldRefresh) {
+ refresh(scopes, tokenOptions);
+ }
+ return token;
+ };
+}
+//# sourceMappingURL=tokenCycler.js.map
- // 5. If the response includes a |Sec-WebSocket-Extensions| header
- // field and this header field indicates the use of an extension
- // that was not present in the client's handshake (the server has
- // indicated an extension not requested by the client), the client
- // MUST _Fail the WebSocket Connection_. (The parsing of this
- // header field to determine which extensions are requested is
- // discussed in Section 9.1.)
- const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
+/***/ }),
- if (secExtension !== null && secExtension !== permessageDeflate) {
- failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')
- return
- }
+/***/ 24449:
+/***/ ((__unused_webpack_module, exports) => {
- // 6. If the response includes a |Sec-WebSocket-Protocol| header field
- // and this header field indicates the use of a subprotocol that was
- // not present in the client's handshake (the server has indicated a
- // subprotocol not requested by the client), the client MUST _Fail
- // the WebSocket Connection_.
- const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
- if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {
- failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
- return
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isNodeReadableStream = isNodeReadableStream;
+exports.isWebReadableStream = isWebReadableStream;
+exports.isReadableStream = isReadableStream;
+exports.isBlob = isBlob;
+function isNodeReadableStream(x) {
+ return Boolean(x && typeof x["pipe"] === "function");
+}
+function isWebReadableStream(x) {
+ return Boolean(x &&
+ typeof x.getReader === "function" &&
+ typeof x.tee === "function");
+}
+function isReadableStream(x) {
+ return isNodeReadableStream(x) || isWebReadableStream(x);
+}
+function isBlob(x) {
+ return typeof x.stream === "function";
+}
+//# sourceMappingURL=typeGuards.js.map
- response.socket.on('data', onSocketData)
- response.socket.on('close', onSocketClose)
- response.socket.on('error', onSocketError)
+/***/ }),
- if (channels.open.hasSubscribers) {
- channels.open.publish({
- address: response.socket.address(),
- protocol: secProtocol,
- extensions: secExtension
- })
- }
+/***/ 87747:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- onEstablish(response)
- }
- })
- return controller
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getUserAgentHeaderName = getUserAgentHeaderName;
+exports.getUserAgentValue = getUserAgentValue;
+const userAgentPlatform_js_1 = __nccwpck_require__(72100);
+const constants_js_1 = __nccwpck_require__(91791);
+function getUserAgentString(telemetryInfo) {
+ const parts = [];
+ for (const [key, value] of telemetryInfo) {
+ const token = value ? `${key}/${value}` : key;
+ parts.push(token);
+ }
+ return parts.join(" ");
}
-
/**
- * @param {Buffer} chunk
+ * @internal
*/
-function onSocketData (chunk) {
- if (!this.ws[kByteParser].write(chunk)) {
- this.pause()
- }
+function getUserAgentHeaderName() {
+ return (0, userAgentPlatform_js_1.getHeaderName)();
}
-
/**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
+ * @internal
*/
-function onSocketClose () {
- const { ws } = this
-
- // If the TCP connection was closed after the
- // WebSocket closing handshake was completed, the WebSocket connection
- // is said to have been closed _cleanly_.
- const wasClean = ws[kSentClose] && ws[kReceivedClose]
-
- let code = 1005
- let reason = ''
-
- const result = ws[kByteParser].closingInfo
-
- if (result) {
- code = result.code ?? 1005
- reason = result.reason
- } else if (!ws[kSentClose]) {
- // If _The WebSocket
- // Connection is Closed_ and no Close control frame was received by the
- // endpoint (such as could occur if the underlying transport connection
- // is lost), _The WebSocket Connection Close Code_ is considered to be
- // 1006.
- code = 1006
- }
-
- // 1. Change the ready state to CLOSED (3).
- ws[kReadyState] = states.CLOSED
-
- // 2. If the user agent was required to fail the WebSocket
- // connection, or if the WebSocket connection was closed
- // after being flagged as full, fire an event named error
- // at the WebSocket object.
- // TODO
-
- // 3. Fire an event named close at the WebSocket object,
- // using CloseEvent, with the wasClean attribute
- // initialized to true if the connection closed cleanly
- // and false otherwise, the code attribute initialized to
- // the WebSocket connection close code, and the reason
- // attribute initialized to the result of applying UTF-8
- // decode without BOM to the WebSocket connection close
- // reason.
- fireEvent('close', ws, CloseEvent, {
- wasClean, code, reason
- })
-
- if (channels.close.hasSubscribers) {
- channels.close.publish({
- websocket: ws,
- code,
- reason
- })
- }
+async function getUserAgentValue(prefix) {
+ const runtimeInfo = new Map();
+ runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION);
+ await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo);
+ const defaultAgent = getUserAgentString(runtimeInfo);
+ const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
+ return userAgentValue;
}
+//# sourceMappingURL=userAgent.js.map
-function onSocketError (error) {
- const { ws } = this
+/***/ }),
- ws[kReadyState] = states.CLOSING
+/***/ 72100:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (channels.socketError.hasSubscribers) {
- channels.socketError.publish(error)
- }
- this.destroy()
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getHeaderName = getHeaderName;
+exports.setPlatformSpecificData = setPlatformSpecificData;
+const tslib_1 = __nccwpck_require__(94176);
+const os = tslib_1.__importStar(__nccwpck_require__(48161));
+const process = tslib_1.__importStar(__nccwpck_require__(1708));
+/**
+ * @internal
+ */
+function getHeaderName() {
+ return "User-Agent";
}
-
-module.exports = {
- establishWebSocketConnection
+/**
+ * @internal
+ */
+async function setPlatformSpecificData(map) {
+ if (process && process.versions) {
+ const versions = process.versions;
+ if (versions.bun) {
+ map.set("Bun", versions.bun);
+ }
+ else if (versions.deno) {
+ map.set("Deno", versions.deno);
+ }
+ else if (versions.node) {
+ map.set("Node", versions.node);
+ }
+ }
+ map.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`);
}
-
+//# sourceMappingURL=userAgentPlatform.js.map
/***/ }),
-/***/ 90077:
-/***/ ((module) => {
+/***/ 7651:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createTracingClient = exports.useInstrumenter = void 0;
+var instrumenter_js_1 = __nccwpck_require__(7565);
+Object.defineProperty(exports, "useInstrumenter", ({ enumerable: true, get: function () { return instrumenter_js_1.useInstrumenter; } }));
+var tracingClient_js_1 = __nccwpck_require__(30530);
+Object.defineProperty(exports, "createTracingClient", ({ enumerable: true, get: function () { return tracingClient_js_1.createTracingClient; } }));
+//# sourceMappingURL=index.js.map
-// This is a Globally Unique Identifier unique used
-// to validate that the endpoint accepts websocket
-// connections.
-// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3
-const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
+/***/ }),
-/** @type {PropertyDescriptor} */
-const staticPropertyDescriptors = {
- enumerable: true,
- writable: false,
- configurable: false
-}
+/***/ 7565:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const states = {
- CONNECTING: 0,
- OPEN: 1,
- CLOSING: 2,
- CLOSED: 3
-}
-const opcodes = {
- CONTINUATION: 0x0,
- TEXT: 0x1,
- BINARY: 0x2,
- CLOSE: 0x8,
- PING: 0x9,
- PONG: 0xA
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createDefaultTracingSpan = createDefaultTracingSpan;
+exports.createDefaultInstrumenter = createDefaultInstrumenter;
+exports.useInstrumenter = useInstrumenter;
+exports.getInstrumenter = getInstrumenter;
+const tracingContext_js_1 = __nccwpck_require__(81334);
+const state_js_1 = __nccwpck_require__(53398);
+function createDefaultTracingSpan() {
+ return {
+ end: () => {
+ // noop
+ },
+ isRecording: () => false,
+ recordException: () => {
+ // noop
+ },
+ setAttribute: () => {
+ // noop
+ },
+ setStatus: () => {
+ // noop
+ },
+ addEvent: () => {
+ // noop
+ },
+ };
}
-
-const maxUnsigned16Bit = 2 ** 16 - 1 // 65535
-
-const parserStates = {
- INFO: 0,
- PAYLOADLENGTH_16: 2,
- PAYLOADLENGTH_64: 3,
- READ_DATA: 4
+function createDefaultInstrumenter() {
+ return {
+ createRequestHeaders: () => {
+ return {};
+ },
+ parseTraceparentHeader: () => {
+ return undefined;
+ },
+ startSpan: (_name, spanOptions) => {
+ return {
+ span: createDefaultTracingSpan(),
+ tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }),
+ };
+ },
+ withContext(_context, callback, ...callbackArgs) {
+ return callback(...callbackArgs);
+ },
+ };
}
-
-const emptyBuffer = Buffer.allocUnsafe(0)
-
-module.exports = {
- uid,
- staticPropertyDescriptors,
- states,
- opcodes,
- maxUnsigned16Bit,
- parserStates,
- emptyBuffer
+/**
+ * Extends the Azure SDK with support for a given instrumenter implementation.
+ *
+ * @param instrumenter - The instrumenter implementation to use.
+ */
+function useInstrumenter(instrumenter) {
+ state_js_1.state.instrumenterImplementation = instrumenter;
}
-
+/**
+ * Gets the currently set instrumenter, a No-Op instrumenter by default.
+ *
+ * @returns The currently set instrumenter
+ */
+function getInstrumenter() {
+ if (!state_js_1.state.instrumenterImplementation) {
+ state_js_1.state.instrumenterImplementation = createDefaultInstrumenter();
+ }
+ return state_js_1.state.instrumenterImplementation;
+}
+//# sourceMappingURL=instrumenter.js.map
/***/ }),
-/***/ 47115:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 53398:
+/***/ ((__unused_webpack_module, exports) => {
-const { webidl } = __nccwpck_require__(94354)
-const { kEnumerableProperty } = __nccwpck_require__(89500)
-const { MessagePort } = __nccwpck_require__(28167)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.state = void 0;
/**
- * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
+ * @internal
+ *
+ * Holds the singleton instrumenter, to be shared across CJS and ESM imports.
*/
-class MessageEvent extends Event {
- #eventInit
-
- constructor (type, eventInitDict = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' })
-
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.MessageEventInit(eventInitDict)
-
- super(type, eventInitDict)
-
- this.#eventInit = eventInitDict
- }
-
- get data () {
- webidl.brandCheck(this, MessageEvent)
-
- return this.#eventInit.data
- }
+exports.state = {
+ instrumenterImplementation: undefined,
+};
+//# sourceMappingURL=state-cjs.cjs.map
- get origin () {
- webidl.brandCheck(this, MessageEvent)
+/***/ }),
- return this.#eventInit.origin
- }
+/***/ 30530:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- get lastEventId () {
- webidl.brandCheck(this, MessageEvent)
- return this.#eventInit.lastEventId
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createTracingClient = createTracingClient;
+const instrumenter_js_1 = __nccwpck_require__(7565);
+const tracingContext_js_1 = __nccwpck_require__(81334);
+/**
+ * Creates a new tracing client.
+ *
+ * @param options - Options used to configure the tracing client.
+ * @returns - An instance of {@link TracingClient}.
+ */
+function createTracingClient(options) {
+ const { namespace, packageName, packageVersion } = options;
+ function startSpan(name, operationOptions, spanOptions) {
+ var _a;
+ const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName: packageName, packageVersion: packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext }));
+ let tracingContext = startSpanResult.tracingContext;
+ const span = startSpanResult.span;
+ if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) {
+ tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace);
+ }
+ span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace));
+ const updatedOptions = Object.assign({}, operationOptions, {
+ tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }),
+ });
+ return {
+ span,
+ updatedOptions,
+ };
+ }
+ async function withSpan(name, operationOptions, callback, spanOptions) {
+ const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);
+ try {
+ const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span)));
+ span.setStatus({ status: "success" });
+ return result;
+ }
+ catch (err) {
+ span.setStatus({ status: "error", error: err });
+ throw err;
+ }
+ finally {
+ span.end();
+ }
+ }
+ function withContext(context, callback, ...callbackArgs) {
+ return (0, instrumenter_js_1.getInstrumenter)().withContext(context, callback, ...callbackArgs);
+ }
+ /**
+ * Parses a traceparent header value into a span identifier.
+ *
+ * @param traceparentHeader - The traceparent header to parse.
+ * @returns An implementation-specific identifier for the span.
+ */
+ function parseTraceparentHeader(traceparentHeader) {
+ return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader);
+ }
+ /**
+ * Creates a set of request headers to propagate tracing information to a backend.
+ *
+ * @param tracingContext - The context containing the span to serialize.
+ * @returns The set of headers to add to a request.
+ */
+ function createRequestHeaders(tracingContext) {
+ return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext);
+ }
+ return {
+ startSpan,
+ withSpan,
+ withContext,
+ parseTraceparentHeader,
+ createRequestHeaders,
+ };
+}
+//# sourceMappingURL=tracingClient.js.map
- get source () {
- webidl.brandCheck(this, MessageEvent)
+/***/ }),
- return this.#eventInit.source
- }
+/***/ 81334:
+/***/ ((__unused_webpack_module, exports) => {
- get ports () {
- webidl.brandCheck(this, MessageEvent)
- if (!Object.isFrozen(this.#eventInit.ports)) {
- Object.freeze(this.#eventInit.ports)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TracingContextImpl = exports.knownContextKeys = void 0;
+exports.createTracingContext = createTracingContext;
+/** @internal */
+exports.knownContextKeys = {
+ span: Symbol.for("@azure/core-tracing span"),
+ namespace: Symbol.for("@azure/core-tracing namespace"),
+};
+/**
+ * Creates a new {@link TracingContext} with the given options.
+ * @param options - A set of known keys that may be set on the context.
+ * @returns A new {@link TracingContext} with the given options.
+ *
+ * @internal
+ */
+function createTracingContext(options = {}) {
+ let context = new TracingContextImpl(options.parentContext);
+ if (options.span) {
+ context = context.setValue(exports.knownContextKeys.span, options.span);
}
+ if (options.namespace) {
+ context = context.setValue(exports.knownContextKeys.namespace, options.namespace);
+ }
+ return context;
+}
+/** @internal */
+class TracingContextImpl {
+ constructor(initialContext) {
+ this._contextMap =
+ initialContext instanceof TracingContextImpl
+ ? new Map(initialContext._contextMap)
+ : new Map();
+ }
+ setValue(key, value) {
+ const newContext = new TracingContextImpl(this);
+ newContext._contextMap.set(key, value);
+ return newContext;
+ }
+ getValue(key) {
+ return this._contextMap.get(key);
+ }
+ deleteValue(key) {
+ const newContext = new TracingContextImpl(this);
+ newContext._contextMap.delete(key);
+ return newContext;
+ }
+}
+exports.TracingContextImpl = TracingContextImpl;
+//# sourceMappingURL=tracingContext.js.map
- return this.#eventInit.ports
- }
-
- initMessageEvent (
- type,
- bubbles = false,
- cancelable = false,
- data = null,
- origin = '',
- lastEventId = '',
- source = null,
- ports = []
- ) {
- webidl.brandCheck(this, MessageEvent)
+/***/ }),
- webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' })
+/***/ 86805:
+/***/ ((__unused_webpack_module, exports) => {
- return new MessageEvent(type, {
- bubbles, cancelable, data, origin, lastEventId, source, ports
- })
- }
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.cancelablePromiseRace = cancelablePromiseRace;
/**
- * @see https://websockets.spec.whatwg.org/#the-closeevent-interface
+ * promise.race() wrapper that aborts rest of promises as soon as the first promise settles.
*/
-class CloseEvent extends Event {
- #eventInit
-
- constructor (type, eventInitDict = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' })
-
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.CloseEventInit(eventInitDict)
-
- super(type, eventInitDict)
-
- this.#eventInit = eventInitDict
- }
-
- get wasClean () {
- webidl.brandCheck(this, CloseEvent)
-
- return this.#eventInit.wasClean
- }
+async function cancelablePromiseRace(abortablePromiseBuilders, options) {
+ var _a, _b;
+ const aborter = new AbortController();
+ function abortHandler() {
+ aborter.abort();
+ }
+ (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler);
+ try {
+ return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal })));
+ }
+ finally {
+ aborter.abort();
+ (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler);
+ }
+}
+//# sourceMappingURL=aborterUtils.js.map
- get code () {
- webidl.brandCheck(this, CloseEvent)
+/***/ }),
- return this.#eventInit.code
- }
+/***/ 84073:
+/***/ ((__unused_webpack_module, exports) => {
- get reason () {
- webidl.brandCheck(this, CloseEvent)
- return this.#eventInit.reason
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.uint8ArrayToString = uint8ArrayToString;
+exports.stringToUint8Array = stringToUint8Array;
+/**
+ * The helper that transforms bytes with specific character encoding into string
+ * @param bytes - the uint8array bytes
+ * @param format - the format we use to encode the byte
+ * @returns a string of the encoded string
+ */
+function uint8ArrayToString(bytes, format) {
+ return Buffer.from(bytes).toString(format);
}
+/**
+ * The helper that transforms string to specific character encoded bytes array.
+ * @param value - the string to be converted
+ * @param format - the format we use to decode the value
+ * @returns a uint8array
+ */
+function stringToUint8Array(value, format) {
+ return Buffer.from(value, format);
+}
+//# sourceMappingURL=bytesEncoding.js.map
-// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
-class ErrorEvent extends Event {
- #eventInit
-
- constructor (type, eventInitDict) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' })
+/***/ }),
- super(type, eventInitDict)
+/***/ 2910:
+/***/ ((__unused_webpack_module, exports) => {
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})
- this.#eventInit = eventInitDict
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+var _a, _b, _c, _d;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isReactNative = exports.isNodeRuntime = exports.isNode = exports.isNodeLike = exports.isBun = exports.isDeno = exports.isWebWorker = exports.isBrowser = void 0;
+/**
+ * A constant that indicates whether the environment the code is running is a Web Browser.
+ */
+// eslint-disable-next-line @azure/azure-sdk/ts-no-window
+exports.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is a Web Worker.
+ */
+exports.isWebWorker = typeof self === "object" &&
+ typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" &&
+ (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" ||
+ ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" ||
+ ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope");
+/**
+ * A constant that indicates whether the environment the code is running is Deno.
+ */
+exports.isDeno = typeof Deno !== "undefined" &&
+ typeof Deno.version !== "undefined" &&
+ typeof Deno.version.deno !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is Bun.sh.
+ */
+exports.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ */
+exports.isNodeLike = typeof globalThis.process !== "undefined" &&
+ Boolean(globalThis.process.version) &&
+ Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node);
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ * @deprecated Use `isNodeLike` instead.
+ */
+exports.isNode = exports.isNodeLike;
+/**
+ * A constant that indicates whether the environment the code is running is Node.JS.
+ */
+exports.isNodeRuntime = exports.isNodeLike && !exports.isBun && !exports.isDeno;
+/**
+ * A constant that indicates whether the environment the code is running is in React-Native.
+ */
+// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js
+exports.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative";
+//# sourceMappingURL=checkEnvironment.js.map
- get message () {
- webidl.brandCheck(this, ErrorEvent)
+/***/ }),
- return this.#eventInit.message
- }
+/***/ 33716:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- get filename () {
- webidl.brandCheck(this, ErrorEvent)
- return this.#eventInit.filename
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createAbortablePromise = createAbortablePromise;
+const abort_controller_1 = __nccwpck_require__(92242);
+/**
+ * Creates an abortable promise.
+ * @param buildPromise - A function that takes the resolve and reject functions as parameters.
+ * @param options - The options for the abortable promise.
+ * @returns A promise that can be aborted.
+ */
+function createAbortablePromise(buildPromise, options) {
+ const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
+ return new Promise((resolve, reject) => {
+ function rejectOnAbort() {
+ reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted."));
+ }
+ function removeListeners() {
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort);
+ }
+ function onAbort() {
+ cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort();
+ removeListeners();
+ rejectOnAbort();
+ }
+ if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) {
+ return rejectOnAbort();
+ }
+ try {
+ buildPromise((x) => {
+ removeListeners();
+ resolve(x);
+ }, (x) => {
+ removeListeners();
+ reject(x);
+ });
+ }
+ catch (err) {
+ reject(err);
+ }
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort);
+ });
+}
+//# sourceMappingURL=createAbortablePromise.js.map
- get lineno () {
- webidl.brandCheck(this, ErrorEvent)
+/***/ }),
- return this.#eventInit.lineno
- }
+/***/ 54744:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- get colno () {
- webidl.brandCheck(this, ErrorEvent)
- return this.#eventInit.colno
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.delay = delay;
+exports.calculateRetryDelay = calculateRetryDelay;
+const createAbortablePromise_js_1 = __nccwpck_require__(33716);
+const random_js_1 = __nccwpck_require__(50832);
+const StandardAbortMessage = "The delay was aborted.";
+/**
+ * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.
+ * @param timeInMs - The number of milliseconds to be delayed.
+ * @param options - The options for delay - currently abort options
+ * @returns Promise that is resolved after timeInMs
+ */
+function delay(timeInMs, options) {
+ let token;
+ const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
+ return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve) => {
+ token = setTimeout(resolve, timeInMs);
+ }, {
+ cleanupBeforeAbort: () => clearTimeout(token),
+ abortSignal,
+ abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage,
+ });
+}
+/**
+ * Calculates the delay interval for retry attempts using exponential delay with jitter.
+ * @param retryAttempt - The current retry attempt number.
+ * @param config - The exponential retry configuration.
+ * @returns An object containing the calculated retry delay.
+ */
+function calculateRetryDelay(retryAttempt, config) {
+ // Exponentially increase the delay each time
+ const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
+ // Don't let the delay exceed the maximum
+ const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
+ // Allow the final value to have some "jitter" (within 50% of the delay size) so
+ // that retries across multiple clients don't occur simultaneously.
+ const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2);
+ return { retryAfterInMs };
+}
+//# sourceMappingURL=delay.js.map
- get error () {
- webidl.brandCheck(this, ErrorEvent)
+/***/ }),
- return this.#eventInit.error
- }
-}
+/***/ 69213:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-Object.defineProperties(MessageEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'MessageEvent',
- configurable: true
- },
- data: kEnumerableProperty,
- origin: kEnumerableProperty,
- lastEventId: kEnumerableProperty,
- source: kEnumerableProperty,
- ports: kEnumerableProperty,
- initMessageEvent: kEnumerableProperty
-})
-Object.defineProperties(CloseEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'CloseEvent',
- configurable: true
- },
- reason: kEnumerableProperty,
- code: kEnumerableProperty,
- wasClean: kEnumerableProperty
-})
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isError = isError;
+exports.getErrorMessage = getErrorMessage;
+const object_js_1 = __nccwpck_require__(15360);
+/**
+ * Typeguard for an error object shape (has name and message)
+ * @param e - Something caught by a catch clause.
+ */
+function isError(e) {
+ if ((0, object_js_1.isObject)(e)) {
+ const hasName = typeof e.name === "string";
+ const hasMessage = typeof e.message === "string";
+ return hasName && hasMessage;
+ }
+ return false;
+}
+/**
+ * Given what is thought to be an error object, return the message if possible.
+ * If the message is missing, returns a stringified version of the input.
+ * @param e - Something thrown from a try block
+ * @returns The error message or a string of the input
+ */
+function getErrorMessage(e) {
+ if (isError(e)) {
+ return e.message;
+ }
+ else {
+ let stringified;
+ try {
+ if (typeof e === "object" && e) {
+ stringified = JSON.stringify(e);
+ }
+ else {
+ stringified = String(e);
+ }
+ }
+ catch (err) {
+ stringified = "[unable to stringify input]";
+ }
+ return `Unknown error ${stringified}`;
+ }
+}
+//# sourceMappingURL=error.js.map
-Object.defineProperties(ErrorEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'ErrorEvent',
- configurable: true
- },
- message: kEnumerableProperty,
- filename: kEnumerableProperty,
- lineno: kEnumerableProperty,
- colno: kEnumerableProperty,
- error: kEnumerableProperty
-})
+/***/ }),
-webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)
+/***/ 30991:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.MessagePort
-)
-const eventInit = [
- {
- key: 'bubbles',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'cancelable',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'composed',
- converter: webidl.converters.boolean,
- defaultValue: false
- }
-]
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.stringToUint8Array = exports.uint8ArrayToString = exports.isWebWorker = exports.isReactNative = exports.isDeno = exports.isNodeRuntime = exports.isNodeLike = exports.isNode = exports.isBun = exports.isBrowser = exports.randomUUID = exports.objectHasProperty = exports.isObjectWithProperties = exports.isDefined = exports.computeSha256Hmac = exports.computeSha256Hash = exports.getErrorMessage = exports.isError = exports.isObject = exports.getRandomIntegerInclusive = exports.createAbortablePromise = exports.cancelablePromiseRace = exports.calculateRetryDelay = exports.delay = void 0;
+var delay_js_1 = __nccwpck_require__(54744);
+Object.defineProperty(exports, "delay", ({ enumerable: true, get: function () { return delay_js_1.delay; } }));
+Object.defineProperty(exports, "calculateRetryDelay", ({ enumerable: true, get: function () { return delay_js_1.calculateRetryDelay; } }));
+var aborterUtils_js_1 = __nccwpck_require__(86805);
+Object.defineProperty(exports, "cancelablePromiseRace", ({ enumerable: true, get: function () { return aborterUtils_js_1.cancelablePromiseRace; } }));
+var createAbortablePromise_js_1 = __nccwpck_require__(33716);
+Object.defineProperty(exports, "createAbortablePromise", ({ enumerable: true, get: function () { return createAbortablePromise_js_1.createAbortablePromise; } }));
+var random_js_1 = __nccwpck_require__(50832);
+Object.defineProperty(exports, "getRandomIntegerInclusive", ({ enumerable: true, get: function () { return random_js_1.getRandomIntegerInclusive; } }));
+var object_js_1 = __nccwpck_require__(15360);
+Object.defineProperty(exports, "isObject", ({ enumerable: true, get: function () { return object_js_1.isObject; } }));
+var error_js_1 = __nccwpck_require__(69213);
+Object.defineProperty(exports, "isError", ({ enumerable: true, get: function () { return error_js_1.isError; } }));
+Object.defineProperty(exports, "getErrorMessage", ({ enumerable: true, get: function () { return error_js_1.getErrorMessage; } }));
+var sha256_js_1 = __nccwpck_require__(83712);
+Object.defineProperty(exports, "computeSha256Hash", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hash; } }));
+Object.defineProperty(exports, "computeSha256Hmac", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hmac; } }));
+var typeGuards_js_1 = __nccwpck_require__(98489);
+Object.defineProperty(exports, "isDefined", ({ enumerable: true, get: function () { return typeGuards_js_1.isDefined; } }));
+Object.defineProperty(exports, "isObjectWithProperties", ({ enumerable: true, get: function () { return typeGuards_js_1.isObjectWithProperties; } }));
+Object.defineProperty(exports, "objectHasProperty", ({ enumerable: true, get: function () { return typeGuards_js_1.objectHasProperty; } }));
+var uuidUtils_js_1 = __nccwpck_require__(50751);
+Object.defineProperty(exports, "randomUUID", ({ enumerable: true, get: function () { return uuidUtils_js_1.randomUUID; } }));
+var checkEnvironment_js_1 = __nccwpck_require__(2910);
+Object.defineProperty(exports, "isBrowser", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBrowser; } }));
+Object.defineProperty(exports, "isBun", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBun; } }));
+Object.defineProperty(exports, "isNode", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNode; } }));
+Object.defineProperty(exports, "isNodeLike", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNodeLike; } }));
+Object.defineProperty(exports, "isNodeRuntime", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNodeRuntime; } }));
+Object.defineProperty(exports, "isDeno", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isDeno; } }));
+Object.defineProperty(exports, "isReactNative", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isReactNative; } }));
+Object.defineProperty(exports, "isWebWorker", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isWebWorker; } }));
+var bytesEncoding_js_1 = __nccwpck_require__(84073);
+Object.defineProperty(exports, "uint8ArrayToString", ({ enumerable: true, get: function () { return bytesEncoding_js_1.uint8ArrayToString; } }));
+Object.defineProperty(exports, "stringToUint8Array", ({ enumerable: true, get: function () { return bytesEncoding_js_1.stringToUint8Array; } }));
+//# sourceMappingURL=index.js.map
-webidl.converters.MessageEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'data',
- converter: webidl.converters.any,
- defaultValue: null
- },
- {
- key: 'origin',
- converter: webidl.converters.USVString,
- defaultValue: ''
- },
- {
- key: 'lastEventId',
- converter: webidl.converters.DOMString,
- defaultValue: ''
- },
- {
- key: 'source',
- // Node doesn't implement WindowProxy or ServiceWorker, so the only
- // valid value for source is a MessagePort.
- converter: webidl.nullableConverter(webidl.converters.MessagePort),
- defaultValue: null
- },
- {
- key: 'ports',
- converter: webidl.converters['sequence'],
- get defaultValue () {
- return []
- }
- }
-])
+/***/ }),
-webidl.converters.CloseEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'wasClean',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'code',
- converter: webidl.converters['unsigned short'],
- defaultValue: 0
- },
- {
- key: 'reason',
- converter: webidl.converters.USVString,
- defaultValue: ''
- }
-])
+/***/ 15360:
+/***/ ((__unused_webpack_module, exports) => {
-webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'message',
- converter: webidl.converters.DOMString,
- defaultValue: ''
- },
- {
- key: 'filename',
- converter: webidl.converters.USVString,
- defaultValue: ''
- },
- {
- key: 'lineno',
- converter: webidl.converters['unsigned long'],
- defaultValue: 0
- },
- {
- key: 'colno',
- converter: webidl.converters['unsigned long'],
- defaultValue: 0
- },
- {
- key: 'error',
- converter: webidl.converters.any
- }
-])
-module.exports = {
- MessageEvent,
- CloseEvent,
- ErrorEvent
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isObject = isObject;
+/**
+ * Helper to determine when an input is a generic JS object.
+ * @returns true when input is an object type that is not null, Array, RegExp, or Date.
+ */
+function isObject(input) {
+ return (typeof input === "object" &&
+ input !== null &&
+ !Array.isArray(input) &&
+ !(input instanceof RegExp) &&
+ !(input instanceof Date));
}
-
+//# sourceMappingURL=object.js.map
/***/ }),
-/***/ 42697:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { maxUnsigned16Bit } = __nccwpck_require__(90077)
+/***/ 50832:
+/***/ ((__unused_webpack_module, exports) => {
-/** @type {import('crypto')} */
-let crypto
-try {
- crypto = __nccwpck_require__(76982)
-} catch {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getRandomIntegerInclusive = getRandomIntegerInclusive;
+/**
+ * Returns a random integer value between a lower and upper bound,
+ * inclusive of both bounds.
+ * Note that this uses Math.random and isn't secure. If you need to use
+ * this for any kind of security purpose, find a better source of random.
+ * @param min - The smallest integer value allowed.
+ * @param max - The largest integer value allowed.
+ */
+function getRandomIntegerInclusive(min, max) {
+ // Make sure inputs are integers.
+ min = Math.ceil(min);
+ max = Math.floor(max);
+ // Pick a random offset from zero to the size of the range.
+ // Since Math.random() can never return 1, we have to make the range one larger
+ // in order to be inclusive of the maximum value after we take the floor.
+ const offset = Math.floor(Math.random() * (max - min + 1));
+ return offset + min;
}
+//# sourceMappingURL=random.js.map
-class WebsocketFrameSend {
- /**
- * @param {Buffer|undefined} data
- */
- constructor (data) {
- this.frameData = data
- this.maskKey = crypto.randomBytes(4)
- }
-
- createFrame (opcode) {
- const bodyLength = this.frameData?.byteLength ?? 0
+/***/ }),
- /** @type {number} */
- let payloadLength = bodyLength // 0-125
- let offset = 6
+/***/ 83712:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (bodyLength > maxUnsigned16Bit) {
- offset += 8 // payload length is next 8 bytes
- payloadLength = 127
- } else if (bodyLength > 125) {
- offset += 2 // payload length is next 2 bytes
- payloadLength = 126
- }
- const buffer = Buffer.allocUnsafe(bodyLength + offset)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.computeSha256Hmac = computeSha256Hmac;
+exports.computeSha256Hash = computeSha256Hash;
+const crypto_1 = __nccwpck_require__(76982);
+/**
+ * Generates a SHA-256 HMAC signature.
+ * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
+ * @param stringToSign - The data to be signed.
+ * @param encoding - The textual encoding to use for the returned HMAC digest.
+ */
+async function computeSha256Hmac(key, stringToSign, encoding) {
+ const decodedKey = Buffer.from(key, "base64");
+ return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding);
+}
+/**
+ * Generates a SHA-256 hash.
+ * @param content - The data to be included in the hash.
+ * @param encoding - The textual encoding to use for the returned hash.
+ */
+async function computeSha256Hash(content, encoding) {
+ return (0, crypto_1.createHash)("sha256").update(content).digest(encoding);
+}
+//# sourceMappingURL=sha256.js.map
- // Clear first 2 bytes, everything else is overwritten
- buffer[0] = buffer[1] = 0
- buffer[0] |= 0x80 // FIN
- buffer[0] = (buffer[0] & 0xF0) + opcode // opcode
+/***/ }),
- /*! ws. MIT License. Einar Otto Stangvik */
- buffer[offset - 4] = this.maskKey[0]
- buffer[offset - 3] = this.maskKey[1]
- buffer[offset - 2] = this.maskKey[2]
- buffer[offset - 1] = this.maskKey[3]
+/***/ 98489:
+/***/ ((__unused_webpack_module, exports) => {
- buffer[1] = payloadLength
- if (payloadLength === 126) {
- buffer.writeUInt16BE(bodyLength, 2)
- } else if (payloadLength === 127) {
- // Clear extended payload length
- buffer[2] = buffer[3] = 0
- buffer.writeUIntBE(bodyLength, 4, 6)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isDefined = isDefined;
+exports.isObjectWithProperties = isObjectWithProperties;
+exports.objectHasProperty = objectHasProperty;
+/**
+ * Helper TypeGuard that checks if something is defined or not.
+ * @param thing - Anything
+ */
+function isDefined(thing) {
+ return typeof thing !== "undefined" && thing !== null;
+}
+/**
+ * Helper TypeGuard that checks if the input is an object with the specified properties.
+ * @param thing - Anything.
+ * @param properties - The name of the properties that should appear in the object.
+ */
+function isObjectWithProperties(thing, properties) {
+ if (!isDefined(thing) || typeof thing !== "object") {
+ return false;
}
-
- buffer[1] |= 0x80 // MASK
-
- // mask body
- for (let i = 0; i < bodyLength; i++) {
- buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]
+ for (const property of properties) {
+ if (!objectHasProperty(thing, property)) {
+ return false;
+ }
}
-
- return buffer
- }
+ return true;
}
-
-module.exports = {
- WebsocketFrameSend
+/**
+ * Helper TypeGuard that checks if the input is an object with the specified property.
+ * @param thing - Any object.
+ * @param property - The name of the property that should appear in the object.
+ */
+function objectHasProperty(thing, property) {
+ return (isDefined(thing) && typeof thing === "object" && property in thing);
}
-
+//# sourceMappingURL=typeGuards.js.map
/***/ }),
-/***/ 13607:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 50751:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+var _a;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.randomUUID = randomUUID;
+const crypto_1 = __nccwpck_require__(76982);
+// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+.
+const uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function"
+ ? globalThis.crypto.randomUUID.bind(globalThis.crypto)
+ : crypto_1.randomUUID;
+/**
+ * Generated Universally Unique Identifier
+ *
+ * @returns RFC4122 v4 UUID.
+ */
+function randomUUID() {
+ return uuidFunction();
+}
+//# sourceMappingURL=uuidUtils.js.map
-const { Writable } = __nccwpck_require__(2203)
-const diagnosticsChannel = __nccwpck_require__(31637)
-const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(90077)
-const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(97945)
-const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(95506)
-const { WebsocketFrameSend } = __nccwpck_require__(42697)
+/***/ }),
-// This code was influenced by ws released under the MIT license.
-// Copyright (c) 2011 Einar Otto Stangvik
-// Copyright (c) 2013 Arnout Kazemier and contributors
-// Copyright (c) 2016 Luigi Pinca and contributors
+/***/ 21328:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const channels = {}
-channels.ping = diagnosticsChannel.channel('undici:websocket:ping')
-channels.pong = diagnosticsChannel.channel('undici:websocket:pong')
-class ByteParser extends Writable {
- #buffers = []
- #byteOffset = 0
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.parseXML = exports.stringifyXML = void 0;
+var xml_js_1 = __nccwpck_require__(86537);
+Object.defineProperty(exports, "stringifyXML", ({ enumerable: true, get: function () { return xml_js_1.stringifyXML; } }));
+Object.defineProperty(exports, "parseXML", ({ enumerable: true, get: function () { return xml_js_1.parseXML; } }));
+var xml_common_js_1 = __nccwpck_require__(51882);
+Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return xml_common_js_1.XML_ATTRKEY; } }));
+Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return xml_common_js_1.XML_CHARKEY; } }));
+//# sourceMappingURL=index.js.map
- #state = parserStates.INFO
+/***/ }),
- #info = {}
- #fragments = []
+/***/ 51882:
+/***/ ((__unused_webpack_module, exports) => {
- constructor (ws) {
- super()
- this.ws = ws
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0;
+/**
+ * Default key used to access the XML attributes.
+ */
+exports.XML_ATTRKEY = "$";
+/**
+ * Default key used to access the XML value content.
+ */
+exports.XML_CHARKEY = "_";
+//# sourceMappingURL=xml.common.js.map
- /**
- * @param {Buffer} chunk
- * @param {() => void} callback
- */
- _write (chunk, _, callback) {
- this.#buffers.push(chunk)
- this.#byteOffset += chunk.length
+/***/ }),
- this.run(callback)
- }
+/***/ 86537:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- /**
- * Runs whenever a new chunk is received.
- * Callback is called whenever there are no more chunks buffering,
- * or not enough bytes are buffered to parse.
- */
- run (callback) {
- while (true) {
- if (this.#state === parserStates.INFO) {
- // If there aren't enough bytes to parse the payload length, etc.
- if (this.#byteOffset < 2) {
- return callback()
- }
- const buffer = this.consume(2)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.stringifyXML = stringifyXML;
+exports.parseXML = parseXML;
+const fast_xml_parser_1 = __nccwpck_require__(1537);
+const xml_common_js_1 = __nccwpck_require__(51882);
+function getCommonOptions(options) {
+ var _a;
+ return {
+ attributesGroupName: xml_common_js_1.XML_ATTRKEY,
+ textNodeName: (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : xml_common_js_1.XML_CHARKEY,
+ ignoreAttributes: false,
+ suppressBooleanAttributes: false,
+ };
+}
+function getSerializerOptions(options = {}) {
+ var _a, _b;
+ return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "root", cdataPropName: (_b = options.cdataPropName) !== null && _b !== void 0 ? _b : "__cdata" });
+}
+function getParserOptions(options = {}) {
+ return Object.assign(Object.assign({}, getCommonOptions(options)), { parseAttributeValue: false, parseTagValue: false, attributeNamePrefix: "", stopNodes: options.stopNodes, processEntities: true });
+}
+/**
+ * Converts given JSON object to XML string
+ * @param obj - JSON object to be converted into XML string
+ * @param opts - Options that govern the XML building of given JSON object
+ * `rootName` indicates the name of the root element in the resulting XML
+ */
+function stringifyXML(obj, opts = {}) {
+ const parserOptions = getSerializerOptions(opts);
+ const j2x = new fast_xml_parser_1.XMLBuilder(parserOptions);
+ const node = { [parserOptions.rootNodeName]: obj };
+ const xmlData = j2x.build(node);
+ return `${xmlData}`.replace(/\n/g, "");
+}
+/**
+ * Converts given XML string into JSON
+ * @param str - String containing the XML content to be parsed into JSON
+ * @param opts - Options that govern the parsing of given xml string
+ * `includeRoot` indicates whether the root element is to be included or not in the output
+ */
+async function parseXML(str, opts = {}) {
+ if (!str) {
+ throw new Error("Document is empty");
+ }
+ const validation = fast_xml_parser_1.XMLValidator.validate(str);
+ if (validation !== true) {
+ throw validation;
+ }
+ const parser = new fast_xml_parser_1.XMLParser(getParserOptions(opts));
+ const parsedXml = parser.parse(str);
+ // Remove the node.
+ // This is a change in behavior on fxp v4. Issue #424
+ if (parsedXml["?xml"]) {
+ delete parsedXml["?xml"];
+ }
+ if (!opts.includeRoot) {
+ for (const key of Object.keys(parsedXml)) {
+ const value = parsedXml[key];
+ return typeof value === "object" ? Object.assign({}, value) : value;
+ }
+ }
+ return parsedXml;
+}
+//# sourceMappingURL=xml.js.map
- this.#info.fin = (buffer[0] & 0x80) !== 0
- this.#info.opcode = buffer[0] & 0x0F
+/***/ }),
- // If we receive a fragmented message, we use the type of the first
- // frame to parse the full message as binary/text, when it's terminated
- this.#info.originalOpcode ??= this.#info.opcode
+/***/ 37024:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION
- if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) {
- // Only text and binary frames can be fragmented
- failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')
- return
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const log_js_1 = __nccwpck_require__(30881);
+const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined;
+let enabledString;
+let enabledNamespaces = [];
+let skippedNamespaces = [];
+const debuggers = [];
+if (debugEnvVariable) {
+ enable(debugEnvVariable);
+}
+const debugObj = Object.assign((namespace) => {
+ return createDebugger(namespace);
+}, {
+ enable,
+ enabled,
+ disable,
+ log: log_js_1.log,
+});
+function enable(namespaces) {
+ enabledString = namespaces;
+ enabledNamespaces = [];
+ skippedNamespaces = [];
+ const wildcard = /\*/g;
+ const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?"));
+ for (const ns of namespaceList) {
+ if (ns.startsWith("-")) {
+ skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`));
+ }
+ else {
+ enabledNamespaces.push(new RegExp(`^${ns}$`));
+ }
+ }
+ for (const instance of debuggers) {
+ instance.enabled = enabled(instance.namespace);
+ }
+}
+function enabled(namespace) {
+ if (namespace.endsWith("*")) {
+ return true;
+ }
+ for (const skipped of skippedNamespaces) {
+ if (skipped.test(namespace)) {
+ return false;
+ }
+ }
+ for (const enabledNamespace of enabledNamespaces) {
+ if (enabledNamespace.test(namespace)) {
+ return true;
+ }
+ }
+ return false;
+}
+function disable() {
+ const result = enabledString || "";
+ enable("");
+ return result;
+}
+function createDebugger(namespace) {
+ const newDebugger = Object.assign(debug, {
+ enabled: enabled(namespace),
+ destroy,
+ log: debugObj.log,
+ namespace,
+ extend,
+ });
+ function debug(...args) {
+ if (!newDebugger.enabled) {
+ return;
+ }
+ if (args.length > 0) {
+ args[0] = `${namespace} ${args[0]}`;
}
+ newDebugger.log(...args);
+ }
+ debuggers.push(newDebugger);
+ return newDebugger;
+}
+function destroy() {
+ const index = debuggers.indexOf(this);
+ if (index >= 0) {
+ debuggers.splice(index, 1);
+ return true;
+ }
+ return false;
+}
+function extend(namespace) {
+ const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
+ newDebugger.log = this.log;
+ return newDebugger;
+}
+exports["default"] = debugObj;
+//# sourceMappingURL=debug.js.map
- const payloadLength = buffer[1] & 0x7F
+/***/ }),
- if (payloadLength <= 125) {
- this.#info.payloadLength = payloadLength
- this.#state = parserStates.READ_DATA
- } else if (payloadLength === 126) {
- this.#state = parserStates.PAYLOADLENGTH_16
- } else if (payloadLength === 127) {
- this.#state = parserStates.PAYLOADLENGTH_64
- }
+/***/ 50143:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (this.#info.fragmented && payloadLength > 125) {
- // A fragmented frame can't be fragmented itself
- failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')
- return
- } else if (
- (this.#info.opcode === opcodes.PING ||
- this.#info.opcode === opcodes.PONG ||
- this.#info.opcode === opcodes.CLOSE) &&
- payloadLength > 125
- ) {
- // Control frames can have a payload length of 125 bytes MAX
- failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.')
- return
- } else if (this.#info.opcode === opcodes.CLOSE) {
- if (payloadLength === 1) {
- failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')
- return
- }
- const body = this.consume(payloadLength)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureLogger = void 0;
+exports.setLogLevel = setLogLevel;
+exports.getLogLevel = getLogLevel;
+exports.createClientLogger = createClientLogger;
+const tslib_1 = __nccwpck_require__(94176);
+const debug_js_1 = tslib_1.__importDefault(__nccwpck_require__(37024));
+const registeredLoggers = new Set();
+const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined;
+let azureLogLevel;
+/**
+ * The AzureLogger provides a mechanism for overriding where logs are output to.
+ * By default, logs are sent to stderr.
+ * Override the `log` method to redirect logs to another location.
+ */
+exports.AzureLogger = (0, debug_js_1.default)("azure");
+exports.AzureLogger.log = (...args) => {
+ debug_js_1.default.log(...args);
+};
+const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"];
+if (logLevelFromEnv) {
+ // avoid calling setLogLevel because we don't want a mis-set environment variable to crash
+ if (isAzureLogLevel(logLevelFromEnv)) {
+ setLogLevel(logLevelFromEnv);
+ }
+ else {
+ console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`);
+ }
+}
+/**
+ * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
+ * @param level - The log level to enable for logging.
+ * Options from most verbose to least verbose are:
+ * - verbose
+ * - info
+ * - warning
+ * - error
+ */
+function setLogLevel(level) {
+ if (level && !isAzureLogLevel(level)) {
+ throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`);
+ }
+ azureLogLevel = level;
+ const enabledNamespaces = [];
+ for (const logger of registeredLoggers) {
+ if (shouldEnable(logger)) {
+ enabledNamespaces.push(logger.namespace);
+ }
+ }
+ debug_js_1.default.enable(enabledNamespaces.join(","));
+}
+/**
+ * Retrieves the currently specified log level.
+ */
+function getLogLevel() {
+ return azureLogLevel;
+}
+const levelMap = {
+ verbose: 400,
+ info: 300,
+ warning: 200,
+ error: 100,
+};
+/**
+ * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
+ * @param namespace - The name of the SDK package.
+ * @hidden
+ */
+function createClientLogger(namespace) {
+ const clientRootLogger = exports.AzureLogger.extend(namespace);
+ patchLogMethod(exports.AzureLogger, clientRootLogger);
+ return {
+ error: createLogger(clientRootLogger, "error"),
+ warning: createLogger(clientRootLogger, "warning"),
+ info: createLogger(clientRootLogger, "info"),
+ verbose: createLogger(clientRootLogger, "verbose"),
+ };
+}
+function patchLogMethod(parent, child) {
+ child.log = (...args) => {
+ parent.log(...args);
+ };
+}
+function createLogger(parent, level) {
+ const logger = Object.assign(parent.extend(level), {
+ level,
+ });
+ patchLogMethod(parent, logger);
+ if (shouldEnable(logger)) {
+ const enabledNamespaces = debug_js_1.default.disable();
+ debug_js_1.default.enable(enabledNamespaces + "," + logger.namespace);
+ }
+ registeredLoggers.add(logger);
+ return logger;
+}
+function shouldEnable(logger) {
+ return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]);
+}
+function isAzureLogLevel(logLevel) {
+ return AZURE_LOG_LEVELS.includes(logLevel);
+}
+//# sourceMappingURL=index.js.map
- this.#info.closeInfo = this.parseCloseBody(false, body)
+/***/ }),
- if (!this.ws[kSentClose]) {
- // If an endpoint receives a Close frame and did not previously send a
- // Close frame, the endpoint MUST send a Close frame in response. (When
- // sending a Close frame in response, the endpoint typically echos the
- // status code it received.)
- const body = Buffer.allocUnsafe(2)
- body.writeUInt16BE(this.#info.closeInfo.code, 0)
- const closeFrame = new WebsocketFrameSend(body)
+/***/ 30881:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this.ws[kResponse].socket.write(
- closeFrame.createFrame(opcodes.CLOSE),
- (err) => {
- if (!err) {
- this.ws[kSentClose] = true
- }
- }
- )
- }
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- this.ws[kReadyState] = states.CLOSING
- this.ws[kReceivedClose] = true
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.log = log;
+const tslib_1 = __nccwpck_require__(94176);
+const node_os_1 = __nccwpck_require__(48161);
+const node_util_1 = tslib_1.__importDefault(__nccwpck_require__(57975));
+const process = tslib_1.__importStar(__nccwpck_require__(1708));
+function log(message, ...args) {
+ process.stderr.write(`${node_util_1.default.format(message, ...args)}${node_os_1.EOL}`);
+}
+//# sourceMappingURL=log.js.map
- this.end()
+/***/ }),
- return
- } else if (this.#info.opcode === opcodes.PING) {
- // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
- // response, unless it already received a Close frame.
- // A Pong frame sent in response to a Ping frame must have identical
- // "Application data"
+/***/ 8946:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- const body = this.consume(payloadLength)
- if (!this.ws[kReceivedClose]) {
- const frame = new WebsocketFrameSend(body)
- this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))
+const WritableStream = (__nccwpck_require__(57075).Writable)
+const inherits = (__nccwpck_require__(57975).inherits)
- if (channels.ping.hasSubscribers) {
- channels.ping.publish({
- payload: body
- })
- }
- }
+const StreamSearch = __nccwpck_require__(86484)
- this.#state = parserStates.INFO
+const PartStream = __nccwpck_require__(87952)
+const HeaderParser = __nccwpck_require__(87003)
- if (this.#byteOffset > 0) {
- continue
- } else {
- callback()
- return
- }
- } else if (this.#info.opcode === opcodes.PONG) {
- // A Pong frame MAY be sent unsolicited. This serves as a
- // unidirectional heartbeat. A response to an unsolicited Pong frame is
- // not expected.
+const DASH = 45
+const B_ONEDASH = Buffer.from('-')
+const B_CRLF = Buffer.from('\r\n')
+const EMPTY_FN = function () {}
- const body = this.consume(payloadLength)
+function Dicer (cfg) {
+ if (!(this instanceof Dicer)) { return new Dicer(cfg) }
+ WritableStream.call(this, cfg)
- if (channels.pong.hasSubscribers) {
- channels.pong.publish({
- payload: body
- })
- }
+ if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }
- if (this.#byteOffset > 0) {
- continue
- } else {
- callback()
- return
- }
- }
- } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
- if (this.#byteOffset < 2) {
- return callback()
- }
+ if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }
- const buffer = this.consume(2)
+ this._headerFirst = cfg.headerFirst
- this.#info.payloadLength = buffer.readUInt16BE(0)
- this.#state = parserStates.READ_DATA
- } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
- if (this.#byteOffset < 8) {
- return callback()
- }
+ this._dashes = 0
+ this._parts = 0
+ this._finished = false
+ this._realFinish = false
+ this._isPreamble = true
+ this._justMatched = false
+ this._firstWrite = true
+ this._inHeader = true
+ this._part = undefined
+ this._cb = undefined
+ this._ignoreData = false
+ this._partOpts = { highWaterMark: cfg.partHwm }
+ this._pause = false
- const buffer = this.consume(8)
- const upper = buffer.readUInt32BE(0)
+ const self = this
+ this._hparser = new HeaderParser(cfg)
+ this._hparser.on('header', function (header) {
+ self._inHeader = false
+ self._part.emit('header', header)
+ })
+}
+inherits(Dicer, WritableStream)
- // 2^31 is the maxinimum bytes an arraybuffer can contain
- // on 32-bit systems. Although, on 64-bit systems, this is
- // 2^53-1 bytes.
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length
- // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275
- // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e
- if (upper > 2 ** 31 - 1) {
- failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')
+Dicer.prototype.emit = function (ev) {
+ if (ev === 'finish' && !this._realFinish) {
+ if (!this._finished) {
+ const self = this
+ process.nextTick(function () {
+ self.emit('error', new Error('Unexpected end of multipart data'))
+ if (self._part && !self._ignoreData) {
+ const type = (self._isPreamble ? 'Preamble' : 'Part')
+ self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))
+ self._part.push(null)
+ process.nextTick(function () {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ })
return
}
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ })
+ }
+ } else { WritableStream.prototype.emit.apply(this, arguments) }
+}
- const lower = buffer.readUInt32BE(4)
+Dicer.prototype._write = function (data, encoding, cb) {
+ // ignore unexpected data (e.g. extra trailer data after finished)
+ if (!this._hparser && !this._bparser) { return cb() }
- this.#info.payloadLength = (upper << 8) + lower
- this.#state = parserStates.READ_DATA
- } else if (this.#state === parserStates.READ_DATA) {
- if (this.#byteOffset < this.#info.payloadLength) {
- // If there is still more data in this chunk that needs to be read
- return callback()
- } else if (this.#byteOffset >= this.#info.payloadLength) {
- // If the server sent multiple frames in a single chunk
+ if (this._headerFirst && this._isPreamble) {
+ if (!this._part) {
+ this._part = new PartStream(this._partOpts)
+ if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() }
+ }
+ const r = this._hparser.push(data)
+ if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }
+ }
- const body = this.consume(this.#info.payloadLength)
+ // allows for "easier" testing
+ if (this._firstWrite) {
+ this._bparser.push(B_CRLF)
+ this._firstWrite = false
+ }
- this.#fragments.push(body)
+ this._bparser.push(data)
- // If the frame is unfragmented, or a fragmented frame was terminated,
- // a message was received
- if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) {
- const fullMessage = Buffer.concat(this.#fragments)
+ if (this._pause) { this._cb = cb } else { cb() }
+}
- websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage)
+Dicer.prototype.reset = function () {
+ this._part = undefined
+ this._bparser = undefined
+ this._hparser = undefined
+}
- this.#info = {}
- this.#fragments.length = 0
- }
+Dicer.prototype.setBoundary = function (boundary) {
+ const self = this
+ this._bparser = new StreamSearch('\r\n--' + boundary)
+ this._bparser.on('info', function (isMatch, data, start, end) {
+ self._oninfo(isMatch, data, start, end)
+ })
+}
- this.#state = parserStates.INFO
- }
- }
+Dicer.prototype._ignore = function () {
+ if (this._part && !this._ignoreData) {
+ this._ignoreData = true
+ this._part.on('error', EMPTY_FN)
+ // we must perform some kind of read on the stream even though we are
+ // ignoring the data, otherwise node's Readable stream will not emit 'end'
+ // after pushing null to the stream
+ this._part.resume()
+ }
+}
- if (this.#byteOffset > 0) {
- continue
+Dicer.prototype._oninfo = function (isMatch, data, start, end) {
+ let buf; const self = this; let i = 0; let r; let shouldWriteMore = true
+
+ if (!this._part && this._justMatched && data) {
+ while (this._dashes < 2 && (start + i) < end) {
+ if (data[start + i] === DASH) {
+ ++i
+ ++this._dashes
} else {
- callback()
+ if (this._dashes) { buf = B_ONEDASH }
+ this._dashes = 0
break
}
}
+ if (this._dashes === 2) {
+ if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) }
+ this.reset()
+ this._finished = true
+ // no more parts will be added
+ if (self._parts === 0) {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ }
+ }
+ if (this._dashes) { return }
}
-
- /**
- * Take n bytes from the buffered Buffers
- * @param {number} n
- * @returns {Buffer|null}
- */
- consume (n) {
- if (n > this.#byteOffset) {
- return null
- } else if (n === 0) {
- return emptyBuffer
+ if (this._justMatched) { this._justMatched = false }
+ if (!this._part) {
+ this._part = new PartStream(this._partOpts)
+ this._part._read = function (n) {
+ self._unpause()
}
-
- if (this.#buffers[0].length === n) {
- this.#byteOffset -= this.#buffers[0].length
- return this.#buffers.shift()
+ if (this._isPreamble && this.listenerCount('preamble') !== 0) {
+ this.emit('preamble', this._part)
+ } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) {
+ this.emit('part', this._part)
+ } else {
+ this._ignore()
}
-
- const buffer = Buffer.allocUnsafe(n)
- let offset = 0
-
- while (offset !== n) {
- const next = this.#buffers[0]
- const { length } = next
-
- if (length + offset === n) {
- buffer.set(this.#buffers.shift(), offset)
- break
- } else if (length + offset > n) {
- buffer.set(next.subarray(0, n - offset), offset)
- this.#buffers[0] = next.subarray(n - offset)
- break
- } else {
- buffer.set(this.#buffers.shift(), offset)
- offset += next.length
+ if (!this._isPreamble) { this._inHeader = true }
+ }
+ if (data && start < end && !this._ignoreData) {
+ if (this._isPreamble || !this._inHeader) {
+ if (buf) { shouldWriteMore = this._part.push(buf) }
+ shouldWriteMore = this._part.push(data.slice(start, end))
+ if (!shouldWriteMore) { this._pause = true }
+ } else if (!this._isPreamble && this._inHeader) {
+ if (buf) { this._hparser.push(buf) }
+ r = this._hparser.push(data.slice(start, end))
+ if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }
+ }
+ }
+ if (isMatch) {
+ this._hparser.reset()
+ if (this._isPreamble) { this._isPreamble = false } else {
+ if (start !== end) {
+ ++this._parts
+ this._part.on('end', function () {
+ if (--self._parts === 0) {
+ if (self._finished) {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ } else {
+ self._unpause()
+ }
+ }
+ })
}
}
+ this._part.push(null)
+ this._part = undefined
+ this._ignoreData = false
+ this._justMatched = true
+ this._dashes = 0
+ }
+}
- this.#byteOffset -= n
+Dicer.prototype._unpause = function () {
+ if (!this._pause) { return }
- return buffer
+ this._pause = false
+ if (this._cb) {
+ const cb = this._cb
+ this._cb = undefined
+ cb()
}
+}
- parseCloseBody (onlyCode, data) {
- // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
- /** @type {number|undefined} */
- let code
+module.exports = Dicer
- if (data.length >= 2) {
- // _The WebSocket Connection Close Code_ is
- // defined as the status code (Section 7.4) contained in the first Close
- // control frame received by the application
- code = data.readUInt16BE(0)
- }
- if (onlyCode) {
- if (!isValidStatusCode(code)) {
- return null
- }
+/***/ }),
- return { code }
- }
+/***/ 87003:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
- /** @type {Buffer} */
- let reason = data.subarray(2)
- // Remove BOM
- if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {
- reason = reason.subarray(3)
- }
- if (code !== undefined && !isValidStatusCode(code)) {
- return null
- }
+const EventEmitter = (__nccwpck_require__(78474).EventEmitter)
+const inherits = (__nccwpck_require__(57975).inherits)
+const getLimit = __nccwpck_require__(5245)
- try {
- // TODO: optimize this
- reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)
- } catch {
- return null
+const StreamSearch = __nccwpck_require__(86484)
+
+const B_DCRLF = Buffer.from('\r\n\r\n')
+const RE_CRLF = /\r\n/g
+const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex
+
+function HeaderParser (cfg) {
+ EventEmitter.call(this)
+
+ cfg = cfg || {}
+ const self = this
+ this.nread = 0
+ this.maxed = false
+ this.npairs = 0
+ this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)
+ this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)
+ this.buffer = ''
+ this.header = {}
+ this.finished = false
+ this.ss = new StreamSearch(B_DCRLF)
+ this.ss.on('info', function (isMatch, data, start, end) {
+ if (data && !self.maxed) {
+ if (self.nread + end - start >= self.maxHeaderSize) {
+ end = self.maxHeaderSize - self.nread + start
+ self.nread = self.maxHeaderSize
+ self.maxed = true
+ } else { self.nread += (end - start) }
+
+ self.buffer += data.toString('binary', start, end)
}
+ if (isMatch) { self._finish() }
+ })
+}
+inherits(HeaderParser, EventEmitter)
- return { code, reason }
- }
+HeaderParser.prototype.push = function (data) {
+ const r = this.ss.push(data)
+ if (this.finished) { return r }
+}
- get closingInfo () {
- return this.#info.closeInfo
+HeaderParser.prototype.reset = function () {
+ this.finished = false
+ this.buffer = ''
+ this.header = {}
+ this.ss.reset()
+}
+
+HeaderParser.prototype._finish = function () {
+ if (this.buffer) { this._parseHeader() }
+ this.ss.matches = this.ss.maxMatches
+ const header = this.header
+ this.header = {}
+ this.buffer = ''
+ this.finished = true
+ this.nread = this.npairs = 0
+ this.maxed = false
+ this.emit('header', header)
+}
+
+HeaderParser.prototype._parseHeader = function () {
+ if (this.npairs === this.maxHeaderPairs) { return }
+
+ const lines = this.buffer.split(RE_CRLF)
+ const len = lines.length
+ let m, h
+
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ if (lines[i].length === 0) { continue }
+ if (lines[i][0] === '\t' || lines[i][0] === ' ') {
+ // folded header content
+ // RFC2822 says to just remove the CRLF and not the whitespace following
+ // it, so we follow the RFC and include the leading whitespace ...
+ if (h) {
+ this.header[h][this.header[h].length - 1] += lines[i]
+ continue
+ }
+ }
+
+ const posColon = lines[i].indexOf(':')
+ if (
+ posColon === -1 ||
+ posColon === 0
+ ) {
+ return
+ }
+ m = RE_HDR.exec(lines[i])
+ h = m[1].toLowerCase()
+ this.header[h] = this.header[h] || []
+ this.header[h].push((m[2] || ''))
+ if (++this.npairs === this.maxHeaderPairs) { break }
}
}
-module.exports = {
- ByteParser
-}
+module.exports = HeaderParser
/***/ }),
-/***/ 97945:
-/***/ ((module) => {
+/***/ 87952:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module.exports = {
- kWebSocketURL: Symbol('url'),
- kReadyState: Symbol('ready state'),
- kController: Symbol('controller'),
- kResponse: Symbol('response'),
- kBinaryType: Symbol('binary type'),
- kSentClose: Symbol('sent close'),
- kReceivedClose: Symbol('received close'),
- kByteParser: Symbol('byte parser')
+const inherits = (__nccwpck_require__(57975).inherits)
+const ReadableStream = (__nccwpck_require__(57075).Readable)
+
+function PartStream (opts) {
+ ReadableStream.call(this, opts)
}
+inherits(PartStream, ReadableStream)
+
+PartStream.prototype._read = function (n) {}
+
+module.exports = PartStream
/***/ }),
-/***/ 95506:
+/***/ 86484:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(97945)
-const { states, opcodes } = __nccwpck_require__(90077)
-const { MessageEvent, ErrorEvent } = __nccwpck_require__(47115)
-
-/* globals Blob */
-
/**
- * @param {import('./websocket').WebSocket} ws
+ * Copyright Brian White. All rights reserved.
+ *
+ * @see https://github.com/mscdex/streamsearch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ *
+ * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
+ * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
*/
-function isEstablished (ws) {
- // If the server's response is validated as provided for above, it is
- // said that _The WebSocket Connection is Established_ and that the
- // WebSocket Connection is in the OPEN state.
- return ws[kReadyState] === states.OPEN
-}
+const EventEmitter = (__nccwpck_require__(78474).EventEmitter)
+const inherits = (__nccwpck_require__(57975).inherits)
-/**
- * @param {import('./websocket').WebSocket} ws
- */
-function isClosing (ws) {
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- return ws[kReadyState] === states.CLOSING
-}
+function SBMH (needle) {
+ if (typeof needle === 'string') {
+ needle = Buffer.from(needle)
+ }
-/**
- * @param {import('./websocket').WebSocket} ws
- */
-function isClosed (ws) {
- return ws[kReadyState] === states.CLOSED
-}
+ if (!Buffer.isBuffer(needle)) {
+ throw new TypeError('The needle has to be a String or a Buffer.')
+ }
-/**
- * @see https://dom.spec.whatwg.org/#concept-event-fire
- * @param {string} e
- * @param {EventTarget} target
- * @param {EventInit | undefined} eventInitDict
- */
-function fireEvent (e, target, eventConstructor = Event, eventInitDict) {
- // 1. If eventConstructor is not given, then let eventConstructor be Event.
+ const needleLength = needle.length
- // 2. Let event be the result of creating an event given eventConstructor,
- // in the relevant realm of target.
- // 3. Initialize event’s type attribute to e.
- const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap
+ if (needleLength === 0) {
+ throw new Error('The needle cannot be an empty String/Buffer.')
+ }
- // 4. Initialize any other IDL attributes of event as described in the
- // invocation of this algorithm.
+ if (needleLength > 256) {
+ throw new Error('The needle cannot have a length bigger than 256.')
+ }
- // 5. Return the result of dispatching event at target, with legacy target
- // override flag set if set.
- target.dispatchEvent(event)
+ this.maxMatches = Infinity
+ this.matches = 0
+
+ this._occ = new Array(256)
+ .fill(needleLength) // Initialize occurrence table.
+ this._lookbehind_size = 0
+ this._needle = needle
+ this._bufpos = 0
+
+ this._lookbehind = Buffer.alloc(needleLength)
+
+ // Populate occurrence table with analysis of the needle,
+ // ignoring last letter.
+ for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var
+ this._occ[needle[i]] = needleLength - 1 - i
+ }
}
+inherits(SBMH, EventEmitter)
-/**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- * @param {import('./websocket').WebSocket} ws
- * @param {number} type Opcode
- * @param {Buffer} data application data
- */
-function websocketMessageReceived (ws, type, data) {
- // 1. If ready state is not OPEN (1), then return.
- if (ws[kReadyState] !== states.OPEN) {
- return
+SBMH.prototype.reset = function () {
+ this._lookbehind_size = 0
+ this.matches = 0
+ this._bufpos = 0
+}
+
+SBMH.prototype.push = function (chunk, pos) {
+ if (!Buffer.isBuffer(chunk)) {
+ chunk = Buffer.from(chunk, 'binary')
}
+ const chlen = chunk.length
+ this._bufpos = pos || 0
+ let r
+ while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }
+ return r
+}
- // 2. Let dataForEvent be determined by switching on type and binary type:
- let dataForEvent
+SBMH.prototype._sbmh_feed = function (data) {
+ const len = data.length
+ const needle = this._needle
+ const needleLength = needle.length
+ const lastNeedleChar = needle[needleLength - 1]
- if (type === opcodes.TEXT) {
- // -> type indicates that the data is Text
- // a new DOMString containing data
- try {
- dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)
- } catch {
- failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
- return
+ // Positive: points to a position in `data`
+ // pos == 3 points to data[3]
+ // Negative: points to a position in the lookbehind buffer
+ // pos == -2 points to lookbehind[lookbehind_size - 2]
+ let pos = -this._lookbehind_size
+ let ch
+
+ if (pos < 0) {
+ // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
+ // search with character lookup code that considers both the
+ // lookbehind buffer and the current round's haystack data.
+ //
+ // Loop until
+ // there is a match.
+ // or until
+ // we've moved past the position that requires the
+ // lookbehind buffer. In this case we switch to the
+ // optimized loop.
+ // or until
+ // the character to look at lies outside the haystack.
+ while (pos < 0 && pos <= len - needleLength) {
+ ch = this._sbmh_lookup_char(data, pos + needleLength - 1)
+
+ if (
+ ch === lastNeedleChar &&
+ this._sbmh_memcmp(data, pos, needleLength - 1)
+ ) {
+ this._lookbehind_size = 0
+ ++this.matches
+ this.emit('info', true)
+
+ return (this._bufpos = pos + needleLength)
+ }
+ pos += this._occ[ch]
}
- } else if (type === opcodes.BINARY) {
- if (ws[kBinaryType] === 'blob') {
- // -> type indicates that the data is Binary and binary type is "blob"
- // a new Blob object, created in the relevant Realm of the WebSocket
- // object, that represents data as its raw data
- dataForEvent = new Blob([data])
- } else {
- // -> type indicates that the data is Binary and binary type is "arraybuffer"
- // a new ArrayBuffer object, created in the relevant Realm of the
- // WebSocket object, whose contents are data
- dataForEvent = new Uint8Array(data).buffer
+
+ // No match.
+
+ if (pos < 0) {
+ // There's too few data for Boyer-Moore-Horspool to run,
+ // so let's use a different algorithm to skip as much as
+ // we can.
+ // Forward pos until
+ // the trailing part of lookbehind + data
+ // looks like the beginning of the needle
+ // or until
+ // pos == 0
+ while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }
}
- }
- // 3. Fire an event named message at the WebSocket object, using MessageEvent,
- // with the origin attribute initialized to the serialization of the WebSocket
- // object’s url's origin, and the data attribute initialized to dataForEvent.
- fireEvent('message', ws, MessageEvent, {
- origin: ws[kWebSocketURL].origin,
- data: dataForEvent
- })
-}
+ if (pos >= 0) {
+ // Discard lookbehind buffer.
+ this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)
+ this._lookbehind_size = 0
+ } else {
+ // Cut off part of the lookbehind buffer that has
+ // been processed and append the entire haystack
+ // into it.
+ const bytesToCutOff = this._lookbehind_size + pos
+ if (bytesToCutOff > 0) {
+ // The cut off data is guaranteed not to contain the needle.
+ this.emit('info', false, this._lookbehind, 0, bytesToCutOff)
+ }
-/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455
- * @see https://datatracker.ietf.org/doc/html/rfc2616
- * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
- * @param {string} protocol
- */
-function isValidSubprotocol (protocol) {
- // If present, this value indicates one
- // or more comma-separated subprotocol the client wishes to speak,
- // ordered by preference. The elements that comprise this value
- // MUST be non-empty strings with characters in the range U+0021 to
- // U+007E not including separator characters as defined in
- // [RFC2616] and MUST all be unique strings.
- if (protocol.length === 0) {
- return false
- }
+ this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,
+ this._lookbehind_size - bytesToCutOff)
+ this._lookbehind_size -= bytesToCutOff
- for (const char of protocol) {
- const code = char.charCodeAt(0)
+ data.copy(this._lookbehind, this._lookbehind_size)
+ this._lookbehind_size += len
- if (
- code < 0x21 ||
- code > 0x7E ||
- char === '(' ||
- char === ')' ||
- char === '<' ||
- char === '>' ||
- char === '@' ||
- char === ',' ||
- char === ';' ||
- char === ':' ||
- char === '\\' ||
- char === '"' ||
- char === '/' ||
- char === '[' ||
- char === ']' ||
- char === '?' ||
- char === '=' ||
- char === '{' ||
- char === '}' ||
- code === 32 || // SP
- code === 9 // HT
- ) {
- return false
+ this._bufpos = len
+ return len
}
}
- return true
-}
+ pos += (pos >= 0) * this._bufpos
-/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
- * @param {number} code
- */
-function isValidStatusCode (code) {
- if (code >= 1000 && code < 1015) {
- return (
- code !== 1004 && // reserved
- code !== 1005 && // "MUST NOT be set as a status code"
- code !== 1006 // "MUST NOT be set as a status code"
- )
+ // Lookbehind buffer is now empty. We only need to check if the
+ // needle is in the haystack.
+ if (data.indexOf(needle, pos) !== -1) {
+ pos = data.indexOf(needle, pos)
+ ++this.matches
+ if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }
+
+ return (this._bufpos = pos + needleLength)
+ } else {
+ pos = len - needleLength
}
- return code >= 3000 && code <= 4999
-}
+ // There was no match. If there's trailing haystack data that we cannot
+ // match yet using the Boyer-Moore-Horspool algorithm (because the trailing
+ // data is less than the needle size) then match using a modified
+ // algorithm that starts matching from the beginning instead of the end.
+ // Whatever trailing data is left after running this algorithm is added to
+ // the lookbehind buffer.
+ while (
+ pos < len &&
+ (
+ data[pos] !== needle[0] ||
+ (
+ (Buffer.compare(
+ data.subarray(pos, pos + len - pos),
+ needle.subarray(0, len - pos)
+ ) !== 0)
+ )
+ )
+ ) {
+ ++pos
+ }
+ if (pos < len) {
+ data.copy(this._lookbehind, 0, pos, pos + (len - pos))
+ this._lookbehind_size = len - pos
+ }
-/**
- * @param {import('./websocket').WebSocket} ws
- * @param {string|undefined} reason
- */
-function failWebsocketConnection (ws, reason) {
- const { [kController]: controller, [kResponse]: response } = ws
+ // Everything until pos is guaranteed not to contain needle data.
+ if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }
- controller.abort()
+ this._bufpos = len
+ return len
+}
- if (response?.socket && !response.socket.destroyed) {
- response.socket.destroy()
- }
+SBMH.prototype._sbmh_lookup_char = function (data, pos) {
+ return (pos < 0)
+ ? this._lookbehind[this._lookbehind_size + pos]
+ : data[pos]
+}
- if (reason) {
- fireEvent('error', ws, ErrorEvent, {
- error: new Error(reason)
- })
+SBMH.prototype._sbmh_memcmp = function (data, pos, len) {
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }
}
+ return true
}
-module.exports = {
- isEstablished,
- isClosing,
- isClosed,
- fireEvent,
- isValidSubprotocol,
- isValidStatusCode,
- failWebsocketConnection,
- websocketMessageReceived
-}
+module.exports = SBMH
/***/ }),
-/***/ 90551:
+/***/ 75249:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { webidl } = __nccwpck_require__(94354)
-const { DOMException } = __nccwpck_require__(21234)
-const { URLSerializer } = __nccwpck_require__(37246)
-const { getGlobalOrigin } = __nccwpck_require__(62896)
-const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(90077)
-const {
- kWebSocketURL,
- kReadyState,
- kController,
- kBinaryType,
- kResponse,
- kSentClose,
- kByteParser
-} = __nccwpck_require__(97945)
-const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(95506)
-const { establishWebSocketConnection } = __nccwpck_require__(96114)
-const { WebsocketFrameSend } = __nccwpck_require__(42697)
-const { ByteParser } = __nccwpck_require__(13607)
-const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(89500)
-const { getGlobalDispatcher } = __nccwpck_require__(61481)
-const { types } = __nccwpck_require__(39023)
+const WritableStream = (__nccwpck_require__(57075).Writable)
+const { inherits } = __nccwpck_require__(57975)
+const Dicer = __nccwpck_require__(8946)
-let experimentalWarned = false
+const MultipartParser = __nccwpck_require__(35764)
+const UrlencodedParser = __nccwpck_require__(21411)
+const parseParams = __nccwpck_require__(60717)
-// https://websockets.spec.whatwg.org/#interface-definition
-class WebSocket extends EventTarget {
- #events = {
- open: null,
- error: null,
- close: null,
- message: null
+function Busboy (opts) {
+ if (!(this instanceof Busboy)) { return new Busboy(opts) }
+
+ if (typeof opts !== 'object') {
+ throw new TypeError('Busboy expected an options-Object.')
+ }
+ if (typeof opts.headers !== 'object') {
+ throw new TypeError('Busboy expected an options-Object with headers-attribute.')
+ }
+ if (typeof opts.headers['content-type'] !== 'string') {
+ throw new TypeError('Missing Content-Type-header.')
}
- #bufferedAmount = 0
- #protocol = ''
- #extensions = ''
+ const {
+ headers,
+ ...streamOptions
+ } = opts
- /**
- * @param {string} url
- * @param {string|string[]} protocols
- */
- constructor (url, protocols = []) {
- super()
+ this.opts = {
+ autoDestroy: false,
+ ...streamOptions
+ }
+ WritableStream.call(this, this.opts)
- webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' })
+ this._done = false
+ this._parser = this.getParserByHeaders(headers)
+ this._finished = false
+}
+inherits(Busboy, WritableStream)
- if (!experimentalWarned) {
- experimentalWarned = true
- process.emitWarning('WebSockets are experimental, expect them to change at any time.', {
- code: 'UNDICI-WS'
- })
+Busboy.prototype.emit = function (ev) {
+ if (ev === 'finish') {
+ if (!this._done) {
+ this._parser?.end()
+ return
+ } else if (this._finished) {
+ return
}
+ this._finished = true
+ }
+ WritableStream.prototype.emit.apply(this, arguments)
+}
- const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols)
-
- url = webidl.converters.USVString(url)
- protocols = options.protocols
-
- // 1. Let baseURL be this's relevant settings object's API base URL.
- const baseURL = getGlobalOrigin()
-
- // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.
- let urlRecord
-
- try {
- urlRecord = new URL(url, baseURL)
- } catch (e) {
- // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
- throw new DOMException(e, 'SyntaxError')
- }
+Busboy.prototype.getParserByHeaders = function (headers) {
+ const parsed = parseParams(headers['content-type'])
- // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
- if (urlRecord.protocol === 'http:') {
- urlRecord.protocol = 'ws:'
- } else if (urlRecord.protocol === 'https:') {
- // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
- urlRecord.protocol = 'wss:'
- }
+ const cfg = {
+ defCharset: this.opts.defCharset,
+ fileHwm: this.opts.fileHwm,
+ headers,
+ highWaterMark: this.opts.highWaterMark,
+ isPartAFile: this.opts.isPartAFile,
+ limits: this.opts.limits,
+ parsedConType: parsed,
+ preservePath: this.opts.preservePath
+ }
- // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
- if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {
- throw new DOMException(
- `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,
- 'SyntaxError'
- )
- }
+ if (MultipartParser.detect.test(parsed[0])) {
+ return new MultipartParser(this, cfg)
+ }
+ if (UrlencodedParser.detect.test(parsed[0])) {
+ return new UrlencodedParser(this, cfg)
+ }
+ throw new Error('Unsupported Content-Type.')
+}
- // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError"
- // DOMException.
- if (urlRecord.hash || urlRecord.href.endsWith('#')) {
- throw new DOMException('Got fragment', 'SyntaxError')
- }
+Busboy.prototype._write = function (chunk, encoding, cb) {
+ this._parser.write(chunk, cb)
+}
- // 8. If protocols is a string, set protocols to a sequence consisting
- // of just that string.
- if (typeof protocols === 'string') {
- protocols = [protocols]
- }
+module.exports = Busboy
+module.exports["default"] = Busboy
+module.exports.Busboy = Busboy
- // 9. If any of the values in protocols occur more than once or otherwise
- // fail to match the requirements for elements that comprise the value
- // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket
- // protocol, then throw a "SyntaxError" DOMException.
- if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {
- throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
- }
+module.exports.Dicer = Dicer
- if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {
- throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
- }
- // 10. Set this's url to urlRecord.
- this[kWebSocketURL] = new URL(urlRecord.href)
+/***/ }),
- // 11. Let client be this's relevant settings object.
+/***/ 35764:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 12. Run this step in parallel:
- // 1. Establish a WebSocket connection given urlRecord, protocols,
- // and client.
- this[kController] = establishWebSocketConnection(
- urlRecord,
- protocols,
- this,
- (response) => this.#onConnectionEstablished(response),
- options
- )
- // Each WebSocket object has an associated ready state, which is a
- // number representing the state of the connection. Initially it must
- // be CONNECTING (0).
- this[kReadyState] = WebSocket.CONNECTING
+// TODO:
+// * support 1 nested multipart level
+// (see second multipart example here:
+// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
+// * support limits.fieldNameSize
+// -- this will require modifications to utils.parseParams
- // The extensions attribute must initially return the empty string.
+const { Readable } = __nccwpck_require__(57075)
+const { inherits } = __nccwpck_require__(57975)
- // The protocol attribute must initially return the empty string.
+const Dicer = __nccwpck_require__(8946)
- // Each WebSocket object has an associated binary type, which is a
- // BinaryType. Initially it must be "blob".
- this[kBinaryType] = 'blob'
- }
+const parseParams = __nccwpck_require__(60717)
+const decodeText = __nccwpck_require__(16607)
+const basename = __nccwpck_require__(15080)
+const getLimit = __nccwpck_require__(5245)
- /**
- * @see https://websockets.spec.whatwg.org/#dom-websocket-close
- * @param {number|undefined} code
- * @param {string|undefined} reason
- */
- close (code = undefined, reason = undefined) {
- webidl.brandCheck(this, WebSocket)
+const RE_BOUNDARY = /^boundary$/i
+const RE_FIELD = /^form-data$/i
+const RE_CHARSET = /^charset$/i
+const RE_FILENAME = /^filename$/i
+const RE_NAME = /^name$/i
- if (code !== undefined) {
- code = webidl.converters['unsigned short'](code, { clamp: true })
- }
+Multipart.detect = /^multipart\/form-data/i
+function Multipart (boy, cfg) {
+ let i
+ let len
+ const self = this
+ let boundary
+ const limits = cfg.limits
+ const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))
+ const parsedConType = cfg.parsedConType || []
+ const defCharset = cfg.defCharset || 'utf8'
+ const preservePath = cfg.preservePath
+ const fileOpts = { highWaterMark: cfg.fileHwm }
- if (reason !== undefined) {
- reason = webidl.converters.USVString(reason)
+ for (i = 0, len = parsedConType.length; i < len; ++i) {
+ if (Array.isArray(parsedConType[i]) &&
+ RE_BOUNDARY.test(parsedConType[i][0])) {
+ boundary = parsedConType[i][1]
+ break
}
+ }
- // 1. If code is present, but is neither an integer equal to 1000 nor an
- // integer in the range 3000 to 4999, inclusive, throw an
- // "InvalidAccessError" DOMException.
- if (code !== undefined) {
- if (code !== 1000 && (code < 3000 || code > 4999)) {
- throw new DOMException('invalid code', 'InvalidAccessError')
- }
+ function checkFinished () {
+ if (nends === 0 && finished && !boy._done) {
+ finished = false
+ self.end()
}
+ }
- let reasonByteLength = 0
+ if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }
- // 2. If reason is present, then run these substeps:
- if (reason !== undefined) {
- // 1. Let reasonBytes be the result of encoding reason.
- // 2. If reasonBytes is longer than 123 bytes, then throw a
- // "SyntaxError" DOMException.
- reasonByteLength = Buffer.byteLength(reason)
+ const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
+ const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)
+ const filesLimit = getLimit(limits, 'files', Infinity)
+ const fieldsLimit = getLimit(limits, 'fields', Infinity)
+ const partsLimit = getLimit(limits, 'parts', Infinity)
+ const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)
+ const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)
- if (reasonByteLength > 123) {
- throw new DOMException(
- `Reason must be less than 123 bytes; received ${reasonByteLength}`,
- 'SyntaxError'
- )
- }
- }
+ let nfiles = 0
+ let nfields = 0
+ let nends = 0
+ let curFile
+ let curField
+ let finished = false
- // 3. Run the first matching steps from the following list:
- if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) {
- // If this's ready state is CLOSING (2) or CLOSED (3)
- // Do nothing.
- } else if (!isEstablished(this)) {
- // If the WebSocket connection is not yet established
- // Fail the WebSocket connection and set this's ready state
- // to CLOSING (2).
- failWebsocketConnection(this, 'Connection was closed before it was established.')
- this[kReadyState] = WebSocket.CLOSING
- } else if (!isClosing(this)) {
- // If the WebSocket closing handshake has not yet been started
- // Start the WebSocket closing handshake and set this's ready
- // state to CLOSING (2).
- // - If neither code nor reason is present, the WebSocket Close
- // message must not have a body.
- // - If code is present, then the status code to use in the
- // WebSocket Close message must be the integer given by code.
- // - If reason is also present, then reasonBytes must be
- // provided in the Close message after the status code.
+ this._needDrain = false
+ this._pause = false
+ this._cb = undefined
+ this._nparts = 0
+ this._boy = boy
- const frame = new WebsocketFrameSend()
+ const parserCfg = {
+ boundary,
+ maxHeaderPairs: headerPairsLimit,
+ maxHeaderSize: headerSizeLimit,
+ partHwm: fileOpts.highWaterMark,
+ highWaterMark: cfg.highWaterMark
+ }
- // If neither code nor reason is present, the WebSocket Close
- // message must not have a body.
+ this.parser = new Dicer(parserCfg)
+ this.parser.on('drain', function () {
+ self._needDrain = false
+ if (self._cb && !self._pause) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ }).on('part', function onPart (part) {
+ if (++self._nparts > partsLimit) {
+ self.parser.removeListener('part', onPart)
+ self.parser.on('part', skipPart)
+ boy.hitPartsLimit = true
+ boy.emit('partsLimit')
+ return skipPart(part)
+ }
- // If code is present, then the status code to use in the
- // WebSocket Close message must be the integer given by code.
- if (code !== undefined && reason === undefined) {
- frame.frameData = Buffer.allocUnsafe(2)
- frame.frameData.writeUInt16BE(code, 0)
- } else if (code !== undefined && reason !== undefined) {
- // If reason is also present, then reasonBytes must be
- // provided in the Close message after the status code.
- frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
- frame.frameData.writeUInt16BE(code, 0)
- // the body MAY contain UTF-8-encoded data with value /reason/
- frame.frameData.write(reason, 2, 'utf-8')
- } else {
- frame.frameData = emptyBuffer
- }
+ // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
+ // us emit 'end' early since we know the part has ended if we are already
+ // seeing the next part
+ if (curField) {
+ const field = curField
+ field.emit('end')
+ field.removeAllListeners('end')
+ }
- /** @type {import('stream').Duplex} */
- const socket = this[kResponse].socket
+ part.on('header', function (header) {
+ let contype
+ let fieldname
+ let parsed
+ let charset
+ let encoding
+ let filename
+ let nsize = 0
- socket.write(frame.createFrame(opcodes.CLOSE), (err) => {
- if (!err) {
- this[kSentClose] = true
+ if (header['content-type']) {
+ parsed = parseParams(header['content-type'][0])
+ if (parsed[0]) {
+ contype = parsed[0].toLowerCase()
+ for (i = 0, len = parsed.length; i < len; ++i) {
+ if (RE_CHARSET.test(parsed[i][0])) {
+ charset = parsed[i][1].toLowerCase()
+ break
+ }
+ }
}
- })
+ }
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- this[kReadyState] = states.CLOSING
- } else {
- // Otherwise
- // Set this's ready state to CLOSING (2).
- this[kReadyState] = WebSocket.CLOSING
- }
- }
+ if (contype === undefined) { contype = 'text/plain' }
+ if (charset === undefined) { charset = defCharset }
- /**
- * @see https://websockets.spec.whatwg.org/#dom-websocket-send
- * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
- */
- send (data) {
- webidl.brandCheck(this, WebSocket)
+ if (header['content-disposition']) {
+ parsed = parseParams(header['content-disposition'][0])
+ if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }
+ for (i = 0, len = parsed.length; i < len; ++i) {
+ if (RE_NAME.test(parsed[i][0])) {
+ fieldname = parsed[i][1]
+ } else if (RE_FILENAME.test(parsed[i][0])) {
+ filename = parsed[i][1]
+ if (!preservePath) { filename = basename(filename) }
+ }
+ }
+ } else { return skipPart(part) }
- webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' })
+ if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }
- data = webidl.converters.WebSocketSendData(data)
+ let onData,
+ onEnd
- // 1. If this's ready state is CONNECTING, then throw an
- // "InvalidStateError" DOMException.
- if (this[kReadyState] === WebSocket.CONNECTING) {
- throw new DOMException('Sent before connected.', 'InvalidStateError')
- }
+ if (isPartAFile(fieldname, contype, filename)) {
+ // file/binary field
+ if (nfiles === filesLimit) {
+ if (!boy.hitFilesLimit) {
+ boy.hitFilesLimit = true
+ boy.emit('filesLimit')
+ }
+ return skipPart(part)
+ }
- // 2. Run the appropriate set of steps from the following list:
- // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1
- // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
+ ++nfiles
- if (!isEstablished(this) || isClosing(this)) {
- return
- }
+ if (boy.listenerCount('file') === 0) {
+ self.parser._ignore()
+ return
+ }
- /** @type {import('stream').Duplex} */
- const socket = this[kResponse].socket
+ ++nends
+ const file = new FileStream(fileOpts)
+ curFile = file
+ file.on('end', function () {
+ --nends
+ self._pause = false
+ checkFinished()
+ if (self._cb && !self._needDrain) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ })
+ file._read = function (n) {
+ if (!self._pause) { return }
+ self._pause = false
+ if (self._cb && !self._needDrain) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ }
+ boy.emit('file', fieldname, file, filename, encoding, contype)
- // If data is a string
- if (typeof data === 'string') {
- // If the WebSocket connection is established and the WebSocket
- // closing handshake has not yet started, then the user agent
- // must send a WebSocket Message comprised of the data argument
- // using a text frame opcode; if the data cannot be sent, e.g.
- // because it would need to be buffered but the buffer is full,
- // the user agent must flag the WebSocket as full and then close
- // the WebSocket connection. Any invocation of this method with a
- // string argument that does not throw an exception must increase
- // the bufferedAmount attribute by the number of bytes needed to
- // express the argument as UTF-8.
+ onData = function (data) {
+ if ((nsize += data.length) > fileSizeLimit) {
+ const extralen = fileSizeLimit - nsize + data.length
+ if (extralen > 0) { file.push(data.slice(0, extralen)) }
+ file.truncated = true
+ file.bytesRead = fileSizeLimit
+ part.removeAllListeners('data')
+ file.emit('limit')
+ return
+ } else if (!file.push(data)) { self._pause = true }
- const value = Buffer.from(data)
- const frame = new WebsocketFrameSend(value)
- const buffer = frame.createFrame(opcodes.TEXT)
+ file.bytesRead = nsize
+ }
- this.#bufferedAmount += value.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= value.byteLength
- })
- } else if (types.isArrayBuffer(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need
- // to be buffered but the buffer is full, the user agent must flag
- // the WebSocket as full and then close the WebSocket connection.
- // The data to be sent is the data stored in the buffer described
- // by the ArrayBuffer object. Any invocation of this method with an
- // ArrayBuffer argument that does not throw an exception must
- // increase the bufferedAmount attribute by the length of the
- // ArrayBuffer in bytes.
+ onEnd = function () {
+ curFile = undefined
+ file.push(null)
+ }
+ } else {
+ // non-file field
+ if (nfields === fieldsLimit) {
+ if (!boy.hitFieldsLimit) {
+ boy.hitFieldsLimit = true
+ boy.emit('fieldsLimit')
+ }
+ return skipPart(part)
+ }
- const value = Buffer.from(data)
- const frame = new WebsocketFrameSend(value)
- const buffer = frame.createFrame(opcodes.BINARY)
+ ++nfields
+ ++nends
+ let buffer = ''
+ let truncated = false
+ curField = part
- this.#bufferedAmount += value.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= value.byteLength
- })
- } else if (ArrayBuffer.isView(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need to
- // be buffered but the buffer is full, the user agent must flag the
- // WebSocket as full and then close the WebSocket connection. The
- // data to be sent is the data stored in the section of the buffer
- // described by the ArrayBuffer object that data references. Any
- // invocation of this method with this kind of argument that does
- // not throw an exception must increase the bufferedAmount attribute
- // by the length of data’s buffer in bytes.
+ onData = function (data) {
+ if ((nsize += data.length) > fieldSizeLimit) {
+ const extralen = (fieldSizeLimit - (nsize - data.length))
+ buffer += data.toString('binary', 0, extralen)
+ truncated = true
+ part.removeAllListeners('data')
+ } else { buffer += data.toString('binary') }
+ }
- const ab = Buffer.from(data, data.byteOffset, data.byteLength)
+ onEnd = function () {
+ curField = undefined
+ if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }
+ boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)
+ --nends
+ checkFinished()
+ }
+ }
- const frame = new WebsocketFrameSend(ab)
- const buffer = frame.createFrame(opcodes.BINARY)
+ /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
+ broken. Streams2/streams3 is a huge black box of confusion, but
+ somehow overriding the sync state seems to fix things again (and still
+ seems to work for previous node versions).
+ */
+ part._readableState.sync = false
- this.#bufferedAmount += ab.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= ab.byteLength
- })
- } else if (isBlobLike(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need to
- // be buffered but the buffer is full, the user agent must flag the
- // WebSocket as full and then close the WebSocket connection. The data
- // to be sent is the raw data represented by the Blob object. Any
- // invocation of this method with a Blob argument that does not throw
- // an exception must increase the bufferedAmount attribute by the size
- // of the Blob object’s raw data, in bytes.
+ part.on('data', onData)
+ part.on('end', onEnd)
+ }).on('error', function (err) {
+ if (curFile) { curFile.emit('error', err) }
+ })
+ }).on('error', function (err) {
+ boy.emit('error', err)
+ }).on('finish', function () {
+ finished = true
+ checkFinished()
+ })
+}
- const frame = new WebsocketFrameSend()
+Multipart.prototype.write = function (chunk, cb) {
+ const r = this.parser.write(chunk)
+ if (r && !this._pause) {
+ cb()
+ } else {
+ this._needDrain = !r
+ this._cb = cb
+ }
+}
- data.arrayBuffer().then((ab) => {
- const value = Buffer.from(ab)
- frame.frameData = value
- const buffer = frame.createFrame(opcodes.BINARY)
+Multipart.prototype.end = function () {
+ const self = this
- this.#bufferedAmount += value.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= value.byteLength
- })
- })
- }
+ if (self.parser.writable) {
+ self.parser.end()
+ } else if (!self._boy._done) {
+ process.nextTick(function () {
+ self._boy._done = true
+ self._boy.emit('finish')
+ })
}
+}
+
+function skipPart (part) {
+ part.resume()
+}
- get readyState () {
- webidl.brandCheck(this, WebSocket)
+function FileStream (opts) {
+ Readable.call(this, opts)
- // The readyState getter steps are to return this's ready state.
- return this[kReadyState]
- }
+ this.bytesRead = 0
- get bufferedAmount () {
- webidl.brandCheck(this, WebSocket)
+ this.truncated = false
+}
- return this.#bufferedAmount
- }
+inherits(FileStream, Readable)
- get url () {
- webidl.brandCheck(this, WebSocket)
+FileStream.prototype._read = function (n) {}
- // The url getter steps are to return this's url, serialized.
- return URLSerializer(this[kWebSocketURL])
- }
+module.exports = Multipart
- get extensions () {
- webidl.brandCheck(this, WebSocket)
- return this.#extensions
- }
+/***/ }),
- get protocol () {
- webidl.brandCheck(this, WebSocket)
+/***/ 21411:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return this.#protocol
- }
- get onopen () {
- webidl.brandCheck(this, WebSocket)
- return this.#events.open
- }
+const Decoder = __nccwpck_require__(4364)
+const decodeText = __nccwpck_require__(16607)
+const getLimit = __nccwpck_require__(5245)
- set onopen (fn) {
- webidl.brandCheck(this, WebSocket)
+const RE_CHARSET = /^charset$/i
- if (this.#events.open) {
- this.removeEventListener('open', this.#events.open)
- }
+UrlEncoded.detect = /^application\/x-www-form-urlencoded/i
+function UrlEncoded (boy, cfg) {
+ const limits = cfg.limits
+ const parsedConType = cfg.parsedConType
+ this.boy = boy
- if (typeof fn === 'function') {
- this.#events.open = fn
- this.addEventListener('open', fn)
- } else {
- this.#events.open = null
+ this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
+ this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)
+ this.fieldsLimit = getLimit(limits, 'fields', Infinity)
+
+ let charset
+ for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var
+ if (Array.isArray(parsedConType[i]) &&
+ RE_CHARSET.test(parsedConType[i][0])) {
+ charset = parsedConType[i][1].toLowerCase()
+ break
}
}
- get onerror () {
- webidl.brandCheck(this, WebSocket)
+ if (charset === undefined) { charset = cfg.defCharset || 'utf8' }
- return this.#events.error
+ this.decoder = new Decoder()
+ this.charset = charset
+ this._fields = 0
+ this._state = 'key'
+ this._checkingBytes = true
+ this._bytesKey = 0
+ this._bytesVal = 0
+ this._key = ''
+ this._val = ''
+ this._keyTrunc = false
+ this._valTrunc = false
+ this._hitLimit = false
+}
+
+UrlEncoded.prototype.write = function (data, cb) {
+ if (this._fields === this.fieldsLimit) {
+ if (!this.boy.hitFieldsLimit) {
+ this.boy.hitFieldsLimit = true
+ this.boy.emit('fieldsLimit')
+ }
+ return cb()
}
- set onerror (fn) {
- webidl.brandCheck(this, WebSocket)
+ let idxeq; let idxamp; let i; let p = 0; const len = data.length
- if (this.#events.error) {
- this.removeEventListener('error', this.#events.error)
- }
+ while (p < len) {
+ if (this._state === 'key') {
+ idxeq = idxamp = undefined
+ for (i = p; i < len; ++i) {
+ if (!this._checkingBytes) { ++p }
+ if (data[i] === 0x3D/* = */) {
+ idxeq = i
+ break
+ } else if (data[i] === 0x26/* & */) {
+ idxamp = i
+ break
+ }
+ if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
+ this._hitLimit = true
+ break
+ } else if (this._checkingBytes) { ++this._bytesKey }
+ }
- if (typeof fn === 'function') {
- this.#events.error = fn
- this.addEventListener('error', fn)
- } else {
- this.#events.error = null
- }
- }
+ if (idxeq !== undefined) {
+ // key with assignment
+ if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }
+ this._state = 'val'
- get onclose () {
- webidl.brandCheck(this, WebSocket)
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._val = ''
+ this._bytesVal = 0
+ this._valTrunc = false
+ this.decoder.reset()
- return this.#events.close
- }
+ p = idxeq + 1
+ } else if (idxamp !== undefined) {
+ // key with no assignment
+ ++this._fields
+ let key; const keyTrunc = this._keyTrunc
+ if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }
- set onclose (fn) {
- webidl.brandCheck(this, WebSocket)
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._key = ''
+ this._bytesKey = 0
+ this._keyTrunc = false
+ this.decoder.reset()
- if (this.#events.close) {
- this.removeEventListener('close', this.#events.close)
- }
+ if (key.length) {
+ this.boy.emit('field', decodeText(key, 'binary', this.charset),
+ '',
+ keyTrunc,
+ false)
+ }
- if (typeof fn === 'function') {
- this.#events.close = fn
- this.addEventListener('close', fn)
+ p = idxamp + 1
+ if (this._fields === this.fieldsLimit) { return cb() }
+ } else if (this._hitLimit) {
+ // we may not have hit the actual limit if there are encoded bytes...
+ if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }
+ p = i
+ if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
+ // yep, we actually did hit the limit
+ this._checkingBytes = false
+ this._keyTrunc = true
+ }
+ } else {
+ if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }
+ p = len
+ }
} else {
- this.#events.close = null
+ idxamp = undefined
+ for (i = p; i < len; ++i) {
+ if (!this._checkingBytes) { ++p }
+ if (data[i] === 0x26/* & */) {
+ idxamp = i
+ break
+ }
+ if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
+ this._hitLimit = true
+ break
+ } else if (this._checkingBytes) { ++this._bytesVal }
+ }
+
+ if (idxamp !== undefined) {
+ ++this._fields
+ if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ decodeText(this._val, 'binary', this.charset),
+ this._keyTrunc,
+ this._valTrunc)
+ this._state = 'key'
+
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._key = ''
+ this._bytesKey = 0
+ this._keyTrunc = false
+ this.decoder.reset()
+
+ p = idxamp + 1
+ if (this._fields === this.fieldsLimit) { return cb() }
+ } else if (this._hitLimit) {
+ // we may not have hit the actual limit if there are encoded bytes...
+ if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }
+ p = i
+ if ((this._val === '' && this.fieldSizeLimit === 0) ||
+ (this._bytesVal = this._val.length) === this.fieldSizeLimit) {
+ // yep, we actually did hit the limit
+ this._checkingBytes = false
+ this._valTrunc = true
+ }
+ } else {
+ if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }
+ p = len
+ }
}
}
+ cb()
+}
- get onmessage () {
- webidl.brandCheck(this, WebSocket)
+UrlEncoded.prototype.end = function () {
+ if (this.boy._done) { return }
- return this.#events.message
+ if (this._state === 'key' && this._key.length > 0) {
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ '',
+ this._keyTrunc,
+ false)
+ } else if (this._state === 'val') {
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ decodeText(this._val, 'binary', this.charset),
+ this._keyTrunc,
+ this._valTrunc)
}
+ this.boy._done = true
+ this.boy.emit('finish')
+}
- set onmessage (fn) {
- webidl.brandCheck(this, WebSocket)
+module.exports = UrlEncoded
- if (this.#events.message) {
- this.removeEventListener('message', this.#events.message)
- }
- if (typeof fn === 'function') {
- this.#events.message = fn
- this.addEventListener('message', fn)
- } else {
- this.#events.message = null
- }
- }
+/***/ }),
- get binaryType () {
- webidl.brandCheck(this, WebSocket)
+/***/ 4364:
+/***/ ((module) => {
- return this[kBinaryType]
- }
- set binaryType (type) {
- webidl.brandCheck(this, WebSocket)
- if (type !== 'blob' && type !== 'arraybuffer') {
- this[kBinaryType] = 'blob'
- } else {
- this[kBinaryType] = type
+const RE_PLUS = /\+/g
+
+const HEX = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+]
+
+function Decoder () {
+ this.buffer = undefined
+}
+Decoder.prototype.write = function (str) {
+ // Replace '+' with ' ' before decoding
+ str = str.replace(RE_PLUS, ' ')
+ let res = ''
+ let i = 0; let p = 0; const len = str.length
+ for (; i < len; ++i) {
+ if (this.buffer !== undefined) {
+ if (!HEX[str.charCodeAt(i)]) {
+ res += '%' + this.buffer
+ this.buffer = undefined
+ --i // retry character
+ } else {
+ this.buffer += str[i]
+ ++p
+ if (this.buffer.length === 2) {
+ res += String.fromCharCode(parseInt(this.buffer, 16))
+ this.buffer = undefined
+ }
+ }
+ } else if (str[i] === '%') {
+ if (i > p) {
+ res += str.substring(p, i)
+ p = i
+ }
+ this.buffer = ''
+ ++p
}
}
+ if (p < len && this.buffer === undefined) { res += str.substring(p) }
+ return res
+}
+Decoder.prototype.reset = function () {
+ this.buffer = undefined
+}
- /**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- */
- #onConnectionEstablished (response) {
- // processResponse is called when the "response’s header list has been received and initialized."
- // once this happens, the connection is open
- this[kResponse] = response
-
- const parser = new ByteParser(this)
- parser.on('drain', function onParserDrain () {
- this.ws[kResponse].socket.resume()
- })
+module.exports = Decoder
- response.socket.ws = this
- this[kByteParser] = parser
- // 1. Change the ready state to OPEN (1).
- this[kReadyState] = states.OPEN
+/***/ }),
- // 2. Change the extensions attribute’s value to the extensions in use, if
- // it is not the null value.
- // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
- const extensions = response.headersList.get('sec-websocket-extensions')
+/***/ 15080:
+/***/ ((module) => {
- if (extensions !== null) {
- this.#extensions = extensions
- }
- // 3. Change the protocol attribute’s value to the subprotocol in use, if
- // it is not the null value.
- // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9
- const protocol = response.headersList.get('sec-websocket-protocol')
- if (protocol !== null) {
- this.#protocol = protocol
+module.exports = function basename (path) {
+ if (typeof path !== 'string') { return '' }
+ for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var
+ switch (path.charCodeAt(i)) {
+ case 0x2F: // '/'
+ case 0x5C: // '\'
+ path = path.slice(i + 1)
+ return (path === '..' || path === '.' ? '' : path)
}
-
- // 4. Fire an event named open at the WebSocket object.
- fireEvent('open', this)
}
+ return (path === '..' || path === '.' ? '' : path)
}
-// https://websockets.spec.whatwg.org/#dom-websocket-connecting
-WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING
-// https://websockets.spec.whatwg.org/#dom-websocket-open
-WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN
-// https://websockets.spec.whatwg.org/#dom-websocket-closing
-WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING
-// https://websockets.spec.whatwg.org/#dom-websocket-closed
-WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED
-Object.defineProperties(WebSocket.prototype, {
- CONNECTING: staticPropertyDescriptors,
- OPEN: staticPropertyDescriptors,
- CLOSING: staticPropertyDescriptors,
- CLOSED: staticPropertyDescriptors,
- url: kEnumerableProperty,
- readyState: kEnumerableProperty,
- bufferedAmount: kEnumerableProperty,
- onopen: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onclose: kEnumerableProperty,
- close: kEnumerableProperty,
- onmessage: kEnumerableProperty,
- binaryType: kEnumerableProperty,
- send: kEnumerableProperty,
- extensions: kEnumerableProperty,
- protocol: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'WebSocket',
- writable: false,
- enumerable: false,
- configurable: true
- }
-})
+/***/ }),
-Object.defineProperties(WebSocket, {
- CONNECTING: staticPropertyDescriptors,
- OPEN: staticPropertyDescriptors,
- CLOSING: staticPropertyDescriptors,
- CLOSED: staticPropertyDescriptors
-})
+/***/ 16607:
+/***/ (function(module) {
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.DOMString
-)
-webidl.converters['DOMString or sequence'] = function (V) {
- if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {
- return webidl.converters['sequence'](V)
- }
- return webidl.converters.DOMString(V)
+// Node has always utf-8
+const utf8Decoder = new TextDecoder('utf-8')
+const textDecoders = new Map([
+ ['utf-8', utf8Decoder],
+ ['utf8', utf8Decoder]
+])
+
+function getDecoder (charset) {
+ let lc
+ while (true) {
+ switch (charset) {
+ case 'utf-8':
+ case 'utf8':
+ return decoders.utf8
+ case 'latin1':
+ case 'ascii': // TODO: Make these a separate, strict decoder?
+ case 'us-ascii':
+ case 'iso-8859-1':
+ case 'iso8859-1':
+ case 'iso88591':
+ case 'iso_8859-1':
+ case 'windows-1252':
+ case 'iso_8859-1:1987':
+ case 'cp1252':
+ case 'x-cp1252':
+ return decoders.latin1
+ case 'utf16le':
+ case 'utf-16le':
+ case 'ucs2':
+ case 'ucs-2':
+ return decoders.utf16le
+ case 'base64':
+ return decoders.base64
+ default:
+ if (lc === undefined) {
+ lc = true
+ charset = charset.toLowerCase()
+ continue
+ }
+ return decoders.other.bind(charset)
+ }
+ }
}
-// This implements the propsal made in https://github.com/whatwg/websockets/issues/42
-webidl.converters.WebSocketInit = webidl.dictionaryConverter([
- {
- key: 'protocols',
- converter: webidl.converters['DOMString or sequence'],
- get defaultValue () {
- return []
+const decoders = {
+ utf8: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
}
+ return data.utf8Slice(0, data.length)
},
- {
- key: 'dispatcher',
- converter: (V) => V,
- get defaultValue () {
- return getGlobalDispatcher()
+
+ latin1: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ return data
}
+ return data.latin1Slice(0, data.length)
},
- {
- key: 'headers',
- converter: webidl.nullableConverter(webidl.converters.HeadersInit)
- }
-])
-webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {
- if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {
- return webidl.converters.WebSocketInit(V)
- }
+ utf16le: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
+ }
+ return data.ucs2Slice(0, data.length)
+ },
- return { protocols: webidl.converters['DOMString or sequence'](V) }
-}
+ base64: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
+ }
+ return data.base64Slice(0, data.length)
+ },
-webidl.converters.WebSocketSendData = function (V) {
- if (webidl.util.Type(V) === 'Object') {
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
+ other: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
}
- if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) {
- return webidl.converters.BufferSource(V)
+ if (textDecoders.has(this.toString())) {
+ try {
+ return textDecoders.get(this).decode(data)
+ } catch {}
}
+ return typeof data === 'string'
+ ? data
+ : data.toString()
}
-
- return webidl.converters.USVString(V)
}
-module.exports = {
- WebSocket
+function decodeText (text, sourceEncoding, destEncoding) {
+ if (text) {
+ return getDecoder(destEncoding)(text, sourceEncoding)
+ }
+ return text
}
+module.exports = decodeText
-/***/ }),
-/***/ 49367:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ }),
+/***/ 5245:
+/***/ ((module) => {
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-function getUserAgent() {
- if (typeof navigator === "object" && "userAgent" in navigator) {
- return navigator.userAgent;
- }
+module.exports = function getLimit (limits, name, defaultLimit) {
+ if (
+ !limits ||
+ limits[name] === undefined ||
+ limits[name] === null
+ ) { return defaultLimit }
- if (typeof process === "object" && process.version !== undefined) {
- return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
- }
+ if (
+ typeof limits[name] !== 'number' ||
+ isNaN(limits[name])
+ ) { throw new TypeError('Limit ' + name + ' is not a valid number') }
- return "";
+ return limits[name]
}
-exports.getUserAgent = getUserAgent;
-//# sourceMappingURL=index.js.map
-
/***/ }),
-/***/ 68776:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 60717:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/* eslint-disable object-property-newline */
-const iconvLite = __nccwpck_require__(43368);
-const supportedNames = __nccwpck_require__(67944);
-const labelsToNames = __nccwpck_require__(6225);
-const supportedNamesSet = new Set(supportedNames);
+const decodeText = __nccwpck_require__(16607)
-// https://encoding.spec.whatwg.org/#concept-encoding-get
-exports.labelToName = label => {
- label = String(label).trim().toLowerCase();
+const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g
- return labelsToNames[label] || null;
-};
+const EncodedLookup = {
+ '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04',
+ '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09',
+ '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c',
+ '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e',
+ '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12',
+ '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17',
+ '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b',
+ '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d',
+ '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20',
+ '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25',
+ '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a',
+ '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c',
+ '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f',
+ '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33',
+ '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38',
+ '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b',
+ '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e',
+ '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41',
+ '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46',
+ '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a',
+ '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d',
+ '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f',
+ '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54',
+ '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59',
+ '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c',
+ '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e',
+ '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62',
+ '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67',
+ '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b',
+ '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d',
+ '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70',
+ '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75',
+ '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a',
+ '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c',
+ '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f',
+ '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83',
+ '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88',
+ '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b',
+ '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e',
+ '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91',
+ '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96',
+ '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a',
+ '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d',
+ '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f',
+ '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2',
+ '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4',
+ '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7',
+ '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9',
+ '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab',
+ '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac',
+ '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad',
+ '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae',
+ '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0',
+ '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2',
+ '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5',
+ '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7',
+ '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba',
+ '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb',
+ '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc',
+ '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd',
+ '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf',
+ '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0',
+ '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3',
+ '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5',
+ '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8',
+ '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca',
+ '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb',
+ '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc',
+ '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce',
+ '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf',
+ '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1',
+ '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3',
+ '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6',
+ '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8',
+ '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda',
+ '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb',
+ '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd',
+ '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde',
+ '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf',
+ '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1',
+ '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4',
+ '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6',
+ '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9',
+ '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea',
+ '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec',
+ '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed',
+ '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee',
+ '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef',
+ '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2',
+ '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4',
+ '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7',
+ '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9',
+ '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb',
+ '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc',
+ '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd',
+ '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe',
+ '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff'
+}
-// https://encoding.spec.whatwg.org/#decode
-exports.decode = (uint8Array, fallbackEncodingName) => {
- let encoding = fallbackEncodingName;
- if (!exports.isSupported(encoding)) {
- throw new RangeError(`"${encoding}" is not a supported encoding name`);
- }
+function encodedReplacer (match) {
+ return EncodedLookup[match]
+}
- const bomEncoding = exports.getBOMEncoding(uint8Array);
- if (bomEncoding !== null) {
- encoding = bomEncoding;
- // iconv-lite will strip BOMs for us, so no need to do the extra byte removal that the spec does.
- // Note that we won't end up in the x-user-defined case when there's a bomEncoding.
- }
+const STATE_KEY = 0
+const STATE_VALUE = 1
+const STATE_CHARSET = 2
+const STATE_LANG = 3
- if (encoding === "x-user-defined") {
- // https://encoding.spec.whatwg.org/#x-user-defined-decoder
- let result = "";
- for (const byte of uint8Array) {
- if (byte <= 0x7F) {
- result += String.fromCodePoint(byte);
- } else {
- result += String.fromCodePoint(0xF780 + byte - 0x80);
+function parseParams (str) {
+ const res = []
+ let state = STATE_KEY
+ let charset = ''
+ let inquote = false
+ let escaping = false
+ let p = 0
+ let tmp = ''
+ const len = str.length
+
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ const char = str[i]
+ if (char === '\\' && inquote) {
+ if (escaping) { escaping = false } else {
+ escaping = true
+ continue
}
+ } else if (char === '"') {
+ if (!escaping) {
+ if (inquote) {
+ inquote = false
+ state = STATE_KEY
+ } else { inquote = true }
+ continue
+ } else { escaping = false }
+ } else {
+ if (escaping && inquote) { tmp += '\\' }
+ escaping = false
+ if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") {
+ if (state === STATE_CHARSET) {
+ state = STATE_LANG
+ charset = tmp.substring(1)
+ } else { state = STATE_VALUE }
+ tmp = ''
+ continue
+ } else if (state === STATE_KEY &&
+ (char === '*' || char === '=') &&
+ res.length) {
+ state = char === '*'
+ ? STATE_CHARSET
+ : STATE_VALUE
+ res[p] = [tmp, undefined]
+ tmp = ''
+ continue
+ } else if (!inquote && char === ';') {
+ state = STATE_KEY
+ if (charset) {
+ if (tmp.length) {
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+ 'binary',
+ charset)
+ }
+ charset = ''
+ } else if (tmp.length) {
+ tmp = decodeText(tmp, 'binary', 'utf8')
+ }
+ if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
+ tmp = ''
+ ++p
+ continue
+ } else if (!inquote && (char === ' ' || char === '\t')) { continue }
}
- return result;
+ tmp += char
}
-
- return iconvLite.decode(uint8Array, encoding);
-};
-
-// https://github.com/whatwg/html/issues/1910#issuecomment-254017369
-exports.getBOMEncoding = uint8Array => {
- if (uint8Array[0] === 0xFE && uint8Array[1] === 0xFF) {
- return "UTF-16BE";
- } else if (uint8Array[0] === 0xFF && uint8Array[1] === 0xFE) {
- return "UTF-16LE";
- } else if (uint8Array[0] === 0xEF && uint8Array[1] === 0xBB && uint8Array[2] === 0xBF) {
- return "UTF-8";
+ if (charset && tmp.length) {
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+ 'binary',
+ charset)
+ } else if (tmp) {
+ tmp = decodeText(tmp, 'binary', 'utf8')
}
- return null;
-};
-
-exports.isSupported = name => {
- return supportedNamesSet.has(String(name));
-};
-
-
-/***/ }),
-
-/***/ 54849:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+ if (res[p] === undefined) {
+ if (tmp) { res[p] = tmp }
+ } else { res[p][1] = tmp }
-const {
- asciiLowercase,
- solelyContainsHTTPTokenCodePoints,
- soleyContainsHTTPQuotedStringTokenCodePoints
-} = __nccwpck_require__(74694);
+ return res
+}
-module.exports = class MIMETypeParameters {
- constructor(map) {
- this._map = map;
- }
+module.exports = parseParams
- get size() {
- return this._map.size;
- }
- get(name) {
- name = asciiLowercase(String(name));
- return this._map.get(name);
- }
+/***/ }),
- has(name) {
- name = asciiLowercase(String(name));
- return this._map.has(name);
- }
+/***/ 74352:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- set(name, value) {
- name = asciiLowercase(String(name));
- value = String(value);
- if (!solelyContainsHTTPTokenCodePoints(name)) {
- throw new Error(`Invalid MIME type parameter name "${name}": only HTTP token code points are valid.`);
- }
- if (!soleyContainsHTTPQuotedStringTokenCodePoints(value)) {
- throw new Error(`Invalid MIME type parameter value "${value}": only HTTP quoted-string token code points are ` +
- `valid.`);
- }
+// @ts-check
+// ==================================================================================
+// audio.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 16. audio
+// ----------------------------------------------------------------------------------
- return this._map.set(name, value);
- }
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const util = __nccwpck_require__(77496);
- clear() {
- this._map.clear();
- }
+let _platform = process.platform;
- delete(name) {
- name = asciiLowercase(String(name));
- return this._map.delete(name);
- }
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
- forEach(callbackFn, thisArg) {
- this._map.forEach(callbackFn, thisArg);
- }
+function parseAudioType(str, input, output) {
+ str = str.toLowerCase();
+ let result = '';
- keys() {
- return this._map.keys();
- }
+ if (str.indexOf('input') >= 0) { result = 'Microphone'; }
+ if (str.indexOf('display audio') >= 0) { result = 'Speaker'; }
+ if (str.indexOf('speak') >= 0) { result = 'Speaker'; }
+ if (str.indexOf('laut') >= 0) { result = 'Speaker'; }
+ if (str.indexOf('loud') >= 0) { result = 'Speaker'; }
+ if (str.indexOf('head') >= 0) { result = 'Headset'; }
+ if (str.indexOf('mic') >= 0) { result = 'Microphone'; }
+ if (str.indexOf('mikr') >= 0) { result = 'Microphone'; }
+ if (str.indexOf('phone') >= 0) { result = 'Phone'; }
+ if (str.indexOf('controll') >= 0) { result = 'Controller'; }
+ if (str.indexOf('line o') >= 0) { result = 'Line Out'; }
+ if (str.indexOf('digital o') >= 0) { result = 'Digital Out'; }
+ if (str.indexOf('smart sound technology') >= 0) { result = 'Digital Signal Processor'; }
+ if (str.indexOf('high definition audio') >= 0) { result = 'Sound Driver'; }
- values() {
- return this._map.values();
+ if (!result && output) {
+ result = 'Speaker';
+ } else if (!result && input) {
+ result = 'Microphone';
}
+ return result;
+}
- entries() {
- return this._map.entries();
- }
- [Symbol.iterator]() {
- return this._map[Symbol.iterator]();
+function getLinuxAudioPci() {
+ let cmd = 'lspci -v 2>/dev/null';
+ let result = [];
+ try {
+ const parts = execSync(cmd, util.execOptsLinux).toString().split('\n\n');
+ parts.forEach(element => {
+ const lines = element.split('\n');
+ if (lines && lines.length && lines[0].toLowerCase().indexOf('audio') >= 0) {
+ const audio = {};
+ audio.slotId = lines[0].split(' ')[0];
+ audio.driver = util.getValue(lines, 'Kernel driver in use', ':', true) || util.getValue(lines, 'Kernel modules', ':', true);
+ result.push(audio);
+ }
+ });
+ return result;
+ } catch (e) {
+ return result;
}
-};
-
-
-/***/ }),
-
-/***/ 79836:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-const MIMETypeParameters = __nccwpck_require__(54849);
-const parse = __nccwpck_require__(94276);
-const serialize = __nccwpck_require__(15363);
-const {
- asciiLowercase,
- solelyContainsHTTPTokenCodePoints
-} = __nccwpck_require__(74694);
+}
-module.exports = class MIMEType {
- constructor(string) {
- string = String(string);
- const result = parse(string);
- if (result === null) {
- throw new Error(`Could not parse MIME type string "${string}"`);
- }
+function parseLinuxAudioPciMM(lines, audioPCI) {
+ const result = {};
+ const slotId = util.getValue(lines, 'Slot');
- this._type = result.type;
- this._subtype = result.subtype;
- this._parameters = new MIMETypeParameters(result.parameters);
- }
+ const pciMatch = audioPCI.filter(function (item) { return item.slotId === slotId; });
- static parse(string) {
- try {
- return new this(string);
- } catch (e) {
- return null;
- }
- }
+ result.id = slotId;
+ result.name = util.getValue(lines, 'SDevice');
+ result.manufacturer = util.getValue(lines, 'SVendor');
+ result.revision = util.getValue(lines, 'Rev');
+ result.driver = pciMatch && pciMatch.length === 1 && pciMatch[0].driver ? pciMatch[0].driver : '';
+ result.default = null;
+ result.channel = 'PCIe';
+ result.type = parseAudioType(result.name, null, null);
+ result.in = null;
+ result.out = null;
+ result.status = 'online';
- get essence() {
- return `${this.type}/${this.subtype}`;
- }
+ return result;
+}
- get type() {
- return this._type;
- }
+function parseDarwinChannel(str) {
+ let result = '';
- set type(value) {
- value = asciiLowercase(String(value));
+ if (str.indexOf('builtin') >= 0) { result = 'Built-In'; }
+ if (str.indexOf('extern') >= 0) { result = 'Audio-Jack'; }
+ if (str.indexOf('hdmi') >= 0) { result = 'HDMI'; }
+ if (str.indexOf('displayport') >= 0) { result = 'Display-Port'; }
+ if (str.indexOf('usb') >= 0) { result = 'USB'; }
+ if (str.indexOf('pci') >= 0) { result = 'PCIe'; }
- if (value.length === 0) {
- throw new Error("Invalid type: must be a non-empty string");
- }
- if (!solelyContainsHTTPTokenCodePoints(value)) {
- throw new Error(`Invalid type ${value}: must contain only HTTP token code points`);
- }
+ return result;
+}
- this._type = value;
- }
+function parseDarwinAudio(audioObject, id) {
+ const result = {};
+ const channelStr = ((audioObject.coreaudio_device_transport || '') + ' ' + (audioObject._name || '')).toLowerCase();
- get subtype() {
- return this._subtype;
- }
+ result.id = id;
+ result.name = audioObject._name;
+ result.manufacturer = audioObject.coreaudio_device_manufacturer;
+ result.revision = null;
+ result.driver = null;
+ result.default = !!(audioObject.coreaudio_default_audio_input_device || '') || !!(audioObject.coreaudio_default_audio_output_device || '');
+ result.channel = parseDarwinChannel(channelStr);
+ result.type = parseAudioType(result.name, !!(audioObject.coreaudio_device_input || ''), !!(audioObject.coreaudio_device_output || ''));
+ result.in = !!(audioObject.coreaudio_device_input || '');
+ result.out = !!(audioObject.coreaudio_device_output || '');
+ result.status = 'online';
- set subtype(value) {
- value = asciiLowercase(String(value));
+ return result;
+}
- if (value.length === 0) {
- throw new Error("Invalid subtype: must be a non-empty string");
- }
- if (!solelyContainsHTTPTokenCodePoints(value)) {
- throw new Error(`Invalid subtype ${value}: must contain only HTTP token code points`);
- }
+function parseWindowsAudio(lines) {
+ const result = {};
+ const status = util.getValue(lines, 'StatusInfo', ':');
- this._subtype = value;
- }
+ result.id = util.getValue(lines, 'DeviceID', ':'); // PNPDeviceID??
+ result.name = util.getValue(lines, 'name', ':');
+ result.manufacturer = util.getValue(lines, 'manufacturer', ':');
+ result.revision = null;
+ result.driver = null;
+ result.default = null;
+ result.channel = null;
+ result.type = parseAudioType(result.name, null, null);
+ result.in = null;
+ result.out = null;
+ result.status = status;
- get parameters() {
- return this._parameters;
- }
+ return result;
+}
- toString() {
- // The serialize function works on both "MIME type records" (i.e. the results of parse) and on this class, since
- // this class's interface is identical.
- return serialize(this);
- }
+function audio(callback) {
- isJavaScript({ prohibitParameters = false } = {}) {
- switch (this._type) {
- case "text": {
- switch (this._subtype) {
- case "ecmascript":
- case "javascript":
- case "javascript1.0":
- case "javascript1.1":
- case "javascript1.2":
- case "javascript1.3":
- case "javascript1.4":
- case "javascript1.5":
- case "jscript":
- case "livescript":
- case "x-ecmascript":
- case "x-javascript": {
- return !prohibitParameters || this._parameters.size === 0;
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = [];
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ let cmd = 'lspci -vmm 2>/dev/null';
+ exec(cmd, function (error, stdout) {
+ // PCI
+ if (!error) {
+ const audioPCI = getLinuxAudioPci();
+ const parts = stdout.toString().split('\n\n');
+ parts.forEach(element => {
+ const lines = element.split('\n');
+ if (util.getValue(lines, 'class', ':', true).toLowerCase().indexOf('audio') >= 0) {
+ const audio = parseLinuxAudioPciMM(lines, audioPCI);
+ result.push(audio);
+ }
+ });
}
- default: {
- return false;
+ if (callback) {
+ callback(result);
}
- }
+ resolve(result);
+ });
}
- case "application": {
- switch (this._subtype) {
- case "ecmascript":
- case "javascript":
- case "x-ecmascript":
- case "x-javascript": {
- return !prohibitParameters || this._parameters.size === 0;
+ if (_darwin) {
+ let cmd = 'system_profiler SPAudioDataType -json';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ try {
+ const outObj = JSON.parse(stdout.toString());
+ if (outObj.SPAudioDataType && outObj.SPAudioDataType.length && outObj.SPAudioDataType[0] && outObj.SPAudioDataType[0]['_items'] && outObj.SPAudioDataType[0]['_items'].length) {
+ for (let i = 0; i < outObj.SPAudioDataType[0]['_items'].length; i++) {
+ const audio = parseDarwinAudio(outObj.SPAudioDataType[0]['_items'][i], i);
+ result.push(audio);
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
}
- default: {
- return false;
+ if (callback) {
+ callback(result);
}
- }
+ resolve(result);
+ });
}
- default: {
- return false;
+ if (_windows) {
+ util.powerShell('Get-CimInstance Win32_SoundDevice | select DeviceID,StatusInfo,Name,Manufacturer | fl').then((stdout, error) => {
+ if (!error) {
+ const parts = stdout.toString().split(/\n\s*\n/);
+ parts.forEach(element => {
+ const lines = element.split('\n');
+ if (util.getValue(lines, 'name', ':')) {
+ result.push(parseWindowsAudio(lines));
+ }
+ });
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
}
- }
- }
- isXML() {
- return (this._subtype === "xml" && (this._type === "text" || this._type === "application")) ||
- this._subtype.endsWith("+xml");
- }
- isHTML() {
- return this._subtype === "html" && this._type === "text";
- }
-};
+ if (_sunos) {
+ resolve(null);
+ }
+ });
+ });
+}
+
+exports.audio = audio;
/***/ }),
-/***/ 94276:
+/***/ 63179:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const {
- removeLeadingAndTrailingHTTPWhitespace,
- removeTrailingHTTPWhitespace,
- isHTTPWhitespaceChar,
- solelyContainsHTTPTokenCodePoints,
- soleyContainsHTTPQuotedStringTokenCodePoints,
- asciiLowercase,
- collectAnHTTPQuotedString
-} = __nccwpck_require__(74694);
+// @ts-check;
+// ==================================================================================
+// battery.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 6. Battery
+// ----------------------------------------------------------------------------------
-module.exports = input => {
- input = removeLeadingAndTrailingHTTPWhitespace(input);
+const exec = (__nccwpck_require__(35317).exec);
+const fs = __nccwpck_require__(79896);
+const util = __nccwpck_require__(77496);
- let position = 0;
- let type = "";
- while (position < input.length && input[position] !== "/") {
- type += input[position];
- ++position;
- }
+let _platform = process.platform;
- if (type.length === 0 || !solelyContainsHTTPTokenCodePoints(type)) {
- return null;
- }
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
- if (position >= input.length) {
- return null;
+function parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity) {
+ const result = {};
+ let status = util.getValue(lines, 'BatteryStatus', ':').trim();
+ // 1 = "Discharging"
+ // 2 = "On A/C"
+ // 3 = "Fully Charged"
+ // 4 = "Low"
+ // 5 = "Critical"
+ // 6 = "Charging"
+ // 7 = "Charging High"
+ // 8 = "Charging Low"
+ // 9 = "Charging Critical"
+ // 10 = "Undefined"
+ // 11 = "Partially Charged"
+ if (status >= 0) {
+ const statusValue = status ? parseInt(status) : 0;
+ result.status = statusValue;
+ result.hasBattery = true;
+ result.maxCapacity = fullChargeCapacity || parseInt(util.getValue(lines, 'DesignCapacity', ':') || 0);
+ result.designedCapacity = parseInt(util.getValue(lines, 'DesignCapacity', ':') || designedCapacity);
+ result.voltage = parseInt(util.getValue(lines, 'DesignVoltage', ':') || 0) / 1000.0;
+ result.capacityUnit = 'mWh';
+ result.percent = parseInt(util.getValue(lines, 'EstimatedChargeRemaining', ':') || 0);
+ result.currentCapacity = parseInt(result.maxCapacity * result.percent / 100);
+ result.isCharging = (statusValue >= 6 && statusValue <= 9) || statusValue === 11 || ((statusValue !== 3) && (statusValue !== 1) && result.percent < 100);
+ result.acConnected = result.isCharging || statusValue === 2;
+ result.model = util.getValue(lines, 'DeviceID', ':');
+ } else {
+ result.status = -1;
}
- // Skips past "/"
- ++position;
+ return result;
+}
- let subtype = "";
- while (position < input.length && input[position] !== ";") {
- subtype += input[position];
- ++position;
- }
+module.exports = function (callback) {
- subtype = removeTrailingHTTPWhitespace(subtype);
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ hasBattery: false,
+ cycleCount: 0,
+ isCharging: false,
+ designedCapacity: 0,
+ maxCapacity: 0,
+ currentCapacity: 0,
+ voltage: 0,
+ capacityUnit: '',
+ percent: 0,
+ timeRemaining: null,
+ acConnected: true,
+ type: '',
+ model: '',
+ manufacturer: '',
+ serial: ''
+ };
- if (subtype.length === 0 || !solelyContainsHTTPTokenCodePoints(subtype)) {
- return null;
- }
+ if (_linux) {
+ let battery_path = '';
+ if (fs.existsSync('/sys/class/power_supply/BAT1/uevent')) {
+ battery_path = '/sys/class/power_supply/BAT1/';
+ } else if (fs.existsSync('/sys/class/power_supply/BAT0/uevent')) {
+ battery_path = '/sys/class/power_supply/BAT0/';
+ }
- const mimeType = {
- type: asciiLowercase(type),
- subtype: asciiLowercase(subtype),
- parameters: new Map()
- };
+ let acConnected = false;
+ let acPath = '';
+ if (fs.existsSync('/sys/class/power_supply/AC/online')) {
+ acPath = '/sys/class/power_supply/AC/online';
+ } else if (fs.existsSync('/sys/class/power_supply/AC0/online')) {
+ acPath = '/sys/class/power_supply/AC0/online';
+ }
- while (position < input.length) {
- // Skip past ";"
- ++position;
+ if (acPath) {
+ const file = fs.readFileSync(acPath);
+ acConnected = file.toString().trim() === '1';
+ }
- while (isHTTPWhitespaceChar(input[position])) {
- ++position;
- }
+ if (battery_path) {
+ fs.readFile(battery_path + 'uevent', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
- let parameterName = "";
- while (position < input.length && input[position] !== ";" && input[position] !== "=") {
- parameterName += input[position];
- ++position;
- }
- parameterName = asciiLowercase(parameterName);
+ result.isCharging = (util.getValue(lines, 'POWER_SUPPLY_STATUS', '=').toLowerCase() === 'charging');
+ result.acConnected = acConnected || result.isCharging;
+ result.voltage = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_VOLTAGE_NOW', '='), 10) / 1000000.0;
+ result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
+ result.cycleCount = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CYCLE_COUNT', '='), 10);
+ result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL', '=', true, true), 10) / 1000.0 * (result.voltage || 1));
+ const desingedMinVoltage = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_VOLTAGE_MIN_DESIGN', '='), 10) / 1000000.0;
+ result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL_DESIGN', '=', true, true), 10) / 1000.0 * (desingedMinVoltage || result.voltage || 1));
+ result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10) / 1000.0 * (result.voltage || 1));
+ if (!result.maxCapacity) {
+ result.maxCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL', '=', true, true), 10) / 1000.0;
+ result.designedCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL_DESIGN', '=', true, true), 10) / 1000.0 | result.maxCapacity;
+ result.currentCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10) / 1000.0;
+ }
+ const percent = util.getValue(lines, 'POWER_SUPPLY_CAPACITY', '=');
+ const energy = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10);
+ const power = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_POWER_NOW', '='), 10);
+ const current = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CURRENT_NOW', '='), 10);
+ const charge = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10);
- if (position < input.length) {
- if (input[position] === ";") {
- continue;
+ result.percent = parseInt('0' + percent, 10);
+ if (result.maxCapacity && result.currentCapacity) {
+ result.hasBattery = true;
+ if (!percent) {
+ result.percent = 100.0 * result.currentCapacity / result.maxCapacity;
+ }
+ }
+ if (result.isCharging) {
+ result.hasBattery = true;
+ }
+ if (energy && power) {
+ result.timeRemaining = Math.floor(energy / power * 60);
+ } else if (current && charge) {
+ result.timeRemaining = Math.floor(charge / current * 60);
+ } else if (current && result.currentCapacity) {
+ result.timeRemaining = Math.floor(result.currentCapacity / current * 60);
+ }
+ result.type = util.getValue(lines, 'POWER_SUPPLY_TECHNOLOGY', '=');
+ result.model = util.getValue(lines, 'POWER_SUPPLY_MODEL_NAME', '=');
+ result.manufacturer = util.getValue(lines, 'POWER_SUPPLY_MANUFACTURER', '=');
+ result.serial = util.getValue(lines, 'POWER_SUPPLY_SERIAL_NUMBER', '=');
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ exec('sysctl -i hw.acpi.battery hw.acpi.acline', function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ const batteries = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.units'), 10);
+ const percent = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.life'), 10);
+ result.hasBattery = (batteries > 0);
+ result.cycleCount = null;
+ result.isCharging = util.getValue(lines, 'hw.acpi.acline') !== '1';
+ result.acConnected = result.isCharging;
+ result.maxCapacity = null;
+ result.currentCapacity = null;
+ result.capacityUnit = 'unknown';
+ result.percent = batteries ? percent : null;
+ if (callback) { callback(result); }
+ resolve(result);
+ });
}
- // Skip past "="
- ++position;
- }
-
- let parameterValue = null;
- if (input[position] === "\"") {
- [parameterValue, position] = collectAnHTTPQuotedString(input, position);
-
- while (position < input.length && input[position] !== ";") {
- ++position;
+ if (_darwin) {
+ exec('ioreg -n AppleSmartBattery -r | egrep "CycleCount|IsCharging|DesignCapacity|MaxCapacity|CurrentCapacity|DeviceName|BatterySerialNumber|Serial|TimeRemaining|Voltage"; pmset -g batt | grep %', function (error, stdout) {
+ if (stdout) {
+ let lines = stdout.toString().replace(/ +/g, '').replace(/"+/g, '').replace(/-/g, '').split('\n');
+ result.cycleCount = parseInt('0' + util.getValue(lines, 'cyclecount', '='), 10);
+ result.voltage = parseInt('0' + util.getValue(lines, 'voltage', '='), 10) / 1000.0;
+ result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
+ result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'applerawmaxcapacity', '='), 10) * (result.voltage || 1));
+ result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'applerawcurrentcapacity', '='), 10) * (result.voltage || 1));
+ result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'DesignCapacity', '='), 10) * (result.voltage || 1));
+ result.manufacturer = 'Apple';
+ result.serial = util.getValue(lines, 'BatterySerialNumber', '=') || util.getValue(lines, 'Serial', '=');
+ result.model = util.getValue(lines, 'DeviceName', '=');
+ let percent = null;
+ const line = util.getValue(lines, 'internal', 'Battery');
+ let parts = line.split(';');
+ if (parts && parts[0]) {
+ let parts2 = parts[0].split('\t');
+ if (parts2 && parts2[1]) {
+ percent = parseFloat(parts2[1].trim().replace(/%/g, ''));
+ }
+ }
+ if (parts && parts[1]) {
+ result.isCharging = (parts[1].trim() === 'charging');
+ result.acConnected = (parts[1].trim() !== 'discharging');
+ } else {
+ result.isCharging = util.getValue(lines, 'ischarging', '=').toLowerCase() === 'yes';
+ result.acConnected = result.isCharging;
+ }
+ if (result.maxCapacity && result.currentCapacity) {
+ result.hasBattery = true;
+ result.type = 'Li-ion';
+ result.percent = percent !== null ? percent : Math.round(100.0 * result.currentCapacity / result.maxCapacity);
+ if (!result.isCharging) {
+ result.timeRemaining = parseInt('0' + util.getValue(lines, 'TimeRemaining', '='), 10);
+ }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
}
- } else {
- parameterValue = "";
- while (position < input.length && input[position] !== ";") {
- parameterValue += input[position];
- ++position;
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
}
-
- parameterValue = removeTrailingHTTPWhitespace(parameterValue);
-
- if (parameterValue === "") {
- continue;
+ if (_windows) {
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance Win32_Battery | select BatteryStatus, DesignCapacity, DesignVoltage, EstimatedChargeRemaining, DeviceID | fl'));
+ workload.push(util.powerShell('(Get-WmiObject -Class BatteryStaticData -Namespace ROOT/WMI).DesignedCapacity'));
+ workload.push(util.powerShell('(Get-CimInstance -Class BatteryFullChargedCapacity -Namespace ROOT/WMI).FullChargedCapacity'));
+ util.promiseAll(
+ workload
+ ).then((data) => {
+ if (data) {
+ let parts = data.results[0].split(/\n\s*\n/);
+ let batteries = [];
+ const hasValue = value => /\S/.test(value);
+ for (let i = 0; i < parts.length; i++) {
+ if (hasValue(parts[i]) && (!batteries.length || !hasValue(parts[i - 1]))) {
+ batteries.push([]);
+ }
+ if (hasValue(parts[i])) {
+ batteries[batteries.length - 1].push(parts[i]);
+ }
+ }
+ let designCapacities = data.results[1].split('\r\n').filter(e => e);
+ let fullChargeCapacities = data.results[2].split('\r\n').filter(e => e);
+ if (batteries.length) {
+ let first = false;
+ let additionalBatteries = [];
+ for (let i = 0; i < batteries.length; i++) {
+ let lines = batteries[i][0].split('\r\n');
+ const designedCapacity = designCapacities && designCapacities.length >= (i + 1) && designCapacities[i] ? util.toInt(designCapacities[i]) : 0;
+ const fullChargeCapacity = fullChargeCapacities && fullChargeCapacities.length >= (i + 1) && fullChargeCapacities[i] ? util.toInt(fullChargeCapacities[i]) : 0;
+ const parsed = parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity);
+ if (!first && parsed.status > 0 && parsed.status !== 10) {
+ result.hasBattery = parsed.hasBattery;
+ result.maxCapacity = parsed.maxCapacity;
+ result.designedCapacity = parsed.designedCapacity;
+ result.voltage = parsed.voltage;
+ result.capacityUnit = parsed.capacityUnit;
+ result.percent = parsed.percent;
+ result.currentCapacity = parsed.currentCapacity;
+ result.isCharging = parsed.isCharging;
+ result.acConnected = parsed.acConnected;
+ result.model = parsed.model;
+ first = true;
+ } else if (parsed.status !== -1) {
+ additionalBatteries.push(
+ {
+ hasBattery: parsed.hasBattery,
+ maxCapacity: parsed.maxCapacity,
+ designedCapacity: parsed.designedCapacity,
+ voltage: parsed.voltage,
+ capacityUnit: parsed.capacityUnit,
+ percent: parsed.percent,
+ currentCapacity: parsed.currentCapacity,
+ isCharging: parsed.isCharging,
+ timeRemaining: null,
+ acConnected: parsed.acConnected,
+ model: parsed.model,
+ type: '',
+ manufacturer: '',
+ serial: ''
+ }
+ );
+ }
+ }
+ if (!first && additionalBatteries.length) {
+ result = additionalBatteries[0];
+ additionalBatteries.shift();
+ }
+ if (additionalBatteries.length) {
+ result.additionalBatteries = additionalBatteries;
+ }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
}
- }
-
- if (parameterName.length > 0 &&
- solelyContainsHTTPTokenCodePoints(parameterName) &&
- soleyContainsHTTPQuotedStringTokenCodePoints(parameterValue) &&
- !mimeType.parameters.has(parameterName)) {
- mimeType.parameters.set(parameterName, parameterValue);
- }
- }
-
- return mimeType;
+ });
+ });
};
/***/ }),
-/***/ 15363:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 6588:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const { solelyContainsHTTPTokenCodePoints } = __nccwpck_require__(74694);
+// @ts-check
+// ==================================================================================
+// audio.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 17. bluetooth
+// ----------------------------------------------------------------------------------
-module.exports = mimeType => {
- let serialization = `${mimeType.type}/${mimeType.subtype}`;
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const path = __nccwpck_require__(16928);
+const util = __nccwpck_require__(77496);
+const bluetoothVendors = __nccwpck_require__(25173);
+const fs = __nccwpck_require__(79896);
- if (mimeType.parameters.size === 0) {
- return serialization;
- }
+let _platform = process.platform;
- for (let [name, value] of mimeType.parameters) {
- serialization += ";";
- serialization += name;
- serialization += "=";
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
- if (!solelyContainsHTTPTokenCodePoints(value) || value.length === 0) {
- value = value.replace(/(["\\])/ug, "\\$1");
- value = `"${value}"`;
- }
+function parseBluetoothType(str) {
+ let result = '';
- serialization += value;
- }
+ if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
+ if (str.indexOf('mouse') >= 0) { result = 'Mouse'; }
+ if (str.indexOf('trackpad') >= 0) { result = 'Trackpad'; }
+ if (str.indexOf('speaker') >= 0) { result = 'Speaker'; }
+ if (str.indexOf('headset') >= 0) { result = 'Headset'; }
+ if (str.indexOf('phone') >= 0) { result = 'Phone'; }
+ if (str.indexOf('macbook') >= 0) { result = 'Computer'; }
+ if (str.indexOf('imac') >= 0) { result = 'Computer'; }
+ if (str.indexOf('ipad') >= 0) { result = 'Tablet'; }
+ if (str.indexOf('watch') >= 0) { result = 'Watch'; }
+ if (str.indexOf('headphone') >= 0) { result = 'Headset'; }
+ // to be continued ...
- return serialization;
-};
+ return result;
+}
+function parseBluetoothManufacturer(str) {
+ let result = str.split(' ')[0];
+ str = str.toLowerCase();
+ if (str.indexOf('apple') >= 0) { result = 'Apple'; }
+ if (str.indexOf('ipad') >= 0) { result = 'Apple'; }
+ if (str.indexOf('imac') >= 0) { result = 'Apple'; }
+ if (str.indexOf('iphone') >= 0) { result = 'Apple'; }
+ if (str.indexOf('magic mouse') >= 0) { result = 'Apple'; }
+ if (str.indexOf('magic track') >= 0) { result = 'Apple'; }
+ if (str.indexOf('macbook') >= 0) { result = 'Apple'; }
+ // to be continued ...
-/***/ }),
+ return result;
+}
-/***/ 74694:
-/***/ ((__unused_webpack_module, exports) => {
+function parseBluetoothVendor(str) {
+ const id = parseInt(str);
+ if (!isNaN(id)) return bluetoothVendors[id];
+}
+function parseLinuxBluetoothInfo(lines, macAddr1, macAddr2) {
+ const result = {};
+ result.device = null;
+ result.name = util.getValue(lines, 'name', '=');
+ result.manufacturer = null;
+ result.macDevice = macAddr1;
+ result.macHost = macAddr2;
+ result.batteryPercent = null;
+ result.type = parseBluetoothType(result.name.toLowerCase());
+ result.connected = false;
-exports.removeLeadingAndTrailingHTTPWhitespace = string => {
- return string.replace(/^[ \t\n\r]+/u, "").replace(/[ \t\n\r]+$/u, "");
-};
+ return result;
+}
-exports.removeTrailingHTTPWhitespace = string => {
- return string.replace(/[ \t\n\r]+$/u, "");
-};
+function parseDarwinBluetoothDevices(bluetoothObject, macAddr2) {
+ const result = {};
+ const typeStr = ((bluetoothObject.device_minorClassOfDevice_string || bluetoothObject.device_majorClassOfDevice_string || bluetoothObject.device_minorType || '') + (bluetoothObject.device_name || '')).toLowerCase();
-exports.isHTTPWhitespaceChar = char => {
- return char === " " || char === "\t" || char === "\n" || char === "\r";
-};
+ result.device = bluetoothObject.device_services || '';
+ result.name = bluetoothObject.device_name || '';
+ result.manufacturer = bluetoothObject.device_manufacturer || parseBluetoothVendor(bluetoothObject.device_vendorID) || parseBluetoothManufacturer(bluetoothObject.device_name || '') || '';
+ result.macDevice = (bluetoothObject.device_addr || bluetoothObject.device_address || '').toLowerCase().replace(/-/g, ':');
+ result.macHost = macAddr2;
+ result.batteryPercent = bluetoothObject.device_batteryPercent || null;
+ result.type = parseBluetoothType(typeStr);
+ result.connected = bluetoothObject.device_isconnected === 'attrib_Yes' || false;
-exports.solelyContainsHTTPTokenCodePoints = string => {
- return /^[-!#$%&'*+.^_`|~A-Za-z0-9]*$/u.test(string);
-};
+ return result;
+}
-exports.soleyContainsHTTPQuotedStringTokenCodePoints = string => {
- return /^[\t\u0020-\u007E\u0080-\u00FF]*$/u.test(string);
-};
+function parseWindowsBluetooth(lines) {
+ const result = {};
-exports.asciiLowercase = string => {
- return string.replace(/[A-Z]/ug, l => l.toLowerCase());
-};
+ result.device = null;
+ result.name = util.getValue(lines, 'name', ':');
+ result.manufacturer = util.getValue(lines, 'manufacturer', ':');
+ result.macDevice = null;
+ result.macHost = null;
+ result.batteryPercent = null;
+ result.type = parseBluetoothType(result.name.toLowerCase());
+ result.connected = null;
-// This variant only implements it with the extract-value flag set.
-exports.collectAnHTTPQuotedString = (input, position) => {
- let value = "";
+ return result;
+}
- position++;
+function bluetoothDevices(callback) {
- while (true) {
- while (position < input.length && input[position] !== "\"" && input[position] !== "\\") {
- value += input[position];
- ++position;
- }
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = [];
+ if (_linux) {
+ // get files in /var/lib/bluetooth/ recursive
+ const btFiles = util.getFilesInPath('/var/lib/bluetooth/');
+ btFiles.forEach((element) => {
+ const filename = path.basename(element);
+ const pathParts = element.split('/');
+ const macAddr1 = pathParts.length >= 6 ? pathParts[pathParts.length - 2] : null;
+ const macAddr2 = pathParts.length >= 7 ? pathParts[pathParts.length - 3] : null;
+ if (filename === 'info') {
+ const infoFile = fs.readFileSync(element, { encoding: 'utf8' }).split('\n');
+ result.push(parseLinuxBluetoothInfo(infoFile, macAddr1, macAddr2));
+ }
+ });
+ // determine "connected" with hcitool con
+ try {
+ const hdicon = execSync('hcitool con', util.execOptsLinux).toString().toLowerCase();
+ for (let i = 0; i < result.length; i++) {
+ if (result[i].macDevice && result[i].macDevice.length > 10 && hdicon.indexOf(result[i].macDevice.toLowerCase()) >= 0) {
+ result[i].connected = true;
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
- if (position >= input.length) {
- break;
- }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ if (_darwin) {
+ let cmd = 'system_profiler SPBluetoothDataType -json';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ try {
+ const outObj = JSON.parse(stdout.toString());
+ if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_title'] && outObj.SPBluetoothDataType[0]['device_title'].length) {
+ // missing: host BT Adapter macAddr ()
+ let macAddr2 = null;
+ if (outObj.SPBluetoothDataType[0]['local_device_title'] && outObj.SPBluetoothDataType[0].local_device_title.general_address) {
+ macAddr2 = outObj.SPBluetoothDataType[0].local_device_title.general_address.toLowerCase().replace(/-/g, ':');
+ }
+ outObj.SPBluetoothDataType[0]['device_title'].forEach((element) => {
+ const obj = element;
+ const objKey = Object.keys(obj);
+ if (objKey && objKey.length === 1) {
+ const innerObject = obj[objKey[0]];
+ innerObject.device_name = objKey[0];
+ const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
+ result.push(bluetoothDevice);
+ }
+ });
+ }
+ if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_connected'] && outObj.SPBluetoothDataType[0]['device_connected'].length) {
+ const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null;
+ outObj.SPBluetoothDataType[0]['device_connected'].forEach((element) => {
+ const obj = element;
+ const objKey = Object.keys(obj);
+ if (objKey && objKey.length === 1) {
+ const innerObject = obj[objKey[0]];
+ innerObject.device_name = objKey[0];
+ innerObject.device_isconnected = 'attrib_Yes';
+ const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
+ result.push(bluetoothDevice);
+ }
+ });
+ }
+ if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_not_connected'] && outObj.SPBluetoothDataType[0]['device_not_connected'].length) {
+ const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null;
+ outObj.SPBluetoothDataType[0]['device_not_connected'].forEach((element) => {
+ const obj = element;
+ const objKey = Object.keys(obj);
+ if (objKey && objKey.length === 1) {
+ const innerObject = obj[objKey[0]];
+ innerObject.device_name = objKey[0];
+ innerObject.device_isconnected = 'attrib_No';
+ const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
+ result.push(bluetoothDevice);
+ }
+ });
+ }
+ } catch (e) {
+ util.noop();
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_windows) {
+ util.powerShell('Get-CimInstance Win32_PNPEntity | select PNPClass, Name, Manufacturer | fl').then((stdout, error) => {
+ if (!error) {
+ const parts = stdout.toString().split(/\n\s*\n/);
+ parts.forEach((part) => {
+ if (util.getValue(part.split('\n'), 'PNPClass', ':') === 'Bluetooth') {
+ result.push(parseWindowsBluetooth(part.split('\n')));
+ }
+ });
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_freebsd || _netbsd || _openbsd || _sunos) {
+ resolve(null);
+ }
+ });
+ });
+}
- const quoteOrBackslash = input[position];
- ++position;
+exports.bluetoothDevices = bluetoothDevices;
- if (quoteOrBackslash === "\\") {
- if (position >= input.length) {
- value += "\\";
- break;
- }
- value += input[position];
- ++position;
- } else {
- break;
- }
- }
+/***/ }),
- return [value, position];
+/***/ 25173:
+/***/ ((module) => {
+
+
+// @ts-check
+module.exports = {
+ 0x0000: 'Ericsson Technology Licensing',
+ 0x0001: 'Nokia Mobile Phones',
+ 0x0002: 'Intel Corp.',
+ 0x0003: 'IBM Corp.',
+ 0x0004: 'Toshiba Corp.',
+ 0x0005: '3Com',
+ 0x0006: 'Microsoft',
+ 0x0007: 'Lucent',
+ 0x0008: 'Motorola',
+ 0x0009: 'Infineon Technologies AG',
+ 0x000a: 'Cambridge Silicon Radio',
+ 0x000b: 'Silicon Wave',
+ 0x000c: 'Digianswer A/S',
+ 0x000d: 'Texas Instruments Inc.',
+ 0x000e: 'Ceva, Inc. (formerly Parthus Technologies, Inc.)',
+ 0x000f: 'Broadcom Corporation',
+ 0x0010: 'Mitel Semiconductor',
+ 0x0011: 'Widcomm, Inc',
+ 0x0012: 'Zeevo, Inc.',
+ 0x0013: 'Atmel Corporation',
+ 0x0014: 'Mitsubishi Electric Corporation',
+ 0x0015: 'RTX Telecom A/S',
+ 0x0016: 'KC Technology Inc.',
+ 0x0017: 'NewLogic',
+ 0x0018: 'Transilica, Inc.',
+ 0x0019: 'Rohde & Schwarz GmbH & Co. KG',
+ 0x001a: 'TTPCom Limited',
+ 0x001b: 'Signia Technologies, Inc.',
+ 0x001c: 'Conexant Systems Inc.',
+ 0x001d: 'Qualcomm',
+ 0x001e: 'Inventel',
+ 0x001f: 'AVM Berlin',
+ 0x0020: 'BandSpeed, Inc.',
+ 0x0021: 'Mansella Ltd',
+ 0x0022: 'NEC Corporation',
+ 0x0023: 'WavePlus Technology Co., Ltd.',
+ 0x0024: 'Alcatel',
+ 0x0025: 'NXP Semiconductors (formerly Philips Semiconductors)',
+ 0x0026: 'C Technologies',
+ 0x0027: 'Open Interface',
+ 0x0028: 'R F Micro Devices',
+ 0x0029: 'Hitachi Ltd',
+ 0x002a: 'Symbol Technologies, Inc.',
+ 0x002b: 'Tenovis',
+ 0x002c: 'Macronix International Co. Ltd.',
+ 0x002d: 'GCT Semiconductor',
+ 0x002e: 'Norwood Systems',
+ 0x002f: 'MewTel Technology Inc.',
+ 0x0030: 'ST Microelectronics',
+ 0x0031: 'Synopsis',
+ 0x0032: 'Red-M (Communications) Ltd',
+ 0x0033: 'Commil Ltd',
+ 0x0034: 'Computer Access Technology Corporation (CATC)',
+ 0x0035: 'Eclipse (HQ Espana) S.L.',
+ 0x0036: 'Renesas Electronics Corporation',
+ 0x0037: 'Mobilian Corporation',
+ 0x0038: 'Terax',
+ 0x0039: 'Integrated System Solution Corp.',
+ 0x003a: 'Matsushita Electric Industrial Co., Ltd.',
+ 0x003b: 'Gennum Corporation',
+ 0x003c: 'BlackBerry Limited (formerly Research In Motion)',
+ 0x003d: 'IPextreme, Inc.',
+ 0x003e: 'Systems and Chips, Inc.',
+ 0x003f: 'Bluetooth SIG, Inc.',
+ 0x0040: 'Seiko Epson Corporation',
+ 0x0041: 'Integrated Silicon Solution Taiwan, Inc.',
+ 0x0042: 'CONWISE Technology Corporation Ltd',
+ 0x0043: 'PARROT SA',
+ 0x0044: 'Socket Mobile',
+ 0x0045: 'Atheros Communications, Inc.',
+ 0x0046: 'MediaTek, Inc.',
+ 0x0047: 'Bluegiga',
+ 0x0048: 'Marvell Technology Group Ltd.',
+ 0x0049: '3DSP Corporation',
+ 0x004a: 'Accel Semiconductor Ltd.',
+ 0x004b: 'Continental Automotive Systems',
+ 0x004c: 'Apple, Inc.',
+ 0x004d: 'Staccato Communications, Inc.',
+ 0x004e: 'Avago Technologies',
+ 0x004f: 'APT Licensing Ltd.',
+ 0x0050: 'SiRF Technology',
+ 0x0051: 'Tzero Technologies, Inc.',
+ 0x0052: 'J&M Corporation',
+ 0x0053: 'Free2move AB',
+ 0x0054: '3DiJoy Corporation',
+ 0x0055: 'Plantronics, Inc.',
+ 0x0056: 'Sony Ericsson Mobile Communications',
+ 0x0057: 'Harman International Industries, Inc.',
+ 0x0058: 'Vizio, Inc.',
+ 0x0059: 'Nordic Semiconductor ASA',
+ 0x005a: 'EM Microelectronic-Marin SA',
+ 0x005b: 'Ralink Technology Corporation',
+ 0x005c: 'Belkin International, Inc.',
+ 0x005d: 'Realtek Semiconductor Corporation',
+ 0x005e: 'Stonestreet One, LLC',
+ 0x005f: 'Wicentric, Inc.',
+ 0x0060: 'RivieraWaves S.A.S',
+ 0x0061: 'RDA Microelectronics',
+ 0x0062: 'Gibson Guitars',
+ 0x0063: 'MiCommand Inc.',
+ 0x0064: 'Band XI International, LLC',
+ 0x0065: 'Hewlett-Packard Company',
+ 0x0066: '9Solutions Oy',
+ 0x0067: 'GN Netcom A/S',
+ 0x0068: 'General Motors',
+ 0x0069: 'A&D Engineering, Inc.',
+ 0x006a: 'MindTree Ltd.',
+ 0x006b: 'Polar Electro OY',
+ 0x006c: 'Beautiful Enterprise Co., Ltd.',
+ 0x006d: 'BriarTek, Inc.',
+ 0x006e: 'Summit Data Communications, Inc.',
+ 0x006f: 'Sound ID',
+ 0x0070: 'Monster, LLC',
+ 0x0071: 'connectBlue AB',
+ 0x0072: 'ShangHai Super Smart Electronics Co. Ltd.',
+ 0x0073: 'Group Sense Ltd.',
+ 0x0074: 'Zomm, LLC',
+ 0x0075: 'Samsung Electronics Co. Ltd.',
+ 0x0076: 'Creative Technology Ltd.',
+ 0x0077: 'Laird Technologies',
+ 0x0078: 'Nike, Inc.',
+ 0x0079: 'lesswire AG',
+ 0x007a: 'MStar Semiconductor, Inc.',
+ 0x007b: 'Hanlynn Technologies',
+ 0x007c: 'A & R Cambridge',
+ 0x007d: 'Seers Technology Co. Ltd',
+ 0x007e: 'Sports Tracking Technologies Ltd.',
+ 0x007f: 'Autonet Mobile',
+ 0x0080: 'DeLorme Publishing Company, Inc.',
+ 0x0081: 'WuXi Vimicro',
+ 0x0082: 'Sennheiser Communications A/S',
+ 0x0083: 'TimeKeeping Systems, Inc.',
+ 0x0084: 'Ludus Helsinki Ltd.',
+ 0x0085: 'BlueRadios, Inc.',
+ 0x0086: 'equinox AG',
+ 0x0087: 'Garmin International, Inc.',
+ 0x0088: 'Ecotest',
+ 0x0089: 'GN ReSound A/S',
+ 0x008a: 'Jawbone',
+ 0x008b: 'Topcorn Positioning Systems, LLC',
+ 0x008c: 'Gimbal Inc. (formerly Qualcomm Labs, Inc. and Qualcomm Retail Solutions, Inc.)',
+ 0x008d: 'Zscan Software',
+ 0x008e: 'Quintic Corp.',
+ 0x008f: 'Stollman E+V GmbH',
+ 0x0090: 'Funai Electric Co., Ltd.',
+ 0x0091: 'Advanced PANMOBIL Systems GmbH & Co. KG',
+ 0x0092: 'ThinkOptics, Inc.',
+ 0x0093: 'Universal Electronics, Inc.',
+ 0x0094: 'Airoha Technology Corp.',
+ 0x0095: 'NEC Lighting, Ltd.',
+ 0x0096: 'ODM Technology, Inc.',
+ 0x0097: 'ConnecteDevice Ltd.',
+ 0x0098: 'zer01.tv GmbH',
+ 0x0099: 'i.Tech Dynamic Global Distribution Ltd.',
+ 0x009a: 'Alpwise',
+ 0x009b: 'Jiangsu Toppower Automotive Electronics Co., Ltd.',
+ 0x009c: 'Colorfy, Inc.',
+ 0x009d: 'Geoforce Inc.',
+ 0x009e: 'Bose Corporation',
+ 0x009f: 'Suunto Oy',
+ 0x00a0: 'Kensington Computer Products Group',
+ 0x00a1: 'SR-Medizinelektronik',
+ 0x00a2: 'Vertu Corporation Limited',
+ 0x00a3: 'Meta Watch Ltd.',
+ 0x00a4: 'LINAK A/S',
+ 0x00a5: 'OTL Dynamics LLC',
+ 0x00a6: 'Panda Ocean Inc.',
+ 0x00a7: 'Visteon Corporation',
+ 0x00a8: 'ARP Devices Limited',
+ 0x00a9: 'Magneti Marelli S.p.A',
+ 0x00aa: 'CAEN RFID srl',
+ 0x00ab: 'Ingenieur-Systemgruppe Zahn GmbH',
+ 0x00ac: 'Green Throttle Games',
+ 0x00ad: 'Peter Systemtechnik GmbH',
+ 0x00ae: 'Omegawave Oy',
+ 0x00af: 'Cinetix',
+ 0x00b0: 'Passif Semiconductor Corp',
+ 0x00b1: 'Saris Cycling Group, Inc',
+ 0x00b2: 'Bekey A/S',
+ 0x00b3: 'Clarinox Technologies Pty. Ltd.',
+ 0x00b4: 'BDE Technology Co., Ltd.',
+ 0x00b5: 'Swirl Networks',
+ 0x00b6: 'Meso international',
+ 0x00b7: 'TreLab Ltd',
+ 0x00b8: 'Qualcomm Innovation Center, Inc. (QuIC)',
+ 0x00b9: 'Johnson Controls, Inc.',
+ 0x00ba: 'Starkey Laboratories Inc.',
+ 0x00bb: 'S-Power Electronics Limited',
+ 0x00bc: 'Ace Sensor Inc',
+ 0x00bd: 'Aplix Corporation',
+ 0x00be: 'AAMP of America',
+ 0x00bf: 'Stalmart Technology Limited',
+ 0x00c0: 'AMICCOM Electronics Corporation',
+ 0x00c1: 'Shenzhen Excelsecu Data Technology Co.,Ltd',
+ 0x00c2: 'Geneq Inc.',
+ 0x00c3: 'adidas AG',
+ 0x00c4: 'LG Electronics',
+ 0x00c5: 'Onset Computer Corporation',
+ 0x00c6: 'Selfly BV',
+ 0x00C7: 'Quuppa Oy.',
+ 0x00C8: 'GeLo Inc',
+ 0x00C9: 'Evluma',
+ 0x00CA: 'MC10',
+ 0x00CB: 'Binauric SE',
+ 0x00CC: 'Beats Electronics',
+ 0x00CD: 'Microchip Technology Inc.',
+ 0x00CE: 'Elgato Systems GmbH',
+ 0x00CF: 'ARCHOS SA',
+ 0x00D0: 'Dexcom, Inc.',
+ 0x00D1: 'Polar Electro Europe B.V.',
+ 0x00D2: 'Dialog Semiconductor B.V.',
+ 0x00D3: 'Taixingbang Technology (HK) Co,. LTD.',
+ 0x00D4: 'Kawantech',
+ 0x00D5: 'Austco Communication Systems',
+ 0x00D6: 'Timex Group USA, Inc.',
+ 0x00D7: 'Qualcomm Technologies, Inc.',
+ 0x00D8: 'Qualcomm Connected Experiences, Inc.',
+ 0x00D9: 'Voyetra Turtle Beach',
+ 0x00DA: 'txtr GmbH',
+ 0x00DB: 'Biosentronics',
+ 0x00DC: 'Procter & Gamble',
+ 0x00DD: 'Hosiden Corporation',
+ 0x00DE: 'Muzik LLC',
+ 0x00DF: 'Misfit Wearables Corp',
+ 0x00E0: 'Google',
+ 0x00E1: 'Danlers Ltd',
+ 0x00E2: 'Semilink Inc',
+ 0x00E3: 'inMusic Brands, Inc',
+ 0x00E4: 'L.S. Research Inc.',
+ 0x00E5: 'Eden Software Consultants Ltd.',
+ 0x00E6: 'Freshtemp',
+ 0x00e7: 'KS Technologies',
+ 0x00e8: 'ACTS Technologies',
+ 0x00e9: 'Vtrack Systems',
+ 0x00ea: 'Nielsen-Kellerman Company',
+ 0x00eb: 'Server Technology, Inc.',
+ 0x00ec: 'BioResearch Associates',
+ 0x00ed: 'Jolly Logic, LLC',
+ 0x00ee: 'Above Average Outcomes, Inc.',
+ 0x00ef: 'Bitsplitters GmbH',
+ 0x00f0: 'PayPal, Inc.',
+ 0x00f1: 'Witron Technology Limited',
+ 0x00f2: 'Aether Things Inc. (formerly Morse Project Inc.)',
+ 0x00f3: 'Kent Displays Inc.',
+ 0x00f4: 'Nautilus Inc.',
+ 0x00f5: 'Smartifier Oy',
+ 0x00f6: 'Elcometer Limited',
+ 0x00f7: 'VSN Technologies Inc.',
+ 0x00f8: 'AceUni Corp., Ltd.',
+ 0x00f9: 'StickNFind',
+ 0x00fa: 'Crystal Code AB',
+ 0x00fb: 'KOUKAAM a.s.',
+ 0x00fc: 'Delphi Corporation',
+ 0x00fd: 'ValenceTech Limited',
+ 0x00fe: 'Reserved',
+ 0x00ff: 'Typo Products, LLC',
+ 0x0100: 'TomTom International BV',
+ 0x0101: 'Fugoo, Inc',
+ 0x0102: 'Keiser Corporation',
+ 0x0103: 'Bang & Olufsen A/S',
+ 0x0104: 'PLUS Locations Systems Pty Ltd',
+ 0x0105: 'Ubiquitous Computing Technology Corporation',
+ 0x0106: 'Innovative Yachtter Solutions',
+ 0x0107: 'William Demant Holding A/S',
+ 0x0108: 'Chicony Electronics Co., Ltd.',
+ 0x0109: 'Atus BV',
+ 0x010a: 'Codegate Ltd.',
+ 0x010b: 'ERi, Inc.',
+ 0x010c: 'Transducers Direct, LLC',
+ 0x010d: 'Fujitsu Ten Limited',
+ 0x010e: 'Audi AG',
+ 0x010f: 'HiSilicon Technologies Co., Ltd.',
+ 0x0110: 'Nippon Seiki Co., Ltd.',
+ 0x0111: 'Steelseries ApS',
+ 0x0112: 'vyzybl Inc.',
+ 0x0113: 'Openbrain Technologies, Co., Ltd.',
+ 0x0114: 'Xensr',
+ 0x0115: 'e.solutions',
+ 0x0116: '1OAK Technologies',
+ 0x0117: 'Wimoto Technologies Inc',
+ 0x0118: 'Radius Networks, Inc.',
+ 0x0119: 'Wize Technology Co., Ltd.',
+ 0x011a: 'Qualcomm Labs, Inc.',
+ 0x011b: 'Aruba Networks',
+ 0x011c: 'Baidu',
+ 0x011d: 'Arendi AG',
+ 0x011e: 'Skoda Auto a.s.',
+ 0x011f: 'Volkswagon AG',
+ 0x0120: 'Porsche AG',
+ 0x0121: 'Sino Wealth Electronic Ltd.',
+ 0x0122: 'AirTurn, Inc.',
+ 0x0123: 'Kinsa, Inc.',
+ 0x0124: 'HID Global',
+ 0x0125: 'SEAT es',
+ 0x0126: 'Promethean Ltd.',
+ 0x0127: 'Salutica Allied Solutions',
+ 0x0128: 'GPSI Group Pty Ltd',
+ 0x0129: 'Nimble Devices Oy',
+ 0x012a: 'Changzhou Yongse Infotech Co., Ltd',
+ 0x012b: 'SportIQ',
+ 0x012c: 'TEMEC Instruments B.V.',
+ 0x012d: 'Sony Corporation',
+ 0x012e: 'ASSA ABLOY',
+ 0x012f: 'Clarion Co., Ltd.',
+ 0x0130: 'Warehouse Innovations',
+ 0x0131: 'Cypress Semiconductor Corporation',
+ 0x0132: 'MADS Inc',
+ 0x0133: 'Blue Maestro Limited',
+ 0x0134: 'Resolution Products, Inc.',
+ 0x0135: 'Airewear LLC',
+ 0x0136: 'Seed Labs, Inc. (formerly ETC sp. z.o.o.)',
+ 0x0137: 'Prestigio Plaza Ltd.',
+ 0x0138: 'NTEO Inc.',
+ 0x0139: 'Focus Systems Corporation',
+ 0x013a: 'Tencent Holdings Limited',
+ 0x013b: 'Allegion',
+ 0x013c: 'Murata Manufacuring Co., Ltd.',
+ 0x013e: 'Nod, Inc.',
+ 0x013f: 'B&B Manufacturing Company',
+ 0x0140: 'Alpine Electronics (China) Co., Ltd',
+ 0x0141: 'FedEx Services',
+ 0x0142: 'Grape Systems Inc.',
+ 0x0143: 'Bkon Connect',
+ 0x0144: 'Lintech GmbH',
+ 0x0145: 'Novatel Wireless',
+ 0x0146: 'Ciright',
+ 0x0147: 'Mighty Cast, Inc.',
+ 0x0148: 'Ambimat Electronics',
+ 0x0149: 'Perytons Ltd.',
+ 0x014a: 'Tivoli Audio, LLC',
+ 0x014b: 'Master Lock',
+ 0x014c: 'Mesh-Net Ltd',
+ 0x014d: 'Huizhou Desay SV Automotive CO., LTD.',
+ 0x014e: 'Tangerine, Inc.',
+ 0x014f: 'B&W Group Ltd.',
+ 0x0150: 'Pioneer Corporation',
+ 0x0151: 'OnBeep',
+ 0x0152: 'Vernier Software & Technology',
+ 0x0153: 'ROL Ergo',
+ 0x0154: 'Pebble Technology',
+ 0x0155: 'NETATMO',
+ 0x0156: 'Accumulate AB',
+ 0x0157: 'Anhui Huami Information Technology Co., Ltd.',
+ 0x0158: 'Inmite s.r.o.',
+ 0x0159: 'ChefSteps, Inc.',
+ 0x015a: 'micas AG',
+ 0x015b: 'Biomedical Research Ltd.',
+ 0x015c: 'Pitius Tec S.L.',
+ 0x015d: 'Estimote, Inc.',
+ 0x015e: 'Unikey Technologies, Inc.',
+ 0x015f: 'Timer Cap Co.',
+ 0x0160: 'AwoX',
+ 0x0161: 'yikes',
+ 0x0162: 'MADSGlobal NZ Ltd.',
+ 0x0163: 'PCH International',
+ 0x0164: 'Qingdao Yeelink Information Technology Co., Ltd.',
+ 0x0165: 'Milwaukee Tool (formerly Milwaukee Electric Tools)',
+ 0x0166: 'MISHIK Pte Ltd',
+ 0x0167: 'Bayer HealthCare',
+ 0x0168: 'Spicebox LLC',
+ 0x0169: 'emberlight',
+ 0x016a: 'Cooper-Atkins Corporation',
+ 0x016b: 'Qblinks',
+ 0x016c: 'MYSPHERA',
+ 0x016d: 'LifeScan Inc',
+ 0x016e: 'Volantic AB',
+ 0x016f: 'Podo Labs, Inc',
+ 0x0170: 'Roche Diabetes Care AG',
+ 0x0171: 'Amazon Fulfillment Service',
+ 0x0172: 'Connovate Technology Private Limited',
+ 0x0173: 'Kocomojo, LLC',
+ 0x0174: 'Everykey LLC',
+ 0x0175: 'Dynamic Controls',
+ 0x0176: 'SentriLock',
+ 0x0177: 'I-SYST inc.',
+ 0x0178: 'CASIO COMPUTER CO., LTD.',
+ 0x0179: 'LAPIS Semiconductor Co., Ltd.',
+ 0x017a: 'Telemonitor, Inc.',
+ 0x017b: 'taskit GmbH',
+ 0x017c: 'Daimler AG',
+ 0x017d: 'BatAndCat',
+ 0x017e: 'BluDotz Ltd',
+ 0x017f: 'XTel ApS',
+ 0x0180: 'Gigaset Communications GmbH',
+ 0x0181: 'Gecko Health Innovations, Inc.',
+ 0x0182: 'HOP Ubiquitous',
+ 0x0183: 'To Be Assigned',
+ 0x0184: 'Nectar',
+ 0x0185: 'bel’apps LLC',
+ 0x0186: 'CORE Lighting Ltd',
+ 0x0187: 'Seraphim Sense Ltd',
+ 0x0188: 'Unico RBC',
+ 0x0189: 'Physical Enterprises Inc.',
+ 0x018a: 'Able Trend Technology Limited',
+ 0x018b: 'Konica Minolta, Inc.',
+ 0x018c: 'Wilo SE',
+ 0x018d: 'Extron Design Services',
+ 0x018e: 'Fitbit, Inc.',
+ 0x018f: 'Fireflies Systems',
+ 0x0190: 'Intelletto Technologies Inc.',
+ 0x0191: 'FDK CORPORATION',
+ 0x0192: 'Cloudleaf, Inc',
+ 0x0193: 'Maveric Automation LLC',
+ 0x0194: 'Acoustic Stream Corporation',
+ 0x0195: 'Zuli',
+ 0x0196: 'Paxton Access Ltd',
+ 0x0197: 'WiSilica Inc',
+ 0x0198: 'Vengit Limited',
+ 0x0199: 'SALTO SYSTEMS S.L.',
+ 0x019a: 'TRON Forum (formerly T-Engine Forum)',
+ 0x019b: 'CUBETECH s.r.o.',
+ 0x019c: 'Cokiya Incorporated',
+ 0x019d: 'CVS Health',
+ 0x019e: 'Ceruus',
+ 0x019f: 'Strainstall Ltd',
+ 0x01a0: 'Channel Enterprises (HK) Ltd.',
+ 0x01a1: 'FIAMM',
+ 0x01a2: 'GIGALANE.CO.,LTD',
+ 0x01a3: 'EROAD',
+ 0x01a4: 'Mine Safety Appliances',
+ 0x01a5: 'Icon Health and Fitness',
+ 0x01a6: 'Asandoo GmbH',
+ 0x01a7: 'ENERGOUS CORPORATION',
+ 0x01a8: 'Taobao',
+ 0x01a9: 'Canon Inc.',
+ 0x01aa: 'Geophysical Technology Inc.',
+ 0x01ab: 'Facebook, Inc.',
+ 0x01ac: 'Nipro Diagnostics, Inc.',
+ 0x01ad: 'FlightSafety International',
+ 0x01ae: 'Earlens Corporation',
+ 0x01af: 'Sunrise Micro Devices, Inc.',
+ 0x01b0: 'Star Micronics Co., Ltd.',
+ 0x01b1: 'Netizens Sp. z o.o.',
+ 0x01b2: 'Nymi Inc.',
+ 0x01b3: 'Nytec, Inc.',
+ 0x01b4: 'Trineo Sp. z o.o.',
+ 0x01b5: 'Nest Labs Inc.',
+ 0x01b6: 'LM Technologies Ltd',
+ 0x01b7: 'General Electric Company',
+ 0x01b8: 'i+D3 S.L.',
+ 0x01b9: 'HANA Micron',
+ 0x01ba: 'Stages Cycling LLC',
+ 0x01bb: 'Cochlear Bone Anchored Solutions AB',
+ 0x01bc: 'SenionLab AB',
+ 0x01bd: 'Syszone Co., Ltd',
+ 0x01be: 'Pulsate Mobile Ltd.',
+ 0x01bf: 'Hong Kong HunterSun Electronic Limited',
+ 0x01c0: 'pironex GmbH',
+ 0x01c1: 'BRADATECH Corp.',
+ 0x01c2: 'Transenergooil AG',
+ 0x01c3: 'Bunch',
+ 0x01c4: 'DME Microelectronics',
+ 0x01c5: 'Bitcraze AB',
+ 0x01c6: 'HASWARE Inc.',
+ 0x01c7: 'Abiogenix Inc.',
+ 0x01c8: 'Poly-Control ApS',
+ 0x01c9: 'Avi-on',
+ 0x01ca: 'Laerdal Medical AS',
+ 0x01cb: 'Fetch My Pet',
+ 0x01cc: 'Sam Labs Ltd.',
+ 0x01cd: 'Chengdu Synwing Technology Ltd',
+ 0x01ce: 'HOUWA SYSTEM DESIGN, k.k.',
+ 0x01cf: 'BSH',
+ 0x01d0: 'Primus Inter Pares Ltd',
+ 0x01d1: 'August',
+ 0x01d2: 'Gill Electronics',
+ 0x01d3: 'Sky Wave Design',
+ 0x01d4: 'Newlab S.r.l.',
+ 0x01d5: 'ELAD srl',
+ 0x01d6: 'G-wearables inc.',
+ 0x01d7: 'Squadrone Systems Inc.',
+ 0x01d8: 'Code Corporation',
+ 0x01d9: 'Savant Systems LLC',
+ 0x01da: 'Logitech International SA',
+ 0x01db: 'Innblue Consulting',
+ 0x01dc: 'iParking Ltd.',
+ 0x01dd: 'Koninklijke Philips Electronics N.V.',
+ 0x01de: 'Minelab Electronics Pty Limited',
+ 0x01df: 'Bison Group Ltd.',
+ 0x01e0: 'Widex A/S',
+ 0x01e1: 'Jolla Ltd',
+ 0x01e2: 'Lectronix, Inc.',
+ 0x01e3: 'Caterpillar Inc',
+ 0x01e4: 'Freedom Innovations',
+ 0x01e5: 'Dynamic Devices Ltd',
+ 0x01e6: 'Technology Solutions (UK) Ltd',
+ 0x01e7: 'IPS Group Inc.',
+ 0x01e8: 'STIR',
+ 0x01e9: 'Sano, Inc',
+ 0x01ea: 'Advanced Application Design, Inc.',
+ 0x01eb: 'AutoMap LLC',
+ 0x01ec: 'Spreadtrum Communications Shanghai Ltd',
+ 0x01ed: 'CuteCircuit LTD',
+ 0x01ee: 'Valeo Service',
+ 0x01ef: 'Fullpower Technologies, Inc.',
+ 0x01f0: 'KloudNation',
+ 0x01f1: 'Zebra Technologies Corporation',
+ 0x01f2: 'Itron, Inc.',
+ 0x01f3: 'The University of Tokyo',
+ 0x01f4: 'UTC Fire and Security',
+ 0x01f5: 'Cool Webthings Limited',
+ 0x01f6: 'DJO Global',
+ 0x01f7: 'Gelliner Limited',
+ 0x01f8: 'Anyka (Guangzhou) Microelectronics Technology Co, LTD',
+ 0x01f9: 'Medtronic, Inc.',
+ 0x01fa: 'Gozio, Inc.',
+ 0x01fb: 'Form Lifting, LLC',
+ 0x01fc: 'Wahoo Fitness, LLC',
+ 0x01fd: 'Kontakt Micro-Location Sp. z o.o.',
+ 0x01fe: 'Radio System Corporation',
+ 0x01ff: 'Freescale Semiconductor, Inc.',
+ 0x0200: 'Verifone Systems PTe Ltd. Taiwan Branch',
+ 0x0201: 'AR Timing',
+ 0x0202: 'Rigado LLC',
+ 0x0203: 'Kemppi Oy',
+ 0x0204: 'Tapcentive Inc.',
+ 0x0205: 'Smartbotics Inc.',
+ 0x0206: 'Otter Products, LLC',
+ 0x0207: 'STEMP Inc.',
+ 0x0208: 'LumiGeek LLC',
+ 0x0209: 'InvisionHeart Inc.',
+ 0x020A: 'Macnica Inc. ',
+ 0x020b: 'Jaguar Land Rover Limited',
+ 0x020c: 'CoroWare Technologies, Inc',
+ 0x020d: 'Simplo Technology Co., LTD',
+ 0x020e: 'Omron Healthcare Co., LTD',
+ 0x020f: 'Comodule GMBH',
+ 0x0210: 'ikeGPS',
+ 0x0211: 'Telink Semiconductor Co. Ltd',
+ 0x0212: 'Interplan Co., Ltd',
+ 0x0213: 'Wyler AG',
+ 0x0214: 'IK Multimedia Production srl',
+ 0x0215: 'Lukoton Experience Oy',
+ 0x0216: 'MTI Ltd',
+ 0x0217: 'Tech4home, Lda',
+ 0x0218: 'Hiotech AB',
+ 0x0219: 'DOTT Limited',
+ 0x021A: 'Blue Speck Labs, LLC',
+ 0x021B: 'Cisco Systems, Inc',
+ 0x021C: 'Mobicomm Inc',
+ 0x021D: 'Edamic',
+ 0x021E: 'Goodnet, Ltd',
+ 0x021F: 'Luster Leaf Products Inc',
+ 0x0220: 'Manus Machina BV',
+ 0x0221: 'Mobiquity Networks Inc',
+ 0x0222: 'Praxis Dynamics',
+ 0x0223: 'Philip Morris Products S.A.',
+ 0x0224: 'Comarch SA',
+ 0x0225: 'Nestl Nespresso S.A.',
+ 0x0226: 'Merlinia A/S',
+ 0x0227: 'LifeBEAM Technologies',
+ 0x0228: 'Twocanoes Labs, LLC',
+ 0x0229: 'Muoverti Limited',
+ 0x022A: 'Stamer Musikanlagen GMBH',
+ 0x022B: 'Tesla Motors',
+ 0x022C: 'Pharynks Corporation',
+ 0x022D: 'Lupine',
+ 0x022E: 'Siemens AG',
+ 0x022F: 'Huami (Shanghai) Culture Communication CO., LTD',
+ 0x0230: 'Foster Electric Company, Ltd',
+ 0x0231: 'ETA SA',
+ 0x0232: 'x-Senso Solutions Kft',
+ 0x0233: 'Shenzhen SuLong Communication Ltd',
+ 0x0234: 'FengFan (BeiJing) Technology Co, Ltd',
+ 0x0235: 'Qrio Inc',
+ 0x0236: 'Pitpatpet Ltd',
+ 0x0237: 'MSHeli s.r.l.',
+ 0x0238: 'Trakm8 Ltd',
+ 0x0239: 'JIN CO, Ltd',
+ 0x023A: 'Alatech Tehnology',
+ 0x023B: 'Beijing CarePulse Electronic Technology Co, Ltd',
+ 0x023C: 'Awarepoint',
+ 0x023D: 'ViCentra B.V.',
+ 0x023E: 'Raven Industries',
+ 0x023F: 'WaveWare Technologies Inc.',
+ 0x0240: 'Argenox Technologies',
+ 0x0241: 'Bragi GmbH',
+ 0x0242: '16Lab Inc',
+ 0x0243: 'Masimo Corp',
+ 0x0244: 'Iotera Inc',
+ 0x0245: 'Endress+Hauser',
+ 0x0246: 'ACKme Networks, Inc.',
+ 0x0247: 'FiftyThree Inc.',
+ 0x0248: 'Parker Hannifin Corp',
+ 0x0249: 'Transcranial Ltd',
+ 0x024A: 'Uwatec AG',
+ 0x024B: 'Orlan LLC',
+ 0x024C: 'Blue Clover Devices',
+ 0x024D: 'M-Way Solutions GmbH',
+ 0x024E: 'Microtronics Engineering GmbH',
+ 0x024F: 'Schneider Schreibgerte GmbH',
+ 0x0250: 'Sapphire Circuits LLC',
+ 0x0251: 'Lumo Bodytech Inc.',
+ 0x0252: 'UKC Technosolution',
+ 0x0253: 'Xicato Inc.',
+ 0x0254: 'Playbrush',
+ 0x0255: 'Dai Nippon Printing Co., Ltd.',
+ 0x0256: 'G24 Power Limited',
+ 0x0257: 'AdBabble Local Commerce Inc.',
+ 0x0258: 'Devialet SA',
+ 0x0259: 'ALTYOR',
+ 0x025A: 'University of Applied Sciences Valais/Haute Ecole Valaisanne',
+ 0x025B: 'Five Interactive, LLC dba Zendo',
+ 0x025C: 'NetEaseHangzhouNetwork co.Ltd.',
+ 0x025D: 'Lexmark International Inc.',
+ 0x025E: 'Fluke Corporation',
+ 0x025F: 'Yardarm Technologies',
+ 0x0260: 'SensaRx',
+ 0x0261: 'SECVRE GmbH',
+ 0x0262: 'Glacial Ridge Technologies',
+ 0x0263: 'Identiv, Inc.',
+ 0x0264: 'DDS, Inc.',
+ 0x0265: 'SMK Corporation',
+ 0x0266: 'Schawbel Technologies LLC',
+ 0x0267: 'XMI Systems SA',
+ 0x0268: 'Cerevo',
+ 0x0269: 'Torrox GmbH & Co KG',
+ 0x026A: 'Gemalto',
+ 0x026B: 'DEKA Research & Development Corp.',
+ 0x026C: 'Domster Tadeusz Szydlowski',
+ 0x026D: 'Technogym SPA',
+ 0x026E: 'FLEURBAEY BVBA',
+ 0x026F: 'Aptcode Solutions',
+ 0x0270: 'LSI ADL Technology',
+ 0x0271: 'Animas Corp',
+ 0x0272: 'Alps Electric Co., Ltd.',
+ 0x0273: 'OCEASOFT',
+ 0x0274: 'Motsai Research',
+ 0x0275: 'Geotab',
+ 0x0276: 'E.G.O. Elektro-Gertebau GmbH',
+ 0x0277: 'bewhere inc',
+ 0x0278: 'Johnson Outdoors Inc',
+ 0x0279: 'steute Schaltgerate GmbH & Co. KG',
+ 0x027A: 'Ekomini inc.',
+ 0x027B: 'DEFA AS',
+ 0x027C: 'Aseptika Ltd',
+ 0x027D: 'HUAWEI Technologies Co., Ltd. ( )',
+ 0x027E: 'HabitAware, LLC',
+ 0x027F: 'ruwido austria gmbh',
+ 0x0280: 'ITEC corporation',
+ 0x0281: 'StoneL',
+ 0x0282: 'Sonova AG',
+ 0x0283: 'Maven Machines, Inc.',
+ 0x0284: 'Synapse Electronics',
+ 0x0285: 'Standard Innovation Inc.',
+ 0x0286: 'RF Code, Inc.',
+ 0x0287: 'Wally Ventures S.L.',
+ 0x0288: 'Willowbank Electronics Ltd',
+ 0x0289: 'SK Telecom',
+ 0x028A: 'Jetro AS',
+ 0x028B: 'Code Gears LTD',
+ 0x028C: 'NANOLINK APS',
+ 0x028D: 'IF, LLC',
+ 0x028E: 'RF Digital Corp',
+ 0x028F: 'Church & Dwight Co., Inc',
+ 0x0290: 'Multibit Oy',
+ 0x0291: 'CliniCloud Inc',
+ 0x0292: 'SwiftSensors',
+ 0x0293: 'Blue Bite',
+ 0x0294: 'ELIAS GmbH',
+ 0x0295: 'Sivantos GmbH',
+ 0x0296: 'Petzl',
+ 0x0297: 'storm power ltd',
+ 0x0298: 'EISST Ltd',
+ 0x0299: 'Inexess Technology Simma KG',
+ 0x029A: 'Currant, Inc.',
+ 0x029B: 'C2 Development, Inc.',
+ 0x029C: 'Blue Sky Scientific, LLC',
+ 0x029D: 'ALOTTAZS LABS, LLC',
+ 0x029E: 'Kupson spol. s r.o.',
+ 0x029F: 'Areus Engineering GmbH',
+ 0x02A0: 'Impossible Camera GmbH',
+ 0x02A1: 'InventureTrack Systems',
+ 0x02A2: 'LockedUp',
+ 0x02A3: 'Itude',
+ 0x02A4: 'Pacific Lock Company',
+ 0x02A5: 'Tendyron Corporation ( )',
+ 0x02A6: 'Robert Bosch GmbH',
+ 0x02A7: 'Illuxtron international B.V.',
+ 0x02A8: 'miSport Ltd.',
+ 0x02A9: 'Chargelib',
+ 0x02AA: 'Doppler Lab',
+ 0x02AB: 'BBPOS Limited',
+ 0x02AC: 'RTB Elektronik GmbH & Co. KG',
+ 0x02AD: 'Rx Networks, Inc.',
+ 0x02AE: 'WeatherFlow, Inc.',
+ 0x02AF: 'Technicolor USA Inc.',
+ 0x02B0: 'Bestechnic(Shanghai),Ltd',
+ 0x02B1: 'Raden Inc',
+ 0x02B2: 'JouZen Oy',
+ 0x02B3: 'CLABER S.P.A.',
+ 0x02B4: 'Hyginex, Inc.',
+ 0x02B5: 'HANSHIN ELECTRIC RAILWAY CO.,LTD.',
+ 0x02B6: 'Schneider Electric',
+ 0x02B7: 'Oort Technologies LLC',
+ 0x02B8: 'Chrono Therapeutics',
+ 0x02B9: 'Rinnai Corporation',
+ 0x02BA: 'Swissprime Technologies AG',
+ 0x02BB: 'Koha.,Co.Ltd',
+ 0x02BC: 'Genevac Ltd',
+ 0x02BD: 'Chemtronics',
+ 0x02BE: 'Seguro Technology Sp. z o.o.',
+ 0x02BF: 'Redbird Flight Simulations',
+ 0x02C0: 'Dash Robotics',
+ 0x02C1: 'LINE Corporation',
+ 0x02C2: 'Guillemot Corporation',
+ 0x02C3: 'Techtronic Power Tools Technology Limited',
+ 0x02C4: 'Wilson Sporting Goods',
+ 0x02C5: 'Lenovo (Singapore) Pte Ltd. ( )',
+ 0x02C6: 'Ayatan Sensors',
+ 0x02C7: 'Electronics Tomorrow Limited',
+ 0x02C8: 'VASCO Data Security International, Inc.',
+ 0x02C9: 'PayRange Inc.',
+ 0x02CA: 'ABOV Semiconductor',
+ 0x02CB: 'AINA-Wireless Inc.',
+ 0x02CC: 'Eijkelkamp Soil & Water',
+ 0x02CD: 'BMA ergonomics b.v.',
+ 0x02CE: 'Teva Branded Pharmaceutical Products R&D, Inc.',
+ 0x02CF: 'Anima',
+ 0x02D0: '3M',
+ 0x02D1: 'Empatica Srl',
+ 0x02D2: 'Afero, Inc.',
+ 0x02D3: 'Powercast Corporation',
+ 0x02D4: 'Secuyou ApS',
+ 0x02D5: 'OMRON Corporation',
+ 0x02D6: 'Send Solutions',
+ 0x02D7: 'NIPPON SYSTEMWARE CO.,LTD.',
+ 0x02D8: 'Neosfar',
+ 0x02D9: 'Fliegl Agrartechnik GmbH',
+ 0x02DA: 'Gilvader',
+ 0x02DB: 'Digi International Inc (R)',
+ 0x02DC: 'DeWalch Technologies, Inc.',
+ 0x02DD: 'Flint Rehabilitation Devices, LLC',
+ 0x02DE: 'Samsung SDS Co., Ltd.',
+ 0x02DF: 'Blur Product Development',
+ 0x02E0: 'University of Michigan',
+ 0x02E1: 'Victron Energy BV',
+ 0x02E2: 'NTT docomo',
+ 0x02E3: 'Carmanah Technologies Corp.',
+ 0x02E4: 'Bytestorm Ltd.',
+ 0x02E5: 'Espressif Incorporated ( () )',
+ 0x02E6: 'Unwire',
+ 0x02E7: 'Connected Yard, Inc.',
+ 0x02E8: 'American Music Environments',
+ 0x02E9: 'Sensogram Technologies, Inc.',
+ 0x02EA: 'Fujitsu Limited',
+ 0x02EB: 'Ardic Technology',
+ 0x02EC: 'Delta Systems, Inc',
+ 0x02ED: 'HTC Corporation',
+ 0x02EE: 'Citizen Holdings Co., Ltd.',
+ 0x02EF: 'SMART-INNOVATION.inc',
+ 0x02F0: 'Blackrat Software',
+ 0x02F1: 'The Idea Cave, LLC',
+ 0x02F2: 'GoPro, Inc.',
+ 0x02F3: 'AuthAir, Inc',
+ 0x02F4: 'Vensi, Inc.',
+ 0x02F5: 'Indagem Tech LLC',
+ 0x02F6: 'Intemo Technologies',
+ 0x02F7: 'DreamVisions co., Ltd.',
+ 0x02F8: 'Runteq Oy Ltd',
+ 0x02F9: 'IMAGINATION TECHNOLOGIES LTD',
+ 0x02FA: 'CoSTAR TEchnologies',
+ 0x02FB: 'Clarius Mobile Health Corp.',
+ 0x02FC: 'Shanghai Frequen Microelectronics Co., Ltd.',
+ 0x02FD: 'Uwanna, Inc.',
+ 0x02FE: 'Lierda Science & Technology Group Co., Ltd.',
+ 0x02FF: 'Silicon Laboratories',
+ 0x0300: 'World Moto Inc.',
+ 0x0301: 'Giatec Scientific Inc.',
+ 0x0302: 'Loop Devices, Inc',
+ 0x0303: 'IACA electronique',
+ 0x0304: 'Martians Inc',
+ 0x0305: 'Swipp ApS',
+ 0x0306: 'Life Laboratory Inc.',
+ 0x0307: 'FUJI INDUSTRIAL CO.,LTD.',
+ 0x0308: 'Surefire, LLC',
+ 0x0309: 'Dolby Labs',
+ 0x030A: 'Ellisys',
+ 0x030B: 'Magnitude Lighting Converters',
+ 0x030C: 'Hilti AG',
+ 0x030D: 'Devdata S.r.l.',
+ 0x030E: 'Deviceworx',
+ 0x030F: 'Shortcut Labs',
+ 0x0310: 'SGL Italia S.r.l.',
+ 0x0311: 'PEEQ DATA',
+ 0x0312: 'Ducere Technologies Pvt Ltd',
+ 0x0313: 'DiveNav, Inc.',
+ 0x0314: 'RIIG AI Sp. z o.o.',
+ 0x0315: 'Thermo Fisher Scientific',
+ 0x0316: 'AG Measurematics Pvt. Ltd.',
+ 0x0317: 'CHUO Electronics CO., LTD.',
+ 0x0318: 'Aspenta International',
+ 0x0319: 'Eugster Frismag AG',
+ 0x031A: 'Amber wireless GmbH',
+ 0x031B: 'HQ Inc',
+ 0x031C: 'Lab Sensor Solutions',
+ 0x031D: 'Enterlab ApS',
+ 0x031E: 'Eyefi, Inc.',
+ 0x031F: 'MetaSystem S.p.A.',
+ 0x0320: 'SONO ELECTRONICS. CO., LTD',
+ 0x0321: 'Jewelbots',
+ 0x0322: 'Compumedics Limited',
+ 0x0323: 'Rotor Bike Components',
+ 0x0324: 'Astro, Inc.',
+ 0x0325: 'Amotus Solutions',
+ 0x0326: 'Healthwear Technologies (Changzhou)Ltd',
+ 0x0327: 'Essex Electronics',
+ 0x0328: 'Grundfos A/S',
+ 0x0329: 'Eargo, Inc.',
+ 0x032A: 'Electronic Design Lab',
+ 0x032B: 'ESYLUX',
+ 0x032C: 'NIPPON SMT.CO.,Ltd',
+ 0x032D: 'BM innovations GmbH',
+ 0x032E: 'indoormap',
+ 0x032F: 'OttoQ Inc',
+ 0x0330: 'North Pole Engineering',
+ 0x0331: '3flares Technologies Inc.',
+ 0x0332: 'Electrocompaniet A.S.',
+ 0x0333: 'Mul-T-Lock',
+ 0x0334: 'Corentium AS',
+ 0x0335: 'Enlighted Inc',
+ 0x0336: 'GISTIC',
+ 0x0337: 'AJP2 Holdings, LLC',
+ 0x0338: 'COBI GmbH',
+ 0x0339: 'Blue Sky Scientific, LLC',
+ 0x033A: 'Appception, Inc.',
+ 0x033B: 'Courtney Thorne Limited',
+ 0x033C: 'Virtuosys',
+ 0x033D: 'TPV Technology Limited',
+ 0x033E: 'Monitra SA',
+ 0x033F: 'Automation Components, Inc.',
+ 0x0340: 'Letsense s.r.l.',
+ 0x0341: 'Etesian Technologies LLC',
+ 0x0342: 'GERTEC BRASIL LTDA.',
+ 0x0343: 'Drekker Development Pty. Ltd.',
+ 0x0344: 'Whirl Inc',
+ 0x0345: 'Locus Positioning',
+ 0x0346: 'Acuity Brands Lighting, Inc',
+ 0x0347: 'Prevent Biometrics',
+ 0x0348: 'Arioneo',
+ 0x0349: 'VersaMe',
+ 0x034A: 'Vaddio',
+ 0x034B: 'Libratone A/S',
+ 0x034C: 'HM Electronics, Inc.',
+ 0x034D: 'TASER International, Inc.',
+ 0x034E: 'SafeTrust Inc.',
+ 0x034F: 'Heartland Payment Systems',
+ 0x0350: 'Bitstrata Systems Inc.',
+ 0x0351: 'Pieps GmbH',
+ 0x0352: 'iRiding(Xiamen)Technology Co.,Ltd.',
+ 0x0353: 'Alpha Audiotronics, Inc.',
+ 0x0354: 'TOPPAN FORMS CO.,LTD.',
+ 0x0355: 'Sigma Designs, Inc.',
+ 0x0356: 'Spectrum Brands, Inc.',
+ 0x0357: 'Polymap Wireless',
+ 0x0358: 'MagniWare Ltd.',
+ 0x0359: 'Novotec Medical GmbH',
+ 0x035A: 'Medicom Innovation Partner a/s',
+ 0x035B: 'Matrix Inc.',
+ 0x035C: 'Eaton Corporation',
+ 0x035D: 'KYS',
+ 0x035E: 'Naya Health, Inc.',
+ 0x035F: 'Acromag',
+ 0x0360: 'Insulet Corporation',
+ 0x0361: 'Wellinks Inc.',
+ 0x0362: 'ON Semiconductor',
+ 0x0363: 'FREELAP SA',
+ 0x0364: 'Favero Electronics Srl',
+ 0x0365: 'BioMech Sensor LLC',
+ 0x0366: 'BOLTT Sports technologies Private limited',
+ 0x0367: 'Saphe International',
+ 0x0368: 'Metormote AB',
+ 0x0369: 'littleBits',
+ 0x036A: 'SetPoint Medical',
+ 0x036B: 'BRControls Products BV',
+ 0x036C: 'Zipcar',
+ 0x036D: 'AirBolt Pty Ltd',
+ 0x036E: 'KeepTruckin Inc',
+ 0x036F: 'Motiv, Inc.',
+ 0x0370: 'Wazombi Labs O',
+ 0x0371: 'ORBCOMM',
+ 0x0372: 'Nixie Labs, Inc.',
+ 0x0373: 'AppNearMe Ltd',
+ 0x0374: 'Holman Industries',
+ 0x0375: 'Expain AS',
+ 0x0376: 'Electronic Temperature Instruments Ltd',
+ 0x0377: 'Plejd AB',
+ 0x0378: 'Propeller Health',
+ 0x0379: 'Shenzhen iMCO Electronic Technology Co.,Ltd',
+ 0x037A: 'Algoria',
+ 0x037B: 'Apption Labs Inc.',
+ 0x037C: 'Cronologics Corporation',
+ 0x037D: 'MICRODIA Ltd.',
+ 0x037E: 'lulabytes S.L.',
+ 0x037F: 'Nestec S.A.',
+ 0x0380: 'LLC MEGA - F service',
+ 0x0381: 'Sharp Corporation',
+ 0x0382: 'Precision Outcomes Ltd',
+ 0x0383: 'Kronos Incorporated',
+ 0x0384: 'OCOSMOS Co., Ltd.',
+ 0x0385: 'Embedded Electronic Solutions Ltd. dba e2Solutions',
+ 0x0386: 'Aterica Inc.',
+ 0x0387: 'BluStor PMC, Inc.',
+ 0x0388: 'Kapsch TrafficCom AB',
+ 0x0389: 'ActiveBlu Corporation',
+ 0x038A: 'Kohler Mira Limited',
+ 0x038B: 'Noke',
+ 0x038C: 'Appion Inc.',
+ 0x038D: 'Resmed Ltd',
+ 0x038E: 'Crownstone B.V.',
+ 0x038F: 'Xiaomi Inc.',
+ 0x0390: 'INFOTECH s.r.o.',
+ 0x0391: 'Thingsquare AB',
+ 0x0392: 'T&D',
+ 0x0393: 'LAVAZZA S.p.A.',
+ 0x0394: 'Netclearance Systems, Inc.',
+ 0x0395: 'SDATAWAY',
+ 0x0396: 'BLOKS GmbH',
+ 0x0397: 'LEGO System A/S',
+ 0x0398: 'Thetatronics Ltd',
+ 0x0399: 'Nikon Corporation',
+ 0x039A: 'NeST',
+ 0x039B: 'South Silicon Valley Microelectronics',
+ 0x039C: 'ALE International',
+ 0x039D: 'CareView Communications, Inc.',
+ 0x039E: 'SchoolBoard Limited',
+ 0x039F: 'Molex Corporation',
+ 0x03A0: 'IVT Wireless Limited',
+ 0x03A1: 'Alpine Labs LLC',
+ 0x03A2: 'Candura Instruments',
+ 0x03A3: 'SmartMovt Technology Co., Ltd',
+ 0x03A4: 'Token Zero Ltd',
+ 0x03A5: 'ACE CAD Enterprise Co., Ltd. (ACECAD)',
+ 0x03A6: 'Medela, Inc',
+ 0x03A7: 'AeroScout',
+ 0x03A8: 'Esrille Inc.',
+ 0x03A9: 'THINKERLY SRL',
+ 0x03AA: 'Exon Sp. z o.o.',
+ 0x03AB: 'Meizu Technology Co., Ltd.',
+ 0x03AC: 'Smablo LTD',
+ 0x03AD: 'XiQ',
+ 0x03AE: 'Allswell Inc.',
+ 0x03AF: 'Comm-N-Sense Corp DBA Verigo',
+ 0x03B0: 'VIBRADORM GmbH',
+ 0x03B1: 'Otodata Wireless Network Inc.',
+ 0x03B2: 'Propagation Systems Limited',
+ 0x03B3: 'Midwest Instruments & Controls',
+ 0x03B4: 'Alpha Nodus, inc.',
+ 0x03B5: 'petPOMM, Inc',
+ 0x03B6: 'Mattel',
+ 0x03B7: 'Airbly Inc.',
+ 0x03B8: 'A-Safe Limited',
+ 0x03B9: 'FREDERIQUE CONSTANT SA',
+ 0x03BA: 'Maxscend Microelectronics Company Limited',
+ 0x03BB: 'Abbott Diabetes Care',
+ 0x03BC: 'ASB Bank Ltd',
+ 0x03BD: 'amadas',
+ 0x03BE: 'Applied Science, Inc.',
+ 0x03BF: 'iLumi Solutions Inc.',
+ 0x03C0: 'Arch Systems Inc.',
+ 0x03C1: 'Ember Technologies, Inc.',
+ 0x03C2: 'Snapchat Inc',
+ 0x03C3: 'Casambi Technologies Oy',
+ 0x03C4: 'Pico Technology Inc.',
+ 0x03C5: 'St. Jude Medical, Inc.',
+ 0x03C6: 'Intricon',
+ 0x03C7: 'Structural Health Systems, Inc.',
+ 0x03C8: 'Avvel International',
+ 0x03C9: 'Gallagher Group',
+ 0x03CA: 'In2things Automation Pvt. Ltd.',
+ 0x03CB: 'SYSDEV Srl',
+ 0x03CC: 'Vonkil Technologies Ltd',
+ 0x03CD: 'Wynd Technologies, Inc.',
+ 0x03CE: 'CONTRINEX S.A.',
+ 0x03CF: 'MIRA, Inc.',
+ 0x03D0: 'Watteam Ltd',
+ 0x03D1: 'Density Inc.',
+ 0x03D2: 'IOT Pot India Private Limited',
+ 0x03D3: 'Sigma Connectivity AB',
+ 0x03D4: 'PEG PEREGO SPA',
+ 0x03D5: 'Wyzelink Systems Inc.',
+ 0x03D6: 'Yota Devices LTD',
+ 0x03D7: 'FINSECUR',
+ 0x03D8: 'Zen-Me Labs Ltd',
+ 0x03D9: '3IWare Co., Ltd.',
+ 0x03DA: 'EnOcean GmbH',
+ 0x03DB: 'Instabeat, Inc',
+ 0x03DC: 'Nima Labs',
+ 0x03DD: 'Andreas Stihl AG & Co. KG',
+ 0x03DE: 'Nathan Rhoades LLC',
+ 0x03DF: 'Grob Technologies, LLC',
+ 0x03E0: 'Actions (Zhuhai) Technology Co., Limited',
+ 0x03E1: 'SPD Development Company Ltd',
+ 0x03E2: 'Sensoan Oy',
+ 0x03E3: 'Qualcomm Life Inc',
+ 0x03E4: 'Chip-ing AG',
+ 0x03E5: 'ffly4u',
+ 0x03E6: 'IoT Instruments Oy',
+ 0x03E7: 'TRUE Fitness Technology',
+ 0x03E8: 'Reiner Kartengeraete GmbH & Co. KG.',
+ 0x03E9: 'SHENZHEN LEMONJOY TECHNOLOGY CO., LTD.',
+ 0x03EA: 'Hello Inc.',
+ 0x03EB: 'Evollve Inc.',
+ 0x03EC: 'Jigowatts Inc.',
+ 0x03ED: 'BASIC MICRO.COM,INC.',
+ 0x03EE: 'CUBE TECHNOLOGIES',
+ 0x03EF: 'foolography GmbH',
+ 0x03F0: 'CLINK',
+ 0x03F1: 'Hestan Smart Cooking Inc.',
+ 0x03F2: 'WindowMaster A/S',
+ 0x03F3: 'Flowscape AB',
+ 0x03F4: 'PAL Technologies Ltd',
+ 0x03F5: 'WHERE, Inc.',
+ 0x03F6: 'Iton Technology Corp.',
+ 0x03F7: 'Owl Labs Inc.',
+ 0x03F8: 'Rockford Corp.',
+ 0x03F9: 'Becon Technologies Co.,Ltd.',
+ 0x03FA: 'Vyassoft Technologies Inc',
+ 0x03FB: 'Nox Medical',
+ 0x03FC: 'Kimberly-Clark',
+ 0x03FD: 'Trimble Navigation Ltd.',
+ 0x03FE: 'Littelfuse',
+ 0x03FF: 'Withings',
+ 0x0400: 'i-developer IT Beratung UG',
+ 0x0402: 'Sears Holdings Corporation',
+ 0x0403: 'Gantner Electronic GmbH',
+ 0x0404: 'Authomate Inc',
+ 0x0405: 'Vertex International, Inc.',
+ 0x0406: 'Airtago',
+ 0x0407: 'Swiss Audio SA',
+ 0x0408: 'ToGetHome Inc.',
+ 0x0409: 'AXIS',
+ 0x040A: 'Openmatics',
+ 0x040B: 'Jana Care Inc.',
+ 0x040C: 'Senix Corporation',
+ 0x040D: 'NorthStar Battery Company, LLC',
+ 0x040E: 'SKF (U.K.) Limited',
+ 0x040F: 'CO-AX Technology, Inc.',
+ 0x0410: 'Fender Musical Instruments',
+ 0x0411: 'Luidia Inc',
+ 0x0412: 'SEFAM',
+ 0x0413: 'Wireless Cables Inc',
+ 0x0414: 'Lightning Protection International Pty Ltd',
+ 0x0415: 'Uber Technologies Inc',
+ 0x0416: 'SODA GmbH',
+ 0x0417: 'Fatigue Science',
+ 0x0418: 'Alpine Electronics Inc.',
+ 0x0419: 'Novalogy LTD',
+ 0x041A: 'Friday Labs Limited',
+ 0x041B: 'OrthoAccel Technologies',
+ 0x041C: 'WaterGuru, Inc.',
+ 0x041D: 'Benning Elektrotechnik und Elektronik GmbH & Co. KG',
+ 0x041E: 'Dell Computer Corporation',
+ 0x041F: 'Kopin Corporation',
+ 0x0420: 'TecBakery GmbH',
+ 0x0421: 'Backbone Labs, Inc.',
+ 0x0422: 'DELSEY SA',
+ 0x0423: 'Chargifi Limited',
+ 0x0424: 'Trainesense Ltd.',
+ 0x0425: 'Unify Software and Solutions GmbH & Co. KG',
+ 0x0426: 'Husqvarna AB',
+ 0x0427: 'Focus fleet and fuel management inc',
+ 0x0428: 'SmallLoop, LLC',
+ 0x0429: 'Prolon Inc.',
+ 0x042A: 'BD Medical',
+ 0x042B: 'iMicroMed Incorporated',
+ 0x042C: 'Ticto N.V.',
+ 0x042D: 'Meshtech AS',
+ 0x042E: 'MemCachier Inc.',
+ 0x042F: 'Danfoss A/S',
+ 0x0430: 'SnapStyk Inc.',
+ 0x0431: 'Amyway Corporation',
+ 0x0432: 'Silk Labs, Inc.',
+ 0x0433: 'Pillsy Inc.',
+ 0x0434: 'Hatch Baby, Inc.',
+ 0x0435: 'Blocks Wearables Ltd.',
+ 0x0436: 'Drayson Technologies (Europe) Limited',
+ 0x0437: 'eBest IOT Inc.',
+ 0x0438: 'Helvar Ltd',
+ 0x0439: 'Radiance Technologies',
+ 0x043A: 'Nuheara Limited',
+ 0x043B: 'Appside co., ltd.',
+ 0x043C: 'DeLaval',
+ 0x043D: 'Coiler Corporation',
+ 0x043E: 'Thermomedics, Inc.',
+ 0x043F: 'Tentacle Sync GmbH',
+ 0x0440: 'Valencell, Inc.',
+ 0x0441: 'iProtoXi Oy',
+ 0x0442: 'SECOM CO., LTD.',
+ 0x0443: 'Tucker International LLC',
+ 0x0444: 'Metanate Limited',
+ 0x0445: 'Kobian Canada Inc.',
+ 0x0446: 'NETGEAR, Inc.',
+ 0x0447: 'Fabtronics Australia Pty Ltd',
+ 0x0448: 'Grand Centrix GmbH',
+ 0x0449: '1UP USA.com llc',
+ 0x044A: 'SHIMANO INC.',
+ 0x044B: 'Nain Inc.',
+ 0x044C: 'LifeStyle Lock, LLC',
+ 0x044D: 'VEGA Grieshaber KG',
+ 0x044E: 'Xtrava Inc.',
+ 0x044F: 'TTS Tooltechnic Systems AG & Co. KG',
+ 0x0450: 'Teenage Engineering AB',
+ 0x0451: 'Tunstall Nordic AB',
+ 0x0452: 'Svep Design Center AB',
+ 0x0453: 'GreenPeak Technologies BV',
+ 0x0454: 'Sphinx Electronics GmbH & Co KG',
+ 0x0455: 'Atomation',
+ 0x0456: 'Nemik Consulting Inc',
+ 0x0457: 'RF INNOVATION',
+ 0x0458: 'Mini Solution Co., Ltd.',
+ 0x0459: 'Lumenetix, Inc',
+ 0x045A: '2048450 Ontario Inc',
+ 0x045B: 'SPACEEK LTD',
+ 0x045C: 'Delta T Corporation',
+ 0x045D: 'Boston Scientific Corporation',
+ 0x045E: 'Nuviz, Inc.',
+ 0x045F: 'Real Time Automation, Inc.',
+ 0x0460: 'Kolibree',
+ 0x0461: 'vhf elektronik GmbH',
+ 0x0462: 'Bonsai Systems GmbH',
+ 0x0463: 'Fathom Systems Inc.',
+ 0x0464: 'Bellman & Symfon',
+ 0x0465: 'International Forte Group LLC',
+ 0x0466: 'CycleLabs Solutions inc.',
+ 0x0467: 'Codenex Oy',
+ 0x0468: 'Kynesim Ltd',
+ 0x0469: 'Palago AB',
+ 0x046A: 'INSIGMA INC.',
+ 0x046B: 'PMD Solutions',
+ 0x046C: 'Qingdao Realtime Technology Co., Ltd.',
+ 0x046D: 'BEGA Gantenbrink-Leuchten KG',
+ 0x046E: 'Pambor Ltd.',
+ 0xFFFF: 'SPECIAL USE/DEFAULT'
};
/***/ }),
-/***/ 27460:
-/***/ ((module) => {
-
-// Returns a wrapper function that returns a wrapped callback
-// The wrapper function should do some stuff, and return a
-// presumably different callback function.
-// This makes sure that own properties are retained, so that
-// decorations and such are not lost along the way.
-module.exports = wrappy
-function wrappy (fn, cb) {
- if (fn && cb) return wrappy(fn)(cb)
-
- if (typeof fn !== 'function')
- throw new TypeError('need wrapper function')
-
- Object.keys(fn).forEach(function (k) {
- wrapper[k] = fn[k]
- })
-
- return wrapper
-
- function wrapper() {
- var args = new Array(arguments.length)
- for (var i = 0; i < args.length; i++) {
- args[i] = arguments[i]
- }
- var ret = fn.apply(this, args)
- var cb = args[args.length-1]
- if (typeof ret === 'function' && ret !== cb) {
- Object.keys(cb).forEach(function (k) {
- ret[k] = cb[k]
- })
- }
- return ret
- }
-}
-
-
-/***/ }),
-
-/***/ 73700:
-/***/ ((module) => {
-
-module.exports = eval("require")("osx-temperature-sensor");
-
-
-/***/ }),
-
-/***/ 52704:
-/***/ ((module) => {
-
-module.exports = eval("require")("supports-color");
-
-
-/***/ }),
-
-/***/ 42613:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert");
-
-/***/ }),
-
-/***/ 90290:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks");
-
-/***/ }),
-
-/***/ 20181:
-/***/ ((module) => {
-
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer");
-
-/***/ }),
-
-/***/ 35317:
-/***/ ((module) => {
+/***/ 16832:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process");
-/***/ }),
+// @ts-check
+// ==================================================================================
+// cpu.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 4. CPU
+// ----------------------------------------------------------------------------------
-/***/ 64236:
-/***/ ((module) => {
+const os = __nccwpck_require__(70857);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const fs = __nccwpck_require__(79896);
+const util = __nccwpck_require__(77496);
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console");
+let _platform = process.platform;
-/***/ }),
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
-/***/ 76982:
-/***/ ((module) => {
+let _cpu_speed = 0;
+let _current_cpu = {
+ user: 0,
+ nice: 0,
+ system: 0,
+ idle: 0,
+ irq: 0,
+ steal: 0,
+ guest: 0,
+ load: 0,
+ tick: 0,
+ ms: 0,
+ currentLoad: 0,
+ currentLoadUser: 0,
+ currentLoadSystem: 0,
+ currentLoadNice: 0,
+ currentLoadIdle: 0,
+ currentLoadIrq: 0,
+ currentLoadSteal: 0,
+ currentLoadGuest: 0,
+ rawCurrentLoad: 0,
+ rawCurrentLoadUser: 0,
+ rawCurrentLoadSystem: 0,
+ rawCurrentLoadNice: 0,
+ rawCurrentLoadIdle: 0,
+ rawCurrentLoadIrq: 0,
+ rawCurrentLoadSteal: 0,
+ rawCurrentLoadGuest: 0
+};
+let _cpus = [];
+let _corecount = 0;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto");
+const AMDBaseFrequencies = {
+ '8346': '1.8',
+ '8347': '1.9',
+ '8350': '2.0',
+ '8354': '2.2',
+ '8356|SE': '2.4',
+ '8356': '2.3',
+ '8360': '2.5',
+ '2372': '2.1',
+ '2373': '2.1',
+ '2374': '2.2',
+ '2376': '2.3',
+ '2377': '2.3',
+ '2378': '2.4',
+ '2379': '2.4',
+ '2380': '2.5',
+ '2381': '2.5',
+ '2382': '2.6',
+ '2384': '2.7',
+ '2386': '2.8',
+ '2387': '2.8',
+ '2389': '2.9',
+ '2393': '3.1',
+ '8374': '2.2',
+ '8376': '2.3',
+ '8378': '2.4',
+ '8379': '2.4',
+ '8380': '2.5',
+ '8381': '2.5',
+ '8382': '2.6',
+ '8384': '2.7',
+ '8386': '2.8',
+ '8387': '2.8',
+ '8389': '2.9',
+ '8393': '3.1',
+ '2419EE': '1.8',
+ '2423HE': '2.0',
+ '2425HE': '2.1',
+ '2427': '2.2',
+ '2431': '2.4',
+ '2435': '2.6',
+ '2439SE': '2.8',
+ '8425HE': '2.1',
+ '8431': '2.4',
+ '8435': '2.6',
+ '8439SE': '2.8',
+ '4122': '2.2',
+ '4130': '2.6',
+ '4162EE': '1.7',
+ '4164EE': '1.8',
+ '4170HE': '2.1',
+ '4174HE': '2.3',
+ '4176HE': '2.4',
+ '4180': '2.6',
+ '4184': '2.8',
+ '6124HE': '1.8',
+ '6128HE': '2.0',
+ '6132HE': '2.2',
+ '6128': '2.0',
+ '6134': '2.3',
+ '6136': '2.4',
+ '6140': '2.6',
+ '6164HE': '1.7',
+ '6166HE': '1.8',
+ '6168': '1.9',
+ '6172': '2.1',
+ '6174': '2.2',
+ '6176': '2.3',
+ '6176SE': '2.3',
+ '6180SE': '2.5',
+ '3250': '2.5',
+ '3260': '2.7',
+ '3280': '2.4',
+ '4226': '2.7',
+ '4228': '2.8',
+ '4230': '2.9',
+ '4234': '3.1',
+ '4238': '3.3',
+ '4240': '3.4',
+ '4256': '1.6',
+ '4274': '2.5',
+ '4276': '2.6',
+ '4280': '2.8',
+ '4284': '3.0',
+ '6204': '3.3',
+ '6212': '2.6',
+ '6220': '3.0',
+ '6234': '2.4',
+ '6238': '2.6',
+ '6262HE': '1.6',
+ '6272': '2.1',
+ '6274': '2.2',
+ '6276': '2.3',
+ '6278': '2.4',
+ '6282SE': '2.6',
+ '6284SE': '2.7',
+ '6308': '3.5',
+ '6320': '2.8',
+ '6328': '3.2',
+ '6338P': '2.3',
+ '6344': '2.6',
+ '6348': '2.8',
+ '6366': '1.8',
+ '6370P': '2.0',
+ '6376': '2.3',
+ '6378': '2.4',
+ '6380': '2.5',
+ '6386': '2.8',
+ 'FX|4100': '3.6',
+ 'FX|4120': '3.9',
+ 'FX|4130': '3.8',
+ 'FX|4150': '3.8',
+ 'FX|4170': '4.2',
+ 'FX|6100': '3.3',
+ 'FX|6120': '3.6',
+ 'FX|6130': '3.6',
+ 'FX|6200': '3.8',
+ 'FX|8100': '2.8',
+ 'FX|8120': '3.1',
+ 'FX|8140': '3.2',
+ 'FX|8150': '3.6',
+ 'FX|8170': '3.9',
+ 'FX|4300': '3.8',
+ 'FX|4320': '4.0',
+ 'FX|4350': '4.2',
+ 'FX|6300': '3.5',
+ 'FX|6350': '3.9',
+ 'FX|8300': '3.3',
+ 'FX|8310': '3.4',
+ 'FX|8320': '3.5',
+ 'FX|8350': '4.0',
+ 'FX|8370': '4.0',
+ 'FX|9370': '4.4',
+ 'FX|9590': '4.7',
+ 'FX|8320E': '3.2',
+ 'FX|8370E': '3.3',
-/***/ }),
+ // ZEN Desktop CPUs
+ '1200': '3.1',
+ 'Pro 1200': '3.1',
+ '1300X': '3.5',
+ 'Pro 1300': '3.5',
+ '1400': '3.2',
+ '1500X': '3.5',
+ 'Pro 1500': '3.5',
+ '1600': '3.2',
+ '1600X': '3.6',
+ 'Pro 1600': '3.2',
+ '1700': '3.0',
+ 'Pro 1700': '3.0',
+ '1700X': '3.4',
+ 'Pro 1700X': '3.4',
+ '1800X': '3.6',
+ '1900X': '3.8',
+ '1920': '3.2',
+ '1920X': '3.5',
+ '1950X': '3.4',
-/***/ 31637:
-/***/ ((module) => {
+ // ZEN Desktop APUs
+ '200GE': '3.2',
+ 'Pro 200GE': '3.2',
+ '220GE': '3.4',
+ '240GE': '3.5',
+ '3000G': '3.5',
+ '300GE': '3.4',
+ '3050GE': '3.4',
+ '2200G': '3.5',
+ 'Pro 2200G': '3.5',
+ '2200GE': '3.2',
+ 'Pro 2200GE': '3.2',
+ '2400G': '3.6',
+ 'Pro 2400G': '3.6',
+ '2400GE': '3.2',
+ 'Pro 2400GE': '3.2',
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel");
+ // ZEN Mobile APUs
+ 'Pro 200U': '2.3',
+ '300U': '2.4',
+ '2200U': '2.5',
+ '3200U': '2.6',
+ '2300U': '2.0',
+ 'Pro 2300U': '2.0',
+ '2500U': '2.0',
+ 'Pro 2500U': '2.2',
+ '2600H': '3.2',
+ '2700U': '2.0',
+ 'Pro 2700U': '2.2',
+ '2800H': '3.3',
-/***/ }),
+ // ZEN Server Processors
+ '7351': '2.4',
+ '7351P': '2.4',
+ '7401': '2.0',
+ '7401P': '2.0',
+ '7551P': '2.0',
+ '7551': '2.0',
+ '7251': '2.1',
+ '7261': '2.5',
+ '7281': '2.1',
+ '7301': '2.2',
+ '7371': '3.1',
+ '7451': '2.3',
+ '7501': '2.0',
+ '7571': '2.2',
+ '7601': '2.2',
-/***/ 24434:
-/***/ ((module) => {
+ // ZEN Embedded Processors
+ 'V1500B': '2.2',
+ 'V1780B': '3.35',
+ 'V1202B': '2.3',
+ 'V1404I': '2.0',
+ 'V1605B': '2.0',
+ 'V1756B': '3.25',
+ 'V1807B': '3.35',
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events");
+ '3101': '2.1',
+ '3151': '2.7',
+ '3201': '1.5',
+ '3251': '2.5',
+ '3255': '2.5',
+ '3301': '2.0',
+ '3351': '1.9',
+ '3401': '1.85',
+ '3451': '2.15',
-/***/ }),
+ // ZEN+ Desktop
+ '1200|AF': '3.1',
+ '2300X': '3.5',
+ '2500X': '3.6',
+ '2600': '3.4',
+ '2600E': '3.1',
+ '1600|AF': '3.2',
+ '2600X': '3.6',
+ '2700': '3.2',
+ '2700E': '2.8',
+ 'Pro 2700': '3.2',
+ '2700X': '3.7',
+ 'Pro 2700X': '3.6',
+ '2920X': '3.5',
+ '2950X': '3.5',
+ '2970WX': '3.0',
+ '2990WX': '3.0',
-/***/ 79896:
-/***/ ((module) => {
+ // ZEN+ Desktop APU
+ 'Pro 300GE': '3.4',
+ 'Pro 3125GE': '3.4',
+ '3150G': '3.5',
+ 'Pro 3150G': '3.5',
+ '3150GE': '3.3',
+ 'Pro 3150GE': '3.3',
+ '3200G': '3.6',
+ 'Pro 3200G': '3.6',
+ '3200GE': '3.3',
+ 'Pro 3200GE': '3.3',
+ '3350G': '3.6',
+ 'Pro 3350G': '3.6',
+ '3350GE': '3.3',
+ 'Pro 3350GE': '3.3',
+ '3400G': '3.7',
+ 'Pro 3400G': '3.7',
+ '3400GE': '3.3',
+ 'Pro 3400GE': '3.3',
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");
+ // ZEN+ Mobile
+ '3300U': '2.1',
+ 'PRO 3300U': '2.1',
+ '3450U': '2.1',
+ '3500U': '2.1',
+ 'PRO 3500U': '2.1',
+ '3500C': '2.1',
+ '3550H': '2.1',
+ '3580U': '2.1',
+ '3700U': '2.3',
+ 'PRO 3700U': '2.3',
+ '3700C': '2.3',
+ '3750H': '2.3',
+ '3780U': '2.3',
-/***/ }),
+ // ZEN2 Desktop CPUS
+ '3100': '3.6',
+ '3300X': '3.8',
+ '3500': '3.6',
+ '3500X': '3.6',
+ '3600': '3.6',
+ 'Pro 3600': '3.6',
+ '3600X': '3.8',
+ '3600XT': '3.8',
+ 'Pro 3700': '3.6',
+ '3700X': '3.6',
+ '3800X': '3.9',
+ '3800XT': '3.9',
+ '3900': '3.1',
+ 'Pro 3900': '3.1',
+ '3900X': '3.8',
+ '3900XT': '3.8',
+ '3950X': '3.5',
+ '3960X': '3.8',
+ '3970X': '3.7',
+ '3990X': '2.9',
+ '3945WX': '4.0',
+ '3955WX': '3.9',
+ '3975WX': '3.5',
+ '3995WX': '2.7',
-/***/ 58611:
-/***/ ((module) => {
+ // ZEN2 Desktop APUs
+ '4300GE': '3.5',
+ 'Pro 4300GE': '3.5',
+ '4300G': '3.8',
+ 'Pro 4300G': '3.8',
+ '4600GE': '3.3',
+ 'Pro 4650GE': '3.3',
+ '4600G': '3.7',
+ 'Pro 4650G': '3.7',
+ '4700GE': '3.1',
+ 'Pro 4750GE': '3.1',
+ '4700G': '3.6',
+ 'Pro 4750G': '3.6',
+ '4300U': '2.7',
+ '4450U': '2.5',
+ 'Pro 4450U': '2.5',
+ '4500U': '2.3',
+ '4600U': '2.1',
+ 'PRO 4650U': '2.1',
+ '4680U': '2.1',
+ '4600HS': '3.0',
+ '4600H': '3.0',
+ '4700U': '2.0',
+ 'PRO 4750U': '1.7',
+ '4800U': '1.8',
+ '4800HS': '2.9',
+ '4800H': '2.9',
+ '4900HS': '3.0',
+ '4900H': '3.3',
+ '5300U': '2.6',
+ '5500U': '2.1',
+ '5700U': '1.8',
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http");
+ // ZEN2 - EPYC
+ '7232P': '3.1',
+ '7302P': '3.0',
+ '7402P': '2.8',
+ '7502P': '2.5',
+ '7702P': '2.0',
+ '7252': '3.1',
+ '7262': '3.2',
+ '7272': '2.9',
+ '7282': '2.8',
+ '7302': '3.0',
+ '7352': '2.3',
+ '7402': '2.8',
+ '7452': '2.35',
+ '7502': '2.5',
+ '7532': '2.4',
+ '7542': '2.9',
+ '7552': '2.2',
+ '7642': '2.3',
+ '7662': '2.0',
+ '7702': '2.0',
+ '7742': '2.25',
+ '7H12': '2.6',
+ '7F32': '3.7',
+ '7F52': '3.5',
+ '7F72': '3.2',
-/***/ }),
+ // Epyc (Milan)
-/***/ 85675:
-/***/ ((module) => {
+ '7773X': '2.2',
+ '7763': '2.45',
+ '7713': '2.0',
+ '7713P': '2.0',
+ '7663': '2.0',
+ '7643': '2.3',
+ '7573X': '2.8',
+ '75F3': '2.95',
+ '7543': '2.8',
+ '7543P': '2.8',
+ '7513': '2.6',
+ '7473X': '2.8',
+ '7453': '2.75',
+ '74F3': '3.2',
+ '7443': '2.85',
+ '7443P': '2.85',
+ '7413': '2.65',
+ '7373X': '3.05',
+ '73F3': '3.5',
+ '7343': '3.2',
+ '7313': '3.0',
+ '7313P': '3.0',
+ '72F3': '3.7',
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2");
+ // ZEN3
+ '5600X': '3.7',
+ '5800X': '3.8',
+ '5900X': '3.7',
+ '5950X': '3.4',
+ '5945WX': '4.1',
+ '5955WX': '4.0',
+ '5965WX': '3.8',
+ '5975WX': '3.6',
+ '5995WX': '2.7',
-/***/ }),
+ '7960X': '4.2',
+ '7970X': '4.0',
+ '7980X': '3.2',
-/***/ 65692:
-/***/ ((module) => {
+ '7965WX': '4.2',
+ '7975WX': '4.0',
+ '7985WX': '3.2',
+ '7995WX': '2.5',
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https");
+ // ZEN4
+ '9754': '2.25',
+ '9754S': '2.25',
+ '9734': '2.2',
+ '9684X': '2.55',
+ '9384X': '3.1',
+ '9184X': '3.55',
+ '9654P': '2.4',
+ '9654': '2.4',
+ '9634': '2.25',
+ '9554P': '3.1',
+ '9554': '3.1',
+ '9534': '2.45',
+ '9474F': '3.6',
+ '9454P': '2.75',
+ '9454': '2.75',
+ '9374F': '3.85',
+ '9354P': '3.25',
+ '9354': '3.25',
+ '9334': '2.7',
+ '9274F': '4.05',
+ '9254': '2.9',
+ '9224': '2.5',
+ '9174F': '4.1',
+ '9124': '3.0'
+};
-/***/ }),
+const socketTypes = {
+ 1: 'Other',
+ 2: 'Unknown',
+ 3: 'Daughter Board',
+ 4: 'ZIF Socket',
+ 5: 'Replacement/Piggy Back',
+ 6: 'None',
+ 7: 'LIF Socket',
+ 8: 'Slot 1',
+ 9: 'Slot 2',
+ 10: '370 Pin Socket',
+ 11: 'Slot A',
+ 12: 'Slot M',
+ 13: '423',
+ 14: 'A (Socket 462)',
+ 15: '478',
+ 16: '754',
+ 17: '940',
+ 18: '939',
+ 19: 'mPGA604',
+ 20: 'LGA771',
+ 21: 'LGA775',
+ 22: 'S1',
+ 23: 'AM2',
+ 24: 'F (1207)',
+ 25: 'LGA1366',
+ 26: 'G34',
+ 27: 'AM3',
+ 28: 'C32',
+ 29: 'LGA1156',
+ 30: 'LGA1567',
+ 31: 'PGA988A',
+ 32: 'BGA1288',
+ 33: 'rPGA988B',
+ 34: 'BGA1023',
+ 35: 'BGA1224',
+ 36: 'LGA1155',
+ 37: 'LGA1356',
+ 38: 'LGA2011',
+ 39: 'FS1',
+ 40: 'FS2',
+ 41: 'FM1',
+ 42: 'FM2',
+ 43: 'LGA2011-3',
+ 44: 'LGA1356-3',
+ 45: 'LGA1150',
+ 46: 'BGA1168',
+ 47: 'BGA1234',
+ 48: 'BGA1364',
+ 49: 'AM4',
+ 50: 'LGA1151',
+ 51: 'BGA1356',
+ 52: 'BGA1440',
+ 53: 'BGA1515',
+ 54: 'LGA3647-1',
+ 55: 'SP3',
+ 56: 'SP3r2',
+ 57: 'LGA2066',
+ 58: 'BGA1392',
+ 59: 'BGA1510',
+ 60: 'BGA1528',
+ 61: 'LGA4189',
+ 62: 'LGA1200',
+ 63: 'LGA4677',
+ 64: 'LGA1700',
+ 65: 'BGA1744',
+ 66: 'BGA1781',
+ 67: 'BGA1211',
+ 68: 'BGA2422',
+ 69: 'LGA1211',
+ 70: 'LGA2422',
+ 71: 'LGA5773',
+ 72: 'BGA5773',
+};
-/***/ 69278:
-/***/ ((module) => {
+const socketTypesByName = {
+ 'LGA1150': 'i7-5775C i3-4340 i3-4170 G3250 i3-4160T i3-4160 E3-1231 G3258 G3240 i7-4790S i7-4790K i7-4790 i5-4690K i5-4690 i5-4590T i5-4590S i5-4590 i5-4460 i3-4360 i3-4150 G1820 G3420 G3220 i7-4771 i5-4440 i3-4330 i3-4130T i3-4130 E3-1230 i7-4770S i7-4770K i7-4770 i5-4670K i5-4670 i5-4570T i5-4570S i5-4570 i5-4430',
+ 'LGA1151': 'i9-9900KS E-2288G E-2224 G5420 i9-9900T i9-9900 i7-9700T i7-9700F i7-9700E i7-9700 i5-9600 i5-9500T i5-9500F i5-9500 i5-9400T i3-9350K i3-9300 i3-9100T i3-9100F i3-9100 G4930 i9-9900KF i7-9700KF i5-9600KF i5-9400F i5-9400 i3-9350KF i9-9900K i7-9700K i5-9600K G5500 G5400 i7-8700T i7-8086K i5-8600 i5-8500T i5-8500 i5-8400T i3-8300 i3-8100T G4900 i7-8700K i7-8700 i5-8600K i5-8400 i3-8350K i3-8100 E3-1270 G4600 G4560 i7-7700T i7-7700K i7-7700 i5-7600K i5-7600 i5-7500T i5-7500 i5-7400 i3-7350K i3-7300 i3-7100T i3-7100 G3930 G3900 G4400 i7-6700T i7-6700K i7-6700 i5-6600K i5-6600 i5-6500T i5-6500 i5-6400T i5-6400 i3-6300 i3-6100T i3-6100 E3-1270 E3-1270 T4500 T4400',
+ '1155': 'G440 G460 G465 G470 G530T G540T G550T G1610T G1620T G530 G540 G1610 G550 G1620 G555 G1630 i3-2100T i3-2120T i3-3220T i3-3240T i3-3250T i3-2100 i3-2105 i3-2102 i3-3210 i3-3220 i3-2125 i3-2120 i3-3225 i3-2130 i3-3245 i3-3240 i3-3250 i5-3570T i5-2500T i5-2400S i5-2405S i5-2390T i5-3330S i5-2500S i5-3335S i5-2300 i5-3450S i5-3340S i5-3470S i5-3475S i5-3470T i5-2310 i5-3550S i5-2320 i5-3330 i5-3350P i5-3450 i5-2400 i5-3340 i5-3570S i5-2380P i5-2450P i5-3470 i5-2500K i5-3550 i5-2500 i5-3570 i5-3570K i5-2550K i7-3770T i7-2600S i7-3770S i7-2600K i7-2600 i7-3770 i7-3770K i7-2700K G620T G630T G640T G2020T G645T G2100T G2030T G622 G860T G620 G632 G2120T G630 G640 G2010 G840 G2020 G850 G645 G2030 G860 G2120 G870 G2130 G2140 E3-1220L E3-1220L E3-1260L E3-1265L E3-1220 E3-1225 E3-1220 E3-1235 E3-1225 E3-1230 E3-1230 E3-1240 E3-1245 E3-1270 E3-1275 E3-1240 E3-1245 E3-1270 E3-1280 E3-1275 E3-1290 E3-1280 E3-1290'
+};
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net");
+function getSocketTypesByName(str) {
+ let result = '';
+ for (const key in socketTypesByName) {
+ const names = socketTypesByName[key].split(' ');
+ names.forEach(element => {
+ if (str.indexOf(element) >= 0) {
+ result = key;
+ }
+ });
+ }
+ return result;
+}
-/***/ }),
+function cpuManufacturer(str) {
+ let result = str;
+ str = str.toLowerCase();
-/***/ 34589:
-/***/ ((module) => {
+ if (str.indexOf('intel') >= 0) { result = 'Intel'; }
+ if (str.indexOf('amd') >= 0) { result = 'AMD'; }
+ if (str.indexOf('qemu') >= 0) { result = 'QEMU'; }
+ if (str.indexOf('hygon') >= 0) { result = 'Hygon'; }
+ if (str.indexOf('centaur') >= 0) { result = 'WinChip/Via'; }
+ if (str.indexOf('vmware') >= 0) { result = 'VMware'; }
+ if (str.indexOf('Xen') >= 0) { result = 'Xen Hypervisor'; }
+ if (str.indexOf('tcg') >= 0) { result = 'QEMU'; }
+ if (str.indexOf('apple') >= 0) { result = 'Apple'; }
+ if (str.indexOf('sifive') >= 0) { result = 'SiFive'; }
+ if (str.indexOf('thead') >= 0) { result = 'T-Head'; }
+ if (str.indexOf('andestech') >= 0) { result = 'Andes Technology'; }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:assert");
+ return result;
+}
-/***/ }),
+function cpuBrandManufacturer(res) {
+ res.brand = res.brand.replace(/\(R\)+/g, '®').replace(/\s+/g, ' ').trim();
+ res.brand = res.brand.replace(/\(TM\)+/g, '™').replace(/\s+/g, ' ').trim();
+ res.brand = res.brand.replace(/\(C\)+/g, '©').replace(/\s+/g, ' ').trim();
+ res.brand = res.brand.replace(/CPU+/g, '').replace(/\s+/g, ' ').trim();
+ res.manufacturer = cpuManufacturer(res.brand);
-/***/ 16698:
-/***/ ((module) => {
+ let parts = res.brand.split(' ');
+ parts.shift();
+ res.brand = parts.join(' ');
+ return res;
+}
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:async_hooks");
+function getAMDSpeed(brand) {
+ let result = '0';
+ for (let key in AMDBaseFrequencies) {
+ if ({}.hasOwnProperty.call(AMDBaseFrequencies, key)) {
+ let parts = key.split('|');
+ let found = 0;
+ parts.forEach(item => {
+ if (brand.indexOf(item) > -1) {
+ found++;
+ }
+ });
+ if (found === parts.length) {
+ result = AMDBaseFrequencies[key];
+ }
+ }
+ }
+ return parseFloat(result);
+}
-/***/ }),
+// --------------------------
+// CPU - brand, speed
-/***/ 4573:
-/***/ ((module) => {
+function getCpu() {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer");
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ const UNKNOWN = 'unknown';
+ let result = {
+ manufacturer: UNKNOWN,
+ brand: UNKNOWN,
+ vendor: '',
+ family: '',
+ model: '',
+ stepping: '',
+ revision: '',
+ voltage: '',
+ speed: 0,
+ speedMin: 0,
+ speedMax: 0,
+ governor: '',
+ cores: util.cores(),
+ physicalCores: util.cores(),
+ performanceCores: util.cores(),
+ efficiencyCores: 0,
+ processors: 1,
+ socket: '',
+ flags: '',
+ virtualization: false,
+ cache: {}
+ };
+ cpuFlags().then(flags => {
+ result.flags = flags;
+ result.virtualization = flags.indexOf('vmx') > -1 || flags.indexOf('svm') > -1;
+ if (_darwin) {
+ exec('sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min hw.packages hw.physicalcpu_max hw.ncpu hw.tbfrequency hw.cpufamily hw.cpusubfamily', function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ const modelline = util.getValue(lines, 'machdep.cpu.brand_string');
+ const modellineParts = modelline.split('@');
+ result.brand = modellineParts[0].trim();
+ const speed = modellineParts[1] ? modellineParts[1].trim() : '0';
+ result.speed = parseFloat(speed.replace(/GHz+/g, ''));
+ let tbFrequency = util.getValue(lines, 'hw.tbfrequency') / 1000000000.0;
+ tbFrequency = tbFrequency < 0.1 ? tbFrequency * 100 : tbFrequency;
+ result.speed = result.speed === 0 ? tbFrequency : result.speed;
-/***/ }),
+ _cpu_speed = result.speed;
+ result = cpuBrandManufacturer(result);
+ result.speedMin = util.getValue(lines, 'hw.cpufrequency_min') ? (util.getValue(lines, 'hw.cpufrequency_min') / 1000000000.0) : result.speed;
+ result.speedMax = util.getValue(lines, 'hw.cpufrequency_max') ? (util.getValue(lines, 'hw.cpufrequency_max') / 1000000000.0) : result.speed;
+ result.vendor = util.getValue(lines, 'machdep.cpu.vendor') || 'Apple';
+ result.family = util.getValue(lines, 'machdep.cpu.family') || util.getValue(lines, 'hw.cpufamily');
+ result.model = util.getValue(lines, 'machdep.cpu.model');
+ result.stepping = util.getValue(lines, 'machdep.cpu.stepping') || util.getValue(lines, 'hw.cpusubfamily');
+ result.virtualization = true;
+ const countProcessors = util.getValue(lines, 'hw.packages');
+ const countCores = util.getValue(lines, 'hw.physicalcpu_max');
+ const countThreads = util.getValue(lines, 'hw.ncpu');
+ if (os.arch() === 'arm64') {
+ result.socket = 'SOC';
+ try {
+ const clusters = execSync('ioreg -c IOPlatformDevice -d 3 -r | grep cluster-type').toString().split('\n');
+ const efficiencyCores = clusters.filter(line => line.indexOf('"E"') >= 0).length;
+ const performanceCores = clusters.filter(line => line.indexOf('"P"') >= 0).length;
+ result.efficiencyCores = efficiencyCores;
+ result.performanceCores = performanceCores;
+ } catch (e) {
+ util.noop();
+ }
+ }
+ if (countProcessors) {
+ result.processors = parseInt(countProcessors) || 1;
+ }
+ if (countCores && countThreads) {
+ result.cores = parseInt(countThreads) || util.cores();
+ result.physicalCores = parseInt(countCores) || util.cores();
+ }
+ cpuCache().then((res) => {
+ result.cache = res;
+ resolve(result);
+ });
+ });
+ }
+ if (_linux) {
+ let modelline = '';
+ let lines = [];
+ if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; }
+ exec('export LC_ALL=C; lscpu; echo -n "Governor: "; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null; echo; unset LC_ALL', function (error, stdout) {
+ if (!error) {
+ lines = stdout.toString().split('\n');
+ }
+ modelline = util.getValue(lines, 'model name') || modelline;
+ modelline = util.getValue(lines, 'bios model name') || modelline;
+ modelline = util.cleanString(modelline);
+ const modellineParts = modelline.split('@');
+ result.brand = modellineParts[0].trim();
+ result.speed = modellineParts[1] ? parseFloat(modellineParts[1].trim()) : 0;
+ if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
+ result.speed = getAMDSpeed(result.brand);
+ }
+ if (result.speed === 0) {
+ const current = getCpuCurrentSpeedSync();
+ if (current.avg !== 0) { result.speed = current.avg; }
+ }
+ _cpu_speed = result.speed;
+ result.speedMin = Math.round(parseFloat(util.getValue(lines, 'cpu min mhz').replace(/,/g, '.')) / 10.0) / 100;
+ result.speedMax = Math.round(parseFloat(util.getValue(lines, 'cpu max mhz').replace(/,/g, '.')) / 10.0) / 100;
-/***/ 37540:
-/***/ ((module) => {
+ result = cpuBrandManufacturer(result);
+ result.vendor = cpuManufacturer(util.getValue(lines, 'vendor id'));
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:console");
+ result.family = util.getValue(lines, 'cpu family');
+ result.model = util.getValue(lines, 'model:');
+ result.stepping = util.getValue(lines, 'stepping');
+ result.revision = util.getValue(lines, 'cpu revision');
+ result.cache.l1d = util.getValue(lines, 'l1d cache');
+ if (result.cache.l1d) { result.cache.l1d = parseInt(result.cache.l1d) * (result.cache.l1d.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1d.indexOf('K') !== -1 ? 1024 : 1)); }
+ result.cache.l1i = util.getValue(lines, 'l1i cache');
+ if (result.cache.l1i) { result.cache.l1i = parseInt(result.cache.l1i) * (result.cache.l1i.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1i.indexOf('K') !== -1 ? 1024 : 1)); }
+ result.cache.l2 = util.getValue(lines, 'l2 cache');
+ if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2) * (result.cache.l2.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l2.indexOf('K') !== -1 ? 1024 : 1)); }
+ result.cache.l3 = util.getValue(lines, 'l3 cache');
+ if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3) * (result.cache.l3.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l3.indexOf('K') !== -1 ? 1024 : 1)); }
-/***/ }),
+ const threadsPerCore = util.getValue(lines, 'thread(s) per core') || '1';
+ const processors = util.getValue(lines, 'socket(s)') || '1';
+ const threadsPerCoreInt = parseInt(threadsPerCore, 10); // threads per code (normally only for performance cores)
+ const processorsInt = parseInt(processors, 10) || 1; // number of sockets / processor units in machine (normally 1)
+ const coresPerSocket = parseInt(util.getValue(lines, 'core(s) per socket'), 10); // number of cores (e.g. 16 on i12900)
+ result.physicalCores = coresPerSocket ? coresPerSocket * processorsInt : result.cores / threadsPerCoreInt;
+ result.performanceCores = threadsPerCoreInt > 1 ? result.cores - result.physicalCores : result.cores;
+ result.efficiencyCores = threadsPerCoreInt > 1 ? result.cores - (threadsPerCoreInt * result.performanceCores) : 0;
+ result.processors = processorsInt;
+ result.governor = util.getValue(lines, 'governor') || '';
-/***/ 77598:
-/***/ ((module) => {
+ // Test Raspberry
+ if (result.vendor === 'ARM') {
+ const linesRpi = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
+ const rPIRevision = util.decodePiCpuinfo(linesRpi);
+ if (rPIRevision.model.toLowerCase().indexOf('raspberry') >= 0) {
+ result.family = result.manufacturer;
+ result.manufacturer = rPIRevision.manufacturer;
+ result.brand = rPIRevision.processor;
+ result.revision = rPIRevision.revisionCode;
+ result.socket = 'SOC';
+ }
+ }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto");
+ // Test RISC-V
+ if (util.getValue(lines, 'architecture') === 'riscv64') {
+ const linesRiscV = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
+ const uarch = util.getValue(linesRiscV, 'uarch') || '';
+ if (uarch.indexOf(',') > -1) {
+ const split = uarch.split(',');
+ result.manufacturer = cpuManufacturer(split[0]);
+ result.brand = split[1];
+ }
+ }
-/***/ }),
+ // socket type
+ let lines2 = [];
+ exec('export LC_ALL=C; dmidecode –t 4 2>/dev/null | grep "Upgrade: Socket"; unset LC_ALL', function (error2, stdout2) {
+ lines2 = stdout2.toString().split('\n');
+ if (lines2 && lines2.length) {
+ result.socket = util.getValue(lines2, 'Upgrade').replace('Socket', '').trim() || result.socket;
+ }
+ resolve(result);
+ });
+ });
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ let modelline = '';
+ let lines = [];
+ if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; }
+ exec('export LC_ALL=C; dmidecode -t 4; dmidecode -t 7 unset LC_ALL', function (error, stdout) {
+ let cache = [];
+ if (!error) {
+ const data = stdout.toString().split('# dmidecode');
+ const processor = data.length > 1 ? data[1] : '';
+ cache = data.length > 2 ? data[2].split('Cache Information') : [];
-/***/ 53053:
-/***/ ((module) => {
+ lines = processor.split('\n');
+ }
+ result.brand = modelline.split('@')[0].trim();
+ result.speed = modelline.split('@')[1] ? parseFloat(modelline.split('@')[1].trim()) : 0;
+ if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
+ result.speed = getAMDSpeed(result.brand);
+ }
+ if (result.speed === 0) {
+ const current = getCpuCurrentSpeedSync();
+ if (current.avg !== 0) { result.speed = current.avg; }
+ }
+ _cpu_speed = result.speed;
+ result.speedMin = result.speed;
+ result.speedMax = Math.round(parseFloat(util.getValue(lines, 'max speed').replace(/Mhz/g, '')) / 10.0) / 100;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:diagnostics_channel");
+ result = cpuBrandManufacturer(result);
+ result.vendor = cpuManufacturer(util.getValue(lines, 'manufacturer'));
+ let sig = util.getValue(lines, 'signature');
+ sig = sig.split(',');
+ for (let i = 0; i < sig.length; i++) {
+ sig[i] = sig[i].trim();
+ }
+ result.family = util.getValue(sig, 'Family', ' ', true);
+ result.model = util.getValue(sig, 'Model', ' ', true);
+ result.stepping = util.getValue(sig, 'Stepping', ' ', true);
+ result.revision = '';
+ const voltage = parseFloat(util.getValue(lines, 'voltage'));
+ result.voltage = isNaN(voltage) ? '' : voltage.toFixed(2);
+ for (let i = 0; i < cache.length; i++) {
+ lines = cache[i].split('\n');
+ let cacheType = util.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-');
+ cacheType = cacheType.length ? cacheType[0] : '';
+ const sizeParts = util.getValue(lines, 'Installed Size').split(' ');
+ let size = parseInt(sizeParts[0], 10);
+ const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb';
+ size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1)));
+ if (cacheType) {
+ if (cacheType === 'l1') {
+ result.cache[cacheType + 'd'] = size / 2;
+ result.cache[cacheType + 'i'] = size / 2;
+ } else {
+ result.cache[cacheType] = size;
+ }
+ }
+ }
+ // socket type
+ result.socket = util.getValue(lines, 'Upgrade').replace('Socket', '').trim();
+ // # threads / # cores
+ const threadCount = util.getValue(lines, 'thread count').trim();
+ const coreCount = util.getValue(lines, 'core count').trim();
+ if (coreCount && threadCount) {
+ result.cores = parseInt(threadCount, 10);
+ result.physicalCores = parseInt(coreCount, 10);
+ }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ resolve(result);
+ }
+ if (_windows) {
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance Win32_processor | select Name, Revision, L2CacheSize, L3CacheSize, Manufacturer, MaxClockSpeed, Description, UpgradeMethod, Caption, NumberOfLogicalProcessors, NumberOfCores | fl'));
+ workload.push(util.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl'));
+ workload.push(util.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent'));
-/***/ }),
+ Promise.all(
+ workload
+ ).then((data) => {
+ let lines = data[0].split('\r\n');
+ let name = util.getValue(lines, 'name', ':') || '';
+ if (name.indexOf('@') >= 0) {
+ result.brand = name.split('@')[0].trim();
+ result.speed = name.split('@')[1] ? parseFloat(name.split('@')[1].trim()) : 0;
+ _cpu_speed = result.speed;
+ } else {
+ result.brand = name.trim();
+ result.speed = 0;
+ }
+ result = cpuBrandManufacturer(result);
+ result.revision = util.getValue(lines, 'revision', ':');
+ result.vendor = util.getValue(lines, 'manufacturer', ':');
+ result.speedMax = Math.round(parseFloat(util.getValue(lines, 'maxclockspeed', ':').replace(/,/g, '.')) / 10.0) / 100;
+ if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
+ result.speed = getAMDSpeed(result.brand);
+ }
+ if (result.speed === 0) {
+ result.speed = result.speedMax;
+ }
+ result.speedMin = result.speed;
-/***/ 78474:
-/***/ ((module) => {
+ let description = util.getValue(lines, 'description', ':').split(' ');
+ for (let i = 0; i < description.length; i++) {
+ if (description[i].toLowerCase().startsWith('family') && (i + 1) < description.length && description[i + 1]) {
+ result.family = description[i + 1];
+ }
+ if (description[i].toLowerCase().startsWith('model') && (i + 1) < description.length && description[i + 1]) {
+ result.model = description[i + 1];
+ }
+ if (description[i].toLowerCase().startsWith('stepping') && (i + 1) < description.length && description[i + 1]) {
+ result.stepping = description[i + 1];
+ }
+ }
+ // socket type
+ const socketId = util.getValue(lines, 'UpgradeMethod', ':');
+ if (socketTypes[socketId]) {
+ result.socket = socketTypes[socketId];
+ }
+ const socketByName = getSocketTypesByName(name);
+ if (socketByName) {
+ result.socket = socketByName;
+ }
+ // # threads / # cores
+ const countProcessors = util.countLines(lines, 'Caption');
+ const countThreads = util.getValue(lines, 'NumberOfLogicalProcessors', ':');
+ const countCores = util.getValue(lines, 'NumberOfCores', ':');
+ if (countProcessors) {
+ result.processors = parseInt(countProcessors) || 1;
+ }
+ if (countCores && countThreads) {
+ result.cores = parseInt(countThreads) || util.cores();
+ result.physicalCores = parseInt(countCores) || util.cores();
+ }
+ if (countProcessors > 1) {
+ result.cores = result.cores * countProcessors;
+ result.physicalCores = result.physicalCores * countProcessors;
+ }
+ result.cache = parseWinCache(data[0], data[1]);
+ const hyperv = data[2] ? data[2].toString().toLowerCase() : '';
+ result.virtualization = hyperv.indexOf('true') !== -1;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events");
+ resolve(result);
+ });
+ } catch (e) {
+ resolve(result);
+ }
+ }
+ });
+ });
+ });
+}
-/***/ }),
+// --------------------------
+// CPU - Processor Data
-/***/ 37067:
-/***/ ((module) => {
+function cpu(callback) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http");
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ getCpu().then(result => {
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ });
+}
-/***/ }),
+exports.cpu = cpu;
-/***/ 32467:
-/***/ ((module) => {
+// --------------------------
+// CPU - current speed - in GHz
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http2");
+function getCpuCurrentSpeedSync() {
-/***/ }),
+ let cpus = os.cpus();
+ let minFreq = 999999999;
+ let maxFreq = 0;
+ let avgFreq = 0;
+ let cores = [];
+ let speeds = [];
-/***/ 44708:
-/***/ ((module) => {
+ if (cpus && cpus.length && cpus[0].speed) {
+ for (let i in cpus) {
+ speeds.push(cpus[i].speed > 100 ? (cpus[i].speed + 1) / 1000 : cpus[i].speed / 10);
+ }
+ } else if (_linux) {
+ try {
+ const speedStrings = execSync('cat /proc/cpuinfo | grep "cpu MHz" | cut -d " " -f 3', util.execOptsLinux).toString().split('\n').filter((line) => line.length > 0);
+ for (let i in speedStrings) {
+ speeds.push(Math.floor(parseInt(speedStrings[i], 10) / 10) / 100);
+ }
+ } catch {
+ util.noop();
+ }
+ }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:https");
+ if (speeds && speeds.length) {
+ for (let i in speeds) {
+ avgFreq = avgFreq + speeds[i];
+ if (speeds[i] > maxFreq) { maxFreq = speeds[i]; }
+ if (speeds[i] < minFreq) { minFreq = speeds[i]; }
+ cores.push(parseFloat(speeds[i].toFixed(2)));
+ }
+ avgFreq = avgFreq / speeds.length;
+ return {
+ min: parseFloat(minFreq.toFixed(2)),
+ max: parseFloat(maxFreq.toFixed(2)),
+ avg: parseFloat((avgFreq).toFixed(2)),
+ cores: cores
+ };
+ } else {
+ return {
+ min: 0,
+ max: 0,
+ avg: 0,
+ cores: cores
+ };
+ }
+}
-/***/ }),
+function cpuCurrentSpeed(callback) {
-/***/ 77030:
-/***/ ((module) => {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = getCpuCurrentSpeedSync();
+ if (result.avg === 0 && _cpu_speed !== 0) {
+ const currCpuSpeed = parseFloat(_cpu_speed);
+ result = {
+ min: currCpuSpeed,
+ max: currCpuSpeed,
+ avg: currCpuSpeed,
+ cores: []
+ };
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+}
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:net");
+exports.cpuCurrentSpeed = cpuCurrentSpeed;
-/***/ }),
+// --------------------------
+// CPU - temperature
+// if sensors are installed
-/***/ 48161:
-/***/ ((module) => {
+function cpuTemperature(callback) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:os");
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ main: null,
+ cores: [],
+ max: null,
+ socket: [],
+ chipset: null
+ };
+ if (_linux) {
+ // CPU Chipset, Socket
+ try {
+ const cmd = 'cat /sys/class/thermal/thermal_zone*/type 2>/dev/null; echo "-----"; cat /sys/class/thermal/thermal_zone*/temp 2>/dev/null;';
+ const parts = execSync(cmd, util.execOptsLinux).toString().split('-----\n');
+ if (parts.length === 2) {
+ const lines = parts[0].split('\n');
+ const lines2 = parts[1].split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].trim();
+ if (line.startsWith('acpi') && lines2[i]) {
+ result.socket.push(Math.round(parseInt(lines2[i], 10) / 100) / 10);
+ }
+ if (line.startsWith('pch') && lines2[i]) {
+ result.chipset = Math.round(parseInt(lines2[i], 10) / 100) / 10;
+ }
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
-/***/ }),
+ const cmd = 'for mon in /sys/class/hwmon/hwmon*; do for label in "$mon"/temp*_label; do if [ -f $label ]; then value=${label%_*}_input; echo $(cat "$label")___$(cat "$value"); fi; done; done;';
+ try {
+ exec(cmd, function (error, stdout) {
+ stdout = stdout.toString();
+ const tdiePos = stdout.toLowerCase().indexOf('tdie');
+ if (tdiePos !== -1) {
+ stdout = stdout.substring(tdiePos);
+ }
+ let lines = stdout.split('\n');
+ let tctl = 0;
+ lines.forEach(line => {
+ const parts = line.split('___');
+ const label = parts[0];
+ const value = parts.length > 1 && parts[1] ? parts[1] : '0';
+ if (value && label && label.toLowerCase() === 'tctl') {
+ tctl = result.main = Math.round(parseInt(value, 10) / 100) / 10;
+ }
+ if (value && (label === undefined || (label && label.toLowerCase().startsWith('core')))) {
+ result.cores.push(Math.round(parseInt(value, 10) / 100) / 10);
+ } else if (value && label && result.main === null && (label.toLowerCase().indexOf('package') >= 0 || label.toLowerCase().indexOf('physical') >= 0 || label.toLowerCase() === 'tccd1')) {
+ result.main = Math.round(parseInt(value, 10) / 100) / 10;
+ }
+ });
+ if (tctl && result.main === null) {
+ result.main = tctl;
+ }
-/***/ 643:
-/***/ ((module) => {
+ if (result.cores.length > 0) {
+ if (result.main === null) {
+ result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length);
+ }
+ let maxtmp = Math.max.apply(Math, result.cores);
+ result.max = (maxtmp > result.main) ? maxtmp : result.main;
+ }
+ if (result.main !== null) {
+ if (result.max === null) {
+ result.max = result.main;
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ return;
+ }
+ exec('sensors', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ let tdieTemp = null;
+ let newSectionStarts = true;
+ let section = '';
+ lines.forEach(function (line) {
+ // determine section
+ if (line.trim() === '') {
+ newSectionStarts = true;
+ } else if (newSectionStarts) {
+ if (line.trim().toLowerCase().startsWith('acpi')) { section = 'acpi'; }
+ if (line.trim().toLowerCase().startsWith('pch')) { section = 'pch'; }
+ if (line.trim().toLowerCase().startsWith('core')) { section = 'core'; }
+ newSectionStarts = false;
+ }
+ let regex = /[+-]([^°]*)/g;
+ let temps = line.match(regex);
+ let firstPart = line.split(':')[0].toUpperCase();
+ if (section === 'acpi') {
+ // socket temp
+ if (firstPart.indexOf('TEMP') !== -1) {
+ result.socket.push(parseFloat(temps));
+ }
+ } else if (section === 'pch') {
+ // chipset temp
+ if (firstPart.indexOf('TEMP') !== -1 && !result.chipset) {
+ result.chipset = parseFloat(temps);
+ }
+ }
+ // cpu temp
+ if (firstPart.indexOf('PHYSICAL') !== -1 || firstPart.indexOf('PACKAGE') !== -1) {
+ result.main = parseFloat(temps);
+ }
+ if (firstPart.indexOf('CORE ') !== -1) {
+ result.cores.push(parseFloat(temps));
+ }
+ if (firstPart.indexOf('TDIE') !== -1 && tdieTemp === null) {
+ tdieTemp = parseFloat(temps);
+ }
+ });
+ if (result.cores.length > 0) {
+ result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length);
+ let maxtmp = Math.max.apply(Math, result.cores);
+ result.max = (maxtmp > result.main) ? maxtmp : result.main;
+ } else {
+ if (result.main === null && tdieTemp !== null) {
+ result.main = tdieTemp;
+ result.max = tdieTemp;
+ }
+ }
+ if (result.main !== null || result.max !== null) {
+ if (callback) { callback(result); }
+ resolve(result);
+ return;
+ }
+ }
+ fs.stat('/sys/class/thermal/thermal_zone0/temp', function (err) {
+ if (err === null) {
+ fs.readFile('/sys/class/thermal/thermal_zone0/temp', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 0) {
+ result.main = parseFloat(lines[0]) / 1000.0;
+ result.max = result.main;
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ exec('/opt/vc/bin/vcgencmd measure_temp', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 0 && lines[0].indexOf('=')) {
+ result.main = parseFloat(lines[0].split('=')[1]);
+ result.max = result.main;
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ });
+ });
+ });
+ } catch (er) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ exec('sysctl dev.cpu | grep temp', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ let sum = 0;
+ lines.forEach(function (line) {
+ const parts = line.split(':');
+ if (parts.length > 1) {
+ const temp = parseFloat(parts[1].replace(',', '.'));
+ if (temp > result.max) { result.max = temp; }
+ sum = sum + temp;
+ result.cores.push(temp);
+ }
+ });
+ if (result.cores.length) {
+ result.main = Math.round(sum / result.cores.length * 100) / 100;
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ let osxTemp = null;
+ try {
+ osxTemp = __nccwpck_require__(73700);
+ } catch (er) {
+ osxTemp = null;
+ }
+ if (osxTemp) {
+ result = osxTemp.cpuTemperature();
+ // round to 2 digits
+ if (result.main) {
+ result.main = Math.round(result.main * 100) / 100;
+ }
+ if (result.max) {
+ result.max = Math.round(result.max * 100) / 100;
+ }
+ if (result.cores && result.cores.length) {
+ for (let i = 0; i < result.cores.length; i++) {
+ result.cores[i] = Math.round(result.cores[i] * 100) / 100;
+ }
+ }
+ }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:perf_hooks");
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_windows) {
+ try {
+ util.powerShell('Get-CimInstance MSAcpi_ThermalZoneTemperature -Namespace "root/wmi" | Select CurrentTemperature').then((stdout, error) => {
+ if (!error) {
+ let sum = 0;
+ let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
+ lines.forEach(function (line) {
+ let value = (parseInt(line, 10) - 2732) / 10;
+ if (!isNaN(value)) {
+ sum = sum + value;
+ if (value > result.max) { result.max = value; }
+ result.cores.push(value);
+ }
+ });
+ if (result.cores.length) {
+ result.main = sum / result.cores.length;
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ });
+ });
+}
-/***/ }),
+exports.cpuTemperature = cpuTemperature;
-/***/ 1708:
-/***/ ((module) => {
+// --------------------------
+// CPU Flags
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:process");
+function cpuFlags(callback) {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = '';
+ if (_windows) {
+ try {
+ exec('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', util.execOptsWin, function (error, stdout) {
+ if (!error) {
+ let flag_hex = stdout.split('0x').pop().trim();
+ let flag_bin_unpadded = parseInt(flag_hex, 16).toString(2);
+ let flag_bin = '0'.repeat(32 - flag_bin_unpadded.length) + flag_bin_unpadded;
+ // empty flags are the reserved fields in the CPUID feature bit list
+ // as found on wikipedia:
+ // https://en.wikipedia.org/wiki/CPUID
+ let all_flags = [
+ 'fpu', 'vme', 'de', 'pse', 'tsc', 'msr', 'pae', 'mce', 'cx8', 'apic',
+ '', 'sep', 'mtrr', 'pge', 'mca', 'cmov', 'pat', 'pse-36', 'psn', 'clfsh',
+ '', 'ds', 'acpi', 'mmx', 'fxsr', 'sse', 'sse2', 'ss', 'htt', 'tm', 'ia64', 'pbe'
+ ];
+ for (let f = 0; f < all_flags.length; f++) {
+ if (flag_bin[f] === '1' && all_flags[f] !== '') {
+ result += ' ' + all_flags[f];
+ }
+ }
+ result = result.trim().toLowerCase();
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_linux) {
+ try {
-/***/ 41792:
-/***/ ((module) => {
+ exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ if (line.split(':')[0].toUpperCase().indexOf('FLAGS') !== -1) {
+ result = line.split(':')[1].trim().toLowerCase();
+ }
+ });
+ }
+ if (!result) {
+ fs.readFile('/proc/cpuinfo', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result = util.getValue(lines, 'features', ':', true).toLowerCase();
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ exec('export LC_ALL=C; dmidecode -t 4 2>/dev/null; unset LC_ALL', function (error, stdout) {
+ let flags = [];
+ if (!error) {
+ let parts = stdout.toString().split('\tFlags:');
+ const lines = parts.length > 1 ? parts[1].split('\tVersion:')[0].split('\n') : [];
+ lines.forEach(function (line) {
+ let flag = (line.indexOf('(') ? line.split('(')[0].toLowerCase() : '').trim().replace(/\t/g, '');
+ if (flag) {
+ flags.push(flag);
+ }
+ });
+ }
+ result = flags.join(' ').trim().toLowerCase();
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ exec('sysctl machdep.cpu.features', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 0 && lines[0].indexOf('machdep.cpu.features:') !== -1) {
+ result = lines[0].split(':')[1].trim().toLowerCase();
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+}
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:querystring");
+exports.cpuFlags = cpuFlags;
-/***/ }),
+// --------------------------
+// CPU Cache
-/***/ 57075:
-/***/ ((module) => {
+function cpuCache(callback) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream");
+ return new Promise((resolve) => {
+ process.nextTick(() => {
-/***/ }),
+ let result = {
+ l1d: null,
+ l1i: null,
+ l2: null,
+ l3: null,
+ };
+ if (_linux) {
+ try {
+ exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ let parts = line.split(':');
+ if (parts[0].toUpperCase().indexOf('L1D CACHE') !== -1) {
+ result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
+ }
+ if (parts[0].toUpperCase().indexOf('L1I CACHE') !== -1) {
+ result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
+ }
+ if (parts[0].toUpperCase().indexOf('L2 CACHE') !== -1) {
+ result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
+ }
+ if (parts[0].toUpperCase().indexOf('L3 CACHE') !== -1) {
+ result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
+ }
+ });
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ exec('export LC_ALL=C; dmidecode -t 7 2>/dev/null; unset LC_ALL', function (error, stdout) {
+ let cache = [];
+ if (!error) {
+ const data = stdout.toString();
+ cache = data.split('Cache Information');
+ cache.shift();
+ }
+ for (let i = 0; i < cache.length; i++) {
+ const lines = cache[i].split('\n');
+ let cacheType = util.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-');
+ cacheType = cacheType.length ? cacheType[0] : '';
+ const sizeParts = util.getValue(lines, 'Installed Size').split(' ');
+ let size = parseInt(sizeParts[0], 10);
+ const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb';
+ size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1)));
+ if (cacheType) {
+ if (cacheType === 'l1') {
+ result.cache[cacheType + 'd'] = size / 2;
+ result.cache[cacheType + 'i'] = size / 2;
+ } else {
+ result.cache[cacheType] = size;
+ }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ exec('sysctl hw.l1icachesize hw.l1dcachesize hw.l2cachesize hw.l3cachesize', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ let parts = line.split(':');
+ if (parts[0].toLowerCase().indexOf('hw.l1icachesize') !== -1) {
+ result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
+ }
+ if (parts[0].toLowerCase().indexOf('hw.l1dcachesize') !== -1) {
+ result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
+ }
+ if (parts[0].toLowerCase().indexOf('hw.l2cachesize') !== -1) {
+ result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
+ }
+ if (parts[0].toLowerCase().indexOf('hw.l3cachesize') !== -1) {
+ result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
+ }
+ });
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_windows) {
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance Win32_processor | select L2CacheSize, L3CacheSize | fl'));
+ workload.push(util.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl'));
-/***/ 41692:
-/***/ ((module) => {
+ Promise.all(
+ workload
+ ).then((data) => {
+ result = parseWinCache(data[0], data[1]);
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:tls");
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ });
+ });
+}
-/***/ }),
+function parseWinCache(linesProc, linesCache) {
+ let result = {
+ l1d: null,
+ l1i: null,
+ l2: null,
+ l3: null,
+ };
-/***/ 73136:
-/***/ ((module) => {
+ // Win32_processor
+ let lines = linesProc.split('\r\n');
+ result.l1d = 0;
+ result.l1i = 0;
+ result.l2 = util.getValue(lines, 'l2cachesize', ':');
+ result.l3 = util.getValue(lines, 'l3cachesize', ':');
+ if (result.l2) { result.l2 = parseInt(result.l2, 10) * 1024; } else { result.l2 = 0; }
+ if (result.l3) { result.l3 = parseInt(result.l3, 10) * 1024; } else { result.l3 = 0; }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:url");
+ // Win32_CacheMemory
+ const parts = linesCache.split(/\n\s*\n/);
+ let l1i = 0;
+ let l1d = 0;
+ let l2 = 0;
+ parts.forEach(function (part) {
+ const lines = part.split('\r\n');
+ const cacheType = util.getValue(lines, 'CacheType');
+ const level = util.getValue(lines, 'Level');
+ const installedSize = util.getValue(lines, 'InstalledSize');
+ // L1 Instructions
+ if (level === '3' && cacheType === '3') {
+ result.l1i = result.l1i + parseInt(installedSize, 10) * 1024;
+ }
+ // L1 Data
+ if (level === '3' && cacheType === '4') {
+ result.l1d = result.l1d + parseInt(installedSize, 10) * 1024;
+ }
+ // L1 all
+ if (level === '3' && cacheType === '5') {
+ l1i = parseInt(installedSize, 10) / 2;
+ l1d = parseInt(installedSize, 10) / 2;
+ }
+ // L2
+ if (level === '4' && cacheType === '5') {
+ l2 = l2 + parseInt(installedSize, 10) * 1024;
+ }
+ });
+ if (!result.l1i && !result.l1d) {
+ result.l1i = l1i;
+ result.l1d = l1d;
+ }
+ if (l2) {
+ result.l2 = l2;
+ }
+ return result;
+}
-/***/ }),
+exports.cpuCache = cpuCache;
-/***/ 57975:
-/***/ ((module) => {
+// --------------------------
+// CPU - current load - in %
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util");
+function getLoad() {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let loads = os.loadavg().map(function (x) { return x / util.cores(); });
+ let avgLoad = parseFloat((Math.max.apply(Math, loads)).toFixed(2));
+ let result = {};
-/***/ 73429:
-/***/ ((module) => {
+ let now = Date.now() - _current_cpu.ms;
+ if (now >= 200) {
+ _current_cpu.ms = Date.now();
+ const cpus = os.cpus().map(function (cpu) {
+ cpu.times.steal = 0;
+ cpu.times.guest = 0;
+ return cpu;
+ });
+ let totalUser = 0;
+ let totalSystem = 0;
+ let totalNice = 0;
+ let totalIrq = 0;
+ let totalIdle = 0;
+ let totalSteal = 0;
+ let totalGuest = 0;
+ let cores = [];
+ _corecount = (cpus && cpus.length) ? cpus.length : 0;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util/types");
+ // linux: try to get other cpu stats
+ if (_linux) {
+ try {
+ const lines = execSync('cat /proc/stat 2>/dev/null | grep cpu', util.execOptsLinux).toString().split('\n');
+ if (lines.length > 1) {
+ lines.shift();
+ if (lines.length === cpus.length) {
+ for (let i = 0; i < lines.length; i++) {
+ let parts = lines[i].split(' ');
+ if (parts.length >= 10) {
+ const steal = parseFloat(parts[8]) || 0;
+ const guest = parseFloat(parts[9]) || 0;
+ cpus[i].times.steal = steal;
+ cpus[i].times.guest = guest;
+ }
+ }
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
+ }
-/***/ }),
+ for (let i = 0; i < _corecount; i++) {
+ const cpu = cpus[i].times;
+ totalUser += cpu.user;
+ totalSystem += cpu.sys;
+ totalNice += cpu.nice;
+ totalIdle += cpu.idle;
+ totalIrq += cpu.irq;
+ totalSteal += cpu.steal || 0;
+ totalGuest += cpu.guest || 0;
+ let tmpTick = (_cpus && _cpus[i] && _cpus[i].totalTick ? _cpus[i].totalTick : 0);
+ let tmpLoad = (_cpus && _cpus[i] && _cpus[i].totalLoad ? _cpus[i].totalLoad : 0);
+ let tmpUser = (_cpus && _cpus[i] && _cpus[i].user ? _cpus[i].user : 0);
+ let tmpSystem = (_cpus && _cpus[i] && _cpus[i].sys ? _cpus[i].sys : 0);
+ let tmpNice = (_cpus && _cpus[i] && _cpus[i].nice ? _cpus[i].nice : 0);
+ let tmpIdle = (_cpus && _cpus[i] && _cpus[i].idle ? _cpus[i].idle : 0);
+ let tmpIrq = (_cpus && _cpus[i] && _cpus[i].irq ? _cpus[i].irq : 0);
+ let tmpSteal = (_cpus && _cpus[i] && _cpus[i].steal ? _cpus[i].steal : 0);
+ let tmpGuest = (_cpus && _cpus[i] && _cpus[i].guest ? _cpus[i].guest : 0);
+ _cpus[i] = cpu;
+ _cpus[i].totalTick = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest + _cpus[i].idle;
+ _cpus[i].totalLoad = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest;
+ _cpus[i].currentTick = _cpus[i].totalTick - tmpTick;
+ _cpus[i].load = (_cpus[i].totalLoad - tmpLoad);
+ _cpus[i].loadUser = (_cpus[i].user - tmpUser);
+ _cpus[i].loadSystem = (_cpus[i].sys - tmpSystem);
+ _cpus[i].loadNice = (_cpus[i].nice - tmpNice);
+ _cpus[i].loadIdle = (_cpus[i].idle - tmpIdle);
+ _cpus[i].loadIrq = (_cpus[i].irq - tmpIrq);
+ _cpus[i].loadSteal = (_cpus[i].steal - tmpSteal);
+ _cpus[i].loadGuest = (_cpus[i].guest - tmpGuest);
+ cores[i] = {};
+ cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
+ cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100;
+ cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100;
+ cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100;
+ cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100;
+ cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100;
+ cores[i].loadSteal = _cpus[i].loadSteal / _cpus[i].currentTick * 100;
+ cores[i].loadGuest = _cpus[i].loadGuest / _cpus[i].currentTick * 100;
+ cores[i].rawLoad = _cpus[i].load;
+ cores[i].rawLoadUser = _cpus[i].loadUser;
+ cores[i].rawLoadSystem = _cpus[i].loadSystem;
+ cores[i].rawLoadNice = _cpus[i].loadNice;
+ cores[i].rawLoadIdle = _cpus[i].loadIdle;
+ cores[i].rawLoadIrq = _cpus[i].loadIrq;
+ cores[i].rawLoadSteal = _cpus[i].loadSteal;
+ cores[i].rawLoadGuest = _cpus[i].loadGuest;
+ }
+ let totalTick = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest + totalIdle;
+ let totalLoad = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest;
+ let currentTick = totalTick - _current_cpu.tick;
+ result = {
+ avgLoad: avgLoad,
+ currentLoad: (totalLoad - _current_cpu.load) / currentTick * 100,
+ currentLoadUser: (totalUser - _current_cpu.user) / currentTick * 100,
+ currentLoadSystem: (totalSystem - _current_cpu.system) / currentTick * 100,
+ currentLoadNice: (totalNice - _current_cpu.nice) / currentTick * 100,
+ currentLoadIdle: (totalIdle - _current_cpu.idle) / currentTick * 100,
+ currentLoadIrq: (totalIrq - _current_cpu.irq) / currentTick * 100,
+ currentLoadSteal: (totalSteal - _current_cpu.steal) / currentTick * 100,
+ currentLoadGuest: (totalGuest - _current_cpu.guest) / currentTick * 100,
+ rawCurrentLoad: (totalLoad - _current_cpu.load),
+ rawCurrentLoadUser: (totalUser - _current_cpu.user),
+ rawCurrentLoadSystem: (totalSystem - _current_cpu.system),
+ rawCurrentLoadNice: (totalNice - _current_cpu.nice),
+ rawCurrentLoadIdle: (totalIdle - _current_cpu.idle),
+ rawCurrentLoadIrq: (totalIrq - _current_cpu.irq),
+ rawCurrentLoadSteal: (totalSteal - _current_cpu.steal),
+ rawCurrentLoadGuest: (totalGuest - _current_cpu.guest),
+ cpus: cores
+ };
+ _current_cpu = {
+ user: totalUser,
+ nice: totalNice,
+ system: totalSystem,
+ idle: totalIdle,
+ irq: totalIrq,
+ steal: totalSteal,
+ guest: totalGuest,
+ tick: totalTick,
+ load: totalLoad,
+ ms: _current_cpu.ms,
+ currentLoad: result.currentLoad,
+ currentLoadUser: result.currentLoadUser,
+ currentLoadSystem: result.currentLoadSystem,
+ currentLoadNice: result.currentLoadNice,
+ currentLoadIdle: result.currentLoadIdle,
+ currentLoadIrq: result.currentLoadIrq,
+ currentLoadSteal: result.currentLoadSteal,
+ currentLoadGuest: result.currentLoadGuest,
+ rawCurrentLoad: result.rawCurrentLoad,
+ rawCurrentLoadUser: result.rawCurrentLoadUser,
+ rawCurrentLoadSystem: result.rawCurrentLoadSystem,
+ rawCurrentLoadNice: result.rawCurrentLoadNice,
+ rawCurrentLoadIdle: result.rawCurrentLoadIdle,
+ rawCurrentLoadIrq: result.rawCurrentLoadIrq,
+ rawCurrentLoadSteal: result.rawCurrentLoadSteal,
+ rawCurrentLoadGuest: result.rawCurrentLoadGuest,
+ };
+ } else {
+ let cores = [];
+ for (let i = 0; i < _corecount; i++) {
+ cores[i] = {};
+ cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
+ cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100;
+ cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100;
+ cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100;
+ cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100;
+ cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100;
+ cores[i].rawLoad = _cpus[i].load;
+ cores[i].rawLoadUser = _cpus[i].loadUser;
+ cores[i].rawLoadSystem = _cpus[i].loadSystem;
+ cores[i].rawLoadNice = _cpus[i].loadNice;
+ cores[i].rawLoadIdle = _cpus[i].loadIdle;
+ cores[i].rawLoadIrq = _cpus[i].loadIrq;
+ cores[i].rawLoadSteal = _cpus[i].loadSteal;
+ cores[i].rawLoadGuest = _cpus[i].loadGuest;
+ }
+ result = {
+ avgLoad: avgLoad,
+ currentLoad: _current_cpu.currentLoad,
+ currentLoadUser: _current_cpu.currentLoadUser,
+ currentLoadSystem: _current_cpu.currentLoadSystem,
+ currentLoadNice: _current_cpu.currentLoadNice,
+ currentLoadIdle: _current_cpu.currentLoadIdle,
+ currentLoadIrq: _current_cpu.currentLoadIrq,
+ currentLoadSteal: _current_cpu.currentLoadSteal,
+ currentLoadGuest: _current_cpu.currentLoadGuest,
+ rawCurrentLoad: _current_cpu.rawCurrentLoad,
+ rawCurrentLoadUser: _current_cpu.rawCurrentLoadUser,
+ rawCurrentLoadSystem: _current_cpu.rawCurrentLoadSystem,
+ rawCurrentLoadNice: _current_cpu.rawCurrentLoadNice,
+ rawCurrentLoadIdle: _current_cpu.rawCurrentLoadIdle,
+ rawCurrentLoadIrq: _current_cpu.rawCurrentLoadIrq,
+ rawCurrentLoadSteal: _current_cpu.rawCurrentLoadSteal,
+ rawCurrentLoadGuest: _current_cpu.rawCurrentLoadGuest,
+ cpus: cores
+ };
+ }
+ resolve(result);
+ });
+ });
+}
-/***/ 75919:
-/***/ ((module) => {
+function currentLoad(callback) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:worker_threads");
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ getLoad().then(result => {
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ });
+}
-/***/ }),
+exports.currentLoad = currentLoad;
-/***/ 38522:
-/***/ ((module) => {
+// --------------------------
+// PS - full load
+// since bootup
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:zlib");
+function getFullLoad() {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
-/***/ 70857:
-/***/ ((module) => {
+ const cpus = os.cpus();
+ let totalUser = 0;
+ let totalSystem = 0;
+ let totalNice = 0;
+ let totalIrq = 0;
+ let totalIdle = 0;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os");
+ let result = 0;
-/***/ }),
+ if (cpus && cpus.length) {
+ for (let i = 0, len = cpus.length; i < len; i++) {
+ const cpu = cpus[i].times;
+ totalUser += cpu.user;
+ totalSystem += cpu.sys;
+ totalNice += cpu.nice;
+ totalIrq += cpu.irq;
+ totalIdle += cpu.idle;
+ }
+ let totalTicks = totalIdle + totalIrq + totalNice + totalSystem + totalUser;
+ result = (totalTicks - totalIdle) / totalTicks * 100.0;
-/***/ 16928:
-/***/ ((module) => {
+ }
+ resolve(result);
+ });
+ });
+}
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");
+function fullLoad(callback) {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ getFullLoad().then(result => {
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ });
+}
-/***/ 82987:
-/***/ ((module) => {
+exports.fullLoad = fullLoad;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks");
/***/ }),
-/***/ 83480:
-/***/ ((module) => {
+/***/ 81820:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring");
-/***/ }),
+// @ts-check
+// ==================================================================================
+// docker.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 13. Docker
+// ----------------------------------------------------------------------------------
-/***/ 2203:
-/***/ ((module) => {
+const util = __nccwpck_require__(77496);
+const DockerSocket = __nccwpck_require__(23945);
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream");
+let _platform = process.platform;
+const _windows = (_platform === 'win32');
-/***/ }),
+let _docker_container_stats = {};
+let _docker_socket;
+let _docker_last_read = 0;
-/***/ 63774:
-/***/ ((module) => {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web");
+// --------------------------
+// get containers (parameter all: get also inactive/exited containers)
-/***/ }),
+function dockerInfo(callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
+ const result = {};
-/***/ 13193:
-/***/ ((module) => {
+ _docker_socket.getInfo((data) => {
+ result.id = data.ID;
+ result.containers = data.Containers;
+ result.containersRunning = data.ContainersRunning;
+ result.containersPaused = data.ContainersPaused;
+ result.containersStopped = data.ContainersStopped;
+ result.images = data.Images;
+ result.driver = data.Driver;
+ result.memoryLimit = data.MemoryLimit;
+ result.swapLimit = data.SwapLimit;
+ result.kernelMemory = data.KernelMemory;
+ result.cpuCfsPeriod = data.CpuCfsPeriod;
+ result.cpuCfsQuota = data.CpuCfsQuota;
+ result.cpuShares = data.CPUShares;
+ result.cpuSet = data.CPUSet;
+ result.ipv4Forwarding = data.IPv4Forwarding;
+ result.bridgeNfIptables = data.BridgeNfIptables;
+ result.bridgeNfIp6tables = data.BridgeNfIp6tables;
+ result.debug = data.Debug;
+ result.nfd = data.NFd;
+ result.oomKillDisable = data.OomKillDisable;
+ result.ngoroutines = data.NGoroutines;
+ result.systemTime = data.SystemTime;
+ result.loggingDriver = data.LoggingDriver;
+ result.cgroupDriver = data.CgroupDriver;
+ result.nEventsListener = data.NEventsListener;
+ result.kernelVersion = data.KernelVersion;
+ result.operatingSystem = data.OperatingSystem;
+ result.osType = data.OSType;
+ result.architecture = data.Architecture;
+ result.ncpu = data.NCPU;
+ result.memTotal = data.MemTotal;
+ result.dockerRootDir = data.DockerRootDir;
+ result.httpProxy = data.HttpProxy;
+ result.httpsProxy = data.HttpsProxy;
+ result.noProxy = data.NoProxy;
+ result.name = data.Name;
+ result.labels = data.Labels;
+ result.experimentalBuild = data.ExperimentalBuild;
+ result.serverVersion = data.ServerVersion;
+ result.clusterStore = data.ClusterStore;
+ result.clusterAdvertise = data.ClusterAdvertise;
+ result.defaultRuntime = data.DefaultRuntime;
+ result.liveRestoreEnabled = data.LiveRestoreEnabled;
+ result.isolation = data.Isolation;
+ result.initBinary = data.InitBinary;
+ result.productLicense = data.ProductLicense;
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ });
+}
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder");
+exports.dockerInfo = dockerInfo;
-/***/ }),
+function dockerImages(all, callback) {
-/***/ 53557:
-/***/ ((module) => {
+ // fallback - if only callback is given
+ if (util.isFunction(all) && !callback) {
+ callback = all;
+ all = false;
+ }
+ if (typeof all === 'string' && all === 'true') {
+ all = true;
+ }
+ if (typeof all !== 'boolean' && all !== undefined) {
+ all = false;
+ }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers");
+ all = all || false;
+ let result = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
+ const workload = [];
-/***/ }),
+ _docker_socket.listImages(all, data => {
+ let dockerImages = {};
+ try {
+ dockerImages = data;
+ if (dockerImages && Object.prototype.toString.call(dockerImages) === '[object Array]' && dockerImages.length > 0) {
-/***/ 64756:
-/***/ ((module) => {
+ dockerImages.forEach(function (element) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls");
+ if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) {
+ element.Name = element.Names[0].replace(/^\/|\/$/g, '');
+ }
+ workload.push(dockerImagesInspect(element.Id.trim(), element));
+ });
+ if (workload.length) {
+ Promise.all(
+ workload
+ ).then((data) => {
+ if (callback) { callback(data); }
+ resolve(data);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } catch (err) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+ });
+}
-/***/ }),
+// --------------------------
+// container inspect (for one container)
-/***/ 52018:
-/***/ ((module) => {
+function dockerImagesInspect(imageID, payload) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ imageID = imageID || '';
+ if (typeof imageID !== 'string') {
+ return resolve();
+ }
+ const imageIDSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(imageID, true)).trim();
+ if (imageIDSanitized) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty");
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
-/***/ }),
+ _docker_socket.inspectImage(imageIDSanitized.trim(), data => {
+ try {
+ resolve({
+ id: payload.Id,
+ container: data.Container,
+ comment: data.Comment,
+ os: data.Os,
+ architecture: data.Architecture,
+ parent: data.Parent,
+ dockerVersion: data.DockerVersion,
+ size: data.Size,
+ sharedSize: payload.SharedSize,
+ virtualSize: data.VirtualSize,
+ author: data.Author,
+ created: data.Created ? Math.round(new Date(data.Created).getTime() / 1000) : 0,
+ containerConfig: data.ContainerConfig ? data.ContainerConfig : {},
+ graphDriver: data.GraphDriver ? data.GraphDriver : {},
+ repoDigests: data.RepoDigests ? data.RepoDigests : {},
+ repoTags: data.RepoTags ? data.RepoTags : {},
+ config: data.Config ? data.Config : {},
+ rootFS: data.RootFS ? data.RootFS : {},
+ });
+ } catch (err) {
+ resolve();
+ }
+ });
+ } else {
+ resolve();
+ }
+ });
+ });
+}
-/***/ 87016:
-/***/ ((module) => {
+exports.dockerImages = dockerImages;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url");
+function dockerContainers(all, callback) {
-/***/ }),
+ function inContainers(containers, id) {
+ let filtered = containers.filter(obj => {
+ /**
+ * @namespace
+ * @property {string} Id
+ */
+ return (obj.Id && (obj.Id === id));
+ });
+ return (filtered.length > 0);
+ }
-/***/ 39023:
-/***/ ((module) => {
+ // fallback - if only callback is given
+ if (util.isFunction(all) && !callback) {
+ callback = all;
+ all = false;
+ }
+ if (typeof all === 'string' && all === 'true') {
+ all = true;
+ }
+ if (typeof all !== 'boolean' && all !== undefined) {
+ all = false;
+ }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util");
+ all = all || false;
+ let result = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
+ const workload = [];
-/***/ }),
+ _docker_socket.listContainers(all, data => {
+ let docker_containers = {};
+ try {
+ docker_containers = data;
+ if (docker_containers && Object.prototype.toString.call(docker_containers) === '[object Array]' && docker_containers.length > 0) {
+ // GC in _docker_container_stats
+ for (let key in _docker_container_stats) {
+ if ({}.hasOwnProperty.call(_docker_container_stats, key)) {
+ if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; }
+ }
+ }
-/***/ 98253:
-/***/ ((module) => {
+ docker_containers.forEach(function (element) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types");
+ if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) {
+ element.Name = element.Names[0].replace(/^\/|\/$/g, '');
+ }
+ workload.push(dockerContainerInspect(element.Id.trim(), element));
+ });
+ if (workload.length) {
+ Promise.all(
+ workload
+ ).then((data) => {
+ if (callback) { callback(data); }
+ resolve(data);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } catch (err) {
+ // GC in _docker_container_stats
+ for (let key in _docker_container_stats) {
+ if ({}.hasOwnProperty.call(_docker_container_stats, key)) {
+ if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+ });
+}
-/***/ }),
+// --------------------------
+// container inspect (for one container)
-/***/ 28167:
-/***/ ((module) => {
+function dockerContainerInspect(containerID, payload) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ containerID = containerID || '';
+ if (typeof containerID !== 'string') {
+ return resolve();
+ }
+ const containerIdSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerID, true)).trim();
+ if (containerIdSanitized) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads");
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
-/***/ }),
+ _docker_socket.getInspect(containerIdSanitized.trim(), data => {
+ try {
+ resolve({
+ id: payload.Id,
+ name: payload.Name,
+ image: payload.Image,
+ imageID: payload.ImageID,
+ command: payload.Command,
+ created: payload.Created,
+ started: data.State && data.State.StartedAt ? Math.round(new Date(data.State.StartedAt).getTime() / 1000) : 0,
+ finished: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? Math.round(new Date(data.State.FinishedAt).getTime() / 1000) : 0,
+ createdAt: data.Created ? data.Created : '',
+ startedAt: data.State && data.State.StartedAt ? data.State.StartedAt : '',
+ finishedAt: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? data.State.FinishedAt : '',
+ state: payload.State,
+ restartCount: data.RestartCount || 0,
+ platform: data.Platform || '',
+ driver: data.Driver || '',
+ ports: payload.Ports,
+ mounts: payload.Mounts,
+ // hostconfig: payload.HostConfig,
+ // network: payload.NetworkSettings
+ });
+ } catch (err) {
+ resolve();
+ }
+ });
+ } else {
+ resolve();
+ }
+ });
+ });
+}
-/***/ 43106:
-/***/ ((module) => {
+exports.dockerContainers = dockerContainers;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib");
+// --------------------------
+// helper functions for calculation of docker stats
-/***/ }),
+function docker_calcCPUPercent(cpu_stats, precpu_stats) {
+ /**
+ * @namespace
+ * @property {object} cpu_usage
+ * @property {number} cpu_usage.total_usage
+ * @property {number} system_cpu_usage
+ * @property {object} cpu_usage
+ * @property {Array} cpu_usage.percpu_usage
+ */
-/***/ 85276:
-/***/ ((__unused_webpack_module, exports) => {
+ if (!_windows) {
+ let cpuPercent = 0.0;
+ // calculate the change for the cpu usage of the container in between readings
+ let cpuDelta = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
+ // calculate the change for the entire system between readings
+ let systemDelta = cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage;
+ if (systemDelta > 0.0 && cpuDelta > 0.0) {
+ // calculate the change for the cpu usage of the container in between readings
+ if (precpu_stats.online_cpus) {
+ cpuPercent = (cpuDelta / systemDelta) * precpu_stats.online_cpus * 100.0;
+ }
+ else {
+ cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0;
+ }
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AbortError = void 0;
-/**
- * This error is thrown when an asynchronous operation has been aborted.
- * Check for this error by testing the `name` that the name property of the
- * error matches `"AbortError"`.
- *
- * @example
- * ```ts
- * const controller = new AbortController();
- * controller.abort();
- * try {
- * doAsyncWork(controller.signal)
- * } catch (e) {
- * if (e.name === 'AbortError') {
- * // handle abort error here.
- * }
- * }
- * ```
- */
-class AbortError extends Error {
- constructor(message) {
- super(message);
- this.name = "AbortError";
+ return cpuPercent;
+ } else {
+ let nanoSecNow = util.nanoSeconds();
+ let cpuPercent = 0.0;
+ if (_docker_last_read > 0) {
+ let possIntervals = (nanoSecNow - _docker_last_read); // / 100 * os.cpus().length;
+ let intervalsUsed = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
+ if (possIntervals > 0) {
+ cpuPercent = 100.0 * intervalsUsed / possIntervals;
+ }
}
+ _docker_last_read = nanoSecNow;
+ return cpuPercent;
+ }
}
-exports.AbortError = AbortError;
-//# sourceMappingURL=AbortError.js.map
-/***/ }),
+function docker_calcNetworkIO(networks) {
+ let rx;
+ let wx;
+ for (let key in networks) {
+ // skip loop if the property is from prototype
+ if (!{}.hasOwnProperty.call(networks, key)) { continue; }
-/***/ 92242:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ /**
+ * @namespace
+ * @property {number} rx_bytes
+ * @property {number} tx_bytes
+ */
+ let obj = networks[key];
+ rx = +obj.rx_bytes;
+ wx = +obj.tx_bytes;
+ }
+ return {
+ rx,
+ wx
+ };
+}
+function docker_calcBlockIO(blkio_stats) {
+ let result = {
+ r: 0,
+ w: 0
+ };
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AbortError = void 0;
-var AbortError_js_1 = __nccwpck_require__(85276);
-Object.defineProperty(exports, "AbortError", ({ enumerable: true, get: function () { return AbortError_js_1.AbortError; } }));
-//# sourceMappingURL=index.js.map
+ /**
+ * @namespace
+ * @property {Array} io_service_bytes_recursive
+ */
+ if (blkio_stats && blkio_stats.io_service_bytes_recursive && Object.prototype.toString.call(blkio_stats.io_service_bytes_recursive) === '[object Array]' && blkio_stats.io_service_bytes_recursive.length > 0) {
+ blkio_stats.io_service_bytes_recursive.forEach(function (element) {
+ /**
+ * @namespace
+ * @property {string} op
+ * @property {number} value
+ */
-/***/ }),
+ if (element.op && element.op.toLowerCase() === 'read' && element.value) {
+ result.r += element.value;
+ }
+ if (element.op && element.op.toLowerCase() === 'write' && element.value) {
+ result.w += element.value;
+ }
+ });
+ }
+ return result;
+}
-/***/ 21746:
-/***/ ((__unused_webpack_module, exports) => {
+function dockerContainerStats(containerIDs, callback) {
+ let containerArray = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureKeyCredential = void 0;
-/**
- * A static-key-based credential that supports updating
- * the underlying key value.
- */
-class AzureKeyCredential {
- /**
- * The value of the key to be used in authentication
- */
- get key() {
- return this._key;
- }
- /**
- * Create an instance of an AzureKeyCredential for use
- * with a service client.
- *
- * @param key - The initial value of the key to use in authentication
- */
- constructor(key) {
- if (!key) {
- throw new Error("key must be a non-empty string");
+ // fallback - if only callback is given
+ if (util.isFunction(containerIDs) && !callback) {
+ callback = containerIDs;
+ containerArray = ['*'];
+ } else {
+ containerIDs = containerIDs || '*';
+ if (typeof containerIDs !== 'string') {
+ if (callback) { callback([]); }
+ return resolve([]);
+ }
+ let containerIDsSanitized = '';
+ try {
+ containerIDsSanitized.__proto__.toLowerCase = util.stringToLower;
+ containerIDsSanitized.__proto__.replace = util.stringReplace;
+ containerIDsSanitized.__proto__.toString = util.stringToString;
+ containerIDsSanitized.__proto__.substr = util.stringSubstr;
+ containerIDsSanitized.__proto__.substring = util.stringSubstring;
+ containerIDsSanitized.__proto__.trim = util.stringTrim;
+ containerIDsSanitized.__proto__.startsWith = util.stringStartWith;
+ } catch (e) {
+ Object.setPrototypeOf(containerIDsSanitized, util.stringObj);
}
- this._key = key;
- }
- /**
- * Change the value of the key.
- *
- * Updates will take effect upon the next request after
- * updating the key value.
- *
- * @param newKey - The new key value to be used
- */
- update(newKey) {
- this._key = newKey;
- }
-}
-exports.AzureKeyCredential = AzureKeyCredential;
-//# sourceMappingURL=azureKeyCredential.js.map
-/***/ }),
+ containerIDsSanitized = containerIDs;
+ containerIDsSanitized = containerIDsSanitized.trim();
+ if (containerIDsSanitized !== '*') {
+ containerIDsSanitized = '';
+ const s = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerIDs, true)).trim();
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ s[i].__proto__.toLowerCase = util.stringToLower;
+ const sl = s[i].toLowerCase();
+ if (sl && sl[0] && !sl[1]) {
+ containerIDsSanitized = containerIDsSanitized + sl[0];
+ }
+ }
+ }
+ }
-/***/ 37859:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ containerIDsSanitized = containerIDsSanitized.trim().toLowerCase().replace(/,+/g, '|');
+ containerArray = containerIDsSanitized.split('|');
+ }
+ const result = [];
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureNamedKeyCredential = void 0;
-exports.isNamedKeyCredential = isNamedKeyCredential;
-const core_util_1 = __nccwpck_require__(30991);
-/**
- * A static name/key-based credential that supports updating
- * the underlying name and key values.
- */
-class AzureNamedKeyCredential {
- /**
- * The value of the key to be used in authentication.
- */
- get key() {
- return this._key;
- }
- /**
- * The value of the name to be used in authentication.
- */
- get name() {
- return this._name;
- }
- /**
- * Create an instance of an AzureNamedKeyCredential for use
- * with a service client.
- *
- * @param name - The initial value of the name to use in authentication.
- * @param key - The initial value of the key to use in authentication.
- */
- constructor(name, key) {
- if (!name || !key) {
- throw new TypeError("name and key must be non-empty strings");
+ const workload = [];
+ if (containerArray.length && containerArray[0].trim() === '*') {
+ containerArray = [];
+ dockerContainers().then(allContainers => {
+ for (let container of allContainers) {
+ containerArray.push(container.id.substring(0, 12));
+ }
+ if (containerArray.length) {
+ dockerContainerStats(containerArray.join(',')).then(result => {
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ } else {
+ for (let containerID of containerArray) {
+ workload.push(dockerContainerStatsSingle(containerID.trim()));
}
- this._name = name;
- this._key = key;
- }
- /**
- * Change the value of the key.
- *
- * Updates will take effect upon the next request after
- * updating the key value.
- *
- * @param newName - The new name value to be used.
- * @param newKey - The new key value to be used.
- */
- update(newName, newKey) {
- if (!newName || !newKey) {
- throw new TypeError("newName and newKey must be non-empty strings");
+ if (workload.length) {
+ Promise.all(
+ workload
+ ).then((data) => {
+ if (callback) { callback(data); }
+ resolve(data);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
}
- this._name = newName;
- this._key = newKey;
- }
+ }
+ });
+ });
}
-exports.AzureNamedKeyCredential = AzureNamedKeyCredential;
-/**
- * Tests an object to determine whether it implements NamedKeyCredential.
- *
- * @param credential - The assumed NamedKeyCredential to be tested.
- */
-function isNamedKeyCredential(credential) {
- return ((0, core_util_1.isObjectWithProperties)(credential, ["name", "key"]) &&
- typeof credential.key === "string" &&
- typeof credential.name === "string");
+
+// --------------------------
+// container stats (for one container)
+
+function dockerContainerStatsSingle(containerID) {
+ containerID = containerID || '';
+ let result = {
+ id: containerID,
+ memUsage: 0,
+ memLimit: 0,
+ memPercent: 0,
+ cpuPercent: 0,
+ pids: 0,
+ netIO: {
+ rx: 0,
+ wx: 0
+ },
+ blockIO: {
+ r: 0,
+ w: 0
+ },
+ restartCount: 0,
+ cpuStats: {},
+ precpuStats: {},
+ memoryStats: {},
+ networks: {},
+ };
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (containerID) {
+
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
+
+ _docker_socket.getInspect(containerID, dataInspect => {
+ try {
+ _docker_socket.getStats(containerID, data => {
+ try {
+ let stats = data;
+ if (!stats.message) {
+ if (data.id) { result.id = data.id; }
+ result.memUsage = (stats.memory_stats && stats.memory_stats.usage ? stats.memory_stats.usage : 0);
+ result.memLimit = (stats.memory_stats && stats.memory_stats.limit ? stats.memory_stats.limit : 0);
+ result.memPercent = (stats.memory_stats && stats.memory_stats.usage && stats.memory_stats.limit ? stats.memory_stats.usage / stats.memory_stats.limit * 100.0 : 0);
+ result.cpuPercent = (stats.cpu_stats && stats.precpu_stats ? docker_calcCPUPercent(stats.cpu_stats, stats.precpu_stats) : 0);
+ result.pids = (stats.pids_stats && stats.pids_stats.current ? stats.pids_stats.current : 0);
+ result.restartCount = (dataInspect.RestartCount ? dataInspect.RestartCount : 0);
+ if (stats.networks) { result.netIO = docker_calcNetworkIO(stats.networks); }
+ if (stats.blkio_stats) { result.blockIO = docker_calcBlockIO(stats.blkio_stats); }
+ result.cpuStats = (stats.cpu_stats ? stats.cpu_stats : {});
+ result.precpuStats = (stats.precpu_stats ? stats.precpu_stats : {});
+ result.memoryStats = (stats.memory_stats ? stats.memory_stats : {});
+ result.networks = (stats.networks ? stats.networks : {});
+ }
+ } catch (err) {
+ util.noop();
+ }
+ // }
+ resolve(result);
+ });
+ } catch (err) {
+ util.noop();
+ }
+ });
+ } else {
+ resolve(result);
+ }
+ });
+ });
}
-//# sourceMappingURL=azureNamedKeyCredential.js.map
-/***/ }),
+exports.dockerContainerStats = dockerContainerStats;
-/***/ 52372:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// container processes (for one container)
+function dockerContainerProcesses(containerID, callback) {
+ let result = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ containerID = containerID || '';
+ if (typeof containerID !== 'string') {
+ return resolve(result);
+ }
+ const containerIdSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerID, true)).trim();
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureSASCredential = void 0;
-exports.isSASCredential = isSASCredential;
-const core_util_1 = __nccwpck_require__(30991);
-/**
- * A static-signature-based credential that supports updating
- * the underlying signature value.
- */
-class AzureSASCredential {
- /**
- * The value of the shared access signature to be used in authentication
- */
- get signature() {
- return this._signature;
- }
- /**
- * Create an instance of an AzureSASCredential for use
- * with a service client.
- *
- * @param signature - The initial value of the shared access signature to use in authentication
- */
- constructor(signature) {
- if (!signature) {
- throw new Error("shared access signature must be a non-empty string");
- }
- this._signature = signature;
- }
- /**
- * Change the value of the signature.
- *
- * Updates will take effect upon the next request after
- * updating the signature value.
- *
- * @param newSignature - The new shared access signature value to be used
- */
- update(newSignature) {
- if (!newSignature) {
- throw new Error("shared access signature must be a non-empty string");
- }
- this._signature = newSignature;
- }
-}
-exports.AzureSASCredential = AzureSASCredential;
-/**
- * Tests an object to determine whether it implements SASCredential.
- *
- * @param credential - The assumed SASCredential to be tested.
- */
-function isSASCredential(credential) {
- return ((0, core_util_1.isObjectWithProperties)(credential, ["signature"]) && typeof credential.signature === "string");
-}
-//# sourceMappingURL=azureSASCredential.js.map
+ if (containerIdSanitized) {
-/***/ }),
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
-/***/ 15269:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ _docker_socket.getProcesses(containerIdSanitized, data => {
+ /**
+ * @namespace
+ * @property {Array} Titles
+ * @property {Array} Processes
+ **/
+ try {
+ if (data && data.Titles && data.Processes) {
+ let titles = data.Titles.map(function (value) {
+ return value.toUpperCase();
+ });
+ let pos_pid = titles.indexOf('PID');
+ let pos_ppid = titles.indexOf('PPID');
+ let pos_pgid = titles.indexOf('PGID');
+ let pos_vsz = titles.indexOf('VSZ');
+ let pos_time = titles.indexOf('TIME');
+ let pos_elapsed = titles.indexOf('ELAPSED');
+ let pos_ni = titles.indexOf('NI');
+ let pos_ruser = titles.indexOf('RUSER');
+ let pos_user = titles.indexOf('USER');
+ let pos_rgroup = titles.indexOf('RGROUP');
+ let pos_group = titles.indexOf('GROUP');
+ let pos_stat = titles.indexOf('STAT');
+ let pos_rss = titles.indexOf('RSS');
+ let pos_command = titles.indexOf('COMMAND');
+ data.Processes.forEach(process => {
+ result.push({
+ pidHost: (pos_pid >= 0 ? process[pos_pid] : ''),
+ ppid: (pos_ppid >= 0 ? process[pos_ppid] : ''),
+ pgid: (pos_pgid >= 0 ? process[pos_pgid] : ''),
+ user: (pos_user >= 0 ? process[pos_user] : ''),
+ ruser: (pos_ruser >= 0 ? process[pos_ruser] : ''),
+ group: (pos_group >= 0 ? process[pos_group] : ''),
+ rgroup: (pos_rgroup >= 0 ? process[pos_rgroup] : ''),
+ stat: (pos_stat >= 0 ? process[pos_stat] : ''),
+ time: (pos_time >= 0 ? process[pos_time] : ''),
+ elapsed: (pos_elapsed >= 0 ? process[pos_elapsed] : ''),
+ nice: (pos_ni >= 0 ? process[pos_ni] : ''),
+ rss: (pos_rss >= 0 ? process[pos_rss] : ''),
+ vsz: (pos_vsz >= 0 ? process[pos_vsz] : ''),
+ command: (pos_command >= 0 ? process[pos_command] : '')
+ });
+ });
+ }
+ } catch (err) {
+ util.noop();
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isTokenCredential = exports.isSASCredential = exports.AzureSASCredential = exports.isNamedKeyCredential = exports.AzureNamedKeyCredential = exports.isKeyCredential = exports.AzureKeyCredential = void 0;
-var azureKeyCredential_js_1 = __nccwpck_require__(21746);
-Object.defineProperty(exports, "AzureKeyCredential", ({ enumerable: true, get: function () { return azureKeyCredential_js_1.AzureKeyCredential; } }));
-var keyCredential_js_1 = __nccwpck_require__(67415);
-Object.defineProperty(exports, "isKeyCredential", ({ enumerable: true, get: function () { return keyCredential_js_1.isKeyCredential; } }));
-var azureNamedKeyCredential_js_1 = __nccwpck_require__(37859);
-Object.defineProperty(exports, "AzureNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.AzureNamedKeyCredential; } }));
-Object.defineProperty(exports, "isNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.isNamedKeyCredential; } }));
-var azureSASCredential_js_1 = __nccwpck_require__(52372);
-Object.defineProperty(exports, "AzureSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.AzureSASCredential; } }));
-Object.defineProperty(exports, "isSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.isSASCredential; } }));
-var tokenCredential_js_1 = __nccwpck_require__(64381);
-Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, get: function () { return tokenCredential_js_1.isTokenCredential; } }));
-//# sourceMappingURL=index.js.map
+exports.dockerContainerProcesses = dockerContainerProcesses;
-/***/ }),
+function dockerVolumes(callback) {
-/***/ 67415:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ let result = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
+ _docker_socket.listVolumes((data) => {
+ let dockerVolumes = {};
+ try {
+ dockerVolumes = data;
+ if (dockerVolumes && dockerVolumes.Volumes && Object.prototype.toString.call(dockerVolumes.Volumes) === '[object Array]' && dockerVolumes.Volumes.length > 0) {
+ dockerVolumes.Volumes.forEach(function (element) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isKeyCredential = isKeyCredential;
-const core_util_1 = __nccwpck_require__(30991);
-/**
- * Tests an object to determine whether it implements KeyCredential.
- *
- * @param credential - The assumed KeyCredential to be tested.
- */
-function isKeyCredential(credential) {
- return (0, core_util_1.isObjectWithProperties)(credential, ["key"]) && typeof credential.key === "string";
+ result.push({
+ name: element.Name,
+ driver: element.Driver,
+ labels: element.Labels,
+ mountpoint: element.Mountpoint,
+ options: element.Options,
+ scope: element.Scope,
+ created: element.CreatedAt ? Math.round(new Date(element.CreatedAt).getTime() / 1000) : 0,
+ });
+ });
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } catch (err) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+ });
}
-//# sourceMappingURL=keyCredential.js.map
-/***/ }),
+exports.dockerVolumes = dockerVolumes;
-/***/ 64381:
-/***/ ((__unused_webpack_module, exports) => {
+function dockerAll(callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ dockerContainers(true).then(result => {
+ if (result && Object.prototype.toString.call(result) === '[object Array]' && result.length > 0) {
+ let l = result.length;
+ result.forEach(function (element) {
+ dockerContainerStats(element.id).then((res) => {
+ // include stats in array
+ element.memUsage = res[0].memUsage;
+ element.memLimit = res[0].memLimit;
+ element.memPercent = res[0].memPercent;
+ element.cpuPercent = res[0].cpuPercent;
+ element.pids = res[0].pids;
+ element.netIO = res[0].netIO;
+ element.blockIO = res[0].blockIO;
+ element.cpuStats = res[0].cpuStats;
+ element.precpuStats = res[0].precpuStats;
+ element.memoryStats = res[0].memoryStats;
+ element.networks = res[0].networks;
+ dockerContainerProcesses(element.id).then(processes => {
+ element.processes = processes;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isBearerToken = isBearerToken;
-exports.isPopToken = isPopToken;
-exports.isTokenCredential = isTokenCredential;
-/**
- * @internal
- * @param accessToken - Access token
- * @returns Whether a token is bearer type or not
- */
-function isBearerToken(accessToken) {
- return !accessToken.tokenType || accessToken.tokenType === "Bearer";
-}
-/**
- * @internal
- * @param accessToken - Access token
- * @returns Whether a token is Pop token or not
- */
-function isPopToken(accessToken) {
- return accessToken.tokenType === "pop";
-}
-/**
- * Tests an object to determine whether it implements TokenCredential.
- *
- * @param credential - The assumed TokenCredential to be tested.
- */
-function isTokenCredential(credential) {
- // Check for an object with a 'getToken' function and possibly with
- // a 'signRequest' function. We do this check to make sure that
- // a ServiceClientCredentials implementor (like TokenClientCredentials
- // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
- // it doesn't actually implement TokenCredential also.
- const castCredential = credential;
- return (castCredential &&
- typeof castCredential.getToken === "function" &&
- (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
+ l -= 1;
+ if (l === 0) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ // all done??
+ });
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+ });
}
-//# sourceMappingURL=tokenCredential.js.map
+
+exports.dockerAll = dockerAll;
+
/***/ }),
-/***/ 85110:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 23945:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.authorizeRequestOnClaimChallenge = exports.parseCAEChallenge = void 0;
-const log_js_1 = __nccwpck_require__(75630);
-const base64_js_1 = __nccwpck_require__(59793);
-/**
- * Converts: `Bearer a="b", c="d", Bearer d="e", f="g"`.
- * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.
- *
- * @internal
- */
-function parseCAEChallenge(challenges) {
- const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x);
- return bearerChallenges.map((challenge) => {
- const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x);
- const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="')));
- // Key-value pairs to plain object:
- return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
- });
-}
-exports.parseCAEChallenge = parseCAEChallenge;
-/**
- * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:
- * [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).
- *
- * Call the `bearerTokenAuthenticationPolicy` with the following options:
- *
- * ```ts
- * import { bearerTokenAuthenticationPolicy } from "@azure/core-rest-pipeline";
- * import { authorizeRequestOnClaimChallenge } from "@azure/core-client";
- *
- * const bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy({
- * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge
- * });
- * ```
- *
- * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.
- * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.
- *
- * Example challenge with claims:
- *
- * ```
- * Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
- * error_description="User session has been revoked",
- * claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
- * ```
- */
-async function authorizeRequestOnClaimChallenge(onChallengeOptions) {
- const { scopes, response } = onChallengeOptions;
- const logger = onChallengeOptions.logger || log_js_1.logger;
- const challenge = response.headers.get("WWW-Authenticate");
- if (!challenge) {
- logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`);
- return false;
- }
- const challenges = parseCAEChallenge(challenge) || [];
- const parsedChallenge = challenges.find((x) => x.claims);
- if (!parsedChallenge) {
- logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`);
- return false;
- }
- const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, {
- claims: (0, base64_js_1.decodeStringToString)(parsedChallenge.claims),
- });
- if (!accessToken) {
- return false;
- }
- onChallengeOptions.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
- return true;
-}
-exports.authorizeRequestOnClaimChallenge = authorizeRequestOnClaimChallenge;
-//# sourceMappingURL=authorizeRequestOnClaimChallenge.js.map
+// @ts-check
+// ==================================================================================
+// dockerSockets.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 13. DockerSockets
+// ----------------------------------------------------------------------------------
-/***/ }),
+const net = __nccwpck_require__(69278);
+const isWin = (__nccwpck_require__(70857).type)() === 'Windows_NT';
+const socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock';
-/***/ 75794:
-/***/ ((__unused_webpack_module, exports) => {
+class DockerSocket {
+ getInfo(callback) {
+ try {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.authorizeRequestOnTenantChallenge = void 0;
-/**
- * A set of constants used internally when processing requests.
- */
-const Constants = {
- DefaultScope: "/.default",
- /**
- * Defines constants for use with HTTP headers.
- */
- HeaderConstants: {
- /**
- * The Authorization header.
- */
- AUTHORIZATION: "authorization",
- },
-};
-function isUuid(text) {
- return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text);
-}
-/**
- * Defines a callback to handle auth challenge for Storage APIs.
- * This implements the bearer challenge process described here: https://docs.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge
- * Handling has specific features for storage that departs to the general AAD challenge docs.
- **/
-const authorizeRequestOnTenantChallenge = async (challengeOptions) => {
- const requestOptions = requestToOptions(challengeOptions.request);
- const challenge = getChallenge(challengeOptions.response);
- if (challenge) {
- const challengeInfo = parseChallenge(challenge);
- const challengeScopes = buildScopes(challengeOptions, challengeInfo);
- const tenantId = extractTenantId(challengeInfo);
- if (!tenantId) {
- return false;
- }
- const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId }));
- if (!accessToken) {
- return false;
- }
- challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}`);
- return true;
- }
- return false;
-};
-exports.authorizeRequestOnTenantChallenge = authorizeRequestOnTenantChallenge;
-/**
- * Extracts the tenant id from the challenge information
- * The tenant id is contained in the authorization_uri as the first
- * path part.
- */
-function extractTenantId(challengeInfo) {
- const parsedAuthUri = new URL(challengeInfo.authorization_uri);
- const pathSegments = parsedAuthUri.pathname.split("/");
- const tenantId = pathSegments[1];
- if (tenantId && isUuid(tenantId)) {
- return tenantId;
- }
- return undefined;
-}
-/**
- * Builds the authentication scopes based on the information that comes in the
- * challenge information. Scopes url is present in the resource_id, if it is empty
- * we keep using the original scopes.
- */
-function buildScopes(challengeOptions, challengeInfo) {
- if (!challengeInfo.resource_id) {
- return challengeOptions.scopes;
- }
- const challengeScopes = new URL(challengeInfo.resource_id);
- challengeScopes.pathname = Constants.DefaultScope;
- let scope = challengeScopes.toString();
- if (scope === "https://disk.azure.com/.default") {
- // the extra slash is required by the service
- scope = "https://disk.azure.com//.default";
- }
- return [scope];
-}
-/**
- * We will retrieve the challenge only if the response status code was 401,
- * and if the response contained the header "WWW-Authenticate" with a non-empty value.
- */
-function getChallenge(response) {
- const challenge = response.headers.get("WWW-Authenticate");
- if (response.status === 401 && challenge) {
- return challenge;
- }
- return;
-}
-/**
- * Converts: `Bearer a="b" c="d"`.
- * Into: `[ { a: 'b', c: 'd' }]`.
- *
- * @internal
- */
-function parseChallenge(challenge) {
- const bearerChallenge = challenge.slice("Bearer ".length);
- const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x);
- const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("=")));
- // Key-value pairs to plain object:
- return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
-}
-/**
- * Extracts the options form a Pipeline Request for later re-use
- */
-function requestToOptions(request) {
- return {
- abortSignal: request.abortSignal,
- requestOptions: {
- timeout: request.timeout,
- },
- tracingOptions: request.tracingOptions,
- };
-}
-//# sourceMappingURL=authorizeRequestOnTenantChallenge.js.map
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
-/***/ }),
+ socket.on('connect', () => {
+ socket.write('GET http:/info HTTP/1.0\r\n\r\n');
+ });
-/***/ 59793:
-/***/ ((__unused_webpack_module, exports) => {
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decodeStringToString = exports.decodeString = exports.encodeByteArray = exports.encodeString = void 0;
-/**
- * Encodes a string in base64 format.
- * @param value - the string to encode
- * @internal
- */
-function encodeString(value) {
- return Buffer.from(value).toString("base64");
-}
-exports.encodeString = encodeString;
-/**
- * Encodes a byte array in base64 format.
- * @param value - the Uint8Aray to encode
- * @internal
- */
-function encodeByteArray(value) {
- const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer);
- return bufferValue.toString("base64");
-}
-exports.encodeByteArray = encodeByteArray;
-/**
- * Decodes a base64 string into a byte array.
- * @param value - the base64 string to decode
- * @internal
- */
-function decodeString(value) {
- return Buffer.from(value, "base64");
-}
-exports.decodeString = decodeString;
-/**
- * Decodes a base64 string into a string.
- * @param value - the base64 string to decode
- * @internal
- */
-function decodeStringToString(value) {
- return Buffer.from(value, "base64").toString();
-}
-exports.decodeStringToString = decodeStringToString;
-//# sourceMappingURL=base64.js.map
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
+ }
+ });
+ } catch (err) {
+ callback({});
+ }
+ }
-/***/ }),
+ listImages(all, callback) {
+ try {
-/***/ 21795:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+ socket.on('connect', () => {
+ socket.write('GET http:/images/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n');
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.deserializationPolicy = exports.deserializationPolicyName = void 0;
-const interfaces_js_1 = __nccwpck_require__(35590);
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-const serializer_js_1 = __nccwpck_require__(66774);
-const operationHelpers_js_1 = __nccwpck_require__(17036);
-const defaultJsonContentTypes = ["application/json", "text/json"];
-const defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
-/**
- * The programmatic identifier of the deserializationPolicy.
- */
-exports.deserializationPolicyName = "deserializationPolicy";
-/**
- * This policy handles parsing out responses according to OperationSpecs on the request.
- */
-function deserializationPolicy(options = {}) {
- var _a, _b, _c, _d, _e, _f, _g;
- const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes;
- const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes;
- const parseXML = options.parseXML;
- const serializerOptions = options.serializerOptions;
- const updatedOptions = {
- xml: {
- rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "",
- includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false,
- xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : interfaces_js_1.XML_CHARKEY,
- },
- };
- return {
- name: exports.deserializationPolicyName,
- async sendRequest(request, next) {
- const response = await next(request);
- return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML);
- },
- };
-}
-exports.deserializationPolicy = deserializationPolicy;
-function getOperationResponseMap(parsedResponse) {
- let result;
- const request = parsedResponse.request;
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
- if (operationSpec) {
- if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) {
- result = operationSpec.responses[parsedResponse.status];
- }
- else {
- result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse);
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
}
+ });
+ } catch (err) {
+ callback({});
}
- return result;
-}
-function shouldDeserializeResponse(parsedResponse) {
- const request = parsedResponse.request;
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize;
- let result;
- if (shouldDeserialize === undefined) {
- result = true;
- }
- else if (typeof shouldDeserialize === "boolean") {
- result = shouldDeserialize;
- }
- else {
- result = shouldDeserialize(parsedResponse);
- }
- return result;
-}
-async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) {
- const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML);
- if (!shouldDeserializeResponse(parsedResponse)) {
- return parsedResponse;
- }
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(parsedResponse.request);
- const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
- if (!operationSpec || !operationSpec.responses) {
- return parsedResponse;
- }
- const responseSpec = getOperationResponseMap(parsedResponse);
- const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options);
- if (error) {
- throw error;
- }
- else if (shouldReturnResponse) {
- return parsedResponse;
- }
- // An operation response spec does exist for current status code, so
- // use it to deserialize the response.
- if (responseSpec) {
- if (responseSpec.bodyMapper) {
- let valueToDeserialize = parsedResponse.parsedBody;
- if (operationSpec.isXML && responseSpec.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
- valueToDeserialize =
- typeof valueToDeserialize === "object"
- ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
- : [];
- }
- try {
- parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options);
- }
- catch (deserializeError) {
- const restError = new core_rest_pipeline_1.RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, {
- statusCode: parsedResponse.status,
- request: parsedResponse.request,
- response: parsedResponse,
- });
- throw restError;
- }
- }
- else if (operationSpec.httpMethod === "HEAD") {
- // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
- parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
- }
- if (responseSpec.headersMapper) {
- parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true });
- }
+ }
+
+ inspectImage(id, callback) {
+ id = id || '';
+ if (id) {
+ try {
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/images/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
+ }
+ });
+ } catch (err) {
+ callback({});
+ }
+ } else {
+ callback({});
}
- return parsedResponse;
-}
-function isOperationSpecEmpty(operationSpec) {
- const expectedStatusCodes = Object.keys(operationSpec.responses);
- return (expectedStatusCodes.length === 0 ||
- (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
-}
-function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) {
- var _a;
- const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;
- const isExpectedStatusCode = isOperationSpecEmpty(operationSpec)
- ? isSuccessByStatus
- : !!responseSpec;
- if (isExpectedStatusCode) {
- if (responseSpec) {
- if (!responseSpec.isError) {
- return { error: null, shouldReturnResponse: false };
- }
- }
- else {
- return { error: null, shouldReturnResponse: false };
+ }
+
+ listContainers(all, callback) {
+ try {
+
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/containers/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
}
+ });
+ } catch (err) {
+ callback({});
}
- const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default;
- const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status))
- ? `Unexpected status code: ${parsedResponse.status}`
- : parsedResponse.bodyAsText;
- const error = new core_rest_pipeline_1.RestError(initialErrorMessage, {
- statusCode: parsedResponse.status,
- request: parsedResponse.request,
- response: parsedResponse,
- });
- // If the item failed but there's no error spec or default spec to deserialize the error,
- // we should fail so we just throw the parsed response
- if (!errorResponseSpec) {
- throw error;
+ }
+
+ getStats(id, callback) {
+ id = id || '';
+ if (id) {
+ try {
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/containers/' + id + '/stats?stream=0 HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
+ }
+ });
+ } catch (err) {
+ callback({});
+ }
+ } else {
+ callback({});
}
- const defaultBodyMapper = errorResponseSpec.bodyMapper;
- const defaultHeadersMapper = errorResponseSpec.headersMapper;
- try {
- // If error response has a body, try to deserialize it using default body mapper.
- // Then try to extract error code & message from it
- if (parsedResponse.parsedBody) {
- const parsedBody = parsedResponse.parsedBody;
- let deserializedError;
- if (defaultBodyMapper) {
- let valueToDeserialize = parsedBody;
- if (operationSpec.isXML && defaultBodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
- valueToDeserialize = [];
- const elementName = defaultBodyMapper.xmlElementName;
- if (typeof parsedBody === "object" && elementName) {
- valueToDeserialize = parsedBody[elementName];
- }
- }
- deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options);
- }
- const internalError = parsedBody.error || deserializedError || parsedBody;
- error.code = internalError.code;
- if (internalError.message) {
- error.message = internalError.message;
- }
- if (defaultBodyMapper) {
- error.response.parsedBody = deserializedError;
- }
- }
- // If error response has headers, try to deserialize it using default header mapper
- if (parsedResponse.headers && defaultHeadersMapper) {
- error.response.parsedHeaders =
- operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders");
- }
+ }
+
+ getInspect(id, callback) {
+ id = id || '';
+ if (id) {
+ try {
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/containers/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
+ }
+ });
+ } catch (err) {
+ callback({});
+ }
+ } else {
+ callback({});
}
- catch (defaultError) {
- error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`;
+ }
+
+ getProcesses(id, callback) {
+ id = id || '';
+ if (id) {
+ try {
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/containers/' + id + '/top?ps_args=-opid,ppid,pgid,vsz,time,etime,nice,ruser,user,rgroup,group,stat,rss,args HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
+ }
+ });
+ } catch (err) {
+ callback({});
+ }
+ } else {
+ callback({});
}
- return { error, shouldReturnResponse: false };
-}
-async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
- var _a;
- if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) &&
- operationResponse.bodyAsText) {
- const text = operationResponse.bodyAsText;
- const contentType = operationResponse.headers.get("Content-Type") || "";
- const contentComponents = !contentType
- ? []
- : contentType.split(";").map((component) => component.toLowerCase());
+ }
+
+ listVolumes(callback) {
+ try {
+
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/volumes HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
try {
- if (contentComponents.length === 0 ||
- contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) {
- operationResponse.parsedBody = JSON.parse(text);
- return operationResponse;
- }
- else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) {
- if (!parseXML) {
- throw new Error("Parsing XML not supported.");
- }
- const body = await parseXML(text, opts.xml);
- operationResponse.parsedBody = body;
- return operationResponse;
- }
- }
- catch (err) {
- const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;
- const errCode = err.code || core_rest_pipeline_1.RestError.PARSE_ERROR;
- const e = new core_rest_pipeline_1.RestError(msg, {
- code: errCode,
- statusCode: operationResponse.status,
- request: operationResponse.request,
- response: operationResponse,
- });
- throw e;
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
}
+ });
+ } catch (err) {
+ callback({});
}
- return operationResponse;
+ }
}
-//# sourceMappingURL=deserializationPolicy.js.map
+
+module.exports = DockerSocket;
+
/***/ }),
-/***/ 64663:
+/***/ 50223:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getCachedDefaultHttpClient = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-let cachedHttpClient;
-function getCachedDefaultHttpClient() {
- if (!cachedHttpClient) {
- cachedHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)();
- }
- return cachedHttpClient;
-}
-exports.getCachedDefaultHttpClient = getCachedDefaultHttpClient;
-//# sourceMappingURL=httpClientCache.js.map
+// @ts-check
+// ==================================================================================
+// filesystem.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 8. File System
+// ----------------------------------------------------------------------------------
-/***/ }),
+const util = __nccwpck_require__(77496);
+const fs = __nccwpck_require__(79896);
-/***/ 6868:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const execPromiseSave = util.promisifySave((__nccwpck_require__(35317).exec));
+let _platform = process.platform;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.authorizeRequestOnTenantChallenge = exports.authorizeRequestOnClaimChallenge = exports.serializationPolicyName = exports.serializationPolicy = exports.deserializationPolicyName = exports.deserializationPolicy = exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.createClientPipeline = exports.ServiceClient = exports.MapperTypeNames = exports.createSerializer = void 0;
-var serializer_js_1 = __nccwpck_require__(66774);
-Object.defineProperty(exports, "createSerializer", ({ enumerable: true, get: function () { return serializer_js_1.createSerializer; } }));
-Object.defineProperty(exports, "MapperTypeNames", ({ enumerable: true, get: function () { return serializer_js_1.MapperTypeNames; } }));
-var serviceClient_js_1 = __nccwpck_require__(22732);
-Object.defineProperty(exports, "ServiceClient", ({ enumerable: true, get: function () { return serviceClient_js_1.ServiceClient; } }));
-var pipeline_js_1 = __nccwpck_require__(64524);
-Object.defineProperty(exports, "createClientPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createClientPipeline; } }));
-var interfaces_js_1 = __nccwpck_require__(35590);
-Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_ATTRKEY; } }));
-Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_CHARKEY; } }));
-var deserializationPolicy_js_1 = __nccwpck_require__(21795);
-Object.defineProperty(exports, "deserializationPolicy", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicy; } }));
-Object.defineProperty(exports, "deserializationPolicyName", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicyName; } }));
-var serializationPolicy_js_1 = __nccwpck_require__(87054);
-Object.defineProperty(exports, "serializationPolicy", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicy; } }));
-Object.defineProperty(exports, "serializationPolicyName", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicyName; } }));
-var authorizeRequestOnClaimChallenge_js_1 = __nccwpck_require__(85110);
-Object.defineProperty(exports, "authorizeRequestOnClaimChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnClaimChallenge_js_1.authorizeRequestOnClaimChallenge; } }));
-var authorizeRequestOnTenantChallenge_js_1 = __nccwpck_require__(75794);
-Object.defineProperty(exports, "authorizeRequestOnTenantChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnTenantChallenge_js_1.authorizeRequestOnTenantChallenge; } }));
-//# sourceMappingURL=index.js.map
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
-/***/ }),
+let _fs_speed = {};
+let _disk_io = {};
-/***/ 91030:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// FS - mounted file systems
+function fsSize(drive, callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getPathStringFromParameter = exports.getStreamingResponseStatusCodes = void 0;
-const serializer_js_1 = __nccwpck_require__(66774);
-/**
- * Gets the list of status codes for streaming responses.
- * @internal
- */
-function getStreamingResponseStatusCodes(operationSpec) {
- const result = new Set();
- for (const statusCode in operationSpec.responses) {
- const operationResponse = operationSpec.responses[statusCode];
- if (operationResponse.bodyMapper &&
- operationResponse.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Stream) {
- result.add(Number(statusCode));
- }
- }
+ if (util.isFunction(drive)) {
+ callback = drive;
+ drive = '';
+ }
+
+ let macOsDisks = [];
+ let osMounts = [];
+
+ function getmacOsFsType(fs) {
+ if (!fs.startsWith('/')) { return 'NFS'; }
+ const parts = fs.split('/');
+ const fsShort = parts[parts.length - 1];
+ const macOsDisksSingle = macOsDisks.filter(item => item.indexOf(fsShort) >= 0);
+ if (macOsDisksSingle.length === 1 && macOsDisksSingle[0].indexOf('APFS') >= 0) { return 'APFS'; }
+ return 'HFS';
+ }
+
+ function isLinuxTmpFs(fs) {
+ const linuxTmpFileSystems = ['rootfs', 'unionfs', 'squashfs', 'cramfs', 'initrd', 'initramfs', 'devtmpfs', 'tmpfs', 'udev', 'devfs', 'specfs', 'type', 'appimaged'];
+ let result = false;
+ linuxTmpFileSystems.forEach(linuxFs => {
+ if (fs.toLowerCase().indexOf(linuxFs) >= 0) { result = true; }
+ });
return result;
-}
-exports.getStreamingResponseStatusCodes = getStreamingResponseStatusCodes;
-/**
- * Get the path to this parameter's value as a dotted string (a.b.c).
- * @param parameter - The parameter to get the path string for.
- * @returns The path to this parameter's value as a dotted string.
- * @internal
- */
-function getPathStringFromParameter(parameter) {
- const { parameterPath, mapper } = parameter;
- let result;
- if (typeof parameterPath === "string") {
- result = parameterPath;
- }
- else if (Array.isArray(parameterPath)) {
- result = parameterPath.join(".");
- }
- else {
- result = mapper.serializedName;
+ }
+
+ function filterLines(stdout) {
+ let lines = stdout.toString().split('\n');
+ lines.shift();
+ if (stdout.toString().toLowerCase().indexOf('filesystem')) {
+ let removeLines = 0;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i] && lines[i].toLowerCase().startsWith('filesystem')) {
+ removeLines = i;
+ }
+ }
+ for (let i = 0; i < removeLines; i++) {
+ lines.shift();
+ }
}
- return result;
+ return lines;
+ }
+
+ function parseDf(lines) {
+ let data = [];
+ lines.forEach(function (line) {
+ if (line !== '') {
+ line = line.replace(/ +/g, ' ').split(' ');
+ if (line && ((line[0].startsWith('/')) || (line[6] && line[6] === '/') || (line[0].indexOf('/') > 0) || (line[0].indexOf(':') === 1) || !_darwin && !isLinuxTmpFs(line[1]))) {
+ const fs = line[0];
+ const fsType = ((_linux || _freebsd || _openbsd || _netbsd) ? line[1] : getmacOsFsType(line[0]));
+ const size = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[2] : line[1])) * 1024;
+ const used = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[3] : line[2])) * 1024;
+ const available = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[4] : line[3])) * 1024;
+ const use = parseFloat((100.0 * (used / (used + available))).toFixed(2));
+ let rw = osMounts && Object.keys(osMounts).length > 0 ? osMounts[fs] || false : null;
+ line.splice(0, (_linux || _freebsd || _openbsd || _netbsd) ? 6 : 5);
+ const mount = line.join(' ');
+ if (!data.find(el => (el.fs === fs && el.type === fsType))) {
+ data.push({
+ fs,
+ type: fsType,
+ size,
+ used,
+ available,
+ use,
+ mount,
+ rw
+ });
+ }
+ }
+ }
+ });
+ return data;
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let data = [];
+ if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
+ let cmd = '';
+ macOsDisks = [];
+ osMounts = {};
+ if (_darwin) {
+ cmd = 'df -kP';
+ try {
+ macOsDisks = execSync('diskutil list').toString().split('\n').filter(line => {
+ return !line.startsWith('/') && line.indexOf(':') > 0;
+ });
+ execSync('mount').toString().split('\n').filter(line => {
+ return line.startsWith('/');
+ }).forEach((line) => {
+ osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1;
+ });
+ } catch (e) {
+ util.noop();
+ }
+ }
+ if (_linux) {
+ try {
+ cmd = 'export LC_ALL=C; df -lkPTx squashfs; unset LC_ALL';
+ execSync('cat /proc/mounts 2>/dev/null', util.execOptsLinux).toString().split('\n').filter(line => {
+ return line.startsWith('/');
+ }).forEach((line) => {
+ osMounts[line.split(' ')[0]] = osMounts[line.split(' ')[0]] || false;
+ if (line.toLowerCase().indexOf('/snap/') === -1) {
+ osMounts[line.split(' ')[0]] = ((line.toLowerCase().indexOf('rw,') >= 0 || line.toLowerCase().indexOf(' rw ') >= 0));
+ }
+ });
+ } catch (e) {
+ util.noop();
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ try {
+ cmd = 'df -lkPT';
+ execSync('mount').toString().split('\n').forEach((line) => {
+ osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1;
+ });
+ } catch (e) {
+ util.noop();
+ }
+ }
+ exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ let lines = filterLines(stdout);
+ data = parseDf(lines);
+ if (drive) {
+ data = data.filter(item => {
+ return item.fs.toLowerCase().indexOf(drive.toLowerCase()) >= 0 || item.mount.toLowerCase().indexOf(drive.toLowerCase()) >= 0;
+ });
+ }
+ if ((!error || data.length) && stdout.toString().trim() !== '') {
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ } else {
+ exec('df -kPT', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = filterLines(stdout);
+ data = parseDf(lines);
+ }
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ });
+ }
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(data); }
+ resolve(data);
+ }
+ if (_windows) {
+ try {
+ const cmd = `Get-WmiObject Win32_logicaldisk | select Access,Caption,FileSystem,FreeSpace,Size ${drive ? '| where -property Caption -eq ' + drive : ''} | fl`;
+ util.powerShell(cmd).then((stdout, error) => {
+ if (!error) {
+ let devices = stdout.toString().split(/\n\s*\n/);
+ devices.forEach(function (device) {
+ let lines = device.split('\r\n');
+ const size = util.toInt(util.getValue(lines, 'size', ':'));
+ const free = util.toInt(util.getValue(lines, 'freespace', ':'));
+ const caption = util.getValue(lines, 'caption', ':');
+ const rwValue = util.getValue(lines, 'access', ':');
+ const rw = rwValue ? (util.toInt(rwValue) !== 1) : null;
+ if (size) {
+ data.push({
+ fs: caption,
+ type: util.getValue(lines, 'filesystem', ':'),
+ size,
+ used: size - free,
+ available: free,
+ use: parseFloat(((100.0 * (size - free)) / size).toFixed(2)),
+ mount: caption,
+ rw
+ });
+ }
+ });
+ }
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ });
+ } catch (e) {
+ if (callback) { callback(data); }
+ resolve(data);
+ }
+ }
+ });
+ });
}
-exports.getPathStringFromParameter = getPathStringFromParameter;
-//# sourceMappingURL=interfaceHelpers.js.map
-/***/ }),
+exports.fsSize = fsSize;
-/***/ 35590:
-/***/ ((__unused_webpack_module, exports) => {
+// --------------------------
+// FS - open files count
+function fsOpenFiles(callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0;
-/**
- * Default key used to access the XML attributes.
- */
-exports.XML_ATTRKEY = "$";
-/**
- * Default key used to access the XML value content.
- */
-exports.XML_CHARKEY = "_";
-//# sourceMappingURL=interfaces.js.map
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ const result = {
+ max: null,
+ allocated: null,
+ available: null
+ };
+ if (_freebsd || _openbsd || _netbsd || _darwin) {
+ let cmd = 'sysctl -i kern.maxfiles kern.num_files kern.open_files';
+ exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result.max = parseInt(util.getValue(lines, 'kern.maxfiles', ':'), 10);
+ result.allocated = parseInt(util.getValue(lines, 'kern.num_files', ':'), 10) || parseInt(util.getValue(lines, 'kern.open_files', ':'), 10);
+ result.available = result.max - result.allocated;
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_linux) {
+ fs.readFile('/proc/sys/fs/file-nr', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines[0]) {
+ const parts = lines[0].replace(/\s+/g, ' ').split(' ');
+ if (parts.length === 3) {
+ result.allocated = parseInt(parts[0], 10);
+ result.available = parseInt(parts[1], 10);
+ result.max = parseInt(parts[2], 10);
+ if (!result.available) { result.available = result.max - result.allocated; }
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ } else {
+ fs.readFile('/proc/sys/fs/file-max', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines[0]) {
+ result.max = parseInt(lines[0], 10);
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(null); }
+ resolve(null);
+ }
+ if (_windows) {
+ if (callback) { callback(null); }
+ resolve(null);
+ }
+ });
+ });
+}
-/***/ }),
+exports.fsOpenFiles = fsOpenFiles;
-/***/ 75630:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// disks
+function parseBytes(s) {
+ return parseInt(s.substr(s.indexOf(' (') + 2, s.indexOf(' Bytes)') - 10));
+}
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.logger = void 0;
-const logger_1 = __nccwpck_require__(50143);
-exports.logger = (0, logger_1.createClientLogger)("core-client");
-//# sourceMappingURL=log.js.map
+function parseDevices(lines) {
+ let devices = [];
+ let i = 0;
+ lines.forEach(line => {
+ if (line.length > 0) {
+ if (line[0] === '*') {
+ i++;
+ } else {
+ let parts = line.split(':');
+ if (parts.length > 1) {
+ if (!devices[i]) {
+ devices[i] = {
+ name: '',
+ identifier: '',
+ type: 'disk',
+ fsType: '',
+ mount: '',
+ size: 0,
+ physical: 'HDD',
+ uuid: '',
+ label: '',
+ model: '',
+ serial: '',
+ removable: false,
+ protocol: '',
+ group: '',
+ device: ''
+ };
+ }
+ parts[0] = parts[0].trim().toUpperCase().replace(/ +/g, '');
+ parts[1] = parts[1].trim();
+ if ('DEVICEIDENTIFIER' === parts[0]) { devices[i].identifier = parts[1]; }
+ if ('DEVICENODE' === parts[0]) { devices[i].name = parts[1]; }
+ if ('VOLUMENAME' === parts[0]) {
+ if (parts[1].indexOf('Not applicable') === -1) { devices[i].label = parts[1]; }
+ }
+ if ('PROTOCOL' === parts[0]) { devices[i].protocol = parts[1]; }
+ if ('DISKSIZE' === parts[0]) { devices[i].size = parseBytes(parts[1]); }
+ if ('FILESYSTEMPERSONALITY' === parts[0]) { devices[i].fsType = parts[1]; }
+ if ('MOUNTPOINT' === parts[0]) { devices[i].mount = parts[1]; }
+ if ('VOLUMEUUID' === parts[0]) { devices[i].uuid = parts[1]; }
+ if ('READ-ONLYMEDIA' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'CD/DVD'; }
+ if ('SOLIDSTATE' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'SSD'; }
+ if ('VIRTUAL' === parts[0]) { devices[i].type = 'virtual'; }
+ if ('REMOVABLEMEDIA' === parts[0]) { devices[i].removable = (parts[1] === 'Removable'); }
+ if ('PARTITIONTYPE' === parts[0]) { devices[i].type = 'part'; }
+ if ('DEVICE/MEDIANAME' === parts[0]) { devices[i].model = parts[1]; }
+ }
+ }
+ }
+ });
+ return devices;
+}
+
+function parseBlk(lines) {
+ let data = [];
+
+ lines.filter(line => line !== '').forEach((line) => {
+ try {
+ line = decodeURIComponent(line.replace(/\\x/g, '%'));
+ line = line.replace(/\\/g, '\\\\');
+ let disk = JSON.parse(line);
+ data.push({
+ 'name': disk.name,
+ 'type': disk.type,
+ 'fsType': disk.fsType,
+ 'mount': disk.mountpoint,
+ 'size': parseInt(disk.size),
+ 'physical': (disk.type === 'disk' ? (disk.rota === '0' ? 'SSD' : 'HDD') : (disk.type === 'rom' ? 'CD/DVD' : '')),
+ 'uuid': disk.uuid,
+ 'label': disk.label,
+ 'model': (disk.model || '').trim(),
+ 'serial': disk.serial,
+ 'removable': disk.rm === '1',
+ 'protocol': disk.tran,
+ 'group': disk.group || '',
+ });
+ } catch (e) {
+ util.noop();
+ }
+ });
+ data = util.unique(data);
+ data = util.sortByKey(data, ['type', 'name']);
+ return data;
+}
-/***/ }),
+function decodeMdabmData(lines) {
+ const raid = util.getValue(lines, 'md_level', '=');
+ const label = util.getValue(lines, 'md_name', '='); // <- get label info
+ const uuid = util.getValue(lines, 'md_uuid', '='); // <- get uuid info
+ const members = [];
+ lines.forEach(line => {
+ if (line.toLowerCase().startsWith('md_device_dev') && line.toLowerCase().indexOf('/dev/') > 0) {
+ members.push(line.split('/dev/')[1]);
+ }
+ });
+ return {
+ raid,
+ label,
+ uuid,
+ members
+ };
+}
-/***/ 17036:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function raidMatchLinux(data) {
+ // for all block devices of type "raid%"
+ let result = data;
+ try {
+ data.forEach(element => {
+ if (element.type.startsWith('raid')) {
+ const lines = execSync(`mdadm --export --detail /dev/${element.name}`, util.execOptsLinux).toString().split('\n');
+ const mdData = decodeMdabmData(lines);
+ element.label = mdData.label; // <- assign label info
+ element.uuid = mdData.uuid; // <- assign uuid info
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getOperationRequestInfo = exports.getOperationArgumentValueFromParameter = void 0;
-const state_js_1 = __nccwpck_require__(35077);
-/**
- * @internal
- * Retrieves the value to use for a given operation argument
- * @param operationArguments - The arguments passed from the generated client
- * @param parameter - The parameter description
- * @param fallbackObject - If something isn't found in the arguments bag, look here.
- * Generally used to look at the service client properties.
- */
-function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) {
- let parameterPath = parameter.parameterPath;
- const parameterMapper = parameter.mapper;
- let value;
- if (typeof parameterPath === "string") {
- parameterPath = [parameterPath];
- }
- if (Array.isArray(parameterPath)) {
- if (parameterPath.length > 0) {
- if (parameterMapper.isConstant) {
- value = parameterMapper.defaultValue;
- }
- else {
- let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
- if (!propertySearchResult.propertyFound && fallbackObject) {
- propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath);
- }
- let useDefaultValue = false;
- if (!propertySearchResult.propertyFound) {
- useDefaultValue =
- parameterMapper.required ||
- (parameterPath[0] === "options" && parameterPath.length === 2);
- }
- value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
- }
- }
- }
- else {
- if (parameterMapper.required) {
- value = {};
- }
- for (const propertyName in parameterPath) {
- const propertyMapper = parameterMapper.type.modelProperties[propertyName];
- const propertyPath = parameterPath[propertyName];
- const propertyValue = getOperationArgumentValueFromParameter(operationArguments, {
- parameterPath: propertyPath,
- mapper: propertyMapper,
- }, fallbackObject);
- if (propertyValue !== undefined) {
- if (!value) {
- value = {};
- }
- value[propertyName] = propertyValue;
+ if (mdData.members && mdData.members.length && mdData.raid === element.type) {
+ result = result.map(blockdevice => {
+ if (blockdevice.fsType === 'linux_raid_member' && mdData.members.indexOf(blockdevice.name) >= 0) {
+ blockdevice.group = element.name;
}
+ return blockdevice;
+ });
}
+ }
+ });
+ } catch (e) {
+ util.noop();
+ }
+ return result;
+}
+
+function getDevicesLinux(data) {
+ const result = [];
+ data.forEach(element => {
+ if (element.type.startsWith('disk')) {
+ result.push(element.name);
}
- return value;
+ });
+ return result;
}
-exports.getOperationArgumentValueFromParameter = getOperationArgumentValueFromParameter;
-function getPropertyFromParameterPath(parent, parameterPath) {
- const result = { propertyFound: false };
- let i = 0;
- for (; i < parameterPath.length; ++i) {
- const parameterPathPart = parameterPath[i];
- // Make sure to check inherited properties too, so don't use hasOwnProperty().
- if (parent && parameterPathPart in parent) {
- parent = parent[parameterPathPart];
- }
- else {
- break;
- }
+
+function matchDevicesLinux(data) {
+ let result = data;
+ try {
+ const devices = getDevicesLinux(data);
+ result = result.map(blockdevice => {
+ if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk')) {
+ devices.forEach(element => {
+ if (blockdevice.name.startsWith(element)) {
+ blockdevice.device = '/dev/' + element;
+ }
+ });
+ }
+ return blockdevice;
+ });
+ } catch (e) {
+ util.noop();
+ }
+ return result;
+}
+
+function getDevicesMac(data) {
+ const result = [];
+ data.forEach(element => {
+ if (element.type.startsWith('disk')) {
+ result.push({ name: element.name, model: element.model, device: element.name });
}
- if (i === parameterPath.length) {
- result.propertyValue = parent;
- result.propertyFound = true;
+ if (element.type.startsWith('virtual')) {
+ let device = '';
+ result.forEach(e => {
+ if (e.model === element.model) {
+ device = e.device;
+ }
+ });
+ if (device) {
+ result.push({ name: element.name, model: element.model, device });
+ }
}
- return result;
+ });
+ return result;
}
-const originalRequestSymbol = Symbol.for("@azure/core-client original request");
-function hasOriginalRequest(request) {
- return originalRequestSymbol in request;
+
+function matchDevicesMac(data) {
+ let result = data;
+ try {
+ const devices = getDevicesMac(data);
+ result = result.map(blockdevice => {
+ if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk') || blockdevice.type.startsWith('virtual')) {
+ devices.forEach(element => {
+ if (blockdevice.name.startsWith(element.name)) {
+ blockdevice.device = element.device;
+ }
+ });
+ }
+ return blockdevice;
+ });
+ } catch (e) {
+ util.noop();
+ }
+ return result;
}
-function getOperationRequestInfo(request) {
- if (hasOriginalRequest(request)) {
- return getOperationRequestInfo(request[originalRequestSymbol]);
+
+function getDevicesWin(diskDrives) {
+ const result = [];
+ diskDrives.forEach(element => {
+ const lines = element.split('\r\n');
+ const device = util.getValue(lines, 'DeviceID', ':');
+ let partitions = element.split('@{DeviceID=');
+ if (partitions.length > 1) {
+ partitions = partitions.slice(1);
+ partitions.forEach(partition => {
+ result.push({ name: partition.split(';')[0].toUpperCase(), device });
+ });
}
- let info = state_js_1.state.operationRequestMap.get(request);
- if (!info) {
- info = {};
- state_js_1.state.operationRequestMap.set(request, info);
+ });
+ return result;
+}
+
+function matchDevicesWin(data, diskDrives) {
+ const devices = getDevicesWin(diskDrives);
+ data.map(element => {
+ const filteresDevices = devices.filter((e) => { return e.name === element.name.toUpperCase(); });
+ if (filteresDevices.length > 0) {
+ element.device = filteresDevices[0].device;
}
- return info;
+ return element;
+ });
+ return data;
}
-exports.getOperationRequestInfo = getOperationRequestInfo;
-//# sourceMappingURL=operationHelpers.js.map
-/***/ }),
+function blkStdoutToObject(stdout) {
+ return stdout.toString()
+ .replace(/NAME=/g, '{"name":')
+ .replace(/FSTYPE=/g, ',"fsType":')
+ .replace(/TYPE=/g, ',"type":')
+ .replace(/SIZE=/g, ',"size":')
+ .replace(/MOUNTPOINT=/g, ',"mountpoint":')
+ .replace(/UUID=/g, ',"uuid":')
+ .replace(/ROTA=/g, ',"rota":')
+ .replace(/RO=/g, ',"ro":')
+ .replace(/RM=/g, ',"rm":')
+ .replace(/TRAN=/g, ',"tran":')
+ .replace(/SERIAL=/g, ',"serial":')
+ .replace(/LABEL=/g, ',"label":')
+ .replace(/MODEL=/g, ',"model":')
+ .replace(/OWNER=/g, ',"owner":')
+ .replace(/GROUP=/g, ',"group":')
+ .replace(/\n/g, '}\n');
+}
-/***/ 64524:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function blockDevices(callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let data = [];
+ if (_linux) {
+ // see https://wiki.ubuntuusers.de/lsblk/
+ // exec("lsblk -bo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,TRAN,SERIAL,LABEL,MODEL,OWNER,GROUP,MODE,ALIGNMENT,MIN-IO,OPT-IO,PHY-SEC,LOG-SEC,SCHED,RQ-SIZE,RA,WSAME", function (error, stdout) {
+ exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,TRAN,SERIAL,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = blkStdoutToObject(stdout).split('\n');
+ data = parseBlk(lines);
+ data = raidMatchLinux(data);
+ data = matchDevicesLinux(data);
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ } else {
+ exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = blkStdoutToObject(stdout).split('\n');
+ data = parseBlk(lines);
+ data = raidMatchLinux(data);
+ }
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ });
+ }
+ });
+ }
+ if (_darwin) {
+ exec('diskutil info -all', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ // parse lines into temp array of devices
+ data = parseDevices(lines);
+ data = matchDevicesMac(data);
+ }
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(data); }
+ resolve(data);
+ }
+ if (_windows) {
+ let drivetypes = ['Unknown', 'NoRoot', 'Removable', 'Local', 'Network', 'CD/DVD', 'RAM'];
+ try {
+ // util.wmic('logicaldisk get Caption,Description,DeviceID,DriveType,FileSystem,FreeSpace,Name,Size,VolumeName,VolumeSerialNumber /value').then((stdout, error) => {
+ // util.powerShell('Get-CimInstance Win32_logicaldisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl').then((stdout, error) => {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance -ClassName Win32_LogicalDisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl'));
+ workload.push(util.powerShell('Get-WmiObject -Class Win32_diskdrive | Select-Object -Property PNPDeviceId,DeviceID, Model, Size, @{L=\'Partitions\'; E={$_.GetRelated(\'Win32_DiskPartition\').GetRelated(\'Win32_LogicalDisk\') | Select-Object -Property DeviceID, VolumeName, Size, FreeSpace}} | fl'));
+ util.promiseAll(
+ workload
+ ).then((res) => {
+ let logicalDisks = res.results[0].toString().split(/\n\s*\n/);
+ let diskDrives = res.results[1].toString().split(/\n\s*\n/);
+ logicalDisks.forEach(function (device) {
+ let lines = device.split('\r\n');
+ let drivetype = util.getValue(lines, 'drivetype', ':');
+ if (drivetype) {
+ data.push({
+ name: util.getValue(lines, 'name', ':'),
+ identifier: util.getValue(lines, 'caption', ':'),
+ type: 'disk',
+ fsType: util.getValue(lines, 'filesystem', ':').toLowerCase(),
+ mount: util.getValue(lines, 'caption', ':'),
+ size: util.getValue(lines, 'size', ':'),
+ physical: (drivetype >= 0 && drivetype <= 6) ? drivetypes[drivetype] : drivetypes[0],
+ uuid: util.getValue(lines, 'volumeserialnumber', ':'),
+ label: util.getValue(lines, 'volumename', ':'),
+ model: '',
+ serial: util.getValue(lines, 'volumeserialnumber', ':'),
+ removable: drivetype === '2',
+ protocol: '',
+ group: '',
+ device: ''
+ });
+ }
+ });
+ // match devices
+ data = matchDevicesWin(data, diskDrives);
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ });
+ } catch (e) {
+ if (callback) { callback(data); }
+ resolve(data);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ // will follow
+ if (callback) { callback(null); }
+ resolve(null);
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createClientPipeline = void 0;
-const deserializationPolicy_js_1 = __nccwpck_require__(21795);
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-const serializationPolicy_js_1 = __nccwpck_require__(87054);
-/**
- * Creates a new Pipeline for use with a Service Client.
- * Adds in deserializationPolicy by default.
- * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential.
- * @param options - Options to customize the created pipeline.
- */
-function createClientPipeline(options = {}) {
- const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options !== null && options !== void 0 ? options : {});
- if (options.credentialOptions) {
- pipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({
- credential: options.credentialOptions.credential,
- scopes: options.credentialOptions.credentialScopes,
- }));
- }
- pipeline.addPolicy((0, serializationPolicy_js_1.serializationPolicy)(options.serializationOptions), { phase: "Serialize" });
- pipeline.addPolicy((0, deserializationPolicy_js_1.deserializationPolicy)(options.deserializationOptions), {
- phase: "Deserialize",
});
- return pipeline;
+ });
}
-exports.createClientPipeline = createClientPipeline;
-//# sourceMappingURL=pipeline.js.map
-/***/ }),
+exports.blockDevices = blockDevices;
-/***/ 87054:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// FS - speed
+function calcFsSpeed(rx, wx) {
+ let result = {
+ rx: 0,
+ wx: 0,
+ tx: 0,
+ rx_sec: null,
+ wx_sec: null,
+ tx_sec: null,
+ ms: 0
+ };
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.serializeRequestBody = exports.serializeHeaders = exports.serializationPolicy = exports.serializationPolicyName = void 0;
-const interfaces_js_1 = __nccwpck_require__(35590);
-const operationHelpers_js_1 = __nccwpck_require__(17036);
-const serializer_js_1 = __nccwpck_require__(66774);
-const interfaceHelpers_js_1 = __nccwpck_require__(91030);
-/**
- * The programmatic identifier of the serializationPolicy.
- */
-exports.serializationPolicyName = "serializationPolicy";
-/**
- * This policy handles assembling the request body and headers using
- * an OperationSpec and OperationArguments on the request.
- */
-function serializationPolicy(options = {}) {
- const stringifyXML = options.stringifyXML;
- return {
- name: exports.serializationPolicyName,
- async sendRequest(request, next) {
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
- const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments;
- if (operationSpec && operationArguments) {
- serializeHeaders(request, operationArguments, operationSpec);
- serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);
- }
- return next(request);
- },
- };
+ if (_fs_speed && _fs_speed.ms) {
+ result.rx = rx;
+ result.wx = wx;
+ result.tx = result.rx + result.wx;
+ result.ms = Date.now() - _fs_speed.ms;
+ result.rx_sec = (result.rx - _fs_speed.bytes_read) / (result.ms / 1000);
+ result.wx_sec = (result.wx - _fs_speed.bytes_write) / (result.ms / 1000);
+ result.tx_sec = result.rx_sec + result.wx_sec;
+ _fs_speed.rx_sec = result.rx_sec;
+ _fs_speed.wx_sec = result.wx_sec;
+ _fs_speed.tx_sec = result.tx_sec;
+ _fs_speed.bytes_read = result.rx;
+ _fs_speed.bytes_write = result.wx;
+ _fs_speed.bytes_overall = result.rx + result.wx;
+ _fs_speed.ms = Date.now();
+ _fs_speed.last_ms = result.ms;
+ } else {
+ result.rx = rx;
+ result.wx = wx;
+ result.tx = result.rx + result.wx;
+ _fs_speed.rx_sec = null;
+ _fs_speed.wx_sec = null;
+ _fs_speed.tx_sec = null;
+ _fs_speed.bytes_read = result.rx;
+ _fs_speed.bytes_write = result.wx;
+ _fs_speed.bytes_overall = result.rx + result.wx;
+ _fs_speed.ms = Date.now();
+ _fs_speed.last_ms = 0;
+ }
+ return result;
}
-exports.serializationPolicy = serializationPolicy;
-/**
- * @internal
- */
-function serializeHeaders(request, operationArguments, operationSpec) {
- var _a, _b;
- if (operationSpec.headerParameters) {
- for (const headerParameter of operationSpec.headerParameters) {
- let headerValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, headerParameter);
- if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {
- headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter));
- const headerCollectionPrefix = headerParameter.mapper
- .headerCollectionPrefix;
- if (headerCollectionPrefix) {
- for (const key of Object.keys(headerValue)) {
- request.headers.set(headerCollectionPrefix + key, headerValue[key]);
+
+function fsStats(callback) {
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (_windows || _freebsd || _openbsd || _netbsd || _sunos) {
+ return resolve(null);
+ }
+
+ let result = {
+ rx: 0,
+ wx: 0,
+ tx: 0,
+ rx_sec: null,
+ wx_sec: null,
+ tx_sec: null,
+ ms: 0
+ };
+
+ let rx = 0;
+ let wx = 0;
+ if ((_fs_speed && !_fs_speed.ms) || (_fs_speed && _fs_speed.ms && Date.now() - _fs_speed.ms >= 500)) {
+ if (_linux) {
+ // exec("df -k | grep /dev/", function(error, stdout) {
+ exec('lsblk -r 2>/dev/null | grep /', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ let fs_filter = [];
+ lines.forEach(function (line) {
+ if (line !== '') {
+ line = line.trim().split(' ');
+ if (fs_filter.indexOf(line[0]) === -1) { fs_filter.push(line[0]); }
+ }
+ });
+
+ let output = fs_filter.join('|');
+ exec('cat /proc/diskstats | egrep "' + output + '"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ line = line.trim();
+ if (line !== '') {
+ line = line.replace(/ +/g, ' ').split(' ');
+
+ rx += parseInt(line[5]) * 512;
+ wx += parseInt(line[9]) * 512;
}
+ });
+ result = calcFsSpeed(rx, wx);
}
- else {
- request.headers.set(headerParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter), headerValue);
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ });
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
}
+ });
}
- }
- const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders;
- if (customHeaders) {
- for (const customHeaderName of Object.keys(customHeaders)) {
- request.headers.set(customHeaderName, customHeaders[customHeaderName]);
- }
- }
-}
-exports.serializeHeaders = serializeHeaders;
-/**
- * @internal
- */
-function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () {
- throw new Error("XML serialization unsupported!");
-}) {
- var _a, _b, _c, _d, _e;
- const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions;
- const updatedOptions = {
- xml: {
- rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "",
- includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false,
- xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : interfaces_js_1.XML_CHARKEY,
- },
- };
- const xmlCharKey = updatedOptions.xml.xmlCharKey;
- if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
- request.body = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, operationSpec.requestBody);
- const bodyMapper = operationSpec.requestBody.mapper;
- const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper;
- const typeName = bodyMapper.type.name;
- try {
- if ((request.body !== undefined && request.body !== null) ||
- (nullable && request.body === null) ||
- required) {
- const requestBodyParameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(operationSpec.requestBody);
- request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions);
- const isStream = typeName === serializer_js_1.MapperTypeNames.Stream;
- if (operationSpec.isXML) {
- const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
- const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions);
- if (typeName === serializer_js_1.MapperTypeNames.Sequence) {
- request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey });
- }
- else if (!isStream) {
- request.body = stringifyXML(value, {
- rootName: xmlName || serializedName,
- xmlCharKey,
- });
- }
- }
- else if (typeName === serializer_js_1.MapperTypeNames.String &&
- (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) {
- // the String serializer has validated that request body is a string
- // so just send the string.
- return;
- }
- else if (!isStream) {
- request.body = JSON.stringify(request.body);
+ if (_darwin) {
+ exec('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ line = line.trim();
+ if (line !== '') {
+ line = line.split(',');
+
+ rx += parseInt(line[2]);
+ wx += parseInt(line[9]);
}
+ });
+ result = calcFsSpeed(rx, wx);
}
- }
- catch (error) {
- throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`);
- }
- }
- else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
- request.formData = {};
- for (const formDataParameter of operationSpec.formDataParameters) {
- const formDataParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, formDataParameter);
- if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
- const formDataParameterPropertyName = formDataParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter);
- request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter), updatedOptions);
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ });
}
- }
-}
-exports.serializeRequestBody = serializeRequestBody;
-/**
- * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself
- */
-function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) {
- // Composite and Sequence schemas already got their root namespace set during serialization
- // We just need to add xmlns to the other schema types
- if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
- const result = {};
- result[options.xml.xmlCharKey] = serializedValue;
- result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
- return result;
- }
- return serializedValue;
+ } else {
+ result.ms = _fs_speed.last_ms;
+ result.rx = _fs_speed.bytes_read;
+ result.wx = _fs_speed.bytes_write;
+ result.tx = _fs_speed.bytes_read + _fs_speed.bytes_write;
+ result.rx_sec = _fs_speed.rx_sec;
+ result.wx_sec = _fs_speed.wx_sec;
+ result.tx_sec = _fs_speed.tx_sec;
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ });
+ });
}
-function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) {
- if (!Array.isArray(obj)) {
- obj = [obj];
- }
- if (!xmlNamespaceKey || !xmlNamespace) {
- return { [elementName]: obj };
- }
- const result = { [elementName]: obj };
- result[interfaces_js_1.XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
- return result;
+
+exports.fsStats = fsStats;
+
+function calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime) {
+ let result = {
+ rIO: 0,
+ wIO: 0,
+ tIO: 0,
+ rIO_sec: null,
+ wIO_sec: null,
+ tIO_sec: null,
+ rWaitTime: 0,
+ wWaitTime: 0,
+ tWaitTime: 0,
+ rWaitPercent: null,
+ wWaitPercent: null,
+ tWaitPercent: null,
+ ms: 0
+ };
+ if (_disk_io && _disk_io.ms) {
+ result.rIO = rIO;
+ result.wIO = wIO;
+ result.tIO = rIO + wIO;
+ result.ms = Date.now() - _disk_io.ms;
+ result.rIO_sec = (result.rIO - _disk_io.rIO) / (result.ms / 1000);
+ result.wIO_sec = (result.wIO - _disk_io.wIO) / (result.ms / 1000);
+ result.tIO_sec = result.rIO_sec + result.wIO_sec;
+ result.rWaitTime = rWaitTime;
+ result.wWaitTime = wWaitTime;
+ result.tWaitTime = tWaitTime;
+ result.rWaitPercent = (result.rWaitTime - _disk_io.rWaitTime) * 100 / (result.ms);
+ result.wWaitPercent = (result.wWaitTime - _disk_io.wWaitTime) * 100 / (result.ms);
+ result.tWaitPercent = (result.tWaitTime - _disk_io.tWaitTime) * 100 / (result.ms);
+ _disk_io.rIO = rIO;
+ _disk_io.wIO = wIO;
+ _disk_io.rIO_sec = result.rIO_sec;
+ _disk_io.wIO_sec = result.wIO_sec;
+ _disk_io.tIO_sec = result.tIO_sec;
+ _disk_io.rWaitTime = rWaitTime;
+ _disk_io.wWaitTime = wWaitTime;
+ _disk_io.tWaitTime = tWaitTime;
+ _disk_io.rWaitPercent = result.rWaitPercent;
+ _disk_io.wWaitPercent = result.wWaitPercent;
+ _disk_io.tWaitPercent = result.tWaitPercent;
+ _disk_io.last_ms = result.ms;
+ _disk_io.ms = Date.now();
+ } else {
+ result.rIO = rIO;
+ result.wIO = wIO;
+ result.tIO = rIO + wIO;
+ result.rWaitTime = rWaitTime;
+ result.wWaitTime = wWaitTime;
+ result.tWaitTime = tWaitTime;
+ _disk_io.rIO = rIO;
+ _disk_io.wIO = wIO;
+ _disk_io.rIO_sec = null;
+ _disk_io.wIO_sec = null;
+ _disk_io.tIO_sec = null;
+ _disk_io.rWaitTime = rWaitTime;
+ _disk_io.wWaitTime = wWaitTime;
+ _disk_io.tWaitTime = tWaitTime;
+ _disk_io.rWaitPercent = null;
+ _disk_io.wWaitPercent = null;
+ _disk_io.tWaitPercent = null;
+ _disk_io.last_ms = 0;
+ _disk_io.ms = Date.now();
+ }
+ return result;
}
-//# sourceMappingURL=serializationPolicy.js.map
-/***/ }),
+function disksIO(callback) {
-/***/ 66774:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (_windows) {
+ return resolve(null);
+ }
+ if (_sunos) {
+ return resolve(null);
+ }
+
+ let result = {
+ rIO: 0,
+ wIO: 0,
+ tIO: 0,
+ rIO_sec: null,
+ wIO_sec: null,
+ tIO_sec: null,
+ rWaitTime: 0,
+ wWaitTime: 0,
+ tWaitTime: 0,
+ rWaitPercent: null,
+ wWaitPercent: null,
+ tWaitPercent: null,
+ ms: 0
+ };
+ let rIO = 0;
+ let wIO = 0;
+ let rWaitTime = 0;
+ let wWaitTime = 0;
+ let tWaitTime = 0;
+ if ((_disk_io && !_disk_io.ms) || (_disk_io && _disk_io.ms && Date.now() - _disk_io.ms >= 500)) {
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ // prints Block layer statistics for all mounted volumes
+ // var cmd = "for mount in `lsblk | grep / | sed -r 's/│ └─//' | cut -d ' ' -f 1`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done";
+ // var cmd = "for mount in `lsblk | grep / | sed 's/[│└─├]//g' | awk '{$1=$1};1' | cut -d ' ' -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done";
+ let cmd = 'for mount in `lsblk 2>/dev/null | grep " disk " | sed "s/[│└─├]//g" | awk \'{$1=$1};1\' | cut -d " " -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r "s/ +/;/g" | sed -r "s/^;//"; done';
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.MapperTypeNames = exports.createSerializer = void 0;
-const tslib_1 = __nccwpck_require__(94176);
-const base64 = tslib_1.__importStar(__nccwpck_require__(59793));
-const interfaces_js_1 = __nccwpck_require__(35590);
-const utils_js_1 = __nccwpck_require__(7805);
-class SerializerImpl {
- constructor(modelMappers = {}, isXML = false) {
- this.modelMappers = modelMappers;
- this.isXML = isXML;
- }
- /**
- * @deprecated Removing the constraints validation on client side.
- */
- validateConstraints(mapper, value, objectName) {
- const failValidation = (constraintName, constraintValue) => {
- throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`);
- };
- if (mapper.constraints && value !== undefined && value !== null) {
- const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints;
- if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {
- failValidation("ExclusiveMaximum", ExclusiveMaximum);
- }
- if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {
- failValidation("ExclusiveMinimum", ExclusiveMinimum);
- }
- if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {
- failValidation("InclusiveMaximum", InclusiveMaximum);
- }
- if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {
- failValidation("InclusiveMinimum", InclusiveMinimum);
- }
- if (MaxItems !== undefined && value.length > MaxItems) {
- failValidation("MaxItems", MaxItems);
- }
- if (MaxLength !== undefined && value.length > MaxLength) {
- failValidation("MaxLength", MaxLength);
- }
- if (MinItems !== undefined && value.length < MinItems) {
- failValidation("MinItems", MinItems);
- }
- if (MinLength !== undefined && value.length < MinLength) {
- failValidation("MinLength", MinLength);
- }
- if (MultipleOf !== undefined && value % MultipleOf !== 0) {
- failValidation("MultipleOf", MultipleOf);
+ exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.split('\n');
+ lines.forEach(function (line) {
+ // ignore empty lines
+ if (!line) { return; }
+
+ // sum r/wIO of all disks to compute all disks IO
+ let stats = line.split(';');
+ rIO += parseInt(stats[0]);
+ wIO += parseInt(stats[4]);
+ rWaitTime += parseInt(stats[3]);
+ wWaitTime += parseInt(stats[7]);
+ tWaitTime += parseInt(stats[10]);
+ });
+ result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime);
+
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
}
- if (Pattern) {
- const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
- if (typeof value !== "string" || value.match(pattern) === null) {
- failValidation("Pattern", Pattern);
+ });
+ }
+ if (_darwin) {
+ exec('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ line = line.trim();
+ if (line !== '') {
+ line = line.split(',');
+
+ rIO += parseInt(line[10]);
+ wIO += parseInt(line[0]);
}
+ });
+ result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime);
}
- if (UniqueItems &&
- value.some((item, i, ar) => ar.indexOf(item) !== i)) {
- failValidation("UniqueItems", UniqueItems);
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ });
}
- }
- /**
- * Serialize the given object based on its metadata defined in the mapper
- *
- * @param mapper - The mapper which defines the metadata of the serializable object
- *
- * @param object - A valid Javascript object to be serialized
- *
- * @param objectName - Name of the serialized object
- *
- * @param options - additional options to serialization
- *
- * @returns A valid serialized Javascript object
- */
- serialize(mapper, object, objectName, options = { xml: {} }) {
- var _a, _b, _c;
- const updatedOptions = {
- xml: {
- rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
- includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
- xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
- },
- };
- let payload = {};
- const mapperType = mapper.type.name;
- if (!objectName) {
- objectName = mapper.serializedName;
- }
- if (mapperType.match(/^Sequence$/i) !== null) {
- payload = [];
- }
- if (mapper.isConstant) {
- object = mapper.defaultValue;
- }
- // This table of allowed values should help explain
- // the mapper.required and mapper.nullable properties.
- // X means "neither undefined or null are allowed".
- // || required
- // || true | false
- // nullable || ==========================
- // true || null | undefined/null
- // false || X | undefined
- // undefined || X | undefined/null
- const { required, nullable } = mapper;
- if (required && nullable && object === undefined) {
- throw new Error(`${objectName} cannot be undefined.`);
- }
- if (required && !nullable && (object === undefined || object === null)) {
- throw new Error(`${objectName} cannot be null or undefined.`);
- }
- if (!required && nullable === false && object === null) {
- throw new Error(`${objectName} cannot be null.`);
- }
- if (object === undefined || object === null) {
- payload = object;
- }
- else {
- if (mapperType.match(/^any$/i) !== null) {
- payload = object;
- }
- else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
- payload = serializeBasicTypes(mapperType, objectName, object);
- }
- else if (mapperType.match(/^Enum$/i) !== null) {
- const enumMapper = mapper;
- payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
- }
- else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
- payload = serializeDateTypes(mapperType, object, objectName);
- }
- else if (mapperType.match(/^ByteArray$/i) !== null) {
- payload = serializeByteArrayType(objectName, object);
- }
- else if (mapperType.match(/^Base64Url$/i) !== null) {
- payload = serializeBase64UrlType(objectName, object);
- }
- else if (mapperType.match(/^Sequence$/i) !== null) {
- payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
- else if (mapperType.match(/^Dictionary$/i) !== null) {
- payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
- else if (mapperType.match(/^Composite$/i) !== null) {
- payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
+ } else {
+ result.rIO = _disk_io.rIO;
+ result.wIO = _disk_io.wIO;
+ result.tIO = _disk_io.rIO + _disk_io.wIO;
+ result.ms = _disk_io.last_ms;
+ result.rIO_sec = _disk_io.rIO_sec;
+ result.wIO_sec = _disk_io.wIO_sec;
+ result.tIO_sec = _disk_io.tIO_sec;
+ result.rWaitTime = _disk_io.rWaitTime;
+ result.wWaitTime = _disk_io.wWaitTime;
+ result.tWaitTime = _disk_io.tWaitTime;
+ result.rWaitPercent = _disk_io.rWaitPercent;
+ result.wWaitPercent = _disk_io.wWaitPercent;
+ result.tWaitPercent = _disk_io.tWaitPercent;
+ if (callback) {
+ callback(result);
}
- return payload;
+ resolve(result);
+ }
+ });
+ });
+}
+
+exports.disksIO = disksIO;
+
+function diskLayout(callback) {
+
+ function getVendorFromModel(model) {
+ const diskManufacturers = [
+ { pattern: 'WESTERN.*', manufacturer: 'Western Digital' },
+ { pattern: '^WDC.*', manufacturer: 'Western Digital' },
+ { pattern: 'WD.*', manufacturer: 'Western Digital' },
+ { pattern: 'TOSHIBA.*', manufacturer: 'Toshiba' },
+ { pattern: 'HITACHI.*', manufacturer: 'Hitachi' },
+ { pattern: '^IC.*', manufacturer: 'Hitachi' },
+ { pattern: '^HTS.*', manufacturer: 'Hitachi' },
+ { pattern: 'SANDISK.*', manufacturer: 'SanDisk' },
+ { pattern: 'KINGSTON.*', manufacturer: 'Kingston Technology' },
+ { pattern: '^SONY.*', manufacturer: 'Sony' },
+ { pattern: 'TRANSCEND.*', manufacturer: 'Transcend' },
+ { pattern: 'SAMSUNG.*', manufacturer: 'Samsung' },
+ { pattern: '^ST(?!I\\ ).*', manufacturer: 'Seagate' },
+ { pattern: '^STI\\ .*', manufacturer: 'SimpleTech' },
+ { pattern: '^D...-.*', manufacturer: 'IBM' },
+ { pattern: '^IBM.*', manufacturer: 'IBM' },
+ { pattern: '^FUJITSU.*', manufacturer: 'Fujitsu' },
+ { pattern: '^MP.*', manufacturer: 'Fujitsu' },
+ { pattern: '^MK.*', manufacturer: 'Toshiba' },
+ { pattern: 'MAXTO.*', manufacturer: 'Maxtor' },
+ { pattern: 'PIONEER.*', manufacturer: 'Pioneer' },
+ { pattern: 'PHILIPS.*', manufacturer: 'Philips' },
+ { pattern: 'QUANTUM.*', manufacturer: 'Quantum Technology' },
+ { pattern: 'FIREBALL.*', manufacturer: 'Quantum Technology' },
+ { pattern: '^VBOX.*', manufacturer: 'VirtualBox' },
+ { pattern: 'CORSAIR.*', manufacturer: 'Corsair Components' },
+ { pattern: 'CRUCIAL.*', manufacturer: 'Crucial' },
+ { pattern: 'ECM.*', manufacturer: 'ECM' },
+ { pattern: 'INTEL.*', manufacturer: 'INTEL' },
+ { pattern: 'EVO.*', manufacturer: 'Samsung' },
+ { pattern: 'APPLE.*', manufacturer: 'Apple' },
+ ];
+
+ let result = '';
+ if (model) {
+ model = model.toUpperCase();
+ diskManufacturers.forEach((manufacturer) => {
+ const re = RegExp(manufacturer.pattern);
+ if (re.test(model)) { result = manufacturer.manufacturer; }
+ });
}
- /**
- * Deserialize the given object based on its metadata defined in the mapper
- *
- * @param mapper - The mapper which defines the metadata of the serializable object
- *
- * @param responseBody - A valid Javascript entity to be deserialized
- *
- * @param objectName - Name of the deserialized object
- *
- * @param options - Controls behavior of XML parser and builder.
- *
- * @returns A valid deserialized Javascript object
- */
- deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
- var _a, _b, _c, _d;
- const updatedOptions = {
- xml: {
- rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
- includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
- xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
- },
- ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false,
- };
- if (responseBody === undefined || responseBody === null) {
- if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
- // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
- // between the list being empty versus being missing,
- // so let's do the more user-friendly thing and return an empty list.
- responseBody = [];
- }
- // specifically check for undefined as default value can be a falsey value `0, "", false, null`
- if (mapper.defaultValue !== undefined) {
- responseBody = mapper.defaultValue;
- }
- return responseBody;
- }
- let payload;
- const mapperType = mapper.type.name;
- if (!objectName) {
- objectName = mapper.serializedName;
+ return result;
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+
+ const commitResult = res => {
+ for (let i = 0; i < res.length; i++) {
+ delete res[i].BSDName;
}
- if (mapperType.match(/^Composite$/i) !== null) {
- payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions);
+ if (callback) {
+ callback(res);
}
- else {
- if (this.isXML) {
- const xmlCharKey = updatedOptions.xml.xmlCharKey;
- /**
- * If the mapper specifies this as a non-composite type value but the responseBody contains
- * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties,
- * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property.
- */
- if (responseBody[interfaces_js_1.XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {
- responseBody = responseBody[xmlCharKey];
- }
- }
- if (mapperType.match(/^Number$/i) !== null) {
- payload = parseFloat(responseBody);
- if (isNaN(payload)) {
- payload = responseBody;
+ resolve(res);
+ };
+
+ let result = [];
+ let cmd = '';
+
+ if (_linux) {
+ let cmdFullSmart = '';
+
+ exec('export LC_ALL=C; lsblk -ablJO 2>/dev/null; unset LC_ALL', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ try {
+ const out = stdout.toString().trim();
+ let devices = [];
+ try {
+ const outJSON = JSON.parse(out);
+ if (outJSON && {}.hasOwnProperty.call(outJSON, 'blockdevices')) {
+ devices = outJSON.blockdevices.filter(item => { return (item.type === 'disk') && item.size > 0 && (item.model !== null || (item.mountpoint === null && item.label === null && item.fstype === null && item.parttype === null && item.path && item.path.indexOf('/ram') !== 0 && item.path.indexOf('/loop') !== 0 && item['disc-max'] && item['disc-max'] !== 0)); });
}
- }
- else if (mapperType.match(/^Boolean$/i) !== null) {
- if (responseBody === "true") {
- payload = true;
+ } catch (e) {
+ // fallback to older version of lsblk
+ try {
+ const out2 = execSync('export LC_ALL=C; lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER,GROUP 2>/dev/null; unset LC_ALL', util.execOptsLinux).toString();
+ let lines = blkStdoutToObject(out2).split('\n');
+ const data = parseBlk(lines);
+ devices = data.filter(item => { return (item.type === 'disk') && item.size > 0 && ((item.model !== null && item.model !== '') || (item.mount === '' && item.label === '' && item.fsType === '')); });
+ } catch (e) {
+ util.noop();
}
- else if (responseBody === "false") {
- payload = false;
+ }
+ devices.forEach((device) => {
+ let mediumType = '';
+ const BSDName = '/dev/' + device.name;
+ const logical = device.name;
+ try {
+ mediumType = execSync('cat /sys/block/' + logical + '/queue/rotational 2>/dev/null', util.execOptsLinux).toString().split('\n')[0];
+ } catch (e) {
+ util.noop();
}
- else {
- payload = responseBody;
+ let interfaceType = device.tran ? device.tran.toUpperCase().trim() : '';
+ if (interfaceType === 'NVME') {
+ mediumType = '2';
+ interfaceType = 'PCIe';
}
+ result.push({
+ device: BSDName,
+ type: (mediumType === '0' ? 'SSD' : (mediumType === '1' ? 'HD' : (mediumType === '2' ? 'NVMe' : (device.model && device.model.indexOf('SSD') > -1 ? 'SSD' : (device.model && device.model.indexOf('NVM') > -1 ? 'NVMe' : 'HD'))))),
+ name: device.model || '',
+ vendor: getVendorFromModel(device.model) || (device.vendor ? device.vendor.trim() : ''),
+ size: device.size || 0,
+ bytesPerSector: null,
+ totalCylinders: null,
+ totalHeads: null,
+ totalSectors: null,
+ totalTracks: null,
+ tracksPerCylinder: null,
+ sectorsPerTrack: null,
+ firmwareRevision: device.rev ? device.rev.trim() : '',
+ serialNum: device.serial ? device.serial.trim() : '',
+ interfaceType: interfaceType,
+ smartStatus: 'unknown',
+ temperature: null,
+ BSDName: BSDName
+ });
+ cmd += `printf "\n${BSDName}|"; smartctl -H ${BSDName} | grep overall;`;
+ cmdFullSmart += `${cmdFullSmart ? 'printf ",";' : ''}smartctl -a -j ${BSDName};`;
+ });
+ } catch (e) {
+ util.noop();
}
- else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
- payload = responseBody;
- }
- else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
- payload = new Date(responseBody);
- }
- else if (mapperType.match(/^UnixTime$/i) !== null) {
- payload = unixTimeToDate(responseBody);
- }
- else if (mapperType.match(/^ByteArray$/i) !== null) {
- payload = base64.decodeString(responseBody);
- }
- else if (mapperType.match(/^Base64Url$/i) !== null) {
- payload = base64UrlToByteArray(responseBody);
- }
- else if (mapperType.match(/^Sequence$/i) !== null) {
- payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions);
- }
- else if (mapperType.match(/^Dictionary$/i) !== null) {
- payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions);
- }
- }
- if (mapper.isConstant) {
- payload = mapper.defaultValue;
- }
- return payload;
- }
-}
-/**
- * Method that creates and returns a Serializer.
- * @param modelMappers - Known models to map
- * @param isXML - If XML should be supported
- */
-function createSerializer(modelMappers = {}, isXML = false) {
- return new SerializerImpl(modelMappers, isXML);
-}
-exports.createSerializer = createSerializer;
-function trimEnd(str, ch) {
- let len = str.length;
- while (len - 1 >= 0 && str[len - 1] === ch) {
- --len;
- }
- return str.substr(0, len);
-}
-function bufferToBase64Url(buffer) {
- if (!buffer) {
- return undefined;
- }
- if (!(buffer instanceof Uint8Array)) {
- throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
- }
- // Uint8Array to Base64.
- const str = base64.encodeByteArray(buffer);
- // Base64 to Base64Url.
- return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
-}
-function base64UrlToByteArray(str) {
- if (!str) {
- return undefined;
- }
- if (str && typeof str.valueOf() !== "string") {
- throw new Error("Please provide an input of type string for converting to Uint8Array");
- }
- // Base64Url to Base64.
- str = str.replace(/-/g, "+").replace(/_/g, "/");
- // Base64 to Uint8Array.
- return base64.decodeString(str);
-}
-function splitSerializeName(prop) {
- const classes = [];
- let partialclass = "";
- if (prop) {
- const subwords = prop.split(".");
- for (const item of subwords) {
- if (item.charAt(item.length - 1) === "\\") {
- partialclass += item.substr(0, item.length - 1) + ".";
+ }
+ // check S.M.A.R.T. status
+ if (cmdFullSmart) {
+ exec(cmdFullSmart, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ try {
+ const data = JSON.parse(`[${stdout}]`);
+ data.forEach(disk => {
+ const diskBSDName = disk.smartctl.argv[disk.smartctl.argv.length - 1];
+
+ for (let i = 0; i < result.length; i++) {
+ if (result[i].BSDName === diskBSDName) {
+ result[i].smartStatus = (disk.smart_status.passed ? 'Ok' : (disk.smart_status.passed === false ? 'Predicted Failure' : 'unknown'));
+ if (disk.temperature && disk.temperature.current) {
+ result[i].temperature = disk.temperature.current;
+ }
+ result[i].smartData = disk;
+ }
+ }
+ });
+ commitResult(result);
+ } catch (e) {
+ if (cmd) {
+ cmd = cmd + 'printf "\n"';
+ exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(line => {
+ if (line) {
+ let parts = line.split('|');
+ if (parts.length === 2) {
+ let BSDName = parts[0];
+ parts[1] = parts[1].trim();
+ let parts2 = parts[1].split(':');
+ if (parts2.length === 2) {
+ parts2[1] = parts2[1].trim();
+ let status = parts2[1].toLowerCase();
+ for (let i = 0; i < result.length; i++) {
+ if (result[i].BSDName === BSDName) {
+ result[i].smartStatus = (status === 'passed' ? 'Ok' : (status === 'failed!' ? 'Predicted Failure' : 'unknown'));
+ }
+ }
+ }
+ }
+ }
+ });
+ commitResult(result);
+ });
+ } else {
+ commitResult(result);
+ }
+ }
+ });
+ } else {
+ commitResult(result);
+ }
+ });
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_darwin) {
+ exec('system_profiler SPSerialATADataType SPNVMeDataType SPUSBDataType', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ // split by type:
+ let lines = stdout.toString().split('\n');
+ let linesSATA = [];
+ let linesNVMe = [];
+ let linesUSB = [];
+ let dataType = 'SATA';
+ lines.forEach(line => {
+ if (line === 'NVMExpress:') { dataType = 'NVMe'; }
+ else if (line === 'USB:') { dataType = 'USB'; }
+ else if (line === 'SATA/SATA Express:') { dataType = 'SATA'; }
+ else if (dataType === 'SATA') { linesSATA.push(line); }
+ else if (dataType === 'NVMe') { linesNVMe.push(line); }
+ else if (dataType === 'USB') { linesUSB.push(line); }
+ });
+ try {
+ // Serial ATA Drives
+ let devices = linesSATA.join('\n').split(' Physical Interconnect: ');
+ devices.shift();
+ devices.forEach(function (device) {
+ device = 'InterfaceType: ' + device;
+ let lines = device.split('\n');
+ const mediumType = util.getValue(lines, 'Medium Type', ':', true).trim();
+ const sizeStr = util.getValue(lines, 'capacity', ':', true).trim();
+ const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
+ if (sizeStr) {
+ let sizeValue = 0;
+ if (sizeStr.indexOf('(') >= 0) {
+ sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
+ }
+ if (!sizeValue) {
+ sizeValue = parseInt(sizeStr);
+ }
+ if (sizeValue) {
+ const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
+ result.push({
+ device: BSDName,
+ type: mediumType.startsWith('Solid') ? 'SSD' : 'HD',
+ name: util.getValue(lines, 'Model', ':', true).trim(),
+ vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()) || util.getValue(lines, 'Manufacturer', ':', true),
+ size: sizeValue,
+ bytesPerSector: null,
+ totalCylinders: null,
+ totalHeads: null,
+ totalSectors: null,
+ totalTracks: null,
+ tracksPerCylinder: null,
+ sectorsPerTrack: null,
+ firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
+ serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
+ interfaceType: util.getValue(lines, 'InterfaceType', ':', true).trim(),
+ smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
+ temperature: null,
+ BSDName: BSDName
+ });
+ cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
+ }
+ }
+ });
+ } catch (e) {
+ util.noop();
}
- else {
- partialclass += item;
- classes.push(partialclass);
- partialclass = "";
+
+ // NVME Drives
+ try {
+ let devices = linesNVMe.join('\n').split('\n\n Capacity:');
+ devices.shift();
+ devices.forEach(function (device) {
+ device = '!Capacity: ' + device;
+ let lines = device.split('\n');
+ const linkWidth = util.getValue(lines, 'link width', ':', true).trim();
+ const sizeStr = util.getValue(lines, '!capacity', ':', true).trim();
+ const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
+ if (sizeStr) {
+ let sizeValue = 0;
+ if (sizeStr.indexOf('(') >= 0) {
+ sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
+ }
+ if (!sizeValue) {
+ sizeValue = parseInt(sizeStr);
+ }
+ if (sizeValue) {
+ const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
+ result.push({
+ device: BSDName,
+ type: 'NVMe',
+ name: util.getValue(lines, 'Model', ':', true).trim(),
+ vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()),
+ size: sizeValue,
+ bytesPerSector: null,
+ totalCylinders: null,
+ totalHeads: null,
+ totalSectors: null,
+ totalTracks: null,
+ tracksPerCylinder: null,
+ sectorsPerTrack: null,
+ firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
+ serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
+ interfaceType: ('PCIe ' + linkWidth).trim(),
+ smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
+ temperature: null,
+ BSDName: BSDName
+ });
+ cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
+ }
+ }
+ });
+ } catch (e) {
+ util.noop();
}
- }
- }
- return classes;
-}
-function dateToUnixTime(d) {
- if (!d) {
- return undefined;
- }
- if (typeof d.valueOf() === "string") {
- d = new Date(d);
- }
- return Math.floor(d.getTime() / 1000);
-}
-function unixTimeToDate(n) {
- if (!n) {
- return undefined;
- }
- return new Date(n * 1000);
-}
-function serializeBasicTypes(typeName, objectName, value) {
- if (value !== null && value !== undefined) {
- if (typeName.match(/^Number$/i) !== null) {
- if (typeof value !== "number") {
- throw new Error(`${objectName} with value ${value} must be of type number.`);
+ // USB Drives
+ try {
+ let devices = linesUSB.join('\n').replaceAll('Media:\n ', 'Model:').split('\n\n Product ID:');
+ devices.shift();
+ devices.forEach(function (device) {
+ let lines = device.split('\n');
+ const sizeStr = util.getValue(lines, 'Capacity', ':', true).trim();
+ const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
+ if (sizeStr) {
+ let sizeValue = 0;
+ if (sizeStr.indexOf('(') >= 0) {
+ sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
+ }
+ if (!sizeValue) {
+ sizeValue = parseInt(sizeStr);
+ }
+ if (sizeValue) {
+ const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
+ result.push({
+ device: BSDName,
+ type: 'USB',
+ name: util.getValue(lines, 'Model', ':', true).trim().replaceAll(':', ''),
+ vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()),
+ size: sizeValue,
+ bytesPerSector: null,
+ totalCylinders: null,
+ totalHeads: null,
+ totalSectors: null,
+ totalTracks: null,
+ tracksPerCylinder: null,
+ sectorsPerTrack: null,
+ firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
+ serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
+ interfaceType: 'USB',
+ smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
+ temperature: null,
+ BSDName: BSDName
+ });
+ cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
+ }
+ }
+ });
+ } catch (e) {
+ util.noop();
}
- }
- else if (typeName.match(/^String$/i) !== null) {
- if (typeof value.valueOf() !== "string") {
- throw new Error(`${objectName} with value "${value}" must be of type string.`);
+ if (cmd) {
+ cmd = cmd + 'printf "\n"';
+ exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(line => {
+ if (line) {
+ let parts = line.split('|');
+ if (parts.length === 2) {
+ let BSDName = parts[0];
+ parts[1] = parts[1].trim();
+ let parts2 = parts[1].split(':');
+ if (parts2.length === 2) {
+ parts2[1] = parts2[1].trim();
+ let status = parts2[1].toLowerCase();
+ for (let i = 0; i < result.length; i++) {
+ if (result[i].BSDName === BSDName) {
+ result[i].smartStatus = (status === 'not supported' ? 'not supported' : (status === 'verified' ? 'Ok' : (status === 'failing' ? 'Predicted Failure' : 'unknown')));
+ }
+ }
+ }
+ }
+ }
+ });
+ for (let i = 0; i < result.length; i++) {
+ delete result[i].BSDName;
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } else {
+ for (let i = 0; i < result.length; i++) {
+ delete result[i].BSDName;
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
}
- }
- else if (typeName.match(/^Uuid$/i) !== null) {
- if (!(typeof value.valueOf() === "string" && (0, utils_js_1.isValidUuid)(value))) {
- throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`);
+ }
+ });
+ }
+ if (_windows) {
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance Win32_DiskDrive | select Caption,Size,Status,PNPDeviceId,DeviceId,BytesPerSector,TotalCylinders,TotalHeads,TotalSectors,TotalTracks,TracksPerCylinder,SectorsPerTrack,FirmwareRevision,SerialNumber,InterfaceType | fl'));
+ workload.push(util.powerShell('Get-PhysicalDisk | select BusType,MediaType,FriendlyName,Model,SerialNumber,Size | fl'));
+ if (util.smartMonToolsInstalled()) {
+ try {
+ const smartDev = JSON.parse(execSync('smartctl --scan -j').toString());
+ if (smartDev && smartDev.devices && smartDev.devices.length > 0) {
+ smartDev.devices.forEach((dev) => {
+ workload.push(execPromiseSave(`smartctl -j -a ${dev.name}`, util.execOptsWin));
+ });
+ }
+ } catch (e) {
+ util.noop();
}
- }
- else if (typeName.match(/^Boolean$/i) !== null) {
- if (typeof value !== "boolean") {
- throw new Error(`${objectName} with value ${value} must be of type boolean.`);
+ }
+ util.promiseAll(
+ workload
+ ).then((data) => {
+ let devices = data.results[0].toString().split(/\n\s*\n/);
+ devices.forEach(function (device) {
+ let lines = device.split('\r\n');
+ const size = util.getValue(lines, 'Size', ':').trim();
+ const status = util.getValue(lines, 'Status', ':').trim().toLowerCase();
+ if (size) {
+ result.push({
+ device: util.getValue(lines, 'DeviceId', ':'), // changed from PNPDeviceId to DeviceID (be be able to match devices)
+ type: device.indexOf('SSD') > -1 ? 'SSD' : 'HD', // just a starting point ... better: MSFT_PhysicalDisk - Media Type ... see below
+ name: util.getValue(lines, 'Caption', ':'),
+ vendor: getVendorFromModel(util.getValue(lines, 'Caption', ':', true).trim()),
+ size: parseInt(size),
+ bytesPerSector: parseInt(util.getValue(lines, 'BytesPerSector', ':')),
+ totalCylinders: parseInt(util.getValue(lines, 'TotalCylinders', ':')),
+ totalHeads: parseInt(util.getValue(lines, 'TotalHeads', ':')),
+ totalSectors: parseInt(util.getValue(lines, 'TotalSectors', ':')),
+ totalTracks: parseInt(util.getValue(lines, 'TotalTracks', ':')),
+ tracksPerCylinder: parseInt(util.getValue(lines, 'TracksPerCylinder', ':')),
+ sectorsPerTrack: parseInt(util.getValue(lines, 'SectorsPerTrack', ':')),
+ firmwareRevision: util.getValue(lines, 'FirmwareRevision', ':').trim(),
+ serialNum: util.getValue(lines, 'SerialNumber', ':').trim(),
+ interfaceType: util.getValue(lines, 'InterfaceType', ':').trim(),
+ smartStatus: (status === 'ok' ? 'Ok' : (status === 'degraded' ? 'Degraded' : (status === 'pred fail' ? 'Predicted Failure' : 'Unknown'))),
+ temperature: null,
+ });
+ }
+ });
+ devices = data.results[1].split(/\n\s*\n/);
+ devices.forEach(function (device) {
+ let lines = device.split('\r\n');
+ const serialNum = util.getValue(lines, 'SerialNumber', ':').trim();
+ const name = util.getValue(lines, 'FriendlyName', ':').trim().replace('Msft ', 'Microsoft');
+ const size = util.getValue(lines, 'Size', ':').trim();
+ const model = util.getValue(lines, 'Model', ':').trim();
+ const interfaceType = util.getValue(lines, 'BusType', ':').trim();
+ let mediaType = util.getValue(lines, 'MediaType', ':').trim();
+ if (mediaType === '3' || mediaType === 'HDD') { mediaType = 'HD'; }
+ if (mediaType === '4') { mediaType = 'SSD'; }
+ if (mediaType === '5') { mediaType = 'SCM'; }
+ if (mediaType === 'Unspecified' && (model.toLowerCase().indexOf('virtual') > -1 || model.toLowerCase().indexOf('vbox') > -1)) { mediaType = 'Virtual'; }
+ if (size) {
+ let i = util.findObjectByKey(result, 'serialNum', serialNum);
+ if (i === -1 || serialNum === '') {
+ i = util.findObjectByKey(result, 'name', name);
+ }
+ if (i != -1) {
+ result[i].type = mediaType;
+ result[i].interfaceType = interfaceType;
+ }
+ }
+ });
+ // S.M.A.R.T
+ data.results.shift();
+ data.results.shift();
+ if (data.results.length) {
+ data.results.forEach((smartStr) => {
+ try {
+ const smartData = JSON.parse(smartStr);
+ if (smartData.serial_number) {
+ const serialNum = smartData.serial_number;
+ let i = util.findObjectByKey(result, 'serialNum', serialNum);
+ if (i != -1) {
+ result[i].smartStatus = (smartData.smart_status && smartData.smart_status.passed ? 'Ok' : (smartData.smart_status && smartData.smart_status.passed === false ? 'Predicted Failure' : 'unknown'));
+ if (smartData.temperature && smartData.temperature.current) {
+ result[i].temperature = smartData.temperature.current;
+ }
+ result[i].smartData = smartData;
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
+ });
}
- }
- else if (typeName.match(/^Stream$/i) !== null) {
- const objectType = typeof value;
- if (objectType !== "string" &&
- typeof value.pipe !== "function" && // NodeJS.ReadableStream
- typeof value.tee !== "function" && // browser ReadableStream
- !(value instanceof ArrayBuffer) &&
- !ArrayBuffer.isView(value) &&
- // File objects count as a type of Blob, so we want to use instanceof explicitly
- !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) &&
- objectType !== "function") {
- throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`);
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- }
- return value;
+ }
+ });
+ });
}
-function serializeEnumType(objectName, allowedValues, value) {
- if (!allowedValues) {
- throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);
- }
- const isPresent = allowedValues.some((item) => {
- if (typeof item.valueOf() === "string") {
- return item.toLowerCase() === value.toLowerCase();
- }
- return item === value;
+
+exports.diskLayout = diskLayout;
+
+
+/***/ }),
+
+/***/ 64293:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+
+// @ts-check
+// ==================================================================================
+// graphics.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 7. Graphics (controller, display)
+// ----------------------------------------------------------------------------------
+
+const fs = __nccwpck_require__(79896);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const util = __nccwpck_require__(77496);
+
+let _platform = process.platform;
+let _nvidiaSmiPath = '';
+
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+
+let _resolutionX = 0;
+let _resolutionY = 0;
+let _pixelDepth = 0;
+let _refreshRate = 0;
+
+const videoTypes = {
+ '-2': 'UNINITIALIZED',
+ '-1': 'OTHER',
+ '0': 'HD15',
+ '1': 'SVIDEO',
+ '2': 'Composite video',
+ '3': 'Component video',
+ '4': 'DVI',
+ '5': 'HDMI',
+ '6': 'LVDS',
+ '8': 'D_JPN',
+ '9': 'SDI',
+ '10': 'DP',
+ '11': 'DP embedded',
+ '12': 'UDI',
+ '13': 'UDI embedded',
+ '14': 'SDTVDONGLE',
+ '15': 'MIRACAST',
+ '2147483648': 'INTERNAL'
+};
+
+function getVendorFromModel(model) {
+ const manufacturers = [
+ { pattern: '^LG.+', manufacturer: 'LG' },
+ { pattern: '^BENQ.+', manufacturer: 'BenQ' },
+ { pattern: '^ASUS.+', manufacturer: 'Asus' },
+ { pattern: '^DELL.+', manufacturer: 'Dell' },
+ { pattern: '^SAMSUNG.+', manufacturer: 'Samsung' },
+ { pattern: '^VIEWSON.+', manufacturer: 'ViewSonic' },
+ { pattern: '^SONY.+', manufacturer: 'Sony' },
+ { pattern: '^ACER.+', manufacturer: 'Acer' },
+ { pattern: '^AOC.+', manufacturer: 'AOC Monitors' },
+ { pattern: '^HP.+', manufacturer: 'HP' },
+ { pattern: '^EIZO.?', manufacturer: 'Eizo' },
+ { pattern: '^PHILIPS.?', manufacturer: 'Philips' },
+ { pattern: '^IIYAMA.?', manufacturer: 'Iiyama' },
+ { pattern: '^SHARP.?', manufacturer: 'Sharp' },
+ { pattern: '^NEC.?', manufacturer: 'NEC' },
+ { pattern: '^LENOVO.?', manufacturer: 'Lenovo' },
+ { pattern: 'COMPAQ.?', manufacturer: 'Compaq' },
+ { pattern: 'APPLE.?', manufacturer: 'Apple' },
+ { pattern: 'INTEL.?', manufacturer: 'Intel' },
+ { pattern: 'AMD.?', manufacturer: 'AMD' },
+ { pattern: 'NVIDIA.?', manufacturer: 'NVDIA' },
+ ];
+
+ let result = '';
+ if (model) {
+ model = model.toUpperCase();
+ manufacturers.forEach((manufacturer) => {
+ const re = RegExp(manufacturer.pattern);
+ if (re.test(model)) { result = manufacturer.manufacturer; }
});
- if (!isPresent) {
- throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`);
- }
- return value;
+ }
+ return result;
}
-function serializeByteArrayType(objectName, value) {
- if (value !== undefined && value !== null) {
- if (!(value instanceof Uint8Array)) {
- throw new Error(`${objectName} must be of type Uint8Array.`);
- }
- value = base64.encodeByteArray(value);
- }
- return value;
+
+function getVendorFromId(id) {
+ const vendors = {
+ '610': 'Apple',
+ '1e6d': 'LG',
+ '10ac': 'DELL',
+ '4dd9': 'Sony',
+ '38a3': 'NEC',
+ };
+ return vendors[id] || '';
}
-function serializeBase64UrlType(objectName, value) {
- if (value !== undefined && value !== null) {
- if (!(value instanceof Uint8Array)) {
- throw new Error(`${objectName} must be of type Uint8Array.`);
- }
- value = bufferToBase64Url(value);
- }
- return value;
+
+function vendorToId(str) {
+ let result = '';
+ str = (str || '').toLowerCase();
+ if (str.indexOf('apple') >= 0) { result = '0x05ac'; }
+ else if (str.indexOf('nvidia') >= 0) { result = '0x10de'; }
+ else if (str.indexOf('intel') >= 0) { result = '0x8086'; }
+ else if (str.indexOf('ati') >= 0 || str.indexOf('amd') >= 0) { result = '0x1002'; }
+
+ return result;
}
-function serializeDateTypes(typeName, value, objectName) {
- if (value !== undefined && value !== null) {
- if (typeName.match(/^Date$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
- }
- value =
- value instanceof Date
- ? value.toISOString().substring(0, 10)
- : new Date(value).toISOString().substring(0, 10);
- }
- else if (typeName.match(/^DateTime$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
- }
- value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
- }
- else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
- }
- value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
- }
- else if (typeName.match(/^UnixTime$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +
- `for it to be serialized in UnixTime/Epoch format.`);
- }
- value = dateToUnixTime(value);
- }
- else if (typeName.match(/^TimeSpan$/i) !== null) {
- if (!(0, utils_js_1.isDuration)(value)) {
- throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`);
- }
- }
- }
- return value;
+
+function getMetalVersion(id) {
+ const families = {
+ 'spdisplays_mtlgpufamilymac1': 'mac1',
+ 'spdisplays_mtlgpufamilymac2': 'mac2',
+ 'spdisplays_mtlgpufamilyapple1': 'apple1',
+ 'spdisplays_mtlgpufamilyapple2': 'apple2',
+ 'spdisplays_mtlgpufamilyapple3': 'apple3',
+ 'spdisplays_mtlgpufamilyapple4': 'apple4',
+ 'spdisplays_mtlgpufamilyapple5': 'apple5',
+ 'spdisplays_mtlgpufamilyapple6': 'apple6',
+ 'spdisplays_mtlgpufamilyapple7': 'apple7',
+ 'spdisplays_metalfeaturesetfamily11': 'family1_v1',
+ 'spdisplays_metalfeaturesetfamily12': 'family1_v2',
+ 'spdisplays_metalfeaturesetfamily13': 'family1_v3',
+ 'spdisplays_metalfeaturesetfamily14': 'family1_v4',
+ 'spdisplays_metalfeaturesetfamily21': 'family2_v1'
+ };
+ return families[id] || '';
}
-function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) {
- var _a;
- if (!Array.isArray(object)) {
- throw new Error(`${objectName} must be of type Array.`);
- }
- let elementType = mapper.type.element;
- if (!elementType || typeof elementType !== "object") {
- throw new Error(`element" metadata for an Array must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}.`);
- }
- // Quirk: Composite mappers referenced by `element` might
- // not have *all* properties declared (like uberParent),
- // so let's try to look up the full definition by name.
- if (elementType.type.name === "Composite" && elementType.type.className) {
- elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType;
- }
- const tempArray = [];
- for (let i = 0; i < object.length; i++) {
- const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
- if (isXml && elementType.xmlNamespace) {
- const xmlnsKey = elementType.xmlNamespacePrefix
- ? `xmlns:${elementType.xmlNamespacePrefix}`
- : "xmlns";
- if (elementType.type.name === "Composite") {
- tempArray[i] = Object.assign({}, serializedValue);
- tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
- }
- else {
- tempArray[i] = {};
- tempArray[i][options.xml.xmlCharKey] = serializedValue;
- tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
- }
- }
- else {
- tempArray[i] = serializedValue;
+
+function graphics(callback) {
+
+ function parseLinesDarwin(graphicsArr) {
+ const res = {
+ controllers: [],
+ displays: []
+ };
+ try {
+ graphicsArr.forEach(function (item) {
+ // controllers
+ const bus = ((item.sppci_bus || '').indexOf('builtin') > -1 ? 'Built-In' : ((item.sppci_bus || '').indexOf('pcie') > -1 ? 'PCIe' : ''));
+ const vram = (parseInt((item.spdisplays_vram || ''), 10) || 0) * (((item.spdisplays_vram || '').indexOf('GB') > -1) ? 1024 : 1);
+ const vramDyn = (parseInt((item.spdisplays_vram_shared || ''), 10) || 0) * (((item.spdisplays_vram_shared || '').indexOf('GB') > -1) ? 1024 : 1);
+ let metalVersion = getMetalVersion(item.spdisplays_metal || item.spdisplays_metalfamily || '');
+ res.controllers.push({
+ vendor: getVendorFromModel(item.spdisplays_vendor || '') || item.spdisplays_vendor || '',
+ model: item.sppci_model || '',
+ bus,
+ vramDynamic: bus === 'Built-In',
+ vram: vram || vramDyn || null,
+ deviceId: item['spdisplays_device-id'] || '',
+ vendorId: item['spdisplays_vendor-id'] || vendorToId((item['spdisplays_vendor'] || '') + (item.sppci_model || '')),
+ external: (item.sppci_device_type === 'spdisplays_egpu'),
+ cores: item['sppci_cores'] || null,
+ metalVersion
+ });
+
+ // displays
+ if (item.spdisplays_ndrvs && item.spdisplays_ndrvs.length) {
+ item.spdisplays_ndrvs.forEach(function (displayItem) {
+ const connectionType = displayItem['spdisplays_connection_type'] || '';
+ const currentResolutionParts = (displayItem['_spdisplays_resolution'] || '').split('@');
+ const currentResolution = currentResolutionParts[0].split('x');
+ const pixelParts = (displayItem['_spdisplays_pixels'] || '').split('x');
+ const pixelDepthString = displayItem['spdisplays_depth'] || '';
+ const serial = displayItem['_spdisplays_display-serial-number'] || displayItem['_spdisplays_display-serial-number2'] || null;
+ res.displays.push({
+ vendor: getVendorFromId(displayItem['_spdisplays_display-vendor-id'] || '') || getVendorFromModel(displayItem['_name'] || ''),
+ vendorId: displayItem['_spdisplays_display-vendor-id'] || '',
+ model: displayItem['_name'] || '',
+ productionYear: displayItem['_spdisplays_display-year'] || null,
+ serial: serial !== '0' ? serial : null,
+ displayId: displayItem['_spdisplays_displayID'] || null,
+ main: displayItem['spdisplays_main'] ? displayItem['spdisplays_main'] === 'spdisplays_yes' : false,
+ builtin: (displayItem['spdisplays_display_type'] || '').indexOf('built-in') > -1,
+ connection: ((connectionType.indexOf('_internal') > -1) ? 'Internal' : ((connectionType.indexOf('_displayport') > -1) ? 'Display Port' : ((connectionType.indexOf('_hdmi') > -1) ? 'HDMI' : null))),
+ sizeX: null,
+ sizeY: null,
+ pixelDepth: (pixelDepthString === 'CGSThirtyBitColor' ? 30 : (pixelDepthString === 'CGSThirtytwoBitColor' ? 32 : (pixelDepthString === 'CGSTwentyfourBitColor' ? 24 : null))),
+ resolutionX: pixelParts.length > 1 ? parseInt(pixelParts[0], 10) : null,
+ resolutionY: pixelParts.length > 1 ? parseInt(pixelParts[1], 10) : null,
+ currentResX: currentResolution.length > 1 ? parseInt(currentResolution[0], 10) : null,
+ currentResY: currentResolution.length > 1 ? parseInt(currentResolution[1], 10) : null,
+ positionX: 0,
+ positionY: 0,
+ currentRefreshRate: currentResolutionParts.length > 1 ? parseInt(currentResolutionParts[1], 10) : null,
+
+ });
+ });
}
+ });
+ return res;
+ } catch (e) {
+ return res;
}
- return tempArray;
-}
-function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) {
- if (typeof object !== "object") {
- throw new Error(`${objectName} must be of type object.`);
- }
- const valueType = mapper.type.value;
- if (!valueType || typeof valueType !== "object") {
- throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}.`);
- }
- const tempDictionary = {};
- for (const key of Object.keys(object)) {
- const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
- // If the element needs an XML namespace we need to add it within the $ property
- tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
- }
- // Add the namespace to the root element if needed
- if (isXml && mapper.xmlNamespace) {
- const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
- const result = tempDictionary;
- result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
- return result;
- }
- return tempDictionary;
-}
-/**
- * Resolves the additionalProperties property from a referenced mapper
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- * @param objectName - name of the object being serialized
- */
-function resolveAdditionalProperties(serializer, mapper, objectName) {
- const additionalProperties = mapper.type.additionalProperties;
- if (!additionalProperties && mapper.type.className) {
- const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
- return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties;
- }
- return additionalProperties;
-}
-/**
- * Finds the mapper referenced by className
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- * @param objectName - name of the object being serialized
- */
-function resolveReferencedMapper(serializer, mapper, objectName) {
- const className = mapper.type.className;
- if (!className) {
- throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`);
+ }
+
+ function parseLinesLinuxControllers(lines) {
+ let controllers = [];
+ let currentController = {
+ vendor: '',
+ subVendor: '',
+ model: '',
+ bus: '',
+ busAddress: '',
+ vram: null,
+ vramDynamic: false,
+ pciID: ''
+ };
+ let isGraphicsController = false;
+ // PCI bus IDs
+ let pciIDs = [];
+ try {
+ pciIDs = execSync('export LC_ALL=C; dmidecode -t 9 2>/dev/null; unset LC_ALL | grep "Bus Address: "', util.execOptsLinux).toString().split('\n');
+ for (let i = 0; i < pciIDs.length; i++) {
+ pciIDs[i] = pciIDs[i].replace('Bus Address:', '').replace('0000:', '').trim();
+ }
+ pciIDs = pciIDs.filter(function (el) {
+ return el != null && el;
+ });
+ } catch (e) {
+ util.noop();
}
- return serializer.modelMappers[className];
-}
-/**
- * Resolves a composite mapper's modelProperties.
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- */
-function resolveModelProperties(serializer, mapper, objectName) {
- let modelProps = mapper.type.modelProperties;
- if (!modelProps) {
- const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
- if (!modelMapper) {
- throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
- }
- modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties;
- if (!modelProps) {
- throw new Error(`modelProperties cannot be null or undefined in the ` +
- `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`);
+ let i = 1;
+ lines.forEach((line) => {
+ let subsystem = '';
+ if (i < lines.length && lines[i]) { // get next line;
+ subsystem = lines[i];
+ if (subsystem.indexOf(':') > 0) {
+ subsystem = subsystem.split(':')[1];
}
- }
- return modelProps;
-}
-function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) {
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
- mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
- }
- if (object !== undefined && object !== null) {
- const payload = {};
- const modelProps = resolveModelProperties(serializer, mapper, objectName);
- for (const key of Object.keys(modelProps)) {
- const propertyMapper = modelProps[key];
- if (propertyMapper.readOnly) {
- continue;
+ }
+ if ('' !== line.trim()) {
+ if (' ' !== line[0] && '\t' !== line[0]) { // first line of new entry
+ let isExternal = (pciIDs.indexOf(line.split(' ')[0]) >= 0);
+ let vgapos = line.toLowerCase().indexOf(' vga ');
+ let _3dcontrollerpos = line.toLowerCase().indexOf('3d controller');
+ if (vgapos !== -1 || _3dcontrollerpos !== -1) { // VGA
+ if (_3dcontrollerpos !== -1 && vgapos === -1) {
+ vgapos = _3dcontrollerpos;
}
- let propName;
- let parentObject = payload;
- if (serializer.isXML) {
- if (propertyMapper.xmlIsWrapped) {
- propName = propertyMapper.xmlName;
- }
- else {
- propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
- }
+ if (currentController.vendor || currentController.model || currentController.bus || currentController.vram !== null || currentController.vramDynamic) { // already a controller found
+ controllers.push(currentController);
+ currentController = {
+ vendor: '',
+ model: '',
+ bus: '',
+ busAddress: '',
+ vram: null,
+ vramDynamic: false,
+ };
}
- else {
- const paths = splitSerializeName(propertyMapper.serializedName);
- propName = paths.pop();
- for (const pathName of paths) {
- const childObject = parentObject[pathName];
- if ((childObject === undefined || childObject === null) &&
- ((object[key] !== undefined && object[key] !== null) ||
- propertyMapper.defaultValue !== undefined)) {
- parentObject[pathName] = {};
- }
- parentObject = parentObject[pathName];
- }
+
+ const pciIDCandidate = line.split(' ')[0];
+ if (/[\da-fA-F]{2}:[\da-fA-F]{2}\.[\da-fA-F]/.test(pciIDCandidate)) {
+ currentController.busAddress = pciIDCandidate;
}
- if (parentObject !== undefined && parentObject !== null) {
- if (isXml && mapper.xmlNamespace) {
- const xmlnsKey = mapper.xmlNamespacePrefix
- ? `xmlns:${mapper.xmlNamespacePrefix}`
- : "xmlns";
- parentObject[interfaces_js_1.XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[interfaces_js_1.XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace });
+ isGraphicsController = true;
+ let endpos = line.search(/\[[0-9a-f]{4}:[0-9a-f]{4}]|$/);
+ let parts = line.substr(vgapos, endpos - vgapos).split(':');
+ currentController.busAddress = line.substr(0, vgapos).trim();
+ if (parts.length > 1) {
+ parts[1] = parts[1].trim();
+ if (parts[1].toLowerCase().indexOf('corporation') >= 0) {
+ currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf('corporation') + 11).trim();
+ currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf('corporation') + 11, 200).split('(')[0].trim();
+ currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard';
+ currentController.vram = null;
+ currentController.vramDynamic = false;
+ } else if (parts[1].toLowerCase().indexOf(' inc.') >= 0) {
+ if ((parts[1].match(/]/g) || []).length > 1) {
+ currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim();
+ currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim();
+ } else {
+ currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' inc.') + 5).trim();
+ currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' inc.') + 5, 200).trim().split('(')[0].trim();
}
- const propertyObjectName = propertyMapper.serializedName !== ""
- ? objectName + "." + propertyMapper.serializedName
- : objectName;
- let toSerialize = object[key];
- const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
- if (polymorphicDiscriminator &&
- polymorphicDiscriminator.clientName === key &&
- (toSerialize === undefined || toSerialize === null)) {
- toSerialize = mapper.serializedName;
+ currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard';
+ currentController.vram = null;
+ currentController.vramDynamic = false;
+ } else if (parts[1].toLowerCase().indexOf(' ltd.') >= 0) {
+ if ((parts[1].match(/]/g) || []).length > 1) {
+ currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim();
+ currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim();
+ } else {
+ currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' ltd.') + 5).trim();
+ currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' ltd.') + 5, 200).trim().split('(')[0].trim();
}
- const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options);
- if (serializedValue !== undefined && propName !== undefined && propName !== null) {
- const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
- if (isXml && propertyMapper.xmlIsAttribute) {
- // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.
- // This keeps things simple while preventing name collision
- // with names in user documents.
- parentObject[interfaces_js_1.XML_ATTRKEY] = parentObject[interfaces_js_1.XML_ATTRKEY] || {};
- parentObject[interfaces_js_1.XML_ATTRKEY][propName] = serializedValue;
- }
- else if (isXml && propertyMapper.xmlIsWrapped) {
- parentObject[propName] = { [propertyMapper.xmlElementName]: value };
- }
- else {
- parentObject[propName] = value;
- }
+ }
+ if (currentController.model && subsystem.indexOf(currentController.model) !== -1) {
+ const subVendor = subsystem.split(currentController.model)[0].trim();
+ if (subVendor) {
+ currentController.subVendor = subVendor;
}
+ }
}
+
+ } else {
+ isGraphicsController = false;
+ }
}
- const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
- if (additionalPropertiesMapper) {
- const propNames = Object.keys(modelProps);
- for (const clientPropName in object) {
- const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
- if (isAdditionalProperty) {
- payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options);
- }
+ if (isGraphicsController) { // within VGA details
+ let parts = line.split(':');
+ if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('devicename') !== -1 && parts[1].toLowerCase().indexOf('onboard') !== -1) { currentController.bus = 'Onboard'; }
+ if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('region') !== -1 && parts[1].toLowerCase().indexOf('memory') !== -1) {
+ let memparts = parts[1].split('=');
+ if (memparts.length > 1) {
+ currentController.vram = parseInt(memparts[1]);
}
+ }
}
- return payload;
- }
- return object;
-}
-function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) {
- if (!isXml || !propertyMapper.xmlNamespace) {
- return serializedValue;
+ }
+ i++;
+ });
+
+ if (currentController.vendor || currentController.model || currentController.bus || currentController.busAddress || currentController.vram !== null || currentController.vramDynamic) { // already a controller found
+ controllers.push(currentController);
}
- const xmlnsKey = propertyMapper.xmlNamespacePrefix
- ? `xmlns:${propertyMapper.xmlNamespacePrefix}`
- : "xmlns";
- const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
- if (["Composite"].includes(propertyMapper.type.name)) {
- if (serializedValue[interfaces_js_1.XML_ATTRKEY]) {
- return serializedValue;
+ return (controllers);
+ }
+
+ function parseLinesLinuxClinfo(controllers, lines) {
+ const fieldPattern = /\[([^\]]+)\]\s+(\w+)\s+(.*)/;
+ const devices = lines.reduce((devices, line) => {
+ const field = fieldPattern.exec(line.trim());
+ if (field) {
+ if (!devices[field[1]]) {
+ devices[field[1]] = {};
}
- else {
- const result = Object.assign({}, serializedValue);
- result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
- return result;
+ devices[field[1]][field[2]] = field[3];
+ }
+ return devices;
+ }, {});
+ for (let deviceId in devices) {
+ const device = devices[deviceId];
+ if (device['CL_DEVICE_TYPE'] === 'CL_DEVICE_TYPE_GPU') {
+ let busAddress;
+ if (device['CL_DEVICE_TOPOLOGY_AMD']) {
+ const bdf = device['CL_DEVICE_TOPOLOGY_AMD'].match(/[a-zA-Z0-9]+:\d+\.\d+/);
+ if (bdf) {
+ busAddress = bdf[0];
+ }
+ } else if (device['CL_DEVICE_PCI_BUS_ID_NV'] && device['CL_DEVICE_PCI_SLOT_ID_NV']) {
+ const bus = parseInt(device['CL_DEVICE_PCI_BUS_ID_NV']);
+ const slot = parseInt(device['CL_DEVICE_PCI_SLOT_ID_NV']);
+ if (!isNaN(bus) && !isNaN(slot)) {
+ const b = bus & 0xff;
+ const d = (slot >> 3) & 0xff;
+ const f = slot & 0x07;
+ busAddress = `${b.toString().padStart(2, '0')}:${d.toString().padStart(2, '0')}.${f}`;
+ }
+ }
+ if (busAddress) {
+ let controller = controllers.find(controller => controller.busAddress === busAddress);
+ if (!controller) {
+ controller = {
+ vendor: '',
+ model: '',
+ bus: '',
+ busAddress,
+ vram: null,
+ vramDynamic: false
+ };
+ controllers.push(controller);
+ }
+ controller.vendor = device['CL_DEVICE_VENDOR'];
+ if (device['CL_DEVICE_BOARD_NAME_AMD']) {
+ controller.model = device['CL_DEVICE_BOARD_NAME_AMD'];
+ } else {
+ controller.model = device['CL_DEVICE_NAME'];
+ }
+ const memory = parseInt(device['CL_DEVICE_GLOBAL_MEM_SIZE']);
+ if (!isNaN(memory)) {
+ controller.vram = Math.round(memory / 1024 / 1024);
+ }
}
+ }
}
- const result = {};
- result[options.xml.xmlCharKey] = serializedValue;
- result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
- return result;
-}
-function isSpecialXmlProperty(propertyName, options) {
- return [interfaces_js_1.XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
-}
-function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
- var _a, _b;
- const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : interfaces_js_1.XML_CHARKEY;
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
- mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
+ return controllers;
+ }
+
+ function getNvidiaSmi() {
+ if (_nvidiaSmiPath) {
+ return _nvidiaSmiPath;
}
- const modelProps = resolveModelProperties(serializer, mapper, objectName);
- let instance = {};
- const handledPropertyNames = [];
- for (const key of Object.keys(modelProps)) {
- const propertyMapper = modelProps[key];
- const paths = splitSerializeName(modelProps[key].serializedName);
- handledPropertyNames.push(paths[0]);
- const { serializedName, xmlName, xmlElementName } = propertyMapper;
- let propertyObjectName = objectName;
- if (serializedName !== "" && serializedName !== undefined) {
- propertyObjectName = objectName + "." + serializedName;
- }
- const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
- if (headerCollectionPrefix) {
- const dictionary = {};
- for (const headerKey of Object.keys(responseBody)) {
- if (headerKey.startsWith(headerCollectionPrefix)) {
- dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options);
- }
- handledPropertyNames.push(headerKey);
- }
- instance[key] = dictionary;
- }
- else if (serializer.isXML) {
- if (propertyMapper.xmlIsAttribute && responseBody[interfaces_js_1.XML_ATTRKEY]) {
- instance[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options);
- }
- else if (propertyMapper.xmlIsMsText) {
- if (responseBody[xmlCharKey] !== undefined) {
- instance[key] = responseBody[xmlCharKey];
- }
- else if (typeof responseBody === "string") {
- // The special case where xml parser parses "content" into JSON of
- // `{ name: "content"}` instead of `{ name: { "_": "content" }}`
- instance[key] = responseBody;
- }
- }
- else {
- const propertyName = xmlElementName || xmlName || serializedName;
- if (propertyMapper.xmlIsWrapped) {
- /* a list of wrapped by
- For the xml example below
-
- ...
- ...
-
- the responseBody has
- {
- Cors: {
- CorsRule: [{...}, {...}]
- }
- }
- xmlName is "Cors" and xmlElementName is"CorsRule".
- */
- const wrapped = responseBody[xmlName];
- const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : [];
- instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options);
- handledPropertyNames.push(xmlName);
- }
- else {
- const property = responseBody[propertyName];
- instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
- handledPropertyNames.push(propertyName);
- }
- }
- }
- else {
- // deserialize the property if it is present in the provided responseBody instance
- let propertyInstance;
- let res = responseBody;
- // traversing the object step by step.
- let steps = 0;
- for (const item of paths) {
- if (!res)
- break;
- steps++;
- res = res[item];
- }
- // only accept null when reaching the last position of object otherwise it would be undefined
- if (res === null && steps < paths.length) {
- res = undefined;
- }
- propertyInstance = res;
- const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
- // checking that the model property name (key)(ex: "fishtype") and the
- // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
- // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
- // is a better approach. The generator is not consistent with escaping '\.' in the
- // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
- // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
- // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
- // the transformation of model property name (ex: "fishtype") is done consistently.
- // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
- if (polymorphicDiscriminator &&
- key === polymorphicDiscriminator.clientName &&
- (propertyInstance === undefined || propertyInstance === null)) {
- propertyInstance = mapper.serializedName;
- }
- let serializedValue;
- // paging
- if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
- propertyInstance = responseBody[key];
- const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
- // Copy over any properties that have already been added into the instance, where they do
- // not exist on the newly de-serialized array
- for (const [k, v] of Object.entries(instance)) {
- if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
- arrayInstance[k] = v;
- }
- }
- instance = arrayInstance;
- }
- else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
- serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
- instance[key] = serializedValue;
- }
+
+ if (_windows) {
+ try {
+ const basePath = util.WINDIR + '\\System32\\DriverStore\\FileRepository';
+ // find all directories that have an nvidia-smi.exe file
+ const candidateDirs = fs.readdirSync(basePath).filter(dir => {
+ return fs.readdirSync([basePath, dir].join('/')).includes('nvidia-smi.exe');
+ });
+ // use the directory with the most recently created nvidia-smi.exe file
+ const targetDir = candidateDirs.reduce((prevDir, currentDir) => {
+ const previousNvidiaSmi = fs.statSync([basePath, prevDir, 'nvidia-smi.exe'].join('/'));
+ const currentNvidiaSmi = fs.statSync([basePath, currentDir, 'nvidia-smi.exe'].join('/'));
+ return (previousNvidiaSmi.ctimeMs > currentNvidiaSmi.ctimeMs) ? prevDir : currentDir;
+ });
+
+ if (targetDir) {
+ _nvidiaSmiPath = [basePath, targetDir, 'nvidia-smi.exe'].join('/');
}
+ } catch (e) {
+ util.noop();
+ }
+ } else if (_linux) {
+ _nvidiaSmiPath = 'nvidia-smi';
+ }
+ return _nvidiaSmiPath;
+ }
+
+ function nvidiaSmi(options) {
+ const nvidiaSmiExe = getNvidiaSmi();
+ options = options || util.execOptsWin;
+ if (nvidiaSmiExe) {
+ const nvidiaSmiOpts = '--query-gpu=driver_version,pci.sub_device_id,name,pci.bus_id,fan.speed,memory.total,memory.used,memory.free,utilization.gpu,utilization.memory,temperature.gpu,temperature.memory,power.draw,power.limit,clocks.gr,clocks.mem --format=csv,noheader,nounits';
+ const cmd = nvidiaSmiExe + ' ' + nvidiaSmiOpts + (_linux ? ' 2>/dev/null' : '');
+ if (_linux) {
+ options.stdio = ['pipe', 'pipe', 'ignore'];
+ }
+ try {
+ const res = execSync(cmd, options).toString();
+ return res;
+ } catch (e) {
+ util.noop();
+ }
+ }
+ return '';
+ }
+
+ function nvidiaDevices() {
+
+ function safeParseNumber(value) {
+ if ([null, undefined].includes(value)) {
+ return value;
+ }
+ return parseFloat(value);
+ }
+
+ const stdout = nvidiaSmi();
+ if (!stdout) {
+ return [];
+ }
+
+ const gpus = stdout.split('\n').filter(Boolean);
+ let results = gpus.map(gpu => {
+ const splittedData = gpu.split(', ').map(value => value.includes('N/A') ? undefined : value);
+ if (splittedData.length === 16) {
+ return {
+ driverVersion: splittedData[0],
+ subDeviceId: splittedData[1],
+ name: splittedData[2],
+ pciBus: splittedData[3],
+ fanSpeed: safeParseNumber(splittedData[4]),
+ memoryTotal: safeParseNumber(splittedData[5]),
+ memoryUsed: safeParseNumber(splittedData[6]),
+ memoryFree: safeParseNumber(splittedData[7]),
+ utilizationGpu: safeParseNumber(splittedData[8]),
+ utilizationMemory: safeParseNumber(splittedData[9]),
+ temperatureGpu: safeParseNumber(splittedData[10]),
+ temperatureMemory: safeParseNumber(splittedData[11]),
+ powerDraw: safeParseNumber(splittedData[12]),
+ powerLimit: safeParseNumber(splittedData[13]),
+ clockCore: safeParseNumber(splittedData[14]),
+ clockMemory: safeParseNumber(splittedData[15]),
+ };
+ } else {
+ return {};
+ }
+ });
+ results = results.filter((item) => {
+ return ('pciBus' in item);
+ });
+ return results;
+ }
+
+ function mergeControllerNvidia(controller, nvidia) {
+ if (nvidia.driverVersion) { controller.driverVersion = nvidia.driverVersion; }
+ if (nvidia.subDeviceId) { controller.subDeviceId = nvidia.subDeviceId; }
+ if (nvidia.name) { controller.name = nvidia.name; }
+ if (nvidia.pciBus) { controller.pciBus = nvidia.pciBus; }
+ if (nvidia.fanSpeed) { controller.fanSpeed = nvidia.fanSpeed; }
+ if (nvidia.memoryTotal) {
+ controller.memoryTotal = nvidia.memoryTotal;
+ controller.vram = nvidia.memoryTotal;
+ controller.vramDynamic = false;
+ }
+ if (nvidia.memoryUsed) { controller.memoryUsed = nvidia.memoryUsed; }
+ if (nvidia.memoryFree) { controller.memoryFree = nvidia.memoryFree; }
+ if (nvidia.utilizationGpu) { controller.utilizationGpu = nvidia.utilizationGpu; }
+ if (nvidia.utilizationMemory) { controller.utilizationMemory = nvidia.utilizationMemory; }
+ if (nvidia.temperatureGpu) { controller.temperatureGpu = nvidia.temperatureGpu; }
+ if (nvidia.temperatureMemory) { controller.temperatureMemory = nvidia.temperatureMemory; }
+ if (nvidia.powerDraw) { controller.powerDraw = nvidia.powerDraw; }
+ if (nvidia.powerLimit) { controller.powerLimit = nvidia.powerLimit; }
+ if (nvidia.clockCore) { controller.clockCore = nvidia.clockCore; }
+ if (nvidia.clockMemory) { controller.clockMemory = nvidia.clockMemory; }
+ return controller;
+ }
+
+ function parseLinesLinuxEdid(edid) {
+ // parsen EDID
+ // --> model
+ // --> resolutionx
+ // --> resolutiony
+ // --> builtin = false
+ // --> pixeldepth (?)
+ // --> sizex
+ // --> sizey
+ let result = {
+ vendor: '',
+ model: '',
+ deviceName: '',
+ main: false,
+ builtin: false,
+ connection: '',
+ sizeX: null,
+ sizeY: null,
+ pixelDepth: null,
+ resolutionX: null,
+ resolutionY: null,
+ currentResX: null,
+ currentResY: null,
+ positionX: 0,
+ positionY: 0,
+ currentRefreshRate: null
+ };
+ // find first "Detailed Timing Description"
+ let start = 108;
+ if (edid.substr(start, 6) === '000000') {
+ start += 36;
}
- const additionalPropertiesMapper = mapper.type.additionalProperties;
- if (additionalPropertiesMapper) {
- const isAdditionalProperty = (responsePropName) => {
- for (const clientPropName in modelProps) {
- const paths = splitSerializeName(modelProps[clientPropName].serializedName);
- if (paths[0] === responsePropName) {
- return false;
- }
- }
- return true;
- };
- for (const responsePropName in responseBody) {
- if (isAdditionalProperty(responsePropName)) {
- instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options);
- }
- }
+ if (edid.substr(start, 6) === '000000') {
+ start += 36;
}
- else if (responseBody && !options.ignoreUnknownProperties) {
- for (const key of Object.keys(responseBody)) {
- if (instance[key] === undefined &&
- !handledPropertyNames.includes(key) &&
- !isSpecialXmlProperty(key, options)) {
- instance[key] = responseBody[key];
- }
- }
+ if (edid.substr(start, 6) === '000000') {
+ start += 36;
}
- return instance;
-}
-function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) {
- /* jshint validthis: true */
- const value = mapper.type.value;
- if (!value || typeof value !== "object") {
- throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}`);
+ if (edid.substr(start, 6) === '000000') {
+ start += 36;
}
- if (responseBody) {
- const tempDictionary = {};
- for (const key of Object.keys(responseBody)) {
- tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
+ result.resolutionX = parseInt('0x0' + edid.substr(start + 8, 1) + edid.substr(start + 4, 2));
+ result.resolutionY = parseInt('0x0' + edid.substr(start + 14, 1) + edid.substr(start + 10, 2));
+ result.sizeX = parseInt('0x0' + edid.substr(start + 28, 1) + edid.substr(start + 24, 2));
+ result.sizeY = parseInt('0x0' + edid.substr(start + 29, 1) + edid.substr(start + 26, 2));
+ // monitor name
+ start = edid.indexOf('000000fc00'); // find first "Monitor Description Data"
+ if (start >= 0) {
+ let model_raw = edid.substr(start + 10, 26);
+ if (model_raw.indexOf('0a') !== -1) {
+ model_raw = model_raw.substr(0, model_raw.indexOf('0a'));
+ }
+ try {
+ if (model_raw.length > 2) {
+ result.model = model_raw.match(/.{1,2}/g).map(function (v) {
+ return String.fromCharCode(parseInt(v, 16));
+ }).join('');
}
- return tempDictionary;
- }
- return responseBody;
-}
-function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) {
- var _a;
- let element = mapper.type.element;
- if (!element || typeof element !== "object") {
- throw new Error(`element" metadata for an Array must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}`);
+ } catch (e) {
+ util.noop();
+ }
+ } else {
+ result.model = '';
}
- if (responseBody) {
- if (!Array.isArray(responseBody)) {
- // xml2js will interpret a single element array as just the element, so force it to be an array
- responseBody = [responseBody];
- }
- // Quirk: Composite mappers referenced by `element` might
- // not have *all* properties declared (like uberParent),
- // so let's try to look up the full definition by name.
- if (element.type.name === "Composite" && element.type.className) {
- element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element;
+ return result;
+ }
+
+ function parseLinesLinuxDisplays(lines, depth) {
+ let displays = [];
+ let currentDisplay = {
+ vendor: '',
+ model: '',
+ deviceName: '',
+ main: false,
+ builtin: false,
+ connection: '',
+ sizeX: null,
+ sizeY: null,
+ pixelDepth: null,
+ resolutionX: null,
+ resolutionY: null,
+ currentResX: null,
+ currentResY: null,
+ positionX: 0,
+ positionY: 0,
+ currentRefreshRate: null
+ };
+ let is_edid = false;
+ let is_current = false;
+ let edid_raw = '';
+ let start = 0;
+ for (let i = 1; i < lines.length; i++) { // start with second line
+ if ('' !== lines[i].trim()) {
+ if (' ' !== lines[i][0] && '\t' !== lines[i][0] && lines[i].toLowerCase().indexOf(' connected ') !== -1) { // first line of new entry
+ if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // push last display to array
+ displays.push(currentDisplay);
+ currentDisplay = {
+ vendor: '',
+ model: '',
+ main: false,
+ builtin: false,
+ connection: '',
+ sizeX: null,
+ sizeY: null,
+ pixelDepth: null,
+ resolutionX: null,
+ resolutionY: null,
+ currentResX: null,
+ currentResY: null,
+ positionX: 0,
+ positionY: 0,
+ currentRefreshRate: null
+ };
+ }
+ let parts = lines[i].split(' ');
+ currentDisplay.connection = parts[0];
+ currentDisplay.main = lines[i].toLowerCase().indexOf(' primary ') >= 0;
+ currentDisplay.builtin = (parts[0].toLowerCase().indexOf('edp') >= 0);
}
- const tempArray = [];
- for (let i = 0; i < responseBody.length; i++) {
- tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options);
+
+ // try to read EDID information
+ if (is_edid) {
+ if (lines[i].search(/\S|$/) > start) {
+ edid_raw += lines[i].toLowerCase().trim();
+ } else {
+ // parsen EDID
+ let edid_decoded = parseLinesLinuxEdid(edid_raw);
+ currentDisplay.vendor = edid_decoded.vendor;
+ currentDisplay.model = edid_decoded.model;
+ currentDisplay.resolutionX = edid_decoded.resolutionX;
+ currentDisplay.resolutionY = edid_decoded.resolutionY;
+ currentDisplay.sizeX = edid_decoded.sizeX;
+ currentDisplay.sizeY = edid_decoded.sizeY;
+ currentDisplay.pixelDepth = depth;
+ is_edid = false;
+ }
}
- return tempArray;
- }
- return responseBody;
-}
-function getIndexDiscriminator(discriminators, discriminatorValue, typeName) {
- const typeNamesToCheck = [typeName];
- while (typeNamesToCheck.length) {
- const currentName = typeNamesToCheck.shift();
- const indexDiscriminator = discriminatorValue === currentName
- ? discriminatorValue
- : currentName + "." + discriminatorValue;
- if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
- return discriminators[indexDiscriminator];
+ if (lines[i].toLowerCase().indexOf('edid:') >= 0) {
+ is_edid = true;
+ start = lines[i].search(/\S|$/);
}
- else {
- for (const [name, mapper] of Object.entries(discriminators)) {
- if (name.startsWith(currentName + ".") &&
- mapper.type.uberParent === currentName &&
- mapper.type.className) {
- typeNamesToCheck.push(mapper.type.className);
- }
- }
+ if (lines[i].toLowerCase().indexOf('*current') >= 0) {
+ const parts1 = lines[i].split('(');
+ if (parts1 && parts1.length > 1 && parts1[0].indexOf('x') >= 0) {
+ const resParts = parts1[0].trim().split('x');
+ currentDisplay.currentResX = util.toInt(resParts[0]);
+ currentDisplay.currentResY = util.toInt(resParts[1]);
+ }
+ is_current = true;
}
- }
- return undefined;
-}
-function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
- var _a;
- const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
- if (polymorphicDiscriminator) {
- let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
- if (discriminatorName) {
- // The serializedName might have \\, which we just want to ignore
- if (polymorphicPropertyName === "serializedName") {
- discriminatorName = discriminatorName.replace(/\\/gi, "");
- }
- const discriminatorValue = object[discriminatorName];
- const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className;
- if (typeof discriminatorValue === "string" && typeName) {
- const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName);
- if (polymorphicMapper) {
- mapper = polymorphicMapper;
- }
- }
+ if (is_current && lines[i].toLowerCase().indexOf('clock') >= 0 && lines[i].toLowerCase().indexOf('hz') >= 0 && lines[i].toLowerCase().indexOf('v: height') >= 0) {
+ const parts1 = lines[i].split('clock');
+ if (parts1 && parts1.length > 1 && parts1[1].toLowerCase().indexOf('hz') >= 0) {
+ currentDisplay.currentRefreshRate = util.toInt(parts1[1]);
+ }
+ is_current = false;
}
+ }
}
- return mapper;
-}
-function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
- return (mapper.type.polymorphicDiscriminator ||
- getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
- getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
-}
-function getPolymorphicDiscriminatorSafely(serializer, typeName) {
- return (typeName &&
- serializer.modelMappers[typeName] &&
- serializer.modelMappers[typeName].type.polymorphicDiscriminator);
-}
-/**
- * Known types of Mappers
- */
-exports.MapperTypeNames = {
- Base64Url: "Base64Url",
- Boolean: "Boolean",
- ByteArray: "ByteArray",
- Composite: "Composite",
- Date: "Date",
- DateTime: "DateTime",
- DateTimeRfc1123: "DateTimeRfc1123",
- Dictionary: "Dictionary",
- Enum: "Enum",
- Number: "Number",
- Object: "Object",
- Sequence: "Sequence",
- String: "String",
- Stream: "Stream",
- TimeSpan: "TimeSpan",
- UnixTime: "UnixTime",
-};
-//# sourceMappingURL=serializer.js.map
-
-/***/ }),
-
-/***/ 22732:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // pushen displays
+ if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // still information there
+ displays.push(currentDisplay);
+ }
+ return displays;
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ServiceClient = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-const pipeline_js_1 = __nccwpck_require__(64524);
-const utils_js_1 = __nccwpck_require__(7805);
-const httpClientCache_js_1 = __nccwpck_require__(64663);
-const operationHelpers_js_1 = __nccwpck_require__(17036);
-const urlHelpers_js_1 = __nccwpck_require__(36580);
-const interfaceHelpers_js_1 = __nccwpck_require__(91030);
-const log_js_1 = __nccwpck_require__(75630);
-/**
- * Initializes a new instance of the ServiceClient.
- */
-class ServiceClient {
- /**
- * The ServiceClient constructor
- * @param credential - The credentials used for authentication with the service.
- * @param options - The service client options that govern the behavior of the client.
- */
- constructor(options = {}) {
- var _a, _b;
- this._requestContentType = options.requestContentType;
- this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri;
- if (options.baseUri) {
- log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
- }
- this._allowInsecureConnection = options.allowInsecureConnection;
- this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)();
- this.pipeline = options.pipeline || createDefaultPipeline(options);
- if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) {
- for (const { policy, position } of options.additionalPolicies) {
- // Sign happens after Retry and is commonly needed to occur
- // before policies that intercept post-retry.
- const afterPhase = position === "perRetry" ? "Sign" : undefined;
- this.pipeline.addPolicy(policy, {
- afterPhase,
+ // function starts here
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ controllers: [],
+ displays: []
+ };
+ if (_darwin) {
+ let cmd = 'system_profiler -xml -detailLevel full SPDisplaysDataType';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ try {
+ const output = stdout.toString();
+ result = parseLinesDarwin(util.plistParser(output)[0]._items);
+ } catch (e) {
+ util.noop();
+ }
+ try {
+ stdout = execSync('defaults read /Library/Preferences/com.apple.windowserver.plist 2>/dev/null;defaults read /Library/Preferences/com.apple.windowserver.displays.plist 2>/dev/null; echo ""', { maxBuffer: 1024 * 20000 });
+ const output = (stdout || '').toString();
+ const obj = util.plistReader(output);
+ if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets']['Configs'] && obj['DisplayAnyUserSets']['Configs'][0] && obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig']) {
+ const current = obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig'];
+ let i = 0;
+ current.forEach((o) => {
+ if (o['CurrentInfo'] && o['CurrentInfo']['OriginX'] !== undefined && result.displays && result.displays[i]) {
+ result.displays[i].positionX = o['CurrentInfo']['OriginX'];
+ }
+ if (o['CurrentInfo'] && o['CurrentInfo']['OriginY'] !== undefined && result.displays && result.displays[i]) {
+ result.displays[i].positionY = o['CurrentInfo']['OriginY'];
+ }
+ i++;
+ });
+ }
+ if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets'].length > 0 && obj['DisplayAnyUserSets'][0].length > 0 && obj['DisplayAnyUserSets'][0][0]['DisplayID']) {
+ const current = obj['DisplayAnyUserSets'][0];
+ let i = 0;
+ current.forEach((o) => {
+ if ('OriginX' in o && result.displays && result.displays[i]) {
+ result.displays[i].positionX = o['OriginX'];
+ }
+ if ('OriginY' in o && result.displays && result.displays[i]) {
+ result.displays[i].positionY = o['OriginY'];
+ }
+ if (o['Mode'] && o['Mode']['BitsPerPixel'] !== undefined && result.displays && result.displays[i]) {
+ result.displays[i].pixelDepth = o['Mode']['BitsPerPixel'];
+ }
+ i++;
});
+ }
+ } catch (e) {
+ util.noop();
}
- }
- }
- /**
- * Send the provided httpRequest.
- */
- async sendRequest(request) {
- return this.pipeline.sendRequest(this._httpClient, request);
- }
- /**
- * Send an HTTP request that is populated using the provided OperationSpec.
- * @typeParam T - The typed result of the request, based on the OperationSpec.
- * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.
- * @param operationSpec - The OperationSpec to use to populate the httpRequest.
- */
- async sendOperationRequest(operationArguments, operationSpec) {
- const endpoint = operationSpec.baseUrl || this._endpoint;
- if (!endpoint) {
- throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.");
- }
- // Templatized URLs sometimes reference properties on the ServiceClient child class,
- // so we have to pass `this` below in order to search these properties if they're
- // not part of OperationArguments
- const url = (0, urlHelpers_js_1.getRequestUrl)(endpoint, operationSpec, operationArguments, this);
- const request = (0, core_rest_pipeline_1.createPipelineRequest)({
- url,
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
});
- request.method = operationSpec.httpMethod;
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- operationInfo.operationSpec = operationSpec;
- operationInfo.operationArguments = operationArguments;
- const contentType = operationSpec.contentType || this._requestContentType;
- if (contentType && operationSpec.requestBody) {
- request.headers.set("Content-Type", contentType);
- }
- const options = operationArguments.options;
- if (options) {
- const requestOptions = options.requestOptions;
- if (requestOptions) {
- if (requestOptions.timeout) {
- request.timeout = requestOptions.timeout;
- }
- if (requestOptions.onUploadProgress) {
- request.onUploadProgress = requestOptions.onUploadProgress;
- }
- if (requestOptions.onDownloadProgress) {
- request.onDownloadProgress = requestOptions.onDownloadProgress;
- }
- if (requestOptions.shouldDeserialize !== undefined) {
- operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;
- }
- if (requestOptions.allowInsecureConnection) {
- request.allowInsecureConnection = true;
- }
+ }
+ if (_linux) {
+ // Raspberry: https://elinux.org/RPI_vcgencmd_usage
+ if (util.isRaspberry() && util.isRaspbian()) {
+ let cmd = 'fbset -s | grep \'mode "\'; vcgencmd get_mem gpu; tvservice -s; tvservice -n;';
+ exec(cmd, function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 3 && lines[0].indexOf('mode "') >= -1 && lines[2].indexOf('0x12000a') > -1) {
+ const parts = lines[0].replace('mode', '').replace(/"/g, '').trim().split('x');
+ if (parts.length === 2) {
+ result.displays.push({
+ vendor: '',
+ model: util.getValue(lines, 'device_name', '='),
+ main: true,
+ builtin: false,
+ connection: 'HDMI',
+ sizeX: null,
+ sizeY: null,
+ pixelDepth: null,
+ resolutionX: parseInt(parts[0], 10),
+ resolutionY: parseInt(parts[1], 10),
+ currentResX: null,
+ currentResY: null,
+ positionX: 0,
+ positionY: 0,
+ currentRefreshRate: null
+ });
+ }
}
- if (options.abortSignal) {
- request.abortSignal = options.abortSignal;
+ if (lines.length > 1 && stdout.toString().indexOf('gpu=') >= -1) {
+ result.controllers.push({
+ vendor: 'Broadcom',
+ model: util.getRpiGpu(),
+ bus: '',
+ vram: util.getValue(lines, 'gpu', '=').replace('M', ''),
+ vramDynamic: true
+ });
}
- if (options.tracingOptions) {
- request.tracingOptions = options.tracingOptions;
+ if (callback) {
+ callback(result);
}
- }
- if (this._allowInsecureConnection) {
- request.allowInsecureConnection = true;
- }
- if (request.streamResponseStatusCodes === undefined) {
- request.streamResponseStatusCodes = (0, interfaceHelpers_js_1.getStreamingResponseStatusCodes)(operationSpec);
- }
- try {
- const rawResponse = await this.sendRequest(request);
- const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]);
- if (options === null || options === void 0 ? void 0 : options.onResponse) {
- options.onResponse(rawResponse, flatResponse);
+ resolve(result);
+ });
+ } else {
+ let cmd = 'lspci -vvv 2>/dev/null';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result.controllers = parseLinesLinuxControllers(lines);
+ const nvidiaData = nvidiaDevices();
+ // needs to be rewritten ... using no spread operators
+ result.controllers = result.controllers.map((controller) => { // match by busAddress
+ return mergeControllerNvidia(controller, nvidiaData.find((contr) => contr.pciBus.toLowerCase().endsWith(controller.busAddress.toLowerCase())) || {});
+ });
}
- return flatResponse;
- }
- catch (error) {
- if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) {
- const rawResponse = error.response;
- const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]);
- error.details = flatResponse;
- if (options === null || options === void 0 ? void 0 : options.onResponse) {
- options.onResponse(rawResponse, flatResponse, error);
+ let cmd = 'clinfo --raw';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result.controllers = parseLinesLinuxClinfo(result.controllers, lines);
+ }
+ let cmd = 'xdpyinfo 2>/dev/null | grep \'depth of root window\' | awk \'{ print $5 }\'';
+ exec(cmd, function (error, stdout) {
+ let depth = 0;
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ depth = parseInt(lines[0]) || 0;
}
- }
- throw error;
+ let cmd = 'xrandr --verbose 2>/dev/null';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result.displays = parseLinesLinuxDisplays(lines, depth);
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ });
+ });
+ });
}
- }
-}
-exports.ServiceClient = ServiceClient;
-function createDefaultPipeline(options) {
- const credentialScopes = getCredentialScopes(options);
- const credentialOptions = options.credential && credentialScopes
- ? { credentialScopes, credential: options.credential }
- : undefined;
- return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions }));
-}
-function getCredentialScopes(options) {
- if (options.credentialScopes) {
- return options.credentialScopes;
- }
- if (options.endpoint) {
- return `${options.endpoint}/.default`;
- }
- if (options.baseUri) {
- return `${options.baseUri}/.default`;
- }
- if (options.credential && !options.credentialScopes) {
- throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`);
- }
- return undefined;
-}
-//# sourceMappingURL=serviceClient.js.map
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ if (callback) { callback(null); }
+ resolve(null);
+ }
+ if (_sunos) {
+ if (callback) { callback(null); }
+ resolve(null);
+ }
+ if (_windows) {
-/***/ }),
+ // https://blogs.technet.microsoft.com/heyscriptingguy/2013/10/03/use-powershell-to-discover-multi-monitor-information/
+ // https://devblogs.microsoft.com/scripting/use-powershell-to-discover-multi-monitor-information/
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance win32_VideoController | fl *'));
+ workload.push(util.powerShell('gp "HKLM:\\SYSTEM\\ControlSet001\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}\\*" -ErrorAction SilentlyContinue | where MatchingDeviceId $null -NE | select MatchingDeviceId,HardwareInformation.qwMemorySize | fl'));
+ workload.push(util.powerShell('Get-CimInstance win32_desktopmonitor | fl *'));
+ workload.push(util.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorBasicDisplayParams | fl'));
+ workload.push(util.powerShell('Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Screen]::AllScreens'));
+ workload.push(util.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorConnectionParams | fl'));
+ workload.push(util.powerShell('gwmi WmiMonitorID -Namespace root\\wmi | ForEach-Object {(($_.ManufacturerName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.ProductCodeID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.UserFriendlyName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.SerialNumberID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + $_.InstanceName}'));
-/***/ 35077:
-/***/ ((__unused_webpack_module, exports) => {
+ const nvidiaData = nvidiaDevices();
+ Promise.all(
+ workload
+ ).then((data) => {
+ // controller + vram
+ let csections = data[0].replace(/\r/g, '').split(/\n\s*\n/);
+ let vsections = data[1].replace(/\r/g, '').split(/\n\s*\n/);
+ result.controllers = parseLinesWindowsControllers(csections, vsections);
+ result.controllers = result.controllers.map((controller) => { // match by subDeviceId
+ if (controller.vendor.toLowerCase() === 'nvidia') {
+ return mergeControllerNvidia(controller, nvidiaData.find(device => {
+ let windowsSubDeviceId = (controller.subDeviceId || '').toLowerCase();
+ const nvidiaSubDeviceIdParts = device.subDeviceId.split('x');
+ let nvidiaSubDeviceId = nvidiaSubDeviceIdParts.length > 1 ? nvidiaSubDeviceIdParts[1].toLowerCase() : nvidiaSubDeviceIdParts[0].toLowerCase();
+ const lengthDifference = Math.abs(windowsSubDeviceId.length - nvidiaSubDeviceId.length);
+ if (windowsSubDeviceId.length > nvidiaSubDeviceId.length) {
+ for (let i = 0; i < lengthDifference; i++) {
+ nvidiaSubDeviceId = '0' + nvidiaSubDeviceId;
+ }
+ } else if (windowsSubDeviceId.length < nvidiaSubDeviceId.length) {
+ for (let i = 0; i < lengthDifference; i++) {
+ windowsSubDeviceId = '0' + windowsSubDeviceId;
+ }
+ }
+ return windowsSubDeviceId === nvidiaSubDeviceId;
+ }) || {});
+ } else {
+ return controller;
+ }
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.state = void 0;
-/**
- * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports.
- */
-exports.state = {
- operationRequestMap: new WeakMap(),
-};
-//# sourceMappingURL=state-cjs.cjs.map
+ // displays
+ let dsections = data[2].replace(/\r/g, '').split(/\n\s*\n/);
+ // result.displays = parseLinesWindowsDisplays(dsections);
+ if (dsections[0].trim() === '') { dsections.shift(); }
+ if (dsections.length && dsections[dsections.length - 1].trim() === '') { dsections.pop(); }
-/***/ }),
+ // monitor (powershell)
+ let msections = data[3].replace(/\r/g, '').split('Active ');
+ msections.shift();
-/***/ 36580:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // forms.screens (powershell)
+ let ssections = data[4].replace(/\r/g, '').split('BitsPerPixel ');
+ ssections.shift();
+ // connection params (powershell) - video type
+ let tsections = data[5].replace(/\r/g, '').split(/\n\s*\n/);
+ tsections.shift();
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.appendQueryParams = exports.getRequestUrl = void 0;
-const operationHelpers_js_1 = __nccwpck_require__(17036);
-const interfaceHelpers_js_1 = __nccwpck_require__(91030);
-const CollectionFormatToDelimiterMap = {
- CSV: ",",
- SSV: " ",
- Multi: "Multi",
- TSV: "\t",
- Pipes: "|",
-};
-function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) {
- const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject);
- let isAbsolutePath = false;
- let requestUrl = replaceAll(baseUri, urlReplacements);
- if (operationSpec.path) {
- let path = replaceAll(operationSpec.path, urlReplacements);
- // QUIRK: sometimes we get a path component like /{nextLink}
- // which may be a fully formed URL with a leading /. In that case, we should
- // remove the leading /
- if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) {
- path = path.substring(1);
- }
- // QUIRK: sometimes we get a path component like {nextLink}
- // which may be a fully formed URL. In that case, we should
- // ignore the baseUri.
- if (isAbsoluteUrl(path)) {
- requestUrl = path;
- isAbsolutePath = true;
- }
- else {
- requestUrl = appendPath(requestUrl, path);
- }
- }
- const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject);
- /**
- * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`
- * is an absolute path. This ensures that existing query parameter values in `requestUrl`
- * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it
- * is still being built so there is nothing to overwrite.
- */
- requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);
- return requestUrl;
-}
-exports.getRequestUrl = getRequestUrl;
-function replaceAll(input, replacements) {
- let result = input;
- for (const [searchValue, replaceValue] of replacements) {
- result = result.split(searchValue).join(replaceValue);
- }
- return result;
-}
-function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
- var _a;
- const result = new Map();
- if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) {
- for (const urlParameter of operationSpec.urlParameters) {
- let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject);
- const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter);
- urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString);
- if (!urlParameter.skipEncoding) {
- urlParameterValue = encodeURIComponent(urlParameterValue);
- }
- result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue);
- }
- }
- return result;
-}
-function isAbsoluteUrl(url) {
- return url.includes("://");
-}
-function appendPath(url, pathToAppend) {
- if (!pathToAppend) {
- return url;
- }
- const parsedUrl = new URL(url);
- let newPath = parsedUrl.pathname;
- if (!newPath.endsWith("/")) {
- newPath = `${newPath}/`;
- }
- if (pathToAppend.startsWith("/")) {
- pathToAppend = pathToAppend.substring(1);
- }
- const searchStart = pathToAppend.indexOf("?");
- if (searchStart !== -1) {
- const path = pathToAppend.substring(0, searchStart);
- const search = pathToAppend.substring(searchStart + 1);
- newPath = newPath + path;
- if (search) {
- parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;
- }
- }
- else {
- newPath = newPath + pathToAppend;
- }
- parsedUrl.pathname = newPath;
- return parsedUrl.toString();
-}
-function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
- var _a;
- const result = new Map();
- const sequenceParams = new Set();
- if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) {
- for (const queryParameter of operationSpec.queryParameters) {
- if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
- sequenceParams.add(queryParameter.mapper.serializedName);
- }
- let queryParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, queryParameter, fallbackObject);
- if ((queryParameterValue !== undefined && queryParameterValue !== null) ||
- queryParameter.mapper.required) {
- queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter));
- const delimiter = queryParameter.collectionFormat
- ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]
- : "";
- if (Array.isArray(queryParameterValue)) {
- // replace null and undefined
- queryParameterValue = queryParameterValue.map((item) => {
- if (item === null || item === undefined) {
- return "";
- }
- return item;
- });
- }
- if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) {
- continue;
- }
- else if (Array.isArray(queryParameterValue) &&
- (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) {
- queryParameterValue = queryParameterValue.join(delimiter);
- }
- if (!queryParameter.skipEncoding) {
- if (Array.isArray(queryParameterValue)) {
- queryParameterValue = queryParameterValue.map((item) => {
- return encodeURIComponent(item);
- });
- }
- else {
- queryParameterValue = encodeURIComponent(queryParameterValue);
- }
+ // monitor ID (powershell) - model / vendor
+ const res = data[6].replace(/\r/g, '').split(/\n/);
+ let isections = [];
+ res.forEach(element => {
+ const parts = element.split('|');
+ if (parts.length === 5) {
+ isections.push({
+ vendor: parts[0],
+ code: parts[1],
+ model: parts[2],
+ serial: parts[3],
+ instanceId: parts[4]
+ });
+ }
+ });
+
+ result.displays = parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections);
+
+ if (result.displays.length === 1) {
+ if (_resolutionX) {
+ result.displays[0].resolutionX = _resolutionX;
+ if (!result.displays[0].currentResX) {
+ result.displays[0].currentResX = _resolutionX;
}
- // Join pipes and CSV *after* encoding, or the server will be upset.
- if (Array.isArray(queryParameterValue) &&
- (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) {
- queryParameterValue = queryParameterValue.join(delimiter);
+ }
+ if (_resolutionY) {
+ result.displays[0].resolutionY = _resolutionY;
+ if (result.displays[0].currentResY === 0) {
+ result.displays[0].currentResY = _resolutionY;
}
- result.set(queryParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter), queryParameterValue);
- }
- }
- }
- return {
- queryParams: result,
- sequenceParams,
- };
-}
-function simpleParseQueryParams(queryString) {
- const result = new Map();
- if (!queryString || queryString[0] !== "?") {
- return result;
- }
- // remove the leading ?
- queryString = queryString.slice(1);
- const pairs = queryString.split("&");
- for (const pair of pairs) {
- const [name, value] = pair.split("=", 2);
- const existingValue = result.get(name);
- if (existingValue) {
- if (Array.isArray(existingValue)) {
- existingValue.push(value);
+ }
+ if (_pixelDepth) {
+ result.displays[0].pixelDepth = _pixelDepth;
+ }
}
- else {
- result.set(name, [existingValue, value]);
+ result.displays = result.displays.map(element => {
+ if (_refreshRate && !element.currentRefreshRate) {
+ element.currentRefreshRate = _refreshRate;
+ }
+ return element;
+ });
+
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ })
+ .catch(() => {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- else {
- result.set(name, value);
+ }
+ });
+ });
+
+ function parseLinesWindowsControllers(sections, vections) {
+ const memorySizes = {};
+ for (const i in vections) {
+ if ({}.hasOwnProperty.call(vections, i)) {
+ if (vections[i].trim() !== '') {
+ const lines = vections[i].trim().split('\n');
+ const matchingDeviceId = util.getValue(lines, 'MatchingDeviceId').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i);
+ if (matchingDeviceId) {
+ const quadWordmemorySize = parseInt(util.getValue(lines, 'HardwareInformation.qwMemorySize'));
+ if (!isNaN(quadWordmemorySize)) {
+ let deviceId = matchingDeviceId[1].toUpperCase() + '&' + matchingDeviceId[2].toUpperCase();
+ if (matchingDeviceId[3]) {
+ deviceId += '&' + matchingDeviceId[3].toUpperCase();
+ }
+ if (matchingDeviceId[4]) {
+ deviceId += '&' + matchingDeviceId[4].toUpperCase();
+ }
+ memorySizes[deviceId] = quadWordmemorySize;
+ }
+ }
}
+ }
}
- return result;
-}
-/** @internal */
-function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) {
- if (queryParams.size === 0) {
- return url;
- }
- const parsedUrl = new URL(url);
- // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which
- // can change their meaning to the server, such as in the case of a SAS signature.
- // To avoid accidentally un-encoding a query param, we parse the key/values ourselves
- const combinedParams = simpleParseQueryParams(parsedUrl.search);
- for (const [name, value] of queryParams) {
- const existingValue = combinedParams.get(name);
- if (Array.isArray(existingValue)) {
- if (Array.isArray(value)) {
- existingValue.push(...value);
- const valueSet = new Set(existingValue);
- combinedParams.set(name, Array.from(valueSet));
+
+ let controllers = [];
+ for (let i in sections) {
+ if ({}.hasOwnProperty.call(sections, i)) {
+ if (sections[i].trim() !== '') {
+ let lines = sections[i].trim().split('\n');
+ let pnpDeviceId = util.getValue(lines, 'PNPDeviceID', ':').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i);
+ let subDeviceId = null;
+ let memorySize = null;
+ if (pnpDeviceId) {
+ subDeviceId = pnpDeviceId[3] || '';
+ if (subDeviceId) {
+ subDeviceId = subDeviceId.split('_')[1];
}
- else {
- existingValue.push(value);
+
+ // Match PCI device identifier (there's an order of increasing generality):
+ // https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
+
+ // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4)&REV_r(2)
+ if (memorySize == null && pnpDeviceId[3] && pnpDeviceId[4]) {
+ const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase();
+ if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
+ memorySize = memorySizes[deviceId];
+ }
}
- }
- else if (existingValue) {
- if (Array.isArray(value)) {
- value.unshift(existingValue);
+
+ // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4)
+ if (memorySize == null && pnpDeviceId[3]) {
+ const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase();
+ if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
+ memorySize = memorySizes[deviceId];
+ }
}
- else if (sequenceParams.has(name)) {
- combinedParams.set(name, [existingValue, value]);
+
+ // PCI\VEN_v(4)&DEV_d(4)&REV_r(2)
+ if (memorySize == null && pnpDeviceId[4]) {
+ const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase();
+ if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
+ memorySize = memorySizes[deviceId];
+ }
}
- if (!noOverwrite) {
- combinedParams.set(name, value);
+
+ // PCI\VEN_v(4)&DEV_d(4)
+ if (memorySize == null) {
+ const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase();
+ if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
+ memorySize = memorySizes[deviceId];
+ }
}
+ }
+
+ controllers.push({
+ vendor: util.getValue(lines, 'AdapterCompatibility', ':'),
+ model: util.getValue(lines, 'name', ':'),
+ bus: util.getValue(lines, 'PNPDeviceID', ':').startsWith('PCI') ? 'PCI' : '',
+ vram: (memorySize == null ? util.toInt(util.getValue(lines, 'AdapterRAM', ':')) : memorySize) / 1024 / 1024,
+ vramDynamic: (util.getValue(lines, 'VideoMemoryType', ':') === '2'),
+ subDeviceId
+ });
+ _resolutionX = util.toInt(util.getValue(lines, 'CurrentHorizontalResolution', ':')) || _resolutionX;
+ _resolutionY = util.toInt(util.getValue(lines, 'CurrentVerticalResolution', ':')) || _resolutionY;
+ _refreshRate = util.toInt(util.getValue(lines, 'CurrentRefreshRate', ':')) || _refreshRate;
+ _pixelDepth = util.toInt(util.getValue(lines, 'CurrentBitsPerPixel', ':')) || _pixelDepth;
}
- else {
- combinedParams.set(name, value);
- }
+ }
}
- const searchPieces = [];
- for (const [name, value] of combinedParams) {
- if (typeof value === "string") {
- searchPieces.push(`${name}=${value}`);
- }
- else if (Array.isArray(value)) {
- // QUIRK: If we get an array of values, include multiple key/value pairs
- for (const subValue of value) {
- searchPieces.push(`${name}=${subValue}`);
- }
- }
- else {
- searchPieces.push(`${name}=${value}`);
+ return controllers;
+ }
+
+ function parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections) {
+ let displays = [];
+ let vendor = '';
+ let model = '';
+ let deviceID = '';
+ let resolutionX = 0;
+ let resolutionY = 0;
+ if (dsections && dsections.length) {
+ let linesDisplay = dsections[0].split('\n');
+ vendor = util.getValue(linesDisplay, 'MonitorManufacturer', ':');
+ model = util.getValue(linesDisplay, 'Name', ':');
+ deviceID = util.getValue(linesDisplay, 'PNPDeviceID', ':').replace(/&/g, '&').toLowerCase();
+ resolutionX = util.toInt(util.getValue(linesDisplay, 'ScreenWidth', ':'));
+ resolutionY = util.toInt(util.getValue(linesDisplay, 'ScreenHeight', ':'));
+ }
+ for (let i = 0; i < ssections.length; i++) {
+ if (ssections[i].trim() !== '') {
+ ssections[i] = 'BitsPerPixel ' + ssections[i];
+ msections[i] = 'Active ' + msections[i];
+ // tsections can be empty OR undefined on earlier versions of powershell (<=2.0)
+ // Tag connection type as UNKNOWN by default if this information is missing
+ if (tsections.length === 0 || tsections[i] === undefined) {
+ tsections[i] = 'Unknown';
}
+ let linesScreen = ssections[i].split('\n');
+ let linesMonitor = msections[i].split('\n');
+
+ let linesConnection = tsections[i].split('\n');
+ const bitsPerPixel = util.getValue(linesScreen, 'BitsPerPixel');
+ const bounds = util.getValue(linesScreen, 'Bounds').replace('{', '').replace('}', '').replace(/=/g, ':').split(',');
+ const primary = util.getValue(linesScreen, 'Primary');
+ const sizeX = util.getValue(linesMonitor, 'MaxHorizontalImageSize');
+ const sizeY = util.getValue(linesMonitor, 'MaxVerticalImageSize');
+ const instanceName = util.getValue(linesMonitor, 'InstanceName').toLowerCase();
+ const videoOutputTechnology = util.getValue(linesConnection, 'VideoOutputTechnology');
+ const deviceName = util.getValue(linesScreen, 'DeviceName');
+ let displayVendor = '';
+ let displayModel = '';
+ isections.forEach(element => {
+ if (element.instanceId.toLowerCase().startsWith(instanceName) && vendor.startsWith('(') && model.startsWith('PnP')) {
+ displayVendor = element.vendor;
+ displayModel = element.model;
+ }
+ });
+ displays.push({
+ vendor: instanceName.startsWith(deviceID) && displayVendor === '' ? vendor : displayVendor,
+ model: instanceName.startsWith(deviceID) && displayModel === '' ? model : displayModel,
+ deviceName,
+ main: primary.toLowerCase() === 'true',
+ builtin: videoOutputTechnology === '2147483648',
+ connection: videoOutputTechnology && videoTypes[videoOutputTechnology] ? videoTypes[videoOutputTechnology] : '',
+ resolutionX: util.toInt(util.getValue(bounds, 'Width', ':')),
+ resolutionY: util.toInt(util.getValue(bounds, 'Height', ':')),
+ sizeX: sizeX ? parseInt(sizeX, 10) : null,
+ sizeY: sizeY ? parseInt(sizeY, 10) : null,
+ pixelDepth: bitsPerPixel,
+ currentResX: util.toInt(util.getValue(bounds, 'Width', ':')),
+ currentResY: util.toInt(util.getValue(bounds, 'Height', ':')),
+ positionX: util.toInt(util.getValue(bounds, 'X', ':')),
+ positionY: util.toInt(util.getValue(bounds, 'Y', ':')),
+ });
+ }
}
- // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.
- parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
- return parsedUrl.toString();
+ if (ssections.length === 0) {
+ displays.push({
+ vendor,
+ model,
+ main: true,
+ sizeX: null,
+ sizeY: null,
+ resolutionX,
+ resolutionY,
+ pixelDepth: null,
+ currentResX: resolutionX,
+ currentResY: resolutionY,
+ positionX: 0,
+ positionY: 0
+ });
+ }
+ return displays;
+ }
}
-exports.appendQueryParams = appendQueryParams;
-//# sourceMappingURL=urlHelpers.js.map
+
+exports.graphics = graphics;
+
/***/ }),
-/***/ 7805:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 8134:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.flattenResponse = exports.isValidUuid = exports.isDuration = exports.isPrimitiveBody = void 0;
-/**
- * A type guard for a primitive response body.
- * @param value - Value to test
- *
- * @internal
- */
-function isPrimitiveBody(value, mapperTypeName) {
- return (mapperTypeName !== "Composite" &&
- mapperTypeName !== "Dictionary" &&
- (typeof value === "string" ||
- typeof value === "number" ||
- typeof value === "boolean" ||
- (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !==
- null ||
- value === undefined ||
- value === null));
-}
-exports.isPrimitiveBody = isPrimitiveBody;
-const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
-/**
- * Returns true if the given string is in ISO 8601 format.
- * @param value - The value to be validated for ISO 8601 duration format.
- * @internal
- */
-function isDuration(value) {
- return validateISODuration.test(value);
-}
-exports.isDuration = isDuration;
-const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
-/**
- * Returns true if the provided uuid is valid.
- *
- * @param uuid - The uuid that needs to be validated.
- *
- * @internal
- */
-function isValidUuid(uuid) {
- return validUuidRegex.test(uuid);
+// @ts-check
+// ==================================================================================
+// index.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// Contributors: Guillaume Legrain (https://github.com/glegrain)
+// Riccardo Novaglia (https://github.com/richy24)
+// Quentin Busuttil (https://github.com/Buzut)
+// Lapsio (https://github.com/lapsio)
+// csy (https://github.com/csy1983)
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+
+// ----------------------------------------------------------------------------------
+// Dependencies
+// ----------------------------------------------------------------------------------
+
+const lib_version = (__nccwpck_require__(15460)/* .version */ .rE);
+const util = __nccwpck_require__(77496);
+const system = __nccwpck_require__(97505);
+const osInfo = __nccwpck_require__(20330);
+const cpu = __nccwpck_require__(16832);
+const memory = __nccwpck_require__(84247);
+const battery = __nccwpck_require__(63179);
+const graphics = __nccwpck_require__(64293);
+const filesystem = __nccwpck_require__(50223);
+const network = __nccwpck_require__(61972);
+const wifi = __nccwpck_require__(76037);
+const processes = __nccwpck_require__(82999);
+const users = __nccwpck_require__(69318);
+const internet = __nccwpck_require__(81997);
+const docker = __nccwpck_require__(81820);
+const vbox = __nccwpck_require__(91404);
+const printer = __nccwpck_require__(93338);
+const usb = __nccwpck_require__(76748);
+const audio = __nccwpck_require__(74352);
+const bluetooth = __nccwpck_require__(6588);
+
+let _platform = process.platform;
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+
+// ----------------------------------------------------------------------------------
+// init
+// ----------------------------------------------------------------------------------
+
+if (_windows) {
+ util.getCodepage();
+ util.getPowershell();
}
-exports.isValidUuid = isValidUuid;
-/**
- * Maps the response as follows:
- * - wraps the response body if needed (typically if its type is primitive).
- * - returns null if the combination of the headers and the body is empty.
- * - otherwise, returns the combination of the headers and the body.
- *
- * @param responseObject - a representation of the parsed response
- * @returns the response that will be returned to the user which can be null and/or wrapped
- *
- * @internal
- */
-function handleNullableResponseAndWrappableBody(responseObject) {
- const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body);
- if (responseObject.hasNullableType &&
- Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
- return responseObject.shouldWrapBody ? { body: null } : null;
- }
- else {
- return responseObject.shouldWrapBody
- ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody;
- }
+
+// ----------------------------------------------------------------------------------
+// General
+// ----------------------------------------------------------------------------------
+
+function version() {
+ return lib_version;
}
-/**
- * Take a `FullOperationResponse` and turn it into a flat
- * response object to hand back to the consumer.
- * @param fullResponse - The processed response from the operation request
- * @param responseSpec - The response map from the OperationSpec
- *
- * @internal
- */
-function flattenResponse(fullResponse, responseSpec) {
- var _a, _b;
- const parsedHeaders = fullResponse.parsedHeaders;
- // head methods never have a body, but we return a boolean set to body property
- // to indicate presence/absence of the resource
- if (fullResponse.request.method === "HEAD") {
- return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody });
- }
- const bodyMapper = responseSpec && responseSpec.bodyMapper;
- const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable);
- const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name;
- /** If the body is asked for, we look at the expected body type to handle it */
- if (expectedBodyTypeName === "Stream") {
- return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody });
- }
- const modelProperties = (expectedBodyTypeName === "Composite" &&
- bodyMapper.type.modelProperties) ||
- {};
- const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === "");
- if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
- const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : [];
- for (const key of Object.keys(modelProperties)) {
- if (modelProperties[key].serializedName) {
- arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key];
- }
- }
- if (parsedHeaders) {
- for (const key of Object.keys(parsedHeaders)) {
- arrayResponse[key] = parsedHeaders[key];
- }
- }
- return isNullable &&
- !fullResponse.parsedBody &&
- !parsedHeaders &&
- Object.getOwnPropertyNames(modelProperties).length === 0
- ? null
- : arrayResponse;
- }
- return handleNullableResponseAndWrappableBody({
- body: fullResponse.parsedBody,
- headers: parsedHeaders,
- hasNullableType: isNullable,
- shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),
+
+// ----------------------------------------------------------------------------------
+// Get static and dynamic data (all)
+// ----------------------------------------------------------------------------------
+
+// --------------------------
+// get static data - they should not change until restarted
+
+function getStaticData(callback) {
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+
+ let data = {};
+
+ data.version = version();
+
+ Promise.all([
+ system.system(),
+ system.bios(),
+ system.baseboard(),
+ system.chassis(),
+ osInfo.osInfo(),
+ osInfo.uuid(),
+ osInfo.versions(),
+ cpu.cpu(),
+ cpu.cpuFlags(),
+ graphics.graphics(),
+ network.networkInterfaces(),
+ memory.memLayout(),
+ filesystem.diskLayout()
+ ]).then((res) => {
+ data.system = res[0];
+ data.bios = res[1];
+ data.baseboard = res[2];
+ data.chassis = res[3];
+ data.os = res[4];
+ data.uuid = res[5];
+ data.versions = res[6];
+ data.cpu = res[7];
+ data.cpu.flags = res[8];
+ data.graphics = res[9];
+ data.net = res[10];
+ data.memLayout = res[11];
+ data.diskLayout = res[12];
+ if (callback) { callback(data); }
+ resolve(data);
+ });
});
+ });
}
-exports.flattenResponse = flattenResponse;
-//# sourceMappingURL=utils.js.map
-/***/ }),
-/***/ 39448:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// get all dynamic data - e.g. for monitoring agents
+// may take some seconds to get all data
+// --------------------------
+// 2 additional parameters needed
+// - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql"
+// - iface: define network interface for which you like to monitor network speed e.g. "eth0"
+function getDynamicData(srv, iface, callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ExtendedServiceClient = void 0;
-const disableKeepAlivePolicy_js_1 = __nccwpck_require__(56531);
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-const core_client_1 = __nccwpck_require__(6868);
-const response_js_1 = __nccwpck_require__(79093);
-/**
- * Client to provide compatability between core V1 & V2.
- */
-class ExtendedServiceClient extends core_client_1.ServiceClient {
- constructor(options) {
- var _a, _b;
- super(options);
- if (((_a = options.keepAliveOptions) === null || _a === void 0 ? void 0 : _a.enable) === false &&
- !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) {
- this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)());
- }
- if (((_b = options.redirectOptions) === null || _b === void 0 ? void 0 : _b.handleRedirects) === false) {
- this.pipeline.removePolicy({
- name: core_rest_pipeline_1.redirectPolicyName,
- });
- }
- }
- /**
- * Compatible send operation request function.
- *
- * @param operationArguments - Operation arguments
- * @param operationSpec - Operation Spec
- * @returns
- */
- async sendOperationRequest(operationArguments, operationSpec) {
- var _a;
- const userProvidedCallBack = (_a = operationArguments === null || operationArguments === void 0 ? void 0 : operationArguments.options) === null || _a === void 0 ? void 0 : _a.onResponse;
- let lastResponse;
- function onResponse(rawResponse, flatResponse, error) {
- lastResponse = rawResponse;
- if (userProvidedCallBack) {
- userProvidedCallBack(rawResponse, flatResponse, error);
+ if (util.isFunction(iface)) {
+ callback = iface;
+ iface = '';
+ }
+ if (util.isFunction(srv)) {
+ callback = srv;
+ srv = '';
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+
+ iface = iface || network.getDefaultNetworkInterface();
+ srv = srv || '';
+
+ // use closure to track ƒ completion
+ let functionProcessed = (function () {
+ let totalFunctions = 15;
+ if (_windows) { totalFunctions = 13; }
+ if (_freebsd || _openbsd || _netbsd) { totalFunctions = 11; }
+ if (_sunos) { totalFunctions = 6; }
+
+ return function () {
+ if (--totalFunctions === 0) {
+ if (callback) {
+ callback(data);
}
- }
- operationArguments.options = Object.assign(Object.assign({}, operationArguments.options), { onResponse });
- const result = await super.sendOperationRequest(operationArguments, operationSpec);
- if (lastResponse) {
- Object.defineProperty(result, "_response", {
- value: (0, response_js_1.toCompatResponse)(lastResponse),
- });
- }
- return result;
- }
-}
-exports.ExtendedServiceClient = ExtendedServiceClient;
-//# sourceMappingURL=extendedClient.js.map
+ resolve(data);
+ }
+ };
+ })();
-/***/ }),
+ let data = {};
-/***/ 22842:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // get time
+ data.time = osInfo.time();
+
+ /**
+ * @namespace
+ * @property {Object} versions
+ * @property {string} versions.node
+ * @property {string} versions.v8
+ */
+ data.node = process.versions.node;
+ data.v8 = process.versions.v8;
+ cpu.cpuCurrentSpeed().then((res) => {
+ data.cpuCurrentSpeed = res;
+ functionProcessed();
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.convertHttpClient = void 0;
-const response_js_1 = __nccwpck_require__(79093);
-const util_js_1 = __nccwpck_require__(46);
-/**
- * Converts a RequestPolicy based HttpClient to a PipelineRequest based HttpClient.
- * @param requestPolicyClient - A HttpClient compatible with core-http
- * @returns A HttpClient compatible with core-rest-pipeline
- */
-function convertHttpClient(requestPolicyClient) {
- return {
- sendRequest: async (request) => {
- const response = await requestPolicyClient.sendRequest((0, util_js_1.toWebResourceLike)(request, { createProxy: true }));
- return (0, response_js_1.toPipelineResponse)(response);
- },
- };
-}
-exports.convertHttpClient = convertHttpClient;
-//# sourceMappingURL=httpClientAdapter.js.map
+ users.users().then((res) => {
+ data.users = res;
+ functionProcessed();
+ });
-/***/ }),
+ processes.processes().then((res) => {
+ data.processes = res;
+ functionProcessed();
+ });
-/***/ 14508:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ cpu.currentLoad().then((res) => {
+ data.currentLoad = res;
+ functionProcessed();
+ });
+ if (!_sunos) {
+ cpu.cpuTemperature().then((res) => {
+ data.temp = res;
+ functionProcessed();
+ });
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toHttpHeadersLike = exports.convertHttpClient = exports.disableKeepAlivePolicyName = exports.HttpPipelineLogLevel = exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.ExtendedServiceClient = void 0;
-/**
- * A Shim Library that provides compatibility between Core V1 & V2 Packages.
- *
- * @packageDocumentation
- */
-var extendedClient_js_1 = __nccwpck_require__(39448);
-Object.defineProperty(exports, "ExtendedServiceClient", ({ enumerable: true, get: function () { return extendedClient_js_1.ExtendedServiceClient; } }));
-var requestPolicyFactoryPolicy_js_1 = __nccwpck_require__(15190);
-Object.defineProperty(exports, "requestPolicyFactoryPolicyName", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.requestPolicyFactoryPolicyName; } }));
-Object.defineProperty(exports, "createRequestPolicyFactoryPolicy", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.createRequestPolicyFactoryPolicy; } }));
-Object.defineProperty(exports, "HttpPipelineLogLevel", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.HttpPipelineLogLevel; } }));
-var disableKeepAlivePolicy_js_1 = __nccwpck_require__(56531);
-Object.defineProperty(exports, "disableKeepAlivePolicyName", ({ enumerable: true, get: function () { return disableKeepAlivePolicy_js_1.disableKeepAlivePolicyName; } }));
-var httpClientAdapter_js_1 = __nccwpck_require__(22842);
-Object.defineProperty(exports, "convertHttpClient", ({ enumerable: true, get: function () { return httpClientAdapter_js_1.convertHttpClient; } }));
-var util_js_1 = __nccwpck_require__(46);
-Object.defineProperty(exports, "toHttpHeadersLike", ({ enumerable: true, get: function () { return util_js_1.toHttpHeadersLike; } }));
-//# sourceMappingURL=index.js.map
+ if (!_openbsd && !_freebsd && !_netbsd && !_sunos) {
+ network.networkStats(iface).then((res) => {
+ data.networkStats = res;
+ functionProcessed();
+ });
+ }
-/***/ }),
+ if (!_sunos) {
+ network.networkConnections().then((res) => {
+ data.networkConnections = res;
+ functionProcessed();
+ });
+ }
-/***/ 56531:
-/***/ ((__unused_webpack_module, exports) => {
+ memory.mem().then((res) => {
+ data.mem = res;
+ functionProcessed();
+ });
+ if (!_sunos) {
+ battery().then((res) => {
+ data.battery = res;
+ functionProcessed();
+ });
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.pipelineContainsDisableKeepAlivePolicy = exports.createDisableKeepAlivePolicy = exports.disableKeepAlivePolicyName = void 0;
-exports.disableKeepAlivePolicyName = "DisableKeepAlivePolicy";
-function createDisableKeepAlivePolicy() {
- return {
- name: exports.disableKeepAlivePolicyName,
- async sendRequest(request, next) {
- request.disableKeepAlive = true;
- return next(request);
- },
- };
-}
-exports.createDisableKeepAlivePolicy = createDisableKeepAlivePolicy;
-/**
- * @internal
- */
-function pipelineContainsDisableKeepAlivePolicy(pipeline) {
- return pipeline.getOrderedPolicies().some((policy) => policy.name === exports.disableKeepAlivePolicyName);
-}
-exports.pipelineContainsDisableKeepAlivePolicy = pipelineContainsDisableKeepAlivePolicy;
-//# sourceMappingURL=disableKeepAlivePolicy.js.map
+ if (!_sunos) {
+ processes.services(srv).then((res) => {
+ data.services = res;
+ functionProcessed();
+ });
+ }
+
+ if (!_sunos) {
+ filesystem.fsSize().then((res) => {
+ data.fsSize = res;
+ functionProcessed();
+ });
+ }
-/***/ }),
+ if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) {
+ filesystem.fsStats().then((res) => {
+ data.fsStats = res;
+ functionProcessed();
+ });
+ }
-/***/ 15190:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) {
+ filesystem.disksIO().then((res) => {
+ data.disksIO = res;
+ functionProcessed();
+ });
+ }
+ if (!_openbsd && !_freebsd && !_netbsd && !_sunos) {
+ wifi.wifiNetworks().then((res) => {
+ data.wifiNetworks = res;
+ functionProcessed();
+ });
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.HttpPipelineLogLevel = void 0;
-const util_js_1 = __nccwpck_require__(46);
-const response_js_1 = __nccwpck_require__(79093);
-/**
- * An enum for compatibility with RequestPolicy
- */
-var HttpPipelineLogLevel;
-(function (HttpPipelineLogLevel) {
- HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
- HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
- HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
- HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
-})(HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = HttpPipelineLogLevel = {}));
-const mockRequestPolicyOptions = {
- log(_logLevel, _message) {
- /* do nothing */
- },
- shouldLog(_logLevel) {
- return false;
- },
-};
-/**
- * The name of the RequestPolicyFactoryPolicy
- */
-exports.requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy";
-/**
- * A policy that wraps policies written for core-http.
- * @param factories - An array of `RequestPolicyFactory` objects from a core-http pipeline
- */
-function createRequestPolicyFactoryPolicy(factories) {
- const orderedFactories = factories.slice().reverse();
- return {
- name: exports.requestPolicyFactoryPolicyName,
- async sendRequest(request, next) {
- let httpPipeline = {
- async sendRequest(httpRequest) {
- const response = await next((0, util_js_1.toPipelineRequest)(httpRequest));
- return (0, response_js_1.toCompatResponse)(response, { createProxy: true });
- },
- };
- for (const factory of orderedFactories) {
- httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions);
- }
- const webResourceLike = (0, util_js_1.toWebResourceLike)(request, { createProxy: true });
- const response = await httpPipeline.sendRequest(webResourceLike);
- return (0, response_js_1.toPipelineResponse)(response);
- },
- };
+ internet.inetLatency().then((res) => {
+ data.inetLatency = res;
+ functionProcessed();
+ });
+ });
+ });
}
-exports.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy;
-//# sourceMappingURL=requestPolicyFactoryPolicy.js.map
-
-/***/ }),
-
-/***/ 79093:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// get all data at once
+// --------------------------
+// 2 additional parameters needed
+// - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql"
+// - iface: define network interface for which you like to monitor network speed e.g. "eth0"
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toPipelineResponse = exports.toCompatResponse = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-const util_js_1 = __nccwpck_require__(46);
-const originalResponse = Symbol("Original FullOperationResponse");
-/**
- * A helper to convert response objects from the new pipeline back to the old one.
- * @param response - A response object from core-client.
- * @returns A response compatible with `HttpOperationResponse` from core-http.
- */
-function toCompatResponse(response, options) {
- let request = (0, util_js_1.toWebResourceLike)(response.request);
- let headers = (0, util_js_1.toHttpHeadersLike)(response.headers);
- if (options === null || options === void 0 ? void 0 : options.createProxy) {
- return new Proxy(response, {
- get(target, prop, receiver) {
- if (prop === "headers") {
- return headers;
- }
- else if (prop === "request") {
- return request;
- }
- else if (prop === originalResponse) {
- return response;
- }
- return Reflect.get(target, prop, receiver);
- },
- set(target, prop, value, receiver) {
- if (prop === "headers") {
- headers = value;
- }
- else if (prop === "request") {
- request = value;
- }
- return Reflect.set(target, prop, value, receiver);
- },
- });
- }
- else {
- return Object.assign(Object.assign({}, response), { request,
- headers });
- }
-}
-exports.toCompatResponse = toCompatResponse;
-/**
- * A helper to convert back to a PipelineResponse
- * @param compatResponse - A response compatible with `HttpOperationResponse` from core-http.
- */
-function toPipelineResponse(compatResponse) {
- const extendedCompatResponse = compatResponse;
- const response = extendedCompatResponse[originalResponse];
- const headers = (0, core_rest_pipeline_1.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true }));
- if (response) {
- response.headers = headers;
- return response;
- }
- else {
- return Object.assign(Object.assign({}, compatResponse), { headers, request: (0, util_js_1.toPipelineRequest)(compatResponse.request) });
- }
-}
-exports.toPipelineResponse = toPipelineResponse;
-//# sourceMappingURL=response.js.map
+function getAllData(srv, iface, callback) {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let data = {};
-/***/ 46:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (iface && util.isFunction(iface) && !callback) {
+ callback = iface;
+ iface = '';
+ }
+ if (srv && util.isFunction(srv) && !iface && !callback) {
+ callback = srv;
+ srv = '';
+ iface = '';
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HttpHeaders = exports.toHttpHeadersLike = exports.toWebResourceLike = exports.toPipelineRequest = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-// We use a custom symbol to cache a reference to the original request without
-// exposing it on the public interface.
-const originalRequestSymbol = Symbol("Original PipelineRequest");
-// Symbol.for() will return the same symbol if it's already been created
-// This particular one is used in core-client to handle the case of when a request is
-// cloned but we need to retrieve the OperationSpec and OperationArguments from the
-// original request.
-const originalClientRequestSymbol = Symbol.for("@azure/core-client original request");
-function toPipelineRequest(webResource, options = {}) {
- const compatWebResource = webResource;
- const request = compatWebResource[originalRequestSymbol];
- const headers = (0, core_rest_pipeline_1.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true }));
- if (request) {
- request.headers = headers;
- return request;
- }
- else {
- const newRequest = (0, core_rest_pipeline_1.createPipelineRequest)({
- url: webResource.url,
- method: webResource.method,
- headers,
- withCredentials: webResource.withCredentials,
- timeout: webResource.timeout,
- requestId: webResource.requestId,
- abortSignal: webResource.abortSignal,
- body: webResource.body,
- formData: webResource.formData,
- disableKeepAlive: !!webResource.keepAlive,
- onDownloadProgress: webResource.onDownloadProgress,
- onUploadProgress: webResource.onUploadProgress,
- proxySettings: webResource.proxySettings,
- streamResponseStatusCodes: webResource.streamResponseStatusCodes,
+ getStaticData().then((res) => {
+ data = res;
+ getDynamicData(srv, iface).then((res) => {
+ for (let key in res) {
+ if ({}.hasOwnProperty.call(res, key)) {
+ data[key] = res[key];
+ }
+ }
+ if (callback) { callback(data); }
+ resolve(data);
});
- if (options.originalRequest) {
- newRequest[originalClientRequestSymbol] =
- options.originalRequest;
- }
- return newRequest;
- }
+ });
+ });
+ });
}
-exports.toPipelineRequest = toPipelineRequest;
-function toWebResourceLike(request, options) {
- var _a;
- const originalRequest = (_a = options === null || options === void 0 ? void 0 : options.originalRequest) !== null && _a !== void 0 ? _a : request;
- const webResource = {
- url: request.url,
- method: request.method,
- headers: toHttpHeadersLike(request.headers),
- withCredentials: request.withCredentials,
- timeout: request.timeout,
- requestId: request.headers.get("x-ms-client-request-id") || request.requestId,
- abortSignal: request.abortSignal,
- body: request.body,
- formData: request.formData,
- keepAlive: !!request.disableKeepAlive,
- onDownloadProgress: request.onDownloadProgress,
- onUploadProgress: request.onUploadProgress,
- proxySettings: request.proxySettings,
- streamResponseStatusCodes: request.streamResponseStatusCodes,
- clone() {
- throw new Error("Cannot clone a non-proxied WebResourceLike");
- },
- prepare() {
- throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat");
- },
- validateRequestProperties() {
- /** do nothing */
- },
- };
- if (options === null || options === void 0 ? void 0 : options.createProxy) {
- return new Proxy(webResource, {
- get(target, prop, receiver) {
- if (prop === originalRequestSymbol) {
- return request;
- }
- else if (prop === "clone") {
- return () => {
- return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), {
- createProxy: true,
- originalRequest,
- });
- };
- }
- return Reflect.get(target, prop, receiver);
- },
- set(target, prop, value, receiver) {
- if (prop === "keepAlive") {
- request.disableKeepAlive = !value;
- }
- const passThroughProps = [
- "url",
- "method",
- "withCredentials",
- "timeout",
- "requestId",
- "abortSignal",
- "body",
- "formData",
- "onDownloadProgress",
- "onUploadProgress",
- "proxySettings",
- "streamResponseStatusCodes",
- ];
- if (typeof prop === "string" && passThroughProps.includes(prop)) {
- request[prop] = value;
- }
- return Reflect.set(target, prop, value, receiver);
- },
+
+function get(valueObject, callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ const allPromises = Object.keys(valueObject)
+ .filter(func => ({}.hasOwnProperty.call(exports, func)))
+ .map(func => {
+ const params = valueObject[func].substring(valueObject[func].lastIndexOf('(') + 1, valueObject[func].lastIndexOf(')'));
+ let funcWithoutParams = func.indexOf(')') >= 0 ? func.split(')')[1].trim() : func;
+ funcWithoutParams = func.indexOf('|') >= 0 ? func.split('|')[0].trim() : funcWithoutParams;
+ if (params) {
+ return exports[funcWithoutParams](params);
+ } else {
+ return exports[funcWithoutParams]('');
+ }
});
- }
- else {
- return webResource;
- }
-}
-exports.toWebResourceLike = toWebResourceLike;
-/**
- * Converts HttpHeaders from core-rest-pipeline to look like
- * HttpHeaders from core-http.
- * @param headers - HttpHeaders from core-rest-pipeline
- * @returns HttpHeaders as they looked in core-http
- */
-function toHttpHeadersLike(headers) {
- return new HttpHeaders(headers.toJSON({ preserveCase: true }));
-}
-exports.toHttpHeadersLike = toHttpHeadersLike;
-/**
- * A collection of HttpHeaders that can be sent with a HTTP request.
- */
-function getHeaderKey(headerName) {
- return headerName.toLowerCase();
-}
-/**
- * A collection of HTTP header key/value pairs.
- */
-class HttpHeaders {
- constructor(rawHeaders) {
- this._headersMap = {};
- if (rawHeaders) {
- for (const headerName in rawHeaders) {
- this.set(headerName, rawHeaders[headerName]);
- }
- }
- }
- /**
- * Set a header in this collection with the provided name and value. The name is
- * case-insensitive.
- * @param headerName - The name of the header to set. This value is case-insensitive.
- * @param headerValue - The value of the header to set.
- */
- set(headerName, headerValue) {
- this._headersMap[getHeaderKey(headerName)] = {
- name: headerName,
- value: headerValue.toString(),
- };
- }
- /**
- * Get the header value for the provided header name, or undefined if no header exists in this
- * collection with the provided name.
- * @param headerName - The name of the header.
- */
- get(headerName) {
- const header = this._headersMap[getHeaderKey(headerName)];
- return !header ? undefined : header.value;
- }
- /**
- * Get whether or not this header collection contains a header entry for the provided header name.
- */
- contains(headerName) {
- return !!this._headersMap[getHeaderKey(headerName)];
- }
- /**
- * Remove the header with the provided headerName. Return whether or not the header existed and
- * was removed.
- * @param headerName - The name of the header to remove.
- */
- remove(headerName) {
- const result = this.contains(headerName);
- delete this._headersMap[getHeaderKey(headerName)];
- return result;
- }
- /**
- * Get the headers that are contained this collection as an object.
- */
- rawHeaders() {
- return this.toJson({ preserveCase: true });
- }
- /**
- * Get the headers that are contained in this collection as an array.
- */
- headersArray() {
- const headers = [];
- for (const headerKey in this._headersMap) {
- headers.push(this._headersMap[headerKey]);
- }
- return headers;
- }
- /**
- * Get the header names that are contained in this collection.
- */
- headerNames() {
- const headerNames = [];
- const headers = this.headersArray();
- for (let i = 0; i < headers.length; ++i) {
- headerNames.push(headers[i].name);
- }
- return headerNames;
- }
- /**
- * Get the header values that are contained in this collection.
- */
- headerValues() {
- const headerValues = [];
- const headers = this.headersArray();
- for (let i = 0; i < headers.length; ++i) {
- headerValues.push(headers[i].value);
- }
- return headerValues;
- }
- /**
- * Get the JSON object representation of this HTTP header collection.
- */
- toJson(options = {}) {
+
+ Promise.all(allPromises).then((data) => {
const result = {};
- if (options.preserveCase) {
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- result[header.name] = header.value;
- }
- }
- else {
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- result[getHeaderKey(header.name)] = header.value;
- }
- }
- return result;
- }
- /**
- * Get the string representation of this HTTP header collection.
- */
- toString() {
- return JSON.stringify(this.toJson({ preserveCase: true }));
- }
- /**
- * Create a deep clone/copy of this HttpHeaders collection.
- */
- clone() {
- const resultPreservingCasing = {};
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- resultPreservingCasing[header.name] = header.value;
+ let i = 0;
+ for (let key in valueObject) {
+ if ({}.hasOwnProperty.call(valueObject, key) && {}.hasOwnProperty.call(exports, key) && data.length > i) {
+ if (valueObject[key] === '*' || valueObject[key] === 'all') {
+ result[key] = data[i];
+ } else {
+ let keys = valueObject[key];
+ let filter = '';
+ let filterParts = [];
+ // remove params
+ if (keys.indexOf(')') >= 0) {
+ keys = keys.split(')')[1].trim();
+ }
+ // extract filter and remove it from keys
+ if (keys.indexOf('|') >= 0) {
+ filter = keys.split('|')[1].trim();
+ filterParts = filter.split(':');
+
+ keys = keys.split('|')[0].trim();
+ }
+ keys = keys.replace(/,/g, ' ').replace(/ +/g, ' ').split(' ');
+ if (data[i]) {
+ if (Array.isArray(data[i])) {
+ // result is in an array, go through all elements of array and pick only the right ones
+ const partialArray = [];
+ data[i].forEach(element => {
+ let partialRes = {};
+ if (keys.length === 1 && (keys[0] === '*' || keys[0] === 'all')) {
+ partialRes = element;
+ } else {
+ keys.forEach(k => {
+ if ({}.hasOwnProperty.call(element, k)) {
+ partialRes[k] = element[k];
+ }
+ });
+ }
+ // if there is a filter, then just take those elements
+ if (filter && filterParts.length === 2) {
+ if ({}.hasOwnProperty.call(partialRes, filterParts[0].trim())) {
+ const val = partialRes[filterParts[0].trim()];
+ if (typeof val == 'number') {
+ if (val === parseFloat(filterParts[1].trim())) {
+ partialArray.push(partialRes);
+ }
+ } else if (typeof val == 'string') {
+ if (val.toLowerCase() === filterParts[1].trim().toLowerCase()) {
+ partialArray.push(partialRes);
+ }
+ }
+ }
+ } else {
+ partialArray.push(partialRes);
+ }
+
+ });
+ result[key] = partialArray;
+ } else {
+ const partialRes = {};
+ keys.forEach(k => {
+ if ({}.hasOwnProperty.call(data[i], k)) {
+ partialRes[k] = data[i][k];
+ }
+ });
+ result[key] = partialRes;
+ }
+ } else {
+ result[key] = {};
+ }
+ }
+ i++;
+ }
}
- return new HttpHeaders(resultPreservingCasing);
- }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ });
}
-exports.HttpHeaders = HttpHeaders;
-//# sourceMappingURL=util.js.map
+
+function observe(valueObject, interval, callback) {
+ let _data = null;
+
+ const result = setInterval(() => {
+ get(valueObject).then((data) => {
+ if (JSON.stringify(_data) !== JSON.stringify(data)) {
+ _data = Object.assign({}, data);
+ callback(data);
+ }
+ });
+ }, interval);
+ return result;
+}
+
+// ----------------------------------------------------------------------------------
+// export all libs
+// ----------------------------------------------------------------------------------
+
+exports.version = version;
+exports.system = system.system;
+exports.bios = system.bios;
+exports.baseboard = system.baseboard;
+exports.chassis = system.chassis;
+
+exports.time = osInfo.time;
+exports.osInfo = osInfo.osInfo;
+exports.versions = osInfo.versions;
+exports.shell = osInfo.shell;
+exports.uuid = osInfo.uuid;
+
+exports.cpu = cpu.cpu;
+exports.cpuFlags = cpu.cpuFlags;
+exports.cpuCache = cpu.cpuCache;
+exports.cpuCurrentSpeed = cpu.cpuCurrentSpeed;
+exports.cpuTemperature = cpu.cpuTemperature;
+exports.currentLoad = cpu.currentLoad;
+exports.fullLoad = cpu.fullLoad;
+
+exports.mem = memory.mem;
+exports.memLayout = memory.memLayout;
+
+exports.battery = battery;
+
+exports.graphics = graphics.graphics;
+
+exports.fsSize = filesystem.fsSize;
+exports.fsOpenFiles = filesystem.fsOpenFiles;
+exports.blockDevices = filesystem.blockDevices;
+exports.fsStats = filesystem.fsStats;
+exports.disksIO = filesystem.disksIO;
+exports.diskLayout = filesystem.diskLayout;
+
+exports.networkInterfaceDefault = network.networkInterfaceDefault;
+exports.networkGatewayDefault = network.networkGatewayDefault;
+exports.networkInterfaces = network.networkInterfaces;
+exports.networkStats = network.networkStats;
+exports.networkConnections = network.networkConnections;
+
+exports.wifiNetworks = wifi.wifiNetworks;
+exports.wifiInterfaces = wifi.wifiInterfaces;
+exports.wifiConnections = wifi.wifiConnections;
+
+exports.services = processes.services;
+exports.processes = processes.processes;
+exports.processLoad = processes.processLoad;
+
+exports.users = users.users;
+
+exports.inetChecksite = internet.inetChecksite;
+exports.inetLatency = internet.inetLatency;
+
+exports.dockerInfo = docker.dockerInfo;
+exports.dockerImages = docker.dockerImages;
+exports.dockerContainers = docker.dockerContainers;
+exports.dockerContainerStats = docker.dockerContainerStats;
+exports.dockerContainerProcesses = docker.dockerContainerProcesses;
+exports.dockerVolumes = docker.dockerVolumes;
+exports.dockerAll = docker.dockerAll;
+
+exports.vboxInfo = vbox.vboxInfo;
+
+exports.printer = printer.printer;
+
+exports.usb = usb.usb;
+
+exports.audio = audio.audio;
+exports.bluetoothDevices = bluetooth.bluetoothDevices;
+
+exports.getStaticData = getStaticData;
+exports.getDynamicData = getDynamicData;
+exports.getAllData = getAllData;
+exports.get = get;
+exports.observe = observe;
+
+exports.powerShellStart = util.powerShellStart;
+exports.powerShellRelease = util.powerShellRelease;
+
/***/ }),
-/***/ 27826:
+/***/ 81997:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.pollHttpOperation = exports.isOperationError = exports.getResourceLocation = exports.getOperationStatus = exports.getOperationLocation = exports.initHttpOperation = exports.getStatusFromInitialResponse = exports.getErrorFromResponse = exports.parseRetryAfter = exports.inferLroMode = void 0;
-const operation_js_1 = __nccwpck_require__(26588);
-const logger_js_1 = __nccwpck_require__(80692);
-function getOperationLocationPollingUrl(inputs) {
- const { azureAsyncOperation, operationLocation } = inputs;
- return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
-}
-function getLocationHeader(rawResponse) {
- return rawResponse.headers["location"];
-}
-function getOperationLocationHeader(rawResponse) {
- return rawResponse.headers["operation-location"];
-}
-function getAzureAsyncOperationHeader(rawResponse) {
- return rawResponse.headers["azure-asyncoperation"];
-}
-function findResourceLocation(inputs) {
- var _a;
- const { location, requestMethod, requestPath, resourceLocationConfig } = inputs;
- switch (requestMethod) {
- case "PUT": {
- return requestPath;
- }
- case "DELETE": {
- return undefined;
- }
- case "PATCH": {
- return (_a = getDefault()) !== null && _a !== void 0 ? _a : requestPath;
- }
- default: {
- return getDefault();
- }
- }
- function getDefault() {
- switch (resourceLocationConfig) {
- case "azure-async-operation": {
- return undefined;
- }
- case "original-uri": {
- return requestPath;
- }
- case "location":
- default: {
- return location;
- }
- }
- }
-}
-function inferLroMode(inputs) {
- const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs;
- const operationLocation = getOperationLocationHeader(rawResponse);
- const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse);
- const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation });
- const location = getLocationHeader(rawResponse);
- const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase();
- if (pollingUrl !== undefined) {
- return {
- mode: "OperationLocation",
- operationLocation: pollingUrl,
- resourceLocation: findResourceLocation({
- requestMethod: normalizedRequestMethod,
- location,
- requestPath,
- resourceLocationConfig,
- }),
- };
- }
- else if (location !== undefined) {
- return {
- mode: "ResourceLocation",
- operationLocation: location,
- };
- }
- else if (normalizedRequestMethod === "PUT" && requestPath) {
- return {
- mode: "Body",
- operationLocation: requestPath,
- };
- }
- else {
- return undefined;
- }
-}
-exports.inferLroMode = inferLroMode;
-function transformStatus(inputs) {
- const { status, statusCode } = inputs;
- if (typeof status !== "string" && status !== undefined) {
- throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`);
- }
- switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) {
- case undefined:
- return toOperationStatus(statusCode);
- case "succeeded":
- return "succeeded";
- case "failed":
- return "failed";
- case "running":
- case "accepted":
- case "started":
- case "canceling":
- case "cancelling":
- return "running";
- case "canceled":
- case "cancelled":
- return "canceled";
- default: {
- logger_js_1.logger.verbose(`LRO: unrecognized operation status: ${status}`);
- return status;
+// @ts-check
+// ==================================================================================
+// internet.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 12. Internet
+// ----------------------------------------------------------------------------------
+
+const util = __nccwpck_require__(77496);
+
+let _platform = process.platform;
+
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+
+// --------------------------
+// check if external site is available
+
+function inetChecksite(url, callback) {
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ url: url,
+ ok: false,
+ status: 404,
+ ms: null
+ };
+ if (typeof url !== 'string') {
+ if (callback) { callback(result); }
+ return resolve(result);
+ }
+ let urlSanitized = '';
+ const s = util.sanitizeShellString(url, true);
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ try {
+ s[i].__proto__.toLowerCase = util.stringToLower;
+ } catch (e) {
+ Object.setPrototypeOf(s[i], util.stringObj);
+ }
+
+ const sl = s[i].toLowerCase();
+ if (sl && sl[0] && !sl[1] && sl[0].length === 1) {
+ urlSanitized = urlSanitized + sl[0];
+ }
}
- }
-}
-function getStatus(rawResponse) {
- var _a;
- const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
- return transformStatus({ status, statusCode: rawResponse.statusCode });
-}
-function getProvisioningState(rawResponse) {
- var _a, _b;
- const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
- const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
- return transformStatus({ status, statusCode: rawResponse.statusCode });
-}
-function toOperationStatus(statusCode) {
- if (statusCode === 202) {
- return "running";
- }
- else if (statusCode < 300) {
- return "succeeded";
- }
- else {
- return "failed";
- }
-}
-function parseRetryAfter({ rawResponse }) {
- const retryAfter = rawResponse.headers["retry-after"];
- if (retryAfter !== undefined) {
- // Retry-After header value is either in HTTP date format, or in seconds
- const retryAfterInSeconds = parseInt(retryAfter);
- return isNaN(retryAfterInSeconds)
- ? calculatePollingIntervalFromDate(new Date(retryAfter))
- : retryAfterInSeconds * 1000;
- }
- return undefined;
-}
-exports.parseRetryAfter = parseRetryAfter;
-function getErrorFromResponse(response) {
- const error = accessBodyProperty(response, "error");
- if (!error) {
- logger_js_1.logger.warning(`The long-running operation failed but there is no error property in the response's body`);
- return;
- }
- if (!error.code || !error.message) {
- logger_js_1.logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`);
- return;
- }
- return error;
-}
-exports.getErrorFromResponse = getErrorFromResponse;
-function calculatePollingIntervalFromDate(retryAfterDate) {
- const timeNow = Math.floor(new Date().getTime());
- const retryAfterTime = retryAfterDate.getTime();
- if (timeNow < retryAfterTime) {
- return retryAfterTime - timeNow;
- }
- return undefined;
-}
-function getStatusFromInitialResponse(inputs) {
- const { response, state, operationLocation } = inputs;
- function helper() {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case undefined:
- return toOperationStatus(response.rawResponse.statusCode);
- case "Body":
- return getOperationStatus(response, state);
- default:
- return "running";
+ }
+ result.url = urlSanitized;
+ try {
+ if (urlSanitized && !util.isPrototypePolluted()) {
+ try {
+ urlSanitized.__proto__.startsWith = util.stringStartWith;
+ } catch (e) {
+ Object.setPrototypeOf(urlSanitized, util.stringObj);
+ }
+
+ if (urlSanitized.startsWith('file:') || urlSanitized.startsWith('gopher:') || urlSanitized.startsWith('telnet:') || urlSanitized.startsWith('mailto:') || urlSanitized.startsWith('news:') || urlSanitized.startsWith('nntp:')) {
+ if (callback) { callback(result); }
+ return resolve(result);
+ }
+
+ util.checkWebsite(urlSanitized).then((res) => {
+ result.status = res.statusCode;
+ result.ok = res.statusCode >= 200 && res.statusCode <= 399;;
+ result.ms = (result.ok ? res.time : null);
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
}
- }
- const status = helper();
- return status === "running" && operationLocation === undefined ? "succeeded" : status;
-}
-exports.getStatusFromInitialResponse = getStatusFromInitialResponse;
-/**
- * Initiates the long-running operation.
- */
-async function initHttpOperation(inputs) {
- const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs;
- return (0, operation_js_1.initOperation)({
- init: async () => {
- const response = await lro.sendInitialRequest();
- const config = inferLroMode({
- rawResponse: response.rawResponse,
- requestPath: lro.requestPath,
- requestMethod: lro.requestMethod,
- resourceLocationConfig,
- });
- return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
- },
- stateProxy,
- processResult: processResult
- ? ({ flatResponse }, state) => processResult(flatResponse, state)
- : ({ flatResponse }) => flatResponse,
- getOperationStatus: getStatusFromInitialResponse,
- setErrorAsResult,
+ } catch (err) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
});
+ });
}
-exports.initHttpOperation = initHttpOperation;
-function getOperationLocation({ rawResponse }, state) {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case "OperationLocation": {
- return getOperationLocationPollingUrl({
- operationLocation: getOperationLocationHeader(rawResponse),
- azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse),
- });
- }
- case "ResourceLocation": {
- return getLocationHeader(rawResponse);
+
+exports.inetChecksite = inetChecksite;
+
+// --------------------------
+// check inet latency
+
+function inetLatency(host, callback) {
+
+ // fallback - if only callback is given
+ if (util.isFunction(host) && !callback) {
+ callback = host;
+ host = '';
+ }
+
+ host = host || '8.8.8.8';
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (typeof host !== 'string') {
+ if (callback) { callback(null); }
+ return resolve(null);
+ }
+ let hostSanitized = '';
+ const s = (util.isPrototypePolluted() ? '8.8.8.8' : util.sanitizeShellString(host, true)).trim();
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (!(s[i] === undefined)) {
+ try {
+ s[i].__proto__.toLowerCase = util.stringToLower;
+ } catch (e) {
+ Object.setPrototypeOf(s[i], util.stringObj);
+ }
+
+ const sl = s[i].toLowerCase();
+ if (sl && sl[0] && !sl[1]) {
+ hostSanitized = hostSanitized + sl[0];
+ }
}
- case "Body":
- default: {
- return undefined;
+ }
+ try {
+ hostSanitized.__proto__.startsWith = util.stringStartWith;
+ } catch (e) {
+ Object.setPrototypeOf(hostSanitized, util.stringObj);
+ }
+
+ if (hostSanitized.startsWith('file:') || hostSanitized.startsWith('gopher:') || hostSanitized.startsWith('telnet:') || hostSanitized.startsWith('mailto:') || hostSanitized.startsWith('news:') || hostSanitized.startsWith('nntp:')) {
+ if (callback) { callback(null); }
+ return resolve(null);
+ }
+ let params;
+ if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
+ if (_linux) {
+ params = ['-c', '2', '-w', '3', hostSanitized];
}
- }
-}
-exports.getOperationLocation = getOperationLocation;
-function getOperationStatus({ rawResponse }, state) {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case "OperationLocation": {
- return getStatus(rawResponse);
+ if (_freebsd || _openbsd || _netbsd) {
+ params = ['-c', '2', '-t', '3', hostSanitized];
}
- case "ResourceLocation": {
- return toOperationStatus(rawResponse.statusCode);
+ if (_darwin) {
+ params = ['-c2', '-t3', hostSanitized];
}
- case "Body": {
- return getProvisioningState(rawResponse);
+ util.execSafe('ping', params).then((stdout) => {
+ let result = null;
+ if (stdout) {
+ const lines = stdout.split('\n').filter((line) => (line.indexOf('rtt') >= 0 || line.indexOf('round-trip') >= 0 || line.indexOf('avg') >= 0)).join('\n');
+
+ const line = lines.split('=');
+ if (line.length > 1) {
+ const parts = line[1].split('/');
+ if (parts.length > 1) {
+ result = parseFloat(parts[1]);
+ }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ const params = ['-s', '-a', hostSanitized, '56', '2'];
+ const filt = 'avg';
+ util.execSafe('ping', params, { timeout: 3000 }).then((stdout) => {
+ let result = null;
+ if (stdout) {
+ const lines = stdout.split('\n').filter(line => line.indexOf(filt) >= 0).join('\n');
+ const line = lines.split('=');
+ if (line.length > 1) {
+ const parts = line[1].split('/');
+ if (parts.length > 1) {
+ result = parseFloat(parts[1].replace(',', '.'));
+ }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_windows) {
+ let result = null;
+ try {
+ const params = [hostSanitized, '-n', '1'];
+ util.execSafe('ping', params, util.execOptsWin).then((stdout) => {
+ if (stdout) {
+ let lines = stdout.split('\r\n');
+ lines.shift();
+ lines.forEach(function (line) {
+ if ((line.toLowerCase().match(/ms/g) || []).length === 3) {
+ let l = line.replace(/ +/g, ' ').split(' ');
+ if (l.length > 6) {
+ result = parseFloat(l[l.length - 1]);
+ }
+ }
+ });
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- default:
- throw new Error(`Internal error: Unexpected operation mode: ${mode}`);
- }
-}
-exports.getOperationStatus = getOperationStatus;
-function accessBodyProperty({ flatResponse, rawResponse }, prop) {
- var _a, _b;
- return (_a = flatResponse === null || flatResponse === void 0 ? void 0 : flatResponse[prop]) !== null && _a !== void 0 ? _a : (_b = rawResponse.body) === null || _b === void 0 ? void 0 : _b[prop];
-}
-function getResourceLocation(res, state) {
- const loc = accessBodyProperty(res, "resourceLocation");
- if (loc && typeof loc === "string") {
- state.config.resourceLocation = loc;
- }
- return state.config.resourceLocation;
-}
-exports.getResourceLocation = getResourceLocation;
-function isOperationError(e) {
- return e.name === "RestError";
-}
-exports.isOperationError = isOperationError;
-/** Polls the long-running operation. */
-async function pollHttpOperation(inputs) {
- const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs;
- return (0, operation_js_1.pollOperation)({
- state,
- stateProxy,
- setDelay,
- processResult: processResult
- ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState)
- : ({ flatResponse }) => flatResponse,
- getError: getErrorFromResponse,
- updateState,
- getPollingInterval: parseRetryAfter,
- getOperationLocation,
- getOperationStatus,
- isOperationError,
- getResourceLocation,
- options,
- /**
- * The expansion here is intentional because `lro` could be an object that
- * references an inner this, so we need to preserve a reference to it.
- */
- poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions),
- setErrorAsResult,
+ }
});
+ });
}
-exports.pollHttpOperation = pollHttpOperation;
-//# sourceMappingURL=operation.js.map
+
+exports.inetLatency = inetLatency;
+
/***/ }),
-/***/ 74681:
+/***/ 84247:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createHttpPoller = void 0;
-const operation_js_1 = __nccwpck_require__(27826);
-const poller_js_1 = __nccwpck_require__(81327);
-/**
- * Creates a poller that can be used to poll a long-running operation.
- * @param lro - Description of the long-running operation
- * @param options - options to configure the poller
- * @returns an initialized poller
- */
-async function createHttpPoller(lro, options) {
- const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {};
- return (0, poller_js_1.buildCreatePoller)({
- getStatusFromInitialResponse: operation_js_1.getStatusFromInitialResponse,
- getStatusFromPollResponse: operation_js_1.getOperationStatus,
- isOperationError: operation_js_1.isOperationError,
- getOperationLocation: operation_js_1.getOperationLocation,
- getResourceLocation: operation_js_1.getResourceLocation,
- getPollingInterval: operation_js_1.parseRetryAfter,
- getError: operation_js_1.getErrorFromResponse,
- resolveOnUnsuccessful,
- })({
- init: async () => {
- const response = await lro.sendInitialRequest();
- const config = (0, operation_js_1.inferLroMode)({
- rawResponse: response.rawResponse,
- requestPath: lro.requestPath,
- requestMethod: lro.requestMethod,
- resourceLocationConfig,
- });
- return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
- },
- poll: lro.sendPollRequest,
- }, {
- intervalInMs,
- withOperationLocation,
- restoreFrom,
- updateState,
- processResult: processResult
- ? ({ flatResponse }, state) => processResult(flatResponse, state)
- : ({ flatResponse }) => flatResponse,
- });
-}
-exports.createHttpPoller = createHttpPoller;
-//# sourceMappingURL=poller.js.map
+// @ts-check
+// ==================================================================================
+// memory.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 5. Memory
+// ----------------------------------------------------------------------------------
-/***/ }),
+const os = __nccwpck_require__(70857);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const util = __nccwpck_require__(77496);
+const fs = __nccwpck_require__(79896);
-/***/ 1814:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+let _platform = process.platform;
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createHttpPoller = void 0;
-const tslib_1 = __nccwpck_require__(94176);
-var poller_js_1 = __nccwpck_require__(74681);
-Object.defineProperty(exports, "createHttpPoller", ({ enumerable: true, get: function () { return poller_js_1.createHttpPoller; } }));
-/**
- * This can be uncommented to expose the protocol-agnostic poller
- */
-// export {
-// BuildCreatePollerOptions,
-// Operation,
-// CreatePollerOptions,
-// OperationConfig,
-// RestorableOperationState,
-// } from "./poller/models";
-// export { buildCreatePoller } from "./poller/poller";
-/** legacy */
-tslib_1.__exportStar(__nccwpck_require__(5618), exports);
-tslib_1.__exportStar(__nccwpck_require__(25796), exports);
-tslib_1.__exportStar(__nccwpck_require__(67130), exports);
-//# sourceMappingURL=index.js.map
+const OSX_RAM_manufacturers = {
+ '0x014F': 'Transcend Information',
+ '0x2C00': 'Micron Technology Inc.',
+ '0x802C': 'Micron Technology Inc.',
+ '0x80AD': 'Hynix Semiconductor Inc.',
+ '0x80CE': 'Samsung Electronics Inc.',
+ '0xAD00': 'Hynix Semiconductor Inc.',
+ '0xCE00': 'Samsung Electronics Inc.',
+ '0x02FE': 'Elpida',
+ '0x5105': 'Qimonda AG i. In.',
+ '0x8551': 'Qimonda AG i. In.',
+ '0x859B': 'Crucial',
+ '0x04CD': 'G-Skill'
+};
-/***/ }),
+const LINUX_RAM_manufacturers = {
+ '017A': 'Apacer',
+ '0198': 'HyperX',
+ '029E': 'Corsair',
+ '04CB': 'A-DATA',
+ '04CD': 'G-Skill',
+ '059B': 'Crucial',
+ '00CE': 'Samsung',
+ '1315': 'Crucial',
+ '014F': 'Transcend Information',
+ '2C00': 'Micron Technology Inc.',
+ '802C': 'Micron Technology Inc.',
+ '80AD': 'Hynix Semiconductor Inc.',
+ '80CE': 'Samsung Electronics Inc.',
+ 'AD00': 'Hynix Semiconductor Inc.',
+ 'CE00': 'Samsung Electronics Inc.',
+ '02FE': 'Elpida',
+ '5105': 'Qimonda AG i. In.',
+ '8551': 'Qimonda AG i. In.',
+ '859B': 'Crucial'
+};
-/***/ 5618:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// _______________________________________________________________________________________
+// | R A M | H D |
+// |______________________|_________________________| | |
+// | active buffers/cache | | |
+// |________________________________________________|___________|_________|______________|
+// | used free | used free |
+// |____________________________________________________________|________________________|
+// | total | swap |
+// |____________________________________________________________|________________________|
+
+// free (older versions)
+// ----------------------------------
+// # free
+// total used free shared buffers cached
+// Mem: 16038 (1) 15653 (2) 384 (3) 0 (4) 236 (5) 14788 (6)
+// -/+ buffers/cache: 628 (7) 15409 (8)
+// Swap: 16371 83 16288
+//
+// |------------------------------------------------------------|
+// | R A M |
+// |______________________|_____________________________________|
+// | active (2-(5+6) = 7) | available (3+5+6 = 8) |
+// |______________________|_________________________|___________|
+// | active | buffers/cache (5+6) | |
+// |________________________________________________|___________|
+// | used (2) | free (3) |
+// |____________________________________________________________|
+// | total (1) |
+// |____________________________________________________________|
+//
+// free (since free von procps-ng 3.3.10)
+// ----------------------------------
+// # free
+// total used free shared buffers/cache available
+// Mem: 16038 (1) 628 (2) 386 (3) 0 (4) 15024 (5) 14788 (6)
+// Swap: 16371 83 16288
+//
+// |------------------------------------------------------------|
+// | R A M |
+// |______________________|_____________________________________|
+// | | available (6) estimated |
+// |______________________|_________________________|___________|
+// | active (2) | buffers/cache (5) | free (3) |
+// |________________________________________________|___________|
+// | total (1) |
+// |____________________________________________________________|
+//
+// Reference: http://www.software-architect.net/blog/article/date/2015/06/12/-826c6e5052.html
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.LroEngine = void 0;
-var lroEngine_js_1 = __nccwpck_require__(24203);
-Object.defineProperty(exports, "LroEngine", ({ enumerable: true, get: function () { return lroEngine_js_1.LroEngine; } }));
-//# sourceMappingURL=index.js.map
+// /procs/meminfo - sample (all in kB)
+//
+// MemTotal: 32806380 kB
+// MemFree: 17977744 kB
+// MemAvailable: 19768972 kB
+// Buffers: 517028 kB
+// Cached: 2161876 kB
+// SwapCached: 456 kB
+// Active: 12081176 kB
+// Inactive: 2164616 kB
+// Active(anon): 10832884 kB
+// Inactive(anon): 1477272 kB
+// Active(file): 1248292 kB
+// Inactive(file): 687344 kB
+// Unevictable: 0 kB
+// Mlocked: 0 kB
+// SwapTotal: 16768892 kB
+// SwapFree: 16768304 kB
+// Dirty: 268 kB
+// Writeback: 0 kB
+// AnonPages: 11568832 kB
+// Mapped: 719992 kB
+// Shmem: 743272 kB
+// Slab: 335716 kB
+// SReclaimable: 256364 kB
+// SUnreclaim: 79352 kB
-/***/ }),
+function mem(callback) {
-/***/ 24203:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ total: os.totalmem(),
+ free: os.freemem(),
+ used: os.totalmem() - os.freemem(),
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.LroEngine = void 0;
-const operation_js_1 = __nccwpck_require__(52175);
-const constants_js_1 = __nccwpck_require__(94288);
-const poller_js_1 = __nccwpck_require__(25796);
-const operation_js_2 = __nccwpck_require__(26588);
-/**
- * The LRO Engine, a class that performs polling.
- */
-class LroEngine extends poller_js_1.Poller {
- constructor(lro, options) {
- const { intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {};
- const state = resumeFrom
- ? (0, operation_js_2.deserializeState)(resumeFrom)
- : {};
- const operation = new operation_js_1.GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone);
- super(operation);
- this.resolveOnUnsuccessful = resolveOnUnsuccessful;
- this.config = { intervalInMs: intervalInMs };
- operation.setPollerConfig(this.config);
- }
- /**
- * The method used by the poller to wait before attempting to update its operation.
- */
- delay() {
- return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs));
- }
-}
-exports.LroEngine = LroEngine;
-//# sourceMappingURL=lroEngine.js.map
+ active: os.totalmem() - os.freemem(), // temporarily (fallback)
+ available: os.freemem(), // temporarily (fallback)
+ buffers: 0,
+ cached: 0,
+ slab: 0,
+ buffcache: 0,
-/***/ }),
+ swaptotal: 0,
+ swapused: 0,
+ swapfree: 0,
+ writeback: null,
+ dirty: null
+ };
+
+ if (_linux) {
+ try {
+ fs.readFile('/proc/meminfo', function (error, stdout) {
+ if (!error) {
+ const lines = stdout.toString().split('\n');
+ result.total = parseInt(util.getValue(lines, 'memtotal'), 10);
+ result.total = result.total ? result.total * 1024 : os.totalmem();
+ result.free = parseInt(util.getValue(lines, 'memfree'), 10);
+ result.free = result.free ? result.free * 1024 : os.freemem();
+ result.used = result.total - result.free;
+
+ result.buffers = parseInt(util.getValue(lines, 'buffers'), 10);
+ result.buffers = result.buffers ? result.buffers * 1024 : 0;
+ result.cached = parseInt(util.getValue(lines, 'cached'), 10);
+ result.cached = result.cached ? result.cached * 1024 : 0;
+ result.slab = parseInt(util.getValue(lines, 'slab'), 10);
+ result.slab = result.slab ? result.slab * 1024 : 0;
+ result.buffcache = result.buffers + result.cached + result.slab;
+
+ let available = parseInt(util.getValue(lines, 'memavailable'), 10);
+ result.available = available ? available * 1024 : result.free + result.buffcache;
+ result.active = result.total - result.available;
+
+ result.swaptotal = parseInt(util.getValue(lines, 'swaptotal'), 10);
+ result.swaptotal = result.swaptotal ? result.swaptotal * 1024 : 0;
+ result.swapfree = parseInt(util.getValue(lines, 'swapfree'), 10);
+ result.swapfree = result.swapfree ? result.swapfree * 1024 : 0;
+ result.swapused = result.swaptotal - result.swapfree;
+ result.writeback = parseInt(util.getValue(lines, 'writeback'), 10);
+ result.writeback = result.writeback ? result.writeback * 1024 : 0;
+ result.dirty = parseInt(util.getValue(lines, 'dirty'), 10);
+ result.dirty = result.dirty ? result.dirty * 1024 : 0;
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ try {
+ exec('/sbin/sysctl hw.realmem hw.physmem vm.stats.vm.v_page_count vm.stats.vm.v_wire_count vm.stats.vm.v_active_count vm.stats.vm.v_inactive_count vm.stats.vm.v_cache_count vm.stats.vm.v_free_count vm.stats.vm.v_page_size', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ const pagesize = parseInt(util.getValue(lines, 'vm.stats.vm.v_page_size'), 10);
+ const inactive = parseInt(util.getValue(lines, 'vm.stats.vm.v_inactive_count'), 10) * pagesize;
+ const cache = parseInt(util.getValue(lines, 'vm.stats.vm.v_cache_count'), 10) * pagesize;
+
+ result.total = parseInt(util.getValue(lines, 'hw.realmem'), 10);
+ if (isNaN(result.total)) { result.total = parseInt(util.getValue(lines, 'hw.physmem'), 10); }
+ result.free = parseInt(util.getValue(lines, 'vm.stats.vm.v_free_count'), 10) * pagesize;
+ result.buffcache = inactive + cache;
+ result.available = result.buffcache + result.free;
+ result.active = result.total - result.free - result.buffcache;
+
+ result.swaptotal = 0;
+ result.swapfree = 0;
+ result.swapused = 0;
+
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_darwin) {
+ let pageSize = 4096;
+ try {
+ let sysPpageSize = util.toInt(execSync('sysctl -n vm.pagesize').toString());
+ pageSize = sysPpageSize || pageSize;
+ } catch (e) {
+ util.noop();
+ }
+ try {
+ exec('vm_stat 2>/dev/null | grep "Pages active"', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+
+ result.active = parseInt(lines[0].split(':')[1], 10) * pageSize;
+ result.buffcache = result.used - result.active;
+ result.available = result.free + result.buffcache;
+ }
+ exec('sysctl -n vm.swapusage 2>/dev/null', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 0) {
+ let firstline = lines[0].replace(/,/g, '.').replace(/M/g, '');
+ let lineArray = firstline.trim().split(' ');
+ lineArray.forEach(line => {
+ if (line.toLowerCase().indexOf('total') !== -1) { result.swaptotal = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
+ if (line.toLowerCase().indexOf('used') !== -1) { result.swapused = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
+ if (line.toLowerCase().indexOf('free') !== -1) { result.swapfree = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
+ });
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_windows) {
+ let swaptotal = 0;
+ let swapused = 0;
+ try {
+ util.powerShell('Get-CimInstance Win32_PageFileUsage | Select AllocatedBaseSize, CurrentUsage').then((stdout, error) => {
+ if (!error) {
+ let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
+ lines.forEach(function (line) {
+ if (line !== '') {
+ line = line.trim().split(/\s\s+/);
+ swaptotal = swaptotal + (parseInt(line[0], 10) || 0);
+ swapused = swapused + (parseInt(line[1], 10) || 0);
+ }
+ });
+ }
+ result.swaptotal = swaptotal * 1024 * 1024;
+ result.swapused = swapused * 1024 * 1024;
+ result.swapfree = result.swaptotal - result.swapused;
+
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ });
+ });
+}
-/***/ 52175:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+exports.mem = mem;
+function memLayout(callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.GenericPollOperation = void 0;
-const operation_js_1 = __nccwpck_require__(27826);
-const logger_js_1 = __nccwpck_require__(80692);
-const createStateProxy = () => ({
- initState: (config) => ({ config, isStarted: true }),
- setCanceled: (state) => (state.isCancelled = true),
- setError: (state, error) => (state.error = error),
- setResult: (state, result) => (state.result = result),
- setRunning: (state) => (state.isStarted = true),
- setSucceeded: (state) => (state.isCompleted = true),
- setFailed: () => {
- /** empty body */
- },
- getError: (state) => state.error,
- getResult: (state) => state.result,
- isCanceled: (state) => !!state.isCancelled,
- isFailed: (state) => !!state.error,
- isRunning: (state) => !!state.isStarted,
- isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error),
-});
-class GenericPollOperation {
- constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) {
- this.state = state;
- this.lro = lro;
- this.setErrorAsResult = setErrorAsResult;
- this.lroResourceLocationConfig = lroResourceLocationConfig;
- this.processResult = processResult;
- this.updateState = updateState;
- this.isDone = isDone;
+ function getManufacturerDarwin(manId) {
+ if ({}.hasOwnProperty.call(OSX_RAM_manufacturers, manId)) {
+ return (OSX_RAM_manufacturers[manId]);
}
- setPollerConfig(pollerConfig) {
- this.pollerConfig = pollerConfig;
+ return manId;
+ }
+
+ function getManufacturerLinux(manId) {
+ const manIdSearch = manId.replace('0x', '').toUpperCase();
+ if (manIdSearch.length === 4 && {}.hasOwnProperty.call(LINUX_RAM_manufacturers, manIdSearch)) {
+ return (LINUX_RAM_manufacturers[manIdSearch]);
}
- async update(options) {
- var _a;
- const stateProxy = createStateProxy();
- if (!this.state.isStarted) {
- this.state = Object.assign(Object.assign({}, this.state), (await (0, operation_js_1.initHttpOperation)({
- lro: this.lro,
- stateProxy,
- resourceLocationConfig: this.lroResourceLocationConfig,
- processResult: this.processResult,
- setErrorAsResult: this.setErrorAsResult,
- })));
- }
- const updateState = this.updateState;
- const isDone = this.isDone;
- if (!this.state.isCompleted && this.state.error === undefined) {
- await (0, operation_js_1.pollHttpOperation)({
- lro: this.lro,
- state: this.state,
- stateProxy,
- processResult: this.processResult,
- updateState: updateState
- ? (state, { rawResponse }) => updateState(state, rawResponse)
- : undefined,
- isDone: isDone
- ? ({ flatResponse }, state) => isDone(flatResponse, state)
- : undefined,
- options,
- setDelay: (intervalInMs) => {
- this.pollerConfig.intervalInMs = intervalInMs;
- },
- setErrorAsResult: this.setErrorAsResult,
+ return manId;
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+
+ let result = [];
+
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ exec('export LC_ALL=C; dmidecode -t memory 2>/dev/null | grep -iE "Size:|Type|Speed|Manufacturer|Form Factor|Locator|Memory Device|Serial Number|Voltage|Part Number"; unset LC_ALL', function (error, stdout) {
+ if (!error) {
+ let devices = stdout.toString().split('Memory Device');
+ devices.shift();
+ devices.forEach(function (device) {
+ let lines = device.split('\n');
+ const sizeString = util.getValue(lines, 'Size');
+ const size = sizeString.indexOf('GB') >= 0 ? parseInt(sizeString, 10) * 1024 * 1024 * 1024 : parseInt(sizeString, 10) * 1024 * 1024;
+ let bank = util.getValue(lines, 'Bank Locator');
+ if (bank.toLowerCase().indexOf('bad') >= 0) {
+ bank = '';
+ }
+ if (parseInt(util.getValue(lines, 'Size'), 10) > 0) {
+ const totalWidth = util.toInt(util.getValue(lines, 'Total Width'));
+ const dataWidth = util.toInt(util.getValue(lines, 'Data Width'));
+ result.push({
+ size,
+ bank,
+ type: util.getValue(lines, 'Type:'),
+ ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false,
+ clockSpeed: (util.getValue(lines, 'Configured Clock Speed:') ? parseInt(util.getValue(lines, 'Configured Clock Speed:'), 10) : (util.getValue(lines, 'Speed:') ? parseInt(util.getValue(lines, 'Speed:'), 10) : null)),
+ formFactor: util.getValue(lines, 'Form Factor:'),
+ manufacturer: getManufacturerLinux(util.getValue(lines, 'Manufacturer:')),
+ partNum: util.getValue(lines, 'Part Number:'),
+ serialNum: util.getValue(lines, 'Serial Number:'),
+ voltageConfigured: parseFloat(util.getValue(lines, 'Configured Voltage:')) || null,
+ voltageMin: parseFloat(util.getValue(lines, 'Minimum Voltage:')) || null,
+ voltageMax: parseFloat(util.getValue(lines, 'Maximum Voltage:')) || null,
+ });
+ } else {
+ result.push({
+ size: 0,
+ bank,
+ type: 'Empty',
+ ecc: null,
+ clockSpeed: 0,
+ formFactor: util.getValue(lines, 'Form Factor:'),
+ partNum: '',
+ serialNum: '',
+ voltageConfigured: null,
+ voltageMin: null,
+ voltageMax: null,
+ });
+ }
+ });
+ }
+ if (!result.length) {
+ result.push({
+ size: os.totalmem(),
+ bank: '',
+ type: '',
+ ecc: null,
+ clockSpeed: 0,
+ formFactor: '',
+ partNum: '',
+ serialNum: '',
+ voltageConfigured: null,
+ voltageMin: null,
+ voltageMax: null,
});
- }
- (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state);
- return this;
- }
- async cancel() {
- logger_js_1.logger.error("`cancelOperation` is deprecated because it wasn't implemented");
- return this;
- }
- /**
- * Serializes the Poller operation.
- */
- toString() {
- return JSON.stringify({
- state: this.state,
- });
- }
-}
-exports.GenericPollOperation = GenericPollOperation;
-//# sourceMappingURL=operation.js.map
-/***/ }),
+ // Try Raspberry PI
+ try {
+ let stdout = execSync('cat /proc/cpuinfo 2>/dev/null', util.execOptsLinux);
+ let lines = stdout.toString().split('\n');
+ let model = util.getValue(lines, 'hardware', ':', true).toUpperCase();
+ let version = util.getValue(lines, 'revision', ':', true).toLowerCase();
-/***/ 67130:
-/***/ ((__unused_webpack_module, exports) => {
+ if (model === 'BCM2835' || model === 'BCM2708' || model === 'BCM2709' || model === 'BCM2835' || model === 'BCM2837') {
+ const clockSpeed = {
+ '0': 400,
+ '1': 450,
+ '2': 450,
+ '3': 3200
+ };
+ result[0].type = 'LPDDR2';
+ result[0].type = version && version[2] && version[2] === '3' ? 'LPDDR4' : result[0].type;
+ result[0].ecc = false;
+ result[0].clockSpeed = version && version[2] && clockSpeed[version[2]] || 400;
+ result[0].clockSpeed = version && version[4] && version[4] === 'd' ? 500 : result[0].clockSpeed;
+ result[0].formFactor = 'SoC';
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=pollOperation.js.map
+ stdout = execSync('vcgencmd get_config sdram_freq 2>/dev/null', util.execOptsLinux);
+ lines = stdout.toString().split('\n');
+ let freq = parseInt(util.getValue(lines, 'sdram_freq', '=', true), 10) || 0;
+ if (freq) {
+ result[0].clockSpeed = freq;
+ }
-/***/ }),
+ stdout = execSync('vcgencmd measure_volts sdram_p 2>/dev/null', util.execOptsLinux);
+ lines = stdout.toString().split('\n');
+ let voltage = parseFloat(util.getValue(lines, 'volt', '=', true)) || 0;
+ if (voltage) {
+ result[0].voltageConfigured = voltage;
+ result[0].voltageMin = voltage;
+ result[0].voltageMax = voltage;
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
-/***/ 25796:
-/***/ ((__unused_webpack_module, exports) => {
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ exec('system_profiler SPMemoryDataType', function (error, stdout) {
+ if (!error) {
+ const allLines = stdout.toString().split('\n');
+ const eccStatus = util.getValue(allLines, 'ecc', ':', true).toLowerCase();
+ let devices = stdout.toString().split(' BANK ');
+ let hasBank = true;
+ if (devices.length === 1) {
+ devices = stdout.toString().split(' DIMM');
+ hasBank = false;
+ }
+ devices.shift();
+ devices.forEach(function (device) {
+ let lines = device.split('\n');
+ const bank = (hasBank ? 'BANK ' : 'DIMM') + lines[0].trim().split('/')[0];
+ const size = parseInt(util.getValue(lines, ' Size'));
+ if (size) {
+ result.push({
+ size: size * 1024 * 1024 * 1024,
+ bank: bank,
+ type: util.getValue(lines, ' Type:'),
+ ecc: eccStatus ? eccStatus === 'enabled' : null,
+ clockSpeed: parseInt(util.getValue(lines, ' Speed:'), 10),
+ formFactor: '',
+ manufacturer: getManufacturerDarwin(util.getValue(lines, ' Manufacturer:')),
+ partNum: util.getValue(lines, ' Part Number:'),
+ serialNum: util.getValue(lines, ' Serial Number:'),
+ voltageConfigured: null,
+ voltageMin: null,
+ voltageMax: null,
+ });
+ } else {
+ result.push({
+ size: 0,
+ bank: bank,
+ type: 'Empty',
+ ecc: null,
+ clockSpeed: 0,
+ formFactor: '',
+ manufacturer: '',
+ partNum: '',
+ serialNum: '',
+ voltageConfigured: null,
+ voltageMin: null,
+ voltageMax: null,
+ });
+ }
+ });
+ }
+ if (!result.length) {
+ const lines = stdout.toString().split('\n');
+ const size = parseInt(util.getValue(lines, ' Memory:'));
+ const type = util.getValue(lines, ' Type:');
+ const manufacturerId = util.getValue(lines, ' Manufacturer:');
+ if (size && type) {
+ result.push({
+ size: size * 1024 * 1024 * 1024,
+ bank: '0',
+ type,
+ ecc: false,
+ clockSpeed: null,
+ formFactor: 'SOC',
+ manufacturer: getManufacturerDarwin(manufacturerId),
+ partNum: '',
+ serialNum: '',
+ voltageConfigured: null,
+ voltageMin: null,
+ voltageMax: null,
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Poller = exports.PollerCancelledError = exports.PollerStoppedError = void 0;
-/**
- * When a poller is manually stopped through the `stopPolling` method,
- * the poller will be rejected with an instance of the PollerStoppedError.
- */
-class PollerStoppedError extends Error {
- constructor(message) {
- super(message);
- this.name = "PollerStoppedError";
- Object.setPrototypeOf(this, PollerStoppedError.prototype);
- }
-}
-exports.PollerStoppedError = PollerStoppedError;
-/**
- * When the operation is cancelled, the poller will be rejected with an instance
- * of the PollerCancelledError.
- */
-class PollerCancelledError extends Error {
- constructor(message) {
- super(message);
- this.name = "PollerCancelledError";
- Object.setPrototypeOf(this, PollerCancelledError.prototype);
- }
-}
-exports.PollerCancelledError = PollerCancelledError;
-/**
- * A class that represents the definition of a program that polls through consecutive requests
- * until it reaches a state of completion.
- *
- * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed.
- * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes.
- * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation.
- *
- * ```ts
- * const poller = new MyPoller();
- *
- * // Polling just once:
- * await poller.poll();
- *
- * // We can try to cancel the request here, by calling:
- * //
- * // await poller.cancelOperation();
- * //
- *
- * // Getting the final result:
- * const result = await poller.pollUntilDone();
- * ```
- *
- * The Poller is defined by two types, a type representing the state of the poller, which
- * must include a basic set of properties from `PollOperationState`,
- * and a return type defined by `TResult`, which can be anything.
- *
- * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having
- * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type.
- *
- * ```ts
- * class Client {
- * public async makePoller: PollerLike {
- * const poller = new MyPoller({});
- * // It might be preferred to return the poller after the first request is made,
- * // so that some information can be obtained right away.
- * await poller.poll();
- * return poller;
- * }
- * }
- *
- * const poller: PollerLike = myClient.makePoller();
- * ```
- *
- * A poller can be created through its constructor, then it can be polled until it's completed.
- * At any point in time, the state of the poller can be obtained without delay through the getOperationState method.
- * At any point in time, the intermediate forms of the result type can be requested without delay.
- * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned.
- *
- * ```ts
- * const poller = myClient.makePoller();
- * const state: MyOperationState = poller.getOperationState();
- *
- * // The intermediate result can be obtained at any time.
- * const result: MyResult | undefined = poller.getResult();
- *
- * // The final result can only be obtained after the poller finishes.
- * const result: MyResult = await poller.pollUntilDone();
- * ```
- *
- */
-// eslint-disable-next-line no-use-before-define
-class Poller {
- /**
- * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`.
- *
- * When writing an implementation of a Poller, this implementation needs to deal with the initialization
- * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's
- * operation has already been defined, at least its basic properties. The code below shows how to approach
- * the definition of the constructor of a new custom poller.
- *
- * ```ts
- * export class MyPoller extends Poller {
- * constructor({
- * // Anything you might need outside of the basics
- * }) {
- * let state: MyOperationState = {
- * privateProperty: private,
- * publicProperty: public,
- * };
- *
- * const operation = {
- * state,
- * update,
- * cancel,
- * toString
- * }
- *
- * // Sending the operation to the parent's constructor.
- * super(operation);
- *
- * // You can assign more local properties here.
- * }
- * }
- * ```
- *
- * Inside of this constructor, a new promise is created. This will be used to
- * tell the user when the poller finishes (see `pollUntilDone()`). The promise's
- * resolve and reject methods are also used internally to control when to resolve
- * or reject anyone waiting for the poller to finish.
- *
- * The constructor of a custom implementation of a poller is where any serialized version of
- * a previous poller's operation should be deserialized into the operation sent to the
- * base constructor. For example:
- *
- * ```ts
- * export class MyPoller extends Poller {
- * constructor(
- * baseOperation: string | undefined
- * ) {
- * let state: MyOperationState = {};
- * if (baseOperation) {
- * state = {
- * ...JSON.parse(baseOperation).state,
- * ...state
- * };
- * }
- * const operation = {
- * state,
- * // ...
- * }
- * super(operation);
- * }
- * }
- * ```
- *
- * @param operation - Must contain the basic properties of `PollOperation`.
- */
- constructor(operation) {
- /** controls whether to throw an error if the operation failed or was canceled. */
- this.resolveOnUnsuccessful = false;
- this.stopped = true;
- this.pollProgressCallbacks = [];
- this.operation = operation;
- this.promise = new Promise((resolve, reject) => {
- this.resolve = resolve;
- this.reject = reject;
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
});
- // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown.
- // The above warning would get thrown if `poller.poll` is called, it returns an error,
- // and pullUntilDone did not have a .catch or await try/catch on it's return value.
- this.promise.catch(() => {
- /* intentionally blank */
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_windows) {
+ // https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0a.pdf
+ const memoryTypes = 'Unknown|Other|DRAM|Synchronous DRAM|Cache DRAM|EDO|EDRAM|VRAM|SRAM|RAM|ROM|FLASH|EEPROM|FEPROM|EPROM|CDRAM|3DRAM|SDRAM|SGRAM|RDRAM|DDR|DDR2|DDR2 FB-DIMM|Reserved|DDR3|FBD2|DDR4|LPDDR|LPDDR2|LPDDR3|LPDDR4|Logical non-volatile device|HBM|HBM2|DDR5|LPDDR5'.split('|');
+ const FormFactors = 'Unknown|Other|SIP|DIP|ZIP|SOJ|Proprietary|SIMM|DIMM|TSOP|PGA|RIMM|SODIMM|SRIMM|SMD|SSMP|QFP|TQFP|SOIC|LCC|PLCC|BGA|FPBGA|LGA'.split('|');
+
+ try {
+ util.powerShell('Get-CimInstance Win32_PhysicalMemory | select DataWidth,TotalWidth,Capacity,BankLabel,MemoryType,SMBIOSMemoryType,ConfiguredClockSpeed,Speed,FormFactor,Manufacturer,PartNumber,SerialNumber,ConfiguredVoltage,MinVoltage,MaxVoltage,Tag | fl').then((stdout, error) => {
+ if (!error) {
+ let devices = stdout.toString().split(/\n\s*\n/);
+ devices.shift();
+ devices.forEach(function (device) {
+ let lines = device.split('\r\n');
+ const dataWidth = util.toInt(util.getValue(lines, 'DataWidth', ':'));
+ const totalWidth = util.toInt(util.getValue(lines, 'TotalWidth', ':'));
+ const size = parseInt(util.getValue(lines, 'Capacity', ':'), 10) || 0;
+ const tag = util.getValue(lines, 'Tag', ':');
+ const tagInt = util.splitByNumber(tag);
+ if (size) {
+ result.push({
+ size,
+ bank: util.getValue(lines, 'BankLabel', ':') + (tagInt[1] ? '/' + tagInt[1] : ''), // BankLabel
+ type: memoryTypes[parseInt(util.getValue(lines, 'MemoryType', ':'), 10) || parseInt(util.getValue(lines, 'SMBIOSMemoryType', ':'), 10)],
+ ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false,
+ clockSpeed: parseInt(util.getValue(lines, 'ConfiguredClockSpeed', ':'), 10) || parseInt(util.getValue(lines, 'Speed', ':'), 10) || 0,
+ formFactor: FormFactors[parseInt(util.getValue(lines, 'FormFactor', ':'), 10) || 0],
+ manufacturer: util.getValue(lines, 'Manufacturer', ':'),
+ partNum: util.getValue(lines, 'PartNumber', ':'),
+ serialNum: util.getValue(lines, 'SerialNumber', ':'),
+ voltageConfigured: (parseInt(util.getValue(lines, 'ConfiguredVoltage', ':'), 10) || 0) / 1000.0,
+ voltageMin: (parseInt(util.getValue(lines, 'MinVoltage', ':'), 10) || 0) / 1000.0,
+ voltageMax: (parseInt(util.getValue(lines, 'MaxVoltage', ':'), 10) || 0) / 1000.0,
+ });
+ }
+ });
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ });
+ });
+}
+
+exports.memLayout = memLayout;
+
+
+
+/***/ }),
+
+/***/ 61972:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+
+// @ts-check
+// ==================================================================================
+// network.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 9. Network
+// ----------------------------------------------------------------------------------
+
+const os = __nccwpck_require__(70857);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const fs = __nccwpck_require__(79896);
+const util = __nccwpck_require__(77496);
+
+let _platform = process.platform;
+
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+
+let _network = {};
+let _default_iface = '';
+let _ifaces = {};
+let _dhcpNics = [];
+let _networkInterfaces = [];
+let _mac = {};
+let pathToIp;
+
+function getDefaultNetworkInterface() {
+
+ let ifacename = '';
+ let ifacenameFirst = '';
+ try {
+ let ifaces = os.networkInterfaces();
+
+ let scopeid = 9999;
+
+ // fallback - "first" external interface (sorted by scopeid)
+ for (let dev in ifaces) {
+ if ({}.hasOwnProperty.call(ifaces, dev)) {
+ ifaces[dev].forEach(function (details) {
+ if (details && details.internal === false) {
+ ifacenameFirst = ifacenameFirst || dev; // fallback if no scopeid
+ if (details.scopeid && details.scopeid < scopeid) {
+ ifacename = dev;
+ scopeid = details.scopeid;
+ }
+ }
});
+ }
}
- /**
- * Starts a loop that will break only if the poller is done
- * or if the poller is stopped.
- */
- async startPolling(pollOptions = {}) {
- if (this.stopped) {
- this.stopped = false;
- }
- while (!this.isStopped() && !this.isDone()) {
- await this.poll(pollOptions);
- await this.delay();
+ ifacename = ifacename || ifacenameFirst || '';
+
+ if (_windows) {
+ // https://www.inetdaemon.com/tutorials/internet/ip/routing/default_route.shtml
+ let defaultIp = '';
+ const cmd = 'netstat -r';
+ const result = execSync(cmd, util.execOptsWin);
+ const lines = result.toString().split(os.EOL);
+ lines.forEach(line => {
+ line = line.replace(/\s+/g, ' ').trim();
+ if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) {
+ const parts = line.split(' ');
+ if (parts.length >= 5) {
+ defaultIp = parts[parts.length - 2];
+ }
}
- }
- /**
- * pollOnce does one polling, by calling to the update method of the underlying
- * poll operation to make any relevant change effective.
- *
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
- *
- * @param options - Optional properties passed to the operation's update method.
- */
- async pollOnce(options = {}) {
- if (!this.isDone()) {
- this.operation = await this.operation.update({
- abortSignal: options.abortSignal,
- fireProgress: this.fireProgress.bind(this),
+ });
+ if (defaultIp) {
+ for (let dev in ifaces) {
+ if ({}.hasOwnProperty.call(ifaces, dev)) {
+ ifaces[dev].forEach(function (details) {
+ if (details && details.address && details.address === defaultIp) {
+ ifacename = dev;
+ }
});
+ }
}
- this.processUpdatedState();
+ }
}
- /**
- * fireProgress calls the functions passed in via onProgress the method of the poller.
- *
- * It loops over all of the callbacks received from onProgress, and executes them, sending them
- * the current operation state.
- *
- * @param state - The current operation state.
- */
- fireProgress(state) {
- for (const callback of this.pollProgressCallbacks) {
- callback(state);
- }
+ if (_linux) {
+ let cmd = 'ip route 2> /dev/null | grep default';
+ let result = execSync(cmd, util.execOptsLinux);
+ let parts = result.toString().split('\n')[0].split(/\s+/);
+ if (parts[0] === 'none' && parts[5]) {
+ ifacename = parts[5];
+ } else if (parts[4]) {
+ ifacename = parts[4];
+ }
+
+ if (ifacename.indexOf(':') > -1) {
+ ifacename = ifacename.split(':')[1].trim();
+ }
}
- /**
- * Invokes the underlying operation's cancel method.
- */
- async cancelOnce(options = {}) {
- this.operation = await this.operation.cancel(options);
+ if (_darwin || _freebsd || _openbsd || _netbsd || _sunos) {
+ let cmd = '';
+ if (_linux) { cmd = 'ip route 2> /dev/null | grep default | awk \'{print $5}\''; }
+ if (_darwin) { cmd = 'route -n get default 2>/dev/null | grep interface: | awk \'{print $2}\''; }
+ if (_freebsd || _openbsd || _netbsd || _sunos) { cmd = 'route get 0.0.0.0 | grep interface:'; }
+ let result = execSync(cmd);
+ ifacename = result.toString().split('\n')[0];
+ if (ifacename.indexOf(':') > -1) {
+ ifacename = ifacename.split(':')[1].trim();
+ }
}
- /**
- * Returns a promise that will resolve once a single polling request finishes.
- * It does this by calling the update method of the Poller's operation.
- *
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
- *
- * @param options - Optional properties passed to the operation's update method.
- */
- poll(options = {}) {
- if (!this.pollOncePromise) {
- this.pollOncePromise = this.pollOnce(options);
- const clearPollOncePromise = () => {
- this.pollOncePromise = undefined;
- };
- this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject);
+ } catch (e) {
+ util.noop();
+ }
+ if (ifacename) { _default_iface = ifacename; }
+ return _default_iface;
+}
+
+exports.getDefaultNetworkInterface = getDefaultNetworkInterface;
+
+function getMacAddresses() {
+ let iface = '';
+ let mac = '';
+ let result = {};
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ if (typeof pathToIp === 'undefined') {
+ try {
+ const lines = execSync('which ip', util.execOptsLinux).toString().split('\n');
+ if (lines.length && lines[0].indexOf(':') === -1 && lines[0].indexOf('/') === 0) {
+ pathToIp = lines[0];
+ } else {
+ pathToIp = '';
}
- return this.pollOncePromise;
+ } catch (e) {
+ pathToIp = '';
+ }
}
- processUpdatedState() {
- if (this.operation.state.error) {
- this.stopped = true;
- if (!this.resolveOnUnsuccessful) {
- this.reject(this.operation.state.error);
- throw this.operation.state.error;
- }
- }
- if (this.operation.state.isCancelled) {
- this.stopped = true;
- if (!this.resolveOnUnsuccessful) {
- const error = new PollerCancelledError("Operation was canceled");
- this.reject(error);
- throw error;
+ try {
+ const cmd = 'export LC_ALL=C; ' + ((pathToIp) ? pathToIp + ' link show up' : '/sbin/ifconfig') + '; unset LC_ALL';
+ let res = execSync(cmd, util.execOptsLinux);
+ const lines = res.toString().split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i] && lines[i][0] !== ' ') {
+ if (pathToIp) {
+ let nextline = lines[i + 1].trim().split(' ');
+ if (nextline[0] === 'link/ether') {
+ iface = lines[i].split(' ')[1];
+ iface = iface.slice(0, iface.length - 1);
+ mac = nextline[1];
}
+ } else {
+ iface = lines[i].split(' ')[0];
+ mac = lines[i].split('HWaddr ')[1];
+ }
+
+ if (iface && mac) {
+ result[iface] = mac.trim();
+ iface = '';
+ mac = '';
+ }
}
- if (this.isDone() && this.resolve) {
- // If the poller has finished polling, this means we now have a result.
- // However, it can be the case that TResult is instantiated to void, so
- // we are not expecting a result anyway. To assert that we might not
- // have a result eventually after finishing polling, we cast the result
- // to TResult.
- this.resolve(this.getResult());
- }
+ }
+ } catch (e) {
+ util.noop();
}
- /**
- * Returns a promise that will resolve once the underlying operation is completed.
- */
- async pollUntilDone(pollOptions = {}) {
- if (this.stopped) {
- this.startPolling(pollOptions).catch(this.reject);
+ }
+ if (_darwin) {
+ try {
+ const cmd = '/sbin/ifconfig';
+ let res = execSync(cmd);
+ const lines = res.toString().split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i] && lines[i][0] !== '\t' && lines[i].indexOf(':') > 0) {
+ iface = lines[i].split(':')[0];
+ } else if (lines[i].indexOf('\tether ') === 0) {
+ mac = lines[i].split('\tether ')[1];
+ if (iface && mac) {
+ result[iface] = mac.trim();
+ iface = '';
+ mac = '';
+ }
}
- // This is needed because the state could have been updated by
- // `cancelOperation`, e.g. the operation is canceled or an error occurred.
- this.processUpdatedState();
- return this.promise;
- }
- /**
- * Invokes the provided callback after each polling is completed,
- * sending the current state of the poller's operation.
- *
- * It returns a method that can be used to stop receiving updates on the given callback function.
- */
- onProgress(callback) {
- this.pollProgressCallbacks.push(callback);
- return () => {
- this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback);
- };
- }
- /**
- * Returns true if the poller has finished polling.
- */
- isDone() {
- const state = this.operation.state;
- return Boolean(state.isCompleted || state.isCancelled || state.error);
+ }
+ } catch (e) {
+ util.noop();
}
- /**
- * Stops the poller from continuing to poll.
- */
- stopPolling() {
- if (!this.stopped) {
- this.stopped = true;
- if (this.reject) {
- this.reject(new PollerStoppedError("This poller is already stopped"));
- }
+ }
+ return result;
+}
+
+function networkInterfaceDefault(callback) {
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = getDefaultNetworkInterface();
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+}
+
+exports.networkInterfaceDefault = networkInterfaceDefault;
+
+// --------------------------
+// NET - interfaces
+
+function parseLinesWindowsNics(sections, nconfigsections) {
+ let nics = [];
+ for (let i in sections) {
+ try {
+ if ({}.hasOwnProperty.call(sections, i)) {
+
+ if (sections[i].trim() !== '') {
+
+ let lines = sections[i].trim().split('\r\n');
+ let linesNicConfig = null;
+ try {
+ linesNicConfig = nconfigsections && nconfigsections[i] ? nconfigsections[i].trim().split('\r\n') : [];
+ } catch (e) {
+ util.noop();
+ }
+ let netEnabled = util.getValue(lines, 'NetEnabled', ':');
+ let adapterType = util.getValue(lines, 'AdapterTypeID', ':') === '9' ? 'wireless' : 'wired';
+ let ifacename = util.getValue(lines, 'Name', ':').replace(/\]/g, ')').replace(/\[/g, '(');
+ let iface = util.getValue(lines, 'NetConnectionID', ':').replace(/\]/g, ')').replace(/\[/g, '(');
+ if (ifacename.toLowerCase().indexOf('wi-fi') >= 0 || ifacename.toLowerCase().indexOf('wireless') >= 0) {
+ adapterType = 'wireless';
+ }
+ if (netEnabled !== '') {
+ const speed = parseInt(util.getValue(lines, 'speed', ':').trim(), 10) / 1000000;
+ nics.push({
+ mac: util.getValue(lines, 'MACAddress', ':').toLowerCase(),
+ dhcp: util.getValue(linesNicConfig, 'dhcpEnabled', ':').toLowerCase() === 'true',
+ name: ifacename,
+ iface,
+ netEnabled: netEnabled === 'TRUE',
+ speed: isNaN(speed) ? null : speed,
+ operstate: util.getValue(lines, 'NetConnectionStatus', ':') === '2' ? 'up' : 'down',
+ type: adapterType
+ });
+ }
}
+ }
+ } catch (e) {
+ util.noop();
}
- /**
- * Returns true if the poller is stopped.
- */
- isStopped() {
- return this.stopped;
- }
- /**
- * Attempts to cancel the underlying operation.
- *
- * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
- *
- * If it's called again before it finishes, it will throw an error.
- *
- * @param options - Optional properties passed to the operation's update method.
- */
- cancelOperation(options = {}) {
- if (!this.cancelPromise) {
- this.cancelPromise = this.cancelOnce(options);
- }
- else if (options.abortSignal) {
- throw new Error("A cancel request is currently pending");
+ }
+ return nics;
+}
+
+function getWindowsNics() {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let cmd = 'Get-CimInstance Win32_NetworkAdapter | fl *' + '; echo \'#-#-#-#\';';
+ cmd += 'Get-CimInstance Win32_NetworkAdapterConfiguration | fl DHCPEnabled' + '';
+ try {
+ util.powerShell(cmd).then((data) => {
+ data = data.split('#-#-#-#');
+ const nsections = (data[0] || '').split(/\n\s*\n/);
+ const nconfigsections = (data[1] || '').split(/\n\s*\n/);
+ resolve(parseLinesWindowsNics(nsections, nconfigsections));
+ });
+ } catch (e) {
+ resolve([]);
+ }
+ });
+ });
+}
+
+function getWindowsDNSsuffixes() {
+
+ let iface = {};
+
+ let dnsSuffixes = {
+ primaryDNS: '',
+ exitCode: 0,
+ ifaces: [],
+ };
+
+ try {
+ const ipconfig = execSync('ipconfig /all', util.execOptsWin);
+ const ipconfigArray = ipconfig.split('\r\n\r\n');
+
+ ipconfigArray.forEach((element, index) => {
+
+ if (index == 1) {
+ const longPrimaryDNS = element.split('\r\n').filter((element) => {
+ return element.toUpperCase().includes('DNS');
+ });
+ const primaryDNS = longPrimaryDNS[0].substring(longPrimaryDNS[0].lastIndexOf(':') + 1);
+ dnsSuffixes.primaryDNS = primaryDNS.trim();
+ if (!dnsSuffixes.primaryDNS) { dnsSuffixes.primaryDNS = 'Not defined'; }
+ }
+ if (index > 1) {
+ if (index % 2 == 0) {
+ const name = element.substring(element.lastIndexOf(' ') + 1).replace(':', '');
+ iface.name = name;
+ } else {
+ const connectionSpecificDNS = element.split('\r\n').filter((element) => {
+ return element.toUpperCase().includes('DNS');
+ });
+ const dnsSuffix = connectionSpecificDNS[0].substring(connectionSpecificDNS[0].lastIndexOf(':') + 1);
+ iface.dnsSuffix = dnsSuffix.trim();
+ dnsSuffixes.ifaces.push(iface);
+ iface = {};
}
- return this.cancelPromise;
- }
- /**
- * Returns the state of the operation.
- *
- * Even though TState will be the same type inside any of the methods of any extension of the Poller class,
- * implementations of the pollers can customize what's shared with the public by writing their own
- * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller
- * and a public type representing a safe to share subset of the properties of the internal state.
- * Their definition of getOperationState can then return their public type.
- *
- * Example:
- *
- * ```ts
- * // Let's say we have our poller's operation state defined as:
- * interface MyOperationState extends PollOperationState {
- * privateProperty?: string;
- * publicProperty?: string;
- * }
- *
- * // To allow us to have a true separation of public and private state, we have to define another interface:
- * interface PublicState extends PollOperationState {
- * publicProperty?: string;
- * }
- *
- * // Then, we define our Poller as follows:
- * export class MyPoller extends Poller {
- * // ... More content is needed here ...
- *
- * public getOperationState(): PublicState {
- * const state: PublicState = this.operation.state;
- * return {
- * // Properties from PollOperationState
- * isStarted: state.isStarted,
- * isCompleted: state.isCompleted,
- * isCancelled: state.isCancelled,
- * error: state.error,
- * result: state.result,
- *
- * // The only other property needed by PublicState.
- * publicProperty: state.publicProperty
- * }
- * }
- * }
- * ```
- *
- * You can see this in the tests of this repository, go to the file:
- * `../test/utils/testPoller.ts`
- * and look for the getOperationState implementation.
- */
- getOperationState() {
- return this.operation.state;
- }
- /**
- * Returns the result value of the operation,
- * regardless of the state of the poller.
- * It can return undefined or an incomplete form of the final TResult value
- * depending on the implementation.
- */
- getResult() {
- const state = this.operation.state;
- return state.result;
- }
- /**
- * Returns a serialized version of the poller's operation
- * by invoking the operation's toString method.
- */
- toString() {
- return this.operation.toString();
+ }
+ });
+
+ return dnsSuffixes;
+ } catch (error) {
+ return {
+ primaryDNS: '',
+ exitCode: 0,
+ ifaces: [],
+ };
+ }
+}
+
+function getWindowsIfaceDNSsuffix(ifaces, ifacename) {
+ let dnsSuffix = '';
+ // Adding (.) to ensure ifacename compatibility when duplicated iface-names
+ const interfaceName = ifacename + '.';
+ try {
+ const connectionDnsSuffix = ifaces.filter((iface) => {
+ return interfaceName.includes(iface.name + '.');
+ }).map((iface) => iface.dnsSuffix);
+ if (connectionDnsSuffix[0]) {
+ dnsSuffix = connectionDnsSuffix[0];
}
+ if (!dnsSuffix) { dnsSuffix = ''; }
+ return dnsSuffix;
+ } catch (error) {
+ return 'Unknown';
+ }
}
-exports.Poller = Poller;
-//# sourceMappingURL=poller.js.map
-/***/ }),
+function getWindowsWiredProfilesInformation() {
+ try {
+ const result = execSync('netsh lan show profiles', util.execOptsWin);
+ const profileList = result.split('\r\nProfile on interface');
+ return profileList;
+ } catch (error) {
+ if (error.status === 1 && error.stdout.includes('AutoConfig')) {
+ return 'Disabled';
+ }
+ return [];
+ }
+}
-/***/ 80692:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function getWindowsWirelessIfaceSSID(interfaceName) {
+ try {
+ const result = execSync(`netsh wlan show interface name="${interfaceName}" | findstr "SSID"`, util.execOptsWin);
+ const SSID = result.split('\r\n').shift();
+ const parseSSID = SSID.split(':').pop().trim();
+ return parseSSID;
+ } catch (error) {
+ return 'Unknown';
+ }
+}
+function getWindowsIEEE8021x(connectionType, iface, ifaces) {
+ let i8021x = {
+ state: 'Unknown',
+ protocol: 'Unknown',
+ };
+ if (ifaces === 'Disabled') {
+ i8021x.state = 'Disabled';
+ i8021x.protocol = 'Not defined';
+ return i8021x;
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.logger = void 0;
-const logger_1 = __nccwpck_require__(50143);
-/**
- * The `@azure/logger` configuration for this package.
- * @internal
- */
-exports.logger = (0, logger_1.createClientLogger)("core-lro");
-//# sourceMappingURL=logger.js.map
+ if (connectionType == 'wired' && ifaces.length > 0) {
+ try {
+ // Get 802.1x information by interface name
+ const iface8021xInfo = ifaces.find((element) => {
+ return element.includes(iface + '\r\n');
+ });
+ const arrayIface8021xInfo = iface8021xInfo.split('\r\n');
+ const state8021x = arrayIface8021xInfo.find((element) => {
+ return element.includes('802.1x');
+ });
-/***/ }),
+ if (state8021x.includes('Disabled')) {
+ i8021x.state = 'Disabled';
+ i8021x.protocol = 'Not defined';
+ } else if (state8021x.includes('Enabled')) {
+ const protocol8021x = arrayIface8021xInfo.find((element) => {
+ return element.includes('EAP');
+ });
+ i8021x.protocol = protocol8021x.split(':').pop();
+ i8021x.state = 'Enabled';
+ }
+ } catch (error) {
+ return i8021x;
+ }
+ } else if (connectionType == 'wireless') {
-/***/ 94288:
-/***/ ((__unused_webpack_module, exports) => {
+ let i8021xState = '';
+ let i8021xProtocol = '';
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.terminalStates = exports.POLL_INTERVAL_IN_MS = void 0;
-/**
- * The default time interval to wait before sending the next polling request.
- */
-exports.POLL_INTERVAL_IN_MS = 2000;
-/**
- * The closed set of terminal states.
- */
-exports.terminalStates = ["succeeded", "canceled", "failed"];
-//# sourceMappingURL=constants.js.map
-/***/ }),
+ try {
+ const SSID = getWindowsWirelessIfaceSSID(iface);
+ if (SSID !== 'Unknown') {
-/***/ 26588:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ let ifaceSanitized = '';
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(SSID);
+ const l = util.mathMin(s.length, 32);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ ifaceSanitized = ifaceSanitized + s[i];
+ }
+ }
+ i8021xState = execSync(`netsh wlan show profiles "${ifaceSanitized}" | findstr "802.1X"`, util.execOptsWin);
+ i8021xProtocol = execSync(`netsh wlan show profiles "${ifaceSanitized}" | findstr "EAP"`, util.execOptsWin);
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.pollOperation = exports.initOperation = exports.deserializeState = void 0;
-const logger_js_1 = __nccwpck_require__(80692);
-const constants_js_1 = __nccwpck_require__(94288);
-/**
- * Deserializes the state
- */
-function deserializeState(serializedState) {
- try {
- return JSON.parse(serializedState).state;
+ if (i8021xState.includes(':') && i8021xProtocol.includes(':')) {
+ i8021x.state = i8021xState.split(':').pop();
+ i8021x.protocol = i8021xProtocol.split(':').pop();
+ }
+ } catch (error) {
+ if (error.status === 1 && error.stdout.includes('AutoConfig')) {
+ i8021x.state = 'Disabled';
+ i8021x.protocol = 'Not defined';
+ }
+ return i8021x;
}
- catch (e) {
- throw new Error(`Unable to deserialize input state: ${serializedState}`);
+ }
+
+ return i8021x;
+}
+
+function splitSectionsNics(lines) {
+ const result = [];
+ let section = [];
+ lines.forEach(function (line) {
+ if (!line.startsWith('\t') && !line.startsWith(' ')) {
+ if (section.length) {
+ result.push(section);
+ section = [];
+ }
}
+ section.push(line);
+ });
+ if (section.length) {
+ result.push(section);
+ }
+ return result;
}
-exports.deserializeState = deserializeState;
-function setStateError(inputs) {
- const { state, stateProxy, isOperationError } = inputs;
- return (error) => {
- if (isOperationError(error)) {
- stateProxy.setError(state, error);
- stateProxy.setFailed(state);
- }
- throw error;
+
+function parseLinesDarwinNics(sections) {
+ let nics = [];
+ sections.forEach(section => {
+ let nic = {
+ iface: '',
+ mtu: null,
+ mac: '',
+ ip6: '',
+ ip4: '',
+ speed: null,
+ type: '',
+ operstate: '',
+ duplex: '',
+ internal: false
};
-}
-function appendReadableErrorMessage(currentMessage, innerMessage) {
- let message = currentMessage;
- if (message.slice(-1) !== ".") {
- message = message + ".";
+ const first = section[0];
+ nic.iface = first.split(':')[0].trim();
+ let parts = first.split('> mtu');
+ nic.mtu = parts.length > 1 ? parseInt(parts[1], 10) : null;
+ if (isNaN(nic.mtu)) {
+ nic.mtu = null;
}
- return message + " " + innerMessage;
-}
-function simplifyError(err) {
- let message = err.message;
- let code = err.code;
- let curErr = err;
- while (curErr.innererror) {
- curErr = curErr.innererror;
- code = curErr.code;
- message = appendReadableErrorMessage(message, curErr.message);
+ nic.internal = parts[0].toLowerCase().indexOf('loopback') > -1;
+ section.forEach(line => {
+ if (line.trim().startsWith('ether ')) {
+ nic.mac = line.split('ether ')[1].toLowerCase().trim();
+ }
+ if (line.trim().startsWith('inet6 ') && !nic.ip6) {
+ nic.ip6 = line.split('inet6 ')[1].toLowerCase().split('%')[0].split(' ')[0];
+ }
+ if (line.trim().startsWith('inet ') && !nic.ip4) {
+ nic.ip4 = line.split('inet ')[1].toLowerCase().split(' ')[0];
+ }
+ });
+ let speed = util.getValue(section, 'link rate');
+ nic.speed = speed ? parseFloat(speed) : null;
+ if (nic.speed === null) {
+ speed = util.getValue(section, 'uplink rate');
+ nic.speed = speed ? parseFloat(speed) : null;
+ if (nic.speed !== null && speed.toLowerCase().indexOf('gbps') >= 0) {
+ nic.speed = nic.speed * 1000;
+ }
+ } else {
+ if (speed.toLowerCase().indexOf('gbps') >= 0) {
+ nic.speed = nic.speed * 1000;
+ }
}
- return {
- code,
- message,
- };
+ nic.type = util.getValue(section, 'type').toLowerCase().indexOf('wi-fi') > -1 ? 'wireless' : 'wired';
+ const operstate = util.getValue(section, 'status').toLowerCase();
+ nic.operstate = (operstate === 'active' ? 'up' : (operstate === 'inactive' ? 'down' : 'unknown'));
+ nic.duplex = util.getValue(section, 'media').toLowerCase().indexOf('half-duplex') > -1 ? 'half' : 'full';
+ if (nic.ip6 || nic.ip4 || nic.mac) {
+ nics.push(nic);
+ }
+ });
+ return nics;
}
-function processOperationStatus(result) {
- const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result;
- switch (status) {
- case "succeeded": {
- stateProxy.setSucceeded(state);
- break;
+
+function getDarwinNics() {
+ const cmd = '/sbin/ifconfig -v';
+ try {
+ const lines = execSync(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n');
+ const nsections = splitSectionsNics(lines);
+ return (parseLinesDarwinNics(nsections));
+ } catch (e) {
+ return [];
+ }
+}
+
+function getLinuxIfaceConnectionName(interfaceName) {
+ const cmd = `nmcli device status 2>/dev/null | grep ${interfaceName}`;
+
+ try {
+ const result = execSync(cmd, util.execOptsLinux).toString();
+ const resultFormat = result.replace(/\s+/g, ' ').trim();
+ const connectionNameLines = resultFormat.split(' ').slice(3);
+ const connectionName = connectionNameLines.join(' ');
+ return connectionName != '--' ? connectionName : '';
+ } catch (e) {
+ return '';
+ }
+}
+
+function checkLinuxDCHPInterfaces(file) {
+ let result = [];
+ try {
+ let cmd = `cat ${file} 2> /dev/null | grep 'iface\\|source'`;
+ const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
+
+ lines.forEach(line => {
+ const parts = line.replace(/\s+/g, ' ').trim().split(' ');
+ if (parts.length >= 4) {
+ if (line.toLowerCase().indexOf(' inet ') >= 0 && line.toLowerCase().indexOf('dhcp') >= 0) {
+ result.push(parts[1]);
}
- case "failed": {
- const err = getError === null || getError === void 0 ? void 0 : getError(response);
- let postfix = "";
- if (err) {
- const { code, message } = simplifyError(err);
- postfix = `. ${code}. ${message}`;
+ }
+ if (line.toLowerCase().includes('source')) {
+ let file = line.split(' ')[1];
+ result = result.concat(checkLinuxDCHPInterfaces(file));
+ }
+ });
+ } catch (e) {
+ util.noop();
+ }
+ return result;
+}
+
+function getLinuxDHCPNics() {
+ // alternate methods getting interfaces using DHCP
+ let cmd = 'ip a 2> /dev/null';
+ let result = [];
+ try {
+ const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
+ const nsections = splitSectionsNics(lines);
+ result = (parseLinuxDHCPNics(nsections));
+ } catch (e) {
+ util.noop();
+ }
+ try {
+ result = checkLinuxDCHPInterfaces('/etc/network/interfaces');
+ } catch (e) {
+ util.noop();
+ }
+ return result;
+}
+
+function parseLinuxDHCPNics(sections) {
+ const result = [];
+ if (sections && sections.length) {
+ sections.forEach(lines => {
+ if (lines && lines.length) {
+ const parts = lines[0].split(':');
+ if (parts.length > 2) {
+ for (let line of lines) {
+ if (line.indexOf(' inet ') >= 0 && line.indexOf(' dynamic ') >= 0) {
+ const parts2 = line.split(' ');
+ const nic = parts2[parts2.length - 1].trim();
+ result.push(nic);
+ break;
}
- const errStr = `The long-running operation has failed${postfix}`;
- stateProxy.setError(state, new Error(errStr));
- stateProxy.setFailed(state);
- logger_js_1.logger.warning(errStr);
- break;
- }
- case "canceled": {
- stateProxy.setCanceled(state);
- break;
+ }
}
- }
- if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) ||
- (isDone === undefined &&
- ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) {
- stateProxy.setResult(state, buildResult({
- response,
- state,
- processResult,
- }));
- }
+ }
+ });
+ }
+ return result;
}
-function buildResult(inputs) {
- const { processResult, response, state } = inputs;
- return processResult ? processResult(response, state) : response;
+
+function getLinuxIfaceDHCPstatus(iface, connectionName, DHCPNics) {
+ let result = false;
+ if (connectionName) {
+ const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.method;`;
+ try {
+ const lines = execSync(cmd, util.execOptsLinux).toString();
+ const resultFormat = lines.replace(/\s+/g, ' ').trim();
+
+ let dhcStatus = resultFormat.split(' ').slice(1).toString();
+ switch (dhcStatus) {
+ case 'auto':
+ result = true;
+ break;
+
+ default:
+ result = false;
+ break;
+ }
+ return result;
+ } catch (e) {
+ return (DHCPNics.indexOf(iface) >= 0);
+ }
+ } else {
+ return (DHCPNics.indexOf(iface) >= 0);
+ }
}
-/**
- * Initiates the long-running operation.
- */
-async function initOperation(inputs) {
- const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs;
- const { operationLocation, resourceLocation, metadata, response } = await init();
- if (operationLocation)
- withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
- const config = {
- metadata,
- operationLocation,
- resourceLocation,
- };
- logger_js_1.logger.verbose(`LRO: Operation description:`, config);
- const state = stateProxy.initState(config);
- const status = getOperationStatus({ response, state, operationLocation });
- processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult });
- return state;
+
+function getDarwinIfaceDHCPstatus(iface) {
+ let result = false;
+ const cmd = `ipconfig getpacket "${iface}" 2>/dev/null | grep lease_time;`;
+ try {
+ const lines = execSync(cmd).toString().split('\n');
+ if (lines.length && lines[0].startsWith('lease_time')) {
+ result = true;
+ }
+ } catch (e) {
+ util.noop();
+ }
+ return result;
}
-exports.initOperation = initOperation;
-async function pollOperationHelper(inputs) {
- const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs;
- const response = await poll(operationLocation, options).catch(setStateError({
- state,
- stateProxy,
- isOperationError,
- }));
- const status = getOperationStatus(response, state);
- logger_js_1.logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${constants_js_1.terminalStates.includes(status) ? "Stopped" : "Running"}`);
- if (status === "succeeded") {
- const resourceLocation = getResourceLocation(response, state);
- if (resourceLocation !== undefined) {
- return {
- response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })),
- status,
- };
- }
+
+function getLinuxIfaceDNSsuffix(connectionName) {
+ if (connectionName) {
+ const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.dns-search;`;
+ try {
+ const result = execSync(cmd, util.execOptsLinux).toString();
+ const resultFormat = result.replace(/\s+/g, ' ').trim();
+ const dnsSuffix = resultFormat.split(' ').slice(1).toString();
+ return dnsSuffix == '--' ? 'Not defined' : dnsSuffix;
+ } catch (e) {
+ return 'Unknown';
}
- return { response, status };
+ } else {
+ return 'Unknown';
+ }
}
-/** Polls the long-running operation. */
-async function pollOperation(inputs) {
- const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult, } = inputs;
- const { operationLocation } = state.config;
- if (operationLocation !== undefined) {
- const { response, status } = await pollOperationHelper({
- poll,
- getOperationStatus,
- state,
- stateProxy,
- operationLocation,
- getResourceLocation,
- isOperationError,
- options,
- });
- processOperationStatus({
- status,
- response,
- state,
- stateProxy,
- isDone,
- processResult,
- getError,
- setErrorAsResult,
- });
- if (!constants_js_1.terminalStates.includes(status)) {
- const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response);
- if (intervalInMs)
- setDelay(intervalInMs);
- const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state);
- if (location !== undefined) {
- const isUpdated = operationLocation !== location;
- state.config.operationLocation = location;
- withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated);
- }
- else
- withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
- }
- updateState === null || updateState === void 0 ? void 0 : updateState(state, response);
+
+function getLinuxIfaceIEEE8021xAuth(connectionName) {
+ if (connectionName) {
+ const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep 802-1x.eap;`;
+ try {
+ const result = execSync(cmd, util.execOptsLinux).toString();
+ const resultFormat = result.replace(/\s+/g, ' ').trim();
+ const authenticationProtocol = resultFormat.split(' ').slice(1).toString();
+
+
+ return authenticationProtocol == '--' ? '' : authenticationProtocol;
+ } catch (e) {
+ return 'Not defined';
}
+ } else {
+ return 'Not defined';
+ }
}
-exports.pollOperation = pollOperation;
-//# sourceMappingURL=operation.js.map
-/***/ }),
+function getLinuxIfaceIEEE8021xState(authenticationProtocol) {
+ if (authenticationProtocol) {
+ if (authenticationProtocol == 'Not defined') {
+ return 'Disabled';
+ }
+ return 'Enabled';
+ } else {
+ return 'Unknown';
+ }
+}
-/***/ 81327:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function testVirtualNic(iface, ifaceName, mac) {
+ const virtualMacs = ['00:00:00:00:00:00', '00:03:FF', '00:05:69', '00:0C:29', '00:0F:4B', '00:13:07', '00:13:BE', '00:15:5d', '00:16:3E', '00:1C:42', '00:21:F6', '00:24:0B', '00:50:56', '00:A0:B1', '00:E0:C8', '08:00:27', '0A:00:27', '18:92:2C', '16:DF:49', '3C:F3:92', '54:52:00', 'FC:15:97'];
+ if (mac) {
+ return virtualMacs.filter(item => { return mac.toUpperCase().toUpperCase().startsWith(item.substring(0, mac.length)); }).length > 0 ||
+ iface.toLowerCase().indexOf(' virtual ') > -1 ||
+ ifaceName.toLowerCase().indexOf(' virtual ') > -1 ||
+ iface.toLowerCase().indexOf('vethernet ') > -1 ||
+ ifaceName.toLowerCase().indexOf('vethernet ') > -1 ||
+ iface.toLowerCase().startsWith('veth') ||
+ ifaceName.toLowerCase().startsWith('veth') ||
+ iface.toLowerCase().startsWith('vboxnet') ||
+ ifaceName.toLowerCase().startsWith('vboxnet');
+ } else { return false; }
+}
+function networkInterfaces(callback, rescan, defaultString) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.buildCreatePoller = void 0;
-const operation_js_1 = __nccwpck_require__(26588);
-const constants_js_1 = __nccwpck_require__(94288);
-const core_util_1 = __nccwpck_require__(30991);
-const createStateProxy = () => ({
- /**
- * The state at this point is created to be of type OperationState.
- * It will be updated later to be of type TState when the
- * customer-provided callback, `updateState`, is called during polling.
- */
- initState: (config) => ({ status: "running", config }),
- setCanceled: (state) => (state.status = "canceled"),
- setError: (state, error) => (state.error = error),
- setResult: (state, result) => (state.result = result),
- setRunning: (state) => (state.status = "running"),
- setSucceeded: (state) => (state.status = "succeeded"),
- setFailed: (state) => (state.status = "failed"),
- getError: (state) => state.error,
- getResult: (state) => state.result,
- isCanceled: (state) => state.status === "canceled",
- isFailed: (state) => state.status === "failed",
- isRunning: (state) => state.status === "running",
- isSucceeded: (state) => state.status === "succeeded",
-});
-/**
- * Returns a poller factory.
- */
-function buildCreatePoller(inputs) {
- const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, getError, resolveOnUnsuccessful, } = inputs;
- return async ({ init, poll }, options) => {
- const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, restoreFrom, } = options || {};
- const stateProxy = createStateProxy();
- const withOperationLocation = withOperationLocationCallback
- ? (() => {
- let called = false;
- return (operationLocation, isUpdated) => {
- if (isUpdated)
- withOperationLocationCallback(operationLocation);
- else if (!called)
- withOperationLocationCallback(operationLocation);
- called = true;
- };
- })()
- : undefined;
- const state = restoreFrom
- ? (0, operation_js_1.deserializeState)(restoreFrom)
- : await (0, operation_js_1.initOperation)({
- init,
- stateProxy,
- processResult,
- getOperationStatus: getStatusFromInitialResponse,
- withOperationLocation,
- setErrorAsResult: !resolveOnUnsuccessful,
- });
- let resultPromise;
- const abortController = new AbortController();
- const handlers = new Map();
- const handleProgressEvents = async () => handlers.forEach((h) => h(state));
- const cancelErrMsg = "Operation was canceled";
- let currentPollIntervalInMs = intervalInMs;
- const poller = {
- getOperationState: () => state,
- getResult: () => state.result,
- isDone: () => ["succeeded", "failed", "canceled"].includes(state.status),
- isStopped: () => resultPromise === undefined,
- stopPolling: () => {
- abortController.abort();
- },
- toString: () => JSON.stringify({
- state,
- }),
- onProgress: (callback) => {
- const s = Symbol();
- handlers.set(s, callback);
- return () => handlers.delete(s);
- },
- pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => {
- const { abortSignal: inputAbortSignal } = pollOptions || {};
- // In the future we can use AbortSignal.any() instead
- function abortListener() {
- abortController.abort();
- }
- const abortSignal = abortController.signal;
- if (inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.aborted) {
- abortController.abort();
- }
- else if (!abortSignal.aborted) {
- inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.addEventListener("abort", abortListener, { once: true });
- }
- try {
- if (!poller.isDone()) {
- await poller.poll({ abortSignal });
- while (!poller.isDone()) {
- await (0, core_util_1.delay)(currentPollIntervalInMs, { abortSignal });
- await poller.poll({ abortSignal });
- }
- }
- }
- finally {
- inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.removeEventListener("abort", abortListener);
- }
- if (resolveOnUnsuccessful) {
- return poller.getResult();
- }
- else {
- switch (state.status) {
- case "succeeded":
- return poller.getResult();
- case "canceled":
- throw new Error(cancelErrMsg);
- case "failed":
- throw state.error;
- case "notStarted":
- case "running":
- throw new Error(`Polling completed without succeeding or failing`);
- }
- }
- })().finally(() => {
- resultPromise = undefined;
- }))),
- async poll(pollOptions) {
- if (resolveOnUnsuccessful) {
- if (poller.isDone())
- return;
- }
- else {
- switch (state.status) {
- case "succeeded":
- return;
- case "canceled":
- throw new Error(cancelErrMsg);
- case "failed":
- throw state.error;
- }
- }
- await (0, operation_js_1.pollOperation)({
- poll,
- state,
- stateProxy,
- getOperationLocation,
- isOperationError,
- withOperationLocation,
- getPollingInterval,
- getOperationStatus: getStatusFromPollResponse,
- getResourceLocation,
- processResult,
- getError,
- updateState,
- options: pollOptions,
- setDelay: (pollIntervalInMs) => {
- currentPollIntervalInMs = pollIntervalInMs;
- },
- setErrorAsResult: !resolveOnUnsuccessful,
- });
- await handleProgressEvents();
- if (!resolveOnUnsuccessful) {
- switch (state.status) {
- case "canceled":
- throw new Error(cancelErrMsg);
- case "failed":
- throw state.error;
- }
- }
- },
- };
- return poller;
- };
-}
-exports.buildCreatePoller = buildCreatePoller;
-//# sourceMappingURL=poller.js.map
+ if (typeof callback === 'string') {
+ defaultString = callback;
+ rescan = true;
+ callback = null;
+ }
-/***/ }),
+ if (typeof callback === 'boolean') {
+ rescan = callback;
+ callback = null;
+ defaultString = '';
+ }
+ if (typeof rescan === 'undefined') {
+ rescan = true;
+ }
+ defaultString = defaultString || '';
+ defaultString = '' + defaultString;
-/***/ 91791:
-/***/ ((__unused_webpack_module, exports) => {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let ifaces = os.networkInterfaces();
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.DEFAULT_RETRY_POLICY_COUNT = exports.SDK_VERSION = void 0;
-exports.SDK_VERSION = "1.18.1";
-exports.DEFAULT_RETRY_POLICY_COUNT = 3;
-//# sourceMappingURL=constants.js.map
+ let result = [];
+ let nics = [];
+ let dnsSuffixes = [];
+ let nics8021xInfo = [];
+ // seperate handling in OSX
+ if (_darwin || _freebsd || _openbsd || _netbsd) {
+ if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
+ // no changes - just return object
+ result = _networkInterfaces;
-/***/ }),
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ const defaultInterface = getDefaultNetworkInterface();
+ _ifaces = JSON.parse(JSON.stringify(ifaces));
-/***/ 1130:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ nics = getDarwinNics();
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createPipelineFromOptions = createPipelineFromOptions;
-const logPolicy_js_1 = __nccwpck_require__(19937);
-const pipeline_js_1 = __nccwpck_require__(37050);
-const redirectPolicy_js_1 = __nccwpck_require__(86947);
-const userAgentPolicy_js_1 = __nccwpck_require__(69795);
-const multipartPolicy_js_1 = __nccwpck_require__(77915);
-const decompressResponsePolicy_js_1 = __nccwpck_require__(13299);
-const defaultRetryPolicy_js_1 = __nccwpck_require__(47494);
-const formDataPolicy_js_1 = __nccwpck_require__(37997);
-const core_util_1 = __nccwpck_require__(30991);
-const proxyPolicy_js_1 = __nccwpck_require__(73723);
-const setClientRequestIdPolicy_js_1 = __nccwpck_require__(63866);
-const tlsPolicy_js_1 = __nccwpck_require__(39370);
-const tracingPolicy_js_1 = __nccwpck_require__(14113);
-/**
- * Create a new pipeline with a default set of customizable policies.
- * @param options - Options to configure a custom pipeline.
- */
-function createPipelineFromOptions(options) {
- var _a;
- const pipeline = (0, pipeline_js_1.createEmptyPipeline)();
- if (core_util_1.isNodeLike) {
- if (options.tlsOptions) {
- pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions));
+ nics.forEach(nic => {
+
+ if ({}.hasOwnProperty.call(ifaces, nic.iface)) {
+ ifaces[nic.iface].forEach(function (details) {
+ if (details.family === 'IPv4' || details.family === 4) {
+ nic.ip4subnet = details.netmask;
+ }
+ if (details.family === 'IPv6' || details.family === 6) {
+ nic.ip6subnet = details.netmask;
+ }
+ });
+ }
+
+ let ifaceSanitized = '';
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(nic.iface);
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ ifaceSanitized = ifaceSanitized + s[i];
+ }
+ }
+
+ result.push({
+ iface: nic.iface,
+ ifaceName: nic.iface,
+ default: nic.iface === defaultInterface,
+ ip4: nic.ip4,
+ ip4subnet: nic.ip4subnet || '',
+ ip6: nic.ip6,
+ ip6subnet: nic.ip6subnet || '',
+ mac: nic.mac,
+ internal: nic.internal,
+ virtual: nic.internal ? false : testVirtualNic(nic.iface, nic.iface, nic.mac),
+ operstate: nic.operstate,
+ type: nic.type,
+ duplex: nic.duplex,
+ mtu: nic.mtu,
+ speed: nic.speed,
+ dhcp: getDarwinIfaceDHCPstatus(ifaceSanitized),
+ dnsSuffix: '',
+ ieee8021xAuth: '',
+ ieee8021xState: '',
+ carrierChanges: 0
+ });
+ });
+ _networkInterfaces = result;
+ if (defaultString.toLowerCase().indexOf('default') >= 0) {
+ result = result.filter(item => item.default);
+ if (result.length > 0) {
+ result = result[0];
+ } else {
+ result = [];
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
}
- pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions));
- pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)());
- }
- pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] });
- pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions));
- pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName));
- // The multipart policy is added after policies with no phase, so that
- // policies can be added between it and formDataPolicy to modify
- // properties (e.g., making the boundary constant in recorded tests).
- pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" });
- pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" });
- pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), {
- afterPhase: "Retry",
- });
- if (core_util_1.isNodeLike) {
- // Both XHR and Fetch expect to handle redirects automatically,
- // so only include this policy when we're in Node.
- pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" });
- }
- pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" });
- return pipeline;
-}
-//# sourceMappingURL=createPipelineFromOptions.js.map
+ }
+ if (_linux) {
+ if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
+ // no changes - just return object
+ result = _networkInterfaces;
+
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ _ifaces = JSON.parse(JSON.stringify(ifaces));
+ _dhcpNics = getLinuxDHCPNics();
+ const defaultInterface = getDefaultNetworkInterface();
+ for (let dev in ifaces) {
+ let ip4 = '';
+ let ip4subnet = '';
+ let ip6 = '';
+ let ip6subnet = '';
+ let mac = '';
+ let duplex = '';
+ let mtu = '';
+ let speed = null;
+ let carrierChanges = 0;
+ let dhcp = false;
+ let dnsSuffix = '';
+ let ieee8021xAuth = '';
+ let ieee8021xState = '';
+ let type = '';
+
+ if ({}.hasOwnProperty.call(ifaces, dev)) {
+ let ifaceName = dev;
+ ifaces[dev].forEach(function (details) {
+ if (details.family === 'IPv4' || details.family === 4) {
+ ip4 = details.address;
+ ip4subnet = details.netmask;
+ }
+ if (details.family === 'IPv6' || details.family === 6) {
+ if (!ip6 || ip6.match(/^fe80::/i)) {
+ ip6 = details.address;
+ ip6subnet = details.netmask;
+ }
+ }
+ mac = details.mac;
+ // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2)
+ const nodeMainVersion = parseInt(process.versions.node.split('.'), 10);
+ if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) {
+ if (Object.keys(_mac).length === 0) {
+ _mac = getMacAddresses();
+ }
+ mac = _mac[dev] || '';
+ }
+ });
+ let iface = dev.split(':')[0].trim().toLowerCase();
+ let ifaceSanitized = '';
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface);
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ ifaceSanitized = ifaceSanitized + s[i];
+ }
+ }
+ const cmd = `echo -n "addr_assign_type: "; cat /sys/class/net/${ifaceSanitized}/addr_assign_type 2>/dev/null; echo;
+ echo -n "address: "; cat /sys/class/net/${ifaceSanitized}/address 2>/dev/null; echo;
+ echo -n "addr_len: "; cat /sys/class/net/${ifaceSanitized}/addr_len 2>/dev/null; echo;
+ echo -n "broadcast: "; cat /sys/class/net/${ifaceSanitized}/broadcast 2>/dev/null; echo;
+ echo -n "carrier: "; cat /sys/class/net/${ifaceSanitized}/carrier 2>/dev/null; echo;
+ echo -n "carrier_changes: "; cat /sys/class/net/${ifaceSanitized}/carrier_changes 2>/dev/null; echo;
+ echo -n "dev_id: "; cat /sys/class/net/${ifaceSanitized}/dev_id 2>/dev/null; echo;
+ echo -n "dev_port: "; cat /sys/class/net/${ifaceSanitized}/dev_port 2>/dev/null; echo;
+ echo -n "dormant: "; cat /sys/class/net/${ifaceSanitized}/dormant 2>/dev/null; echo;
+ echo -n "duplex: "; cat /sys/class/net/${ifaceSanitized}/duplex 2>/dev/null; echo;
+ echo -n "flags: "; cat /sys/class/net/${ifaceSanitized}/flags 2>/dev/null; echo;
+ echo -n "gro_flush_timeout: "; cat /sys/class/net/${ifaceSanitized}/gro_flush_timeout 2>/dev/null; echo;
+ echo -n "ifalias: "; cat /sys/class/net/${ifaceSanitized}/ifalias 2>/dev/null; echo;
+ echo -n "ifindex: "; cat /sys/class/net/${ifaceSanitized}/ifindex 2>/dev/null; echo;
+ echo -n "iflink: "; cat /sys/class/net/${ifaceSanitized}/iflink 2>/dev/null; echo;
+ echo -n "link_mode: "; cat /sys/class/net/${ifaceSanitized}/link_mode 2>/dev/null; echo;
+ echo -n "mtu: "; cat /sys/class/net/${ifaceSanitized}/mtu 2>/dev/null; echo;
+ echo -n "netdev_group: "; cat /sys/class/net/${ifaceSanitized}/netdev_group 2>/dev/null; echo;
+ echo -n "operstate: "; cat /sys/class/net/${ifaceSanitized}/operstate 2>/dev/null; echo;
+ echo -n "proto_down: "; cat /sys/class/net/${ifaceSanitized}/proto_down 2>/dev/null; echo;
+ echo -n "speed: "; cat /sys/class/net/${ifaceSanitized}/speed 2>/dev/null; echo;
+ echo -n "tx_queue_len: "; cat /sys/class/net/${ifaceSanitized}/tx_queue_len 2>/dev/null; echo;
+ echo -n "type: "; cat /sys/class/net/${ifaceSanitized}/type 2>/dev/null; echo;
+ echo -n "wireless: "; cat /proc/net/wireless 2>/dev/null | grep ${ifaceSanitized}; echo;
+ echo -n "wirelessspeed: "; iw dev ${ifaceSanitized} link 2>&1 | grep bitrate; echo;`;
+
+ let lines = [];
+ try {
+ lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
+ const connectionName = getLinuxIfaceConnectionName(ifaceSanitized);
+ dhcp = getLinuxIfaceDHCPstatus(ifaceSanitized, connectionName, _dhcpNics);
+ dnsSuffix = getLinuxIfaceDNSsuffix(connectionName);
+ ieee8021xAuth = getLinuxIfaceIEEE8021xAuth(connectionName);
+ ieee8021xState = getLinuxIfaceIEEE8021xState(ieee8021xAuth);
+ } catch (e) {
+ util.noop();
+ }
+ duplex = util.getValue(lines, 'duplex');
+ duplex = duplex.startsWith('cat') ? '' : duplex;
+ mtu = parseInt(util.getValue(lines, 'mtu'), 10);
+ let myspeed = parseInt(util.getValue(lines, 'speed'), 10);
+ speed = isNaN(myspeed) ? null : myspeed;
+ let wirelessspeed = util.getValue(lines, 'wirelessspeed').split('tx bitrate: ');
+ if (speed === null && wirelessspeed.length === 2) {
+ myspeed = parseFloat(wirelessspeed[1]);
+ speed = isNaN(myspeed) ? null : myspeed;
+ }
+ carrierChanges = parseInt(util.getValue(lines, 'carrier_changes'), 10);
+ const operstate = util.getValue(lines, 'operstate');
+ type = operstate === 'up' ? (util.getValue(lines, 'wireless').trim() ? 'wireless' : 'wired') : 'unknown';
+ if (ifaceSanitized === 'lo' || ifaceSanitized.startsWith('bond')) { type = 'virtual'; }
+
+ let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false;
+ if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) {
+ internal = true;
+ }
+ const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac);
+ result.push({
+ iface: ifaceSanitized,
+ ifaceName,
+ default: iface === defaultInterface,
+ ip4,
+ ip4subnet,
+ ip6,
+ ip6subnet,
+ mac,
+ internal,
+ virtual,
+ operstate,
+ type,
+ duplex,
+ mtu,
+ speed,
+ dhcp,
+ dnsSuffix,
+ ieee8021xAuth,
+ ieee8021xState,
+ carrierChanges,
+ });
+ }
+ }
+ _networkInterfaces = result;
+ if (defaultString.toLowerCase().indexOf('default') >= 0) {
+ result = result.filter(item => item.default);
+ if (result.length > 0) {
+ result = result[0];
+ } else {
+ result = [];
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_windows) {
+ if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
+ // no changes - just return object
+ result = _networkInterfaces;
-/***/ }),
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ _ifaces = JSON.parse(JSON.stringify(ifaces));
+ const defaultInterface = getDefaultNetworkInterface();
-/***/ 55316:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ getWindowsNics().then(function (nics) {
+ nics.forEach(nic => {
+ let found = false;
+ Object.keys(ifaces).forEach(key => {
+ if (!found) {
+ ifaces[key].forEach(value => {
+ if (Object.keys(value).indexOf('mac') >= 0) {
+ found = value['mac'] === nic.mac;
+ }
+ });
+ }
+ });
+ if (!found) {
+ ifaces[nic.name] = [{ mac: nic.mac }];
+ }
+ });
+ nics8021xInfo = getWindowsWiredProfilesInformation();
+ dnsSuffixes = getWindowsDNSsuffixes();
+ for (let dev in ifaces) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createDefaultHttpClient = createDefaultHttpClient;
-const nodeHttpClient_js_1 = __nccwpck_require__(56583);
-/**
- * Create the correct HttpClient for the current environment.
- */
-function createDefaultHttpClient() {
- return (0, nodeHttpClient_js_1.createNodeHttpClient)();
-}
-//# sourceMappingURL=defaultHttpClient.js.map
+ let ifaceSanitized = '';
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(dev);
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ ifaceSanitized = ifaceSanitized + s[i];
+ }
+ }
-/***/ }),
+ let iface = dev;
+ let ip4 = '';
+ let ip4subnet = '';
+ let ip6 = '';
+ let ip6subnet = '';
+ let mac = '';
+ let duplex = '';
+ let mtu = '';
+ let speed = null;
+ let carrierChanges = 0;
+ let operstate = 'down';
+ let dhcp = false;
+ let dnsSuffix = '';
+ let ieee8021xAuth = '';
+ let ieee8021xState = '';
+ let type = '';
-/***/ 30596:
-/***/ ((__unused_webpack_module, exports) => {
+ if ({}.hasOwnProperty.call(ifaces, dev)) {
+ let ifaceName = dev;
+ ifaces[dev].forEach(function (details) {
+ if (details.family === 'IPv4' || details.family === 4) {
+ ip4 = details.address;
+ ip4subnet = details.netmask;
+ }
+ if (details.family === 'IPv6' || details.family === 6) {
+ if (!ip6 || ip6.match(/^fe80::/i)) {
+ ip6 = details.address;
+ ip6subnet = details.netmask;
+ }
+ }
+ mac = details.mac;
+ // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2)
+ const nodeMainVersion = parseInt(process.versions.node.split('.'), 10);
+ if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) {
+ if (Object.keys(_mac).length === 0) {
+ _mac = getMacAddresses();
+ }
+ mac = _mac[dev] || '';
+ }
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createHttpHeaders = createHttpHeaders;
-function normalizeName(name) {
- return name.toLowerCase();
-}
-function* headerIterator(map) {
- for (const entry of map.values()) {
- yield [entry.name, entry.value];
- }
-}
-class HttpHeadersImpl {
- constructor(rawHeaders) {
- this._headersMap = new Map();
- if (rawHeaders) {
- for (const headerName of Object.keys(rawHeaders)) {
- this.set(headerName, rawHeaders[headerName]);
- }
- }
- }
- /**
- * Set a header in this collection with the provided name and value. The name is
- * case-insensitive.
- * @param name - The name of the header to set. This value is case-insensitive.
- * @param value - The value of the header to set.
- */
- set(name, value) {
- this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
- }
- /**
- * Get the header value for the provided header name, or undefined if no header exists in this
- * collection with the provided name.
- * @param name - The name of the header. This value is case-insensitive.
- */
- get(name) {
- var _a;
- return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value;
- }
- /**
- * Get whether or not this header collection contains a header entry for the provided header name.
- * @param name - The name of the header to set. This value is case-insensitive.
- */
- has(name) {
- return this._headersMap.has(normalizeName(name));
- }
- /**
- * Remove the header with the provided headerName.
- * @param name - The name of the header to remove.
- */
- delete(name) {
- this._headersMap.delete(normalizeName(name));
- }
- /**
- * Get the JSON object representation of this HTTP header collection.
- */
- toJSON(options = {}) {
- const result = {};
- if (options.preserveCase) {
- for (const entry of this._headersMap.values()) {
- result[entry.name] = entry.value;
+
+ dnsSuffix = getWindowsIfaceDNSsuffix(dnsSuffixes.ifaces, ifaceSanitized);
+ let foundFirst = false;
+ nics.forEach(detail => {
+ if (detail.mac === mac && !foundFirst) {
+ iface = detail.iface || iface;
+ ifaceName = detail.name;
+ dhcp = detail.dhcp;
+ operstate = detail.operstate;
+ speed = operstate === 'up' ? detail.speed : 0;
+ type = detail.type;
+ foundFirst = true;
+ }
+ });
+
+ if (dev.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('802.11n') >= 0 || ifaceName.toLowerCase().indexOf('wireless') >= 0 || ifaceName.toLowerCase().indexOf('wi-fi') >= 0 || ifaceName.toLowerCase().indexOf('wifi') >= 0) {
+ type = 'wireless';
+ }
+
+ const IEEE8021x = getWindowsIEEE8021x(type, ifaceSanitized, nics8021xInfo);
+ ieee8021xAuth = IEEE8021x.protocol;
+ ieee8021xState = IEEE8021x.state;
+ let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false;
+ if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) {
+ internal = true;
+ }
+ const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac);
+ result.push({
+ iface,
+ ifaceName,
+ default: iface === defaultInterface,
+ ip4,
+ ip4subnet,
+ ip6,
+ ip6subnet,
+ mac,
+ internal,
+ virtual,
+ operstate,
+ type,
+ duplex,
+ mtu,
+ speed,
+ dhcp,
+ dnsSuffix,
+ ieee8021xAuth,
+ ieee8021xState,
+ carrierChanges,
+ });
+ }
}
- }
- else {
- for (const [normalizedName, entry] of this._headersMap) {
- result[normalizedName] = entry.value;
+ _networkInterfaces = result;
+ if (defaultString.toLowerCase().indexOf('default') >= 0) {
+ result = result.filter(item => item.default);
+ if (result.length > 0) {
+ result = result[0];
+ } else {
+ result = [];
+ }
}
+ if (callback) { callback(result); }
+ resolve(result);
+ });
}
- return result;
- }
- /**
- * Get the string representation of this HTTP header collection.
- */
- toString() {
- return JSON.stringify(this.toJSON({ preserveCase: true }));
- }
- /**
- * Iterate over tuples of header [name, value] pairs.
- */
- [Symbol.iterator]() {
- return headerIterator(this._headersMap);
- }
-}
-/**
- * Creates an object that satisfies the `HttpHeaders` interface.
- * @param rawHeaders - A simple object representing initial headers
- */
-function createHttpHeaders(rawHeaders) {
- return new HttpHeadersImpl(rawHeaders);
+ }
+ });
+ });
}
-//# sourceMappingURL=httpHeaders.js.map
-/***/ }),
+exports.networkInterfaces = networkInterfaces;
-/***/ 95582:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// NET - Speed
+function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors) {
+ let result = {
+ iface,
+ operstate,
+ rx_bytes,
+ rx_dropped,
+ rx_errors,
+ tx_bytes,
+ tx_dropped,
+ tx_errors,
+ rx_sec: null,
+ tx_sec: null,
+ ms: 0
+ };
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createFileFromStream = exports.createFile = exports.auxiliaryAuthenticationHeaderPolicyName = exports.auxiliaryAuthenticationHeaderPolicy = exports.ndJsonPolicyName = exports.ndJsonPolicy = exports.bearerTokenAuthenticationPolicyName = exports.bearerTokenAuthenticationPolicy = exports.formDataPolicyName = exports.formDataPolicy = exports.tlsPolicyName = exports.tlsPolicy = exports.userAgentPolicyName = exports.userAgentPolicy = exports.defaultRetryPolicy = exports.tracingPolicyName = exports.tracingPolicy = exports.retryPolicy = exports.throttlingRetryPolicyName = exports.throttlingRetryPolicy = exports.systemErrorRetryPolicyName = exports.systemErrorRetryPolicy = exports.redirectPolicyName = exports.redirectPolicy = exports.getDefaultProxySettings = exports.proxyPolicyName = exports.proxyPolicy = exports.multipartPolicyName = exports.multipartPolicy = exports.logPolicyName = exports.logPolicy = exports.setClientRequestIdPolicyName = exports.setClientRequestIdPolicy = exports.exponentialRetryPolicyName = exports.exponentialRetryPolicy = exports.decompressResponsePolicyName = exports.decompressResponsePolicy = exports.isRestError = exports.RestError = exports.createPipelineRequest = exports.createHttpHeaders = exports.createDefaultHttpClient = exports.createPipelineFromOptions = exports.createEmptyPipeline = void 0;
-var pipeline_js_1 = __nccwpck_require__(37050);
-Object.defineProperty(exports, "createEmptyPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createEmptyPipeline; } }));
-var createPipelineFromOptions_js_1 = __nccwpck_require__(1130);
-Object.defineProperty(exports, "createPipelineFromOptions", ({ enumerable: true, get: function () { return createPipelineFromOptions_js_1.createPipelineFromOptions; } }));
-var defaultHttpClient_js_1 = __nccwpck_require__(55316);
-Object.defineProperty(exports, "createDefaultHttpClient", ({ enumerable: true, get: function () { return defaultHttpClient_js_1.createDefaultHttpClient; } }));
-var httpHeaders_js_1 = __nccwpck_require__(30596);
-Object.defineProperty(exports, "createHttpHeaders", ({ enumerable: true, get: function () { return httpHeaders_js_1.createHttpHeaders; } }));
-var pipelineRequest_js_1 = __nccwpck_require__(82425);
-Object.defineProperty(exports, "createPipelineRequest", ({ enumerable: true, get: function () { return pipelineRequest_js_1.createPipelineRequest; } }));
-var restError_js_1 = __nccwpck_require__(97558);
-Object.defineProperty(exports, "RestError", ({ enumerable: true, get: function () { return restError_js_1.RestError; } }));
-Object.defineProperty(exports, "isRestError", ({ enumerable: true, get: function () { return restError_js_1.isRestError; } }));
-var decompressResponsePolicy_js_1 = __nccwpck_require__(13299);
-Object.defineProperty(exports, "decompressResponsePolicy", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicy; } }));
-Object.defineProperty(exports, "decompressResponsePolicyName", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicyName; } }));
-var exponentialRetryPolicy_js_1 = __nccwpck_require__(43048);
-Object.defineProperty(exports, "exponentialRetryPolicy", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicy; } }));
-Object.defineProperty(exports, "exponentialRetryPolicyName", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; } }));
-var setClientRequestIdPolicy_js_1 = __nccwpck_require__(63866);
-Object.defineProperty(exports, "setClientRequestIdPolicy", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicy; } }));
-Object.defineProperty(exports, "setClientRequestIdPolicyName", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicyName; } }));
-var logPolicy_js_1 = __nccwpck_require__(19937);
-Object.defineProperty(exports, "logPolicy", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicy; } }));
-Object.defineProperty(exports, "logPolicyName", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicyName; } }));
-var multipartPolicy_js_1 = __nccwpck_require__(77915);
-Object.defineProperty(exports, "multipartPolicy", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicy; } }));
-Object.defineProperty(exports, "multipartPolicyName", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicyName; } }));
-var proxyPolicy_js_1 = __nccwpck_require__(73723);
-Object.defineProperty(exports, "proxyPolicy", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicy; } }));
-Object.defineProperty(exports, "proxyPolicyName", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicyName; } }));
-Object.defineProperty(exports, "getDefaultProxySettings", ({ enumerable: true, get: function () { return proxyPolicy_js_1.getDefaultProxySettings; } }));
-var redirectPolicy_js_1 = __nccwpck_require__(86947);
-Object.defineProperty(exports, "redirectPolicy", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicy; } }));
-Object.defineProperty(exports, "redirectPolicyName", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicyName; } }));
-var systemErrorRetryPolicy_js_1 = __nccwpck_require__(14298);
-Object.defineProperty(exports, "systemErrorRetryPolicy", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; } }));
-Object.defineProperty(exports, "systemErrorRetryPolicyName", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; } }));
-var throttlingRetryPolicy_js_1 = __nccwpck_require__(96352);
-Object.defineProperty(exports, "throttlingRetryPolicy", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicy; } }));
-Object.defineProperty(exports, "throttlingRetryPolicyName", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; } }));
-var retryPolicy_js_1 = __nccwpck_require__(85001);
-Object.defineProperty(exports, "retryPolicy", ({ enumerable: true, get: function () { return retryPolicy_js_1.retryPolicy; } }));
-var tracingPolicy_js_1 = __nccwpck_require__(14113);
-Object.defineProperty(exports, "tracingPolicy", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicy; } }));
-Object.defineProperty(exports, "tracingPolicyName", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicyName; } }));
-var defaultRetryPolicy_js_1 = __nccwpck_require__(47494);
-Object.defineProperty(exports, "defaultRetryPolicy", ({ enumerable: true, get: function () { return defaultRetryPolicy_js_1.defaultRetryPolicy; } }));
-var userAgentPolicy_js_1 = __nccwpck_require__(69795);
-Object.defineProperty(exports, "userAgentPolicy", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicy; } }));
-Object.defineProperty(exports, "userAgentPolicyName", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicyName; } }));
-var tlsPolicy_js_1 = __nccwpck_require__(39370);
-Object.defineProperty(exports, "tlsPolicy", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicy; } }));
-Object.defineProperty(exports, "tlsPolicyName", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicyName; } }));
-var formDataPolicy_js_1 = __nccwpck_require__(37997);
-Object.defineProperty(exports, "formDataPolicy", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicy; } }));
-Object.defineProperty(exports, "formDataPolicyName", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicyName; } }));
-var bearerTokenAuthenticationPolicy_js_1 = __nccwpck_require__(42081);
-Object.defineProperty(exports, "bearerTokenAuthenticationPolicy", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicy; } }));
-Object.defineProperty(exports, "bearerTokenAuthenticationPolicyName", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicyName; } }));
-var ndJsonPolicy_js_1 = __nccwpck_require__(7303);
-Object.defineProperty(exports, "ndJsonPolicy", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicy; } }));
-Object.defineProperty(exports, "ndJsonPolicyName", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicyName; } }));
-var auxiliaryAuthenticationHeaderPolicy_js_1 = __nccwpck_require__(7250);
-Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicy", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicy; } }));
-Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicyName", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicyName; } }));
-var file_js_1 = __nccwpck_require__(8581);
-Object.defineProperty(exports, "createFile", ({ enumerable: true, get: function () { return file_js_1.createFile; } }));
-Object.defineProperty(exports, "createFileFromStream", ({ enumerable: true, get: function () { return file_js_1.createFileFromStream; } }));
-//# sourceMappingURL=index.js.map
+ if (_network[iface] && _network[iface].ms) {
+ result.ms = Date.now() - _network[iface].ms;
+ result.rx_sec = (rx_bytes - _network[iface].rx_bytes) >= 0 ? (rx_bytes - _network[iface].rx_bytes) / (result.ms / 1000) : 0;
+ result.tx_sec = (tx_bytes - _network[iface].tx_bytes) >= 0 ? (tx_bytes - _network[iface].tx_bytes) / (result.ms / 1000) : 0;
+ _network[iface].rx_bytes = rx_bytes;
+ _network[iface].tx_bytes = tx_bytes;
+ _network[iface].rx_sec = result.rx_sec;
+ _network[iface].tx_sec = result.tx_sec;
+ _network[iface].ms = Date.now();
+ _network[iface].last_ms = result.ms;
+ _network[iface].operstate = operstate;
+ } else {
+ if (!_network[iface]) { _network[iface] = {}; }
+ _network[iface].rx_bytes = rx_bytes;
+ _network[iface].tx_bytes = tx_bytes;
+ _network[iface].rx_sec = null;
+ _network[iface].tx_sec = null;
+ _network[iface].ms = Date.now();
+ _network[iface].last_ms = 0;
+ _network[iface].operstate = operstate;
+ }
+ return result;
+}
-/***/ }),
+function networkStats(ifaces, callback) {
-/***/ 58564:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ let ifacesArray = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.logger = void 0;
-const logger_1 = __nccwpck_require__(50143);
-exports.logger = (0, logger_1.createClientLogger)("core-rest-pipeline");
-//# sourceMappingURL=log.js.map
+ // fallback - if only callback is given
+ if (util.isFunction(ifaces) && !callback) {
+ callback = ifaces;
+ ifacesArray = [getDefaultNetworkInterface()];
+ } else {
+ if (typeof ifaces !== 'string' && ifaces !== undefined) {
+ if (callback) { callback([]); }
+ return resolve([]);
+ }
+ ifaces = ifaces || getDefaultNetworkInterface();
-/***/ }),
+ try {
+ ifaces.__proto__.toLowerCase = util.stringToLower;
+ ifaces.__proto__.replace = util.stringReplace;
+ ifaces.__proto__.toString = util.stringToString;
+ ifaces.__proto__.substr = util.stringSubstr;
+ ifaces.__proto__.substring = util.stringSubstring;
+ ifaces.__proto__.trim = util.stringTrim;
+ ifaces.__proto__.startsWith = util.stringStartWith;
+ } catch (e) {
+ Object.setPrototypeOf(ifaces, util.stringObj);
+ }
-/***/ 56583:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|');
+ ifacesArray = ifaces.split('|');
+ }
+ const result = [];
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getBodyLength = getBodyLength;
-exports.createNodeHttpClient = createNodeHttpClient;
-const tslib_1 = __nccwpck_require__(94176);
-const http = tslib_1.__importStar(__nccwpck_require__(37067));
-const https = tslib_1.__importStar(__nccwpck_require__(44708));
-const zlib = tslib_1.__importStar(__nccwpck_require__(38522));
-const node_stream_1 = __nccwpck_require__(57075);
-const abort_controller_1 = __nccwpck_require__(92242);
-const httpHeaders_js_1 = __nccwpck_require__(30596);
-const restError_js_1 = __nccwpck_require__(97558);
-const log_js_1 = __nccwpck_require__(58564);
-const DEFAULT_TLS_SETTINGS = {};
-function isReadableStream(body) {
- return body && typeof body.pipe === "function";
-}
-function isStreamComplete(stream) {
- if (stream.readable === false) {
- return Promise.resolve();
- }
- return new Promise((resolve) => {
- const handler = () => {
- resolve();
- stream.removeListener("close", handler);
- stream.removeListener("end", handler);
- stream.removeListener("error", handler);
- };
- stream.on("close", handler);
- stream.on("end", handler);
- stream.on("error", handler);
- });
-}
-function isArrayBuffer(body) {
- return body && typeof body.byteLength === "number";
-}
-class ReportTransform extends node_stream_1.Transform {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
- _transform(chunk, _encoding, callback) {
- this.push(chunk);
- this.loadedBytes += chunk.length;
- try {
- this.progressCallback({ loadedBytes: this.loadedBytes });
- callback();
- }
- catch (e) {
- callback(e);
- }
- }
- constructor(progressCallback) {
- super();
- this.loadedBytes = 0;
- this.progressCallback = progressCallback;
- }
-}
-/**
- * A HttpClient implementation that uses Node's "https" module to send HTTPS requests.
- * @internal
- */
-class NodeHttpClient {
- constructor() {
- this.cachedHttpsAgents = new WeakMap();
- }
- /**
- * Makes a request over an underlying transport layer and returns the response.
- * @param request - The request to be made.
- */
- async sendRequest(request) {
- var _a, _b, _c;
- const abortController = new AbortController();
- let abortListener;
- if (request.abortSignal) {
- if (request.abortSignal.aborted) {
- throw new abort_controller_1.AbortError("The operation was aborted.");
- }
- abortListener = (event) => {
- if (event.type === "abort") {
- abortController.abort();
- }
- };
- request.abortSignal.addEventListener("abort", abortListener);
- }
- if (request.timeout > 0) {
- setTimeout(() => {
- abortController.abort();
- }, request.timeout);
- }
- const acceptEncoding = request.headers.get("Accept-Encoding");
- const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate"));
- let body = typeof request.body === "function" ? request.body() : request.body;
- if (body && !request.headers.has("Content-Length")) {
- const bodyLength = getBodyLength(body);
- if (bodyLength !== null) {
- request.headers.set("Content-Length", bodyLength);
- }
+ const workload = [];
+ if (ifacesArray.length && ifacesArray[0].trim() === '*') {
+ ifacesArray = [];
+ networkInterfaces(false).then(allIFaces => {
+ for (let iface of allIFaces) {
+ ifacesArray.push(iface.iface);
+ }
+ networkStats(ifacesArray.join(',')).then(result => {
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ } else {
+ for (let iface of ifacesArray) {
+ workload.push(networkStatsSingle(iface.trim()));
}
- let responseStream;
- try {
- if (body && request.onUploadProgress) {
- const onUploadProgress = request.onUploadProgress;
- const uploadReportStream = new ReportTransform(onUploadProgress);
- uploadReportStream.on("error", (e) => {
- log_js_1.logger.error("Error in upload progress", e);
- });
- if (isReadableStream(body)) {
- body.pipe(uploadReportStream);
- }
- else {
- uploadReportStream.end(body);
- }
- body = uploadReportStream;
- }
- const res = await this.makeRequest(request, abortController, body);
- const headers = getResponseHeaders(res);
- const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
- const response = {
- status,
- headers,
- request,
- };
- // Responses to HEAD must not have a body.
- // If they do return a body, that body must be ignored.
- if (request.method === "HEAD") {
- // call resume() and not destroy() to avoid closing the socket
- // and losing keep alive
- res.resume();
- return response;
- }
- responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
- const onDownloadProgress = request.onDownloadProgress;
- if (onDownloadProgress) {
- const downloadReportStream = new ReportTransform(onDownloadProgress);
- downloadReportStream.on("error", (e) => {
- log_js_1.logger.error("Error in download progress", e);
- });
- responseStream.pipe(downloadReportStream);
- responseStream = downloadReportStream;
- }
- if (
- // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
- ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) ||
- ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))) {
- response.readableStreamBody = responseStream;
- }
- else {
- response.bodyAsText = await streamToText(responseStream);
- }
- return response;
+ if (workload.length) {
+ Promise.all(
+ workload
+ ).then((data) => {
+ if (callback) { callback(data); }
+ resolve(data);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
}
- finally {
- // clean up event listener
- if (request.abortSignal && abortListener) {
- let uploadStreamDone = Promise.resolve();
- if (isReadableStream(body)) {
- uploadStreamDone = isStreamComplete(body);
- }
- let downloadStreamDone = Promise.resolve();
- if (isReadableStream(responseStream)) {
- downloadStreamDone = isStreamComplete(responseStream);
- }
- Promise.all([uploadStreamDone, downloadStreamDone])
- .then(() => {
- var _a;
- // eslint-disable-next-line promise/always-return
- if (abortListener) {
- (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
- }
- })
- .catch((e) => {
- log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e);
- });
- }
+ }
+ });
+ });
+}
+
+function networkStatsSingle(iface) {
+
+ function parseLinesWindowsPerfData(sections) {
+ let perfData = [];
+ for (let i in sections) {
+ if ({}.hasOwnProperty.call(sections, i)) {
+ if (sections[i].trim() !== '') {
+ let lines = sections[i].trim().split('\r\n');
+ perfData.push({
+ name: util.getValue(lines, 'Name', ':').replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase(),
+ rx_bytes: parseInt(util.getValue(lines, 'BytesReceivedPersec', ':'), 10),
+ rx_errors: parseInt(util.getValue(lines, 'PacketsReceivedErrors', ':'), 10),
+ rx_dropped: parseInt(util.getValue(lines, 'PacketsReceivedDiscarded', ':'), 10),
+ tx_bytes: parseInt(util.getValue(lines, 'BytesSentPersec', ':'), 10),
+ tx_errors: parseInt(util.getValue(lines, 'PacketsOutboundErrors', ':'), 10),
+ tx_dropped: parseInt(util.getValue(lines, 'PacketsOutboundDiscarded', ':'), 10)
+ });
}
+ }
}
- makeRequest(request, abortController, body) {
- var _a;
- const url = new URL(request.url);
- const isInsecure = url.protocol !== "https:";
- if (isInsecure && !request.allowInsecureConnection) {
- throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
+ return perfData;
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let ifaceSanitized = '';
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface);
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ ifaceSanitized = ifaceSanitized + s[i];
}
- const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure);
- const options = {
- agent,
- hostname: url.hostname,
- path: `${url.pathname}${url.search}`,
- port: url.port,
- method: request.method,
- headers: request.headers.toJSON({ preserveCase: true }),
- };
- return new Promise((resolve, reject) => {
- const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve);
- req.once("error", (err) => {
- var _a;
- reject(new restError_js_1.RestError(err.message, { code: (_a = err.code) !== null && _a !== void 0 ? _a : restError_js_1.RestError.REQUEST_SEND_ERROR, request }));
- });
- abortController.signal.addEventListener("abort", () => {
- const abortError = new abort_controller_1.AbortError("The operation was aborted.");
- req.destroy(abortError);
- reject(abortError);
+ }
+
+ let result = {
+ iface: ifaceSanitized,
+ operstate: 'unknown',
+ rx_bytes: 0,
+ rx_dropped: 0,
+ rx_errors: 0,
+ tx_bytes: 0,
+ tx_dropped: 0,
+ tx_errors: 0,
+ rx_sec: null,
+ tx_sec: null,
+ ms: 0
+ };
+
+ let operstate = 'unknown';
+ let rx_bytes = 0;
+ let tx_bytes = 0;
+ let rx_dropped = 0;
+ let rx_errors = 0;
+ let tx_dropped = 0;
+ let tx_errors = 0;
+
+ let cmd, lines, stats;
+ if (!_network[ifaceSanitized] || (_network[ifaceSanitized] && !_network[ifaceSanitized].ms) || (_network[ifaceSanitized] && _network[ifaceSanitized].ms && Date.now() - _network[ifaceSanitized].ms >= 500)) {
+ if (_linux) {
+ if (fs.existsSync('/sys/class/net/' + ifaceSanitized)) {
+ cmd =
+ 'cat /sys/class/net/' + ifaceSanitized + '/operstate; ' +
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_bytes; ' +
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_bytes; ' +
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_dropped; ' +
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_errors; ' +
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_dropped; ' +
+ 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_errors; ';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ lines = stdout.toString().split('\n');
+ operstate = lines[0].trim();
+ rx_bytes = parseInt(lines[1], 10);
+ tx_bytes = parseInt(lines[2], 10);
+ rx_dropped = parseInt(lines[3], 10);
+ rx_errors = parseInt(lines[4], 10);
+ tx_dropped = parseInt(lines[5], 10);
+ tx_errors = parseInt(lines[6], 10);
+
+ result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
+
+ }
+ resolve(result);
});
- if (body && isReadableStream(body)) {
- body.pipe(req);
- }
- else if (body) {
- if (typeof body === "string" || Buffer.isBuffer(body)) {
- req.end(body);
- }
- else if (isArrayBuffer(body)) {
- req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
- }
- else {
- log_js_1.logger.error("Unrecognized body type", body);
- reject(new restError_js_1.RestError("Unrecognized body type"));
+ } else {
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ cmd = 'netstat -ibndI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input]
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ lines = stdout.toString().split('\n');
+ for (let i = 1; i < lines.length; i++) {
+ const line = lines[i].replace(/ +/g, ' ').split(' ');
+ if (line && line[0] && line[7] && line[10]) {
+ rx_bytes = rx_bytes + parseInt(line[7]);
+ if (line[6].trim() !== '-') { rx_dropped = rx_dropped + parseInt(line[6]); }
+ if (line[5].trim() !== '-') { rx_errors = rx_errors + parseInt(line[5]); }
+ tx_bytes = tx_bytes + parseInt(line[10]);
+ if (line[12].trim() !== '-') { tx_dropped = tx_dropped + parseInt(line[12]); }
+ if (line[9].trim() !== '-') { tx_errors = tx_errors + parseInt(line[9]); }
+ operstate = 'up';
}
+ }
+ result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
}
- else {
- // streams don't like "undefined" being passed as data
- req.end();
- }
- });
- }
- getOrCreateAgent(request, isInsecure) {
- var _a;
- const disableKeepAlive = request.disableKeepAlive;
- // Handle Insecure requests first
- if (isInsecure) {
- if (disableKeepAlive) {
- // keepAlive:false is the default so we don't need a custom Agent
- return http.globalAgent;
- }
- if (!this.cachedHttpAgent) {
- // If there is no cached agent create a new one and cache it.
- this.cachedHttpAgent = new http.Agent({ keepAlive: true });
- }
- return this.cachedHttpAgent;
+ resolve(result);
+ });
}
- else {
- if (disableKeepAlive && !request.tlsSettings) {
- // When there are no tlsSettings and keepAlive is false
- // we don't need a custom agent
- return https.globalAgent;
- }
- // We use the tlsSettings to index cached clients
- const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS;
- // Get the cached agent or create a new one with the
- // provided values for keepAlive and tlsSettings
- let agent = this.cachedHttpsAgents.get(tlsSettings);
- if (agent && agent.options.keepAlive === !disableKeepAlive) {
- return agent;
- }
- log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent");
- agent = new https.Agent(Object.assign({
- // keepAlive is true if disableKeepAlive is false.
- keepAlive: !disableKeepAlive }, tlsSettings));
- this.cachedHttpsAgents.set(tlsSettings, agent);
- return agent;
+ if (_darwin) {
+ cmd = 'ifconfig ' + ifaceSanitized + ' | grep "status"'; // lgtm [js/shell-command-constructed-from-input]
+ exec(cmd, function (error, stdout) {
+ result.operstate = (stdout.toString().split(':')[1] || '').trim();
+ result.operstate = (result.operstate || '').toLowerCase();
+ result.operstate = (result.operstate === 'active' ? 'up' : (result.operstate === 'inactive' ? 'down' : 'unknown'));
+ cmd = 'netstat -bdI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input]
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ lines = stdout.toString().split('\n');
+ // if there is less than 2 lines, no information for this interface was found
+ if (lines.length > 1 && lines[1].trim() !== '') {
+ // skip header line
+ // use the second line because it is tied to the NIC instead of the ipv4 or ipv6 address
+ stats = lines[1].replace(/ +/g, ' ').split(' ');
+ const offset = stats.length > 11 ? 1 : 0;
+ rx_bytes = parseInt(stats[offset + 5]);
+ rx_dropped = parseInt(stats[offset + 10]);
+ rx_errors = parseInt(stats[offset + 4]);
+ tx_bytes = parseInt(stats[offset + 8]);
+ tx_dropped = parseInt(stats[offset + 10]);
+ tx_errors = parseInt(stats[offset + 7]);
+ result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, result.operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
+ }
+ }
+ resolve(result);
+ });
+ });
}
- }
-}
-function getResponseHeaders(res) {
- const headers = (0, httpHeaders_js_1.createHttpHeaders)();
- for (const header of Object.keys(res.headers)) {
- const value = res.headers[header];
- if (Array.isArray(value)) {
- if (value.length > 0) {
- headers.set(header, value[0]);
+ if (_windows) {
+ let perfData = [];
+ let ifaceName = ifaceSanitized;
+
+ // Performance Data
+ util.powerShell('Get-CimInstance Win32_PerfRawData_Tcpip_NetworkInterface | select Name,BytesReceivedPersec,PacketsReceivedErrors,PacketsReceivedDiscarded,BytesSentPersec,PacketsOutboundErrors,PacketsOutboundDiscarded | fl').then((stdout, error) => {
+ if (!error) {
+ const psections = stdout.toString().split(/\n\s*\n/);
+ perfData = parseLinesWindowsPerfData(psections);
}
+
+ // Network Interfaces
+ networkInterfaces(false).then(interfaces => {
+ // get bytes sent, received from perfData by name
+ rx_bytes = 0;
+ tx_bytes = 0;
+ perfData.forEach(detail => {
+ interfaces.forEach(det => {
+ if ((det.iface.toLowerCase() === ifaceSanitized.toLowerCase() ||
+ det.mac.toLowerCase() === ifaceSanitized.toLowerCase() ||
+ det.ip4.toLowerCase() === ifaceSanitized.toLowerCase() ||
+ det.ip6.toLowerCase() === ifaceSanitized.toLowerCase() ||
+ det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === ifaceSanitized.replace(/[()[\] ]+/g, '').replace('#', '_').toLowerCase()) &&
+ (det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === detail.name)) {
+ ifaceName = det.iface;
+ rx_bytes = detail.rx_bytes;
+ rx_dropped = detail.rx_dropped;
+ rx_errors = detail.rx_errors;
+ tx_bytes = detail.tx_bytes;
+ tx_dropped = detail.tx_dropped;
+ tx_errors = detail.tx_errors;
+ operstate = det.operstate;
+ }
+ });
+ });
+ if (rx_bytes && tx_bytes) {
+ result = calcNetworkSpeed(ifaceName, parseInt(rx_bytes), parseInt(tx_bytes), operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
+ }
+ resolve(result);
+ });
+ });
}
- else if (value) {
- headers.set(header, value);
- }
- }
- return headers;
+ } else {
+ result.rx_bytes = _network[ifaceSanitized].rx_bytes;
+ result.tx_bytes = _network[ifaceSanitized].tx_bytes;
+ result.rx_sec = _network[ifaceSanitized].rx_sec;
+ result.tx_sec = _network[ifaceSanitized].tx_sec;
+ result.ms = _network[ifaceSanitized].last_ms;
+ result.operstate = _network[ifaceSanitized].operstate;
+ resolve(result);
+ }
+ });
+ });
}
-function getDecodedResponseStream(stream, headers) {
- const contentEncoding = headers.get("Content-Encoding");
- if (contentEncoding === "gzip") {
- const unzip = zlib.createGunzip();
- stream.pipe(unzip);
- return unzip;
- }
- else if (contentEncoding === "deflate") {
- const inflate = zlib.createInflate();
- stream.pipe(inflate);
- return inflate;
+
+exports.networkStats = networkStats;
+
+// --------------------------
+// NET - connections (sockets)
+
+function getProcessName(processes, pid) {
+ let cmd = '';
+ processes.forEach(line => {
+ const parts = line.split(' ');
+ const id = parseInt(parts[0], 10) || -1;
+ if (id === pid) {
+ parts.shift();
+ cmd = parts.join(' ').split(':')[0];
}
- return stream;
+ });
+ cmd = cmd.split(' -')[0];
+ cmd = cmd.split(' /')[0];
+ return cmd;
+ // const cmdParts = cmd.split('/');
+ // return cmdParts[cmdParts.length - 1];
}
-function streamToText(stream) {
- return new Promise((resolve, reject) => {
- const buffer = [];
- stream.on("data", (chunk) => {
- if (Buffer.isBuffer(chunk)) {
- buffer.push(chunk);
- }
- else {
- buffer.push(Buffer.from(chunk));
+
+function networkConnections(callback) {
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = [];
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ let cmd = 'export LC_ALL=C; netstat -tunap | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL';
+ if (_freebsd || _openbsd || _netbsd) { cmd = 'export LC_ALL=C; netstat -na | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; }
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ if (!error && (lines.length > 1 || lines[0] != '')) {
+ lines.forEach(function (line) {
+ line = line.replace(/ +/g, ' ').split(' ');
+ if (line.length >= 7) {
+ let localip = line[3];
+ let localport = '';
+ let localaddress = line[3].split(':');
+ if (localaddress.length > 1) {
+ localport = localaddress[localaddress.length - 1];
+ localaddress.pop();
+ localip = localaddress.join(':');
+ }
+ let peerip = line[4];
+ let peerport = '';
+ let peeraddress = line[4].split(':');
+ if (peeraddress.length > 1) {
+ peerport = peeraddress[peeraddress.length - 1];
+ peeraddress.pop();
+ peerip = peeraddress.join(':');
+ }
+ let connstate = line[5];
+ let proc = line[6].split('/');
+
+ if (connstate) {
+ result.push({
+ protocol: line[0],
+ localAddress: localip,
+ localPort: localport,
+ peerAddress: peerip,
+ peerPort: peerport,
+ state: connstate,
+ pid: proc[0] && proc[0] !== '-' ? parseInt(proc[0], 10) : null,
+ process: proc[1] ? proc[1].split(' ')[0].split(':')[0] : ''
+ });
+ }
+ }
+ });
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ } else {
+ cmd = 'ss -tunap | grep "ESTAB\\|SYN-SENT\\|SYN-RECV\\|FIN-WAIT1\\|FIN-WAIT2\\|TIME-WAIT\\|CLOSE\\|CLOSE-WAIT\\|LAST-ACK\\|LISTEN\\|CLOSING"';
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ line = line.replace(/ +/g, ' ').split(' ');
+ if (line.length >= 6) {
+ let localip = line[4];
+ let localport = '';
+ let localaddress = line[4].split(':');
+ if (localaddress.length > 1) {
+ localport = localaddress[localaddress.length - 1];
+ localaddress.pop();
+ localip = localaddress.join(':');
+ }
+ let peerip = line[5];
+ let peerport = '';
+ let peeraddress = line[5].split(':');
+ if (peeraddress.length > 1) {
+ peerport = peeraddress[peeraddress.length - 1];
+ peeraddress.pop();
+ peerip = peeraddress.join(':');
+ }
+ let connstate = line[1];
+ if (connstate === 'ESTAB') { connstate = 'ESTABLISHED'; }
+ if (connstate === 'TIME-WAIT') { connstate = 'TIME_WAIT'; }
+ let pid = null;
+ let process = '';
+ if (line.length >= 7 && line[6].indexOf('users:') > -1) {
+ let proc = line[6].replace('users:(("', '').replace(/"/g, '').split(',');
+ if (proc.length > 2) {
+ process = proc[0].split(' ')[0].split(':')[0];
+ pid = parseInt(proc[1], 10);
+ }
+ }
+ if (connstate) {
+ result.push({
+ protocol: line[0],
+ localAddress: localip,
+ localPort: localport,
+ peerAddress: peerip,
+ peerPort: peerport,
+ state: connstate,
+ pid,
+ process
+ });
+ }
+ }
+ });
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
});
- stream.on("end", () => {
- resolve(Buffer.concat(buffer).toString("utf8"));
+ }
+ if (_darwin) {
+ let cmd = 'netstat -natvln | head -n2; netstat -natvln | grep "tcp4\\|tcp6\\|udp4\\|udp6"';
+ const states = 'ESTABLISHED|SYN_SENT|SYN_RECV|FIN_WAIT1|FIN_WAIT_1|FIN_WAIT2|FIN_WAIT_2|TIME_WAIT|CLOSE|CLOSE_WAIT|LAST_ACK|LISTEN|CLOSING|UNKNOWN'.split('|');
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+ if (!error) {
+ exec('ps -axo pid,command', { maxBuffer: 1024 * 20000 }, function (err2, stdout2) {
+ let processes = stdout2.toString().split('\n');
+ processes = processes.map((line => { return line.trim().replace(/ +/g, ' '); }));
+ let lines = stdout.toString().split('\n');
+ lines.shift();
+ let pidPos = 8;
+ if (lines.length > 1 && lines[0].indexOf('pid') > 0) {
+ const header = (lines.shift() || '').replace(/ Address/g, '_Address').replace(/ +/g, ' ').split(' ');
+ pidPos = header.indexOf('pid');
+ }
+ lines.forEach(function (line) {
+ line = line.replace(/ +/g, ' ').split(' ');
+ if (line.length >= 8) {
+ let localip = line[3];
+ let localport = '';
+ let localaddress = line[3].split('.');
+ if (localaddress.length > 1) {
+ localport = localaddress[localaddress.length - 1];
+ localaddress.pop();
+ localip = localaddress.join('.');
+ }
+ let peerip = line[4];
+ let peerport = '';
+ let peeraddress = line[4].split('.');
+ if (peeraddress.length > 1) {
+ peerport = peeraddress[peeraddress.length - 1];
+ peeraddress.pop();
+ peerip = peeraddress.join('.');
+ }
+ const hasState = states.indexOf(line[5]) >= 0;
+ let connstate = hasState ? line[5] : 'UNKNOWN';
+ let pid = parseInt(line[pidPos + (hasState ? 0 : -1)], 10);
+ if (connstate) {
+ result.push({
+ protocol: line[0],
+ localAddress: localip,
+ localPort: localport,
+ peerAddress: peerip,
+ peerPort: peerport,
+ state: connstate,
+ pid: pid,
+ process: getProcessName(processes, pid)
+ });
+ }
+ }
+ });
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+
+ }
});
- stream.on("error", (e) => {
- if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") {
- reject(e);
- }
- else {
- reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, {
- code: restError_js_1.RestError.PARSE_ERROR,
- }));
+ }
+ if (_windows) {
+ let cmd = 'netstat -nao';
+ try {
+ exec(cmd, util.execOptsWin, function (error, stdout) {
+ if (!error) {
+
+ let lines = stdout.toString().split('\r\n');
+
+ lines.forEach(function (line) {
+ line = line.trim().replace(/ +/g, ' ').split(' ');
+ if (line.length >= 4) {
+ let localip = line[1];
+ let localport = '';
+ let localaddress = line[1].split(':');
+ if (localaddress.length > 1) {
+ localport = localaddress[localaddress.length - 1];
+ localaddress.pop();
+ localip = localaddress.join(':');
+ }
+ localip = localip.replace(/\[/g, '').replace(/\]/g, '');
+ let peerip = line[2];
+ let peerport = '';
+ let peeraddress = line[2].split(':');
+ if (peeraddress.length > 1) {
+ peerport = peeraddress[peeraddress.length - 1];
+ peeraddress.pop();
+ peerip = peeraddress.join(':');
+ }
+ peerip = peerip.replace(/\[/g, '').replace(/\]/g, '');
+ let pid = util.toInt(line[4]);
+ let connstate = line[3];
+ if (connstate === 'HERGESTELLT') { connstate = 'ESTABLISHED'; }
+ if (connstate.startsWith('ABH')) { connstate = 'LISTEN'; }
+ if (connstate === 'SCHLIESSEN_WARTEN') { connstate = 'CLOSE_WAIT'; }
+ if (connstate === 'WARTEND') { connstate = 'TIME_WAIT'; }
+ if (connstate === 'SYN_GESENDET') { connstate = 'SYN_SENT'; }
+
+ if (connstate === 'LISTENING') { connstate = 'LISTEN'; }
+ if (connstate === 'SYN_RECEIVED') { connstate = 'SYN_RECV'; }
+ if (connstate === 'FIN_WAIT_1') { connstate = 'FIN_WAIT1'; }
+ if (connstate === 'FIN_WAIT_2') { connstate = 'FIN_WAIT2'; }
+ if (line[0].toLowerCase() !== 'udp' && connstate) {
+ result.push({
+ protocol: line[0].toLowerCase(),
+ localAddress: localip,
+ localPort: localport,
+ peerAddress: peerip,
+ peerPort: peerport,
+ state: connstate,
+ pid,
+ process: ''
+ });
+ } else if (line[0].toLowerCase() === 'udp') {
+ result.push({
+ protocol: line[0].toLowerCase(),
+ localAddress: localip,
+ localPort: localport,
+ peerAddress: peerip,
+ peerPort: peerport,
+ state: '',
+ pid: parseInt(line[3], 10),
+ process: ''
+ });
+ }
+ }
+ });
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
}
- });
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
});
+ });
}
-/** @internal */
-function getBodyLength(body) {
- if (!body) {
- return 0;
- }
- else if (Buffer.isBuffer(body)) {
- return body.length;
- }
- else if (isReadableStream(body)) {
- return null;
- }
- else if (isArrayBuffer(body)) {
- return body.byteLength;
- }
- else if (typeof body === "string") {
- return Buffer.from(body).length;
- }
- else {
- return null;
- }
-}
-/**
- * Create a new HttpClient instance for the NodeJS environment.
- * @internal
- */
-function createNodeHttpClient() {
- return new NodeHttpClient();
-}
-//# sourceMappingURL=nodeHttpClient.js.map
-
-/***/ }),
-/***/ 37050:
-/***/ ((__unused_webpack_module, exports) => {
+exports.networkConnections = networkConnections;
+function networkGatewayDefault(callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createEmptyPipeline = createEmptyPipeline;
-const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
-/**
- * A private implementation of Pipeline.
- * Do not export this class from the package.
- * @internal
- */
-class HttpPipeline {
- constructor(policies) {
- var _a;
- this._policies = [];
- this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : [];
- this._orderedPolicies = undefined;
- }
- addPolicy(policy, options = {}) {
- if (options.phase && options.afterPhase) {
- throw new Error("Policies inside a phase cannot specify afterPhase.");
- }
- if (options.phase && !ValidPhaseNames.has(options.phase)) {
- throw new Error(`Invalid phase name: ${options.phase}`);
- }
- if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {
- throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);
- }
- this._policies.push({
- policy,
- options,
- });
- this._orderedPolicies = undefined;
- }
- removePolicy(options) {
- const removedPolicies = [];
- this._policies = this._policies.filter((policyDescriptor) => {
- if ((options.name && policyDescriptor.policy.name === options.name) ||
- (options.phase && policyDescriptor.options.phase === options.phase)) {
- removedPolicies.push(policyDescriptor.policy);
- return false;
- }
- else {
- return true;
- }
- });
- this._orderedPolicies = undefined;
- return removedPolicies;
- }
- sendRequest(httpClient, request) {
- const policies = this.getOrderedPolicies();
- const pipeline = policies.reduceRight((next, policy) => {
- return (req) => {
- return policy.sendRequest(req, next);
- };
- }, (req) => httpClient.sendRequest(req));
- return pipeline(request);
- }
- getOrderedPolicies() {
- if (!this._orderedPolicies) {
- this._orderedPolicies = this.orderPolicies();
- }
- return this._orderedPolicies;
- }
- clone() {
- return new HttpPipeline(this._policies);
- }
- static create() {
- return new HttpPipeline();
- }
- orderPolicies() {
- /**
- * The goal of this method is to reliably order pipeline policies
- * based on their declared requirements when they were added.
- *
- * Order is first determined by phase:
- *
- * 1. Serialize Phase
- * 2. Policies not in a phase
- * 3. Deserialize Phase
- * 4. Retry Phase
- * 5. Sign Phase
- *
- * Within each phase, policies are executed in the order
- * they were added unless they were specified to execute
- * before/after other policies or after a particular phase.
- *
- * To determine the final order, we will walk the policy list
- * in phase order multiple times until all dependencies are
- * satisfied.
- *
- * `afterPolicies` are the set of policies that must be
- * executed before a given policy. This requirement is
- * considered satisfied when each of the listed policies
- * have been scheduled.
- *
- * `beforePolicies` are the set of policies that must be
- * executed after a given policy. Since this dependency
- * can be expressed by converting it into a equivalent
- * `afterPolicies` declarations, they are normalized
- * into that form for simplicity.
- *
- * An `afterPhase` dependency is considered satisfied when all
- * policies in that phase have scheduled.
- *
- */
- const result = [];
- // Track all policies we know about.
- const policyMap = new Map();
- function createPhase(name) {
- return {
- name,
- policies: new Set(),
- hasRun: false,
- hasAfterPolicies: false,
- };
- }
- // Track policies for each phase.
- const serializePhase = createPhase("Serialize");
- const noPhase = createPhase("None");
- const deserializePhase = createPhase("Deserialize");
- const retryPhase = createPhase("Retry");
- const signPhase = createPhase("Sign");
- // a list of phases in order
- const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
- // Small helper function to map phase name to each Phase
- function getPhase(phase) {
- if (phase === "Retry") {
- return retryPhase;
- }
- else if (phase === "Serialize") {
- return serializePhase;
- }
- else if (phase === "Deserialize") {
- return deserializePhase;
- }
- else if (phase === "Sign") {
- return signPhase;
- }
- else {
- return noPhase;
- }
- }
- // First walk each policy and create a node to track metadata.
- for (const descriptor of this._policies) {
- const policy = descriptor.policy;
- const options = descriptor.options;
- const policyName = policy.name;
- if (policyMap.has(policyName)) {
- throw new Error("Duplicate policy names not allowed in pipeline");
- }
- const node = {
- policy,
- dependsOn: new Set(),
- dependants: new Set(),
- };
- if (options.afterPhase) {
- node.afterPhase = getPhase(options.afterPhase);
- node.afterPhase.hasAfterPolicies = true;
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = '';
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ let cmd = 'ip route get 1';
+ try {
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ const line = lines && lines[0] ? lines[0] : '';
+ let parts = line.split(' via ');
+ if (parts && parts[1]) {
+ parts = parts[1].split(' ');
+ result = parts[0];
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
}
- policyMap.set(policyName, node);
- const phase = getPhase(options.phase);
- phase.policies.add(node);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- // Now that each policy has a node, connect dependency references.
- for (const descriptor of this._policies) {
- const { policy, options } = descriptor;
- const policyName = policy.name;
- const node = policyMap.get(policyName);
- if (!node) {
- throw new Error(`Missing node for policy ${policyName}`);
- }
- if (options.afterPolicies) {
- for (const afterPolicyName of options.afterPolicies) {
- const afterNode = policyMap.get(afterPolicyName);
- if (afterNode) {
- // Linking in both directions helps later
- // when we want to notify dependants.
- node.dependsOn.add(afterNode);
- afterNode.dependants.add(node);
- }
- }
+ }
+ if (_darwin) {
+ let cmd = 'route -n get default';
+ try {
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+ if (!error) {
+ const lines = stdout.toString().split('\n').map(line => line.trim());
+ result = util.getValue(lines, 'gateway');
}
- if (options.beforePolicies) {
- for (const beforePolicyName of options.beforePolicies) {
- const beforeNode = policyMap.get(beforePolicyName);
- if (beforeNode) {
- // To execute before another node, make it
- // depend on the current node.
- beforeNode.dependsOn.add(node);
- node.dependants.add(beforeNode);
- }
+ if (!result) {
+ cmd = 'netstat -rn | awk \'/default/ {print $2}\'';
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+ const lines = stdout.toString().split('\n').map(line => line.trim());
+ result = lines.find(line => (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(line)));
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ });
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
}
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- function walkPhase(phase) {
- phase.hasRun = true;
- // Sets iterate in insertion order
- for (const node of phase.policies) {
- if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
- // If this node is waiting on a phase to complete,
- // we need to skip it for now.
- // Even if the phase is empty, we should wait for it
- // to be walked to avoid re-ordering policies.
- continue;
- }
- if (node.dependsOn.size === 0) {
- // If there's nothing else we're waiting for, we can
- // add this policy to the result list.
- result.push(node.policy);
- // Notify anything that depends on this policy that
- // the policy has been scheduled.
- for (const dependant of node.dependants) {
- dependant.dependsOn.delete(node);
- }
- policyMap.delete(node.policy.name);
- phase.policies.delete(node);
+ }
+ if (_windows) {
+ try {
+ exec('netstat -r', util.execOptsWin, function (error, stdout) {
+ const lines = stdout.toString().split(os.EOL);
+ lines.forEach(line => {
+ line = line.replace(/\s+/g, ' ').trim();
+ if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) {
+ const parts = line.split(' ');
+ if (parts.length >= 5 && (parts[parts.length - 3]).indexOf('.') > -1) {
+ result = parts[parts.length - 3];
}
- }
- }
- function walkPhases() {
- for (const phase of orderedPhases) {
- walkPhase(phase);
- // if the phase isn't complete
- if (phase.policies.size > 0 && phase !== noPhase) {
- if (!noPhase.hasRun) {
- // Try running noPhase to see if that unblocks this phase next tick.
- // This can happen if a phase that happens before noPhase
- // is waiting on a noPhase policy to complete.
- walkPhase(noPhase);
+ }
+ });
+ if (!result) {
+ util.powerShell('Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq \'0.0.0.0\' -and $_.Mask -eq \'0.0.0.0\' }')
+ .then((data) => {
+ let lines = data.toString().split('\r\n');
+ if (lines.length > 1 && !result) {
+ result = util.getValue(lines, 'NextHop');
+ if (callback) {
+ callback(result);
}
- // Don't proceed to the next phase until this phase finishes.
- return;
- }
- if (phase.hasAfterPolicies) {
- // Run any policies unblocked by this phase
- walkPhase(noPhase);
- }
- }
- }
- // Iterate until we've put every node in the result list.
- let iteration = 0;
- while (policyMap.size > 0) {
- iteration++;
- const initialResultLength = result.length;
- // Keep walking each phase in order until we can order every node.
- walkPhases();
- // The result list *should* get at least one larger each time
- // after the first full pass.
- // Otherwise, we're going to loop forever.
- if (result.length <= initialResultLength && iteration > 1) {
- throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
+ resolve(result);
+ // } else {
+ // exec('ipconfig', util.execOptsWin, function (error, stdout) {
+ // let lines = stdout.toString().split('\r\n');
+ // lines.forEach(function (line) {
+ // line = line.trim().replace(/\. /g, '');
+ // line = line.trim().replace(/ +/g, '');
+ // const parts = line.split(':');
+ // if ((parts[0].toLowerCase().startsWith('standardgate') || parts[0].toLowerCase().indexOf('gateway') > -1 || parts[0].toLowerCase().indexOf('enlace') > -1) && parts[1]) {
+ // result = parts[1];
+ // }
+ // });
+ // if (callback) { callback(result); }
+ // resolve(result);
+ // });
+ }
+ });
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
}
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- return result;
- }
-}
-/**
- * Creates a totally empty pipeline.
- * Useful for testing or creating a custom one.
- */
-function createEmptyPipeline() {
- return HttpPipeline.create();
+ }
+ });
+ });
}
-//# sourceMappingURL=pipeline.js.map
-
-/***/ }),
-
-/***/ 82425:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+exports.networkGatewayDefault = networkGatewayDefault;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createPipelineRequest = createPipelineRequest;
-const httpHeaders_js_1 = __nccwpck_require__(30596);
-const core_util_1 = __nccwpck_require__(30991);
-class PipelineRequestImpl {
- constructor(options) {
- var _a, _b, _c, _d, _e, _f, _g;
- this.url = options.url;
- this.body = options.body;
- this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)();
- this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET";
- this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0;
- this.multipartBody = options.multipartBody;
- this.formData = options.formData;
- this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false;
- this.proxySettings = options.proxySettings;
- this.streamResponseStatusCodes = options.streamResponseStatusCodes;
- this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false;
- this.abortSignal = options.abortSignal;
- this.tracingOptions = options.tracingOptions;
- this.onUploadProgress = options.onUploadProgress;
- this.onDownloadProgress = options.onDownloadProgress;
- this.requestId = options.requestId || (0, core_util_1.randomUUID)();
- this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false;
- this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false;
- }
-}
-/**
- * Creates a new pipeline request with the given options.
- * This method is to allow for the easy setting of default values and not required.
- * @param options - The options to create the request with.
- */
-function createPipelineRequest(options) {
- return new PipelineRequestImpl(options);
-}
-//# sourceMappingURL=pipelineRequest.js.map
/***/ }),
-/***/ 7250:
+/***/ 20330:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.auxiliaryAuthenticationHeaderPolicyName = void 0;
-exports.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy;
-const tokenCycler_js_1 = __nccwpck_require__(82534);
-const log_js_1 = __nccwpck_require__(58564);
-/**
- * The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
- */
-exports.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
-const AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
-async function sendAuthorizeRequest(options) {
- var _a, _b;
- const { scopes, getAccessToken, request } = options;
- const getTokenOptions = {
- abortSignal: request.abortSignal,
- tracingOptions: request.tracingOptions,
- };
- return (_b = (_a = (await getAccessToken(scopes, getTokenOptions))) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : "";
-}
-/**
- * A policy for external tokens to `x-ms-authorization-auxiliary` header.
- * This header will be used when creating a cross-tenant application we may need to handle authentication requests
- * for resources that are in different tenants.
- * You could see [ARM docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
- */
-function auxiliaryAuthenticationHeaderPolicy(options) {
- const { credentials, scopes } = options;
- const logger = options.logger || log_js_1.logger;
- const tokenCyclerMap = new WeakMap();
- return {
- name: exports.auxiliaryAuthenticationHeaderPolicyName,
- async sendRequest(request, next) {
- if (!request.url.toLowerCase().startsWith("https://")) {
- throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
- }
- if (!credentials || credentials.length === 0) {
- logger.info(`${exports.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
- return next(request);
- }
- const tokenPromises = [];
- for (const credential of credentials) {
- let getAccessToken = tokenCyclerMap.get(credential);
- if (!getAccessToken) {
- getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential);
- tokenCyclerMap.set(credential, getAccessToken);
- }
- tokenPromises.push(sendAuthorizeRequest({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- request,
- getAccessToken,
- logger,
- }));
- }
- const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
- if (auxiliaryTokens.length === 0) {
- logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
- return next(request);
- }
- request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
- return next(request);
- },
- };
-}
-//# sourceMappingURL=auxiliaryAuthenticationHeaderPolicy.js.map
+// @ts-check
+// ==================================================================================
+// osinfo.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 3. Operating System
+// ----------------------------------------------------------------------------------
-/***/ }),
+const os = __nccwpck_require__(70857);
+const fs = __nccwpck_require__(79896);
+const util = __nccwpck_require__(77496);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
-/***/ 42081:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+let _platform = process.platform;
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.bearerTokenAuthenticationPolicyName = void 0;
-exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy;
-exports.parseChallenges = parseChallenges;
-const tokenCycler_js_1 = __nccwpck_require__(82534);
-const log_js_1 = __nccwpck_require__(58564);
-const restError_js_1 = __nccwpck_require__(97558);
-/**
- * The programmatic identifier of the bearerTokenAuthenticationPolicy.
- */
-exports.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
-/**
- * Try to send the given request.
- *
- * When a response is received, returns a tuple of the response received and, if the response was received
- * inside a thrown RestError, the RestError that was thrown.
- *
- * Otherwise, if an error was thrown while sending the request that did not provide an underlying response, it
- * will be rethrown.
- */
-async function trySendRequest(request, next) {
+// --------------------------
+// Get current time and OS uptime
+
+function time() {
+ let t = new Date().toString().split(' ');
+ const result = {
+ current: Date.now(),
+ uptime: os.uptime(),
+ timezone: (t.length >= 7) ? t[5] : '',
+ timezoneName: Intl ? Intl.DateTimeFormat().resolvedOptions().timeZone : (t.length >= 7) ? t.slice(6).join(' ').replace(/\(/g, '').replace(/\)/g, '') : ''
+ };
+ if (_darwin || _linux) {
try {
- return [await next(request), undefined];
- }
- catch (e) {
- if ((0, restError_js_1.isRestError)(e) && e.response) {
- return [e.response, e];
- }
- else {
- throw e;
- }
- }
-}
-/**
- * Default authorize request handler
- */
-async function defaultAuthorizeRequest(options) {
- const { scopes, getAccessToken, request } = options;
- // Enable CAE true by default
- const getTokenOptions = {
- abortSignal: request.abortSignal,
- tracingOptions: request.tracingOptions,
- enableCae: true,
- };
- const accessToken = await getAccessToken(scopes, getTokenOptions);
- if (accessToken) {
- options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
- }
-}
-/**
- * We will retrieve the challenge only if the response status code was 401,
- * and if the response contained the header "WWW-Authenticate" with a non-empty value.
- */
-function isChallengeResponse(response) {
- return response.status === 401 && response.headers.has("WWW-Authenticate");
-}
-/**
- * Re-authorize the request for CAE challenge.
- * The response containing the challenge is `options.response`.
- * If this method returns true, the underlying request will be sent once again.
- */
-async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) {
- var _a;
- const { scopes } = onChallengeOptions;
- const accessToken = await onChallengeOptions.getAccessToken(scopes, {
- enableCae: true,
- claims: caeClaims,
- });
- if (!accessToken) {
- return false;
+ const stdout = execSync('date +%Z && date +%z && ls -l /etc/localtime 2>/dev/null', util.execOptsLinux);
+ const lines = stdout.toString().split(os.EOL);
+ if (lines.length > 3 && !lines[0]) {
+ lines.shift();
+ }
+ let timezone = lines[0] || '';
+ if (timezone.startsWith('+') || timezone.startsWith('-')) {
+ timezone = 'GMT';
+ }
+ return {
+ current: Date.now(),
+ uptime: os.uptime(),
+ timezone: lines[1] ? timezone + lines[1] : timezone,
+ timezoneName: lines[2] && lines[2].indexOf('/zoneinfo/') > 0 ? (lines[2].split('/zoneinfo/')[1] || '') : ''
+ };
+ } catch (e) {
+ util.noop();
}
- onChallengeOptions.request.headers.set("Authorization", `${(_a = accessToken.tokenType) !== null && _a !== void 0 ? _a : "Bearer"} ${accessToken.token}`);
- return true;
+ }
+ return result;
}
-/**
- * A policy that can request a token from a TokenCredential implementation and
- * then apply it to the Authorization header of a request as a Bearer token.
- */
-function bearerTokenAuthenticationPolicy(options) {
- var _a, _b, _c;
- const { credential, scopes, challengeCallbacks } = options;
- const logger = options.logger || log_js_1.logger;
- const callbacks = {
- authorizeRequest: (_b = (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) === null || _a === void 0 ? void 0 : _a.bind(challengeCallbacks)) !== null && _b !== void 0 ? _b : defaultAuthorizeRequest,
- authorizeRequestOnChallenge: (_c = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge) === null || _c === void 0 ? void 0 : _c.bind(challengeCallbacks),
- };
- // This function encapsulates the entire process of reliably retrieving the token
- // The options are left out of the public API until there's demand to configure this.
- // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`
- // in order to pass through the `options` object.
- const getAccessToken = credential
- ? (0, tokenCycler_js_1.createTokenCycler)(credential /* , options */)
- : () => Promise.resolve(null);
- return {
- name: exports.bearerTokenAuthenticationPolicyName,
- /**
- * If there's no challenge parameter:
- * - It will try to retrieve the token using the cache, or the credential's getToken.
- * - Then it will try the next policy with or without the retrieved token.
- *
- * It uses the challenge parameters to:
- * - Skip a first attempt to get the token from the credential if there's no cached token,
- * since it expects the token to be retrievable only after the challenge.
- * - Prepare the outgoing request if the `prepareRequest` method has been provided.
- * - Send an initial request to receive the challenge if it fails.
- * - Process a challenge if the response contains it.
- * - Retrieve a token with the challenge information, then re-send the request.
- */
- async sendRequest(request, next) {
- if (!request.url.toLowerCase().startsWith("https://")) {
- throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
- }
- await callbacks.authorizeRequest({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- request,
- getAccessToken,
- logger,
- });
- let response;
- let error;
- let shouldSendRequest;
- [response, error] = await trySendRequest(request, next);
- if (isChallengeResponse(response)) {
- let claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
- // Handle CAE by default when receive CAE claim
- if (claims) {
- let parsedClaim;
- // Return the response immediately if claims is not a valid base64 encoded string
- try {
- parsedClaim = atob(claims);
- }
- catch (e) {
- logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
- return response;
- }
- shouldSendRequest = await authorizeRequestOnCaeChallenge({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- response,
- request,
- getAccessToken,
- logger,
- }, parsedClaim);
- // Send updated request and handle response for RestError
- if (shouldSendRequest) {
- [response, error] = await trySendRequest(request, next);
- }
- }
- else if (callbacks.authorizeRequestOnChallenge) {
- // Handle custom challenges when client provides custom callback
- shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- request,
- response,
- getAccessToken,
- logger,
- });
- // Send updated request and handle response for RestError
- if (shouldSendRequest) {
- [response, error] = await trySendRequest(request, next);
- }
- // If we get another CAE Claim, we will handle it by default and return whatever value we receive for this
- if (isChallengeResponse(response)) {
- claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
- if (claims) {
- let parsedClaim;
- try {
- parsedClaim = atob(claims);
- }
- catch (e) {
- logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
- return response;
- }
- shouldSendRequest = await authorizeRequestOnCaeChallenge({
- scopes: Array.isArray(scopes) ? scopes : [scopes],
- response,
- request,
- getAccessToken,
- logger,
- }, parsedClaim);
- // Send updated request and handle response for RestError
- if (shouldSendRequest) {
- [response, error] = await trySendRequest(request, next);
- }
- }
- }
- }
- }
- if (error) {
- throw error;
- }
- else {
- return response;
- }
- },
- };
+
+exports.time = time;
+
+// --------------------------
+// Get logo filename of OS distribution
+
+function getLogoFile(distro) {
+ distro = distro || '';
+ distro = distro.toLowerCase();
+ let result = _platform;
+ if (_windows) {
+ result = 'windows';
+ }
+ else if (distro.indexOf('mac os') !== -1 || distro.indexOf('macos') !== -1) {
+ result = 'apple';
+ }
+ else if (distro.indexOf('arch') !== -1) {
+ result = 'arch';
+ }
+ else if (distro.indexOf('cachy') !== -1) {
+ result = 'cachy';
+ }
+ else if (distro.indexOf('centos') !== -1) {
+ result = 'centos';
+ }
+ else if (distro.indexOf('coreos') !== -1) {
+ result = 'coreos';
+ }
+ else if (distro.indexOf('debian') !== -1) {
+ result = 'debian';
+ }
+ else if (distro.indexOf('deepin') !== -1) {
+ result = 'deepin';
+ }
+ else if (distro.indexOf('elementary') !== -1) {
+ result = 'elementary';
+ }
+ else if (distro.indexOf('endeavour') !== -1) {
+ result = 'endeavour';
+ }
+ else if (distro.indexOf('fedora') !== -1) {
+ result = 'fedora';
+ }
+ else if (distro.indexOf('gentoo') !== -1) {
+ result = 'gentoo';
+ }
+ else if (distro.indexOf('mageia') !== -1) {
+ result = 'mageia';
+ }
+ else if (distro.indexOf('mandriva') !== -1) {
+ result = 'mandriva';
+ }
+ else if (distro.indexOf('manjaro') !== -1) {
+ result = 'manjaro';
+ }
+ else if (distro.indexOf('mint') !== -1) {
+ result = 'mint';
+ }
+ else if (distro.indexOf('mx') !== -1) {
+ result = 'mx';
+ }
+ else if (distro.indexOf('openbsd') !== -1) {
+ result = 'openbsd';
+ }
+ else if (distro.indexOf('freebsd') !== -1) {
+ result = 'freebsd';
+ }
+ else if (distro.indexOf('opensuse') !== -1) {
+ result = 'opensuse';
+ }
+ else if (distro.indexOf('pclinuxos') !== -1) {
+ result = 'pclinuxos';
+ }
+ else if (distro.indexOf('puppy') !== -1) {
+ result = 'puppy';
+ }
+ else if (distro.indexOf('popos') !== -1) {
+ result = 'popos';
+ }
+ else if (distro.indexOf('raspbian') !== -1) {
+ result = 'raspbian';
+ }
+ else if (distro.indexOf('reactos') !== -1) {
+ result = 'reactos';
+ }
+ else if (distro.indexOf('redhat') !== -1) {
+ result = 'redhat';
+ }
+ else if (distro.indexOf('slackware') !== -1) {
+ result = 'slackware';
+ }
+ else if (distro.indexOf('sugar') !== -1) {
+ result = 'sugar';
+ }
+ else if (distro.indexOf('steam') !== -1) {
+ result = 'steam';
+ }
+ else if (distro.indexOf('suse') !== -1) {
+ result = 'suse';
+ }
+ else if (distro.indexOf('mate') !== -1) {
+ result = 'ubuntu-mate';
+ }
+ else if (distro.indexOf('lubuntu') !== -1) {
+ result = 'lubuntu';
+ }
+ else if (distro.indexOf('xubuntu') !== -1) {
+ result = 'xubuntu';
+ }
+ else if (distro.indexOf('ubuntu') !== -1) {
+ result = 'ubuntu';
+ }
+ else if (distro.indexOf('solaris') !== -1) {
+ result = 'solaris';
+ }
+ else if (distro.indexOf('tails') !== -1) {
+ result = 'tails';
+ }
+ else if (distro.indexOf('feren') !== -1) {
+ result = 'ferenos';
+ }
+ else if (distro.indexOf('robolinux') !== -1) {
+ result = 'robolinux';
+ } else if (_linux && distro) {
+ result = distro.toLowerCase().trim().replace(/\s+/g, '-');
+ }
+ return result;
}
-/**
- * Converts: `Bearer a="b", c="d", Pop e="f", g="h"`.
- * Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`.
- *
- * @internal
- */
-function parseChallenges(challenges) {
- // Challenge regex seperates the string to individual challenges with different schemes in the format `Scheme a="b", c=d`
- // The challenge regex captures parameteres with either quotes values or unquoted values
- const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g;
- // Parameter regex captures the claims group removed from the scheme in the format `a="b"` and `c="d"`
- // CAE challenge always have quoted parameters. For more reference, https://learn.microsoft.com/entra/identity-platform/claims-challenge
- const paramRegex = /(\w+)="([^"]*)"/g;
- const parsedChallenges = [];
- let match;
- // Iterate over each challenge match
- while ((match = challengeRegex.exec(challenges)) !== null) {
- const scheme = match[1];
- const paramsString = match[2];
- const params = {};
- let paramMatch;
- // Iterate over each parameter match
- while ((paramMatch = paramRegex.exec(paramsString)) !== null) {
- params[paramMatch[1]] = paramMatch[2];
- }
- parsedChallenges.push({ scheme, params });
+
+// --------------------------
+// FQDN
+
+function getFQDN() {
+ let fqdn = os.hostname;
+ if (_linux || _darwin) {
+ try {
+ const stdout = execSync('hostname -f 2>/dev/null', util.execOptsLinux);
+ fqdn = stdout.toString().split(os.EOL)[0];
+ } catch (e) {
+ util.noop();
}
- return parsedChallenges;
-}
-/**
- * Parse a pipeline response and look for a CAE challenge with "Bearer" scheme
- * Return the value in the header without parsing the challenge
- * @internal
- */
-function getCaeChallengeClaims(challenges) {
- var _a;
- if (!challenges) {
- return;
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ try {
+ const stdout = execSync('hostname 2>/dev/null');
+ fqdn = stdout.toString().split(os.EOL)[0];
+ } catch (e) {
+ util.noop();
}
- // Find all challenges present in the header
- const parsedChallenges = parseChallenges(challenges);
- return (_a = parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")) === null || _a === void 0 ? void 0 : _a.params.claims;
+ }
+ if (_windows) {
+ try {
+ const stdout = execSync('echo %COMPUTERNAME%.%USERDNSDOMAIN%', util.execOptsWin);
+ fqdn = stdout.toString().replace('.%USERDNSDOMAIN%', '').split(os.EOL)[0];
+ } catch (e) {
+ util.noop();
+ }
+ }
+ return fqdn;
}
-//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map
-
-/***/ }),
-/***/ 13299:
-/***/ ((__unused_webpack_module, exports) => {
+// --------------------------
+// OS Information
+function osInfo(callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decompressResponsePolicyName = void 0;
-exports.decompressResponsePolicy = decompressResponsePolicy;
-/**
- * The programmatic identifier of the decompressResponsePolicy.
- */
-exports.decompressResponsePolicyName = "decompressResponsePolicy";
-/**
- * A policy to enable response decompression according to Accept-Encoding header
- * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
- */
-function decompressResponsePolicy() {
- return {
- name: exports.decompressResponsePolicyName,
- async sendRequest(request, next) {
- // HEAD requests have no body
- if (request.method !== "HEAD") {
- request.headers.set("Accept-Encoding", "gzip,deflate");
- }
- return next(request);
- },
- };
-}
-//# sourceMappingURL=decompressResponsePolicy.js.map
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
-/***/ }),
+ platform: (_platform === 'win32' ? 'Windows' : _platform),
+ distro: 'unknown',
+ release: 'unknown',
+ codename: '',
+ kernel: os.release(),
+ arch: os.arch(),
+ hostname: os.hostname(),
+ fqdn: getFQDN(),
+ codepage: '',
+ logofile: '',
+ serial: '',
+ build: '',
+ servicepack: '',
+ uefi: false
+ };
-/***/ 47494:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (_linux) {
+ exec('cat /etc/*-release; cat /usr/lib/os-release; cat /etc/openwrt_release', function (error, stdout) {
+ /**
+ * @namespace
+ * @property {string} DISTRIB_ID
+ * @property {string} NAME
+ * @property {string} DISTRIB_RELEASE
+ * @property {string} VERSION_ID
+ * @property {string} DISTRIB_CODENAME
+ */
+ let release = {};
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ if (line.indexOf('=') !== -1) {
+ release[line.split('=')[0].trim().toUpperCase()] = line.split('=')[1].trim();
+ }
+ });
+ result.distro = (release.DISTRIB_ID || release.NAME || 'unknown').replace(/"/g, '');
+ result.logofile = getLogoFile(result.distro);
+ let releaseVersion = (release.VERSION || '').replace(/"/g, '');
+ let codename = (release.DISTRIB_CODENAME || release.VERSION_CODENAME || '').replace(/"/g, '');
+ const prettyName = (release.PRETTY_NAME || '').replace(/"/g, '');
+ if (prettyName.indexOf(result.distro + ' ') === 0) {
+ releaseVersion = prettyName.replace(result.distro + ' ', '').trim();
+ }
+ if (releaseVersion.indexOf('(') >= 0) {
+ codename = releaseVersion.split('(')[1].replace(/[()]/g, '').trim();
+ releaseVersion = releaseVersion.split('(')[0].trim();
+ }
+ result.release = (releaseVersion || release.DISTRIB_RELEASE || release.VERSION_ID || 'unknown').replace(/"/g, '');
+ result.codename = codename;
+ result.codepage = util.getCodepage();
+ result.build = (release.BUILD_ID || '').replace(/"/g, '').trim();
+ isUefiLinux().then(uefi => {
+ result.uefi = uefi;
+ uuid().then((data) => {
+ result.serial = data.os;
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ });
+ });
+ }
+ if (_freebsd || _openbsd || _netbsd) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.defaultRetryPolicyName = void 0;
-exports.defaultRetryPolicy = defaultRetryPolicy;
-const exponentialRetryStrategy_js_1 = __nccwpck_require__(34750);
-const throttlingRetryStrategy_js_1 = __nccwpck_require__(40288);
-const retryPolicy_js_1 = __nccwpck_require__(85001);
-const constants_js_1 = __nccwpck_require__(91791);
-/**
- * Name of the {@link defaultRetryPolicy}
- */
-exports.defaultRetryPolicyName = "defaultRetryPolicy";
-/**
- * A policy that retries according to three strategies:
- * - When the server sends a 429 response with a Retry-After header.
- * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
- * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
- */
-function defaultRetryPolicy(options = {}) {
- var _a;
- return {
- name: exports.defaultRetryPolicyName,
- sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], {
- maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
- }).sendRequest,
- };
+ exec('sysctl kern.ostype kern.osrelease kern.osrevision kern.hostuuid machdep.bootmethod kern.geom.confxml', function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ const distro = util.getValue(lines, 'kern.ostype');
+ const logofile = getLogoFile(distro);
+ const release = util.getValue(lines, 'kern.osrelease').split('-')[0];
+ const serial = util.getValue(lines, 'kern.uuid');
+ const bootmethod = util.getValue(lines, 'machdep.bootmethod');
+ const uefiConf = stdout.toString().indexOf('efi') >= 0;
+ const uefi = bootmethod ? bootmethod.toLowerCase().indexOf('uefi') >= 0 : (uefiConf ? uefiConf : null);
+ result.distro = distro || result.distro;
+ result.logofile = logofile || result.logofile;
+ result.release = release || result.release;
+ result.serial = serial || result.serial;
+ result.codename = '';
+ result.codepage = util.getCodepage();
+ result.uefi = uefi || null;
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ exec('sw_vers; sysctl kern.ostype kern.osrelease kern.osrevision kern.uuid', function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ result.serial = util.getValue(lines, 'kern.uuid');
+ result.distro = util.getValue(lines, 'ProductName');
+ result.release = (util.getValue(lines, 'ProductVersion', ':', true, true) + ' ' + util.getValue(lines, 'ProductVersionExtra', ':', true, true)).trim();
+ result.build = util.getValue(lines, 'BuildVersion');
+ result.logofile = getLogoFile(result.distro);
+ result.codename = 'macOS';
+ result.codename = (result.release.indexOf('10.4') > -1 ? 'OS X Tiger' : result.codename);
+ result.codename = (result.release.indexOf('10.5') > -1 ? 'OS X Leopard' : result.codename);
+ result.codename = (result.release.indexOf('10.6') > -1 ? 'OS X Snow Leopard' : result.codename);
+ result.codename = (result.release.indexOf('10.7') > -1 ? 'OS X Lion' : result.codename);
+ result.codename = (result.release.indexOf('10.8') > -1 ? 'OS X Mountain Lion' : result.codename);
+ result.codename = (result.release.indexOf('10.9') > -1 ? 'OS X Mavericks' : result.codename);
+ result.codename = (result.release.indexOf('10.10') > -1 ? 'OS X Yosemite' : result.codename);
+ result.codename = (result.release.indexOf('10.11') > -1 ? 'OS X El Capitan' : result.codename);
+ result.codename = (result.release.indexOf('10.12') > -1 ? 'Sierra' : result.codename);
+ result.codename = (result.release.indexOf('10.13') > -1 ? 'High Sierra' : result.codename);
+ result.codename = (result.release.indexOf('10.14') > -1 ? 'Mojave' : result.codename);
+ result.codename = (result.release.indexOf('10.15') > -1 ? 'Catalina' : result.codename);
+ result.codename = (result.release.startsWith('11.') ? 'Big Sur' : result.codename);
+ result.codename = (result.release.startsWith('12.') ? 'Monterey' : result.codename);
+ result.codename = (result.release.startsWith('13.') ? 'Ventura' : result.codename);
+ result.codename = (result.release.startsWith('14.') ? 'Sonoma' : result.codename);
+ result.codename = (result.release.startsWith('15.') ? 'Sequoia' : result.codename);
+ result.uefi = true;
+ result.codepage = util.getCodepage();
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ result.release = result.kernel;
+ exec('uname -o', function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ result.distro = lines[0];
+ result.logofile = getLogoFile(result.distro);
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_windows) {
+ result.logofile = getLogoFile();
+ result.release = result.kernel;
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance Win32_OperatingSystem | select Caption,SerialNumber,BuildNumber,ServicePackMajorVersion,ServicePackMinorVersion | fl'));
+ workload.push(util.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent'));
+ workload.push(util.powerShell('Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SystemInformation]::TerminalServerSession'));
+ util.promiseAll(
+ workload
+ ).then((data) => {
+ let lines = data.results[0] ? data.results[0].toString().split('\r\n') : [''];
+ result.distro = util.getValue(lines, 'Caption', ':').trim();
+ result.serial = util.getValue(lines, 'SerialNumber', ':').trim();
+ result.build = util.getValue(lines, 'BuildNumber', ':').trim();
+ result.servicepack = util.getValue(lines, 'ServicePackMajorVersion', ':').trim() + '.' + util.getValue(lines, 'ServicePackMinorVersion', ':').trim();
+ result.codepage = util.getCodepage();
+ const hyperv = data.results[1] ? data.results[1].toString().toLowerCase() : '';
+ result.hypervisor = hyperv.indexOf('true') !== -1;
+ const term = data.results[2] ? data.results[2].toString() : '';
+ result.remoteSession = (term.toString().toLowerCase().indexOf('true') >= 0);
+ isUefiWindows().then(uefi => {
+ result.uefi = uefi;
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ });
+ });
}
-//# sourceMappingURL=defaultRetryPolicy.js.map
-
-/***/ }),
-
-/***/ 43048:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+exports.osInfo = osInfo;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.exponentialRetryPolicyName = void 0;
-exports.exponentialRetryPolicy = exponentialRetryPolicy;
-const exponentialRetryStrategy_js_1 = __nccwpck_require__(34750);
-const retryPolicy_js_1 = __nccwpck_require__(85001);
-const constants_js_1 = __nccwpck_require__(91791);
-/**
- * The programmatic identifier of the exponentialRetryPolicy.
- */
-exports.exponentialRetryPolicyName = "exponentialRetryPolicy";
-/**
- * A policy that attempts to retry requests while introducing an exponentially increasing delay.
- * @param options - Options that configure retry logic.
- */
-function exponentialRetryPolicy(options = {}) {
- var _a;
- return (0, retryPolicy_js_1.retryPolicy)([
- (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })),
- ], {
- maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+function isUefiLinux() {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ fs.stat('/sys/firmware/efi', function (err) {
+ if (!err) {
+ return resolve(true);
+ } else {
+ exec('dmesg | grep -E "EFI v"', function (error, stdout) {
+ if (!error) {
+ const lines = stdout.toString().split('\n');
+ return resolve(lines.length > 0);
+ }
+ return resolve(false);
+ });
+ }
+ });
});
+ });
}
-//# sourceMappingURL=exponentialRetryPolicy.js.map
-/***/ }),
+function isUefiWindows() {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ try {
+ exec('findstr /C:"Detected boot environment" "%windir%\\Panther\\setupact.log"', util.execOptsWin, function (error, stdout) {
+ if (!error) {
+ const line = stdout.toString().split('\n\r')[0];
+ return resolve(line.toLowerCase().indexOf('efi') >= 0);
+ } else {
+ exec('echo %firmware_type%', util.execOptsWin, function (error, stdout) {
+ if (!error) {
+ const line = stdout.toString() || '';
+ return resolve(line.toLowerCase().indexOf('efi') >= 0);
+ } else {
+ return resolve(false);
+ }
+ });
+ }
+ });
+ } catch (e) {
+ return resolve(false);
+ }
+ });
+ });
+}
-/***/ 37997:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function versions(apps, callback) {
+ let versionObject = {
+ kernel: os.release(),
+ apache: '',
+ bash: '',
+ bun: '',
+ deno: '',
+ docker: '',
+ dotnet: '',
+ fish: '',
+ gcc: '',
+ git: '',
+ grunt: '',
+ gulp: '',
+ homebrew: '',
+ java: '',
+ mongodb: '',
+ mysql: '',
+ nginx: '',
+ node: '', //process.versions.node,
+ npm: '',
+ openssl: '',
+ perl: '',
+ php: '',
+ pip3: '',
+ pip: '',
+ pm2: '',
+ postfix: '',
+ postgresql: '',
+ powershell: '',
+ python3: '',
+ python: '',
+ redis: '',
+ systemOpenssl: '',
+ systemOpensslLib: '',
+ tsc: '',
+ v8: process.versions.v8,
+ virtualbox: '',
+ yarn: '',
+ zsh: ''
+ };
+ function checkVersionParam(apps) {
+ if (apps === '*') {
+ return {
+ versions: versionObject,
+ counter: 34
+ };
+ }
+ if (!Array.isArray(apps)) {
+ apps = apps.trim().toLowerCase().replace(/,+/g, '|').replace(/ /g, '|');
+ apps = apps.split('|');
+ const result = {
+ versions: {},
+ counter: 0
+ };
+ apps.forEach(el => {
+ if (el) {
+ for (let key in versionObject) {
+ if ({}.hasOwnProperty.call(versionObject, key)) {
+ if (key.toLowerCase() === el.toLowerCase() && !{}.hasOwnProperty.call(result.versions, key)) {
+ result.versions[key] = versionObject[key];
+ if (key === 'openssl') {
+ result.versions.systemOpenssl = '';
+ result.versions.systemOpensslLib = '';
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.formDataPolicyName = void 0;
-exports.formDataPolicy = formDataPolicy;
-const core_util_1 = __nccwpck_require__(30991);
-const httpHeaders_js_1 = __nccwpck_require__(30596);
-/**
- * The programmatic identifier of the formDataPolicy.
- */
-exports.formDataPolicyName = "formDataPolicy";
-function formDataToFormDataMap(formData) {
- var _a;
- const formDataMap = {};
- for (const [key, value] of formData.entries()) {
- (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : (formDataMap[key] = []);
- formDataMap[key].push(value);
+ if (!result.versions[key]) { result.counter++; }
+ }
+ }
+ }
+ }
+ });
+ return result;
}
- return formDataMap;
-}
-/**
- * A policy that encodes FormData on the request into the body.
- */
-function formDataPolicy() {
- return {
- name: exports.formDataPolicyName,
- async sendRequest(request, next) {
- if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) {
- request.formData = formDataToFormDataMap(request.body);
- request.body = undefined;
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (util.isFunction(apps) && !callback) {
+ callback = apps;
+ apps = '*';
+ } else {
+ apps = apps || '*';
+ if (typeof apps !== 'string') {
+ if (callback) { callback({}); }
+ return resolve({});
+ }
+ }
+ const appsObj = checkVersionParam(apps);
+ let totalFunctions = appsObj.counter;
+
+ let functionProcessed = (function () {
+ return function () {
+ if (--totalFunctions === 0) {
+ if (callback) {
+ callback(appsObj.versions);
+ }
+ resolve(appsObj.versions);
+ }
+ };
+ })();
+
+ let cmd = '';
+ try {
+ if ({}.hasOwnProperty.call(appsObj.versions, 'openssl')) {
+ appsObj.versions.openssl = process.versions.openssl;
+ exec('openssl version', function (error, stdout) {
+ if (!error) {
+ let openssl_string = stdout.toString().split('\n')[0].trim();
+ let openssl = openssl_string.split(' ');
+ appsObj.versions.systemOpenssl = openssl.length > 0 ? openssl[1] : openssl[0];
+ appsObj.versions.systemOpensslLib = openssl.length > 0 ? openssl[0] : 'openssl';
}
- if (request.formData) {
- const contentType = request.headers.get("Content-Type");
- if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
- request.body = wwwFormUrlEncode(request.formData);
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'npm')) {
+ exec('npm -v', function (error, stdout) {
+ if (!error) {
+ appsObj.versions.npm = stdout.toString().split('\n')[0];
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'pm2')) {
+ cmd = 'pm2';
+ if (_windows) {
+ cmd += '.cmd';
+ }
+ exec(`${cmd} -v`, function (error, stdout) {
+ if (!error) {
+ let pm2 = stdout.toString().split('\n')[0].trim();
+ if (!pm2.startsWith('[PM2]')) {
+ appsObj.versions.pm2 = pm2;
+ }
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'yarn')) {
+ exec('yarn --version', function (error, stdout) {
+ if (!error) {
+ appsObj.versions.yarn = stdout.toString().split('\n')[0];
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'gulp')) {
+ cmd = 'gulp';
+ if (_windows) {
+ cmd += '.cmd';
+ }
+ exec(`${cmd} --version`, function (error, stdout) {
+ if (!error) {
+ const gulp = stdout.toString().split('\n')[0] || '';
+ appsObj.versions.gulp = (gulp.toLowerCase().split('version')[1] || '').trim();
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'homebrew')) {
+ cmd = 'brew';
+ exec(`${cmd} --version`, function (error, stdout) {
+ if (!error) {
+ const brew = stdout.toString().split('\n')[0] || '';
+ appsObj.versions.homebrew = (brew.toLowerCase().split(' ')[1] || '').trim();
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'tsc')) {
+ cmd = 'tsc';
+ if (_windows) {
+ cmd += '.cmd';
+ }
+ exec(`${cmd} --version`, function (error, stdout) {
+ if (!error) {
+ const tsc = stdout.toString().split('\n')[0] || '';
+ appsObj.versions.tsc = (tsc.toLowerCase().split('version')[1] || '').trim();
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'grunt')) {
+ cmd = 'grunt';
+ if (_windows) {
+ cmd += '.cmd';
+ }
+ exec(`${cmd} --version`, function (error, stdout) {
+ if (!error) {
+ const grunt = stdout.toString().split('\n')[0] || '';
+ appsObj.versions.grunt = (grunt.toLowerCase().split('cli v')[1] || '').trim();
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'git')) {
+ if (_darwin) {
+ const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/git') || fs.existsSync('/opt/homebrew/bin/git');
+ if (util.darwinXcodeExists() || gitHomebrewExists) {
+ exec('git --version', function (error, stdout) {
+ if (!error) {
+ let git = stdout.toString().split('\n')[0] || '';
+ git = (git.toLowerCase().split('version')[1] || '').trim();
+ appsObj.versions.git = (git.split(' ')[0] || '').trim();
}
- else {
- await prepareFormData(request.formData, request);
+ functionProcessed();
+ });
+ } else {
+ functionProcessed();
+ }
+ } else {
+ exec('git --version', function (error, stdout) {
+ if (!error) {
+ let git = stdout.toString().split('\n')[0] || '';
+ git = (git.toLowerCase().split('version')[1] || '').trim();
+ appsObj.versions.git = (git.split(' ')[0] || '').trim();
+ }
+ functionProcessed();
+ });
+ }
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'apache')) {
+ exec('apachectl -v 2>&1', function (error, stdout) {
+ if (!error) {
+ const apache = (stdout.toString().split('\n')[0] || '').split(':');
+ appsObj.versions.apache = (apache.length > 1 ? apache[1].replace('Apache', '').replace('/', '').split('(')[0].trim() : '');
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'nginx')) {
+ exec('nginx -v 2>&1', function (error, stdout) {
+ if (!error) {
+ const nginx = stdout.toString().split('\n')[0] || '';
+ appsObj.versions.nginx = (nginx.toLowerCase().split('/')[1] || '').trim();
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'mysql')) {
+ exec('mysql -V', function (error, stdout) {
+ if (!error) {
+ let mysql = stdout.toString().split('\n')[0] || '';
+ mysql = mysql.toLowerCase();
+ if (mysql.indexOf(',') > -1) {
+ mysql = (mysql.split(',')[0] || '').trim();
+ const parts = mysql.split(' ');
+ appsObj.versions.mysql = (parts[parts.length - 1] || '').trim();
+ } else {
+ if (mysql.indexOf(' ver ') > -1) {
+ mysql = mysql.split(' ver ')[1];
+ appsObj.versions.mysql = mysql.split(' ')[0];
}
- request.formData = undefined;
+ }
}
- return next(request);
- },
- };
-}
-function wwwFormUrlEncode(formData) {
- const urlSearchParams = new URLSearchParams();
- for (const [key, value] of Object.entries(formData)) {
- if (Array.isArray(value)) {
- for (const subValue of value) {
- urlSearchParams.append(key, subValue.toString());
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'php')) {
+ exec('php -v', function (error, stdout) {
+ if (!error) {
+ const php = stdout.toString().split('\n')[0] || '';
+ let parts = php.split('(');
+ if (parts[0].indexOf('-')) {
+ parts = parts[0].split('-');
+ }
+ appsObj.versions.php = parts[0].replace(/[^0-9.]/g, '');
}
+ functionProcessed();
+ });
}
- else {
- urlSearchParams.append(key, value.toString());
+ if ({}.hasOwnProperty.call(appsObj.versions, 'redis')) {
+ exec('redis-server --version', function (error, stdout) {
+ if (!error) {
+ const redis = stdout.toString().split('\n')[0] || '';
+ const parts = redis.split(' ');
+ appsObj.versions.redis = util.getValue(parts, 'v', '=', true);
+ }
+ functionProcessed();
+ });
}
- }
- return urlSearchParams.toString();
-}
-async function prepareFormData(formData, request) {
- // validate content type (multipart/form-data)
- const contentType = request.headers.get("Content-Type");
- if (contentType && !contentType.startsWith("multipart/form-data")) {
- // content type is specified and is not multipart/form-data. Exit.
- return;
- }
- request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data");
- // set body to MultipartRequestBody using content from FormDataMap
- const parts = [];
- for (const [fieldName, values] of Object.entries(formData)) {
- for (const value of Array.isArray(values) ? values : [values]) {
- if (typeof value === "string") {
- parts.push({
- headers: (0, httpHeaders_js_1.createHttpHeaders)({
- "Content-Disposition": `form-data; name="${fieldName}"`,
- }),
- body: (0, core_util_1.stringToUint8Array)(value, "utf-8"),
- });
+ if ({}.hasOwnProperty.call(appsObj.versions, 'docker')) {
+ exec('docker --version', function (error, stdout) {
+ if (!error) {
+ const docker = stdout.toString().split('\n')[0] || '';
+ const parts = docker.split(' ');
+ appsObj.versions.docker = parts.length > 2 && parts[2].endsWith(',') ? parts[2].slice(0, -1) : '';
}
- else if (value === undefined || value === null || typeof value !== "object") {
- throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`);
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'postfix')) {
+ exec('postconf -d | grep mail_version', function (error, stdout) {
+ if (!error) {
+ const postfix = stdout.toString().split('\n') || [];
+ appsObj.versions.postfix = util.getValue(postfix, 'mail_version', '=', true);
}
- else {
- // using || instead of ?? here since if value.name is empty we should create a file name
- const fileName = value.name || "blob";
- const headers = (0, httpHeaders_js_1.createHttpHeaders)();
- headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
- // again, || is used since an empty value.type means the content type is unset
- headers.set("Content-Type", value.type || "application/octet-stream");
- parts.push({
- headers,
- body: value,
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'mongodb')) {
+ exec('mongod --version', function (error, stdout) {
+ if (!error) {
+ const mongodb = stdout.toString().split('\n')[0] || '';
+ appsObj.versions.mongodb = (mongodb.toLowerCase().split(',')[0] || '').replace(/[^0-9.]/g, '');
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'postgresql')) {
+ if (_linux) {
+ exec('locate bin/postgres', function (error, stdout) {
+ if (!error) {
+ const postgresqlBin = stdout.toString().split('\n').sort();
+ if (postgresqlBin.length) {
+ exec(postgresqlBin[postgresqlBin.length - 1] + ' -V', function (error, stdout) {
+ if (!error) {
+ const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
+ appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
+ }
+ functionProcessed();
+ });
+ } else {
+ functionProcessed();
+ }
+ } else {
+ exec('psql -V', function (error, stdout) {
+ if (!error) {
+ const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
+ appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
+ appsObj.versions.postgresql = appsObj.versions.postgresql.split('-')[0];
+ }
+ functionProcessed();
+ });
+ }
+ });
+ } else {
+ if (_windows) {
+ util.powerShell('Get-CimInstance Win32_Service | select caption | fl').then((stdout) => {
+ let serviceSections = stdout.split(/\n\s*\n/);
+ serviceSections.forEach((item) => {
+ if (item.trim() !== '') {
+ let lines = item.trim().split('\r\n');
+ let srvCaption = util.getValue(lines, 'caption', ':', true).toLowerCase();
+ if (srvCaption.indexOf('postgresql') > -1) {
+ const parts = srvCaption.split(' server ');
+ if (parts.length > 1) {
+ appsObj.versions.postgresql = parts[1];
+ }
+ }
+ }
});
+ functionProcessed();
+ });
+ } else {
+ exec('postgres -V', function (error, stdout) {
+ if (!error) {
+ const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
+ appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
+ } else {
+ exec('pg_config --version', function (error, stdout) {
+ if (!error) {
+ const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
+ appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
+ }
+ });
+ }
+ functionProcessed();
+ });
}
+ }
}
- }
- request.multipartBody = { parts };
-}
-//# sourceMappingURL=formDataPolicy.js.map
-
-/***/ }),
-
-/***/ 19937:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.logPolicyName = void 0;
-exports.logPolicy = logPolicy;
-const log_js_1 = __nccwpck_require__(58564);
-const sanitizer_js_1 = __nccwpck_require__(44720);
-/**
- * The programmatic identifier of the logPolicy.
- */
-exports.logPolicyName = "logPolicy";
-/**
- * A policy that logs all requests and responses.
- * @param options - Options to configure logPolicy.
- */
-function logPolicy(options = {}) {
- var _a;
- const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info;
- const sanitizer = new sanitizer_js_1.Sanitizer({
- additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,
- additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
- });
- return {
- name: exports.logPolicyName,
- async sendRequest(request, next) {
- if (!logger.enabled) {
- return next(request);
+ if ({}.hasOwnProperty.call(appsObj.versions, 'perl')) {
+ exec('perl -v', function (error, stdout) {
+ if (!error) {
+ const perl = stdout.toString().split('\n') || '';
+ while (perl.length > 0 && perl[0].trim() === '') {
+ perl.shift();
+ }
+ if (perl.length > 0) {
+ appsObj.versions.perl = perl[0].split('(').pop().split(')')[0].replace('v', '');
+ }
+ }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'python')) {
+ if (_darwin) {
+ try {
+ const stdout = execSync('sw_vers');
+ const lines = stdout.toString().split('\n');
+ const osVersion = util.getValue(lines, 'ProductVersion', ':');
+ const gitHomebrewExists1 = fs.existsSync('/usr/local/Cellar/python');
+ const gitHomebrewExists2 = fs.existsSync('/opt/homebrew/bin/python');
+ if ((util.darwinXcodeExists() && util.semverCompare('12.0.1', osVersion) < 0) || gitHomebrewExists1 || gitHomebrewExists2) {
+ const cmd = gitHomebrewExists1 ? '/usr/local/Cellar/python -V 2>&1' : (gitHomebrewExists2 ? '/opt/homebrew/bin/python -V 2>&1' : 'python -V 2>&1');
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ const python = stdout.toString().split('\n')[0] || '';
+ appsObj.versions.python = python.toLowerCase().replace('python', '').trim();
+ }
+ functionProcessed();
+ });
+ } else {
+ functionProcessed();
+ }
+ } catch (e) {
+ functionProcessed();
}
- logger(`Request: ${sanitizer.sanitize(request)}`);
- const response = await next(request);
- logger(`Response status code: ${response.status}`);
- logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
- return response;
- },
- };
-}
-//# sourceMappingURL=logPolicy.js.map
-
-/***/ }),
-
-/***/ 77915:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.multipartPolicyName = void 0;
-exports.multipartPolicy = multipartPolicy;
-const core_util_1 = __nccwpck_require__(30991);
-const concat_js_1 = __nccwpck_require__(85307);
-const typeGuards_js_1 = __nccwpck_require__(24449);
-function generateBoundary() {
- return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`;
-}
-function encodeHeaders(headers) {
- let result = "";
- for (const [key, value] of headers) {
- result += `${key}: ${value}\r\n`;
- }
- return result;
-}
-function getLength(source) {
- if (source instanceof Uint8Array) {
- return source.byteLength;
- }
- else if ((0, typeGuards_js_1.isBlob)(source)) {
- // if was created using createFile then -1 means we have an unknown size
- return source.size === -1 ? undefined : source.size;
- }
- else {
- return undefined;
- }
-}
-function getTotalLength(sources) {
- let total = 0;
- for (const source of sources) {
- const partLength = getLength(source);
- if (partLength === undefined) {
- return undefined;
+ } else {
+ exec('python -V 2>&1', function (error, stdout) {
+ if (!error) {
+ const python = stdout.toString().split('\n')[0] || '';
+ appsObj.versions.python = python.toLowerCase().replace('python', '').trim();
+ }
+ functionProcessed();
+ });
+ }
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'python3')) {
+ if (_darwin) {
+ const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/python3') || fs.existsSync('/opt/homebrew/bin/python3');
+ if (util.darwinXcodeExists() || gitHomebrewExists) {
+ exec('python3 -V 2>&1', function (error, stdout) {
+ if (!error) {
+ const python = stdout.toString().split('\n')[0] || '';
+ appsObj.versions.python3 = python.toLowerCase().replace('python', '').trim();
+ }
+ functionProcessed();
+ });
+ } else {
+ functionProcessed();
+ }
+ } else {
+ exec('python3 -V 2>&1', function (error, stdout) {
+ if (!error) {
+ const python = stdout.toString().split('\n')[0] || '';
+ appsObj.versions.python3 = python.toLowerCase().replace('python', '').trim();
+ }
+ functionProcessed();
+ });
+ }
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'pip')) {
+ if (_darwin) {
+ const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/pip') || fs.existsSync('/opt/homebrew/bin/pip');
+ if (util.darwinXcodeExists() || gitHomebrewExists) {
+ exec('pip -V 2>&1', function (error, stdout) {
+ if (!error) {
+ const pip = stdout.toString().split('\n')[0] || '';
+ const parts = pip.split(' ');
+ appsObj.versions.pip = parts.length >= 2 ? parts[1] : '';
+ }
+ functionProcessed();
+ });
+ } else {
+ functionProcessed();
+ }
+ } else {
+ exec('pip -V 2>&1', function (error, stdout) {
+ if (!error) {
+ const pip = stdout.toString().split('\n')[0] || '';
+ const parts = pip.split(' ');
+ appsObj.versions.pip = parts.length >= 2 ? parts[1] : '';
+ }
+ functionProcessed();
+ });
+ }
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'pip3')) {
+ if (_darwin) {
+ const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/pip3') || fs.existsSync('/opt/homebrew/bin/pip3');
+ if (util.darwinXcodeExists() || gitHomebrewExists) {
+ exec('pip3 -V 2>&1', function (error, stdout) {
+ if (!error) {
+ const pip = stdout.toString().split('\n')[0] || '';
+ const parts = pip.split(' ');
+ appsObj.versions.pip3 = parts.length >= 2 ? parts[1] : '';
+ }
+ functionProcessed();
+ });
+ } else {
+ functionProcessed();
+ }
+ } else {
+ exec('pip3 -V 2>&1', function (error, stdout) {
+ if (!error) {
+ const pip = stdout.toString().split('\n')[0] || '';
+ const parts = pip.split(' ');
+ appsObj.versions.pip3 = parts.length >= 2 ? parts[1] : '';
+ }
+ functionProcessed();
+ });
+ }
}
- else {
- total += partLength;
+ if ({}.hasOwnProperty.call(appsObj.versions, 'java')) {
+ if (_darwin) {
+ // check if any JVM is installed but avoid dialog box that Java needs to be installed
+ exec('/usr/libexec/java_home -V 2>&1', function (error, stdout) {
+ if (!error && stdout.toString().toLowerCase().indexOf('no java runtime') === -1) {
+ // now this can be done savely
+ exec('java -version 2>&1', function (error, stdout) {
+ if (!error) {
+ const java = stdout.toString().split('\n')[0] || '';
+ const parts = java.split('"');
+ appsObj.versions.java = parts.length === 3 ? parts[1].trim() : '';
+ }
+ functionProcessed();
+ });
+ } else {
+ functionProcessed();
+ }
+ });
+ } else {
+ exec('java -version 2>&1', function (error, stdout) {
+ if (!error) {
+ const java = stdout.toString().split('\n')[0] || '';
+ const parts = java.split('"');
+ appsObj.versions.java = parts.length === 3 ? parts[1].trim() : '';
+ }
+ functionProcessed();
+ });
+ }
}
- }
- return total;
-}
-async function buildRequestBody(request, parts, boundary) {
- const sources = [
- (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"),
- ...parts.flatMap((part) => [
- (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
- (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"),
- (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
- part.body,
- (0, core_util_1.stringToUint8Array)(`\r\n--${boundary}`, "utf-8"),
- ]),
- (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8"),
- ];
- const contentLength = getTotalLength(sources);
- if (contentLength) {
- request.headers.set("Content-Length", contentLength);
- }
- request.body = await (0, concat_js_1.concat)(sources);
-}
-/**
- * Name of multipart policy
- */
-exports.multipartPolicyName = "multipartPolicy";
-const maxBoundaryLength = 70;
-const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
-function assertValidBoundary(boundary) {
- if (boundary.length > maxBoundaryLength) {
- throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
- }
- if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
- throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
- }
-}
-/**
- * Pipeline policy for multipart requests
- */
-function multipartPolicy() {
- return {
- name: exports.multipartPolicyName,
- async sendRequest(request, next) {
- var _a;
- if (!request.multipartBody) {
- return next(request);
+ if ({}.hasOwnProperty.call(appsObj.versions, 'gcc')) {
+ if ((_darwin && util.darwinXcodeExists()) || !_darwin) {
+ exec('gcc -dumpversion', function (error, stdout) {
+ if (!error) {
+ appsObj.versions.gcc = stdout.toString().split('\n')[0].trim() || '';
+ }
+ if (appsObj.versions.gcc.indexOf('.') > -1) {
+ functionProcessed();
+ } else {
+ exec('gcc --version', function (error, stdout) {
+ if (!error) {
+ const gcc = stdout.toString().split('\n')[0].trim();
+ if (gcc.indexOf('gcc') > -1 && gcc.indexOf(')') > -1) {
+ const parts = gcc.split(')');
+ appsObj.versions.gcc = parts[1].trim() || appsObj.versions.gcc;
+ }
+ }
+ functionProcessed();
+ });
+ }
+ });
+ } else {
+ functionProcessed();
+ }
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'virtualbox')) {
+ exec(util.getVboxmanage() + ' -v 2>&1', function (error, stdout) {
+ if (!error) {
+ const vbox = stdout.toString().split('\n')[0] || '';
+ const parts = vbox.split('r');
+ appsObj.versions.virtualbox = parts[0];
}
- if (request.body) {
- throw new Error("multipartBody and regular body cannot be set at the same time");
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'bash')) {
+ exec('bash --version', function (error, stdout) {
+ if (!error) {
+ const line = stdout.toString().split('\n')[0];
+ const parts = line.split(' version ');
+ if (parts.length > 1) {
+ appsObj.versions.bash = parts[1].split(' ')[0].split('(')[0];
+ }
}
- let boundary = request.multipartBody.boundary;
- const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed";
- const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
- if (!parsedHeader) {
- throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'zsh')) {
+ exec('zsh --version', function (error, stdout) {
+ if (!error) {
+ const line = stdout.toString().split('\n')[0];
+ const parts = line.split('zsh ');
+ if (parts.length > 1) {
+ appsObj.versions.zsh = parts[1].split(' ')[0];
+ }
}
- const [, contentType, parsedBoundary] = parsedHeader;
- if (parsedBoundary && boundary && parsedBoundary !== boundary) {
- throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'fish')) {
+ exec('fish --version', function (error, stdout) {
+ if (!error) {
+ const line = stdout.toString().split('\n')[0];
+ const parts = line.split(' version ');
+ if (parts.length > 1) {
+ appsObj.versions.fish = parts[1].split(' ')[0];
+ }
}
- boundary !== null && boundary !== void 0 ? boundary : (boundary = parsedBoundary);
- if (boundary) {
- assertValidBoundary(boundary);
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'bun')) {
+ exec('bun -v', function (error, stdout) {
+ if (!error) {
+ const line = stdout.toString().split('\n')[0].trim();
+ appsObj.versions.bun = line;
}
- else {
- boundary = generateBoundary();
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'deno')) {
+ exec('deno -v', function (error, stdout) {
+ if (!error) {
+ const line = stdout.toString().split('\n')[0].trim();
+ const parts = line.split(' ');
+ if (parts.length > 1) {
+ appsObj.versions.deno = parts[1];
+ }
}
- request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
- await buildRequestBody(request, request.multipartBody.parts, boundary);
- request.multipartBody = undefined;
- return next(request);
- },
- };
-}
-//# sourceMappingURL=multipartPolicy.js.map
-
-/***/ }),
-
-/***/ 7303:
-/***/ ((__unused_webpack_module, exports) => {
-
-
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ndJsonPolicyName = void 0;
-exports.ndJsonPolicy = ndJsonPolicy;
-/**
- * The programmatic identifier of the ndJsonPolicy.
- */
-exports.ndJsonPolicyName = "ndJsonPolicy";
-/**
- * ndJsonPolicy is a policy used to control keep alive settings for every request.
- */
-function ndJsonPolicy() {
- return {
- name: exports.ndJsonPolicyName,
- async sendRequest(request, next) {
- // There currently isn't a good way to bypass the serializer
- if (typeof request.body === "string" && request.body.startsWith("[")) {
- const body = JSON.parse(request.body);
- if (Array.isArray(body)) {
- request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
- }
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'node')) {
+ exec('node -v', function (error, stdout) {
+ if (!error) {
+ let line = stdout.toString().split('\n')[0].trim();
+ if (line.startsWith('v')) { line = line.slice(1); }
+ appsObj.versions.node = line;
}
- return next(request);
- },
- };
+ functionProcessed();
+ });
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'powershell')) {
+ if (_windows) {
+ util.powerShell('$PSVersionTable').then(stdout => {
+ const lines = stdout.toString().split('\n').map(line => line.replace(/ +/g, ' ').replace(/ +/g, ':'));
+ appsObj.versions.powershell = util.getValue(lines, 'psversion');
+ functionProcessed();
+ });
+ } else {
+ functionProcessed();
+ }
+ }
+ if ({}.hasOwnProperty.call(appsObj.versions, 'dotnet')) {
+ if (_windows) {
+ util.powerShell('gci "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP" -recurse | gp -name Version,Release -EA 0 | where { $_.PSChildName -match "^(?!S)\\p{L}"} | select PSChildName, Version, Release').then(stdout => {
+ const lines = stdout.toString().split('\r\n');
+ let dotnet = '';
+ lines.forEach(line => {
+ line = line.replace(/ +/g, ' ');
+ const parts = line.split(' ');
+ dotnet = dotnet || (parts[0].toLowerCase().startsWith('client') && parts.length > 2 ? parts[1].trim() : (parts[0].toLowerCase().startsWith('full') && parts.length > 2 ? parts[1].trim() : ''));
+ });
+ appsObj.versions.dotnet = dotnet.trim();
+ functionProcessed();
+ });
+ } else {
+ functionProcessed();
+ }
+ }
+ } catch (e) {
+ if (callback) { callback(appsObj.versions); }
+ resolve(appsObj.versions);
+ }
+ });
+ });
}
-//# sourceMappingURL=ndJsonPolicy.js.map
-/***/ }),
+exports.versions = versions;
-/***/ 73723:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function shell(callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (_windows) {
+ resolve('cmd');
+ } else {
+ let result = '';
+ exec('echo $SHELL', function (error, stdout) {
+ if (!error) {
+ result = stdout.toString().split('\n')[0];
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ });
+ });
+}
+exports.shell = shell;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.globalNoProxyList = exports.proxyPolicyName = void 0;
-exports.loadNoProxy = loadNoProxy;
-exports.getDefaultProxySettings = getDefaultProxySettings;
-exports.proxyPolicy = proxyPolicy;
-const https_proxy_agent_1 = __nccwpck_require__(54129);
-const http_proxy_agent_1 = __nccwpck_require__(31286);
-const log_js_1 = __nccwpck_require__(58564);
-const HTTPS_PROXY = "HTTPS_PROXY";
-const HTTP_PROXY = "HTTP_PROXY";
-const ALL_PROXY = "ALL_PROXY";
-const NO_PROXY = "NO_PROXY";
-/**
- * The programmatic identifier of the proxyPolicy.
- */
-exports.proxyPolicyName = "proxyPolicy";
-/**
- * Stores the patterns specified in NO_PROXY environment variable.
- * @internal
- */
-exports.globalNoProxyList = [];
-let noProxyListLoaded = false;
-/** A cache of whether a host should bypass the proxy. */
-const globalBypassedMap = new Map();
-function getEnvironmentValue(name) {
- if (process.env[name]) {
- return process.env[name];
- }
- else if (process.env[name.toLowerCase()]) {
- return process.env[name.toLowerCase()];
- }
- return undefined;
-}
-function loadEnvironmentProxyValue() {
- if (!process) {
- return undefined;
- }
- const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
- const allProxy = getEnvironmentValue(ALL_PROXY);
- const httpProxy = getEnvironmentValue(HTTP_PROXY);
- return httpsProxy || allProxy || httpProxy;
-}
-/**
- * Check whether the host of a given `uri` matches any pattern in the no proxy list.
- * If there's a match, any request sent to the same host shouldn't have the proxy settings set.
- * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210
- */
-function isBypassed(uri, noProxyList, bypassedMap) {
- if (noProxyList.length === 0) {
- return false;
- }
- const host = new URL(uri).hostname;
- if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) {
- return bypassedMap.get(host);
- }
- let isBypassedFlag = false;
- for (const pattern of noProxyList) {
- if (pattern[0] === ".") {
- // This should match either domain it self or any subdomain or host
- // .foo.com will match foo.com it self or *.foo.com
- if (host.endsWith(pattern)) {
- isBypassedFlag = true;
- }
- else {
- if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
- isBypassedFlag = true;
- }
- }
- }
- else {
- if (host === pattern) {
- isBypassedFlag = true;
+function getUniqueMacAdresses() {
+ let macs = [];
+ try {
+ const ifaces = os.networkInterfaces();
+ for (let dev in ifaces) {
+ if ({}.hasOwnProperty.call(ifaces, dev)) {
+ ifaces[dev].forEach(function (details) {
+ if (details && details.mac && details.mac !== '00:00:00:00:00:00') {
+ const mac = details.mac.toLowerCase();
+ if (macs.indexOf(mac) === -1) {
+ macs.push(mac);
}
- }
- }
- bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag);
- return isBypassedFlag;
-}
-function loadNoProxy() {
- const noProxy = getEnvironmentValue(NO_PROXY);
- noProxyListLoaded = true;
- if (noProxy) {
- return noProxy
- .split(",")
- .map((item) => item.trim())
- .filter((item) => item.length);
- }
- return [];
-}
-/**
- * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
- * If no argument is given, it attempts to parse a proxy URL from the environment
- * variables `HTTPS_PROXY` or `HTTP_PROXY`.
- * @param proxyUrl - The url of the proxy to use. May contain authentication information.
- * @deprecated - Internally this method is no longer necessary when setting proxy information.
- */
-function getDefaultProxySettings(proxyUrl) {
- if (!proxyUrl) {
- proxyUrl = loadEnvironmentProxyValue();
- if (!proxyUrl) {
- return undefined;
- }
- }
- const parsedUrl = new URL(proxyUrl);
- const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
- return {
- host: schema + parsedUrl.hostname,
- port: Number.parseInt(parsedUrl.port || "80"),
- username: parsedUrl.username,
- password: parsedUrl.password,
- };
-}
-/**
- * This method attempts to parse a proxy URL from the environment
- * variables `HTTPS_PROXY` or `HTTP_PROXY`.
- */
-function getDefaultProxySettingsInternal() {
- const envProxy = loadEnvironmentProxyValue();
- return envProxy ? new URL(envProxy) : undefined;
-}
-function getUrlFromProxySettings(settings) {
- let parsedProxyUrl;
- try {
- parsedProxyUrl = new URL(settings.host);
- }
- catch (_a) {
- throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`);
- }
- parsedProxyUrl.port = String(settings.port);
- if (settings.username) {
- parsedProxyUrl.username = settings.username;
- }
- if (settings.password) {
- parsedProxyUrl.password = settings.password;
- }
- return parsedProxyUrl;
-}
-function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) {
- // Custom Agent should take precedence so if one is present
- // we should skip to avoid overwriting it.
- if (request.agent) {
- return;
- }
- const url = new URL(request.url);
- const isInsecure = url.protocol !== "https:";
- if (request.tlsSettings) {
- log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
- }
- const headers = request.headers.toJSON();
- if (isInsecure) {
- if (!cachedAgents.httpProxyAgent) {
- cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers });
- }
- request.agent = cachedAgents.httpProxyAgent;
- }
- else {
- if (!cachedAgents.httpsProxyAgent) {
- cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers });
- }
- request.agent = cachedAgents.httpsProxyAgent;
+ }
+ });
+ }
}
+ macs = macs.sort(function (a, b) {
+ if (a < b) { return -1; }
+ if (a > b) { return 1; }
+ return 0;
+ });
+ } catch (e) {
+ macs.push('00:00:00:00:00:00');
+ }
+ return macs;
}
-/**
- * A policy that allows one to apply proxy settings to all requests.
- * If not passed static settings, they will be retrieved from the HTTPS_PROXY
- * or HTTP_PROXY environment variables.
- * @param proxySettings - ProxySettings to use on each request.
- * @param options - additional settings, for example, custom NO_PROXY patterns
- */
-function proxyPolicy(proxySettings, options) {
- if (!noProxyListLoaded) {
- exports.globalNoProxyList.push(...loadNoProxy());
- }
- const defaultProxy = proxySettings
- ? getUrlFromProxySettings(proxySettings)
- : getDefaultProxySettingsInternal();
- const cachedAgents = {};
- return {
- name: exports.proxyPolicyName,
- async sendRequest(request, next) {
- var _a;
- if (!request.proxySettings &&
- defaultProxy &&
- !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? undefined : globalBypassedMap)) {
- setProxyAgentOnRequest(request, cachedAgents, defaultProxy);
+
+function uuid(callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+
+ let result = {
+ os: '',
+ hardware: '',
+ macs: getUniqueMacAdresses()
+ };
+ let parts;
+
+ if (_darwin) {
+ exec('system_profiler SPHardwareDataType -json', function (error, stdout) {
+ if (!error) {
+ try {
+ const jsonObj = JSON.parse(stdout.toString());
+ if (jsonObj.SPHardwareDataType && jsonObj.SPHardwareDataType.length > 0) {
+ const spHardware = jsonObj.SPHardwareDataType[0];
+ result.os = spHardware.platform_UUID.toLowerCase();
+ result.hardware = spHardware.serial_number;
+ }
+ } catch (e) {
+ util.noop();
}
- else if (request.proxySettings) {
- setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings));
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_linux) {
+ const cmd = `echo -n "os: "; cat /var/lib/dbus/machine-id 2> /dev/null ||
+cat /etc/machine-id 2> /dev/null; echo;
+echo -n "hardware: "; cat /sys/class/dmi/id/product_uuid 2> /dev/null; echo;`;
+ exec(cmd, function (error, stdout) {
+ const lines = stdout.toString().split('\n');
+ result.os = util.getValue(lines, 'os').toLowerCase();
+ result.hardware = util.getValue(lines, 'hardware').toLowerCase();
+ if (!result.hardware) {
+ const lines = fs.readFileSync('/proc/cpuinfo', { encoding: 'utf8' }).toString().split('\n');
+ const serial = util.getValue(lines, 'serial');
+ result.hardware = serial || '';
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ exec('sysctl -i kern.hostid kern.hostuuid', function (error, stdout) {
+ const lines = stdout.toString().split('\n');
+ result.os = util.getValue(lines, 'kern.hostid', ':').toLowerCase();
+ result.hardware = util.getValue(lines, 'kern.hostuuid', ':').toLowerCase();
+ if (result.os.indexOf('unknown') >= 0) { result.os = ''; }
+ if (result.hardware.indexOf('unknown') >= 0) { result.hardware = ''; }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_windows) {
+ let sysdir = '%windir%\\System32';
+ if (process.arch === 'ia32' && Object.prototype.hasOwnProperty.call(process.env, 'PROCESSOR_ARCHITEW6432')) {
+ sysdir = '%windir%\\sysnative\\cmd.exe /c %windir%\\System32';
+ }
+ util.powerShell('Get-CimInstance Win32_ComputerSystemProduct | select UUID | fl').then((stdout) => {
+ let lines = stdout.split('\r\n');
+ result.hardware = util.getValue(lines, 'uuid', ':').toLowerCase();
+ exec(`${sysdir}\\reg query "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid`, util.execOptsWin, function (error, stdout) {
+ parts = stdout.toString().split('\n\r')[0].split('REG_SZ');
+ result.os = parts.length > 1 ? parts[1].replace(/\r+|\n+|\s+/ig, '').toLowerCase() : '';
+ if (callback) {
+ callback(result);
}
- return next(request);
- },
- };
+ resolve(result);
+ });
+ });
+ }
+ });
+ });
}
-//# sourceMappingURL=proxyPolicy.js.map
+
+exports.uuid = uuid;
+
/***/ }),
-/***/ 86947:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 93338:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.redirectPolicyName = void 0;
-exports.redirectPolicy = redirectPolicy;
-/**
- * The programmatic identifier of the redirectPolicy.
- */
-exports.redirectPolicyName = "redirectPolicy";
-/**
- * Methods that are allowed to follow redirects 301 and 302
- */
-const allowedRedirect = ["GET", "HEAD"];
-/**
- * A policy to follow Location headers from the server in order
- * to support server-side redirection.
- * In the browser, this policy is not used.
- * @param options - Options to control policy behavior.
- */
-function redirectPolicy(options = {}) {
- const { maxRetries = 20 } = options;
- return {
- name: exports.redirectPolicyName,
- async sendRequest(request, next) {
- const response = await next(request);
- return handleRedirect(next, response, maxRetries);
- },
- };
-}
-async function handleRedirect(next, response, maxRetries, currentRetries = 0) {
- const { request, status, headers } = response;
- const locationHeader = headers.get("location");
- if (locationHeader &&
- (status === 300 ||
- (status === 301 && allowedRedirect.includes(request.method)) ||
- (status === 302 && allowedRedirect.includes(request.method)) ||
- (status === 303 && request.method === "POST") ||
- status === 307) &&
- currentRetries < maxRetries) {
- const url = new URL(locationHeader, request.url);
- request.url = url.toString();
- // POST request with Status code 303 should be converted into a
- // redirected GET request if the redirect url is present in the location header
- if (status === 303) {
- request.method = "GET";
- request.headers.delete("Content-Length");
- delete request.body;
- }
- request.headers.delete("Authorization");
- const res = await next(request);
- return handleRedirect(next, res, maxRetries, currentRetries + 1);
+// @ts-check
+// ==================================================================================
+// printers.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 15. printers
+// ----------------------------------------------------------------------------------
+
+const exec = (__nccwpck_require__(35317).exec);
+const util = __nccwpck_require__(77496);
+
+let _platform = process.platform;
+
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+
+const winPrinterStatus = {
+ 1: 'Other',
+ 2: 'Unknown',
+ 3: 'Idle',
+ 4: 'Printing',
+ 5: 'Warmup',
+ 6: 'Stopped Printing',
+ 7: 'Offline',
+};
+
+function parseLinuxCupsHeader(lines) {
+ const result = {};
+ if (lines && lines.length) {
+ if (lines[0].indexOf(' CUPS v') > 0) {
+ const parts = lines[0].split(' CUPS v');
+ result.cupsVersion = parts[1];
}
- return response;
+ }
+ return result;
}
-//# sourceMappingURL=redirectPolicy.js.map
-/***/ }),
+function parseLinuxCupsPrinter(lines) {
+ const result = {};
+ const printerId = util.getValue(lines, 'PrinterId', ' ');
+ result.id = printerId ? parseInt(printerId, 10) : null;
+ result.name = util.getValue(lines, 'Info', ' ');
+ result.model = lines.length > 0 && lines[0] ? lines[0].split(' ')[0] : '';
+ result.uri = util.getValue(lines, 'DeviceURI', ' ');
+ result.uuid = util.getValue(lines, 'UUID', ' ');
+ result.status = util.getValue(lines, 'State', ' ');
+ result.local = util.getValue(lines, 'Location', ' ').toLowerCase().startsWith('local');
+ result.default = null;
+ result.shared = util.getValue(lines, 'Shared', ' ').toLowerCase().startsWith('yes');
-/***/ 85001:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return result;
+}
+function parseLinuxLpstatPrinter(lines, id) {
+ const result = {};
+ result.id = id;
+ result.name = util.getValue(lines, 'Description', ':', true);
+ result.model = lines.length > 0 && lines[0] ? lines[0].split(' ')[0] : '';
+ result.uri = null;
+ result.uuid = null;
+ result.status = lines.length > 0 && lines[0] ? (lines[0].indexOf(' idle') > 0 ? 'idle' : (lines[0].indexOf(' printing') > 0 ? 'printing' : 'unknown')) : null;
+ result.local = util.getValue(lines, 'Location', ':', true).toLowerCase().startsWith('local');
+ result.default = null;
+ result.shared = util.getValue(lines, 'Shared', ' ').toLowerCase().startsWith('yes');
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.retryPolicy = retryPolicy;
-const helpers_js_1 = __nccwpck_require__(94982);
-const logger_1 = __nccwpck_require__(50143);
-const abort_controller_1 = __nccwpck_require__(92242);
-const constants_js_1 = __nccwpck_require__(91791);
-const retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy");
-/**
- * The programmatic identifier of the retryPolicy.
- */
-const retryPolicyName = "retryPolicy";
-/**
- * retryPolicy is a generic policy to enable retrying requests when certain conditions are met
- */
-function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) {
- const logger = options.logger || retryPolicyLogger;
- return {
- name: retryPolicyName,
- async sendRequest(request, next) {
- var _a, _b;
- let response;
- let responseError;
- let retryCount = -1;
- // eslint-disable-next-line no-constant-condition
- retryRequest: while (true) {
- retryCount += 1;
- response = undefined;
- responseError = undefined;
- try {
- logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);
- response = await next(request);
- logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);
- }
- catch (e) {
- logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);
- // RestErrors are valid targets for the retry strategies.
- // If none of the retry strategies can work with them, they will be thrown later in this policy.
- // If the received error is not a RestError, it is immediately thrown.
- responseError = e;
- if (!e || responseError.name !== "RestError") {
- throw e;
- }
- response = responseError.response;
- }
- if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) {
- logger.error(`Retry ${retryCount}: Request aborted.`);
- const abortError = new abort_controller_1.AbortError();
- throw abortError;
- }
- if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) {
- logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
- if (responseError) {
- throw responseError;
- }
- else if (response) {
- return response;
- }
- else {
- throw new Error("Maximum retries reached with no response or error to throw");
- }
- }
- logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
- strategiesLoop: for (const strategy of strategies) {
- const strategyLogger = strategy.logger || retryPolicyLogger;
- strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
- const modifiers = strategy.retry({
- retryCount,
- response,
- responseError,
- });
- if (modifiers.skipStrategy) {
- strategyLogger.info(`Retry ${retryCount}: Skipped.`);
- continue strategiesLoop;
- }
- const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;
- if (errorToThrow) {
- strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow);
- throw errorToThrow;
- }
- if (retryAfterInMs || retryAfterInMs === 0) {
- strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`);
- await (0, helpers_js_1.delay)(retryAfterInMs, undefined, { abortSignal: request.abortSignal });
- continue retryRequest;
- }
- if (redirectTo) {
- strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
- request.url = redirectTo;
- continue retryRequest;
- }
- }
- if (responseError) {
- logger.info(`None of the retry strategies could work with the received error. Throwing it.`);
- throw responseError;
+ return result;
+}
+
+function parseDarwinPrinters(printerObject, id) {
+ const result = {};
+ const uriParts = printerObject.uri.split('/');
+ result.id = id;
+ result.name = printerObject._name;
+ result.model = uriParts.length ? uriParts[uriParts.length - 1] : '';
+ result.uri = printerObject.uri;
+ result.uuid = null;
+ result.status = printerObject.status;
+ result.local = printerObject.printserver === 'local';
+ result.default = printerObject.default === 'yes';
+ result.shared = printerObject.shared === 'yes';
+
+ return result;
+}
+
+function parseWindowsPrinters(lines, id) {
+ const result = {};
+ const status = parseInt(util.getValue(lines, 'PrinterStatus', ':'), 10);
+
+ result.id = id;
+ result.name = util.getValue(lines, 'name', ':');
+ result.model = util.getValue(lines, 'DriverName', ':');
+ result.uri = null;
+ result.uuid = null;
+ result.status = winPrinterStatus[status] ? winPrinterStatus[status] : null;
+ result.local = util.getValue(lines, 'Local', ':').toUpperCase() === 'TRUE';
+ result.default = util.getValue(lines, 'Default', ':').toUpperCase() === 'TRUE';
+ result.shared = util.getValue(lines, 'Shared', ':').toUpperCase() === 'TRUE';
+
+ return result;
+}
+
+function printer(callback) {
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = [];
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ let cmd = 'cat /etc/cups/printers.conf 2>/dev/null';
+ exec(cmd, function (error, stdout) {
+ // printers.conf
+ if (!error) {
+ const parts = stdout.toString().split(' {
+ if (!error) {
+ const parts = stdout.toString().split(/\n\s*\n/);
+ for (let i = 0; i < parts.length; i++) {
+ const printer = parseWindowsPrinters(parts[i].split('\n'), i);
+ if (printer.name || printer.model) {
+ result.push(printer);
+ }
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ resolve(null);
+ }
+ });
+ });
}
-//# sourceMappingURL=retryPolicy.js.map
+
+exports.printer = printer;
+
/***/ }),
-/***/ 63866:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 82999:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+
+// @ts-check
+// ==================================================================================
+// processes.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 10. Processes
+// ----------------------------------------------------------------------------------
+
+const os = __nccwpck_require__(70857);
+const fs = __nccwpck_require__(79896);
+const path = __nccwpck_require__(16928);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+
+const util = __nccwpck_require__(77496);
+
+let _platform = process.platform;
+
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+
+const _processes_cpu = {
+ all: 0,
+ all_utime: 0,
+ all_stime: 0,
+ list: {},
+ ms: 0,
+ result: {}
+};
+const _services_cpu = {
+ all: 0,
+ all_utime: 0,
+ all_stime: 0,
+ list: {},
+ ms: 0,
+ result: {}
+};
+const _process_cpu = {
+ all: 0,
+ all_utime: 0,
+ all_stime: 0,
+ list: {},
+ ms: 0,
+ result: {}
+};
+const _winStatusValues = {
+ '0': 'unknown',
+ '1': 'other',
+ '2': 'ready',
+ '3': 'running',
+ '4': 'blocked',
+ '5': 'suspended blocked',
+ '6': 'suspended ready',
+ '7': 'terminated',
+ '8': 'stopped',
+ '9': 'growing',
+};
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.setClientRequestIdPolicyName = void 0;
-exports.setClientRequestIdPolicy = setClientRequestIdPolicy;
-/**
- * The programmatic identifier of the setClientRequestIdPolicy.
- */
-exports.setClientRequestIdPolicyName = "setClientRequestIdPolicy";
-/**
- * Each PipelineRequest gets a unique id upon creation.
- * This policy passes that unique id along via an HTTP header to enable better
- * telemetry and tracing.
- * @param requestIdHeaderName - The name of the header to pass the request ID to.
- */
-function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
- return {
- name: exports.setClientRequestIdPolicyName,
- async sendRequest(request, next) {
- if (!request.headers.has(requestIdHeaderName)) {
- request.headers.set(requestIdHeaderName, request.requestId);
- }
- return next(request);
- },
- };
+function parseTimeUnix(time) {
+ let result = time;
+ let parts = time.replace(/ +/g, ' ').split(' ');
+ if (parts.length === 5) {
+ result = parts[4] + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(parts[1].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + parts[2]).slice(-2) + ' ' + parts[3];
+ }
+ return result;
}
-//# sourceMappingURL=setClientRequestIdPolicy.js.map
-/***/ }),
+function parseElapsedTime(etime) {
+ let current = new Date();
+ current = new Date(current.getTime() - current.getTimezoneOffset() * 60000);
-/***/ 14298:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ const elapsed = etime.split('-');
+ const timeIndex = elapsed.length - 1;
+ const days = timeIndex > 0 ? parseInt(elapsed[timeIndex - 1]) : 0;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.systemErrorRetryPolicyName = void 0;
-exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
-const exponentialRetryStrategy_js_1 = __nccwpck_require__(34750);
-const retryPolicy_js_1 = __nccwpck_require__(85001);
-const constants_js_1 = __nccwpck_require__(91791);
-/**
- * Name of the {@link systemErrorRetryPolicy}
- */
-exports.systemErrorRetryPolicyName = "systemErrorRetryPolicy";
-/**
- * A retry policy that specifically seeks to handle errors in the
- * underlying transport layer (e.g. DNS lookup failures) rather than
- * retryable error codes from the server itself.
- * @param options - Options that customize the policy.
- */
-function systemErrorRetryPolicy(options = {}) {
- var _a;
- return {
- name: exports.systemErrorRetryPolicyName,
- sendRequest: (0, retryPolicy_js_1.retryPolicy)([
- (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })),
- ], {
- maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
- }).sendRequest,
- };
+ const timeStr = elapsed[timeIndex].split(':');
+ const hours = timeStr.length === 3 ? parseInt(timeStr[0] || 0) : 0;
+ const mins = parseInt(timeStr[timeStr.length === 3 ? 1 : 0] || 0);
+ const secs = parseInt(timeStr[timeStr.length === 3 ? 2 : 1] || 0);
+ const ms = (((((days * 24 + hours) * 60) + mins) * 60 + secs) * 1000);
+
+ let res = new Date(current.getTime());
+ let result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19);
+ try {
+ res = new Date(current.getTime() - ms);
+ result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19);
+ } catch (e) {
+ util.noop();
+ }
+ return result;
}
-//# sourceMappingURL=systemErrorRetryPolicy.js.map
-/***/ }),
+// --------------------------
+// PS - services
+// pass a comma separated string with services to check (mysql, apache, postgresql, ...)
+// this function gives an array back, if the services are running.
-/***/ 96352:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function services(srv, callback) {
+ // fallback - if only callback is given
+ if (util.isFunction(srv) && !callback) {
+ callback = srv;
+ srv = '';
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.throttlingRetryPolicyName = void 0;
-exports.throttlingRetryPolicy = throttlingRetryPolicy;
-const throttlingRetryStrategy_js_1 = __nccwpck_require__(40288);
-const retryPolicy_js_1 = __nccwpck_require__(85001);
-const constants_js_1 = __nccwpck_require__(91791);
-/**
- * Name of the {@link throttlingRetryPolicy}
- */
-exports.throttlingRetryPolicyName = "throttlingRetryPolicy";
-/**
- * A policy that retries when the server sends a 429 response with a Retry-After header.
- *
- * To learn more, please refer to
- * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
- * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
- * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
- *
- * @param options - Options that configure retry logic.
- */
-function throttlingRetryPolicy(options = {}) {
- var _a;
- return {
- name: exports.throttlingRetryPolicyName,
- sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], {
- maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
- }).sendRequest,
- };
-}
-//# sourceMappingURL=throttlingRetryPolicy.js.map
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (typeof srv !== 'string') {
+ if (callback) { callback([]); }
+ return resolve([]);
+ }
-/***/ }),
+ if (srv) {
+ let srvString = '';
+ try {
+ srvString.__proto__.toLowerCase = util.stringToLower;
+ srvString.__proto__.replace = util.stringReplace;
+ srvString.__proto__.toString = util.stringToString;
+ srvString.__proto__.substr = util.stringSubstr;
+ srvString.__proto__.substring = util.stringSubstring;
+ srvString.__proto__.trim = util.stringTrim;
+ srvString.__proto__.startsWith = util.stringStartWith;
+ } catch (e) {
+ Object.setPrototypeOf(srvString, util.stringObj);
+ }
-/***/ 39370:
-/***/ ((__unused_webpack_module, exports) => {
+ const s = util.sanitizeShellString(srv);
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ srvString = srvString + s[i];
+ }
+ }
+ srvString = srvString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|');
+ if (srvString === '') {
+ srvString = '*';
+ }
+ if (util.isPrototypePolluted() && srvString !== '*') {
+ srvString = '------';
+ }
+ let srvs = srvString.split('|');
+ let result = [];
+ let dataSrv = [];
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.tlsPolicyName = void 0;
-exports.tlsPolicy = tlsPolicy;
-/**
- * Name of the TLS Policy
- */
-exports.tlsPolicyName = "tlsPolicy";
-/**
- * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
- */
-function tlsPolicy(tlsSettings) {
- return {
- name: exports.tlsPolicyName,
- sendRequest: async (req, next) => {
- // Users may define a request tlsSettings, honor those over the client level one
- if (!req.tlsSettings) {
- req.tlsSettings = tlsSettings;
+ if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
+ if ((_linux || _freebsd || _openbsd || _netbsd) && srvString === '*') {
+ try {
+ const tmpsrv = execSync('systemctl --all --type=service --no-legend 2> /dev/null', util.execOptsLinux).toString().split('\n');
+ srvs = [];
+ for (const s of tmpsrv) {
+ const name = s.split('.service')[0];
+ if (name && s.indexOf(' not-found ') === -1) {
+ srvs.push(name.trim());
+ }
+ }
+ srvString = srvs.join('|');
+ } catch (d) {
+ try {
+ srvString = '';
+ const tmpsrv = execSync('service --status-all 2> /dev/null', util.execOptsLinux).toString().split('\n');
+ for (const s of tmpsrv) {
+ const parts = s.split(']');
+ if (parts.length === 2) {
+ srvString += (srvString !== '' ? '|' : '') + parts[1].trim();
+ }
+ }
+ srvs = srvString.split('|');
+ } catch (e) {
+ try {
+ const srvStr = execSync('ls /etc/init.d/ -m 2> /dev/null', util.execOptsLinux).toString().split('\n').join('');
+ srvString = '';
+ if (srvStr) {
+ const tmpsrv = srvStr.split(',');
+ for (const s of tmpsrv) {
+ const name = s.trim();
+ if (name) {
+ srvString += (srvString !== '' ? '|' : '') + name;
+ }
+ }
+ srvs = srvString.split('|');
+ }
+ } catch (f) {
+ srvString = '';
+ srvs = [];
+ }
+ }
}
- return next(req);
- },
- };
-}
-//# sourceMappingURL=tlsPolicy.js.map
+ }
+ if ((_darwin) && srvString === '*') { // service enumeration not yet suported on mac OS
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ let args = (_darwin) ? ['-caxo', 'pcpu,pmem,pid,command'] : ['-axo', 'pcpu,pmem,pid,command'];
+ if (srvString !== '' && srvs.length > 0) {
+ util.execSafe('ps', args).then((stdout) => {
+ if (stdout) {
+ let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n');
+ srvs.forEach(function (srv) {
+ let ps;
+ if (_darwin) {
+ ps = lines.filter(function (e) {
+ return (e.toLowerCase().indexOf(srv) !== -1);
+ });
-/***/ }),
+ } else {
+ ps = lines.filter(function (e) {
+ return (e.toLowerCase().indexOf(' ' + srv.toLowerCase() + ':') !== -1) || (e.toLowerCase().indexOf('/' + srv.toLowerCase()) !== -1);
+ });
+ }
+ const pids = [];
+ for (const p of ps) {
+ const pid = p.trim().split(' ')[2];
+ if (pid) {
+ pids.push(parseInt(pid, 10));
+ }
+ }
+ result.push({
+ name: srv,
+ running: ps.length > 0,
+ startmode: '',
+ pids: pids,
+ cpu: parseFloat((ps.reduce(function (pv, cv) {
+ return pv + parseFloat(cv.trim().split(' ')[0]);
+ }, 0)).toFixed(2)),
+ mem: parseFloat((ps.reduce(function (pv, cv) {
+ return pv + parseFloat(cv.trim().split(' ')[1]);
+ }, 0)).toFixed(2))
+ });
+ });
+ if (_linux) {
+ // calc process_cpu - ps is not accurate in linux!
+ let cmd = 'cat /proc/stat | grep "cpu "';
+ for (let i in result) {
+ for (let j in result[i].pids) {
+ cmd += (';cat /proc/' + result[i].pids[j] + '/stat');
+ }
+ }
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+ let curr_processes = stdout.toString().split('\n');
-/***/ 14113:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // first line (all - /proc/stat)
+ let all = parseProcStat(curr_processes.shift());
+ // process
+ let list_new = {};
+ let resultProcess = {};
+ curr_processes.forEach((element) => {
+ resultProcess = calcProcStatLinux(element, all, _services_cpu);
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.tracingPolicyName = void 0;
-exports.tracingPolicy = tracingPolicy;
-const core_tracing_1 = __nccwpck_require__(7651);
-const constants_js_1 = __nccwpck_require__(91791);
-const userAgent_js_1 = __nccwpck_require__(87747);
-const log_js_1 = __nccwpck_require__(58564);
-const core_util_1 = __nccwpck_require__(30991);
-const restError_js_1 = __nccwpck_require__(97558);
-const sanitizer_js_1 = __nccwpck_require__(44720);
-/**
- * The programmatic identifier of the tracingPolicy.
- */
-exports.tracingPolicyName = "tracingPolicy";
-/**
- * A simple policy to create OpenTelemetry Spans for each request made by the pipeline
- * that has SpanOptions with a parent.
- * Requests made without a parent Span will not be recorded.
- * @param options - Options to configure the telemetry logged by the tracing policy.
- */
-function tracingPolicy(options = {}) {
- const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
- const sanitizer = new sanitizer_js_1.Sanitizer({
- additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
- });
- const tracingClient = tryCreateTracingClient();
- return {
- name: exports.tracingPolicyName,
- async sendRequest(request, next) {
- var _a;
- if (!tracingClient) {
- return next(request);
- }
- const userAgent = await userAgentPromise;
- const spanAttributes = {
- "http.url": sanitizer.sanitizeUrl(request.url),
- "http.method": request.method,
- "http.user_agent": userAgent,
- requestId: request.requestId,
- };
- if (userAgent) {
- spanAttributes["http.user_agent"] = userAgent;
- }
- const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {};
- if (!span || !tracingContext) {
- return next(request);
- }
- try {
- const response = await tracingClient.withContext(tracingContext, next, request);
- tryProcessResponse(span, response);
- return response;
- }
- catch (err) {
- tryProcessError(span, err);
- throw err;
- }
- },
- };
-}
-function tryCreateTracingClient() {
- try {
- return (0, core_tracing_1.createTracingClient)({
- namespace: "",
- packageName: "@azure/core-rest-pipeline",
- packageVersion: constants_js_1.SDK_VERSION,
- });
- }
- catch (e) {
- log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`);
- return undefined;
- }
-}
-function tryCreateSpan(tracingClient, request, spanAttributes) {
- try {
- // As per spec, we do not need to differentiate between HTTP and HTTPS in span name.
- const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
- spanKind: "client",
- spanAttributes,
- });
- // If the span is not recording, don't do any more work.
- if (!span.isRecording()) {
- span.end();
- return undefined;
- }
- // set headers
- const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
- for (const [key, value] of Object.entries(headers)) {
- request.headers.set(key, value);
- }
- return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
- }
- catch (e) {
- log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
- return undefined;
- }
-}
-function tryProcessError(span, error) {
- try {
- span.setStatus({
- status: "error",
- error: (0, core_util_1.isError)(error) ? error : undefined,
- });
- if ((0, restError_js_1.isRestError)(error) && error.statusCode) {
- span.setAttribute("http.status_code", error.statusCode);
+ if (resultProcess.pid) {
+ let listPos = -1;
+ for (let i in result) {
+ for (let j in result[i].pids) {
+ if (parseInt(result[i].pids[j]) === parseInt(resultProcess.pid)) {
+ listPos = i;
+ }
+ }
+ }
+ if (listPos >= 0) {
+ result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus;
+ }
+
+ // save new values
+ list_new[resultProcess.pid] = {
+ cpuu: resultProcess.cpuu,
+ cpus: resultProcess.cpus,
+ utime: resultProcess.utime,
+ stime: resultProcess.stime,
+ cutime: resultProcess.cutime,
+ cstime: resultProcess.cstime
+ };
+ }
+ });
+
+ // store old values
+ _services_cpu.all = all;
+ _services_cpu.list = Object.assign({}, list_new);
+ _services_cpu.ms = Date.now() - _services_cpu.ms;
+ _services_cpu.result = Object.assign({}, result);
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } else {
+ args = ['-o', 'comm'];
+ util.execSafe('ps', args).then((stdout) => {
+ if (stdout) {
+ let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n');
+ srvs.forEach(function (srv) {
+ let ps = lines.filter(function (e) {
+ return e.indexOf(srv) !== -1;
+ });
+ result.push({
+ name: srv,
+ running: ps.length > 0,
+ startmode: '',
+ cpu: 0,
+ mem: 0
+ });
+ });
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ srvs.forEach(function (srv) {
+ result.push({
+ name: srv,
+ running: false,
+ startmode: '',
+ cpu: 0,
+ mem: 0
+ });
+ });
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ }
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
}
- span.end();
- }
- catch (e) {
- log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
- }
-}
-function tryProcessResponse(span, response) {
- try {
- span.setAttribute("http.status_code", response.status);
- const serviceRequestId = response.headers.get("x-ms-request-id");
- if (serviceRequestId) {
- span.setAttribute("serviceRequestId", serviceRequestId);
+ if (_windows) {
+ try {
+ let wincommand = 'Get-CimInstance Win32_Service';
+ if (srvs[0] !== '*') {
+ wincommand += ' -Filter "';
+ srvs.forEach((srv) => {
+ wincommand += `Name='${srv}' or `;
+ });
+ wincommand = `${wincommand.slice(0, -4)}"`;
+ }
+ wincommand += ' | select Name,Caption,Started,StartMode,ProcessId | fl';
+ util.powerShell(wincommand).then((stdout, error) => {
+ if (!error) {
+ let serviceSections = stdout.split(/\n\s*\n/);
+ serviceSections.forEach((element) => {
+ if (element.trim() !== '') {
+ let lines = element.trim().split('\r\n');
+ let srvName = util.getValue(lines, 'Name', ':', true).toLowerCase();
+ let srvCaption = util.getValue(lines, 'Caption', ':', true).toLowerCase();
+ let started = util.getValue(lines, 'Started', ':', true);
+ let startMode = util.getValue(lines, 'StartMode', ':', true);
+ let pid = util.getValue(lines, 'ProcessId', ':', true);
+ if (srvString === '*' || srvs.indexOf(srvName) >= 0 || srvs.indexOf(srvCaption) >= 0) {
+ result.push({
+ name: srvName,
+ running: (started.toLowerCase() === 'true'),
+ startmode: startMode,
+ pids: [pid],
+ cpu: 0,
+ mem: 0
+ });
+ dataSrv.push(srvName);
+ dataSrv.push(srvCaption);
+ }
+ }
+
+ });
+
+ if (srvString !== '*') {
+ let srvsMissing = srvs.filter(function (e) {
+ return dataSrv.indexOf(e) === -1;
+ });
+ srvsMissing.forEach(function (srvName) {
+ result.push({
+ name: srvName,
+ running: false,
+ startmode: '',
+ pids: [],
+ cpu: 0,
+ mem: 0
+ });
+ });
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ srvs.forEach(function (srvName) {
+ result.push({
+ name: srvName,
+ running: false,
+ startmode: '',
+ cpu: 0,
+ mem: 0
+ });
+ });
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
}
- span.setStatus({
- status: "success",
- });
- span.end();
- }
- catch (e) {
- log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
- }
+ } else {
+ if (callback) { callback([]); }
+ resolve([]);
+ }
+ });
+ });
}
-//# sourceMappingURL=tracingPolicy.js.map
-/***/ }),
+exports.services = services;
-/***/ 69795:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function parseProcStat(line) {
+ let parts = line.replace(/ +/g, ' ').split(' ');
+ let user = (parts.length >= 2 ? parseInt(parts[1]) : 0);
+ let nice = (parts.length >= 3 ? parseInt(parts[2]) : 0);
+ let system = (parts.length >= 4 ? parseInt(parts[3]) : 0);
+ let idle = (parts.length >= 5 ? parseInt(parts[4]) : 0);
+ let iowait = (parts.length >= 6 ? parseInt(parts[5]) : 0);
+ let irq = (parts.length >= 7 ? parseInt(parts[6]) : 0);
+ let softirq = (parts.length >= 8 ? parseInt(parts[7]) : 0);
+ let steal = (parts.length >= 9 ? parseInt(parts[8]) : 0);
+ let guest = (parts.length >= 10 ? parseInt(parts[9]) : 0);
+ let guest_nice = (parts.length >= 11 ? parseInt(parts[10]) : 0);
+ return user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice;
+}
+function calcProcStatLinux(line, all, _cpu_old) {
+ let statparts = line.replace(/ +/g, ' ').split(')');
+ if (statparts.length >= 2) {
+ let parts = statparts[1].split(' ');
+ if (parts.length >= 16) {
+ let pid = parseInt(statparts[0].split(' ')[0]);
+ let utime = parseInt(parts[12]);
+ let stime = parseInt(parts[13]);
+ let cutime = parseInt(parts[14]);
+ let cstime = parseInt(parts[15]);
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.userAgentPolicyName = void 0;
-exports.userAgentPolicy = userAgentPolicy;
-const userAgent_js_1 = __nccwpck_require__(87747);
-const UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)();
-/**
- * The programmatic identifier of the userAgentPolicy.
- */
-exports.userAgentPolicyName = "userAgentPolicy";
-/**
- * A policy that sets the User-Agent header (or equivalent) to reflect
- * the library version.
- * @param options - Options to customize the user agent value.
- */
-function userAgentPolicy(options = {}) {
- const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
+ // calc
+ let cpuu = 0;
+ let cpus = 0;
+ if (_cpu_old.all > 0 && _cpu_old.list[pid]) {
+ cpuu = (utime + cutime - _cpu_old.list[pid].utime - _cpu_old.list[pid].cutime) / (all - _cpu_old.all) * 100; // user
+ cpus = (stime + cstime - _cpu_old.list[pid].stime - _cpu_old.list[pid].cstime) / (all - _cpu_old.all) * 100; // system
+ } else {
+ cpuu = (utime + cutime) / (all) * 100; // user
+ cpus = (stime + cstime) / (all) * 100; // system
+ }
+ return {
+ pid: pid,
+ utime: utime,
+ stime: stime,
+ cutime: cutime,
+ cstime: cstime,
+ cpuu: cpuu,
+ cpus: cpus
+ };
+ } else {
+ return {
+ pid: 0,
+ utime: 0,
+ stime: 0,
+ cutime: 0,
+ cstime: 0,
+ cpuu: 0,
+ cpus: 0
+ };
+ }
+ } else {
return {
- name: exports.userAgentPolicyName,
- async sendRequest(request, next) {
- if (!request.headers.has(UserAgentHeaderName)) {
- request.headers.set(UserAgentHeaderName, await userAgentValue);
- }
- return next(request);
- },
+ pid: 0,
+ utime: 0,
+ stime: 0,
+ cutime: 0,
+ cstime: 0,
+ cpuu: 0,
+ cpus: 0
};
+ }
}
-//# sourceMappingURL=userAgentPolicy.js.map
-/***/ }),
+function calcProcStatWin(procStat, all, _cpu_old) {
+ // calc
+ let cpuu = 0;
+ let cpus = 0;
+ if (_cpu_old.all > 0 && _cpu_old.list[procStat.pid]) {
+ cpuu = (procStat.utime - _cpu_old.list[procStat.pid].utime) / (all - _cpu_old.all) * 100; // user
+ cpus = (procStat.stime - _cpu_old.list[procStat.pid].stime) / (all - _cpu_old.all) * 100; // system
+ } else {
+ cpuu = (procStat.utime) / (all) * 100; // user
+ cpus = (procStat.stime) / (all) * 100; // system
+ }
+ return {
+ pid: procStat.pid,
+ utime: procStat.utime,
+ stime: procStat.stime,
+ cpuu: cpuu > 0 ? cpuu : 0,
+ cpus: cpus > 0 ? cpus : 0
+ };
+}
-/***/ 97558:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.RestError = void 0;
-exports.isRestError = isRestError;
-const core_util_1 = __nccwpck_require__(30991);
-const inspect_js_1 = __nccwpck_require__(84111);
-const sanitizer_js_1 = __nccwpck_require__(44720);
-const errorSanitizer = new sanitizer_js_1.Sanitizer();
-/**
- * A custom error type for failed pipeline requests.
- */
-class RestError extends Error {
- constructor(message, options = {}) {
- super(message);
- this.name = "RestError";
- this.code = options.code;
- this.statusCode = options.statusCode;
- // The request and response may contain sensitive information in the headers or body.
- // To help prevent this sensitive information being accidentally logged, the request and response
- // properties are marked as non-enumerable here. This prevents them showing up in the output of
- // JSON.stringify and console.log.
- Object.defineProperty(this, "request", { value: options.request, enumerable: false });
- Object.defineProperty(this, "response", { value: options.response, enumerable: false });
- Object.setPrototypeOf(this, RestError.prototype);
- }
- /**
- * Logging method for util.inspect in Node
- */
- [inspect_js_1.custom]() {
- // Extract non-enumerable properties and add them back. This is OK since in this output the request and
- // response get sanitized.
- return `RestError: ${this.message} \n ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`;
+// --------------------------
+// running processes
+
+function processes(callback) {
+
+ let parsedhead = [];
+
+ function getName(command) {
+ command = command || '';
+ let result = command.split(' ')[0];
+ if (result.substr(-1) === ':') {
+ result = result.substr(0, result.length - 1);
}
-}
-exports.RestError = RestError;
-/**
- * Something went wrong when making the request.
- * This means the actual request failed for some reason,
- * such as a DNS issue or the connection being lost.
- */
-RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
-/**
- * This means that parsing the response from the server failed.
- * It may have been malformed.
- */
-RestError.PARSE_ERROR = "PARSE_ERROR";
-/**
- * Typeguard for RestError
- * @param e - Something caught by a catch clause.
- */
-function isRestError(e) {
- if (e instanceof RestError) {
- return true;
+ if (result.substr(0, 1) !== '[') {
+ let parts = result.split('/');
+ if (isNaN(parseInt(parts[parts.length - 1]))) {
+ result = parts[parts.length - 1];
+ } else {
+ result = parts[0];
+ }
}
- return (0, core_util_1.isError)(e) && e.name === "RestError";
-}
-//# sourceMappingURL=restError.js.map
+ return result;
+ }
-/***/ }),
+ function parseLine(line) {
-/***/ 34750:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ let offset = 0;
+ let offset2 = 0;
+ function checkColumn(i) {
+ offset = offset2;
+ if (parsedhead[i]) {
+ offset2 = line.substring(parsedhead[i].to + offset, 10000).indexOf(' ');
+ } else {
+ offset2 = 10000;
+ }
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.exponentialRetryStrategy = exponentialRetryStrategy;
-exports.isExponentialRetryResponse = isExponentialRetryResponse;
-exports.isSystemError = isSystemError;
-const core_util_1 = __nccwpck_require__(30991);
-const throttlingRetryStrategy_js_1 = __nccwpck_require__(40288);
-// intervals are in milliseconds
-const DEFAULT_CLIENT_RETRY_INTERVAL = 1000;
-const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;
-/**
- * A retry strategy that retries with an exponentially increasing delay in these two cases:
- * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
- * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505).
- */
-function exponentialRetryStrategy(options = {}) {
- var _a, _b;
- const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL;
- const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
- return {
- name: "exponentialRetryStrategy",
- retry({ retryCount, response, responseError }) {
- const matchedSystemError = isSystemError(responseError);
- const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;
- const isExponential = isExponentialRetryResponse(response);
- const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;
- const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential);
- if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {
- return { skipStrategy: true };
- }
- if (responseError && !matchedSystemError && !isExponential) {
- return { errorToThrow: responseError };
+ checkColumn(0);
+ const pid = parseInt(line.substring(parsedhead[0].from + offset, parsedhead[0].to + offset2));
+ checkColumn(1);
+ const ppid = parseInt(line.substring(parsedhead[1].from + offset, parsedhead[1].to + offset2));
+ checkColumn(2);
+ const cpu = parseFloat(line.substring(parsedhead[2].from + offset, parsedhead[2].to + offset2).replace(/,/g, '.'));
+ checkColumn(3);
+ const mem = parseFloat(line.substring(parsedhead[3].from + offset, parsedhead[3].to + offset2).replace(/,/g, '.'));
+ checkColumn(4);
+ const priority = parseInt(line.substring(parsedhead[4].from + offset, parsedhead[4].to + offset2));
+ checkColumn(5);
+ const vsz = parseInt(line.substring(parsedhead[5].from + offset, parsedhead[5].to + offset2));
+ checkColumn(6);
+ const rss = parseInt(line.substring(parsedhead[6].from + offset, parsedhead[6].to + offset2));
+ checkColumn(7);
+ const nice = parseInt(line.substring(parsedhead[7].from + offset, parsedhead[7].to + offset2)) || 0;
+ checkColumn(8);
+ const started = !_sunos ? parseElapsedTime(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()) : parseTimeUnix(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim());
+ checkColumn(9);
+ let state = line.substring(parsedhead[9].from + offset, parsedhead[9].to + offset2).trim();
+ state = (state[0] === 'R' ? 'running' : (state[0] === 'S' ? 'sleeping' : (state[0] === 'T' ? 'stopped' : (state[0] === 'W' ? 'paging' : (state[0] === 'X' ? 'dead' : (state[0] === 'Z' ? 'zombie' : ((state[0] === 'D' || state[0] === 'U') ? 'blocked' : 'unknown')))))));
+ checkColumn(10);
+ let tty = line.substring(parsedhead[10].from + offset, parsedhead[10].to + offset2).trim();
+ if (tty === '?' || tty === '??') { tty = ''; }
+ checkColumn(11);
+ const user = line.substring(parsedhead[11].from + offset, parsedhead[11].to + offset2).trim();
+ checkColumn(12);
+ let cmdPath = '';
+ let command = '';
+ let params = '';
+ let fullcommand = line.substring(parsedhead[12].from + offset, parsedhead[12].to + offset2).trim();
+ if (fullcommand.substr(fullcommand.length - 1) === ']') { fullcommand = fullcommand.slice(0, -1); }
+ if (fullcommand.substr(0, 1) === '[') { command = fullcommand.substring(1); }
+ else {
+ const p1 = fullcommand.indexOf('(');
+ const p2 = fullcommand.indexOf(')');
+ const p3 = fullcommand.indexOf('/');
+ const p4 = fullcommand.indexOf(':');
+ if (p1 < p2 && p1 < p3 && p3 < p2) {
+ command = fullcommand.split(' ')[0];
+ command = command.replace(/:/g, '');
+ } else {
+ if (p4 > 0 && (p3 === -1 || p3 > 3)) {
+ command = fullcommand.split(' ')[0];
+ command = command.replace(/:/g, '');
+ } else {
+ // try to figure out where parameter starts
+ let firstParamPos = fullcommand.indexOf(' -');
+ let firstParamPathPos = fullcommand.indexOf(' /');
+ firstParamPos = (firstParamPos >= 0 ? firstParamPos : 10000);
+ firstParamPathPos = (firstParamPathPos >= 0 ? firstParamPathPos : 10000);
+ const firstPos = Math.min(firstParamPos, firstParamPathPos);
+ let tmpCommand = fullcommand.substr(0, firstPos);
+ const tmpParams = fullcommand.substr(firstPos);
+ const lastSlashPos = tmpCommand.lastIndexOf('/');
+ if (lastSlashPos >= 0) {
+ cmdPath = tmpCommand.substr(0, lastSlashPos);
+ tmpCommand = tmpCommand.substr(lastSlashPos + 1);
+ }
+
+ if (firstPos === 10000 && tmpCommand.indexOf(' ') > -1) {
+ const parts = tmpCommand.split(' ');
+ if (fs.existsSync(path.join(cmdPath, parts[0]))) {
+ command = parts.shift();
+ params = (parts.join(' ') + ' ' + tmpParams).trim();
+ } else {
+ command = tmpCommand.trim();
+ params = tmpParams.trim();
}
- return (0, core_util_1.calculateRetryDelay)(retryCount, {
- retryDelayInMs: retryInterval,
- maxRetryDelayInMs: maxRetryInterval,
- });
- },
- };
-}
-/**
- * A response is a retry response if it has status codes:
- * - 408, or
- * - Greater or equal than 500, except for 501 and 505.
- */
-function isExponentialRetryResponse(response) {
- return Boolean(response &&
- response.status !== undefined &&
- (response.status >= 500 || response.status === 408) &&
- response.status !== 501 &&
- response.status !== 505);
-}
-/**
- * Determines whether an error from a pipeline response was triggered in the network layer.
- */
-function isSystemError(err) {
- if (!err) {
- return false;
+ } else {
+ command = tmpCommand.trim();
+ params = tmpParams.trim();
+ }
+ }
+ }
+
}
- return (err.code === "ETIMEDOUT" ||
- err.code === "ESOCKETTIMEDOUT" ||
- err.code === "ECONNREFUSED" ||
- err.code === "ECONNRESET" ||
- err.code === "ENOENT" ||
- err.code === "ENOTFOUND");
-}
-//# sourceMappingURL=exponentialRetryStrategy.js.map
-/***/ }),
+ return ({
+ pid: pid,
+ parentPid: ppid,
+ name: _linux ? getName(command) : command,
+ cpu: cpu,
+ cpuu: 0,
+ cpus: 0,
+ mem: mem,
+ priority: priority,
+ memVsz: vsz,
+ memRss: rss,
+ nice: nice,
+ started: started,
+ state: state,
+ tty: tty,
+ user: user,
+ command: command,
+ params: params,
+ path: cmdPath
+ });
+ }
+
+ function parseProcesses(lines) {
+ let result = [];
+ if (lines.length > 1) {
+ let head = lines[0];
+ parsedhead = util.parseHead(head, 8);
+ lines.shift();
+ lines.forEach(function (line) {
+ if (line.trim() !== '') {
+ result.push(parseLine(line));
+ }
+ });
+ }
+ return result;
+ }
+ function parseProcesses2(lines) {
+
+ function formatDateTime(time) {
+ const month = ('0' + (time.getMonth() + 1).toString()).slice(-2);
+ const year = time.getFullYear().toString();
+ const day = ('0' + time.getDate().toString()).slice(-2);
+ const hours = ('0' + time.getHours().toString()).slice(-2);
+ const mins = ('0' + time.getMinutes().toString()).slice(-2);
+ const secs = ('0' + time.getSeconds().toString()).slice(-2);
+
+ return (year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + secs);
+ }
+
+ function parseElapsed(etime) {
+ let started = '';
+ if (etime.indexOf('d') >= 0) {
+ const elapsed_parts = etime.split('d');
+ started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 24 + elapsed_parts[1] * 1) * 60 * 60 * 1000));
+ } else if (etime.indexOf('h') >= 0) {
+ const elapsed_parts = etime.split('h');
+ started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 60 + elapsed_parts[1] * 1) * 60 * 1000));
+ } else if (etime.indexOf(':') >= 0) {
+ const elapsed_parts = etime.split(':');
+ started = formatDateTime(new Date(Date.now() - (elapsed_parts.length > 1 ? (elapsed_parts[0] * 60 + elapsed_parts[1]) * 1000 : elapsed_parts[0] * 1000)));
+ }
+ return started;
+ }
+
+ let result = [];
+ lines.forEach(function (line) {
+ if (line.trim() !== '') {
+ line = line.trim().replace(/ +/g, ' ').replace(/,+/g, '.');
+ const parts = line.split(' ');
+ const command = parts.slice(9).join(' ');
+ const pmem = parseFloat((1.0 * parseInt(parts[3]) * 1024 / os.totalmem()).toFixed(1));
+ const started = parseElapsed(parts[5]);
+
+ result.push({
+ pid: parseInt(parts[0]),
+ parentPid: parseInt(parts[1]),
+ name: getName(command),
+ cpu: 0,
+ cpuu: 0,
+ cpus: 0,
+ mem: pmem,
+ priority: 0,
+ memVsz: parseInt(parts[2]),
+ memRss: parseInt(parts[3]),
+ nice: parseInt(parts[4]),
+ started: started,
+ state: (parts[6] === 'R' ? 'running' : (parts[6] === 'S' ? 'sleeping' : (parts[6] === 'T' ? 'stopped' : (parts[6] === 'W' ? 'paging' : (parts[6] === 'X' ? 'dead' : (parts[6] === 'Z' ? 'zombie' : ((parts[6] === 'D' || parts[6] === 'U') ? 'blocked' : 'unknown'))))))),
+ tty: parts[7],
+ user: parts[8],
+ command: command
+ });
+ }
+ });
+ return result;
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ all: 0,
+ running: 0,
+ blocked: 0,
+ sleeping: 0,
+ unknown: 0,
+ list: []
+ };
+
+ let cmd = '';
-/***/ 40288:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if ((_processes_cpu.ms && Date.now() - _processes_cpu.ms >= 500) || _processes_cpu.ms === 0) {
+ if (_linux || _freebsd || _openbsd || _netbsd || _darwin || _sunos) {
+ if (_linux) { cmd = 'export LC_ALL=C; ps -axo pid:11,ppid:11,pcpu:6,pmem:6,pri:5,vsz:11,rss:11,ni:5,etime:30,state:5,tty:15,user:20,command; unset LC_ALL'; }
+ if (_freebsd || _openbsd || _netbsd) { cmd = 'export LC_ALL=C; ps -axo pid,ppid,pcpu,pmem,pri,vsz,rss,ni,etime,state,tty,user,command; unset LC_ALL'; }
+ if (_darwin) { cmd = 'ps -axo pid,ppid,pcpu,pmem,pri,vsz=temp_title_1,rss=temp_title_2,nice,etime=temp_title_3,state,tty,user,command -r'; }
+ if (_sunos) { cmd = 'ps -Ao pid,ppid,pcpu,pmem,pri,vsz,rss,nice,stime,s,tty,user,comm'; }
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+ if (!error && stdout.toString().trim()) {
+ result.list = (parseProcesses(stdout.toString().split('\n'))).slice();
+ result.all = result.list.length;
+ result.running = result.list.filter(function (e) {
+ return e.state === 'running';
+ }).length;
+ result.blocked = result.list.filter(function (e) {
+ return e.state === 'blocked';
+ }).length;
+ result.sleeping = result.list.filter(function (e) {
+ return e.state === 'sleeping';
+ }).length;
+ if (_linux) {
+ // calc process_cpu - ps is not accurate in linux!
+ cmd = 'cat /proc/stat | grep "cpu "';
+ result.list.forEach((element) => {
+ cmd += (';cat /proc/' + element.pid + '/stat');
+ });
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+ let curr_processes = stdout.toString().split('\n');
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isThrottlingRetryResponse = isThrottlingRetryResponse;
-exports.throttlingRetryStrategy = throttlingRetryStrategy;
-const helpers_js_1 = __nccwpck_require__(94982);
-/**
- * The header that comes back from Azure services representing
- * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry).
- */
-const RetryAfterHeader = "Retry-After";
-/**
- * The headers that come back from Azure services representing
- * the amount of time (minimum) to wait to retry.
- *
- * "retry-after-ms", "x-ms-retry-after-ms" : milliseconds
- * "Retry-After" : seconds or timestamp
- */
-const AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader];
-/**
- * A response is a throttling retry response if it has a throttling status code (429 or 503),
- * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
- *
- * Returns the `retryAfterInMs` value if the response is a throttling retry response.
- * If not throttling retry response, returns `undefined`.
- *
- * @internal
- */
-function getRetryAfterInMs(response) {
- if (!(response && [429, 503].includes(response.status)))
- return undefined;
- try {
- // Headers: "retry-after-ms", "x-ms-retry-after-ms", "Retry-After"
- for (const header of AllRetryAfterHeaders) {
- const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header);
- if (retryAfterValue === 0 || retryAfterValue) {
- // "Retry-After" header ==> seconds
- // "retry-after-ms", "x-ms-retry-after-ms" headers ==> milli-seconds
- const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1;
- return retryAfterValue * multiplyingFactor; // in milli-seconds
- }
- }
- // RetryAfterHeader ("Retry-After") has a special case where it might be formatted as a date instead of a number of seconds
- const retryAfterHeader = response.headers.get(RetryAfterHeader);
- if (!retryAfterHeader)
- return;
- const date = Date.parse(retryAfterHeader);
- const diff = date - Date.now();
- // negative diff would mean a date in the past, so retry asap with 0 milliseconds
- return Number.isFinite(diff) ? Math.max(0, diff) : undefined;
- }
- catch (_a) {
- return undefined;
- }
-}
-/**
- * A response is a retry response if it has a throttling status code (429 or 503),
- * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
- */
-function isThrottlingRetryResponse(response) {
- return Number.isFinite(getRetryAfterInMs(response));
-}
-function throttlingRetryStrategy() {
- return {
- name: "throttlingRetryStrategy",
- retry({ response }) {
- const retryAfterInMs = getRetryAfterInMs(response);
- if (!Number.isFinite(retryAfterInMs)) {
- return { skipStrategy: true };
- }
- return {
- retryAfterInMs,
- };
- },
- };
-}
-//# sourceMappingURL=throttlingRetryStrategy.js.map
+ // first line (all - /proc/stat)
+ let all = parseProcStat(curr_processes.shift());
-/***/ }),
+ // process
+ let list_new = {};
+ let resultProcess = {};
+ curr_processes.forEach((element) => {
+ resultProcess = calcProcStatLinux(element, all, _processes_cpu);
-/***/ 85307:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (resultProcess.pid) {
+
+ // store pcpu in outer array
+ let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid);
+ if (listPos >= 0) {
+ result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus;
+ result.list[listPos].cpuu = resultProcess.cpuu;
+ result.list[listPos].cpus = resultProcess.cpus;
+ }
+ // save new values
+ list_new[resultProcess.pid] = {
+ cpuu: resultProcess.cpuu,
+ cpus: resultProcess.cpus,
+ utime: resultProcess.utime,
+ stime: resultProcess.stime,
+ cutime: resultProcess.cutime,
+ cstime: resultProcess.cstime
+ };
+ }
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.concat = concat;
-const tslib_1 = __nccwpck_require__(94176);
-const node_stream_1 = __nccwpck_require__(57075);
-const typeGuards_js_1 = __nccwpck_require__(24449);
-const file_js_1 = __nccwpck_require__(8581);
-function streamAsyncIterator() {
- return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() {
- const reader = this.getReader();
- try {
- while (true) {
- const { done, value } = yield tslib_1.__await(reader.read());
- if (done) {
- return yield tslib_1.__await(void 0);
+ // store old values
+ _processes_cpu.all = all;
+ _processes_cpu.list = Object.assign({}, list_new);
+ _processes_cpu.ms = Date.now() - _processes_cpu.ms;
+ _processes_cpu.result = Object.assign({}, result);
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } else {
+ cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,stat,tty,user,comm';
+ if (_sunos) {
+ cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,s,tty,user,comm';
+ }
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.shift();
+
+ result.list = parseProcesses2(lines).slice();
+ result.all = result.list.length;
+ result.running = result.list.filter(function (e) {
+ return e.state === 'running';
+ }).length;
+ result.blocked = result.list.filter(function (e) {
+ return e.state === 'blocked';
+ }).length;
+ result.sleeping = result.list.filter(function (e) {
+ return e.state === 'sleeping';
+ }).length;
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
}
- yield yield tslib_1.__await(value);
+ });
}
+ });
+ } else if (_windows) {
+ try {
+ util.powerShell('Get-CimInstance Win32_Process | select-Object ProcessId,ParentProcessId,ExecutionState,Caption,CommandLine,ExecutablePath,UserModeTime,KernelModeTime,WorkingSetSize,Priority,PageFileUsage, @{n="CreationDate";e={$_.CreationDate.ToString("yyyy-MM-dd HH:mm:ss")}} | fl').then((stdout, error) => {
+ if (!error) {
+ let processSections = stdout.split(/\n\s*\n/);
+ let procs = [];
+ let procStats = [];
+ let list_new = {};
+ let allcpuu = 0;
+ let allcpus = 0;
+ processSections.forEach((element) => {
+ if (element.trim() !== '') {
+ let lines = element.trim().split('\r\n');
+ let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10);
+ let parentPid = parseInt(util.getValue(lines, 'ParentProcessId', ':', true), 10);
+ let statusValue = util.getValue(lines, 'ExecutionState', ':');
+ let name = util.getValue(lines, 'Caption', ':', true);
+ let commandLine = util.getValue(lines, 'CommandLine', ':', true);
+ // get additional command line data
+ let additionalCommand = false;
+ lines.forEach((line) => {
+ if (additionalCommand && line.toLowerCase().startsWith(' ')) {
+ commandLine += ' ' + line.trim();
+ } else {
+ additionalCommand = false;
+ }
+ if (line.toLowerCase().startsWith('commandline')) {
+ additionalCommand = true;
+ }
+ });
+ let commandPath = util.getValue(lines, 'ExecutablePath', ':', true);
+ let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10);
+ let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10);
+ let memw = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10);
+ allcpuu = allcpuu + utime;
+ allcpus = allcpus + stime;
+ result.all++;
+ if (!statusValue) { result.unknown++; }
+ if (statusValue === '3') { result.running++; }
+ if (statusValue === '4' || statusValue === '5') { result.blocked++; }
+
+ procStats.push({
+ pid: pid,
+ utime: utime,
+ stime: stime,
+ cpu: 0,
+ cpuu: 0,
+ cpus: 0,
+ });
+ procs.push({
+ pid: pid,
+ parentPid: parentPid,
+ name: name,
+ cpu: 0,
+ cpuu: 0,
+ cpus: 0,
+ mem: memw / os.totalmem() * 100,
+ priority: parseInt(util.getValue(lines, 'Priority', ':', true), 10),
+ memVsz: parseInt(util.getValue(lines, 'PageFileUsage', ':', true), 10),
+ memRss: Math.floor(parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10) / 1024),
+ nice: 0,
+ started: util.getValue(lines, 'CreationDate', ':', true),
+ state: (!statusValue ? _winStatusValues[0] : _winStatusValues[statusValue]),
+ tty: '',
+ user: '',
+ command: commandLine || name,
+ path: commandPath,
+ params: ''
+ });
+ }
+ });
+
+ result.sleeping = result.all - result.running - result.blocked - result.unknown;
+ result.list = procs;
+ procStats.forEach((element) => {
+ let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _processes_cpu);
+
+ // store pcpu in outer array
+ let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid);
+ if (listPos >= 0) {
+ result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus;
+ result.list[listPos].cpuu = resultProcess.cpuu;
+ result.list[listPos].cpus = resultProcess.cpus;
+ }
+
+ // save new values
+ list_new[resultProcess.pid] = {
+ cpuu: resultProcess.cpuu,
+ cpus: resultProcess.cpus,
+ utime: resultProcess.utime,
+ stime: resultProcess.stime
+ };
+ });
+
+ // store old values
+ _processes_cpu.all = allcpuu + allcpus;
+ _processes_cpu.all_utime = allcpuu;
+ _processes_cpu.all_stime = allcpus;
+ _processes_cpu.list = Object.assign({}, list_new);
+ _processes_cpu.ms = Date.now() - _processes_cpu.ms;
+ _processes_cpu.result = Object.assign({}, result);
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
}
- finally {
- reader.releaseLock();
- }
+ } else {
+ if (callback) { callback(_processes_cpu.result); }
+ resolve(_processes_cpu.result);
+ }
});
+ });
}
-function makeAsyncIterable(webStream) {
- if (!webStream[Symbol.asyncIterator]) {
- webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);
- }
- if (!webStream.values) {
- webStream.values = streamAsyncIterator.bind(webStream);
- }
-}
-function ensureNodeStream(stream) {
- if (stream instanceof ReadableStream) {
- makeAsyncIterable(stream);
- return node_stream_1.Readable.fromWeb(stream);
- }
- else {
- return stream;
- }
-}
-function toStream(source) {
- if (source instanceof Uint8Array) {
- return node_stream_1.Readable.from(Buffer.from(source));
- }
- else if ((0, typeGuards_js_1.isBlob)(source)) {
- return toStream((0, file_js_1.getRawContent)(source));
- }
- else {
- return ensureNodeStream(source);
- }
-}
-/**
- * Utility function that concatenates a set of binary inputs into one combined output.
- *
- * @param sources - array of sources for the concatenation
- * @returns - in Node, a (() =\> NodeJS.ReadableStream) which, when read, produces a concatenation of all the inputs.
- * In browser, returns a `Blob` representing all the concatenated inputs.
- *
- * @internal
- */
-async function concat(sources) {
- return function () {
- const streams = sources.map((x) => (typeof x === "function" ? x() : x)).map(toStream);
- return node_stream_1.Readable.from((function () {
- return tslib_1.__asyncGenerator(this, arguments, function* () {
- var _a, e_1, _b, _c;
- for (const stream of streams) {
- try {
- for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) {
- _c = stream_1_1.value;
- _d = false;
- const chunk = _c;
- yield yield tslib_1.__await(chunk);
- }
- }
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
- finally {
- try {
- if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1));
- }
- finally { if (e_1) throw e_1.error; }
- }
- }
- });
- })());
- };
-}
-//# sourceMappingURL=concat.js.map
-/***/ }),
+exports.processes = processes;
-/***/ 8581:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// PS - process load
+// get detailed information about a certain process
+// (PID, CPU-Usage %, Mem-Usage %)
+function processLoad(proc, callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getRawContent = getRawContent;
-exports.createFileFromStream = createFileFromStream;
-exports.createFile = createFile;
-const core_util_1 = __nccwpck_require__(30991);
-const typeGuards_js_1 = __nccwpck_require__(24449);
-const unimplementedMethods = {
- arrayBuffer: () => {
- throw new Error("Not implemented");
- },
- slice: () => {
- throw new Error("Not implemented");
- },
- text: () => {
- throw new Error("Not implemented");
- },
-};
-/**
- * Private symbol used as key on objects created using createFile containing the
- * original source of the file object.
- *
- * This is used in Node to access the original Node stream without using Blob#stream, which
- * returns a web stream. This is done to avoid a couple of bugs to do with Blob#stream and
- * Readable#to/fromWeb in Node versions we support:
- * - https://github.com/nodejs/node/issues/42694 (fixed in Node 18.14)
- * - https://github.com/nodejs/node/issues/48916 (fixed in Node 20.6)
- *
- * Once these versions are no longer supported, we may be able to stop doing this.
- *
- * @internal
- */
-const rawContent = Symbol("rawContent");
-function hasRawContent(x) {
- return typeof x[rawContent] === "function";
-}
-/**
- * Extract the raw content from a given blob-like object. If the input was created using createFile
- * or createFileFromStream, the exact content passed into createFile/createFileFromStream will be used.
- * For true instances of Blob and File, returns the blob's content as a Web ReadableStream.
- *
- * @internal
- */
-function getRawContent(blob) {
- if (hasRawContent(blob)) {
- return blob[rawContent]();
- }
- else {
- return blob.stream();
- }
-}
-/**
- * Create an object that implements the File interface. This object is intended to be
- * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
- * other situations.
- *
- * Use this function to:
- * - Create a File object for use in RequestBodyType.formData in environments where the
- * global File object is unavailable.
- * - Create a File-like object from a readable stream without reading the stream into memory.
- *
- * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is
- * passed in a request's form data map, the stream will not be read into memory
- * and instead will be streamed when the request is made. In the event of a retry, the
- * stream needs to be read again, so this callback SHOULD return a fresh stream if possible.
- * @param name - the name of the file.
- * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
- */
-function createFileFromStream(stream, name, options = {}) {
- var _a, _b, _c, _d;
- return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => {
- const s = stream();
- if ((0, typeGuards_js_1.isNodeReadableStream)(s)) {
- throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.");
- }
- return s;
- }, [rawContent]: stream });
-}
-/**
- * Create an object that implements the File interface. This object is intended to be
- * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
- * other situations.
- *
- * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.
- *
- * @param content - the content of the file as a Uint8Array in memory.
- * @param name - the name of the file.
- * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
- */
-function createFile(content, name, options = {}) {
- var _a, _b, _c;
- if (core_util_1.isNodeLike) {
- return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content });
- }
- else {
- return new File([content], name, options);
- }
-}
-//# sourceMappingURL=file.js.map
+ // fallback - if only callback is given
+ if (util.isFunction(proc) && !callback) {
+ callback = proc;
+ proc = '';
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+
+ proc = proc || '';
+
+ if (typeof proc !== 'string') {
+ if (callback) { callback([]); }
+ return resolve([]);
+ }
-/***/ }),
+ let processesString = '';
+ try {
+ processesString.__proto__.toLowerCase = util.stringToLower;
+ processesString.__proto__.replace = util.stringReplace;
+ processesString.__proto__.toString = util.stringToString;
+ processesString.__proto__.substr = util.stringSubstr;
+ processesString.__proto__.substring = util.stringSubstring;
+ processesString.__proto__.trim = util.stringTrim;
+ processesString.__proto__.startsWith = util.stringStartWith;
-/***/ 94982:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ } catch (e) {
+ Object.setPrototypeOf(processesString, util.stringObj);
+ }
+ const s = util.sanitizeShellString(proc);
+ const l = util.mathMin(s.length, 2000);
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.delay = delay;
-exports.parseHeaderValueAsNumber = parseHeaderValueAsNumber;
-const abort_controller_1 = __nccwpck_require__(92242);
-const StandardAbortMessage = "The operation was aborted.";
-/**
- * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds.
- * @param delayInMs - The number of milliseconds to be delayed.
- * @param value - The value to be resolved with after a timeout of t milliseconds.
- * @param options - The options for delay - currently abort options
- * - abortSignal - The abortSignal associated with containing operation.
- * - abortErrorMsg - The abort error message associated with containing operation.
- * @returns Resolved promise
- */
-function delay(delayInMs, value, options) {
- return new Promise((resolve, reject) => {
- let timer = undefined;
- let onAborted = undefined;
- const rejectOnAbort = () => {
- return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage));
- };
- const removeListeners = () => {
- if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) {
- options.abortSignal.removeEventListener("abort", onAborted);
- }
- };
- onAborted = () => {
- if (timer) {
- clearTimeout(timer);
- }
- removeListeners();
- return rejectOnAbort();
- };
- if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) {
- return rejectOnAbort();
- }
- timer = setTimeout(() => {
- removeListeners();
- resolve(value);
- }, delayInMs);
- if (options === null || options === void 0 ? void 0 : options.abortSignal) {
- options.abortSignal.addEventListener("abort", onAborted);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ processesString = processesString + s[i];
}
- });
-}
-/**
- * @internal
- * @returns the parsed value or undefined if the parsed value is invalid.
- */
-function parseHeaderValueAsNumber(response, headerName) {
- const value = response.headers.get(headerName);
- if (!value)
- return;
- const valueAsNum = Number(value);
- if (Number.isNaN(valueAsNum))
- return;
- return valueAsNum;
-}
-//# sourceMappingURL=helpers.js.map
+ }
-/***/ }),
+ processesString = processesString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|');
+ if (processesString === '') {
+ processesString = '*';
+ }
+ if (util.isPrototypePolluted() && processesString !== '*') {
+ processesString = '------';
+ }
+ let processes = processesString.split('|');
+ let result = [];
-/***/ 84111:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ const procSanitized = util.isPrototypePolluted() ? '' : (util.sanitizeShellString(proc) || '*');
+ // from here new
+ // let result = {
+ // 'proc': procSanitized,
+ // 'pid': null,
+ // 'cpu': 0,
+ // 'mem': 0
+ // };
+ if (procSanitized && processes.length && processes[0] !== '------') {
+ if (_windows) {
+ try {
+ util.powerShell('Get-CimInstance Win32_Process | select ProcessId,Caption,UserModeTime,KernelModeTime,WorkingSetSize | fl').then((stdout, error) => {
+ if (!error) {
+ let processSections = stdout.split(/\n\s*\n/);
+ let procStats = [];
+ let list_new = {};
+ let allcpuu = 0;
+ let allcpus = 0;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.custom = void 0;
-const node_util_1 = __nccwpck_require__(57975);
-exports.custom = node_util_1.inspect.custom;
-//# sourceMappingURL=inspect.js.map
+ // go through all processes
+ processSections.forEach((element) => {
+ if (element.trim() !== '') {
+ let lines = element.trim().split('\r\n');
+ let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10);
+ let name = util.getValue(lines, 'Caption', ':', true);
+ let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10);
+ let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10);
+ let mem = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10);
+ allcpuu = allcpuu + utime;
+ allcpus = allcpus + stime;
-/***/ }),
+ procStats.push({
+ pid: pid,
+ name,
+ utime: utime,
+ stime: stime,
+ cpu: 0,
+ cpuu: 0,
+ cpus: 0,
+ mem
+ });
+ let pname = '';
+ let inList = false;
+ processes.forEach(function (proc) {
+ if (name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) {
+ inList = true;
+ pname = proc;
+ }
+ });
-/***/ 44720:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (processesString === '*' || inList) {
+ let processFound = false;
+ result.forEach(function (item) {
+ if (item.proc.toLowerCase() === pname.toLowerCase()) {
+ item.pids.push(pid);
+ item.mem += mem / os.totalmem() * 100;
+ processFound = true;
+ }
+ });
+ if (!processFound) {
+ result.push({
+ proc: pname,
+ pid: pid,
+ pids: [pid],
+ cpu: 0,
+ mem: mem / os.totalmem() * 100
+ });
+ }
+ }
+ }
+ });
+ // add missing processes
+ if (processesString !== '*') {
+ let processesMissing = processes.filter(function (name) {
+ return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Sanitizer = void 0;
-const core_util_1 = __nccwpck_require__(30991);
-const RedactedString = "REDACTED";
-// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts
-const defaultAllowedHeaderNames = [
- "x-ms-client-request-id",
- "x-ms-return-client-request-id",
- "x-ms-useragent",
- "x-ms-correlation-request-id",
- "x-ms-request-id",
- "client-request-id",
- "ms-cv",
- "return-client-request-id",
- "traceparent",
- "Access-Control-Allow-Credentials",
- "Access-Control-Allow-Headers",
- "Access-Control-Allow-Methods",
- "Access-Control-Allow-Origin",
- "Access-Control-Expose-Headers",
- "Access-Control-Max-Age",
- "Access-Control-Request-Headers",
- "Access-Control-Request-Method",
- "Origin",
- "Accept",
- "Accept-Encoding",
- "Cache-Control",
- "Connection",
- "Content-Length",
- "Content-Type",
- "Date",
- "ETag",
- "Expires",
- "If-Match",
- "If-Modified-Since",
- "If-None-Match",
- "If-Unmodified-Since",
- "Last-Modified",
- "Pragma",
- "Request-Id",
- "Retry-After",
- "Server",
- "Transfer-Encoding",
- "User-Agent",
- "WWW-Authenticate",
-];
-const defaultAllowedQueryParameters = ["api-version"];
-/**
- * @internal
- */
-class Sanitizer {
- constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) {
- allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
- allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
- this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
- this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
- }
- sanitize(obj) {
- const seen = new Set();
- return JSON.stringify(obj, (key, value) => {
- // Ensure Errors include their interesting non-enumerable members
- if (value instanceof Error) {
- return Object.assign(Object.assign({}, value), { name: value.name, message: value.message });
- }
- if (key === "headers") {
- return this.sanitizeHeaders(value);
- }
- else if (key === "url") {
- return this.sanitizeUrl(value);
- }
- else if (key === "query") {
- return this.sanitizeQuery(value);
- }
- else if (key === "body") {
- // Don't log the request body
- return undefined;
- }
- else if (key === "response") {
- // Don't log response again
- return undefined;
- }
- else if (key === "operationSpec") {
- // When using sendOperationRequest, the request carries a massive
- // field with the autorest spec. No need to log it.
- return undefined;
- }
- else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) {
- if (seen.has(value)) {
- return "[Circular]";
+ });
+ processesMissing.forEach(function (procName) {
+ result.push({
+ proc: procName,
+ pid: null,
+ pids: [],
+ cpu: 0,
+ mem: 0
+ });
+ });
}
- seen.add(value);
- }
- return value;
- }, 2);
- }
- sanitizeUrl(value) {
- if (typeof value !== "string" || value === null || value === "") {
- return value;
- }
- const url = new URL(value);
- if (!url.search) {
- return value;
- }
- for (const [key] of url.searchParams) {
- if (!this.allowedQueryParameters.has(key.toLowerCase())) {
- url.searchParams.set(key, RedactedString);
- }
- }
- return url.toString();
- }
- sanitizeHeaders(obj) {
- const sanitized = {};
- for (const key of Object.keys(obj)) {
- if (this.allowedHeaderNames.has(key.toLowerCase())) {
- sanitized[key] = obj[key];
- }
- else {
- sanitized[key] = RedactedString;
- }
- }
- return sanitized;
- }
- sanitizeQuery(value) {
- if (typeof value !== "object" || value === null) {
- return value;
- }
- const sanitized = {};
- for (const k of Object.keys(value)) {
- if (this.allowedQueryParameters.has(k.toLowerCase())) {
- sanitized[k] = value[k];
- }
- else {
- sanitized[k] = RedactedString;
- }
- }
- return sanitized;
- }
-}
-exports.Sanitizer = Sanitizer;
-//# sourceMappingURL=sanitizer.js.map
-/***/ }),
+ // calculate proc stats for each proc
+ procStats.forEach((element) => {
+ let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _process_cpu);
-/***/ 82534:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ let listPos = -1;
+ for (let j = 0; j < result.length; j++) {
+ if (result[j].pid === resultProcess.pid || result[j].pids.indexOf(resultProcess.pid) >= 0) { listPos = j; }
+ }
+ if (listPos >= 0) {
+ result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus;
+ }
+ // save new values
+ list_new[resultProcess.pid] = {
+ cpuu: resultProcess.cpuu,
+ cpus: resultProcess.cpus,
+ utime: resultProcess.utime,
+ stime: resultProcess.stime
+ };
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.DEFAULT_CYCLER_OPTIONS = void 0;
-exports.createTokenCycler = createTokenCycler;
-const helpers_js_1 = __nccwpck_require__(94982);
-// Default options for the cycler if none are provided
-exports.DEFAULT_CYCLER_OPTIONS = {
- forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires
- retryIntervalInMs: 3000, // Allow refresh attempts every 3s
- refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry
-};
-/**
- * Converts an an unreliable access token getter (which may resolve with null)
- * into an AccessTokenGetter by retrying the unreliable getter in a regular
- * interval.
- *
- * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.
- * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.
- * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.
- * @returns - A promise that, if it resolves, will resolve with an access token.
- */
-async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
- // This wrapper handles exceptions gracefully as long as we haven't exceeded
- // the timeout.
- async function tryGetAccessToken() {
- if (Date.now() < refreshTimeout) {
- try {
- return await getAccessToken();
- }
- catch (_a) {
- return null;
- }
- }
- else {
- const finalToken = await getAccessToken();
- // Timeout is up, so throw if it's still null
- if (finalToken === null) {
- throw new Error("Failed to refresh access token.");
- }
- return finalToken;
- }
- }
- let token = await tryGetAccessToken();
- while (token === null) {
- await (0, helpers_js_1.delay)(retryIntervalInMs);
- token = await tryGetAccessToken();
- }
- return token;
-}
-/**
- * Creates a token cycler from a credential, scopes, and optional settings.
- *
- * A token cycler represents a way to reliably retrieve a valid access token
- * from a TokenCredential. It will handle initializing the token, refreshing it
- * when it nears expiration, and synchronizes refresh attempts to avoid
- * concurrency hazards.
- *
- * @param credential - the underlying TokenCredential that provides the access
- * token
- * @param tokenCyclerOptions - optionally override default settings for the cycler
- *
- * @returns - a function that reliably produces a valid access token
- */
-function createTokenCycler(credential, tokenCyclerOptions) {
- let refreshWorker = null;
- let token = null;
- let tenantId;
- const options = Object.assign(Object.assign({}, exports.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions);
- /**
- * This little holder defines several predicates that we use to construct
- * the rules of refreshing the token.
- */
- const cycler = {
- /**
- * Produces true if a refresh job is currently in progress.
- */
- get isRefreshing() {
- return refreshWorker !== null;
- },
- /**
- * Produces true if the cycler SHOULD refresh (we are within the refresh
- * window and not already refreshing)
- */
- get shouldRefresh() {
- var _a;
- if (cycler.isRefreshing) {
- return false;
- }
- if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) {
- return true;
- }
- return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now();
- },
- /**
- * Produces true if the cycler MUST refresh (null or nearly-expired
- * token).
- */
- get mustRefresh() {
- return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now());
- },
- };
- /**
- * Starts a refresh job or returns the existing job if one is already
- * running.
- */
- function refresh(scopes, getTokenOptions) {
- var _a;
- if (!cycler.isRefreshing) {
- // We bind `scopes` here to avoid passing it around a lot
- const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
- // Take advantage of promise chaining to insert an assignment to `token`
- // before the refresh can be considered done.
- refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs,
- // If we don't have a token, then we should timeout immediately
- (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now())
- .then((_token) => {
- refreshWorker = null;
- token = _token;
- tenantId = getTokenOptions.tenantId;
- return token;
- })
- .catch((reason) => {
- // We also should reset the refresher if we enter a failed state. All
- // existing awaiters will throw, but subsequent requests will start a
- // new retry chain.
- refreshWorker = null;
- token = null;
- tenantId = undefined;
- throw reason;
- });
- }
- return refreshWorker;
- }
- return async (scopes, tokenOptions) => {
- //
- // Simple rules:
- // - If we MUST refresh, then return the refresh task, blocking
- // the pipeline until a token is available.
- // - If we SHOULD refresh, then run refresh but don't return it
- // (we can still use the cached token).
- // - Return the token, since it's fine if we didn't return in
- // step 1.
- //
- const hasClaimChallenge = Boolean(tokenOptions.claims);
- const tenantIdChanged = tenantId !== tokenOptions.tenantId;
- if (hasClaimChallenge) {
- // If we've received a claim, we know the existing token isn't valid
- // We want to clear it so that that refresh worker won't use the old expiration time as a timeout
- token = null;
- }
- // If the tenantId passed in token options is different to the one we have
- // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to
- // refresh the token with the new tenantId or token.
- const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
- if (mustRefresh) {
- return refresh(scopes, tokenOptions);
- }
- if (cycler.shouldRefresh) {
- refresh(scopes, tokenOptions);
+ // store old values
+ _process_cpu.all = allcpuu + allcpus;
+ _process_cpu.all_utime = allcpuu;
+ _process_cpu.all_stime = allcpus;
+ _process_cpu.list = Object.assign({}, list_new);
+ _process_cpu.ms = Date.now() - _process_cpu.ms;
+ _process_cpu.result = JSON.parse(JSON.stringify(result));
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
}
- return token;
- };
-}
-//# sourceMappingURL=tokenCycler.js.map
-
-/***/ }),
-/***/ 24449:
-/***/ ((__unused_webpack_module, exports) => {
+ if (_darwin || _linux || _freebsd || _openbsd || _netbsd) {
+ const params = ['-axo', 'pid,ppid,pcpu,pmem,comm'];
+ util.execSafe('ps', params).then((stdout) => {
+ if (stdout) {
+ let procStats = [];
+ let lines = stdout.toString().split('\n').filter(function (line) {
+ if (processesString === '*') { return true; }
+ if (line.toLowerCase().indexOf('grep') !== -1) { return false; } // remove this??
+ let found = false;
+ processes.forEach(function (item) {
+ found = found || (line.toLowerCase().indexOf(item.toLowerCase()) >= 0);
+ });
+ return found;
+ });
+ lines.shift();
+ lines.forEach(function (line) {
+ let data = line.trim().replace(/ +/g, ' ').split(' ');
+ if (data.length > 4) {
+ const linuxName = data[4].indexOf('/') >= 0 ? data[4].substring(0, data[4].indexOf('/')) : data[4];
+ const name = _linux ? (linuxName) : data[4].substring(data[4].lastIndexOf('/') + 1);
+ procStats.push({
+ name,
+ pid: parseInt(data[0]) || 0,
+ ppid: parseInt(data[1]) || 0,
+ cpu: parseFloat(data[2].replace(',', '.')),
+ mem: parseFloat(data[3].replace(',', '.'))
+ });
+ }
+ });
+ procStats.forEach(function (item) {
+ let listPos = -1;
+ let inList = false;
+ let name = item.name;
+ for (let j = 0; j < result.length; j++) {
+ if (item.name.toLowerCase().indexOf(result[j].proc.toLowerCase()) >= 0) {
+ listPos = j;
+ }
+ }
+ processes.forEach(function (proc) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isNodeReadableStream = isNodeReadableStream;
-exports.isWebReadableStream = isWebReadableStream;
-exports.isReadableStream = isReadableStream;
-exports.isBlob = isBlob;
-function isNodeReadableStream(x) {
- return Boolean(x && typeof x["pipe"] === "function");
-}
-function isWebReadableStream(x) {
- return Boolean(x &&
- typeof x.getReader === "function" &&
- typeof x.tee === "function");
-}
-function isReadableStream(x) {
- return isNodeReadableStream(x) || isWebReadableStream(x);
-}
-function isBlob(x) {
- return typeof x.stream === "function";
-}
-//# sourceMappingURL=typeGuards.js.map
+ if (item.name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) {
+ inList = true;
+ name = proc;
+ }
+ });
+ if ((processesString === '*') || inList) {
+ if (listPos < 0) {
+ if (name) {
+ result.push({
+ proc: name,
+ pid: item.pid,
+ pids: [item.pid],
+ cpu: item.cpu,
+ mem: item.mem
+ });
+ }
+ } else {
+ if (item.ppid < 10) {
+ result[listPos].pid = item.pid;
+ }
+ result[listPos].pids.push(item.pid);
+ result[listPos].cpu += item.cpu;
+ result[listPos].mem += item.mem;
+ }
+ }
+ });
-/***/ }),
+ if (processesString !== '*') {
+ // add missing processes
+ let processesMissing = processes.filter(function (name) {
+ return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0;
+ });
+ processesMissing.forEach(function (procName) {
+ result.push({
+ proc: procName,
+ pid: null,
+ pids: [],
+ cpu: 0,
+ mem: 0
+ });
+ });
+ }
+ if (_linux) {
+ // calc process_cpu - ps is not accurate in linux!
+ result.forEach(function (item) {
+ item.cpu = 0;
+ });
+ let cmd = 'cat /proc/stat | grep "cpu "';
+ for (let i in result) {
+ for (let j in result[i].pids) {
+ cmd += (';cat /proc/' + result[i].pids[j] + '/stat');
+ }
+ }
+ exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
+ let curr_processes = stdout.toString().split('\n');
-/***/ 87747:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // first line (all - /proc/stat)
+ let all = parseProcStat(curr_processes.shift());
+ // process
+ let list_new = {};
+ let resultProcess = {};
+ curr_processes.forEach((element) => {
+ resultProcess = calcProcStatLinux(element, all, _process_cpu);
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getUserAgentHeaderName = getUserAgentHeaderName;
-exports.getUserAgentValue = getUserAgentValue;
-const userAgentPlatform_js_1 = __nccwpck_require__(72100);
-const constants_js_1 = __nccwpck_require__(91791);
-function getUserAgentString(telemetryInfo) {
- const parts = [];
- for (const [key, value] of telemetryInfo) {
- const token = value ? `${key}/${value}` : key;
- parts.push(token);
- }
- return parts.join(" ");
-}
-/**
- * @internal
- */
-function getUserAgentHeaderName() {
- return (0, userAgentPlatform_js_1.getHeaderName)();
-}
-/**
- * @internal
- */
-async function getUserAgentValue(prefix) {
- const runtimeInfo = new Map();
- runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION);
- await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo);
- const defaultAgent = getUserAgentString(runtimeInfo);
- const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
- return userAgentValue;
-}
-//# sourceMappingURL=userAgent.js.map
+ if (resultProcess.pid) {
-/***/ }),
+ // find result item
+ let resultItemId = -1;
+ for (let i in result) {
+ if (result[i].pids.indexOf(resultProcess.pid) >= 0) {
+ resultItemId = i;
+ }
+ }
+ // store pcpu in outer result
+ if (resultItemId >= 0) {
+ result[resultItemId].cpu += resultProcess.cpuu + resultProcess.cpus;
+ }
-/***/ 72100:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // save new values
+ list_new[resultProcess.pid] = {
+ cpuu: resultProcess.cpuu,
+ cpus: resultProcess.cpus,
+ utime: resultProcess.utime,
+ stime: resultProcess.stime,
+ cutime: resultProcess.cutime,
+ cstime: resultProcess.cstime
+ };
+ }
+ });
+ result.forEach(function (item) {
+ item.cpu = Math.round(item.cpu * 100) / 100;
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getHeaderName = getHeaderName;
-exports.setPlatformSpecificData = setPlatformSpecificData;
-const tslib_1 = __nccwpck_require__(94176);
-const os = tslib_1.__importStar(__nccwpck_require__(48161));
-const process = tslib_1.__importStar(__nccwpck_require__(1708));
-/**
- * @internal
- */
-function getHeaderName() {
- return "User-Agent";
-}
-/**
- * @internal
- */
-async function setPlatformSpecificData(map) {
- if (process && process.versions) {
- const versions = process.versions;
- if (versions.bun) {
- map.set("Bun", versions.bun);
- }
- else if (versions.deno) {
- map.set("Deno", versions.deno);
- }
- else if (versions.node) {
- map.set("Node", versions.node);
+ _process_cpu.all = all;
+ _process_cpu.list = Object.assign({}, list_new);
+ _process_cpu.ms = Date.now() - _process_cpu.ms;
+ _process_cpu.result = Object.assign({}, result);
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
}
- }
- map.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`);
+ }
+ });
+ });
}
-//# sourceMappingURL=userAgentPlatform.js.map
-
-/***/ }),
-
-/***/ 7651:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+exports.processLoad = processLoad;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createTracingClient = exports.useInstrumenter = void 0;
-var instrumenter_js_1 = __nccwpck_require__(7565);
-Object.defineProperty(exports, "useInstrumenter", ({ enumerable: true, get: function () { return instrumenter_js_1.useInstrumenter; } }));
-var tracingClient_js_1 = __nccwpck_require__(30530);
-Object.defineProperty(exports, "createTracingClient", ({ enumerable: true, get: function () { return tracingClient_js_1.createTracingClient; } }));
-//# sourceMappingURL=index.js.map
/***/ }),
-/***/ 7565:
+/***/ 97505:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createDefaultTracingSpan = createDefaultTracingSpan;
-exports.createDefaultInstrumenter = createDefaultInstrumenter;
-exports.useInstrumenter = useInstrumenter;
-exports.getInstrumenter = getInstrumenter;
-const tracingContext_js_1 = __nccwpck_require__(81334);
-const state_js_1 = __nccwpck_require__(53398);
-function createDefaultTracingSpan() {
- return {
- end: () => {
- // noop
- },
- isRecording: () => false,
- recordException: () => {
- // noop
- },
- setAttribute: () => {
- // noop
- },
- setStatus: () => {
- // noop
- },
- addEvent: () => {
- // noop
- },
- };
-}
-function createDefaultInstrumenter() {
- return {
- createRequestHeaders: () => {
- return {};
- },
- parseTraceparentHeader: () => {
- return undefined;
- },
- startSpan: (_name, spanOptions) => {
- return {
- span: createDefaultTracingSpan(),
- tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }),
- };
- },
- withContext(_context, callback, ...callbackArgs) {
- return callback(...callbackArgs);
- },
- };
-}
-/**
- * Extends the Azure SDK with support for a given instrumenter implementation.
- *
- * @param instrumenter - The instrumenter implementation to use.
- */
-function useInstrumenter(instrumenter) {
- state_js_1.state.instrumenterImplementation = instrumenter;
-}
-/**
- * Gets the currently set instrumenter, a No-Op instrumenter by default.
- *
- * @returns The currently set instrumenter
- */
-function getInstrumenter() {
- if (!state_js_1.state.instrumenterImplementation) {
- state_js_1.state.instrumenterImplementation = createDefaultInstrumenter();
- }
- return state_js_1.state.instrumenterImplementation;
-}
-//# sourceMappingURL=instrumenter.js.map
+// @ts-check
+// ==================================================================================
+// system.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 2. System (Hardware, BIOS, Base Board)
+// ----------------------------------------------------------------------------------
-/***/ }),
+const fs = __nccwpck_require__(79896);
+const os = __nccwpck_require__(70857);
+const util = __nccwpck_require__(77496);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const execPromise = util.promisify((__nccwpck_require__(35317).exec));
-/***/ 53398:
-/***/ ((__unused_webpack_module, exports) => {
+let _platform = process.platform;
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.state = void 0;
-/**
- * @internal
- *
- * Holds the singleton instrumenter, to be shared across CJS and ESM imports.
- */
-exports.state = {
- instrumenterImplementation: undefined,
-};
-//# sourceMappingURL=state-cjs.cjs.map
+function system(callback) {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
-/***/ 30530:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ let result = {
+ manufacturer: '',
+ model: 'Computer',
+ version: '',
+ serial: '-',
+ uuid: '-',
+ sku: '-',
+ virtual: false
+ };
+
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ exec('export LC_ALL=C; dmidecode -t system 2>/dev/null; unset LC_ALL', function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ result.manufacturer = cleanDefaults(util.getValue(lines, 'manufacturer'));
+ result.model = cleanDefaults(util.getValue(lines, 'product name'));
+ result.version = cleanDefaults(util.getValue(lines, 'version'));
+ result.serial = cleanDefaults(util.getValue(lines, 'serial number'));
+ result.uuid = cleanDefaults((util.getValue(lines, 'uuid'))).toLowerCase();
+ result.sku = cleanDefaults(util.getValue(lines, 'sku number'));
+ // Non-Root values
+ const cmd = `echo -n "product_name: "; cat /sys/devices/virtual/dmi/id/product_name 2>/dev/null; echo;
+ echo -n "product_serial: "; cat /sys/devices/virtual/dmi/id/product_serial 2>/dev/null; echo;
+ echo -n "product_uuid: "; cat /sys/devices/virtual/dmi/id/product_uuid 2>/dev/null; echo;
+ echo -n "product_version: "; cat /sys/devices/virtual/dmi/id/product_version 2>/dev/null; echo;
+ echo -n "sys_vendor: "; cat /sys/devices/virtual/dmi/id/sys_vendor 2>/dev/null; echo;`;
+ try {
+ lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
+ result.manufacturer = cleanDefaults(result.manufacturer === '' ? util.getValue(lines, 'sys_vendor') : result.manufacturer);
+ result.model = cleanDefaults(result.model === '' ? util.getValue(lines, 'product_name') : result.model);
+ result.version = cleanDefaults(result.version === '' ? util.getValue(lines, 'product_version') : result.version);
+ result.serial = cleanDefaults(result.serial === '' ? util.getValue(lines, 'product_serial') : result.serial);
+ result.uuid = cleanDefaults(result.uuid === '' ? util.getValue(lines, 'product_uuid').toLowerCase() : result.uuid);
+ } catch (e) {
+ util.noop();
+ }
+ if (!result.serial) { result.serial = '-'; }
+ if (!result.manufacturer) { result.manufacturer = ''; }
+ if (!result.model) { result.model = 'Computer'; }
+ if (!result.version) { result.version = ''; }
+ if (!result.sku) { result.sku = '-'; }
+
+ // detect virtual (1)
+ if (result.model.toLowerCase() === 'virtualbox' || result.model.toLowerCase() === 'kvm' || result.model.toLowerCase() === 'virtual machine' || result.model.toLowerCase() === 'bochs' || result.model.toLowerCase().startsWith('vmware') || result.model.toLowerCase().startsWith('droplet')) {
+ result.virtual = true;
+ switch (result.model.toLowerCase()) {
+ case 'virtualbox':
+ result.virtualHost = 'VirtualBox';
+ break;
+ case 'vmware':
+ result.virtualHost = 'VMware';
+ break;
+ case 'kvm':
+ result.virtualHost = 'KVM';
+ break;
+ case 'bochs':
+ result.virtualHost = 'bochs';
+ break;
+ }
+ }
+ if (result.manufacturer.toLowerCase().startsWith('vmware') || result.manufacturer.toLowerCase() === 'xen') {
+ result.virtual = true;
+ switch (result.manufacturer.toLowerCase()) {
+ case 'vmware':
+ result.virtualHost = 'VMware';
+ break;
+ case 'xen':
+ result.virtualHost = 'Xen';
+ break;
+ }
+ }
+ if (!result.virtual) {
+ try {
+ const disksById = execSync('ls -1 /dev/disk/by-id/ 2>/dev/null', util.execOptsLinux).toString();
+ if (disksById.indexOf('_QEMU_') >= 0) {
+ result.virtual = true;
+ result.virtualHost = 'QEMU';
+ }
+ if (disksById.indexOf('_VBOX_') >= 0) {
+ result.virtual = true;
+ result.virtualHost = 'VirtualBox';
+ }
+ } catch (e) {
+ util.noop();
+ }
+ }
+ if (!result.virtual && (os.release().toLowerCase().indexOf('microsoft') >= 0 || os.release().toLowerCase().endsWith('wsl2'))) {
+ const kernelVersion = parseFloat(os.release().toLowerCase());
+ result.virtual = true;
+ result.manufacturer = 'Microsoft';
+ result.model = 'WSL';
+ result.version = kernelVersion < 4.19 ? '1' : '2';
+ }
+ if ((_freebsd || _openbsd || _netbsd) && !result.virtualHost) {
+ try {
+ const procInfo = execSync('dmidecode -t 4', util.execOptsLinux);
+ const procLines = procInfo.toString().split('\n');
+ const procManufacturer = util.getValue(procLines, 'manufacturer', ':', true);
+ switch (procManufacturer.toLowerCase()) {
+ case 'virtualbox':
+ result.virtualHost = 'VirtualBox';
+ break;
+ case 'vmware':
+ result.virtualHost = 'VMware';
+ break;
+ case 'kvm':
+ result.virtualHost = 'KVM';
+ break;
+ case 'bochs':
+ result.virtualHost = 'bochs';
+ break;
+ }
+ } catch (e) {
+ util.noop();
+ }
+ }
+ // detect docker
+ if (fs.existsSync('/.dockerenv') || fs.existsSync('/.dockerinit')) {
+ result.model = 'Docker Container';
+ }
+ try {
+ const stdout = execSync('dmesg 2>/dev/null | grep -iE "virtual|hypervisor" | grep -iE "vmware|qemu|kvm|xen" | grep -viE "Nested Virtualization|/virtual/"');
+ // detect virtual machines
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 0) {
+ if (result.model === 'Computer') { result.model = 'Virtual machine'; }
+ result.virtual = true;
+ if (stdout.toString().toLowerCase().indexOf('vmware') >= 0 && !result.virtualHost) {
+ result.virtualHost = 'VMware';
+ }
+ if (stdout.toString().toLowerCase().indexOf('qemu') >= 0 && !result.virtualHost) {
+ result.virtualHost = 'QEMU';
+ }
+ if (stdout.toString().toLowerCase().indexOf('xen') >= 0 && !result.virtualHost) {
+ result.virtualHost = 'Xen';
+ }
+ if (stdout.toString().toLowerCase().indexOf('kvm') >= 0 && !result.virtualHost) {
+ result.virtualHost = 'KVM';
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
+ if (result.manufacturer === '' && result.model === 'Computer' && result.version === '') {
+ // Check Raspberry Pi
+ fs.readFile('/proc/cpuinfo', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result.model = util.getValue(lines, 'hardware', ':', true).toUpperCase();
+ result.version = util.getValue(lines, 'revision', ':', true).toLowerCase();
+ result.serial = util.getValue(lines, 'serial', ':', true);
+ const model = util.getValue(lines, 'model:', ':', true);
+ // reference values: https://elinux.org/RPi_HardwareHistory
+ // https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
+ if ((result.model === 'BCM2835' || result.model === 'BCM2708' || result.model === 'BCM2709' || result.model === 'BCM2710' || result.model === 'BCM2711' || result.model === 'BCM2836' || result.model === 'BCM2837') && model.toLowerCase().indexOf('raspberry') >= 0) {
+ const rPIRevision = util.decodePiCpuinfo(lines);
+ result.model = rPIRevision.model;
+ result.version = rPIRevision.revisionCode;
+ result.manufacturer = 'Raspberry Pi Foundation';
+ result.raspberry = {
+ manufacturer: rPIRevision.manufacturer,
+ processor: rPIRevision.processor,
+ type: rPIRevision.type,
+ revision: rPIRevision.revision
+ };
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ }
+ if (_darwin) {
+ exec('ioreg -c IOPlatformExpertDevice -d 2', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().replace(/[<>"]/g, '').split('\n');
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createTracingClient = createTracingClient;
-const instrumenter_js_1 = __nccwpck_require__(7565);
-const tracingContext_js_1 = __nccwpck_require__(81334);
-/**
- * Creates a new tracing client.
- *
- * @param options - Options used to configure the tracing client.
- * @returns - An instance of {@link TracingClient}.
- */
-function createTracingClient(options) {
- const { namespace, packageName, packageVersion } = options;
- function startSpan(name, operationOptions, spanOptions) {
- var _a;
- const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName: packageName, packageVersion: packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext }));
- let tracingContext = startSpanResult.tracingContext;
- const span = startSpanResult.span;
- if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) {
- tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace);
- }
- span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace));
- const updatedOptions = Object.assign({}, operationOptions, {
- tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }),
+ const model = util.getAppleModel(util.getValue(lines, 'model', '=', true));
+ // const modelParts = util.splitByNumber(model);
+ // const version = util.getValue(lines, 'version', '=', true);
+ result.manufacturer = util.getValue(lines, 'manufacturer', '=', true);
+ result.model = model.key;
+ result.type = macOsChassisType(model.version);
+ result.version = model.version;
+ result.serial = util.getValue(lines, 'ioplatformserialnumber', '=', true);
+ result.uuid = util.getValue(lines, 'ioplatformuuid', '=', true).toLowerCase();
+ result.sku = util.getValue(lines, 'board-id', '=', true) || util.getValue(lines, 'target-sub-type', '=', true);
+ }
+ if (callback) { callback(result); }
+ resolve(result);
});
- return {
- span,
- updatedOptions,
- };
- }
- async function withSpan(name, operationOptions, callback, spanOptions) {
- const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_windows) {
try {
- const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span)));
- span.setStatus({ status: "success" });
- return result;
- }
- catch (err) {
- span.setStatus({ status: "error", error: err });
- throw err;
- }
- finally {
- span.end();
+ util.powerShell('Get-CimInstance Win32_ComputerSystemProduct | select Name,Vendor,Version,IdentifyingNumber,UUID | fl').then((stdout, error) => {
+ if (!error) {
+ let lines = stdout.split('\r\n');
+ result.manufacturer = util.getValue(lines, 'vendor', ':');
+ result.model = util.getValue(lines, 'name', ':');
+ result.version = util.getValue(lines, 'version', ':');
+ result.serial = util.getValue(lines, 'identifyingnumber', ':');
+ result.uuid = util.getValue(lines, 'uuid', ':').toLowerCase();
+ // detect virtual (1)
+ const model = result.model.toLowerCase();
+ if (model === 'virtualbox' || model === 'kvm' || model === 'virtual machine' || model === 'bochs' || model.startsWith('vmware') || model.startsWith('qemu') || model.startsWith('parallels')) {
+ result.virtual = true;
+ if (model.startsWith('virtualbox')) { result.virtualHost = 'VirtualBox'; }
+ if (model.startsWith('vmware')) { result.virtualHost = 'VMware'; }
+ if (model.startsWith('kvm')) { result.virtualHost = 'KVM'; }
+ if (model.startsWith('bochs')) { result.virtualHost = 'bochs'; }
+ if (model.startsWith('qemu')) { result.virtualHost = 'KVM'; }
+ if (model.startsWith('parallels')) { result.virtualHost = 'Parallels'; }
+ }
+ const manufacturer = result.manufacturer.toLowerCase();
+ if (manufacturer.startsWith('vmware') || manufacturer.startsWith('qemu') || manufacturer === 'xen' || manufacturer.startsWith('parallels')) {
+ result.virtual = true;
+ if (manufacturer.startsWith('vmware')) { result.virtualHost = 'VMware'; }
+ if (manufacturer.startsWith('xen')) { result.virtualHost = 'Xen'; }
+ if (manufacturer.startsWith('qemu')) { result.virtualHost = 'KVM'; }
+ if (manufacturer.startsWith('parallels')) { result.virtualHost = 'Parallels'; }
+ }
+ util.powerShell('Get-CimInstance MS_Systeminformation -Namespace "root/wmi" | select systemsku | fl ').then((stdout, error) => {
+ if (!error) {
+ let lines = stdout.split('\r\n');
+ result.sku = util.getValue(lines, 'systemsku', ':');
+ }
+ if (!result.virtual) {
+ util.powerShell('Get-CimInstance Win32_bios | select Version, SerialNumber, SMBIOSBIOSVersion').then((stdout, error) => {
+ if (!error) {
+ let lines = stdout.toString();
+ if (lines.indexOf('VRTUAL') >= 0 || lines.indexOf('A M I ') >= 0 || lines.indexOf('VirtualBox') >= 0 || lines.indexOf('VMWare') >= 0 || lines.indexOf('Xen') >= 0 || lines.indexOf('Parallels') >= 0) {
+ result.virtual = true;
+ if (lines.indexOf('VirtualBox') >= 0 && !result.virtualHost) {
+ result.virtualHost = 'VirtualBox';
+ }
+ if (lines.indexOf('VMware') >= 0 && !result.virtualHost) {
+ result.virtualHost = 'VMware';
+ }
+ if (lines.indexOf('Xen') >= 0 && !result.virtualHost) {
+ result.virtualHost = 'Xen';
+ }
+ if (lines.indexOf('VRTUAL') >= 0 && !result.virtualHost) {
+ result.virtualHost = 'Hyper-V';
+ }
+ if (lines.indexOf('A M I') >= 0 && !result.virtualHost) {
+ result.virtualHost = 'Virtual PC';
+ }
+ if (lines.indexOf('Parallels') >= 0 && !result.virtualHost) {
+ result.virtualHost = 'Parallels';
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- }
- function withContext(context, callback, ...callbackArgs) {
- return (0, instrumenter_js_1.getInstrumenter)().withContext(context, callback, ...callbackArgs);
- }
- /**
- * Parses a traceparent header value into a span identifier.
- *
- * @param traceparentHeader - The traceparent header to parse.
- * @returns An implementation-specific identifier for the span.
- */
- function parseTraceparentHeader(traceparentHeader) {
- return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader);
- }
- /**
- * Creates a set of request headers to propagate tracing information to a backend.
- *
- * @param tracingContext - The context containing the span to serialize.
- * @returns The set of headers to add to a request.
- */
- function createRequestHeaders(tracingContext) {
- return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext);
- }
- return {
- startSpan,
- withSpan,
- withContext,
- parseTraceparentHeader,
- createRequestHeaders,
- };
+ }
+ });
+ });
}
-//# sourceMappingURL=tracingClient.js.map
-
-/***/ }),
-
-/***/ 81334:
-/***/ ((__unused_webpack_module, exports) => {
+exports.system = system;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TracingContextImpl = exports.knownContextKeys = void 0;
-exports.createTracingContext = createTracingContext;
-/** @internal */
-exports.knownContextKeys = {
- span: Symbol.for("@azure/core-tracing span"),
- namespace: Symbol.for("@azure/core-tracing namespace"),
-};
-/**
- * Creates a new {@link TracingContext} with the given options.
- * @param options - A set of known keys that may be set on the context.
- * @returns A new {@link TracingContext} with the given options.
- *
- * @internal
- */
-function createTracingContext(options = {}) {
- let context = new TracingContextImpl(options.parentContext);
- if (options.span) {
- context = context.setValue(exports.knownContextKeys.span, options.span);
- }
- if (options.namespace) {
- context = context.setValue(exports.knownContextKeys.namespace, options.namespace);
- }
- return context;
-}
-/** @internal */
-class TracingContextImpl {
- constructor(initialContext) {
- this._contextMap =
- initialContext instanceof TracingContextImpl
- ? new Map(initialContext._contextMap)
- : new Map();
- }
- setValue(key, value) {
- const newContext = new TracingContextImpl(this);
- newContext._contextMap.set(key, value);
- return newContext;
- }
- getValue(key) {
- return this._contextMap.get(key);
- }
- deleteValue(key) {
- const newContext = new TracingContextImpl(this);
- newContext._contextMap.delete(key);
- return newContext;
- }
+function cleanDefaults(s) {
+ const cmpStr = s.toLowerCase();
+ if (cmpStr.indexOf('o.e.m.') === -1 && cmpStr.indexOf('default string') === -1 && cmpStr !== 'default') {
+ return s || '';
+ }
+ return '';
}
-exports.TracingContextImpl = TracingContextImpl;
-//# sourceMappingURL=tracingContext.js.map
-
-/***/ }),
+function bios(callback) {
-/***/ 86805:
-/***/ ((__unused_webpack_module, exports) => {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ vendor: '',
+ version: '',
+ releaseDate: '',
+ revision: '',
+ };
+ let cmd = '';
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ if (process.arch === 'arm') {
+ cmd = 'cat /proc/cpuinfo | grep Serial';
+ } else {
+ cmd = 'export LC_ALL=C; dmidecode -t bios 2>/dev/null; unset LC_ALL';
+ }
+ exec(cmd, function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ result.vendor = util.getValue(lines, 'Vendor');
+ result.version = util.getValue(lines, 'Version');
+ let datetime = util.getValue(lines, 'Release Date');
+ result.releaseDate = util.parseDateTime(datetime).date;
+ result.revision = util.getValue(lines, 'BIOS Revision');
+ result.serial = util.getValue(lines, 'SerialNumber');
+ let language = util.getValue(lines, 'Currently Installed Language').split('|')[0];
+ if (language) {
+ result.language = language;
+ }
+ if (lines.length && stdout.toString().indexOf('Characteristics:') >= 0) {
+ const features = [];
+ lines.forEach(line => {
+ if (line.indexOf(' is supported') >= 0) {
+ const feature = line.split(' is supported')[0].trim();
+ features.push(feature);
+ }
+ });
+ result.features = features;
+ }
+ // Non-Root values
+ const cmd = `echo -n "bios_date: "; cat /sys/devices/virtual/dmi/id/bios_date 2>/dev/null; echo;
+ echo -n "bios_vendor: "; cat /sys/devices/virtual/dmi/id/bios_vendor 2>/dev/null; echo;
+ echo -n "bios_version: "; cat /sys/devices/virtual/dmi/id/bios_version 2>/dev/null; echo;`;
+ try {
+ lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
+ result.vendor = !result.vendor ? util.getValue(lines, 'bios_vendor') : result.vendor;
+ result.version = !result.version ? util.getValue(lines, 'bios_version') : result.version;
+ datetime = util.getValue(lines, 'bios_date');
+ result.releaseDate = !result.releaseDate ? util.parseDateTime(datetime).date : result.releaseDate;
+ } catch (e) {
+ util.noop();
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ result.vendor = 'Apple Inc.';
+ exec(
+ 'system_profiler SPHardwareDataType -json', function (error, stdout) {
+ try {
+ const hardwareData = JSON.parse(stdout.toString());
+ if (hardwareData && hardwareData.SPHardwareDataType && hardwareData.SPHardwareDataType.length) {
+ let bootRomVersion = hardwareData.SPHardwareDataType[0].boot_rom_version;
+ bootRomVersion = bootRomVersion ? bootRomVersion.split('(')[0].trim() : null;
+ result.version = bootRomVersion;
+ }
+ } catch (e) {
+ util.noop();
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ result.vendor = 'Sun Microsystems';
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_windows) {
+ try {
+ util.powerShell('Get-CimInstance Win32_bios | select Description,Version,Manufacturer,@{n="ReleaseDate";e={$_.ReleaseDate.ToString("yyyy-MM-dd")}},BuildNumber,SerialNumber,SMBIOSBIOSVersion | fl').then((stdout, error) => {
+ if (!error) {
+ let lines = stdout.toString().split('\r\n');
+ const description = util.getValue(lines, 'description', ':');
+ const version = util.getValue(lines, 'SMBIOSBIOSVersion', ':');
+ if (description.indexOf(' Version ') !== -1) {
+ // ... Phoenix ROM BIOS PLUS Version 1.10 A04
+ result.vendor = description.split(' Version ')[0].trim();
+ result.version = description.split(' Version ')[1].trim();
+ } else if (description.indexOf(' Ver: ') !== -1) {
+ // ... BIOS Date: 06/27/16 17:50:16 Ver: 1.4.5
+ result.vendor = util.getValue(lines, 'manufacturer', ':');
+ result.version = description.split(' Ver: ')[1].trim();
+ } else {
+ result.vendor = util.getValue(lines, 'manufacturer', ':');
+ result.version = version || util.getValue(lines, 'version', ':');
+ }
+ result.releaseDate = util.getValue(lines, 'releasedate', ':');
+ result.revision = util.getValue(lines, 'buildnumber', ':');
+ result.serial = cleanDefaults(util.getValue(lines, 'serialnumber', ':'));
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.cancelablePromiseRace = cancelablePromiseRace;
-/**
- * promise.race() wrapper that aborts rest of promises as soon as the first promise settles.
- */
-async function cancelablePromiseRace(abortablePromiseBuilders, options) {
- var _a, _b;
- const aborter = new AbortController();
- function abortHandler() {
- aborter.abort();
- }
- (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler);
- try {
- return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal })));
- }
- finally {
- aborter.abort();
- (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler);
- }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ });
+ });
}
-//# sourceMappingURL=aborterUtils.js.map
-/***/ }),
+exports.bios = bios;
-/***/ 84073:
-/***/ ((__unused_webpack_module, exports) => {
+function baseboard(callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.uint8ArrayToString = uint8ArrayToString;
-exports.stringToUint8Array = stringToUint8Array;
-/**
- * The helper that transforms bytes with specific character encoding into string
- * @param bytes - the uint8array bytes
- * @param format - the format we use to encode the byte
- * @returns a string of the encoded string
- */
-function uint8ArrayToString(bytes, format) {
- return Buffer.from(bytes).toString(format);
-}
-/**
- * The helper that transforms string to specific character encoded bytes array.
- * @param value - the string to be converted
- * @param format - the format we use to decode the value
- * @returns a uint8array
- */
-function stringToUint8Array(value, format) {
- return Buffer.from(value, format);
-}
-//# sourceMappingURL=bytesEncoding.js.map
+ let result = {
+ manufacturer: '',
+ model: '',
+ version: '',
+ serial: '-',
+ assetTag: '-',
+ memMax: null,
+ memSlots: null
+ };
+ let cmd = '';
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ if (process.arch === 'arm') {
+ cmd = 'cat /proc/cpuinfo | grep Serial';
+ // 'BCM2709', 'BCM2835', 'BCM2708' -->
+ } else {
+ cmd = 'export LC_ALL=C; dmidecode -t 2 2>/dev/null; unset LC_ALL';
+ }
+ const workload = [];
+ workload.push(execPromise(cmd));
+ workload.push(execPromise('export LC_ALL=C; dmidecode -t memory 2>/dev/null'));
+ util.promiseAll(
+ workload
+ ).then((data) => {
+ let lines = data.results[0] ? data.results[0].toString().split('\n') : [''];
+ result.manufacturer = cleanDefaults(util.getValue(lines, 'Manufacturer'));
+ result.model = cleanDefaults(util.getValue(lines, 'Product Name'));
+ result.version = cleanDefaults(util.getValue(lines, 'Version'));
+ result.serial = cleanDefaults(util.getValue(lines, 'Serial Number'));
+ result.assetTag = cleanDefaults(util.getValue(lines, 'Asset Tag'));
+ // Non-Root values
+ const cmd = `echo -n "board_asset_tag: "; cat /sys/devices/virtual/dmi/id/board_asset_tag 2>/dev/null; echo;
+ echo -n "board_name: "; cat /sys/devices/virtual/dmi/id/board_name 2>/dev/null; echo;
+ echo -n "board_serial: "; cat /sys/devices/virtual/dmi/id/board_serial 2>/dev/null; echo;
+ echo -n "board_vendor: "; cat /sys/devices/virtual/dmi/id/board_vendor 2>/dev/null; echo;
+ echo -n "board_version: "; cat /sys/devices/virtual/dmi/id/board_version 2>/dev/null; echo;`;
+ try {
+ lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
+ result.manufacturer = cleanDefaults(!result.manufacturer ? util.getValue(lines, 'board_vendor') : result.manufacturer);
+ result.model = cleanDefaults(!result.model ? util.getValue(lines, 'board_name') : result.model);
+ result.version = cleanDefaults(!result.version ? util.getValue(lines, 'board_version') : result.version);
+ result.serial = cleanDefaults(!result.serial ? util.getValue(lines, 'board_serial') : result.serial);
+ result.assetTag = cleanDefaults(!result.assetTag ? util.getValue(lines, 'board_asset_tag') : result.assetTag);
+ } catch (e) {
+ util.noop();
+ }
-/***/ }),
+ // mem
+ lines = data.results[1] ? data.results[1].toString().split('\n') : [''];
+ result.memMax = util.toInt(util.getValue(lines, 'Maximum Capacity')) * 1024 * 1024 * 1024 || null;
+ result.memSlots = util.toInt(util.getValue(lines, 'Number Of Devices')) || null;
+
+ // raspberry
+ let linesRpi = '';
+ try {
+ linesRpi = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
+ } catch (e) {
+ util.noop();
+ }
+ if (linesRpi) {
+ const hardware = util.getValue(linesRpi, 'hardware');
+ if (hardware.startsWith('BCM')) {
+ const rpi = util.decodePiCpuinfo(linesRpi);
+ result.manufacturer = rpi.manufacturer;
+ result.model = 'Raspberry Pi';
+ result.serial = rpi.serial;
+ result.version = rpi.type + ' - ' + rpi.revision;
+ result.memMax = os.totalmem();
+ result.memSlots = 0;
+ }
+ }
-/***/ 2910:
-/***/ ((__unused_webpack_module, exports) => {
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ const workload = [];
+ workload.push(execPromise('ioreg -c IOPlatformExpertDevice -d 2'));
+ workload.push(execPromise('system_profiler SPMemoryDataType'));
+ util.promiseAll(
+ workload
+ ).then((data) => {
+ let lines = data.results[0] ? data.results[0].toString().replace(/[<>"]/g, '').split('\n') : [''];
+ result.manufacturer = util.getValue(lines, 'manufacturer', '=', true);
+ result.model = util.getValue(lines, 'model', '=', true);
+ result.version = util.getValue(lines, 'version', '=', true);
+ result.serial = util.getValue(lines, 'ioplatformserialnumber', '=', true);
+ result.assetTag = util.getValue(lines, 'board-id', '=', true);
+ // mem
+ let devices = data.results[1] ? data.results[1].toString().split(' BANK ') : [''];
+ if (devices.length === 1) {
+ devices = data.results[1] ? data.results[1].toString().split(' DIMM') : [''];
+ }
+ devices.shift();
+ result.memSlots = devices.length;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-var _a, _b, _c, _d;
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isReactNative = exports.isNodeRuntime = exports.isNode = exports.isNodeLike = exports.isBun = exports.isDeno = exports.isWebWorker = exports.isBrowser = void 0;
-/**
- * A constant that indicates whether the environment the code is running is a Web Browser.
- */
-// eslint-disable-next-line @azure/azure-sdk/ts-no-window
-exports.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
-/**
- * A constant that indicates whether the environment the code is running is a Web Worker.
- */
-exports.isWebWorker = typeof self === "object" &&
- typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" &&
- (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" ||
- ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" ||
- ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope");
-/**
- * A constant that indicates whether the environment the code is running is Deno.
- */
-exports.isDeno = typeof Deno !== "undefined" &&
- typeof Deno.version !== "undefined" &&
- typeof Deno.version.deno !== "undefined";
-/**
- * A constant that indicates whether the environment the code is running is Bun.sh.
- */
-exports.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
-/**
- * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
- */
-exports.isNodeLike = typeof globalThis.process !== "undefined" &&
- Boolean(globalThis.process.version) &&
- Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node);
-/**
- * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
- * @deprecated Use `isNodeLike` instead.
- */
-exports.isNode = exports.isNodeLike;
-/**
- * A constant that indicates whether the environment the code is running is Node.JS.
- */
-exports.isNodeRuntime = exports.isNodeLike && !exports.isBun && !exports.isDeno;
-/**
- * A constant that indicates whether the environment the code is running is in React-Native.
- */
-// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js
-exports.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative";
-//# sourceMappingURL=checkEnvironment.js.map
+ if (os.arch() === 'arm64') {
+ result.memSlots = 0;
+ result.memMax = os.totalmem();
+ }
-/***/ }),
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_windows) {
+ try {
+ const workload = [];
+ const win10plus = parseInt(os.release()) >= 10;
+ const maxCapacityAttribute = win10plus ? 'MaxCapacityEx' : 'MaxCapacity';
+ workload.push(util.powerShell('Get-CimInstance Win32_baseboard | select Model,Manufacturer,Product,Version,SerialNumber,PartNumber,SKU | fl'));
+ workload.push(util.powerShell(`Get-CimInstance Win32_physicalmemoryarray | select ${maxCapacityAttribute}, MemoryDevices | fl`));
+ util.promiseAll(
+ workload
+ ).then((data) => {
+ let lines = data.results[0] ? data.results[0].toString().split('\r\n') : [''];
-/***/ 33716:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ result.manufacturer = cleanDefaults(util.getValue(lines, 'manufacturer', ':'));
+ result.model = cleanDefaults(util.getValue(lines, 'model', ':'));
+ if (!result.model) {
+ result.model = cleanDefaults(util.getValue(lines, 'product', ':'));
+ }
+ result.version = cleanDefaults(util.getValue(lines, 'version', ':'));
+ result.serial = cleanDefaults(util.getValue(lines, 'serialnumber', ':'));
+ result.assetTag = cleanDefaults(util.getValue(lines, 'partnumber', ':'));
+ if (!result.assetTag) {
+ result.assetTag = cleanDefaults(util.getValue(lines, 'sku', ':'));
+ }
+ // memphysical
+ lines = data.results[1] ? data.results[1].toString().split('\r\n') : [''];
+ result.memMax = util.toInt(util.getValue(lines, maxCapacityAttribute, ':')) * (win10plus ? 1024 : 1) || null;
+ result.memSlots = util.toInt(util.getValue(lines, 'MemoryDevices', ':')) || null;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createAbortablePromise = createAbortablePromise;
-const abort_controller_1 = __nccwpck_require__(92242);
-/**
- * Creates an abortable promise.
- * @param buildPromise - A function that takes the resolve and reject functions as parameters.
- * @param options - The options for the abortable promise.
- * @returns A promise that can be aborted.
- */
-function createAbortablePromise(buildPromise, options) {
- const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
- return new Promise((resolve, reject) => {
- function rejectOnAbort() {
- reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted."));
- }
- function removeListeners() {
- abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort);
- }
- function onAbort() {
- cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort();
- removeListeners();
- rejectOnAbort();
- }
- if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) {
- return rejectOnAbort();
- }
- try {
- buildPromise((x) => {
- removeListeners();
- resolve(x);
- }, (x) => {
- removeListeners();
- reject(x);
- });
- }
- catch (err) {
- reject(err);
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort);
+ }
});
+ });
}
-//# sourceMappingURL=createAbortablePromise.js.map
-
-/***/ }),
-
-/***/ 54744:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+exports.baseboard = baseboard;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.delay = delay;
-exports.calculateRetryDelay = calculateRetryDelay;
-const createAbortablePromise_js_1 = __nccwpck_require__(33716);
-const random_js_1 = __nccwpck_require__(50832);
-const StandardAbortMessage = "The delay was aborted.";
-/**
- * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.
- * @param timeInMs - The number of milliseconds to be delayed.
- * @param options - The options for delay - currently abort options
- * @returns Promise that is resolved after timeInMs
- */
-function delay(timeInMs, options) {
- let token;
- const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
- return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve) => {
- token = setTimeout(resolve, timeInMs);
- }, {
- cleanupBeforeAbort: () => clearTimeout(token),
- abortSignal,
- abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage,
- });
-}
-/**
- * Calculates the delay interval for retry attempts using exponential delay with jitter.
- * @param retryAttempt - The current retry attempt number.
- * @param config - The exponential retry configuration.
- * @returns An object containing the calculated retry delay.
- */
-function calculateRetryDelay(retryAttempt, config) {
- // Exponentially increase the delay each time
- const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
- // Don't let the delay exceed the maximum
- const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
- // Allow the final value to have some "jitter" (within 50% of the delay size) so
- // that retries across multiple clients don't occur simultaneously.
- const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2);
- return { retryAfterInMs };
+function macOsChassisType(model) {
+ model = model.toLowerCase();
+ if (model.indexOf('macbookair') >= 0 || model.indexOf('macbook air') >= 0) { return 'Notebook'; }
+ if (model.indexOf('macbookpro') >= 0 || model.indexOf('macbook pro') >= 0) { return 'Notebook'; }
+ if (model.indexOf('macbook') >= 0) { return 'Notebook'; }
+ if (model.indexOf('macmini') >= 0 || model.indexOf('mac mini') >= 0) { return 'Desktop'; }
+ if (model.indexOf('imac') >= 0) { return 'Desktop'; }
+ if (model.indexOf('macstudio') >= 0 || model.indexOf('mac studio') >= 0) { return 'Desktop'; }
+ if (model.indexOf('macpro') >= 0 || model.indexOf('mac pro') >= 0) { return 'Tower'; }
+ return 'Other';
}
-//# sourceMappingURL=delay.js.map
-/***/ }),
+function chassis(callback) {
+ const chassisTypes = ['Other',
+ 'Unknown',
+ 'Desktop',
+ 'Low Profile Desktop',
+ 'Pizza Box',
+ 'Mini Tower',
+ 'Tower',
+ 'Portable',
+ 'Laptop',
+ 'Notebook',
+ 'Hand Held',
+ 'Docking Station',
+ 'All in One',
+ 'Sub Notebook',
+ 'Space-Saving',
+ 'Lunch Box',
+ 'Main System Chassis',
+ 'Expansion Chassis',
+ 'SubChassis',
+ 'Bus Expansion Chassis',
+ 'Peripheral Chassis',
+ 'Storage Chassis',
+ 'Rack Mount Chassis',
+ 'Sealed-Case PC',
+ 'Multi-System Chassis',
+ 'Compact PCI',
+ 'Advanced TCA',
+ 'Blade',
+ 'Blade Enclosure',
+ 'Tablet',
+ 'Convertible',
+ 'Detachable',
+ 'IoT Gateway ',
+ 'Embedded PC',
+ 'Mini PC',
+ 'Stick PC',
+ ];
-/***/ 69213:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ manufacturer: '',
+ model: '',
+ type: '',
+ version: '',
+ serial: '-',
+ assetTag: '-',
+ sku: '',
+ };
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ const cmd = `echo -n "chassis_asset_tag: "; cat /sys/devices/virtual/dmi/id/chassis_asset_tag 2>/dev/null; echo;
+ echo -n "chassis_serial: "; cat /sys/devices/virtual/dmi/id/chassis_serial 2>/dev/null; echo;
+ echo -n "chassis_type: "; cat /sys/devices/virtual/dmi/id/chassis_type 2>/dev/null; echo;
+ echo -n "chassis_vendor: "; cat /sys/devices/virtual/dmi/id/chassis_vendor 2>/dev/null; echo;
+ echo -n "chassis_version: "; cat /sys/devices/virtual/dmi/id/chassis_version 2>/dev/null; echo;`;
+ exec(cmd, function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ result.manufacturer = cleanDefaults(util.getValue(lines, 'chassis_vendor'));
+ const ctype = parseInt(util.getValue(lines, 'chassis_type').replace(/\D/g, ''));
+ result.type = cleanDefaults((ctype && !isNaN(ctype) && ctype < chassisTypes.length) ? chassisTypes[ctype - 1] : '');
+ result.version = cleanDefaults(util.getValue(lines, 'chassis_version'));
+ result.serial = cleanDefaults(util.getValue(lines, 'chassis_serial'));
+ result.assetTag = cleanDefaults(util.getValue(lines, 'chassis_asset_tag'));
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isError = isError;
-exports.getErrorMessage = getErrorMessage;
-const object_js_1 = __nccwpck_require__(15360);
-/**
- * Typeguard for an error object shape (has name and message)
- * @param e - Something caught by a catch clause.
- */
-function isError(e) {
- if ((0, object_js_1.isObject)(e)) {
- const hasName = typeof e.name === "string";
- const hasMessage = typeof e.message === "string";
- return hasName && hasMessage;
- }
- return false;
-}
-/**
- * Given what is thought to be an error object, return the message if possible.
- * If the message is missing, returns a stringified version of the input.
- * @param e - Something thrown from a try block
- * @returns The error message or a string of the input
- */
-function getErrorMessage(e) {
- if (isError(e)) {
- return e.message;
- }
- else {
- let stringified;
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ exec('ioreg -c IOPlatformExpertDevice -d 2', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().replace(/[<>"]/g, '').split('\n');
+ const model = util.getAppleModel(util.getValue(lines, 'model', '=', true));
+ // const modelParts = util.splitByNumber(model);
+ // const version = util.getValue(lines, 'version', '=', true);
+ result.manufacturer = util.getValue(lines, 'manufacturer', '=', true);
+ result.model = model.key;
+ result.type = macOsChassisType(model.model);
+ result.version = model.version;
+ result.serial = util.getValue(lines, 'ioplatformserialnumber', '=', true);
+ result.assetTag = util.getValue(lines, 'board-id', '=', true) || util.getValue(lines, 'target-type', '=', true);
+ result.sku = util.getValue(lines, 'target-sub-type', '=', true);
+ }
+
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_windows) {
try {
- if (typeof e === "object" && e) {
- stringified = JSON.stringify(e);
- }
- else {
- stringified = String(e);
+ util.powerShell('Get-CimInstance Win32_SystemEnclosure | select Model,Manufacturer,ChassisTypes,Version,SerialNumber,PartNumber,SKU,SMBIOSAssetTag | fl').then((stdout, error) => {
+ if (!error) {
+ let lines = stdout.toString().split('\r\n');
+
+ result.manufacturer = cleanDefaults(util.getValue(lines, 'manufacturer', ':'));
+ result.model = cleanDefaults(util.getValue(lines, 'model', ':'));
+ const ctype = parseInt(util.getValue(lines, 'ChassisTypes', ':').replace(/\D/g, ''));
+ result.type = (ctype && !isNaN(ctype) && ctype < chassisTypes.length) ? chassisTypes[ctype - 1] : '';
+ result.version = cleanDefaults(util.getValue(lines, 'version', ':'));
+ result.serial = cleanDefaults(util.getValue(lines, 'serialnumber', ':'));
+ result.assetTag = cleanDefaults(util.getValue(lines, 'partnumber', ':'));
+ if (!result.assetTag) {
+ result.assetTag = cleanDefaults(util.getValue(lines, 'SMBIOSAssetTag', ':'));
+ }
+ result.sku = cleanDefaults(util.getValue(lines, 'sku', ':'));
}
+
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- catch (err) {
- stringified = "[unable to stringify input]";
- }
- return `Unknown error ${stringified}`;
- }
+ }
+ });
+ });
}
-//# sourceMappingURL=error.js.map
+
+exports.chassis = chassis;
+
/***/ }),
-/***/ 30991:
+/***/ 76748:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.stringToUint8Array = exports.uint8ArrayToString = exports.isWebWorker = exports.isReactNative = exports.isDeno = exports.isNodeRuntime = exports.isNodeLike = exports.isNode = exports.isBun = exports.isBrowser = exports.randomUUID = exports.objectHasProperty = exports.isObjectWithProperties = exports.isDefined = exports.computeSha256Hmac = exports.computeSha256Hash = exports.getErrorMessage = exports.isError = exports.isObject = exports.getRandomIntegerInclusive = exports.createAbortablePromise = exports.cancelablePromiseRace = exports.calculateRetryDelay = exports.delay = void 0;
-var delay_js_1 = __nccwpck_require__(54744);
-Object.defineProperty(exports, "delay", ({ enumerable: true, get: function () { return delay_js_1.delay; } }));
-Object.defineProperty(exports, "calculateRetryDelay", ({ enumerable: true, get: function () { return delay_js_1.calculateRetryDelay; } }));
-var aborterUtils_js_1 = __nccwpck_require__(86805);
-Object.defineProperty(exports, "cancelablePromiseRace", ({ enumerable: true, get: function () { return aborterUtils_js_1.cancelablePromiseRace; } }));
-var createAbortablePromise_js_1 = __nccwpck_require__(33716);
-Object.defineProperty(exports, "createAbortablePromise", ({ enumerable: true, get: function () { return createAbortablePromise_js_1.createAbortablePromise; } }));
-var random_js_1 = __nccwpck_require__(50832);
-Object.defineProperty(exports, "getRandomIntegerInclusive", ({ enumerable: true, get: function () { return random_js_1.getRandomIntegerInclusive; } }));
-var object_js_1 = __nccwpck_require__(15360);
-Object.defineProperty(exports, "isObject", ({ enumerable: true, get: function () { return object_js_1.isObject; } }));
-var error_js_1 = __nccwpck_require__(69213);
-Object.defineProperty(exports, "isError", ({ enumerable: true, get: function () { return error_js_1.isError; } }));
-Object.defineProperty(exports, "getErrorMessage", ({ enumerable: true, get: function () { return error_js_1.getErrorMessage; } }));
-var sha256_js_1 = __nccwpck_require__(83712);
-Object.defineProperty(exports, "computeSha256Hash", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hash; } }));
-Object.defineProperty(exports, "computeSha256Hmac", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hmac; } }));
-var typeGuards_js_1 = __nccwpck_require__(98489);
-Object.defineProperty(exports, "isDefined", ({ enumerable: true, get: function () { return typeGuards_js_1.isDefined; } }));
-Object.defineProperty(exports, "isObjectWithProperties", ({ enumerable: true, get: function () { return typeGuards_js_1.isObjectWithProperties; } }));
-Object.defineProperty(exports, "objectHasProperty", ({ enumerable: true, get: function () { return typeGuards_js_1.objectHasProperty; } }));
-var uuidUtils_js_1 = __nccwpck_require__(50751);
-Object.defineProperty(exports, "randomUUID", ({ enumerable: true, get: function () { return uuidUtils_js_1.randomUUID; } }));
-var checkEnvironment_js_1 = __nccwpck_require__(2910);
-Object.defineProperty(exports, "isBrowser", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBrowser; } }));
-Object.defineProperty(exports, "isBun", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBun; } }));
-Object.defineProperty(exports, "isNode", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNode; } }));
-Object.defineProperty(exports, "isNodeLike", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNodeLike; } }));
-Object.defineProperty(exports, "isNodeRuntime", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNodeRuntime; } }));
-Object.defineProperty(exports, "isDeno", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isDeno; } }));
-Object.defineProperty(exports, "isReactNative", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isReactNative; } }));
-Object.defineProperty(exports, "isWebWorker", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isWebWorker; } }));
-var bytesEncoding_js_1 = __nccwpck_require__(84073);
-Object.defineProperty(exports, "uint8ArrayToString", ({ enumerable: true, get: function () { return bytesEncoding_js_1.uint8ArrayToString; } }));
-Object.defineProperty(exports, "stringToUint8Array", ({ enumerable: true, get: function () { return bytesEncoding_js_1.stringToUint8Array; } }));
-//# sourceMappingURL=index.js.map
+// @ts-check
+// ==================================================================================
+// usb.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 16. usb
+// ----------------------------------------------------------------------------------
-/***/ }),
+const exec = (__nccwpck_require__(35317).exec);
+const util = __nccwpck_require__(77496);
-/***/ 15360:
-/***/ ((__unused_webpack_module, exports) => {
+let _platform = process.platform;
+
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+function getLinuxUsbType(type, name) {
+ let result = type;
+ const str = (name + ' ' + type).toLowerCase();
+ if (str.indexOf('camera') >= 0) { result = 'Camera'; }
+ else if (str.indexOf('hub') >= 0) { result = 'Hub'; }
+ else if (str.indexOf('keybrd') >= 0) { result = 'Keyboard'; }
+ else if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
+ else if (str.indexOf('mouse') >= 0) { result = 'Mouse'; }
+ else if (str.indexOf('stora') >= 0) { result = 'Storage'; }
+ else if (str.indexOf('microp') >= 0) { result = 'Microphone'; }
+ else if (str.indexOf('headset') >= 0) { result = 'Audio'; }
+ else if (str.indexOf('audio') >= 0) { result = 'Audio'; }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isObject = isObject;
-/**
- * Helper to determine when an input is a generic JS object.
- * @returns true when input is an object type that is not null, Array, RegExp, or Date.
- */
-function isObject(input) {
- return (typeof input === "object" &&
- input !== null &&
- !Array.isArray(input) &&
- !(input instanceof RegExp) &&
- !(input instanceof Date));
+ return result;
}
-//# sourceMappingURL=object.js.map
-/***/ }),
+function parseLinuxUsb(usb) {
+ const result = {};
+ const lines = usb.split('\n');
+ if (lines && lines.length && lines[0].indexOf('Device') >= 0) {
+ const parts = lines[0].split(' ');
+ result.bus = parseInt(parts[0], 10);
+ if (parts[2]) {
+ result.deviceId = parseInt(parts[2], 10);
+ } else {
+ result.deviceId = null;
+ }
+ } else {
+ result.bus = null;
+ result.deviceId = null;
+ }
+ const idVendor = util.getValue(lines, 'idVendor', ' ', true).trim();
+ let vendorParts = idVendor.split(' ');
+ vendorParts.shift();
+ const vendor = vendorParts.join(' ');
+
+ const idProduct = util.getValue(lines, 'idProduct', ' ', true).trim();
+ let productParts = idProduct.split(' ');
+ productParts.shift();
+ const product = productParts.join(' ');
+
+ const interfaceClass = util.getValue(lines, 'bInterfaceClass', ' ', true).trim();
+ let interfaceClassParts = interfaceClass.split(' ');
+ interfaceClassParts.shift();
+ const usbType = interfaceClassParts.join(' ');
+
+ const iManufacturer = util.getValue(lines, 'iManufacturer', ' ', true).trim();
+ let iManufacturerParts = iManufacturer.split(' ');
+ iManufacturerParts.shift();
+ const manufacturer = iManufacturerParts.join(' ');
+
+ const iSerial = util.getValue(lines, 'iSerial', ' ', true).trim();
+ let iSerialParts = iSerial.split(' ');
+ iSerialParts.shift();
+ const serial = iSerialParts.join(' ');
-/***/ 50832:
-/***/ ((__unused_webpack_module, exports) => {
+ result.id = (idVendor.startsWith('0x') ? idVendor.split(' ')[0].substr(2, 10) : '') + ':' + (idProduct.startsWith('0x') ? idProduct.split(' ')[0].substr(2, 10) : '');
+ result.name = product;
+ result.type = getLinuxUsbType(usbType, product);
+ result.removable = null;
+ result.vendor = vendor;
+ result.manufacturer = manufacturer;
+ result.maxPower = util.getValue(lines, 'MaxPower', ' ', true);
+ result.serialNumber = serial;
+ return result;
+}
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getRandomIntegerInclusive = getRandomIntegerInclusive;
-/**
- * Returns a random integer value between a lower and upper bound,
- * inclusive of both bounds.
- * Note that this uses Math.random and isn't secure. If you need to use
- * this for any kind of security purpose, find a better source of random.
- * @param min - The smallest integer value allowed.
- * @param max - The largest integer value allowed.
- */
-function getRandomIntegerInclusive(min, max) {
- // Make sure inputs are integers.
- min = Math.ceil(min);
- max = Math.floor(max);
- // Pick a random offset from zero to the size of the range.
- // Since Math.random() can never return 1, we have to make the range one larger
- // in order to be inclusive of the maximum value after we take the floor.
- const offset = Math.floor(Math.random() * (max - min + 1));
- return offset + min;
+function getDarwinUsbType(name) {
+ let result = '';
+ if (name.indexOf('camera') >= 0) { result = 'Camera'; }
+ else if (name.indexOf('touch bar') >= 0) { result = 'Touch Bar'; }
+ else if (name.indexOf('controller') >= 0) { result = 'Controller'; }
+ else if (name.indexOf('headset') >= 0) { result = 'Audio'; }
+ else if (name.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
+ else if (name.indexOf('trackpad') >= 0) { result = 'Trackpad'; }
+ else if (name.indexOf('sensor') >= 0) { result = 'Sensor'; }
+ else if (name.indexOf('bthusb') >= 0) { result = 'Bluetooth'; }
+ else if (name.indexOf('bth') >= 0) { result = 'Bluetooth'; }
+ else if (name.indexOf('rfcomm') >= 0) { result = 'Bluetooth'; }
+ else if (name.indexOf('usbhub') >= 0) { result = 'Hub'; }
+ else if (name.indexOf(' hub') >= 0) { result = 'Hub'; }
+ else if (name.indexOf('mouse') >= 0) { result = 'Mouse'; }
+ else if (name.indexOf('microp') >= 0) { result = 'Microphone'; }
+ else if (name.indexOf('removable') >= 0) { result = 'Storage'; }
+ return result;
}
-//# sourceMappingURL=random.js.map
-/***/ }),
+function parseDarwinUsb(usb, id) {
+ const result = {};
+ result.id = id;
-/***/ 83712:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ usb = usb.replace(/ \|/g, '');
+ usb = usb.trim();
+ let lines = usb.split('\n');
+ lines.shift();
+ try {
+ for (let i = 0; i < lines.length; i++) {
+ lines[i] = lines[i].trim();
+ lines[i] = lines[i].replace(/=/g, ':');
+ if (lines[i] !== '{' && lines[i] !== '}' && lines[i + 1] && lines[i + 1].trim() !== '}') {
+ lines[i] = lines[i] + ',';
+ }
+ lines[i] = lines[i].replace(':Yes,', ':"Yes",');
+ lines[i] = lines[i].replace(': Yes,', ': "Yes",');
+ lines[i] = lines[i].replace(': Yes', ': "Yes"');
+ lines[i] = lines[i].replace(':No,', ':"No",');
+ lines[i] = lines[i].replace(': No,', ': "No",');
+ lines[i] = lines[i].replace(': No', ': "No"');
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.computeSha256Hmac = computeSha256Hmac;
-exports.computeSha256Hash = computeSha256Hash;
-const crypto_1 = __nccwpck_require__(76982);
-/**
- * Generates a SHA-256 HMAC signature.
- * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
- * @param stringToSign - The data to be signed.
- * @param encoding - The textual encoding to use for the returned HMAC digest.
- */
-async function computeSha256Hmac(key, stringToSign, encoding) {
- const decodedKey = Buffer.from(key, "base64");
- return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding);
-}
-/**
- * Generates a SHA-256 hash.
- * @param content - The data to be included in the hash.
- * @param encoding - The textual encoding to use for the returned hash.
- */
-async function computeSha256Hash(content, encoding) {
- return (0, crypto_1.createHash)("sha256").update(content).digest(encoding);
-}
-//# sourceMappingURL=sha256.js.map
+ // In this case (("com.apple.developer.driverkit.transport.usb"))
+ lines[i] = lines[i].replace('((', '').replace('))', '');
-/***/ }),
+ // In case we have <923c11> we need make it "<923c11>" for correct JSON parse
+ const match = /<(\w+)>/.exec(lines[i]);
+ if (match) {
+ const number = match[0];
+ lines[i] = lines[i].replace(number, `"${number}"`);
+ }
+ }
+ const usbObj = JSON.parse(lines.join('\n'));
+ const removableDrive = (usbObj['Built-In'] ? usbObj['Built-In'].toLowerCase() !== 'yes' : true) && (usbObj['non-removable'] ? usbObj['non-removable'].toLowerCase() === 'no' : true);
-/***/ 98489:
-/***/ ((__unused_webpack_module, exports) => {
+ result.bus = null;
+ result.deviceId = null;
+ result.id = usbObj['USB Address'] || null;
+ result.name = usbObj['kUSBProductString'] || usbObj['USB Product Name'] || null;
+ result.type = getDarwinUsbType((usbObj['kUSBProductString'] || usbObj['USB Product Name'] || '').toLowerCase() + (removableDrive ? ' removable' : ''));
+ result.removable = usbObj['non-removable'] ? usbObj['non-removable'].toLowerCase() || '' === 'no' : true;
+ result.vendor = usbObj['kUSBVendorString'] || usbObj['USB Vendor Name'] || null;
+ result.manufacturer = usbObj['kUSBVendorString'] || usbObj['USB Vendor Name'] || null;
+ result.maxPower = null;
+ result.serialNumber = usbObj['kUSBSerialNumberString'] || null;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isDefined = isDefined;
-exports.isObjectWithProperties = isObjectWithProperties;
-exports.objectHasProperty = objectHasProperty;
-/**
- * Helper TypeGuard that checks if something is defined or not.
- * @param thing - Anything
- */
-function isDefined(thing) {
- return typeof thing !== "undefined" && thing !== null;
-}
-/**
- * Helper TypeGuard that checks if the input is an object with the specified properties.
- * @param thing - Anything.
- * @param properties - The name of the properties that should appear in the object.
- */
-function isObjectWithProperties(thing, properties) {
- if (!isDefined(thing) || typeof thing !== "object") {
- return false;
- }
- for (const property of properties) {
- if (!objectHasProperty(thing, property)) {
- return false;
- }
+ if (result.name) {
+ return result;
+ } else {
+ return null;
}
- return true;
+ } catch (e) {
+ return null;
+ }
}
-/**
- * Helper TypeGuard that checks if the input is an object with the specified property.
- * @param thing - Any object.
- * @param property - The name of the property that should appear in the object.
- */
-function objectHasProperty(thing, property) {
- return (isDefined(thing) && typeof thing === "object" && property in thing);
+
+function getWindowsUsbTypeCreation(creationclass, name) {
+ let result = '';
+ if (name.indexOf('storage') >= 0) { result = 'Storage'; }
+ else if (name.indexOf('speicher') >= 0) { result = 'Storage'; }
+ else if (creationclass.indexOf('usbhub') >= 0) { result = 'Hub'; }
+ else if (creationclass.indexOf('storage') >= 0) { result = 'Storage'; }
+ else if (creationclass.indexOf('usbcontroller') >= 0) { result = 'Controller'; }
+ else if (creationclass.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
+ else if (creationclass.indexOf('pointing') >= 0) { result = 'Mouse'; }
+ else if (creationclass.indexOf('microp') >= 0) { result = 'Microphone'; }
+ else if (creationclass.indexOf('disk') >= 0) { result = 'Storage'; }
+ return result;
}
-//# sourceMappingURL=typeGuards.js.map
-/***/ }),
+function parseWindowsUsb(lines, id) {
+ const usbType = getWindowsUsbTypeCreation(util.getValue(lines, 'CreationClassName', ':').toLowerCase(), util.getValue(lines, 'name', ':').toLowerCase());
-/***/ 50751:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (usbType) {
+ const result = {};
+ result.bus = null;
+ result.deviceId = util.getValue(lines, 'deviceid', ':');
+ result.id = id;
+ result.name = util.getValue(lines, 'name', ':');
+ result.type = usbType;
+ result.removable = null;
+ result.vendor = null;
+ result.manufacturer = util.getValue(lines, 'Manufacturer', ':');
+ result.maxPower = null;
+ result.serialNumber = null;
+ return result;
+ } else {
+ return null;
+ }
+}
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-var _a;
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.randomUUID = randomUUID;
-const crypto_1 = __nccwpck_require__(76982);
-// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+.
-const uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function"
- ? globalThis.crypto.randomUUID.bind(globalThis.crypto)
- : crypto_1.randomUUID;
-/**
- * Generated Universally Unique Identifier
- *
- * @returns RFC4122 v4 UUID.
- */
-function randomUUID() {
- return uuidFunction();
+function usb(callback) {
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = [];
+ if (_linux) {
+ const cmd = 'export LC_ALL=C; lsusb -v 2>/dev/null; unset LC_ALL';
+ exec(cmd, { maxBuffer: 1024 * 1024 * 128 }, function (error, stdout) {
+ if (!error) {
+ const parts = ('\n\n' + stdout.toString()).split('\n\nBus ');
+ for (let i = 1; i < parts.length; i++) {
+ const usb = parseLinuxUsb(parts[i]);
+ result.push(usb);
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ let cmd = 'ioreg -p IOUSB -c AppleUSBRootHubDevice -w0 -l';
+ exec(cmd, { maxBuffer: 1024 * 1024 * 128 }, function (error, stdout) {
+ if (!error) {
+ const parts = (stdout.toString()).split(' +-o ');
+ for (let i = 1; i < parts.length; i++) {
+ const usb = parseDarwinUsb(parts[i]);
+ if (usb) {
+ result.push(usb);
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_windows) {
+ util.powerShell('Get-CimInstance CIM_LogicalDevice | where { $_.Description -match "USB"} | select Name,CreationClassName,DeviceId,Manufacturer | fl').then((stdout, error) => {
+ if (!error) {
+ const parts = stdout.toString().split(/\n\s*\n/);
+ for (let i = 0; i < parts.length; i++) {
+ const usb = parseWindowsUsb(parts[i].split('\n'), i);
+ if (usb && result.filter(x => x.deviceId === usb.deviceId).length === 0) {
+ result.push(usb);
+ }
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_sunos || _freebsd || _openbsd || _netbsd) {
+ resolve(null);
+ }
+ });
+ });
}
-//# sourceMappingURL=uuidUtils.js.map
+
+exports.usb = usb;
+
+
/***/ }),
-/***/ 21328:
+/***/ 69318:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.parseXML = exports.stringifyXML = void 0;
-var xml_js_1 = __nccwpck_require__(86537);
-Object.defineProperty(exports, "stringifyXML", ({ enumerable: true, get: function () { return xml_js_1.stringifyXML; } }));
-Object.defineProperty(exports, "parseXML", ({ enumerable: true, get: function () { return xml_js_1.parseXML; } }));
-var xml_common_js_1 = __nccwpck_require__(51882);
-Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return xml_common_js_1.XML_ATTRKEY; } }));
-Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return xml_common_js_1.XML_CHARKEY; } }));
-//# sourceMappingURL=index.js.map
+// @ts-check
+// ==================================================================================
+// users.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 11. Users/Sessions
+// ----------------------------------------------------------------------------------
-/***/ }),
+const exec = (__nccwpck_require__(35317).exec);
+const util = __nccwpck_require__(77496);
-/***/ 51882:
-/***/ ((__unused_webpack_module, exports) => {
+let _platform = process.platform;
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0;
-/**
- * Default key used to access the XML attributes.
- */
-exports.XML_ATTRKEY = "$";
-/**
- * Default key used to access the XML value content.
- */
-exports.XML_CHARKEY = "_";
-//# sourceMappingURL=xml.common.js.map
+function parseUsersLinux(lines, phase) {
+ let result = [];
+ let result_who = [];
+ let result_w = {};
+ let w_first = true;
+ let w_header = [];
+ let w_pos = [];
+ let who_line = {};
-/***/ }),
+ let is_whopart = true;
+ lines.forEach(function (line) {
+ if (line === '---') {
+ is_whopart = false;
+ } else {
+ let l = line.replace(/ +/g, ' ').split(' ');
-/***/ 86537:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // who part
+ if (is_whopart) {
+ result_who.push({
+ user: l[0],
+ tty: l[1],
+ date: l[2],
+ time: l[3],
+ ip: (l && l.length > 4) ? l[4].replace(/\(/g, '').replace(/\)/g, '') : ''
+ });
+ } else {
+ // w part
+ if (w_first) { // header
+ w_header = l;
+ w_header.forEach(function (item) {
+ w_pos.push(line.indexOf(item));
+ });
+ w_first = false;
+ } else {
+ // split by w_pos
+ result_w.user = line.substring(w_pos[0], w_pos[1] - 1).trim();
+ result_w.tty = line.substring(w_pos[1], w_pos[2] - 1).trim();
+ result_w.ip = line.substring(w_pos[2], w_pos[3] - 1).replace(/\(/g, '').replace(/\)/g, '').trim();
+ result_w.command = line.substring(w_pos[7], 1000).trim();
+ // find corresponding 'who' line
+ who_line = result_who.filter(function (obj) {
+ return (obj.user.substring(0, 8).trim() === result_w.user && obj.tty === result_w.tty);
+ });
+ if (who_line.length === 1) {
+ result.push({
+ user: who_line[0].user,
+ tty: who_line[0].tty,
+ date: who_line[0].date,
+ time: who_line[0].time,
+ ip: who_line[0].ip,
+ command: result_w.command
+ });
+ }
+ }
+ }
+ }
+ });
+ if (result.length === 0 && phase === 2) {
+ return result_who;
+ } else {
+ return result;
+ }
+}
+function parseUsersDarwin(lines) {
+ let result = [];
+ let result_who = [];
+ let result_w = {};
+ let who_line = {};
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.stringifyXML = stringifyXML;
-exports.parseXML = parseXML;
-const fast_xml_parser_1 = __nccwpck_require__(1537);
-const xml_common_js_1 = __nccwpck_require__(51882);
-function getCommonOptions(options) {
- var _a;
- return {
- attributesGroupName: xml_common_js_1.XML_ATTRKEY,
- textNodeName: (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : xml_common_js_1.XML_CHARKEY,
- ignoreAttributes: false,
- suppressBooleanAttributes: false,
- };
-}
-function getSerializerOptions(options = {}) {
- var _a, _b;
- return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "root", cdataPropName: (_b = options.cdataPropName) !== null && _b !== void 0 ? _b : "__cdata" });
-}
-function getParserOptions(options = {}) {
- return Object.assign(Object.assign({}, getCommonOptions(options)), { parseAttributeValue: false, parseTagValue: false, attributeNamePrefix: "", stopNodes: options.stopNodes, processEntities: true });
-}
-/**
- * Converts given JSON object to XML string
- * @param obj - JSON object to be converted into XML string
- * @param opts - Options that govern the XML building of given JSON object
- * `rootName` indicates the name of the root element in the resulting XML
- */
-function stringifyXML(obj, opts = {}) {
- const parserOptions = getSerializerOptions(opts);
- const j2x = new fast_xml_parser_1.XMLBuilder(parserOptions);
- const node = { [parserOptions.rootNodeName]: obj };
- const xmlData = j2x.build(node);
- return `${xmlData}`.replace(/\n/g, "");
-}
-/**
- * Converts given XML string into JSON
- * @param str - String containing the XML content to be parsed into JSON
- * @param opts - Options that govern the parsing of given xml string
- * `includeRoot` indicates whether the root element is to be included or not in the output
- */
-async function parseXML(str, opts = {}) {
- if (!str) {
- throw new Error("Document is empty");
- }
- const validation = fast_xml_parser_1.XMLValidator.validate(str);
- if (validation !== true) {
- throw validation;
- }
- const parser = new fast_xml_parser_1.XMLParser(getParserOptions(opts));
- const parsedXml = parser.parse(str);
- // Remove the node.
- // This is a change in behavior on fxp v4. Issue #424
- if (parsedXml["?xml"]) {
- delete parsedXml["?xml"];
- }
- if (!opts.includeRoot) {
- for (const key of Object.keys(parsedXml)) {
- const value = parsedXml[key];
- return typeof value === "object" ? Object.assign({}, value) : value;
+ let is_whopart = true;
+ lines.forEach(function (line) {
+ if (line === '---') {
+ is_whopart = false;
+ } else {
+ let l = line.replace(/ +/g, ' ').split(' ');
+
+ // who part
+ if (is_whopart) {
+ let dt = ('' + new Date().getFullYear()) + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(l[2].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + l[3]).slice(-2);
+ try {
+ if (new Date(dt) > new Date) {
+ dt = ('' + (new Date().getFullYear() - 1)) + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(l[2].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + l[3]).slice(-2);
+ }
+ } catch {
+ util.noop();
+ }
+ result_who.push({
+ user: l[0],
+ tty: l[1],
+ date: dt,
+ time: l[4],
+ });
+ } else {
+ // w part
+ // split by w_pos
+ result_w.user = l[0];
+ result_w.tty = l[1];
+ result_w.ip = (l[2] !== '-') ? l[2] : '';
+ result_w.command = l.slice(5, 1000).join(' ');
+ // find corresponding 'who' line
+ who_line = result_who.filter(function (obj) {
+ return (obj.user.substring(0, 10) === result_w.user.substring(0, 10) && (obj.tty.substring(3, 1000) === result_w.tty || obj.tty === result_w.tty));
+ });
+ if (who_line.length === 1) {
+ result.push({
+ user: who_line[0].user,
+ tty: who_line[0].tty,
+ date: who_line[0].date,
+ time: who_line[0].time,
+ ip: result_w.ip,
+ command: result_w.command
+ });
}
+ }
}
- return parsedXml;
+ });
+ return result;
}
-//# sourceMappingURL=xml.js.map
-/***/ }),
+function users(callback) {
-/***/ 37024:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = [];
+ // linux
+ if (_linux) {
+ exec('export LC_ALL=C; who --ips; echo "---"; w; unset LC_ALL | tail -n +2', function (error, stdout) {
+ if (!error) {
+ // lines / split
+ let lines = stdout.toString().split('\n');
+ result = parseUsersLinux(lines, 1);
+ if (result.length === 0) {
+ exec('who; echo "---"; w | tail -n +2', function (error, stdout) {
+ if (!error) {
+ // lines / split
+ lines = stdout.toString().split('\n');
+ result = parseUsersLinux(lines, 2);
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ exec('who; echo "---"; w -ih', function (error, stdout) {
+ if (!error) {
+ // lines / split
+ let lines = stdout.toString().split('\n');
+ result = parseUsersDarwin(lines);
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ exec('who; echo "---"; w -h', function (error, stdout) {
+ if (!error) {
+ // lines / split
+ let lines = stdout.toString().split('\n');
+ result = parseUsersDarwin(lines);
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-const log_js_1 = __nccwpck_require__(30881);
-const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined;
-let enabledString;
-let enabledNamespaces = [];
-let skippedNamespaces = [];
-const debuggers = [];
-if (debugEnvVariable) {
- enable(debugEnvVariable);
-}
-const debugObj = Object.assign((namespace) => {
- return createDebugger(namespace);
-}, {
- enable,
- enabled,
- disable,
- log: log_js_1.log,
-});
-function enable(namespaces) {
- enabledString = namespaces;
- enabledNamespaces = [];
- skippedNamespaces = [];
- const wildcard = /\*/g;
- const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?"));
- for (const ns of namespaceList) {
- if (ns.startsWith("-")) {
- skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`));
- }
- else {
- enabledNamespaces.push(new RegExp(`^${ns}$`));
- }
- }
- for (const instance of debuggers) {
- instance.enabled = enabled(instance.namespace);
- }
-}
-function enabled(namespace) {
- if (namespace.endsWith("*")) {
- return true;
- }
- for (const skipped of skippedNamespaces) {
- if (skipped.test(namespace)) {
- return false;
- }
- }
- for (const enabledNamespace of enabledNamespaces) {
- if (enabledNamespace.test(namespace)) {
- return true;
+ if (_darwin) {
+ exec('export LC_ALL=C; who; echo "---"; w -ih; unset LC_ALL', function (error, stdout) {
+ if (!error) {
+ // lines / split
+ let lines = stdout.toString().split('\n');
+ result = parseUsersDarwin(lines);
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_windows) {
+ try {
+ let cmd = 'Get-CimInstance Win32_LogonSession | select LogonId,@{n="StartTime";e={$_.StartTime.ToString("yyyy-MM-dd HH:mm:ss")}} | fl' + '; echo \'#-#-#-#\';';
+ cmd += 'Get-CimInstance Win32_LoggedOnUser | select antecedent,dependent | fl ' + '; echo \'#-#-#-#\';';
+ cmd += '$process = (Get-CimInstance Win32_Process -Filter "name = \'explorer.exe\'"); Invoke-CimMethod -InputObject $process[0] -MethodName GetOwner | select user, domain | fl; get-process -name explorer | select-object sessionid | fl; echo \'#-#-#-#\';';
+ cmd += 'query user';
+ util.powerShell(cmd).then((data) => {
+ if (data) {
+ data = data.split('#-#-#-#');
+ let sessions = parseWinSessions((data[0] || '').split(/\n\s*\n/));
+ let loggedons = parseWinLoggedOn((data[1] || '').split(/\n\s*\n/));
+ let queryUser = parseWinUsersQuery((data[3] || '').split('\r\n'));
+ let users = parseWinUsers((data[2] || '').split(/\n\s*\n/), queryUser);
+ for (let id in loggedons) {
+ if ({}.hasOwnProperty.call(loggedons, id)) {
+ loggedons[id].dateTime = {}.hasOwnProperty.call(sessions, id) ? sessions[id] : '';
+ }
+ }
+ users.forEach(user => {
+ let dateTime = '';
+ for (let id in loggedons) {
+ if ({}.hasOwnProperty.call(loggedons, id)) {
+ if (loggedons[id].user === user.user && (!dateTime || dateTime < loggedons[id].dateTime)) {
+ dateTime = loggedons[id].dateTime;
+ }
+ }
+ }
+
+ result.push({
+ user: user.user,
+ tty: user.tty,
+ date: `${dateTime.substring(0, 10)}`,
+ time: `${dateTime.substring(11, 19)}`,
+ ip: '',
+ command: ''
+ });
+ });
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- }
- return false;
-}
-function disable() {
- const result = enabledString || "";
- enable("");
- return result;
-}
-function createDebugger(namespace) {
- const newDebugger = Object.assign(debug, {
- enabled: enabled(namespace),
- destroy,
- log: debugObj.log,
- namespace,
- extend,
+ }
});
- function debug(...args) {
- if (!newDebugger.enabled) {
- return;
- }
- if (args.length > 0) {
- args[0] = `${namespace} ${args[0]}`;
- }
- newDebugger.log(...args);
- }
- debuggers.push(newDebugger);
- return newDebugger;
+ });
}
-function destroy() {
- const index = debuggers.indexOf(this);
- if (index >= 0) {
- debuggers.splice(index, 1);
- return true;
+
+function parseWinSessions(sessionParts) {
+ const sessions = {};
+ sessionParts.forEach(session => {
+ const lines = session.split('\r\n');
+ const id = util.getValue(lines, 'LogonId');
+ const starttime = util.getValue(lines, 'starttime');
+ if (id) {
+ sessions[id] = starttime;
}
- return false;
-}
-function extend(namespace) {
- const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
- newDebugger.log = this.log;
- return newDebugger;
+ });
+ return sessions;
}
-exports["default"] = debugObj;
-//# sourceMappingURL=debug.js.map
-/***/ }),
+function fuzzyMatch(name1, name2) {
+ name1 = name1.toLowerCase();
+ name2 = name2.toLowerCase();
+ let eq = 0;
+ let len = name1.length;
+ if (name2.length > len) { len = name2.length; }
-/***/ 50143:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ for (let i = 0; i < len; i++) {
+ const c1 = name1[i] || '';
+ const c2 = name2[i] || '';
+ if (c1 === c2) { eq++; }
+ }
+ return (len > 10 ? eq / len > 0.9 : (len > 0 ? eq / len > 0.8 : false));
+}
+function parseWinUsers(userParts, userQuery) {
+ const users = [];
+ userParts.forEach(user => {
+ const lines = user.split('\r\n');
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureLogger = void 0;
-exports.setLogLevel = setLogLevel;
-exports.getLogLevel = getLogLevel;
-exports.createClientLogger = createClientLogger;
-const tslib_1 = __nccwpck_require__(94176);
-const debug_js_1 = tslib_1.__importDefault(__nccwpck_require__(37024));
-const registeredLoggers = new Set();
-const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined;
-let azureLogLevel;
-/**
- * The AzureLogger provides a mechanism for overriding where logs are output to.
- * By default, logs are sent to stderr.
- * Override the `log` method to redirect logs to another location.
- */
-exports.AzureLogger = (0, debug_js_1.default)("azure");
-exports.AzureLogger.log = (...args) => {
- debug_js_1.default.log(...args);
-};
-const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"];
-if (logLevelFromEnv) {
- // avoid calling setLogLevel because we don't want a mis-set environment variable to crash
- if (isAzureLogLevel(logLevelFromEnv)) {
- setLogLevel(logLevelFromEnv);
- }
- else {
- console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`);
+ const domain = util.getValue(lines, 'domain', ':', true);
+ const username = util.getValue(lines, 'user', ':', true);
+ const sessionid = util.getValue(lines, 'sessionid', ':', true);
+
+ if (username) {
+ const quser = userQuery.filter(item => fuzzyMatch(item.user, username));
+ users.push({
+ domain,
+ user: username,
+ tty: quser && quser[0] && quser[0].tty ? quser[0].tty : sessionid
+ });
}
+ });
+ return users;
}
-/**
- * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
- * @param level - The log level to enable for logging.
- * Options from most verbose to least verbose are:
- * - verbose
- * - info
- * - warning
- * - error
- */
-function setLogLevel(level) {
- if (level && !isAzureLogLevel(level)) {
- throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`);
+
+function parseWinLoggedOn(loggedonParts) {
+ const loggedons = {};
+ loggedonParts.forEach(loggedon => {
+ const lines = loggedon.split('\r\n');
+
+ const antecendent = util.getValue(lines, 'antecedent', ':', true);
+ let parts = antecendent.split('=');
+ const name = parts.length > 2 ? parts[1].split(',')[0].replace(/"/g, '').trim() : '';
+ const domain = parts.length > 2 ? parts[2].replace(/"/g, '').replace(/\)/g, '').trim() : '';
+ const dependent = util.getValue(lines, 'dependent', ':', true);
+ parts = dependent.split('=');
+ const id = parts.length > 1 ? parts[1].replace(/"/g, '').replace(/\)/g, '').trim() : '';
+ if (id) {
+ loggedons[id] = {
+ domain,
+ user: name
+ };
}
- azureLogLevel = level;
- const enabledNamespaces = [];
- for (const logger of registeredLoggers) {
- if (shouldEnable(logger)) {
- enabledNamespaces.push(logger.namespace);
+ });
+ return loggedons;
+}
+
+function parseWinUsersQuery(lines) {
+ lines = lines.filter(item => item);
+ let result = [];
+ const header = lines[0];
+ const headerDelimiter = [];
+ if (header) {
+ const start = (header[0] === ' ') ? 1 : 0;
+ headerDelimiter.push(start - 1);
+ let nextSpace = 0;
+ for (let i = start + 1; i < header.length; i++) {
+ if (header[i] === ' ' && ((header[i - 1] === ' ') || (header[i - 1] === '.'))) {
+ nextSpace = i;
+ } else {
+ if (nextSpace) {
+ headerDelimiter.push(nextSpace);
+ nextSpace = 0;
}
+ }
}
- debug_js_1.default.enable(enabledNamespaces.join(","));
-}
-/**
- * Retrieves the currently specified log level.
- */
-function getLogLevel() {
- return azureLogLevel;
-}
-const levelMap = {
- verbose: 400,
- info: 300,
- warning: 200,
- error: 100,
-};
-/**
- * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
- * @param namespace - The name of the SDK package.
- * @hidden
- */
-function createClientLogger(namespace) {
- const clientRootLogger = exports.AzureLogger.extend(namespace);
- patchLogMethod(exports.AzureLogger, clientRootLogger);
- return {
- error: createLogger(clientRootLogger, "error"),
- warning: createLogger(clientRootLogger, "warning"),
- info: createLogger(clientRootLogger, "info"),
- verbose: createLogger(clientRootLogger, "verbose"),
- };
-}
-function patchLogMethod(parent, child) {
- child.log = (...args) => {
- parent.log(...args);
- };
-}
-function createLogger(parent, level) {
- const logger = Object.assign(parent.extend(level), {
- level,
- });
- patchLogMethod(parent, logger);
- if (shouldEnable(logger)) {
- const enabledNamespaces = debug_js_1.default.disable();
- debug_js_1.default.enable(enabledNamespaces + "," + logger.namespace);
+ for (let i = 1; i < lines.length; i++) {
+ if (lines[i].trim()) {
+ const user = lines[i].substring(headerDelimiter[0] + 1, headerDelimiter[1]).trim() || '';
+ const tty = lines[i].substring(headerDelimiter[1] + 1, headerDelimiter[2] - 2).trim() || '';
+ result.push({
+ user: user,
+ tty: tty,
+ });
+ }
}
- registeredLoggers.add(logger);
- return logger;
-}
-function shouldEnable(logger) {
- return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]);
-}
-function isAzureLogLevel(logLevel) {
- return AZURE_LOG_LEVELS.includes(logLevel);
+ }
+ return result;
}
-//# sourceMappingURL=index.js.map
-
-/***/ }),
-
-/***/ 30881:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+exports.users = users;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.log = log;
-const tslib_1 = __nccwpck_require__(94176);
-const node_os_1 = __nccwpck_require__(48161);
-const node_util_1 = tslib_1.__importDefault(__nccwpck_require__(57975));
-const process = tslib_1.__importStar(__nccwpck_require__(1708));
-function log(message, ...args) {
- process.stderr.write(`${node_util_1.default.format(message, ...args)}${node_os_1.EOL}`);
-}
-//# sourceMappingURL=log.js.map
/***/ }),
-/***/ 8946:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 77496:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const WritableStream = (__nccwpck_require__(57075).Writable)
-const inherits = (__nccwpck_require__(57975).inherits)
-const StreamSearch = __nccwpck_require__(86484)
+// @ts-check
+// ==================================================================================
+// utils.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 0. helper functions
+// ----------------------------------------------------------------------------------
-const PartStream = __nccwpck_require__(87952)
-const HeaderParser = __nccwpck_require__(87003)
+const os = __nccwpck_require__(70857);
+const fs = __nccwpck_require__(79896);
+const path = __nccwpck_require__(16928);
+const spawn = (__nccwpck_require__(35317).spawn);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const util = __nccwpck_require__(39023);
-const DASH = 45
-const B_ONEDASH = Buffer.from('-')
-const B_CRLF = Buffer.from('\r\n')
-const EMPTY_FN = function () {}
+let _platform = process.platform;
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
-function Dicer (cfg) {
- if (!(this instanceof Dicer)) { return new Dicer(cfg) }
- WritableStream.call(this, cfg)
+let _cores = 0;
+let wmicPath = '';
+let codepage = '';
+let _smartMonToolsInstalled = null;
+let _rpi_cpuinfo = null;
- if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }
+const WINDIR = process.env.WINDIR || 'C:\\Windows';
- if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }
+// powerShell
+let _psChild;
+let _psResult = '';
+let _psCmds = [];
+let _psPersistent = false;
+let _powerShell = '';
+const _psToUTF8 = '$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; ';
+const _psCmdStart = '--###START###--';
+const _psError = '--ERROR--';
+const _psCmdSeperator = '--###ENDCMD###--';
+const _psIdSeperator = '--##ID##--';
- this._headerFirst = cfg.headerFirst
+const execOptsWin = {
+ windowsHide: true,
+ maxBuffer: 1024 * 20000,
+ encoding: 'UTF-8',
+ env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' })
+};
- this._dashes = 0
- this._parts = 0
- this._finished = false
- this._realFinish = false
- this._isPreamble = true
- this._justMatched = false
- this._firstWrite = true
- this._inHeader = true
- this._part = undefined
- this._cb = undefined
- this._ignoreData = false
- this._partOpts = { highWaterMark: cfg.partHwm }
- this._pause = false
+const execOptsLinux = {
+ maxBuffer: 1024 * 20000,
+ encoding: 'UTF-8',
+ stdio: ['pipe', 'pipe', 'ignore']
+};
- const self = this
- this._hparser = new HeaderParser(cfg)
- this._hparser.on('header', function (header) {
- self._inHeader = false
- self._part.emit('header', header)
- })
+function toInt(value) {
+ let result = parseInt(value, 10);
+ if (isNaN(result)) {
+ result = 0;
+ }
+ return result;
}
-inherits(Dicer, WritableStream)
-Dicer.prototype.emit = function (ev) {
- if (ev === 'finish' && !this._realFinish) {
- if (!this._finished) {
- const self = this
- process.nextTick(function () {
- self.emit('error', new Error('Unexpected end of multipart data'))
- if (self._part && !self._ignoreData) {
- const type = (self._isPreamble ? 'Preamble' : 'Part')
- self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))
- self._part.push(null)
- process.nextTick(function () {
- self._realFinish = true
- self.emit('finish')
- self._realFinish = false
- })
- return
- }
- self._realFinish = true
- self.emit('finish')
- self._realFinish = false
- })
+function splitByNumber(str) {
+ let numberStarted = false;
+ let num = '';
+ let cpart = '';
+ for (const c of str) {
+ if ((c >= '0' && c <= '9') || numberStarted) {
+ numberStarted = true;
+ num += c;
+ } else {
+ cpart += c;
}
- } else { WritableStream.prototype.emit.apply(this, arguments) }
+ }
+ return [cpart, num];
}
-Dicer.prototype._write = function (data, encoding, cb) {
- // ignore unexpected data (e.g. extra trailer data after finished)
- if (!this._hparser && !this._bparser) { return cb() }
+const stringObj = new String();
+const stringReplace = new String().replace;
+const stringToLower = new String().toLowerCase;
+const stringToString = new String().toString;
+const stringSubstr = new String().substr;
+const stringSubstring = new String().substring;
+const stringTrim = new String().trim;
+const stringStartWith = new String().startsWith;
+const mathMin = Math.min;
- if (this._headerFirst && this._isPreamble) {
- if (!this._part) {
- this._part = new PartStream(this._partOpts)
- if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() }
+function isFunction(functionToCheck) {
+ let getType = {};
+ return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
+}
+
+function unique(obj) {
+ let uniques = [];
+ let stringify = {};
+ for (let i = 0; i < obj.length; i++) {
+ let keys = Object.keys(obj[i]);
+ keys.sort(function (a, b) { return a - b; });
+ let str = '';
+ for (let j = 0; j < keys.length; j++) {
+ str += JSON.stringify(keys[j]);
+ str += JSON.stringify(obj[i][keys[j]]);
+ }
+ if (!{}.hasOwnProperty.call(stringify, str)) {
+ uniques.push(obj[i]);
+ stringify[str] = true;
}
- const r = this._hparser.push(data)
- if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }
}
+ return uniques;
+}
- // allows for "easier" testing
- if (this._firstWrite) {
- this._bparser.push(B_CRLF)
- this._firstWrite = false
- }
+function sortByKey(array, keys) {
+ return array.sort(function (a, b) {
+ let x = '';
+ let y = '';
+ keys.forEach(function (key) {
+ x = x + a[key]; y = y + b[key];
+ });
+ return ((x < y) ? -1 : ((x > y) ? 1 : 0));
+ });
+}
- this._bparser.push(data)
+function cores() {
+ if (_cores === 0) {
+ _cores = os.cpus().length;
+ }
+ return _cores;
+}
- if (this._pause) { this._cb = cb } else { cb() }
+function getValue(lines, property, separator, trimmed, lineMatch) {
+ separator = separator || ':';
+ property = property.toLowerCase();
+ trimmed = trimmed || false;
+ lineMatch = lineMatch || false;
+ let result = '';
+ lines.some((line) => {
+ let lineLower = line.toLowerCase().replace(/\t/g, '');
+ if (trimmed) {
+ lineLower = lineLower.trim();
+ }
+ if (lineLower.startsWith(property) && (lineMatch ? (lineLower.match(property + separator)) || (lineLower.match(property + ' ' + separator)) : true)) {
+ const parts = trimmed ? line.trim().split(separator) : line.split(separator);
+ if (parts.length >= 2) {
+ parts.shift();
+ result = parts.join(separator).trim();
+ return true;
+ }
+ }
+ });
+ return result;
}
-Dicer.prototype.reset = function () {
- this._part = undefined
- this._bparser = undefined
- this._hparser = undefined
+function decodeEscapeSequence(str, base) {
+ base = base || 16;
+ return str.replace(/\\x([0-9A-Fa-f]{2})/g, function () {
+ return String.fromCharCode(parseInt(arguments[1], base));
+ });
}
-Dicer.prototype.setBoundary = function (boundary) {
- const self = this
- this._bparser = new StreamSearch('\r\n--' + boundary)
- this._bparser.on('info', function (isMatch, data, start, end) {
- self._oninfo(isMatch, data, start, end)
- })
+function detectSplit(str) {
+ let seperator = '';
+ let part = 0;
+ str.split('').forEach(element => {
+ if (element >= '0' && element <= '9') {
+ if (part === 1) { part++; }
+ } else {
+ if (part === 0) { part++; }
+ if (part === 1) {
+ seperator += element;
+ }
+ }
+ });
+ return seperator;
}
-Dicer.prototype._ignore = function () {
- if (this._part && !this._ignoreData) {
- this._ignoreData = true
- this._part.on('error', EMPTY_FN)
- // we must perform some kind of read on the stream even though we are
- // ignoring the data, otherwise node's Readable stream will not emit 'end'
- // after pushing null to the stream
- this._part.resume()
+function parseTime(t, pmDesignator) {
+ pmDesignator = pmDesignator || '';
+ t = t.toUpperCase();
+ let hour = 0;
+ let min = 0;
+ let splitter = detectSplit(t);
+ let parts = t.split(splitter);
+ if (parts.length >= 2) {
+ if (parts[2]) {
+ parts[1] += parts[2];
+ }
+ let isPM = (parts[1] && (parts[1].toLowerCase().indexOf('pm') > -1) || (parts[1].toLowerCase().indexOf('p.m.') > -1) || (parts[1].toLowerCase().indexOf('p. m.') > -1) || (parts[1].toLowerCase().indexOf('n') > -1) || (parts[1].toLowerCase().indexOf('ch') > -1) || (parts[1].toLowerCase().indexOf('ös') > -1) || (pmDesignator && parts[1].toLowerCase().indexOf(pmDesignator) > -1));
+ hour = parseInt(parts[0], 10);
+ min = parseInt(parts[1], 10);
+ hour = isPM && hour < 12 ? hour + 12 : hour;
+ return ('0' + hour).substr(-2) + ':' + ('0' + min).substr(-2);
}
}
-Dicer.prototype._oninfo = function (isMatch, data, start, end) {
- let buf; const self = this; let i = 0; let r; let shouldWriteMore = true
+function parseDateTime(dt, culture) {
+ const result = {
+ date: '',
+ time: ''
+ };
+ culture = culture || {};
+ let dateFormat = (culture.dateFormat || '').toLowerCase();
+ let pmDesignator = (culture.pmDesignator || '');
- if (!this._part && this._justMatched && data) {
- while (this._dashes < 2 && (start + i) < end) {
- if (data[start + i] === DASH) {
- ++i
- ++this._dashes
- } else {
- if (this._dashes) { buf = B_ONEDASH }
- this._dashes = 0
- break
+ const parts = dt.split(' ');
+ if (parts[0]) {
+ if (parts[0].indexOf('/') >= 0) {
+ // Dateformat: mm/dd/yyyy or dd/mm/yyyy or dd/mm/yy or yyyy/mm/dd
+ const dtparts = parts[0].split('/');
+ if (dtparts.length === 3) {
+ if (dtparts[0].length === 4) {
+ // Dateformat: yyyy/mm/dd
+ result.date = dtparts[0] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[2]).substr(-2);
+ } else if (dtparts[2].length === 2) {
+ if ((dateFormat.indexOf('/d/') > -1 || dateFormat.indexOf('/dd/') > -1)) {
+ // Dateformat: mm/dd/yy
+ result.date = '20' + dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
+ } else {
+ // Dateformat: dd/mm/yy
+ result.date = '20' + dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
+ }
+ } else {
+ // Dateformat: mm/dd/yyyy or dd/mm/yyyy
+ const isEN = ((dt.toLowerCase().indexOf('pm') > -1) || (dt.toLowerCase().indexOf('p.m.') > -1) || (dt.toLowerCase().indexOf('p. m.') > -1) || (dt.toLowerCase().indexOf('am') > -1) || (dt.toLowerCase().indexOf('a.m.') > -1) || (dt.toLowerCase().indexOf('a. m.') > -1));
+ if ((isEN || dateFormat.indexOf('/d/') > -1 || dateFormat.indexOf('/dd/') > -1) && dateFormat.indexOf('dd/') !== 0) {
+ // Dateformat: mm/dd/yyyy
+ result.date = dtparts[2] + '-' + ('0' + dtparts[0]).substr(-2) + '-' + ('0' + dtparts[1]).substr(-2);
+ } else {
+ // Dateformat: dd/mm/yyyy
+ result.date = dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
+ }
+ }
}
}
- if (this._dashes === 2) {
- if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) }
- this.reset()
- this._finished = true
- // no more parts will be added
- if (self._parts === 0) {
- self._realFinish = true
- self.emit('finish')
- self._realFinish = false
+ if (parts[0].indexOf('.') >= 0) {
+ const dtparts = parts[0].split('.');
+ if (dtparts.length === 3) {
+ if (dateFormat.indexOf('.d.') > -1 || dateFormat.indexOf('.dd.') > -1) {
+ // Dateformat: mm.dd.yyyy
+ result.date = dtparts[2] + '-' + ('0' + dtparts[0]).substr(-2) + '-' + ('0' + dtparts[1]).substr(-2);
+ } else {
+ // Dateformat: dd.mm.yyyy
+ result.date = dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
+ }
}
}
- if (this._dashes) { return }
- }
- if (this._justMatched) { this._justMatched = false }
- if (!this._part) {
- this._part = new PartStream(this._partOpts)
- this._part._read = function (n) {
- self._unpause()
- }
- if (this._isPreamble && this.listenerCount('preamble') !== 0) {
- this.emit('preamble', this._part)
- } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) {
- this.emit('part', this._part)
- } else {
- this._ignore()
+ if (parts[0].indexOf('-') >= 0) {
+ // Dateformat: yyyy-mm-dd
+ const dtparts = parts[0].split('-');
+ if (dtparts.length === 3) {
+ result.date = dtparts[0] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[2]).substr(-2);
+ }
}
- if (!this._isPreamble) { this._inHeader = true }
}
- if (data && start < end && !this._ignoreData) {
- if (this._isPreamble || !this._inHeader) {
- if (buf) { shouldWriteMore = this._part.push(buf) }
- shouldWriteMore = this._part.push(data.slice(start, end))
- if (!shouldWriteMore) { this._pause = true }
- } else if (!this._isPreamble && this._inHeader) {
- if (buf) { this._hparser.push(buf) }
- r = this._hparser.push(data.slice(start, end))
- if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }
+ if (parts[1]) {
+ parts.shift();
+ let time = parts.join(' ');
+ result.time = parseTime(time, pmDesignator);
+ }
+ return result;
+}
+
+function parseHead(head, rights) {
+ let space = (rights > 0);
+ let count = 1;
+ let from = 0;
+ let to = 0;
+ let result = [];
+ for (let i = 0; i < head.length; i++) {
+ if (count <= rights) {
+ if (/\s/.test(head[i]) && !space) {
+ to = i - 1;
+ result.push({
+ from: from,
+ to: to + 1,
+ cap: head.substring(from, to + 1)
+ });
+ from = to + 2;
+ count++;
+ }
+ space = head[i] === ' ';
+ } else {
+ if (!/\s/.test(head[i]) && space) {
+ to = i - 1;
+ if (from < to) {
+ result.push({
+ from: from,
+ to: to,
+ cap: head.substring(from, to)
+ });
+ }
+ from = to + 1;
+ count++;
+ }
+ space = head[i] === ' ';
}
}
- if (isMatch) {
- this._hparser.reset()
- if (this._isPreamble) { this._isPreamble = false } else {
- if (start !== end) {
- ++this._parts
- this._part.on('end', function () {
- if (--self._parts === 0) {
- if (self._finished) {
- self._realFinish = true
- self.emit('finish')
- self._realFinish = false
- } else {
- self._unpause()
- }
- }
- })
+ to = 5000;
+ result.push({
+ from: from,
+ to: to,
+ cap: head.substring(from, to)
+ });
+ let len = result.length;
+ for (let i = 0; i < len; i++) {
+ if (result[i].cap.replace(/\s/g, '').length === 0) {
+ if (i + 1 < len) {
+ result[i].to = result[i + 1].to;
+ result[i].cap = result[i].cap + result[i + 1].cap;
+ result.splice(i + 1, 1);
+ len = len - 1;
}
}
- this._part.push(null)
- this._part = undefined
- this._ignoreData = false
- this._justMatched = true
- this._dashes = 0
}
+ return result;
}
-Dicer.prototype._unpause = function () {
- if (!this._pause) { return }
-
- this._pause = false
- if (this._cb) {
- const cb = this._cb
- this._cb = undefined
- cb()
+function findObjectByKey(array, key, value) {
+ for (let i = 0; i < array.length; i++) {
+ if (array[i][key] === value) {
+ return i;
+ }
}
+ return -1;
}
-module.exports = Dicer
-
-
-/***/ }),
-
-/***/ 87003:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const EventEmitter = (__nccwpck_require__(78474).EventEmitter)
-const inherits = (__nccwpck_require__(57975).inherits)
-const getLimit = __nccwpck_require__(5245)
-
-const StreamSearch = __nccwpck_require__(86484)
-
-const B_DCRLF = Buffer.from('\r\n\r\n')
-const RE_CRLF = /\r\n/g
-const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex
-
-function HeaderParser (cfg) {
- EventEmitter.call(this)
-
- cfg = cfg || {}
- const self = this
- this.nread = 0
- this.maxed = false
- this.npairs = 0
- this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)
- this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)
- this.buffer = ''
- this.header = {}
- this.finished = false
- this.ss = new StreamSearch(B_DCRLF)
- this.ss.on('info', function (isMatch, data, start, end) {
- if (data && !self.maxed) {
- if (self.nread + end - start >= self.maxHeaderSize) {
- end = self.maxHeaderSize - self.nread + start
- self.nread = self.maxHeaderSize
- self.maxed = true
- } else { self.nread += (end - start) }
-
- self.buffer += data.toString('binary', start, end)
+function getPowershell() {
+ _powerShell = 'powershell.exe';
+ if (_windows) {
+ const defaultPath = `${WINDIR}\\system32\\WindowsPowerShell\\v1.0\\powershell.exe`;
+ if (fs.existsSync(defaultPath)) {
+ _powerShell = defaultPath;
}
- if (isMatch) { self._finish() }
- })
+ }
}
-inherits(HeaderParser, EventEmitter)
-HeaderParser.prototype.push = function (data) {
- const r = this.ss.push(data)
- if (this.finished) { return r }
+function getWmic() {
+ if (os.type() === 'Windows_NT' && !wmicPath) {
+ wmicPath = WINDIR + '\\system32\\wbem\\wmic.exe';
+ if (!fs.existsSync(wmicPath)) {
+ try {
+ const wmicPathArray = execSync('WHERE WMIC', execOptsWin).toString().split('\r\n');
+ if (wmicPathArray && wmicPathArray.length) {
+ wmicPath = wmicPathArray[0];
+ } else {
+ wmicPath = 'wmic';
+ }
+ } catch (e) {
+ wmicPath = 'wmic';
+ }
+ }
+ }
+ return wmicPath;
}
-HeaderParser.prototype.reset = function () {
- this.finished = false
- this.buffer = ''
- this.header = {}
- this.ss.reset()
+function wmic(command) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ try {
+ powerShell(getWmic() + ' ' + command).then(stdout => {
+ resolve(stdout, '');
+ });
+ } catch (e) {
+ resolve('', e);
+ }
+ });
+ });
}
-HeaderParser.prototype._finish = function () {
- if (this.buffer) { this._parseHeader() }
- this.ss.matches = this.ss.maxMatches
- const header = this.header
- this.header = {}
- this.buffer = ''
- this.finished = true
- this.nread = this.npairs = 0
- this.maxed = false
- this.emit('header', header)
+function getVboxmanage() {
+ return _windows ? `"${process.env.VBOX_INSTALL_PATH || process.env.VBOX_MSI_INSTALL_PATH}\\VBoxManage.exe"` : 'vboxmanage';
}
-HeaderParser.prototype._parseHeader = function () {
- if (this.npairs === this.maxHeaderPairs) { return }
-
- const lines = this.buffer.split(RE_CRLF)
- const len = lines.length
- let m, h
+function powerShellProceedResults(data) {
+ let id = '';
+ let parts;
+ let res = '';
+ // startID
+ if (data.indexOf(_psCmdStart) >= 0) {
+ parts = data.split(_psCmdStart);
+ const parts2 = parts[1].split(_psIdSeperator);
+ id = parts2[0];
+ if (parts2.length > 1) {
+ data = parts2.slice(1).join(_psIdSeperator);
+ }
+ }
+ // result;
+ if (data.indexOf(_psCmdSeperator) >= 0) {
+ parts = data.split(_psCmdSeperator);
+ res = parts[0];
+ }
+ let remove = -1;
+ for (let i = 0; i < _psCmds.length; i++) {
+ if (_psCmds[i].id === id) {
+ remove = i;
+ _psCmds[i].callback(res);
+ }
+ }
+ if (remove >= 0) {
+ _psCmds.splice(remove, 1);
+ }
+}
- for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
- if (lines[i].length === 0) { continue }
- if (lines[i][0] === '\t' || lines[i][0] === ' ') {
- // folded header content
- // RFC2822 says to just remove the CRLF and not the whitespace following
- // it, so we follow the RFC and include the leading whitespace ...
- if (h) {
- this.header[h][this.header[h].length - 1] += lines[i]
- continue
- }
+function powerShellStart() {
+ if (!_psChild) {
+ _psChild = spawn(_powerShell, ['-NoProfile', '-NoLogo', '-InputFormat', 'Text', '-NoExit', '-Command', '-'], {
+ stdio: 'pipe',
+ windowsHide: true,
+ maxBuffer: 1024 * 20000,
+ encoding: 'UTF-8',
+ env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' })
+ });
+ if (_psChild && _psChild.pid) {
+ _psPersistent = true;
+ _psChild.stdout.on('data', function (data) {
+ _psResult = _psResult + data.toString('utf8');
+ if (data.indexOf(_psCmdSeperator) >= 0) {
+ powerShellProceedResults(_psResult);
+ _psResult = '';
+ }
+ });
+ _psChild.stderr.on('data', function () {
+ powerShellProceedResults(_psResult + _psError);
+ });
+ _psChild.on('error', function () {
+ powerShellProceedResults(_psResult + _psError);
+ });
+ _psChild.on('close', function () {
+ if (_psChild) { _psChild.kill(); }
+ });
}
+ }
+}
- const posColon = lines[i].indexOf(':')
- if (
- posColon === -1 ||
- posColon === 0
- ) {
- return
+function powerShellRelease() {
+ try {
+ if (_psChild) {
+ _psChild.stdin.write('exit' + os.EOL);
+ _psChild.stdin.end();
+ _psPersistent = false;
}
- m = RE_HDR.exec(lines[i])
- h = m[1].toLowerCase()
- this.header[h] = this.header[h] || []
- this.header[h].push((m[2] || ''))
- if (++this.npairs === this.maxHeaderPairs) { break }
+ } catch (e) {
+ if (_psChild) { _psChild.kill(); }
}
+ _psChild = null;
}
-module.exports = HeaderParser
-
+function powerShell(cmd) {
-/***/ }),
+ /// const pattern = [
+ /// '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
+ /// '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))'
+ /// ].join('|');
-/***/ 87952:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (_psPersistent) {
+ const id = Math.random().toString(36).substring(2, 12);
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ function callback(data) {
+ resolve(data);
+ }
+ _psCmds.push({
+ id,
+ cmd,
+ callback,
+ start: new Date()
+ });
+ try {
+ if (_psChild && _psChild.pid) {
+ _psChild.stdin.write(_psToUTF8 + 'echo ' + _psCmdStart + id + _psIdSeperator + '; ' + os.EOL + cmd + os.EOL + 'echo ' + _psCmdSeperator + os.EOL);
+ }
+ } catch (e) {
+ resolve('');
+ }
+ });
+ });
+ } else {
+ let result = '';
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ try {
+ const child = spawn(_powerShell, ['-NoProfile', '-NoLogo', '-InputFormat', 'Text', '-NoExit', '-ExecutionPolicy', 'Unrestricted', '-Command', '-'], {
+ stdio: 'pipe',
+ windowsHide: true,
+ maxBuffer: 1024 * 20000,
+ encoding: 'UTF-8',
+ env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' })
+ });
-const inherits = (__nccwpck_require__(57975).inherits)
-const ReadableStream = (__nccwpck_require__(57075).Readable)
+ if (child && !child.pid) {
+ child.on('error', function () {
+ resolve(result);
+ });
+ }
+ if (child && child.pid) {
+ child.stdout.on('data', function (data) {
+ result = result + data.toString('utf8');
+ });
+ child.stderr.on('data', function () {
+ child.kill();
+ resolve(result);
+ });
+ child.on('close', function () {
+ child.kill();
-function PartStream (opts) {
- ReadableStream.call(this, opts)
+ resolve(result);
+ });
+ child.on('error', function () {
+ child.kill();
+ resolve(result);
+ });
+ try {
+ child.stdin.write(_psToUTF8 + cmd + os.EOL);
+ child.stdin.write('exit' + os.EOL);
+ child.stdin.end();
+ } catch (e) {
+ child.kill();
+ resolve(result);
+ }
+ } else {
+ resolve(result);
+ }
+ } catch (e) {
+ resolve(result);
+ }
+ });
+ });
+ }
}
-inherits(PartStream, ReadableStream)
-
-PartStream.prototype._read = function (n) {}
-
-module.exports = PartStream
-
-
-/***/ }),
-
-/***/ 86484:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+function execSafe(cmd, args, options) {
+ let result = '';
+ options = options || {};
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ try {
+ const child = spawn(cmd, args, options);
-/**
- * Copyright Brian White. All rights reserved.
- *
- * @see https://github.com/mscdex/streamsearch
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to
- * deal in the Software without restriction, including without limitation the
- * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- * sell copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
- * IN THE SOFTWARE.
- *
- * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
- * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
- */
-const EventEmitter = (__nccwpck_require__(78474).EventEmitter)
-const inherits = (__nccwpck_require__(57975).inherits)
+ if (child && !child.pid) {
+ child.on('error', function () {
+ resolve(result);
+ });
+ }
+ if (child && child.pid) {
+ child.stdout.on('data', function (data) {
+ result += data.toString();
+ });
+ child.on('close', function () {
+ child.kill();
+ resolve(result);
+ });
+ child.on('error', function () {
+ child.kill();
+ resolve(result);
+ });
+ } else {
+ resolve(result);
+ }
+ } catch (e) {
+ resolve(result);
+ }
+ });
+ });
+}
-function SBMH (needle) {
- if (typeof needle === 'string') {
- needle = Buffer.from(needle)
+function getCodepage() {
+ if (_windows) {
+ if (!codepage) {
+ try {
+ const stdout = execSync('chcp', execOptsWin);
+ const lines = stdout.toString().split('\r\n');
+ const parts = lines[0].split(':');
+ codepage = parts.length > 1 ? parts[1].replace('.', '').trim() : '';
+ } catch (err) {
+ codepage = '437';
+ }
+ }
+ return codepage;
}
-
- if (!Buffer.isBuffer(needle)) {
- throw new TypeError('The needle has to be a String or a Buffer.')
+ if (_linux || _darwin || _freebsd || _openbsd || _netbsd) {
+ if (!codepage) {
+ try {
+ const stdout = execSync('echo $LANG', execOptsLinux);
+ const lines = stdout.toString().split('\r\n');
+ const parts = lines[0].split('.');
+ codepage = parts.length > 1 ? parts[1].trim() : '';
+ if (!codepage) {
+ codepage = 'UTF-8';
+ }
+ } catch (err) {
+ codepage = 'UTF-8';
+ }
+ }
+ return codepage;
}
+}
- const needleLength = needle.length
-
- if (needleLength === 0) {
- throw new Error('The needle cannot be an empty String/Buffer.')
+function smartMonToolsInstalled() {
+ if (_smartMonToolsInstalled !== null) {
+ return _smartMonToolsInstalled;
}
-
- if (needleLength > 256) {
- throw new Error('The needle cannot have a length bigger than 256.')
+ _smartMonToolsInstalled = false;
+ if (_windows) {
+ try {
+ const pathArray = execSync('WHERE smartctl 2>nul', execOptsWin).toString().split('\r\n');
+ if (pathArray && pathArray.length) {
+ _smartMonToolsInstalled = pathArray[0].indexOf(':\\') >= 0;
+ } else {
+ _smartMonToolsInstalled = false;
+ }
+ } catch (e) {
+ _smartMonToolsInstalled = false;
+ }
}
+ if (_linux || _darwin || _freebsd || _openbsd || _netbsd) {
+ try {
+ const pathArray = execSync('which smartctl 2>/dev/null', execOptsLinux).toString().split('\r\n');
+ _smartMonToolsInstalled = pathArray.length > 0;
+ } catch (e) {
+ util.noop();
+ }
+ }
+ return _smartMonToolsInstalled;
+}
- this.maxMatches = Infinity
- this.matches = 0
-
- this._occ = new Array(256)
- .fill(needleLength) // Initialize occurrence table.
- this._lookbehind_size = 0
- this._needle = needle
- this._bufpos = 0
-
- this._lookbehind = Buffer.alloc(needleLength)
+function isRaspberry() {
+ const PI_MODEL_NO = [
+ 'BCM2708',
+ 'BCM2709',
+ 'BCM2710',
+ 'BCM2711',
+ 'BCM2712',
+ 'BCM2835',
+ 'BCM2836',
+ 'BCM2837',
+ 'BCM2837B0'
+ ];
+ let cpuinfo = [];
- // Populate occurrence table with analysis of the needle,
- // ignoring last letter.
- for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var
- this._occ[needle[i]] = needleLength - 1 - i
+ if (_rpi_cpuinfo !== null) {
+ cpuinfo = _rpi_cpuinfo;
+ } else {
+ try {
+ cpuinfo = fs.readFileSync('/proc/cpuinfo', { encoding: 'utf8' }).toString().split('\n');
+ _rpi_cpuinfo = cpuinfo;
+ } catch (e) {
+ return false;
+ }
}
-}
-inherits(SBMH, EventEmitter)
-SBMH.prototype.reset = function () {
- this._lookbehind_size = 0
- this.matches = 0
- this._bufpos = 0
+ const hardware = getValue(cpuinfo, 'hardware');
+ return (hardware && PI_MODEL_NO.indexOf(hardware) > -1);
}
-SBMH.prototype.push = function (chunk, pos) {
- if (!Buffer.isBuffer(chunk)) {
- chunk = Buffer.from(chunk, 'binary')
+function isRaspbian() {
+ let osrelease = [];
+ try {
+ osrelease = fs.readFileSync('/etc/os-release', { encoding: 'utf8' }).toString().split('\n');
+ } catch (e) {
+ return false;
}
- const chlen = chunk.length
- this._bufpos = pos || 0
- let r
- while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }
- return r
+ const id = getValue(osrelease, 'id', '=');
+ return (id && id.indexOf('raspbian') > -1);
}
-SBMH.prototype._sbmh_feed = function (data) {
- const len = data.length
- const needle = this._needle
- const needleLength = needle.length
- const lastNeedleChar = needle[needleLength - 1]
-
- // Positive: points to a position in `data`
- // pos == 3 points to data[3]
- // Negative: points to a position in the lookbehind buffer
- // pos == -2 points to lookbehind[lookbehind_size - 2]
- let pos = -this._lookbehind_size
- let ch
+function execWin(cmd, opts, callback) {
+ if (!callback) {
+ callback = opts;
+ opts = execOptsWin;
+ }
+ let newCmd = 'chcp 65001 > nul && cmd /C ' + cmd + ' && chcp ' + codepage + ' > nul';
+ exec(newCmd, opts, function (error, stdout) {
+ callback(error, stdout);
+ });
+}
- if (pos < 0) {
- // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
- // search with character lookup code that considers both the
- // lookbehind buffer and the current round's haystack data.
- //
- // Loop until
- // there is a match.
- // or until
- // we've moved past the position that requires the
- // lookbehind buffer. In this case we switch to the
- // optimized loop.
- // or until
- // the character to look at lies outside the haystack.
- while (pos < 0 && pos <= len - needleLength) {
- ch = this._sbmh_lookup_char(data, pos + needleLength - 1)
+function darwinXcodeExists() {
+ const cmdLineToolsExists = fs.existsSync('/Library/Developer/CommandLineTools/usr/bin/');
+ const xcodeAppExists = fs.existsSync('/Applications/Xcode.app/Contents/Developer/Tools');
+ const xcodeExists = fs.existsSync('/Library/Developer/Xcode/');
+ return (cmdLineToolsExists || xcodeExists || xcodeAppExists);
+}
- if (
- ch === lastNeedleChar &&
- this._sbmh_memcmp(data, pos, needleLength - 1)
- ) {
- this._lookbehind_size = 0
- ++this.matches
- this.emit('info', true)
+function nanoSeconds() {
+ const time = process.hrtime();
+ if (!Array.isArray(time) || time.length !== 2) {
+ return 0;
+ }
+ return +time[0] * 1e9 + +time[1];
+}
- return (this._bufpos = pos + needleLength)
+function countUniqueLines(lines, startingWith) {
+ startingWith = startingWith || '';
+ const uniqueLines = [];
+ lines.forEach(line => {
+ if (line.startsWith(startingWith)) {
+ if (uniqueLines.indexOf(line) === -1) {
+ uniqueLines.push(line);
}
- pos += this._occ[ch]
}
+ });
+ return uniqueLines.length;
+}
- // No match.
-
- if (pos < 0) {
- // There's too few data for Boyer-Moore-Horspool to run,
- // so let's use a different algorithm to skip as much as
- // we can.
- // Forward pos until
- // the trailing part of lookbehind + data
- // looks like the beginning of the needle
- // or until
- // pos == 0
- while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }
+function countLines(lines, startingWith) {
+ startingWith = startingWith || '';
+ const uniqueLines = [];
+ lines.forEach(line => {
+ if (line.startsWith(startingWith)) {
+ uniqueLines.push(line);
}
+ });
+ return uniqueLines.length;
+}
- if (pos >= 0) {
- // Discard lookbehind buffer.
- this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)
- this._lookbehind_size = 0
- } else {
- // Cut off part of the lookbehind buffer that has
- // been processed and append the entire haystack
- // into it.
- const bytesToCutOff = this._lookbehind_size + pos
- if (bytesToCutOff > 0) {
- // The cut off data is guaranteed not to contain the needle.
- this.emit('info', false, this._lookbehind, 0, bytesToCutOff)
- }
+function sanitizeShellString(str, strict) {
+ if (typeof strict === 'undefined') { strict = false; }
+ const s = str || '';
+ let result = '';
+ const l = mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (!(s[i] === undefined ||
+ s[i] === '>' ||
+ s[i] === '<' ||
+ s[i] === '*' ||
+ s[i] === '?' ||
+ s[i] === '[' ||
+ s[i] === ']' ||
+ s[i] === '|' ||
+ s[i] === '˚' ||
+ s[i] === '$' ||
+ s[i] === ';' ||
+ s[i] === '&' ||
+ s[i] === ']' ||
+ s[i] === '#' ||
+ s[i] === '\\' ||
+ s[i] === '\t' ||
+ s[i] === '\n' ||
+ s[i] === '\r' ||
+ s[i] === '\'' ||
+ s[i] === '`' ||
+ s[i] === '"' ||
+ s[i].length > 1 ||
+ (strict && s[i] === '(') ||
+ (strict && s[i] === ')') ||
+ (strict && s[i] === '@') ||
+ (strict && s[i] === ' ') ||
+ (strict && s[i] == '{') ||
+ (strict && s[i] == ';') ||
+ (strict && s[i] == '}'))) {
+ result = result + s[i];
+ }
+ }
+ return result;
+}
- this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,
- this._lookbehind_size - bytesToCutOff)
- this._lookbehind_size -= bytesToCutOff
+function isPrototypePolluted() {
+ const s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
+ let notPolluted = true;
+ let st = '';
- data.copy(this._lookbehind, this._lookbehind_size)
- this._lookbehind_size += len
+ try {
+ st.__proto__.replace = stringReplace;
+ st.__proto__.toLowerCase = stringToLower;
+ st.__proto__.toString = stringToString;
+ st.__proto__.substr = stringSubstr;
+ st.__proto__.substring = stringSubstring;
+ st.__proto__.trim = stringTrim;
+ st.__proto__.startsWith = stringStartWith;
+ } catch (e) {
+ Object.setPrototypeOf(st, stringObj);
+ }
+ notPolluted = notPolluted || (s.length !== 62);
+ const ms = Date.now();
+ if (typeof ms === 'number' && ms > 1600000000000) {
+ const l = ms % 100 + 15;
+ for (let i = 0; i < l; i++) {
+ const r = Math.random() * 61.99999999 + 1;
+ const rs = parseInt(Math.floor(r).toString(), 10);
+ const rs2 = parseInt(r.toString().split('.')[0], 10);
+ const q = Math.random() * 61.99999999 + 1;
+ const qs = parseInt(Math.floor(q).toString(), 10);
+ const qs2 = parseInt(q.toString().split('.')[0], 10);
+ notPolluted = notPolluted && (r !== q);
+ notPolluted = notPolluted && rs === rs2 && qs === qs2;
+ st += s[rs - 1];
+ }
+ notPolluted = notPolluted && st.length === l;
+ // string manipulation
+ let p = Math.random() * l * 0.9999999999;
+ let stm = st.substr(0, p) + ' ' + st.substr(p, 2000);
+ try {
+ stm.__proto__.replace = stringReplace;
+ } catch (e) {
+ Object.setPrototypeOf(stm, stringObj);
+ }
+ let sto = stm.replace(/ /g, '');
+ notPolluted = notPolluted && st === sto;
+ p = Math.random() * l * 0.9999999999;
+ stm = st.substr(0, p) + '{' + st.substr(p, 2000);
+ sto = stm.replace(/{/g, '');
+ notPolluted = notPolluted && st === sto;
+ p = Math.random() * l * 0.9999999999;
+ stm = st.substr(0, p) + '*' + st.substr(p, 2000);
+ sto = stm.replace(/\*/g, '');
+ notPolluted = notPolluted && st === sto;
+ p = Math.random() * l * 0.9999999999;
+ stm = st.substr(0, p) + '$' + st.substr(p, 2000);
+ sto = stm.replace(/\$/g, '');
+ notPolluted = notPolluted && st === sto;
- this._bufpos = len
- return len
+ // lower
+ const stl = st.toLowerCase();
+ notPolluted = notPolluted && (stl.length === l) && stl[l - 1] && !(stl[l]);
+ for (let i = 0; i < l; i++) {
+ const s1 = st[i];
+ try {
+ s1.__proto__.toLowerCase = stringToLower;
+ } catch (e) {
+ Object.setPrototypeOf(st, stringObj);
+ }
+ const s2 = stl ? stl[i] : '';
+ const s1l = s1.toLowerCase();
+ notPolluted = notPolluted && s1l[0] === s2 && s1l[0] && !(s1l[1]);
}
}
+ return !notPolluted;
+}
- pos += (pos >= 0) * this._bufpos
+function hex2bin(hex) {
+ return ('00000000' + (parseInt(hex, 16)).toString(2)).substr(-8);
+}
- // Lookbehind buffer is now empty. We only need to check if the
- // needle is in the haystack.
- if (data.indexOf(needle, pos) !== -1) {
- pos = data.indexOf(needle, pos)
- ++this.matches
- if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }
+function getFilesInPath(source) {
+ const lstatSync = fs.lstatSync;
+ const readdirSync = fs.readdirSync;
+ const join = path.join;
- return (this._bufpos = pos + needleLength)
- } else {
- pos = len - needleLength
+ function isDirectory(source) {
+ return lstatSync(source).isDirectory();
}
+ function isFile(source) { return lstatSync(source).isFile(); }
- // There was no match. If there's trailing haystack data that we cannot
- // match yet using the Boyer-Moore-Horspool algorithm (because the trailing
- // data is less than the needle size) then match using a modified
- // algorithm that starts matching from the beginning instead of the end.
- // Whatever trailing data is left after running this algorithm is added to
- // the lookbehind buffer.
- while (
- pos < len &&
- (
- data[pos] !== needle[0] ||
- (
- (Buffer.compare(
- data.subarray(pos, pos + len - pos),
- needle.subarray(0, len - pos)
- ) !== 0)
- )
- )
- ) {
- ++pos
+ function getDirectories(source) {
+ return readdirSync(source).map(function (name) { return join(source, name); }).filter(isDirectory);
}
- if (pos < len) {
- data.copy(this._lookbehind, 0, pos, pos + (len - pos))
- this._lookbehind_size = len - pos
+ function getFiles(source) {
+ return readdirSync(source).map(function (name) { return join(source, name); }).filter(isFile);
}
- // Everything until pos is guaranteed not to contain needle data.
- if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }
-
- this._bufpos = len
- return len
-}
-
-SBMH.prototype._sbmh_lookup_char = function (data, pos) {
- return (pos < 0)
- ? this._lookbehind[this._lookbehind_size + pos]
- : data[pos]
-}
+ function getFilesRecursively(source) {
+ try {
+ let dirs = getDirectories(source);
+ let files = dirs
+ .map(function (dir) { return getFilesRecursively(dir); })
+ .reduce(function (a, b) { return a.concat(b); }, []);
+ return files.concat(getFiles(source));
+ } catch (e) {
+ return [];
+ }
+ }
-SBMH.prototype._sbmh_memcmp = function (data, pos, len) {
- for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
- if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }
+ if (fs.existsSync(source)) {
+ return getFilesRecursively(source);
+ } else {
+ return [];
}
- return true
}
-module.exports = SBMH
+function decodePiCpuinfo(lines) {
+ if (_rpi_cpuinfo === null) {
+ _rpi_cpuinfo = lines;
+ }
-/***/ }),
+ // https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
-/***/ 75249:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ const oldRevisionCodes = {
+ '0002': {
+ type: 'B',
+ revision: '1.0',
+ memory: 256,
+ manufacturer: 'Egoman',
+ processor: 'BCM2835'
+ },
+ '0003': {
+ type: 'B',
+ revision: '1.0',
+ memory: 256,
+ manufacturer: 'Egoman',
+ processor: 'BCM2835'
+ },
+ '0004': {
+ type: 'B',
+ revision: '2.0',
+ memory: 256,
+ manufacturer: 'Sony UK',
+ processor: 'BCM2835'
+ },
+ '0005': {
+ type: 'B',
+ revision: '2.0',
+ memory: 256,
+ manufacturer: 'Qisda',
+ processor: 'BCM2835'
+ },
+ '0006': {
+ type: 'B',
+ revision: '2.0',
+ memory: 256,
+ manufacturer: 'Egoman',
+ processor: 'BCM2835'
+ },
+ '0007': {
+ type: 'A',
+ revision: '2.0',
+ memory: 256,
+ manufacturer: 'Egoman',
+ processor: 'BCM2835'
+ },
+ '0008': {
+ type: 'A',
+ revision: '2.0',
+ memory: 256,
+ manufacturer: 'Sony UK',
+ processor: 'BCM2835'
+ },
+ '0009': {
+ type: 'A',
+ revision: '2.0',
+ memory: 256,
+ manufacturer: 'Qisda',
+ processor: 'BCM2835'
+ },
+ '000d': {
+ type: 'B',
+ revision: '2.0',
+ memory: 512,
+ manufacturer: 'Egoman',
+ processor: 'BCM2835'
+ },
+ '000e': {
+ type: 'B',
+ revision: '2.0',
+ memory: 512,
+ manufacturer: 'Sony UK',
+ processor: 'BCM2835'
+ },
+ '000f': {
+ type: 'B',
+ revision: '2.0',
+ memory: 512,
+ manufacturer: 'Egoman',
+ processor: 'BCM2835'
+ },
+ '0010': {
+ type: 'B+',
+ revision: '1.2',
+ memory: 512,
+ manufacturer: 'Sony UK',
+ processor: 'BCM2835'
+ },
+ '0011': {
+ type: 'CM1',
+ revision: '1.0',
+ memory: 512,
+ manufacturer: 'Sony UK',
+ processor: 'BCM2835'
+ },
+ '0012': {
+ type: 'A+',
+ revision: '1.1',
+ memory: 256,
+ manufacturer: 'Sony UK',
+ processor: 'BCM2835'
+ },
+ '0013': {
+ type: 'B+',
+ revision: '1.2',
+ memory: 512,
+ manufacturer: 'Embest',
+ processor: 'BCM2835'
+ },
+ '0014': {
+ type: 'CM1',
+ revision: '1.0',
+ memory: 512,
+ manufacturer: 'Embest',
+ processor: 'BCM2835'
+ },
+ '0015': {
+ type: 'A+',
+ revision: '1.1',
+ memory: 256,
+ manufacturer: '512MB Embest',
+ processor: 'BCM2835'
+ }
+ };
+ const processorList = [
+ 'BCM2835',
+ 'BCM2836',
+ 'BCM2837',
+ 'BCM2711',
+ 'BCM2712',
+ ];
+ const manufacturerList = [
+ 'Sony UK',
+ 'Egoman',
+ 'Embest',
+ 'Sony Japan',
+ 'Embest',
+ 'Stadium'
+ ];
+ const typeList = {
+ '00': 'A',
+ '01': 'B',
+ '02': 'A+',
+ '03': 'B+',
+ '04': '2B',
+ '05': 'Alpha (early prototype)',
+ '06': 'CM1',
+ '08': '3B',
+ '09': 'Zero',
+ '0a': 'CM3',
+ '0c': 'Zero W',
+ '0d': '3B+',
+ '0e': '3A+',
+ '0f': 'Internal use only',
+ '10': 'CM3+',
+ '11': '4B',
+ '12': 'Zero 2 W',
+ '13': '400',
+ '14': 'CM4',
+ '15': 'CM4S',
+ '16': 'Internal use only',
+ '17': '5',
+ '18': 'CM5',
+ '19': '500',
+ '1a': 'CM5 Lite',
+ };
+ const revisionCode = getValue(lines, 'revision', ':', true);
+ const model = getValue(lines, 'model:', ':', true);
+ const serial = getValue(lines, 'serial', ':', true);
-const WritableStream = (__nccwpck_require__(57075).Writable)
-const { inherits } = __nccwpck_require__(57975)
-const Dicer = __nccwpck_require__(8946)
+ let result = {};
+ if ({}.hasOwnProperty.call(oldRevisionCodes, revisionCode)) {
+ // old revision codes
+ result = {
+ model,
+ serial,
+ revisionCode,
+ memory: oldRevisionCodes[revisionCode].memory,
+ manufacturer: oldRevisionCodes[revisionCode].manufacturer,
+ processor: oldRevisionCodes[revisionCode].processor,
+ type: oldRevisionCodes[revisionCode].type,
+ revision: oldRevisionCodes[revisionCode].revision,
+ };
-const MultipartParser = __nccwpck_require__(35764)
-const UrlencodedParser = __nccwpck_require__(21411)
-const parseParams = __nccwpck_require__(60717)
+ } else {
+ // new revision code
+ const revision = ('00000000' + getValue(lines, 'revision', ':', true).toLowerCase()).substr(-8);
+ const memSizeCode = parseInt(hex2bin(revision.substr(2, 1)).substr(5, 3), 2) || 0;
+ const manufacturer = manufacturerList[parseInt(revision.substr(3, 1), 10)];
+ const processor = processorList[parseInt(revision.substr(4, 1), 10)];
+ const typeCode = revision.substr(5, 2);
-function Busboy (opts) {
- if (!(this instanceof Busboy)) { return new Busboy(opts) }
- if (typeof opts !== 'object') {
- throw new TypeError('Busboy expected an options-Object.')
+ result = {
+ model,
+ serial,
+ revisionCode,
+ memory: 256 * Math.pow(2, memSizeCode),
+ manufacturer,
+ processor,
+ type: {}.hasOwnProperty.call(typeList, typeCode) ? typeList[typeCode] : '',
+ revision: '1.' + revision.substr(7, 1),
+ };
}
- if (typeof opts.headers !== 'object') {
- throw new TypeError('Busboy expected an options-Object with headers-attribute.')
+ return result;
+}
+
+function getRpiGpu() {
+ let cpuinfo = null;
+ if (_rpi_cpuinfo !== null) {
+ cpuinfo = _rpi_cpuinfo;
+ } else {
+ try {
+ cpuinfo = fs.readFileSync('/proc/cpuinfo', { encoding: 'utf8' }).toString().split('\n');
+ _rpi_cpuinfo = cpuinfo;
+ } catch (e) {
+ return false;
+ }
}
- if (typeof opts.headers['content-type'] !== 'string') {
- throw new TypeError('Missing Content-Type-header.')
+
+ const rpi = decodePiCpuinfo(cpuinfo);
+ if (rpi.type === '4B' || rpi.type === 'CM4' || rpi.type === 'CM4S' || rpi.type === '400') { return 'VideoCore VI'; }
+ if (rpi.type === '5') { return 'VideoCore VII'; }
+ return 'VideoCore IV';
+}
+
+function promiseAll(promises) {
+ const resolvingPromises = promises.map(function (promise) {
+ return new Promise(function (resolve) {
+ let payload = new Array(2);
+ promise.then(function (result) {
+ payload[0] = result;
+ })
+ .catch(function (error) {
+ payload[1] = error;
+ })
+ .then(function () {
+ // The wrapped Promise returns an array: 0 = result, 1 = error ... we resolve all
+ resolve(payload);
+ });
+ });
+ });
+ const errors = [];
+ const results = [];
+
+ // Execute all wrapped Promises
+ return Promise.all(resolvingPromises)
+ .then(function (items) {
+ items.forEach(function (payload) {
+ if (payload[1]) {
+ errors.push(payload[1]);
+ results.push(null);
+ } else {
+ errors.push(null);
+ results.push(payload[0]);
+ }
+ });
+
+ return {
+ errors: errors,
+ results: results
+ };
+ });
+}
+
+function promisify(nodeStyleFunction) {
+ return function () {
+ const args = Array.prototype.slice.call(arguments);
+ return new Promise(function (resolve, reject) {
+ args.push(function (err, data) {
+ if (err) {
+ reject(err);
+ } else {
+ resolve(data);
+ }
+ });
+ nodeStyleFunction.apply(null, args);
+ });
+ };
+}
+
+function promisifySave(nodeStyleFunction) {
+ return function () {
+ const args = Array.prototype.slice.call(arguments);
+ return new Promise(function (resolve) {
+ args.push(function (err, data) {
+ resolve(data);
+ });
+ nodeStyleFunction.apply(null, args);
+ });
+ };
+}
+
+function linuxVersion() {
+ let result = '';
+ if (_linux) {
+ try {
+ result = execSync('uname -v', execOptsLinux).toString();
+ } catch (e) {
+ result = '';
+ }
}
+ return result;
+}
- const {
- headers,
- ...streamOptions
- } = opts
+function plistParser(xmlStr) {
+ const tags = ['array', 'dict', 'key', 'string', 'integer', 'date', 'real', 'data', 'boolean', 'arrayEmpty'];
+ const startStr = '' && pos < len) {
+ pos++;
}
- WritableStream.call(this, this.opts)
- this._done = false
- this._parser = this.getParserByHeaders(headers)
- this._finished = false
-}
-inherits(Busboy, WritableStream)
+ let depth = 0;
+ let inTagStart = false;
+ let inTagContent = false;
+ let inTagEnd = false;
+ let metaData = [{ tagStart: '', tagEnd: '', tagContent: '', key: '', data: null }];
+ let c = '';
+ let cn = xmlStr[pos];
-Busboy.prototype.emit = function (ev) {
- if (ev === 'finish') {
- if (!this._done) {
- this._parser?.end()
- return
- } else if (this._finished) {
- return
+ while (pos < len) {
+ c = cn;
+ if (pos + 1 < len) { cn = xmlStr[pos + 1]; }
+ if (c === '<') {
+ inTagContent = false;
+ if (cn === '/') { inTagEnd = true; }
+ else if (metaData[depth].tagStart) {
+ metaData[depth].tagContent = '';
+ if (!metaData[depth].data) { metaData[depth].data = metaData[depth].tagStart === 'array' ? [] : {}; }
+ depth++;
+ metaData.push({ tagStart: '', tagEnd: '', tagContent: '', key: null, data: null });
+ inTagStart = true;
+ inTagContent = false;
+ }
+ else if (!inTagStart) { inTagStart = true; }
+ } else if (c === '>') {
+ if (metaData[depth].tagStart === 'true/') { inTagStart = false; inTagEnd = true; metaData[depth].tagStart = ''; metaData[depth].tagEnd = '/boolean'; metaData[depth].data = true; }
+ if (metaData[depth].tagStart === 'false/') { inTagStart = false; inTagEnd = true; metaData[depth].tagStart = ''; metaData[depth].tagEnd = '/boolean'; metaData[depth].data = false; }
+ if (metaData[depth].tagStart === 'array/') { inTagStart = false; inTagEnd = true; metaData[depth].tagStart = ''; metaData[depth].tagEnd = '/arrayEmpty'; metaData[depth].data = []; }
+ if (inTagContent) { inTagContent = false; }
+ if (inTagStart) {
+ inTagStart = false;
+ inTagContent = true;
+ if (metaData[depth].tagStart === 'array') {
+ metaData[depth].data = [];
+ }
+ if (metaData[depth].tagStart === 'dict') {
+ metaData[depth].data = {};
+ }
+ }
+ if (inTagEnd) {
+ inTagEnd = false;
+ if (metaData[depth].tagEnd && tags.indexOf(metaData[depth].tagEnd.substr(1)) >= 0) {
+ if (metaData[depth].tagEnd === '/dict' || metaData[depth].tagEnd === '/array') {
+ if (depth > 1 && metaData[depth - 2].tagStart === 'array') {
+ metaData[depth - 2].data.push(metaData[depth - 1].data);
+ }
+ if (depth > 1 && metaData[depth - 2].tagStart === 'dict') {
+ metaData[depth - 2].data[metaData[depth - 1].key] = metaData[depth - 1].data;
+ }
+ depth--;
+ metaData.pop();
+ metaData[depth].tagContent = '';
+ metaData[depth].tagStart = '';
+ metaData[depth].tagEnd = '';
+ }
+ else {
+ if (metaData[depth].tagEnd === '/key' && metaData[depth].tagContent) {
+ metaData[depth].key = metaData[depth].tagContent;
+ } else {
+ if (metaData[depth].tagEnd === '/real' && metaData[depth].tagContent) { metaData[depth].data = parseFloat(metaData[depth].tagContent) || 0; }
+ if (metaData[depth].tagEnd === '/integer' && metaData[depth].tagContent) { metaData[depth].data = parseInt(metaData[depth].tagContent) || 0; }
+ if (metaData[depth].tagEnd === '/string' && metaData[depth].tagContent) { metaData[depth].data = metaData[depth].tagContent || ''; }
+ if (metaData[depth].tagEnd === '/boolean') { metaData[depth].data = metaData[depth].tagContent || false; }
+ if (metaData[depth].tagEnd === '/arrayEmpty') { metaData[depth].data = metaData[depth].tagContent || []; }
+ if (depth > 0 && metaData[depth - 1].tagStart === 'array') { metaData[depth - 1].data.push(metaData[depth].data); }
+ if (depth > 0 && metaData[depth - 1].tagStart === 'dict') { metaData[depth - 1].data[metaData[depth].key] = metaData[depth].data; }
+ }
+ metaData[depth].tagContent = '';
+ metaData[depth].tagStart = '';
+ metaData[depth].tagEnd = '';
+ }
+ }
+ metaData[depth].tagEnd = '';
+ inTagStart = false;
+ inTagContent = false;
+ }
+ } else {
+ if (inTagStart) { metaData[depth].tagStart += c; }
+ if (inTagEnd) { metaData[depth].tagEnd += c; }
+ if (inTagContent) { metaData[depth].tagContent += c; }
}
- this._finished = true
- }
- WritableStream.prototype.emit.apply(this, arguments)
-}
-
-Busboy.prototype.getParserByHeaders = function (headers) {
- const parsed = parseParams(headers['content-type'])
-
- const cfg = {
- defCharset: this.opts.defCharset,
- fileHwm: this.opts.fileHwm,
- headers,
- highWaterMark: this.opts.highWaterMark,
- isPartAFile: this.opts.isPartAFile,
- limits: this.opts.limits,
- parsedConType: parsed,
- preservePath: this.opts.preservePath
- }
-
- if (MultipartParser.detect.test(parsed[0])) {
- return new MultipartParser(this, cfg)
- }
- if (UrlencodedParser.detect.test(parsed[0])) {
- return new UrlencodedParser(this, cfg)
+ pos++;
}
- throw new Error('Unsupported Content-Type.')
+ return metaData[0].data;
}
-Busboy.prototype._write = function (chunk, encoding, cb) {
- this._parser.write(chunk, cb)
+function strIsNumeric(str) {
+ return typeof str === 'string' && !isNaN(str) && !isNaN(parseFloat(str));
}
-module.exports = Busboy
-module.exports["default"] = Busboy
-module.exports.Busboy = Busboy
-
-module.exports.Dicer = Dicer
-
-
-/***/ }),
-
-/***/ 35764:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-// TODO:
-// * support 1 nested multipart level
-// (see second multipart example here:
-// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
-// * support limits.fieldNameSize
-// -- this will require modifications to utils.parseParams
-
-const { Readable } = __nccwpck_require__(57075)
-const { inherits } = __nccwpck_require__(57975)
-
-const Dicer = __nccwpck_require__(8946)
-
-const parseParams = __nccwpck_require__(60717)
-const decodeText = __nccwpck_require__(16607)
-const basename = __nccwpck_require__(15080)
-const getLimit = __nccwpck_require__(5245)
-
-const RE_BOUNDARY = /^boundary$/i
-const RE_FIELD = /^form-data$/i
-const RE_CHARSET = /^charset$/i
-const RE_FILENAME = /^filename$/i
-const RE_NAME = /^name$/i
-
-Multipart.detect = /^multipart\/form-data/i
-function Multipart (boy, cfg) {
- let i
- let len
- const self = this
- let boundary
- const limits = cfg.limits
- const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))
- const parsedConType = cfg.parsedConType || []
- const defCharset = cfg.defCharset || 'utf8'
- const preservePath = cfg.preservePath
- const fileOpts = { highWaterMark: cfg.fileHwm }
-
- for (i = 0, len = parsedConType.length; i < len; ++i) {
- if (Array.isArray(parsedConType[i]) &&
- RE_BOUNDARY.test(parsedConType[i][0])) {
- boundary = parsedConType[i][1]
- break
+function plistReader(output) {
+ const lines = output.split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i].indexOf(' = ') >= 0) {
+ const lineParts = lines[i].split(' = ');
+ lineParts[0] = lineParts[0].trim();
+ if (!lineParts[0].startsWith('"')) {
+ lineParts[0] = '"' + lineParts[0] + '"';
+ }
+ lineParts[1] = lineParts[1].trim();
+ if (lineParts[1].indexOf('"') === -1 && lineParts[1].endsWith(';')) {
+ const valueString = lineParts[1].substring(0, lineParts[1].length - 1);
+ if (!strIsNumeric(valueString)) {
+ lineParts[1] = `"${valueString}";`;
+ }
+ }
+ if (lineParts[1].indexOf('"') >= 0 && lineParts[1].endsWith(';')) {
+ const valueString = lineParts[1].substring(0, lineParts[1].length - 1).replace(/"/g, '');
+ if (strIsNumeric(valueString)) {
+ lineParts[1] = `${valueString};`;
+ }
+ }
+ lines[i] = lineParts.join(' : ');
}
- }
-
- function checkFinished () {
- if (nends === 0 && finished && !boy._done) {
- finished = false
- self.end()
+ lines[i] = lines[i].replace(/\(/g, '[').replace(/\)/g, ']').replace(/;/g, ',').trim();
+ if (lines[i].startsWith('}') && lines[i - 1] && lines[i - 1].endsWith(',')) {
+ lines[i - 1] = lines[i - 1].substring(0, lines[i - 1].length - 1);
}
}
-
- if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }
-
- const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
- const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)
- const filesLimit = getLimit(limits, 'files', Infinity)
- const fieldsLimit = getLimit(limits, 'fields', Infinity)
- const partsLimit = getLimit(limits, 'parts', Infinity)
- const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)
- const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)
-
- let nfiles = 0
- let nfields = 0
- let nends = 0
- let curFile
- let curField
- let finished = false
-
- this._needDrain = false
- this._pause = false
- this._cb = undefined
- this._nparts = 0
- this._boy = boy
-
- const parserCfg = {
- boundary,
- maxHeaderPairs: headerPairsLimit,
- maxHeaderSize: headerSizeLimit,
- partHwm: fileOpts.highWaterMark,
- highWaterMark: cfg.highWaterMark
+ output = lines.join('');
+ let obj = {};
+ try {
+ obj = JSON.parse(output);
+ } catch (e) {
+ noop();
}
+ return obj;
+}
- this.parser = new Dicer(parserCfg)
- this.parser.on('drain', function () {
- self._needDrain = false
- if (self._cb && !self._pause) {
- const cb = self._cb
- self._cb = undefined
- cb()
- }
- }).on('part', function onPart (part) {
- if (++self._nparts > partsLimit) {
- self.parser.removeListener('part', onPart)
- self.parser.on('part', skipPart)
- boy.hitPartsLimit = true
- boy.emit('partsLimit')
- return skipPart(part)
+function semverCompare(v1, v2) {
+ let res = 0;
+ const parts1 = v1.split('.');
+ const parts2 = v2.split('.');
+ if (parts1[0] < parts2[0]) { res = 1; }
+ else if (parts1[0] > parts2[0]) { res = -1; }
+ else if (parts1[0] === parts2[0] && parts1.length >= 2 && parts2.length >= 2) {
+ if (parts1[1] < parts2[1]) { res = 1; }
+ else if (parts1[1] > parts2[1]) { res = -1; }
+ else if (parts1[1] === parts2[1]) {
+ if (parts1.length >= 3 && parts2.length >= 3) {
+ if (parts1[2] < parts2[2]) { res = 1; }
+ else if (parts1[2] > parts2[2]) { res = -1; }
+ } else if (parts2.length >= 3) {
+ res = 1;
+ }
}
+ }
+ return res;
+}
- // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
- // us emit 'end' early since we know the part has ended if we are already
- // seeing the next part
- if (curField) {
- const field = curField
- field.emit('end')
- field.removeAllListeners('end')
+function getAppleModel(key) {
+ const appleModelIds = [
+ {
+ key: 'Mac15,12',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: 'M3',
+ year: '2024',
+ additional: ''
+ },
+ {
+ key: 'Mac14,15',
+ name: 'MacBook Air',
+ size: '15-inch',
+ processor: 'M2',
+ year: '2024',
+ additional: ''
+ },
+ {
+ key: 'Mac14,2',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: 'M2',
+ year: '2022',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir10,1',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: 'M1',
+ year: '2020',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir9,1',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: '2020',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir8,2',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: '2019',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir8,1',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: '2018',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir7,2',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: '2017',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir7,2',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: 'Early 2015',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir7,1',
+ name: 'MacBook Air',
+ size: '11-inch',
+ processor: '',
+ year: 'Early 2015',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir6,2',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: 'Early 2014',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir6,1',
+ name: 'MacBook Air',
+ size: '11-inch',
+ processor: '',
+ year: 'Early 2014',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir6,2',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: 'Mid 2013',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir6,1',
+ name: 'MacBook Air',
+ size: '11-inch',
+ processor: '',
+ year: 'Mid 2013',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir5,2',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: 'Mid 2012',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir5,1',
+ name: 'MacBook Air',
+ size: '11-inch',
+ processor: '',
+ year: 'Mid 2012',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir4,2',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: 'Mid 2011',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir4,1',
+ name: 'MacBook Air',
+ size: '11-inch',
+ processor: '',
+ year: 'Mid 2011',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir3,2',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: 'Late 2010',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir3,1',
+ name: 'MacBook Air',
+ size: '11-inch',
+ processor: '',
+ year: 'Late 2010',
+ additional: ''
+ },
+ {
+ key: 'MacBookAir2,1',
+ name: 'MacBook Air',
+ size: '13-inch',
+ processor: '',
+ year: 'Mid 2009',
+ additional: ''
+ },
+ {
+ key: 'Mac16,1',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M4',
+ year: '2024',
+ additional: ''
+ },
+ {
+ key: 'Mac16,6',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M4 Pro',
+ year: '2024',
+ additional: ''
+ },
+ {
+ key: 'Mac16,8',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M4 Max',
+ year: '2024',
+ additional: ''
+ },
+ {
+ key: 'Mac16,5',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: 'M4 Pro',
+ year: '2024',
+ additional: ''
+ },
+ {
+ key: 'Mac16,6',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: 'M4 Max',
+ year: '2024',
+ additional: ''
+ },
+ {
+ key: 'Mac15,3',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M3',
+ year: 'Nov 2023',
+ additional: ''
+ },
+ {
+ key: 'Mac15,6',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M3 Pro',
+ year: 'Nov 2023',
+ additional: ''
+ },
+ {
+ key: 'Mac15,8',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M3 Pro',
+ year: 'Nov 2023',
+ additional: ''
+ },
+ {
+ key: 'Mac15,10',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M3 Max',
+ year: 'Nov 2023',
+ additional: ''
+ },
+ {
+ key: 'Mac15,7',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: 'M3 Pro',
+ year: 'Nov 2023',
+ additional: ''
+ },
+ {
+ key: 'Mac15,9',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: 'M3 Pro',
+ year: 'Nov 2023',
+ additional: ''
+ },
+ {
+ key: 'Mac15,11',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: 'M3 Max',
+ year: 'Nov 2023',
+ additional: ''
+ },
+ {
+ key: 'Mac14,5',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M2 Max',
+ year: '2023',
+ additional: ''
+ },
+ {
+ key: 'Mac14,9',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M2 Max',
+ year: '2023',
+ additional: ''
+ },
+ {
+ key: 'Mac14,6',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: 'M2 Max',
+ year: '2023',
+ additional: ''
+ },
+ {
+ key: 'Mac14,10',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: 'M2 Max',
+ year: '2023',
+ additional: ''
+ },
+ {
+ key: 'Mac14,7',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: 'M2',
+ year: '2022',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro18,3',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M1 Pro',
+ year: '2021',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro18,4',
+ name: 'MacBook Pro',
+ size: '14-inch',
+ processor: 'M1 Max',
+ year: '2021',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro18,1',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: 'M1 Pro',
+ year: '2021',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro18,2',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: 'M1 Max',
+ year: '2021',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro17,1',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: 'M1',
+ year: '2020',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro16,3',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: '2020',
+ additional: 'Two Thunderbolt 3 ports'
+ },
+ {
+ key: 'MacBookPro16,2',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: '2020',
+ additional: 'Four Thunderbolt 3 ports'
+ },
+ {
+ key: 'MacBookPro16,1',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: '',
+ year: '2019',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro16,4',
+ name: 'MacBook Pro',
+ size: '16-inch',
+ processor: '',
+ year: '2019',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro15,3',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: '2019',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro15,2',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: '2019',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro15,1',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: '2019',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro15,4',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: '2019',
+ additional: 'Two Thunderbolt 3 ports'
+ },
+ {
+ key: 'MacBookPro15,1',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: '2018',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro15,2',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: '2018',
+ additional: 'Four Thunderbolt 3 ports'
+ },
+ {
+ key: 'MacBookPro14,1',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: '2017',
+ additional: 'Two Thunderbolt 3 ports'
+ },
+ {
+ key: 'MacBookPro14,2',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: '2017',
+ additional: 'Four Thunderbolt 3 ports'
+ },
+ {
+ key: 'MacBookPro14,3',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: '2017',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro13,1',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: '2016',
+ additional: 'Two Thunderbolt 3 ports'
+ },
+ {
+ key: 'MacBookPro13,2',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: '2016',
+ additional: 'Four Thunderbolt 3 ports'
+ },
+ {
+ key: 'MacBookPro13,3',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: '2016',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro11,4',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Mid 2015',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro11,5',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Mid 2015',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro12,1',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: 'Early 2015',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro11,2',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Late 2013',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro11,3',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Late 2013',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro11,1',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: 'Late 2013',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro10,1',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Mid 2012',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro10,2',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: 'Late 2012',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro9,1',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Mid 2012',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro9,2',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: 'Mid 2012',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro8,3',
+ name: 'MacBook Pro',
+ size: '17-inch',
+ processor: '',
+ year: 'Early 2011',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro8,2',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Early 2011',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro8,1',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: 'Early 2011',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro6,1',
+ name: 'MacBook Pro',
+ size: '17-inch',
+ processor: '',
+ year: 'Mid 2010',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro6,2',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Mid 2010',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro7,1',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: 'Mid 2010',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro5,2',
+ name: 'MacBook Pro',
+ size: '17-inch',
+ processor: '',
+ year: 'Early 2009',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro5,3',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Mid 2009',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro5,5',
+ name: 'MacBook Pro',
+ size: '13-inch',
+ processor: '',
+ year: 'Mid 2009',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro5,1',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Late 2008',
+ additional: ''
+ },
+ {
+ key: 'MacBookPro4,1',
+ name: 'MacBook Pro',
+ size: '15-inch',
+ processor: '',
+ year: 'Early 2008',
+ additional: ''
+ },
+ {
+ key: 'MacBook10,1',
+ name: 'MacBook',
+ size: '12-inch',
+ processor: '',
+ year: '2017',
+ additional: ''
+ },
+ {
+ key: 'MacBook9,1',
+ name: 'MacBook',
+ size: '12-inch',
+ processor: '',
+ year: 'Early 2016',
+ additional: ''
+ },
+ {
+ key: 'MacBook8,1',
+ name: 'MacBook',
+ size: '12-inch',
+ processor: '',
+ year: 'Early 2015',
+ additional: ''
+ },
+ {
+ key: 'MacBook7,1',
+ name: 'MacBook',
+ size: '13-inch',
+ processor: '',
+ year: 'Mid 2010',
+ additional: ''
+ },
+ {
+ key: 'MacBook6,1',
+ name: 'MacBook',
+ size: '13-inch',
+ processor: '',
+ year: 'Late 2009',
+ additional: ''
+ },
+ {
+ key: 'MacBook5,2',
+ name: 'MacBook',
+ size: '13-inch',
+ processor: '',
+ year: 'Early 2009',
+ additional: ''
+ },
+ {
+ key: 'Mac14,13',
+ name: 'Mac Studio',
+ size: '',
+ processor: '',
+ year: '2023',
+ additional: ''
+ },
+ {
+ key: 'Mac14,14',
+ name: 'Mac Studio',
+ size: '',
+ processor: '',
+ year: '2023',
+ additional: ''
+ },
+ {
+ key: 'Mac13,1',
+ name: 'Mac Studio',
+ size: '',
+ processor: '',
+ year: '2022',
+ additional: ''
+ },
+ {
+ key: 'Mac13,2',
+ name: 'Mac Studio',
+ size: '',
+ processor: '',
+ year: '2022',
+ additional: ''
+ },
+ {
+ key: 'Mac16,11',
+ name: 'Mac mini',
+ size: '',
+ processor: 'M4 Pro',
+ year: '2024',
+ additional: ''
+ },
+ {
+ key: 'Mac16,10',
+ name: 'Mac mini',
+ size: '',
+ processor: 'M4',
+ year: '2024',
+ additional: ''
+ },
+ {
+ key: 'Mac14,3',
+ name: 'Mac mini',
+ size: '',
+ processor: 'M2',
+ year: '2023',
+ additional: ''
+ },
+ {
+ key: 'Mac14,12',
+ name: 'Mac mini',
+ size: '',
+ processor: 'M2 Pro',
+ year: '2023',
+ additional: ''
+ },
+ {
+ key: 'Macmini9,1',
+ name: 'Mac mini',
+ size: '',
+ processor: 'M1',
+ year: '2020',
+ additional: ''
+ },
+ {
+ key: 'Macmini8,1',
+ name: 'Mac mini',
+ size: '',
+ processor: '',
+ year: 'Late 2018',
+ additional: ''
+ },
+ {
+ key: 'Macmini7,1',
+ name: 'Mac mini',
+ size: '',
+ processor: '',
+ year: 'Late 2014',
+ additional: ''
+ },
+ {
+ key: 'Macmini6,1',
+ name: 'Mac mini',
+ size: '',
+ processor: '',
+ year: 'Late 2012',
+ additional: ''
+ },
+ {
+ key: 'Macmini6,2',
+ name: 'Mac mini',
+ size: '',
+ processor: '',
+ year: 'Late 2012',
+ additional: ''
+ },
+ {
+ key: 'Macmini5,1',
+ name: 'Mac mini',
+ size: '',
+ processor: '',
+ year: 'Mid 2011',
+ additional: ''
+ },
+ {
+ key: 'Macmini5,2',
+ name: 'Mac mini',
+ size: '',
+ processor: '',
+ year: 'Mid 2011',
+ additional: ''
+ },
+ {
+ key: 'Macmini4,1',
+ name: 'Mac mini',
+ size: '',
+ processor: '',
+ year: 'Mid 2010',
+ additional: ''
+ },
+ {
+ key: 'Macmini3,1',
+ name: 'Mac mini',
+ size: '',
+ processor: '',
+ year: 'Early 2009',
+ additional: ''
+ },
+ {
+ key: 'Mac16,3',
+ name: 'iMac',
+ size: '24-inch',
+ processor: 'M4',
+ year: '2024',
+ additional: 'Four ports'
+ },
+ {
+ key: 'Mac16,2',
+ name: 'iMac',
+ size: '24-inch',
+ processor: 'M4',
+ year: '2024',
+ additional: 'Two ports'
+ },
+ {
+ key: 'Mac15,5',
+ name: 'iMac',
+ size: '24-inch',
+ processor: 'M3',
+ year: '2023',
+ additional: 'Four ports'
+ },
+ {
+ key: 'Mac15,4',
+ name: 'iMac',
+ size: '24-inch',
+ processor: 'M3',
+ year: '2023',
+ additional: 'Two ports'
+ },
+ {
+ key: 'iMac21,1',
+ name: 'iMac',
+ size: '24-inch',
+ processor: 'M1',
+ year: '2021',
+ additional: ''
+ },
+ {
+ key: 'iMac21,2',
+ name: 'iMac',
+ size: '24-inch',
+ processor: 'M1',
+ year: '2021',
+ additional: ''
+ },
+ {
+ key: 'iMac20,1',
+ name: 'iMac',
+ size: '27-inch',
+ processor: '',
+ year: '2020',
+ additional: 'Retina 5K'
+ },
+ {
+ key: 'iMac20,2',
+ name: 'iMac',
+ size: '27-inch',
+ processor: '',
+ year: '2020',
+ additional: 'Retina 5K'
+ },
+ {
+ key: 'iMac19,1',
+ name: 'iMac',
+ size: '27-inch',
+ processor: '',
+ year: '2019',
+ additional: 'Retina 5K'
+ },
+ {
+ key: 'iMac19,2',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: '2019',
+ additional: 'Retina 4K'
+ },
+ {
+ key: 'iMacPro1,1',
+ name: 'iMac Pro',
+ size: '',
+ processor: '',
+ year: '2017',
+ additional: ''
+ },
+ {
+ key: 'iMac18,3',
+ name: 'iMac',
+ size: '27-inch',
+ processor: '',
+ year: '2017',
+ additional: 'Retina 5K'
+ },
+ {
+ key: 'iMac18,2',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: '2017',
+ additional: 'Retina 4K'
+ },
+ {
+ key: 'iMac18,1',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: '2017',
+ additional: ''
+ },
+ {
+ key: 'iMac17,1',
+ name: 'iMac',
+ size: '27-inch',
+ processor: '',
+ year: 'Late 2015',
+ additional: 'Retina 5K'
+ },
+ {
+ key: 'iMac16,2',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: 'Late 2015',
+ additional: 'Retina 4K'
+ },
+ {
+ key: 'iMac16,1',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: 'Late 2015',
+ additional: ''
+ },
+ {
+ key: 'iMac15,1',
+ name: 'iMac',
+ size: '27-inch',
+ processor: '',
+ year: 'Late 2014',
+ additional: 'Retina 5K'
+ },
+ {
+ key: 'iMac14,4',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: 'Mid 2014',
+ additional: ''
+ },
+ {
+ key: 'iMac14,2',
+ name: 'iMac',
+ size: '27-inch',
+ processor: '',
+ year: 'Late 2013',
+ additional: ''
+ },
+ {
+ key: 'iMac14,1',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: 'Late 2013',
+ additional: ''
+ },
+ {
+ key: 'iMac13,2',
+ name: 'iMac',
+ size: '27-inch',
+ processor: '',
+ year: 'Late 2012',
+ additional: ''
+ },
+ {
+ key: 'iMac13,1',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: 'Late 2012',
+ additional: ''
+ },
+ {
+ key: 'iMac12,2',
+ name: 'iMac',
+ size: '27-inch',
+ processor: '',
+ year: 'Mid 2011',
+ additional: ''
+ },
+ {
+ key: 'iMac12,1',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: 'Mid 2011',
+ additional: ''
+ },
+ {
+ key: 'iMac11,3',
+ name: 'iMac',
+ size: '27-inch',
+ processor: '',
+ year: 'Mid 2010',
+ additional: ''
+ },
+ {
+ key: 'iMac11,2',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: 'Mid 2010',
+ additional: ''
+ },
+ {
+ key: 'iMac10,1',
+ name: 'iMac',
+ size: '21.5-inch',
+ processor: '',
+ year: 'Late 2009',
+ additional: ''
+ },
+ {
+ key: 'iMac9,1',
+ name: 'iMac',
+ size: '20-inch',
+ processor: '',
+ year: 'Early 2009',
+ additional: ''
+ },
+ {
+ key: 'Mac14,8',
+ name: 'Mac Pro',
+ size: '',
+ processor: '',
+ year: '2023',
+ additional: ''
+ },
+ {
+ key: 'Mac14,8',
+ name: 'Mac Pro',
+ size: '',
+ processor: '',
+ year: '2023',
+ additional: 'Rack'
+ },
+ {
+ key: 'MacPro7,1',
+ name: 'Mac Pro',
+ size: '',
+ processor: '',
+ year: '2019',
+ additional: ''
+ },
+ {
+ key: 'MacPro7,1',
+ name: 'Mac Pro',
+ size: '',
+ processor: '',
+ year: '2019',
+ additional: 'Rack'
+ },
+ {
+ key: 'MacPro6,1',
+ name: 'Mac Pro',
+ size: '',
+ processor: '',
+ year: 'Late 2013',
+ additional: ''
+ },
+ {
+ key: 'MacPro5,1',
+ name: 'Mac Pro',
+ size: '',
+ processor: '',
+ year: 'Mid 2012',
+ additional: ''
+ },
+ {
+ key: 'MacPro5,1',
+ name: 'Mac Pro Server',
+ size: '',
+ processor: '',
+ year: 'Mid 2012',
+ additional: 'Server'
+ },
+ {
+ key: 'MacPro5,1',
+ name: 'Mac Pro',
+ size: '',
+ processor: '',
+ year: 'Mid 2010',
+ additional: ''
+ },
+ {
+ key: 'MacPro5,1',
+ name: 'Mac Pro Server',
+ size: '',
+ processor: '',
+ year: 'Mid 2010',
+ additional: 'Server'
+ },
+ {
+ key: 'MacPro4,1',
+ name: 'Mac Pro',
+ size: '',
+ processor: '',
+ year: 'Early 2009',
+ additional: ''
}
+ ];
- part.on('header', function (header) {
- let contype
- let fieldname
- let parsed
- let charset
- let encoding
- let filename
- let nsize = 0
-
- if (header['content-type']) {
- parsed = parseParams(header['content-type'][0])
- if (parsed[0]) {
- contype = parsed[0].toLowerCase()
- for (i = 0, len = parsed.length; i < len; ++i) {
- if (RE_CHARSET.test(parsed[i][0])) {
- charset = parsed[i][1].toLowerCase()
- break
- }
- }
- }
- }
-
- if (contype === undefined) { contype = 'text/plain' }
- if (charset === undefined) { charset = defCharset }
-
- if (header['content-disposition']) {
- parsed = parseParams(header['content-disposition'][0])
- if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }
- for (i = 0, len = parsed.length; i < len; ++i) {
- if (RE_NAME.test(parsed[i][0])) {
- fieldname = parsed[i][1]
- } else if (RE_FILENAME.test(parsed[i][0])) {
- filename = parsed[i][1]
- if (!preservePath) { filename = basename(filename) }
- }
- }
- } else { return skipPart(part) }
-
- if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }
-
- let onData,
- onEnd
-
- if (isPartAFile(fieldname, contype, filename)) {
- // file/binary field
- if (nfiles === filesLimit) {
- if (!boy.hitFilesLimit) {
- boy.hitFilesLimit = true
- boy.emit('filesLimit')
- }
- return skipPart(part)
- }
-
- ++nfiles
-
- if (boy.listenerCount('file') === 0) {
- self.parser._ignore()
- return
- }
-
- ++nends
- const file = new FileStream(fileOpts)
- curFile = file
- file.on('end', function () {
- --nends
- self._pause = false
- checkFinished()
- if (self._cb && !self._needDrain) {
- const cb = self._cb
- self._cb = undefined
- cb()
- }
- })
- file._read = function (n) {
- if (!self._pause) { return }
- self._pause = false
- if (self._cb && !self._needDrain) {
- const cb = self._cb
- self._cb = undefined
- cb()
- }
- }
- boy.emit('file', fieldname, file, filename, encoding, contype)
-
- onData = function (data) {
- if ((nsize += data.length) > fileSizeLimit) {
- const extralen = fileSizeLimit - nsize + data.length
- if (extralen > 0) { file.push(data.slice(0, extralen)) }
- file.truncated = true
- file.bytesRead = fileSizeLimit
- part.removeAllListeners('data')
- file.emit('limit')
- return
- } else if (!file.push(data)) { self._pause = true }
-
- file.bytesRead = nsize
- }
-
- onEnd = function () {
- curFile = undefined
- file.push(null)
- }
- } else {
- // non-file field
- if (nfields === fieldsLimit) {
- if (!boy.hitFieldsLimit) {
- boy.hitFieldsLimit = true
- boy.emit('fieldsLimit')
- }
- return skipPart(part)
- }
-
- ++nfields
- ++nends
- let buffer = ''
- let truncated = false
- curField = part
-
- onData = function (data) {
- if ((nsize += data.length) > fieldSizeLimit) {
- const extralen = (fieldSizeLimit - (nsize - data.length))
- buffer += data.toString('binary', 0, extralen)
- truncated = true
- part.removeAllListeners('data')
- } else { buffer += data.toString('binary') }
- }
-
- onEnd = function () {
- curField = undefined
- if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }
- boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)
- --nends
- checkFinished()
- }
- }
-
- /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
- broken. Streams2/streams3 is a huge black box of confusion, but
- somehow overriding the sync state seems to fix things again (and still
- seems to work for previous node versions).
- */
- part._readableState.sync = false
-
- part.on('data', onData)
- part.on('end', onEnd)
- }).on('error', function (err) {
- if (curFile) { curFile.emit('error', err) }
- })
- }).on('error', function (err) {
- boy.emit('error', err)
- }).on('finish', function () {
- finished = true
- checkFinished()
- })
-}
-
-Multipart.prototype.write = function (chunk, cb) {
- const r = this.parser.write(chunk)
- if (r && !this._pause) {
- cb()
- } else {
- this._needDrain = !r
- this._cb = cb
- }
-}
-
-Multipart.prototype.end = function () {
- const self = this
-
- if (self.parser.writable) {
- self.parser.end()
- } else if (!self._boy._done) {
- process.nextTick(function () {
- self._boy._done = true
- self._boy.emit('finish')
- })
+ const list = appleModelIds.filter((model) => model.key === key);
+ if (list.length === 0) {
+ return {
+ key: key,
+ model: 'Apple',
+ version: 'Unknown'
+ };
}
+ const features = [];
+ if (list[0].size) { features.push(list[0].size); }
+ if (list[0].processor) { features.push(list[0].processor); }
+ if (list[0].year) { features.push(list[0].year); }
+ if (list[0].additional) { features.push(list[0].additional); }
+ return {
+ key: key,
+ model: list[0].name,
+ version: list[0].name + ' (' + features.join(', ') + ')'
+ };
}
-function skipPart (part) {
- part.resume()
-}
-
-function FileStream (opts) {
- Readable.call(this, opts)
-
- this.bytesRead = 0
+function checkWebsite(url, timeout = 5000) {
+ const http = ((url.startsWith('https:') || url.indexOf(':443/') > 0 || url.indexOf(':8443/') > 0) ? __nccwpck_require__(65692) : __nccwpck_require__(58611));
+ const t = Date.now();
+ return new Promise((resolve) => {
+ const request = http
+ .get(url, function (res) {
+ res.on('data', () => { });
+ res.on('end', () => {
+ resolve({
+ url,
+ statusCode: res.statusCode,
+ message: res.statusMessage,
+ time: Date.now() - t
+ });
+ });
+ })
+ .on("error", function (e) {
+ resolve({
+ url,
+ statusCode: 404,
+ message: e.message,
+ time: Date.now() - t
+ });
+ })
+ .setTimeout(timeout, () => {
+ request.close();
+ resolve({
+ url,
+ statusCode: 408,
+ message: 'Request Timeout',
+ time: Date.now() - t
+ });
+ });
+ });
+};
- this.truncated = false
+function cleanString(str) {
+ return str.replace(/To Be Filled By O.E.M./g, '');
}
+function noop() { }
-inherits(FileStream, Readable)
-
-FileStream.prototype._read = function (n) {}
-
-module.exports = Multipart
+exports.toInt = toInt;
+exports.splitByNumber = splitByNumber;
+exports.execOptsWin = execOptsWin;
+exports.execOptsLinux = execOptsLinux;
+exports.getCodepage = getCodepage;
+exports.execWin = execWin;
+exports.isFunction = isFunction;
+exports.unique = unique;
+exports.sortByKey = sortByKey;
+exports.cores = cores;
+exports.getValue = getValue;
+exports.decodeEscapeSequence = decodeEscapeSequence;
+exports.parseDateTime = parseDateTime;
+exports.parseHead = parseHead;
+exports.findObjectByKey = findObjectByKey;
+exports.getWmic = getWmic;
+exports.wmic = wmic;
+exports.darwinXcodeExists = darwinXcodeExists;
+exports.getVboxmanage = getVboxmanage;
+exports.powerShell = powerShell;
+exports.powerShellStart = powerShellStart;
+exports.powerShellRelease = powerShellRelease;
+exports.execSafe = execSafe;
+exports.nanoSeconds = nanoSeconds;
+exports.countUniqueLines = countUniqueLines;
+exports.countLines = countLines;
+exports.noop = noop;
+exports.isRaspberry = isRaspberry;
+exports.isRaspbian = isRaspbian;
+exports.sanitizeShellString = sanitizeShellString;
+exports.isPrototypePolluted = isPrototypePolluted;
+exports.decodePiCpuinfo = decodePiCpuinfo;
+exports.getRpiGpu = getRpiGpu;
+exports.promiseAll = promiseAll;
+exports.promisify = promisify;
+exports.promisifySave = promisifySave;
+exports.smartMonToolsInstalled = smartMonToolsInstalled;
+exports.linuxVersion = linuxVersion;
+exports.plistParser = plistParser;
+exports.plistReader = plistReader;
+exports.stringObj = stringObj;
+exports.stringReplace = stringReplace;
+exports.stringToLower = stringToLower;
+exports.stringToString = stringToString;
+exports.stringSubstr = stringSubstr;
+exports.stringSubstring = stringSubstring;
+exports.stringTrim = stringTrim;
+exports.stringStartWith = stringStartWith;
+exports.mathMin = mathMin;
+exports.WINDIR = WINDIR;
+exports.getFilesInPath = getFilesInPath;
+exports.semverCompare = semverCompare;
+exports.getAppleModel = getAppleModel;
+exports.checkWebsite = checkWebsite;
+exports.cleanString = cleanString;
+exports.getPowershell = getPowershell;
/***/ }),
-/***/ 21411:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 91404:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// @ts-check
+// ==================================================================================
+// virtualbox.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 14. Docker
+// ----------------------------------------------------------------------------------
-const Decoder = __nccwpck_require__(4364)
-const decodeText = __nccwpck_require__(16607)
-const getLimit = __nccwpck_require__(5245)
+const os = __nccwpck_require__(70857);
+const exec = (__nccwpck_require__(35317).exec);
+const util = __nccwpck_require__(77496);
-const RE_CHARSET = /^charset$/i
+function vboxInfo(callback) {
-UrlEncoded.detect = /^application\/x-www-form-urlencoded/i
-function UrlEncoded (boy, cfg) {
- const limits = cfg.limits
- const parsedConType = cfg.parsedConType
- this.boy = boy
+ // fallback - if only callback is given
+ let result = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ try {
+ exec(util.getVboxmanage() + ' list vms --long', function (error, stdout) {
+ let parts = (os.EOL + stdout.toString()).split(os.EOL + 'Name:');
+ parts.shift();
+ parts.forEach(part => {
+ const lines = ('Name:' + part).split(os.EOL);
+ const state = util.getValue(lines, 'State');
+ const running = state.startsWith('running');
+ const runningSinceString = running ? state.replace('running (since ', '').replace(')', '').trim() : '';
+ let runningSince = 0;
+ try {
+ if (running) {
+ const sinceDateObj = new Date(runningSinceString);
+ const offset = sinceDateObj.getTimezoneOffset();
+ runningSince = Math.round((Date.now() - Date.parse(sinceDateObj)) / 1000) + offset * 60;
+ }
+ } catch (e) {
+ util.noop();
+ }
+ const stoppedSinceString = !running ? state.replace('powered off (since', '').replace(')', '').trim() : '';
+ let stoppedSince = 0;
+ try {
+ if (!running) {
+ const sinceDateObj = new Date(stoppedSinceString);
+ const offset = sinceDateObj.getTimezoneOffset();
+ stoppedSince = Math.round((Date.now() - Date.parse(sinceDateObj)) / 1000) + offset * 60;
+ }
+ } catch (e) {
+ util.noop();
+ }
+ result.push({
+ id: util.getValue(lines, 'UUID'),
+ name: util.getValue(lines, 'Name'),
+ running,
+ started: runningSinceString,
+ runningSince,
+ stopped: stoppedSinceString,
+ stoppedSince,
+ guestOS: util.getValue(lines, 'Guest OS'),
+ hardwareUUID: util.getValue(lines, 'Hardware UUID'),
+ memory: parseInt(util.getValue(lines, 'Memory size', ' '), 10),
+ vram: parseInt(util.getValue(lines, 'VRAM size'), 10),
+ cpus: parseInt(util.getValue(lines, 'Number of CPUs'), 10),
+ cpuExepCap: util.getValue(lines, 'CPU exec cap'),
+ cpuProfile: util.getValue(lines, 'CPUProfile'),
+ chipset: util.getValue(lines, 'Chipset'),
+ firmware: util.getValue(lines, 'Firmware'),
+ pageFusion: util.getValue(lines, 'Page Fusion') === 'enabled',
+ configFile: util.getValue(lines, 'Config file'),
+ snapshotFolder: util.getValue(lines, 'Snapshot folder'),
+ logFolder: util.getValue(lines, 'Log folder'),
+ hpet: util.getValue(lines, 'HPET') === 'enabled',
+ pae: util.getValue(lines, 'PAE') === 'enabled',
+ longMode: util.getValue(lines, 'Long Mode') === 'enabled',
+ tripleFaultReset: util.getValue(lines, 'Triple Fault Reset') === 'enabled',
+ apic: util.getValue(lines, 'APIC') === 'enabled',
+ x2Apic: util.getValue(lines, 'X2APIC') === 'enabled',
+ acpi: util.getValue(lines, 'ACPI') === 'enabled',
+ ioApic: util.getValue(lines, 'IOAPIC') === 'enabled',
+ biosApicMode: util.getValue(lines, 'BIOS APIC mode'),
+ bootMenuMode: util.getValue(lines, 'Boot menu mode'),
+ bootDevice1: util.getValue(lines, 'Boot Device 1'),
+ bootDevice2: util.getValue(lines, 'Boot Device 2'),
+ bootDevice3: util.getValue(lines, 'Boot Device 3'),
+ bootDevice4: util.getValue(lines, 'Boot Device 4'),
+ timeOffset: util.getValue(lines, 'Time offset'),
+ rtc: util.getValue(lines, 'RTC'),
+ });
+ });
- this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
- this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)
- this.fieldsLimit = getLimit(limits, 'fields', Infinity)
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+}
- let charset
- for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var
- if (Array.isArray(parsedConType[i]) &&
- RE_CHARSET.test(parsedConType[i][0])) {
- charset = parsedConType[i][1].toLowerCase()
- break
- }
- }
+exports.vboxInfo = vboxInfo;
- if (charset === undefined) { charset = cfg.defCharset || 'utf8' }
- this.decoder = new Decoder()
- this.charset = charset
- this._fields = 0
- this._state = 'key'
- this._checkingBytes = true
- this._bytesKey = 0
- this._bytesVal = 0
- this._key = ''
- this._val = ''
- this._keyTrunc = false
- this._valTrunc = false
- this._hitLimit = false
-}
+/***/ }),
-UrlEncoded.prototype.write = function (data, cb) {
- if (this._fields === this.fieldsLimit) {
- if (!this.boy.hitFieldsLimit) {
- this.boy.hitFieldsLimit = true
- this.boy.emit('fieldsLimit')
- }
- return cb()
- }
+/***/ 76037:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- let idxeq; let idxamp; let i; let p = 0; const len = data.length
- while (p < len) {
- if (this._state === 'key') {
- idxeq = idxamp = undefined
- for (i = p; i < len; ++i) {
- if (!this._checkingBytes) { ++p }
- if (data[i] === 0x3D/* = */) {
- idxeq = i
- break
- } else if (data[i] === 0x26/* & */) {
- idxamp = i
- break
- }
- if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
- this._hitLimit = true
- break
- } else if (this._checkingBytes) { ++this._bytesKey }
- }
+// @ts-check
+// ==================================================================================
+// wifi.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 9. wifi
+// ----------------------------------------------------------------------------------
- if (idxeq !== undefined) {
- // key with assignment
- if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }
- this._state = 'val'
+const os = __nccwpck_require__(70857);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const util = __nccwpck_require__(77496);
- this._hitLimit = false
- this._checkingBytes = true
- this._val = ''
- this._bytesVal = 0
- this._valTrunc = false
- this.decoder.reset()
+let _platform = process.platform;
- p = idxeq + 1
- } else if (idxamp !== undefined) {
- // key with no assignment
- ++this._fields
- let key; const keyTrunc = this._keyTrunc
- if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
- this._hitLimit = false
- this._checkingBytes = true
- this._key = ''
- this._bytesKey = 0
- this._keyTrunc = false
- this.decoder.reset()
+function wifiDBFromQuality(quality) {
+ const qual = parseFloat(quality);
+ if (qual < 0) { return 0; }
+ if (qual >= 100) { return -50; }
+ return (qual / 2 - 100);
+}
- if (key.length) {
- this.boy.emit('field', decodeText(key, 'binary', this.charset),
- '',
- keyTrunc,
- false)
- }
+function wifiQualityFromDB(db) {
+ const result = 2 * (parseFloat(db) + 100);
+ return result <= 100 ? result : 100;
+}
- p = idxamp + 1
- if (this._fields === this.fieldsLimit) { return cb() }
- } else if (this._hitLimit) {
- // we may not have hit the actual limit if there are encoded bytes...
- if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }
- p = i
- if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
- // yep, we actually did hit the limit
- this._checkingBytes = false
- this._keyTrunc = true
- }
- } else {
- if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }
- p = len
- }
- } else {
- idxamp = undefined
- for (i = p; i < len; ++i) {
- if (!this._checkingBytes) { ++p }
- if (data[i] === 0x26/* & */) {
- idxamp = i
- break
- }
- if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
- this._hitLimit = true
- break
- } else if (this._checkingBytes) { ++this._bytesVal }
- }
+const _wifi_frequencies = {
+ 1: 2412,
+ 2: 2417,
+ 3: 2422,
+ 4: 2427,
+ 5: 2432,
+ 6: 2437,
+ 7: 2442,
+ 8: 2447,
+ 9: 2452,
+ 10: 2457,
+ 11: 2462,
+ 12: 2467,
+ 13: 2472,
+ 14: 2484,
+ 32: 5160,
+ 34: 5170,
+ 36: 5180,
+ 38: 5190,
+ 40: 5200,
+ 42: 5210,
+ 44: 5220,
+ 46: 5230,
+ 48: 5240,
+ 50: 5250,
+ 52: 5260,
+ 54: 5270,
+ 56: 5280,
+ 58: 5290,
+ 60: 5300,
+ 62: 5310,
+ 64: 5320,
+ 68: 5340,
+ 96: 5480,
+ 100: 5500,
+ 102: 5510,
+ 104: 5520,
+ 106: 5530,
+ 108: 5540,
+ 110: 5550,
+ 112: 5560,
+ 114: 5570,
+ 116: 5580,
+ 118: 5590,
+ 120: 5600,
+ 122: 5610,
+ 124: 5620,
+ 126: 5630,
+ 128: 5640,
+ 132: 5660,
+ 134: 5670,
+ 136: 5680,
+ 138: 5690,
+ 140: 5700,
+ 142: 5710,
+ 144: 5720,
+ 149: 5745,
+ 151: 5755,
+ 153: 5765,
+ 155: 5775,
+ 157: 5785,
+ 159: 5795,
+ 161: 5805,
+ 165: 5825,
+ 169: 5845,
+ 173: 5865,
+ 183: 4915,
+ 184: 4920,
+ 185: 4925,
+ 187: 4935,
+ 188: 4940,
+ 189: 4945,
+ 192: 4960,
+ 196: 4980
+};
- if (idxamp !== undefined) {
- ++this._fields
- if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }
- this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
- decodeText(this._val, 'binary', this.charset),
- this._keyTrunc,
- this._valTrunc)
- this._state = 'key'
+function wifiFrequencyFromChannel(channel) {
+ return {}.hasOwnProperty.call(_wifi_frequencies, channel) ? _wifi_frequencies[channel] : null;
+}
- this._hitLimit = false
- this._checkingBytes = true
- this._key = ''
- this._bytesKey = 0
- this._keyTrunc = false
- this.decoder.reset()
+function wifiChannelFromFrequencs(frequency) {
+ let channel = 0;
+ for (let key in _wifi_frequencies) {
+ if ({}.hasOwnProperty.call(_wifi_frequencies, key)) {
+ if (_wifi_frequencies[key] === frequency) { channel = util.toInt(key); }
+ }
+ }
+ return channel;
+}
- p = idxamp + 1
- if (this._fields === this.fieldsLimit) { return cb() }
- } else if (this._hitLimit) {
- // we may not have hit the actual limit if there are encoded bytes...
- if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }
- p = i
- if ((this._val === '' && this.fieldSizeLimit === 0) ||
- (this._bytesVal = this._val.length) === this.fieldSizeLimit) {
- // yep, we actually did hit the limit
- this._checkingBytes = false
- this._valTrunc = true
+function ifaceListLinux() {
+ const result = [];
+ const cmd = 'iw dev 2>/dev/null';
+ try {
+ const all = execSync(cmd, util.execOptsLinux).toString().split('\n').map(line => line.trim()).join('\n');
+ const parts = all.split('\nInterface ');
+ parts.shift();
+ parts.forEach(ifaceDetails => {
+ const lines = ifaceDetails.split('\n');
+ const iface = lines[0];
+ const id = util.toInt(util.getValue(lines, 'ifindex', ' '));
+ const mac = util.getValue(lines, 'addr', ' ');
+ const channel = util.toInt(util.getValue(lines, 'channel', ' '));
+ result.push({
+ id,
+ iface,
+ mac,
+ channel
+ });
+ });
+ return result;
+ } catch (e) {
+ try {
+ const all = execSync('nmcli -t -f general,wifi-properties,wired-properties,interface-flags,capabilities,nsp device show 2>/dev/null', util.execOptsLinux).toString();
+ const parts = all.split('\n\n');
+ let i = 1;
+ parts.forEach(ifaceDetails => {
+ const lines = ifaceDetails.split('\n');
+ const iface = util.getValue(lines, 'GENERAL.DEVICE');
+ const type = util.getValue(lines, 'GENERAL.TYPE');
+ const id = i++; // // util.getValue(lines, 'GENERAL.PATH');
+ const mac = util.getValue(lines, 'GENERAL.HWADDR');
+ const channel = '';
+ if (type.toLowerCase() === 'wifi') {
+ result.push({
+ id,
+ iface,
+ mac,
+ channel
+ });
}
- } else {
- if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }
- p = len
- }
+ });
+ return result;
+ } catch (e) {
+ return [];
}
}
- cb()
}
-UrlEncoded.prototype.end = function () {
- if (this.boy._done) { return }
-
- if (this._state === 'key' && this._key.length > 0) {
- this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
- '',
- this._keyTrunc,
- false)
- } else if (this._state === 'val') {
- this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
- decodeText(this._val, 'binary', this.charset),
- this._keyTrunc,
- this._valTrunc)
+function nmiDeviceLinux(iface) {
+ const cmd = `nmcli -t -f general,wifi-properties,capabilities,ip4,ip6 device show ${iface} 2> /dev/null`;
+ try {
+ const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
+ const ssid = util.getValue(lines, 'GENERAL.CONNECTION');
+ return {
+ iface,
+ type: util.getValue(lines, 'GENERAL.TYPE'),
+ vendor: util.getValue(lines, 'GENERAL.VENDOR'),
+ product: util.getValue(lines, 'GENERAL.PRODUCT'),
+ mac: util.getValue(lines, 'GENERAL.HWADDR').toLowerCase(),
+ ssid: ssid !== '--' ? ssid : null
+ };
+ } catch (e) {
+ return {};
}
- this.boy._done = true
- this.boy.emit('finish')
}
-module.exports = UrlEncoded
-
-
-/***/ }),
-
-/***/ 4364:
-/***/ ((module) => {
-
-
-
-const RE_PLUS = /\+/g
-
-const HEX = [
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
- 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
-]
-
-function Decoder () {
- this.buffer = undefined
-}
-Decoder.prototype.write = function (str) {
- // Replace '+' with ' ' before decoding
- str = str.replace(RE_PLUS, ' ')
- let res = ''
- let i = 0; let p = 0; const len = str.length
- for (; i < len; ++i) {
- if (this.buffer !== undefined) {
- if (!HEX[str.charCodeAt(i)]) {
- res += '%' + this.buffer
- this.buffer = undefined
- --i // retry character
- } else {
- this.buffer += str[i]
- ++p
- if (this.buffer.length === 2) {
- res += String.fromCharCode(parseInt(this.buffer, 16))
- this.buffer = undefined
- }
- }
- } else if (str[i] === '%') {
- if (i > p) {
- res += str.substring(p, i)
- p = i
- }
- this.buffer = ''
- ++p
- }
+function nmiConnectionLinux(ssid) {
+ const cmd = `nmcli -t --show-secrets connection show ${ssid} 2>/dev/null`;
+ try {
+ const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
+ const bssid = util.getValue(lines, '802-11-wireless.seen-bssids').toLowerCase();
+ return {
+ ssid: ssid !== '--' ? ssid : null,
+ uuid: util.getValue(lines, 'connection.uuid'),
+ type: util.getValue(lines, 'connection.type'),
+ autoconnect: util.getValue(lines, 'connection.autoconnect') === 'yes',
+ security: util.getValue(lines, '802-11-wireless-security.key-mgmt'),
+ bssid: bssid !== '--' ? bssid : null
+ };
+ } catch (e) {
+ return {};
}
- if (p < len && this.buffer === undefined) { res += str.substring(p) }
- return res
-}
-Decoder.prototype.reset = function () {
- this.buffer = undefined
}
-module.exports = Decoder
-
-
-/***/ }),
+function wpaConnectionLinux(iface) {
+ if (!iface) {
+ return {};
+ }
+ const cmd = `wpa_cli -i ${iface} status 2>&1`;
+ try {
+ const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
+ const freq = util.toInt(util.getValue(lines, 'freq', '='));
+ return {
+ ssid: util.getValue(lines, 'ssid', '='),
+ uuid: util.getValue(lines, 'uuid', '='),
+ security: util.getValue(lines, 'key_mgmt', '='),
+ freq,
+ channel: wifiChannelFromFrequencs(freq),
+ bssid: util.getValue(lines, 'bssid', '=').toLowerCase()
+ };
+ } catch (e) {
+ return {};
+ }
+}
-/***/ 15080:
-/***/ ((module) => {
+function getWifiNetworkListNmi() {
+ const result = [];
+ const cmd = 'nmcli -t -m multiline --fields active,ssid,bssid,mode,chan,freq,signal,security,wpa-flags,rsn-flags device wifi list 2>/dev/null';
+ try {
+ const stdout = execSync(cmd, util.execOptsLinux);
+ const parts = stdout.toString().split('ACTIVE:');
+ parts.shift();
+ parts.forEach(part => {
+ part = 'ACTIVE:' + part;
+ const lines = part.split(os.EOL);
+ const channel = util.getValue(lines, 'CHAN');
+ const frequency = util.getValue(lines, 'FREQ').toLowerCase().replace('mhz', '').trim();
+ const security = util.getValue(lines, 'SECURITY').replace('(', '').replace(')', '');
+ const wpaFlags = util.getValue(lines, 'WPA-FLAGS').replace('(', '').replace(')', '');
+ const rsnFlags = util.getValue(lines, 'RSN-FLAGS').replace('(', '').replace(')', '');
+ const quality = util.getValue(lines, 'SIGNAL');
+ result.push({
+ ssid: util.getValue(lines, 'SSID'),
+ bssid: util.getValue(lines, 'BSSID').toLowerCase(),
+ mode: util.getValue(lines, 'MODE'),
+ channel: channel ? parseInt(channel, 10) : null,
+ frequency: frequency ? parseInt(frequency, 10) : null,
+ signalLevel: wifiDBFromQuality(quality),
+ quality: quality ? parseInt(quality, 10) : null,
+ security: security && security !== 'none' ? security.split(' ') : [],
+ wpaFlags: wpaFlags && wpaFlags !== 'none' ? wpaFlags.split(' ') : [],
+ rsnFlags: rsnFlags && rsnFlags !== 'none' ? rsnFlags.split(' ') : []
+ });
+ });
+ return result;
+ } catch (e) {
+ return [];
+ }
+}
+function getWifiNetworkListIw(iface) {
+ const result = [];
+ try {
+ let iwlistParts = execSync(`export LC_ALL=C; iwlist ${iface} scan 2>&1; unset LC_ALL`, util.execOptsLinux).toString().split(' Cell ');
+ if (iwlistParts[0].indexOf('resource busy') >= 0) { return -1; }
+ if (iwlistParts.length > 1) {
+ iwlistParts.shift();
+ iwlistParts.forEach(element => {
+ const lines = element.split('\n');
+ const channel = util.getValue(lines, 'channel', ':', true);
+ const address = (lines && lines.length && lines[0].indexOf('Address:') >= 0 ? lines[0].split('Address:')[1].trim().toLowerCase() : '');
+ const mode = util.getValue(lines, 'mode', ':', true);
+ const frequency = util.getValue(lines, 'frequency', ':', true);
+ const qualityString = util.getValue(lines, 'Quality', '=', true);
+ const dbParts = qualityString.toLowerCase().split('signal level=');
+ const db = dbParts.length > 1 ? util.toInt(dbParts[1]) : 0;
+ const quality = db ? wifiQualityFromDB(db) : 0;
+ const ssid = util.getValue(lines, 'essid', ':', true);
+ // security and wpa-flags
+ const isWpa = element.indexOf(' WPA ') >= 0;
+ const isWpa2 = element.indexOf('WPA2 ') >= 0;
+ const security = [];
+ if (isWpa) { security.push('WPA'); }
+ if (isWpa2) { security.push('WPA2'); }
+ const wpaFlags = [];
+ let wpaFlag = '';
+ lines.forEach(function (line) {
+ const l = line.trim().toLowerCase();
+ if (l.indexOf('group cipher') >= 0) {
+ if (wpaFlag) {
+ wpaFlags.push(wpaFlag);
+ }
+ const parts = l.split(':');
+ if (parts.length > 1) {
+ wpaFlag = parts[1].trim().toUpperCase();
+ }
+ }
+ if (l.indexOf('pairwise cipher') >= 0) {
+ const parts = l.split(':');
+ if (parts.length > 1) {
+ if (parts[1].indexOf('tkip')) { wpaFlag = (wpaFlag ? 'TKIP/' + wpaFlag : 'TKIP'); }
+ else if (parts[1].indexOf('ccmp')) { wpaFlag = (wpaFlag ? 'CCMP/' + wpaFlag : 'CCMP'); }
+ else if (parts[1].indexOf('proprietary')) { wpaFlag = (wpaFlag ? 'PROP/' + wpaFlag : 'PROP'); }
+ }
+ }
+ if (l.indexOf('authentication suites') >= 0) {
+ const parts = l.split(':');
+ if (parts.length > 1) {
+ if (parts[1].indexOf('802.1x')) { wpaFlag = (wpaFlag ? '802.1x/' + wpaFlag : '802.1x'); }
+ else if (parts[1].indexOf('psk')) { wpaFlag = (wpaFlag ? 'PSK/' + wpaFlag : 'PSK'); }
+ }
+ }
+ });
+ if (wpaFlag) {
+ wpaFlags.push(wpaFlag);
+ }
-module.exports = function basename (path) {
- if (typeof path !== 'string') { return '' }
- for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var
- switch (path.charCodeAt(i)) {
- case 0x2F: // '/'
- case 0x5C: // '\'
- path = path.slice(i + 1)
- return (path === '..' || path === '.' ? '' : path)
+ result.push({
+ ssid,
+ bssid: address,
+ mode,
+ channel: channel ? util.toInt(channel) : null,
+ frequency: frequency ? util.toInt(frequency.replace('.', '')) : null,
+ signalLevel: db,
+ quality,
+ security,
+ wpaFlags,
+ rsnFlags: []
+ });
+ });
}
+ return result;
+ } catch (e) {
+ return -1;
}
- return (path === '..' || path === '.' ? '' : path)
}
-
-/***/ }),
-
-/***/ 16607:
-/***/ (function(module) {
-
-
-
-// Node has always utf-8
-const utf8Decoder = new TextDecoder('utf-8')
-const textDecoders = new Map([
- ['utf-8', utf8Decoder],
- ['utf8', utf8Decoder]
-])
-
-function getDecoder (charset) {
- let lc
- while (true) {
- switch (charset) {
- case 'utf-8':
- case 'utf8':
- return decoders.utf8
- case 'latin1':
- case 'ascii': // TODO: Make these a separate, strict decoder?
- case 'us-ascii':
- case 'iso-8859-1':
- case 'iso8859-1':
- case 'iso88591':
- case 'iso_8859-1':
- case 'windows-1252':
- case 'iso_8859-1:1987':
- case 'cp1252':
- case 'x-cp1252':
- return decoders.latin1
- case 'utf16le':
- case 'utf-16le':
- case 'ucs2':
- case 'ucs-2':
- return decoders.utf16le
- case 'base64':
- return decoders.base64
- default:
- if (lc === undefined) {
- lc = true
- charset = charset.toLowerCase()
- continue
+function parseWifiDarwinXX(wifiObj) {
+ const result = [];
+ if (wifiObj) {
+ wifiObj.forEach(function (wifiItem) {
+ const signalLevel = wifiItem.RSSI;
+ let security = [];
+ let wpaFlags = [];
+ let ssid = wifiItem.SSID_STR || '';
+ if (wifiItem.WPA_IE) {
+ security.push('WPA');
+ if (wifiItem.WPA_IE.IE_KEY_WPA_UCIPHERS) {
+ wifiItem.WPA_IE.IE_KEY_WPA_UCIPHERS.forEach(function (ciphers) {
+ if (ciphers === 0 && wpaFlags.indexOf('unknown/TKIP') === -1) { wpaFlags.push('unknown/TKIP'); }
+ if (ciphers === 2 && wpaFlags.indexOf('PSK/TKIP') === -1) { wpaFlags.push('PSK/TKIP'); }
+ if (ciphers === 4 && wpaFlags.indexOf('PSK/AES') === -1) { wpaFlags.push('PSK/AES'); }
+ });
}
- return decoders.other.bind(charset)
- }
+ }
+ if (wifiItem.RSN_IE) {
+ security.push('WPA2');
+ if (wifiItem.RSN_IE.IE_KEY_RSN_UCIPHERS) {
+ wifiItem.RSN_IE.IE_KEY_RSN_UCIPHERS.forEach(function (ciphers) {
+ if (ciphers === 0 && wpaFlags.indexOf('unknown/TKIP') === -1) { wpaFlags.push('unknown/TKIP'); }
+ if (ciphers === 2 && wpaFlags.indexOf('TKIP/TKIP') === -1) { wpaFlags.push('TKIP/TKIP'); }
+ if (ciphers === 4 && wpaFlags.indexOf('PSK/AES') === -1) { wpaFlags.push('PSK/AES'); }
+ });
+ }
+ }
+ if (wifiItem.SSID && ssid === '') {
+ try {
+ ssid = Buffer.from(wifiItem.SSID, 'base64').toString('utf8');
+ } catch (err) {
+ util.noop();
+ }
+ }
+ result.push({
+ ssid,
+ bssid: wifiItem.BSSID || '',
+ mode: '',
+ channel: wifiItem.CHANNEL,
+ frequency: wifiFrequencyFromChannel(wifiItem.CHANNEL),
+ signalLevel: signalLevel ? parseInt(signalLevel, 10) : null,
+ quality: wifiQualityFromDB(signalLevel),
+ security,
+ wpaFlags,
+ rsnFlags: []
+ });
+ });
}
+ return result;
}
-const decoders = {
- utf8: (data, sourceEncoding) => {
- if (data.length === 0) {
- return ''
- }
- if (typeof data === 'string') {
- data = Buffer.from(data, sourceEncoding)
- }
- return data.utf8Slice(0, data.length)
- },
+function parseWifiDarwin(wifiStr) {
+ const result = [];
+ try {
+ let wifiObj = JSON.parse(wifiStr);
+ wifiObj = wifiObj.SPAirPortDataType[0].spairport_airport_interfaces[0].spairport_airport_other_local_wireless_networks;
+ wifiObj.forEach(function (wifiItem) {
- latin1: (data, sourceEncoding) => {
- if (data.length === 0) {
- return ''
- }
- if (typeof data === 'string') {
- return data
- }
- return data.latin1Slice(0, data.length)
- },
+ let security = [];
+ const sm = wifiItem.spairport_security_mode;
+ if (sm === 'spairport_security_mode_wep') {
+ security.push('WEP');
+ } else if (sm === 'spairport_security_mode_wpa2_personal') {
+ security.push('WPA2');
+ } else if (sm.startsWith('spairport_security_mode_wpa2_enterprise')) {
+ security.push('WPA2 EAP');
+ } else if (sm.startsWith('pairport_security_mode_wpa3_transition')) {
+ security.push('WPA2/WPA3');
+ } else if (sm.startsWith('pairport_security_mode_wpa3')) {
+ security.push('WPA3');
+ }
+ const channel = parseInt(('' + wifiItem.spairport_network_channel).split(' ')[0]) || 0;
+ const signalLevel = wifiItem.spairport_signal_noise || null;
- utf16le: (data, sourceEncoding) => {
- if (data.length === 0) {
- return ''
- }
- if (typeof data === 'string') {
- data = Buffer.from(data, sourceEncoding)
- }
- return data.ucs2Slice(0, data.length)
- },
+ result.push({
+ ssid: wifiItem._name || '',
+ bssid: wifiItem.spairport_network_bssid || null,
+ mode: wifiItem.spairport_network_phymode,
+ channel,
+ frequency: wifiFrequencyFromChannel(channel),
+ signalLevel: signalLevel ? parseInt(signalLevel, 10) : null,
+ quality: wifiQualityFromDB(signalLevel),
+ security,
+ wpaFlags: [],
+ rsnFlags: []
+ });
+ });
+ return result;
+ } catch (e) {
+ return result;
+ }
+};
+function wifiNetworks(callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = [];
+ if (_linux) {
+ result = getWifiNetworkListNmi();
+ if (result.length === 0) {
+ try {
+ const iwconfigParts = execSync('export LC_ALL=C; iwconfig 2>/dev/null; unset LC_ALL', util.execOptsLinux).toString().split('\n\n');
+ let iface = '';
+ iwconfigParts.forEach(element => {
+ if (element.indexOf('no wireless') === -1 && element.trim() !== '') {
+ iface = element.split(' ')[0];
+ }
+ });
+ if (iface) {
+ let ifaceSanitized = '';
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface, true);
+ const l = util.mathMin(s.length, 2000);
- base64: (data, sourceEncoding) => {
- if (data.length === 0) {
- return ''
- }
- if (typeof data === 'string') {
- data = Buffer.from(data, sourceEncoding)
- }
- return data.base64Slice(0, data.length)
- },
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ ifaceSanitized = ifaceSanitized + s[i];
+ }
+ }
- other: (data, sourceEncoding) => {
- if (data.length === 0) {
- return ''
- }
- if (typeof data === 'string') {
- data = Buffer.from(data, sourceEncoding)
- }
+ const res = getWifiNetworkListIw(ifaceSanitized);
+ if (res === -1) {
+ // try again after 4 secs
+ setTimeout(function (iface) {
+ const res = getWifiNetworkListIw(iface);
+ if (res != -1) { result = res; }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }, 4000);
+ } else {
+ result = res;
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ } catch (e) {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ } else if (_darwin) {
+ let cmd = 'system_profiler SPAirPortDataType -json 2>/dev/null';
+ exec(cmd, { maxBuffer: 1024 * 40000 }, function (error, stdout) {
+ result = parseWifiDarwin(stdout.toString());
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } else if (_windows) {
+ let cmd = 'netsh wlan show networks mode=Bssid';
+ util.powerShell(cmd).then((stdout) => {
+ const ssidParts = stdout.toString('utf8').split(os.EOL + os.EOL + 'SSID ');
+ ssidParts.shift();
- if (textDecoders.has(this.toString())) {
- try {
- return textDecoders.get(this).decode(data)
- } catch {}
- }
- return typeof data === 'string'
- ? data
- : data.toString()
- }
-}
+ ssidParts.forEach(ssidPart => {
+ const ssidLines = ssidPart.split(os.EOL);
+ if (ssidLines && ssidLines.length >= 8 && ssidLines[0].indexOf(':') >= 0) {
+ const bssidsParts = ssidPart.split(' BSSID');
+ bssidsParts.shift();
-function decodeText (text, sourceEncoding, destEncoding) {
- if (text) {
- return getDecoder(destEncoding)(text, sourceEncoding)
- }
- return text
-}
+ bssidsParts.forEach((bssidPart) => {
+ const bssidLines = bssidPart.split(os.EOL);
+ const bssidLine = bssidLines[0].split(':');
+ bssidLine.shift();
+ const bssid = bssidLine.join(':').trim().toLowerCase();
+ const channel = bssidLines[3].split(':').pop().trim();
+ const quality = bssidLines[1].split(':').pop().trim();
-module.exports = decodeText
+ result.push({
+ ssid: ssidLines[0].split(':').pop().trim(),
+ bssid,
+ mode: '',
+ channel: channel ? parseInt(channel, 10) : null,
+ frequency: wifiFrequencyFromChannel(channel),
+ signalLevel: wifiDBFromQuality(quality),
+ quality: quality ? parseInt(quality, 10) : null,
+ security: [ssidLines[2].split(':').pop().trim()],
+ wpaFlags: [ssidLines[3].split(':').pop().trim()],
+ rsnFlags: []
+ });
+ });
+ }
+ });
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ });
+ });
+}
-/***/ }),
+exports.wifiNetworks = wifiNetworks;
-/***/ 5245:
-/***/ ((module) => {
+function getVendor(model) {
+ model = model.toLowerCase();
+ let result = '';
+ if (model.indexOf('intel') >= 0) { result = 'Intel'; }
+ else if (model.indexOf('realtek') >= 0) { result = 'Realtek'; }
+ else if (model.indexOf('qualcom') >= 0) { result = 'Qualcom'; }
+ else if (model.indexOf('broadcom') >= 0) { result = 'Broadcom'; }
+ else if (model.indexOf('cavium') >= 0) { result = 'Cavium'; }
+ else if (model.indexOf('cisco') >= 0) { result = 'Cisco'; }
+ else if (model.indexOf('marvel') >= 0) { result = 'Marvel'; }
+ else if (model.indexOf('zyxel') >= 0) { result = 'Zyxel'; }
+ else if (model.indexOf('melanox') >= 0) { result = 'Melanox'; }
+ else if (model.indexOf('d-link') >= 0) { result = 'D-Link'; }
+ else if (model.indexOf('tp-link') >= 0) { result = 'TP-Link'; }
+ else if (model.indexOf('asus') >= 0) { result = 'Asus'; }
+ else if (model.indexOf('linksys') >= 0) { result = 'Linksys'; }
+ return result;
+}
+function formatBssid(s) {
+ s = s.replace(//g, '').match(/.{1,2}/g) || [];
+ return s.join(':');
+}
+function wifiConnections(callback) {
-module.exports = function getLimit (limits, name, defaultLimit) {
- if (
- !limits ||
- limits[name] === undefined ||
- limits[name] === null
- ) { return defaultLimit }
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ const result = [];
- if (
- typeof limits[name] !== 'number' ||
- isNaN(limits[name])
- ) { throw new TypeError('Limit ' + name + ' is not a valid number') }
+ if (_linux) {
+ const ifaces = ifaceListLinux();
+ const networkList = getWifiNetworkListNmi();
+ ifaces.forEach(ifaceDetail => {
+ let ifaceSanitized = '';
+ const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(ifaceDetail.iface, true);
+ const ll = util.mathMin(s.length, 2000);
- return limits[name]
-}
+ for (let i = 0; i <= ll; i++) {
+ if (s[i] !== undefined) {
+ ifaceSanitized = ifaceSanitized + s[i];
+ }
+ }
+ const nmiDetails = nmiDeviceLinux(ifaceSanitized);
+ const wpaDetails = wpaConnectionLinux(ifaceSanitized);
+ const ssid = nmiDetails.ssid || wpaDetails.ssid;
+ const network = networkList.filter(nw => nw.ssid === ssid);
+ let ssidSanitized = '';
+ const t = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(ssid, true);
+ const l = util.mathMin(t.length, 32);
+ for (let i = 0; i <= l; i++) {
+ if (t[i] !== undefined) {
+ ssidSanitized = ssidSanitized + t[i];
+ }
+ }
-/***/ }),
+ const nmiConnection = nmiConnectionLinux(ssidSanitized);
+ const channel = network && network.length && network[0].channel ? network[0].channel : (wpaDetails.channel ? wpaDetails.channel : null);
+ const bssid = network && network.length && network[0].bssid ? network[0].bssid : (wpaDetails.bssid ? wpaDetails.bssid : null);
+ const signalLevel = network && network.length && network[0].signalLevel ? network[0].signalLevel : null;
+ if (ssid && bssid) {
+ result.push({
+ id: ifaceDetail.id,
+ iface: ifaceDetail.iface,
+ model: nmiDetails.product,
+ ssid,
+ bssid: network && network.length && network[0].bssid ? network[0].bssid : (wpaDetails.bssid ? wpaDetails.bssid : null),
+ channel,
+ frequency: channel ? wifiFrequencyFromChannel(channel) : null,
+ type: nmiConnection.type ? nmiConnection.type : '802.11',
+ security: nmiConnection.security ? nmiConnection.security : (wpaDetails.security ? wpaDetails.security : null),
+ signalLevel,
+ quality: wifiQualityFromDB(signalLevel),
+ txRate: null
+ });
+ }
+ });
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ } else if (_darwin) {
+ let cmd = 'system_profiler SPNetworkDataType SPAirPortDataType -xml 2>/dev/null; echo "######" ; ioreg -n AppleBCMWLANSkywalkInterface -r 2>/dev/null';
+ exec(cmd, function (error, stdout) {
+ try {
+ const parts = stdout.toString().split('######');
+ const profilerObj = util.plistParser(parts[0]);
+ const networkObj = profilerObj[0]._SPCommandLineArguments.indexOf('SPNetworkDataType') >= 0 ? profilerObj[0]._items : profilerObj[1]._items;
+ const airportObj = profilerObj[0]._SPCommandLineArguments.indexOf('SPAirPortDataType') >= 0 ? profilerObj[0]._items[0].spairport_airport_interfaces : profilerObj[1]._items[0].spairport_airport_interfaces;
-/***/ 60717:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // parts[1] : ioreg
+ let lines3 = [];
+ if (parts[1].indexOf(' | {') > 0 && parts[1].indexOf(' | }') > parts[1].indexOf(' | {')) {
+ lines3 = parts[1].split(' | {')[1].split(' | }')[0].replace(/ \| /g, '').replace(/"/g, '').split('\n');
+ }
-/* eslint-disable object-property-newline */
+ const networkWifiObj = networkObj.find((item) => { return item._name === 'Wi-Fi'; });
+ const airportWifiObj = airportObj[0].spairport_current_network_information;
+ const channel = parseInt(('' + airportWifiObj.spairport_network_channel).split(' ')[0]) || 0;
+ const signalLevel = airportWifiObj.spairport_signal_noise || null;
-const decodeText = __nccwpck_require__(16607)
+ let security = [];
+ const sm = airportWifiObj.spairport_security_mode;
+ if (sm === 'spairport_security_mode_wep') {
+ security.push('WEP');
+ } else if (sm === 'spairport_security_mode_wpa2_personal') {
+ security.push('WPA2');
+ } else if (sm.startsWith('spairport_security_mode_wpa2_enterprise')) {
+ security.push('WPA2 EAP');
+ } else if (sm.startsWith('pairport_security_mode_wpa3_transition')) {
+ security.push('WPA2/WPA3');
+ } else if (sm.startsWith('pairport_security_mode_wpa3')) {
+ security.push('WPA3');
+ }
-const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g
+ result.push({
+ id: networkWifiObj._name || 'Wi-Fi',
+ iface: networkWifiObj.interface || '',
+ model: networkWifiObj.hardware || '',
+ ssid: airportWifiObj._name || '',
+ bssid: airportWifiObj.spairport_network_bssid || '',
+ channel,
+ frequency: channel ? wifiFrequencyFromChannel(channel) : null,
+ type: airportWifiObj.spairport_network_phymode || '802.11',
+ security,
+ signalLevel: signalLevel ? parseInt(signalLevel, 10) : null,
+ quality: wifiQualityFromDB(signalLevel),
+ txRate: airportWifiObj.spairport_network_rate || null,
+ });
-const EncodedLookup = {
- '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04',
- '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09',
- '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c',
- '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e',
- '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12',
- '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17',
- '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b',
- '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d',
- '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20',
- '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25',
- '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a',
- '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c',
- '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f',
- '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33',
- '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38',
- '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b',
- '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e',
- '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41',
- '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46',
- '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a',
- '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d',
- '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f',
- '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54',
- '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59',
- '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c',
- '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e',
- '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62',
- '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67',
- '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b',
- '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d',
- '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70',
- '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75',
- '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a',
- '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c',
- '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f',
- '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83',
- '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88',
- '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b',
- '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e',
- '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91',
- '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96',
- '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a',
- '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d',
- '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f',
- '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2',
- '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4',
- '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7',
- '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9',
- '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab',
- '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac',
- '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad',
- '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae',
- '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0',
- '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2',
- '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5',
- '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7',
- '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba',
- '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb',
- '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc',
- '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd',
- '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf',
- '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0',
- '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3',
- '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5',
- '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8',
- '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca',
- '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb',
- '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc',
- '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce',
- '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf',
- '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1',
- '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3',
- '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6',
- '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8',
- '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda',
- '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb',
- '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd',
- '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde',
- '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf',
- '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1',
- '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4',
- '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6',
- '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9',
- '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea',
- '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec',
- '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed',
- '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee',
- '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef',
- '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2',
- '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4',
- '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7',
- '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9',
- '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb',
- '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc',
- '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd',
- '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe',
- '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff'
+ } catch (e) {
+ util.noop();
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } else if (_windows) {
+ let cmd = 'netsh wlan show interfaces';
+ util.powerShell(cmd).then(function (stdout) {
+ const allLines = stdout.toString().split('\r\n');
+ for (let i = 0; i < allLines.length; i++) {
+ allLines[i] = allLines[i].trim();
+ }
+ const parts = allLines.join('\r\n').split(':\r\n\r\n');
+ parts.shift();
+ parts.forEach(part => {
+ const lines = part.split('\r\n');
+ if (lines.length >= 5) {
+ const iface = lines[0].indexOf(':') >= 0 ? lines[0].split(':')[1].trim() : '';
+ const model = lines[1].indexOf(':') >= 0 ? lines[1].split(':')[1].trim() : '';
+ const id = lines[2].indexOf(':') >= 0 ? lines[2].split(':')[1].trim() : '';
+ const ssid = util.getValue(lines, 'SSID', ':', true);
+ const bssid = util.getValue(lines, 'BSSID', ':', true) || util.getValue(lines, 'AP BSSID', ':', true);
+ const quality = util.getValue(lines, 'Signal', ':', true);
+ const signalLevel = wifiDBFromQuality(quality);
+ const type = util.getValue(lines, 'Radio type', ':', true) || util.getValue(lines, 'Type de radio', ':', true) || util.getValue(lines, 'Funktyp', ':', true) || null;
+ const security = util.getValue(lines, 'authentication', ':', true) || util.getValue(lines, 'Authentification', ':', true) || util.getValue(lines, 'Authentifizierung', ':', true) || null;
+ const channel = util.getValue(lines, 'Channel', ':', true) || util.getValue(lines, 'Canal', ':', true) || util.getValue(lines, 'Kanal', ':', true) || null;
+ const txRate = util.getValue(lines, 'Transmit rate (mbps)', ':', true) || util.getValue(lines, 'Transmission (mbit/s)', ':', true) || util.getValue(lines, 'Empfangsrate (MBit/s)', ':', true) || null;
+ if (model && id && ssid && bssid) {
+ result.push({
+ id,
+ iface,
+ model,
+ ssid,
+ bssid,
+ channel: util.toInt(channel),
+ frequency: channel ? wifiFrequencyFromChannel(channel) : null,
+ type,
+ security,
+ signalLevel,
+ quality: quality ? parseInt(quality, 10) : null,
+ txRate: util.toInt(txRate) || null
+ });
+ }
+ }
+ });
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ });
+ });
}
-function encodedReplacer (match) {
- return EncodedLookup[match]
-}
+exports.wifiConnections = wifiConnections;
-const STATE_KEY = 0
-const STATE_VALUE = 1
-const STATE_CHARSET = 2
-const STATE_LANG = 3
+function wifiInterfaces(callback) {
-function parseParams (str) {
- const res = []
- let state = STATE_KEY
- let charset = ''
- let inquote = false
- let escaping = false
- let p = 0
- let tmp = ''
- const len = str.length
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ const result = [];
- for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
- const char = str[i]
- if (char === '\\' && inquote) {
- if (escaping) { escaping = false } else {
- escaping = true
- continue
- }
- } else if (char === '"') {
- if (!escaping) {
- if (inquote) {
- inquote = false
- state = STATE_KEY
- } else { inquote = true }
- continue
- } else { escaping = false }
- } else {
- if (escaping && inquote) { tmp += '\\' }
- escaping = false
- if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") {
- if (state === STATE_CHARSET) {
- state = STATE_LANG
- charset = tmp.substring(1)
- } else { state = STATE_VALUE }
- tmp = ''
- continue
- } else if (state === STATE_KEY &&
- (char === '*' || char === '=') &&
- res.length) {
- state = char === '*'
- ? STATE_CHARSET
- : STATE_VALUE
- res[p] = [tmp, undefined]
- tmp = ''
- continue
- } else if (!inquote && char === ';') {
- state = STATE_KEY
- if (charset) {
- if (tmp.length) {
- tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
- 'binary',
- charset)
+ if (_linux) {
+ const ifaces = ifaceListLinux();
+ ifaces.forEach(ifaceDetail => {
+ const nmiDetails = nmiDeviceLinux(ifaceDetail.iface);
+ result.push({
+ id: ifaceDetail.id,
+ iface: ifaceDetail.iface,
+ model: nmiDetails.product ? nmiDetails.product : null,
+ vendor: nmiDetails.vendor ? nmiDetails.vendor : null,
+ mac: ifaceDetail.mac,
+ });
+ });
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ } else if (_darwin) {
+ let cmd = 'system_profiler SPNetworkDataType';
+ exec(cmd, function (error, stdout) {
+ const parts1 = stdout.toString().split('\n\n Wi-Fi:\n\n');
+ if (parts1.length > 1) {
+ const lines = parts1[1].split('\n\n')[0].split('\n');
+ const iface = util.getValue(lines, 'BSD Device Name', ':', true);
+ const mac = util.getValue(lines, 'MAC Address', ':', true);
+ const model = util.getValue(lines, 'hardware', ':', true);
+ result.push({
+ id: 'Wi-Fi',
+ iface,
+ model,
+ vendor: '',
+ mac
+ });
}
- charset = ''
- } else if (tmp.length) {
- tmp = decodeText(tmp, 'binary', 'utf8')
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } else if (_windows) {
+ let cmd = 'netsh wlan show interfaces';
+ util.powerShell(cmd).then(function (stdout) {
+ const allLines = stdout.toString().split('\r\n');
+ for (let i = 0; i < allLines.length; i++) {
+ allLines[i] = allLines[i].trim();
+ }
+ const parts = allLines.join('\r\n').split(':\r\n\r\n');
+ parts.shift();
+ parts.forEach(part => {
+ const lines = part.split('\r\n');
+ if (lines.length >= 5) {
+ const iface = lines[0].indexOf(':') >= 0 ? lines[0].split(':')[1].trim() : '';
+ const model = lines[1].indexOf(':') >= 0 ? lines[1].split(':')[1].trim() : '';
+ const id = lines[2].indexOf(':') >= 0 ? lines[2].split(':')[1].trim() : '';
+ const macParts = lines[3].indexOf(':') >= 0 ? lines[3].split(':') : [];
+ macParts.shift();
+ const mac = macParts.join(':').trim();
+ const vendor = getVendor(model);
+ if (iface && model && id && mac) {
+ result.push({
+ id,
+ iface,
+ model,
+ vendor,
+ mac,
+ });
+ }
+ }
+ });
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } else {
+ if (callback) {
+ callback(result);
}
- if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
- tmp = ''
- ++p
- continue
- } else if (!inquote && (char === ' ' || char === '\t')) { continue }
- }
- tmp += char
- }
- if (charset && tmp.length) {
- tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
- 'binary',
- charset)
- } else if (tmp) {
- tmp = decodeText(tmp, 'binary', 'utf8')
- }
-
- if (res[p] === undefined) {
- if (tmp) { res[p] = tmp }
- } else { res[p][1] = tmp }
-
- return res
+ resolve(result);
+ }
+ });
+ });
}
-module.exports = parseParams
+exports.wifiInterfaces = wifiInterfaces;
/***/ }),
@@ -149334,7 +149407,7 @@ module.exports = /*#__PURE__*/JSON.parse('[["0","\\u0000",128],["a1","。",62],[
/***/ 15460:
/***/ ((module) => {
-module.exports = {"rE":"5.24.3"};
+module.exports = {"rE":"5.25.3"};
/***/ }),
@@ -149600,7 +149673,7 @@ var cache = __nccwpck_require__(57968);
// EXTERNAL MODULE: ../../node_modules/@actions/github/lib/github.js
var lib_github = __nccwpck_require__(58064);
// EXTERNAL MODULE: ../../node_modules/systeminformation/lib/index.js
-var lib = __nccwpck_require__(70657);
+var lib = __nccwpck_require__(8134);
// EXTERNAL MODULE: ../../node_modules/yaml/dist/index.js
var dist = __nccwpck_require__(33483);
// EXTERNAL MODULE: ../../node_modules/semver/index.js
diff --git a/dist/post/LICENSE.txt b/dist/post/LICENSE.txt
index 26041f8f..09d0144b 100644
--- a/dist/post/LICENSE.txt
+++ b/dist/post/LICENSE.txt
@@ -1465,7 +1465,7 @@ systeminformation
MIT
The MIT License (MIT)
-Copyright (c) 2014-2024 Sebastian Hildebrandt
+Copyright (c) 2014-2025 Sebastian Hildebrandt
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
diff --git a/dist/post/index.js b/dist/post/index.js
index 25e5b0ad..5d3c1d91 100644
--- a/dist/post/index.js
+++ b/dist/post/index.js
@@ -52638,53373 +52638,53446 @@ module.exports = toNumber
/***/ }),
-/***/ 47411:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// audio.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 16. audio
-// ----------------------------------------------------------------------------------
-
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-function parseAudioType(str, input, output) {
- str = str.toLowerCase();
- let result = '';
+/***/ 94176:
+/***/ ((module) => {
- if (str.indexOf('input') >= 0) { result = 'Microphone'; }
- if (str.indexOf('display audio') >= 0) { result = 'Speaker'; }
- if (str.indexOf('speak') >= 0) { result = 'Speaker'; }
- if (str.indexOf('laut') >= 0) { result = 'Speaker'; }
- if (str.indexOf('loud') >= 0) { result = 'Speaker'; }
- if (str.indexOf('head') >= 0) { result = 'Headset'; }
- if (str.indexOf('mic') >= 0) { result = 'Microphone'; }
- if (str.indexOf('mikr') >= 0) { result = 'Microphone'; }
- if (str.indexOf('phone') >= 0) { result = 'Phone'; }
- if (str.indexOf('controll') >= 0) { result = 'Controller'; }
- if (str.indexOf('line o') >= 0) { result = 'Line Out'; }
- if (str.indexOf('digital o') >= 0) { result = 'Digital Out'; }
- if (str.indexOf('smart sound technology') >= 0) { result = 'Digital Signal Processor'; }
- if (str.indexOf('high definition audio') >= 0) { result = 'Sound Driver'; }
+/******************************************************************************
+Copyright (c) Microsoft Corporation.
- if (!result && output) {
- result = 'Speaker';
- } else if (!result && input) {
- result = 'Microphone';
- }
- return result;
-}
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */
+var __extends;
+var __assign;
+var __rest;
+var __decorate;
+var __param;
+var __esDecorate;
+var __runInitializers;
+var __propKey;
+var __setFunctionName;
+var __metadata;
+var __awaiter;
+var __generator;
+var __exportStar;
+var __values;
+var __read;
+var __spread;
+var __spreadArrays;
+var __spreadArray;
+var __await;
+var __asyncGenerator;
+var __asyncDelegator;
+var __asyncValues;
+var __makeTemplateObject;
+var __importStar;
+var __importDefault;
+var __classPrivateFieldGet;
+var __classPrivateFieldSet;
+var __classPrivateFieldIn;
+var __createBinding;
+var __addDisposableResource;
+var __disposeResources;
+var __rewriteRelativeImportExtension;
+(function (factory) {
+ var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
+ if (typeof define === "function" && define.amd) {
+ define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
+ }
+ else if ( true && typeof module.exports === "object") {
+ factory(createExporter(root, createExporter(module.exports)));
+ }
+ else {
+ factory(createExporter(root));
+ }
+ function createExporter(exports, previous) {
+ if (exports !== root) {
+ if (typeof Object.create === "function") {
+ Object.defineProperty(exports, "__esModule", { value: true });
+ }
+ else {
+ exports.__esModule = true;
+ }
+ }
+ return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
+ }
+})
+(function (exporter) {
+ var extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
-function getLinuxAudioPci() {
- let cmd = 'lspci -v 2>/dev/null';
- let result = [];
- try {
- const parts = execSync(cmd, util.execOptsLinux).toString().split('\n\n');
- parts.forEach(element => {
- const lines = element.split('\n');
- if (lines && lines.length && lines[0].toLowerCase().indexOf('audio') >= 0) {
- const audio = {};
- audio.slotId = lines[0].split(' ')[0];
- audio.driver = util.getValue(lines, 'Kernel driver in use', ':', true) || util.getValue(lines, 'Kernel modules', ':', true);
- result.push(audio);
- }
- });
- return result;
- } catch (e) {
- return result;
- }
-}
+ __extends = function (d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
-function parseLinuxAudioPciMM(lines, audioPCI) {
- const result = {};
- const slotId = util.getValue(lines, 'Slot');
+ __assign = Object.assign || function (t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ };
- const pciMatch = audioPCI.filter(function (item) { return item.slotId === slotId; });
+ __rest = function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+ };
- result.id = slotId;
- result.name = util.getValue(lines, 'SDevice');
- result.manufacturer = util.getValue(lines, 'SVendor');
- result.revision = util.getValue(lines, 'Rev');
- result.driver = pciMatch && pciMatch.length === 1 && pciMatch[0].driver ? pciMatch[0].driver : '';
- result.default = null;
- result.channel = 'PCIe';
- result.type = parseAudioType(result.name, null, null);
- result.in = null;
- result.out = null;
- result.status = 'online';
+ __decorate = function (decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+ };
- return result;
-}
+ __param = function (paramIndex, decorator) {
+ return function (target, key) { decorator(target, key, paramIndex); }
+ };
-function parseDarwinChannel(str) {
- let result = '';
+ __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
+ var _, done = false;
+ for (var i = decorators.length - 1; i >= 0; i--) {
+ var context = {};
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
+ if (kind === "accessor") {
+ if (result === void 0) continue;
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
+ if (_ = accept(result.get)) descriptor.get = _;
+ if (_ = accept(result.set)) descriptor.set = _;
+ if (_ = accept(result.init)) initializers.unshift(_);
+ }
+ else if (_ = accept(result)) {
+ if (kind === "field") initializers.unshift(_);
+ else descriptor[key] = _;
+ }
+ }
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
+ done = true;
+ };
- if (str.indexOf('builtin') >= 0) { result = 'Built-In'; }
- if (str.indexOf('extern') >= 0) { result = 'Audio-Jack'; }
- if (str.indexOf('hdmi') >= 0) { result = 'HDMI'; }
- if (str.indexOf('displayport') >= 0) { result = 'Display-Port'; }
- if (str.indexOf('usb') >= 0) { result = 'USB'; }
- if (str.indexOf('pci') >= 0) { result = 'PCIe'; }
+ __runInitializers = function (thisArg, initializers, value) {
+ var useValue = arguments.length > 2;
+ for (var i = 0; i < initializers.length; i++) {
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
+ }
+ return useValue ? value : void 0;
+ };
- return result;
-}
+ __propKey = function (x) {
+ return typeof x === "symbol" ? x : "".concat(x);
+ };
-function parseDarwinAudio(audioObject, id) {
- const result = {};
- const channelStr = ((audioObject.coreaudio_device_transport || '') + ' ' + (audioObject._name || '')).toLowerCase();
+ __setFunctionName = function (f, name, prefix) {
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
+ };
- result.id = id;
- result.name = audioObject._name;
- result.manufacturer = audioObject.coreaudio_device_manufacturer;
- result.revision = null;
- result.driver = null;
- result.default = !!(audioObject.coreaudio_default_audio_input_device || '') || !!(audioObject.coreaudio_default_audio_output_device || '');
- result.channel = parseDarwinChannel(channelStr);
- result.type = parseAudioType(result.name, !!(audioObject.coreaudio_device_input || ''), !!(audioObject.coreaudio_device_output || ''));
- result.in = !!(audioObject.coreaudio_device_input || '');
- result.out = !!(audioObject.coreaudio_device_output || '');
- result.status = 'online';
+ __metadata = function (metadataKey, metadataValue) {
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
+ };
- return result;
-}
+ __awaiter = function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ };
-function parseWindowsAudio(lines) {
- const result = {};
- const status = util.getValue(lines, 'StatusInfo', ':');
+ __generator = function (thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+ };
- result.id = util.getValue(lines, 'DeviceID', ':'); // PNPDeviceID??
- result.name = util.getValue(lines, 'name', ':');
- result.manufacturer = util.getValue(lines, 'manufacturer', ':');
- result.revision = null;
- result.driver = null;
- result.default = null;
- result.channel = null;
- result.type = parseAudioType(result.name, null, null);
- result.in = null;
- result.out = null;
- result.status = status;
+ __exportStar = function(m, o) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
+ };
- return result;
-}
+ __createBinding = Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+ }) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+ });
-function audio(callback) {
+ __values = function (o) {
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+ if (m) return m.call(o);
+ if (o && typeof o.length === "number") return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+ };
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux || _freebsd || _openbsd || _netbsd) {
- let cmd = 'lspci -vmm 2>/dev/null';
- exec(cmd, function (error, stdout) {
- // PCI
- if (!error) {
- const audioPCI = getLinuxAudioPci();
- const parts = stdout.toString().split('\n\n');
- parts.forEach(element => {
- const lines = element.split('\n');
- if (util.getValue(lines, 'class', ':', true).toLowerCase().indexOf('audio') >= 0) {
- const audio = parseLinuxAudioPciMM(lines, audioPCI);
- result.push(audio);
- }
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_darwin) {
- let cmd = 'system_profiler SPAudioDataType -json';
- exec(cmd, function (error, stdout) {
- if (!error) {
+ __read = function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
try {
- const outObj = JSON.parse(stdout.toString());
- if (outObj.SPAudioDataType && outObj.SPAudioDataType.length && outObj.SPAudioDataType[0] && outObj.SPAudioDataType[0]['_items'] && outObj.SPAudioDataType[0]['_items'].length) {
- for (let i = 0; i < outObj.SPAudioDataType[0]['_items'].length; i++) {
- const audio = parseDarwinAudio(outObj.SPAudioDataType[0]['_items'][i], i);
- result.push(audio);
- }
- }
- } catch (e) {
- util.noop();
+ if (r && !r.done && (m = i["return"])) m.call(i);
}
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_windows) {
- util.powerShell('Get-CimInstance Win32_SoundDevice | select DeviceID,StatusInfo,Name,Manufacturer | fl').then((stdout, error) => {
- if (!error) {
- const parts = stdout.toString().split(/\n\s*\n/);
- parts.forEach(element => {
- const lines = element.split('\n');
- if (util.getValue(lines, 'name', ':')) {
- result.push(parseWindowsAudio(lines));
- }
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_sunos) {
- resolve(null);
- }
- });
- });
-}
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+ };
-exports.audio = audio;
+ /** @deprecated */
+ __spread = function () {
+ for (var ar = [], i = 0; i < arguments.length; i++)
+ ar = ar.concat(__read(arguments[i]));
+ return ar;
+ };
+ /** @deprecated */
+ __spreadArrays = function () {
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+ r[k] = a[j];
+ return r;
+ };
-/***/ }),
+ __spreadArray = function (to, from, pack) {
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
+ if (ar || !(i in from)) {
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
+ ar[i] = from[i];
+ }
+ }
+ return to.concat(ar || Array.prototype.slice.call(from));
+ };
-/***/ 35552:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ __await = function (v) {
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
+ };
+ __asyncGenerator = function (thisArg, _arguments, generator) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
+ function fulfill(value) { resume("next", value); }
+ function reject(value) { resume("throw", value); }
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
+ };
-// @ts-check;
-// ==================================================================================
-// battery.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 6. Battery
-// ----------------------------------------------------------------------------------
+ __asyncDelegator = function (o) {
+ var i, p;
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
+ };
-const exec = (__nccwpck_require__(35317).exec);
-const fs = __nccwpck_require__(79896);
-const util = __nccwpck_require__(33225);
+ __asyncValues = function (o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+ };
-let _platform = process.platform;
+ __makeTemplateObject = function (cooked, raw) {
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
+ return cooked;
+ };
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
+ var __setModuleDefault = Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+ }) : function(o, v) {
+ o["default"] = v;
+ };
-function parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity) {
- const result = {};
- let status = util.getValue(lines, 'BatteryStatus', ':').trim();
- // 1 = "Discharging"
- // 2 = "On A/C"
- // 3 = "Fully Charged"
- // 4 = "Low"
- // 5 = "Critical"
- // 6 = "Charging"
- // 7 = "Charging High"
- // 8 = "Charging Low"
- // 9 = "Charging Critical"
- // 10 = "Undefined"
- // 11 = "Partially Charged"
- if (status >= 0) {
- const statusValue = status ? parseInt(status) : 0;
- result.status = statusValue;
- result.hasBattery = true;
- result.maxCapacity = fullChargeCapacity || parseInt(util.getValue(lines, 'DesignCapacity', ':') || 0);
- result.designedCapacity = parseInt(util.getValue(lines, 'DesignCapacity', ':') || designedCapacity);
- result.voltage = parseInt(util.getValue(lines, 'DesignVoltage', ':') || 0) / 1000.0;
- result.capacityUnit = 'mWh';
- result.percent = parseInt(util.getValue(lines, 'EstimatedChargeRemaining', ':') || 0);
- result.currentCapacity = parseInt(result.maxCapacity * result.percent / 100);
- result.isCharging = (statusValue >= 6 && statusValue <= 9) || statusValue === 11 || ((statusValue !== 3) && (statusValue !== 1) && result.percent < 100);
- result.acConnected = result.isCharging || statusValue === 2;
- result.model = util.getValue(lines, 'DeviceID', ':');
- } else {
- result.status = -1;
- }
+ var ownKeys = function(o) {
+ ownKeys = Object.getOwnPropertyNames || function (o) {
+ var ar = [];
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+ return ar;
+ };
+ return ownKeys(o);
+ };
- return result;
-}
+ __importStar = function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+ __setModuleDefault(result, mod);
+ return result;
+ };
-module.exports = function (callback) {
+ __importDefault = function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+ };
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
- hasBattery: false,
- cycleCount: 0,
- isCharging: false,
- designedCapacity: 0,
- maxCapacity: 0,
- currentCapacity: 0,
- voltage: 0,
- capacityUnit: '',
- percent: 0,
- timeRemaining: null,
- acConnected: true,
- type: '',
- model: '',
- manufacturer: '',
- serial: ''
- };
+ __classPrivateFieldGet = function (receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+ };
- if (_linux) {
- let battery_path = '';
- if (fs.existsSync('/sys/class/power_supply/BAT1/uevent')) {
- battery_path = '/sys/class/power_supply/BAT1/';
- } else if (fs.existsSync('/sys/class/power_supply/BAT0/uevent')) {
- battery_path = '/sys/class/power_supply/BAT0/';
- }
+ __classPrivateFieldSet = function (receiver, state, value, kind, f) {
+ if (kind === "m") throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+ };
- let acConnected = false;
- let acPath = '';
- if (fs.existsSync('/sys/class/power_supply/AC/online')) {
- acPath = '/sys/class/power_supply/AC/online';
- } else if (fs.existsSync('/sys/class/power_supply/AC0/online')) {
- acPath = '/sys/class/power_supply/AC0/online';
- }
+ __classPrivateFieldIn = function (state, receiver) {
+ if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
+ return typeof state === "function" ? receiver === state : state.has(receiver);
+ };
- if (acPath) {
- const file = fs.readFileSync(acPath);
- acConnected = file.toString().trim() === '1';
+ __addDisposableResource = function (env, value, async) {
+ if (value !== null && value !== void 0) {
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
+ var dispose, inner;
+ if (async) {
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
+ dispose = value[Symbol.asyncDispose];
+ }
+ if (dispose === void 0) {
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
+ dispose = value[Symbol.dispose];
+ if (async) inner = dispose;
+ }
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
+ env.stack.push({ value: value, dispose: dispose, async: async });
}
+ else if (async) {
+ env.stack.push({ async: true });
+ }
+ return value;
+ };
- if (battery_path) {
- fs.readFile(battery_path + 'uevent', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
-
- result.isCharging = (util.getValue(lines, 'POWER_SUPPLY_STATUS', '=').toLowerCase() === 'charging');
- result.acConnected = acConnected || result.isCharging;
- result.voltage = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_VOLTAGE_NOW', '='), 10) / 1000000.0;
- result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
- result.cycleCount = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CYCLE_COUNT', '='), 10);
- result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL', '=', true, true), 10) / 1000.0 * (result.voltage || 1));
- const desingedMinVoltage = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_VOLTAGE_MIN_DESIGN', '='), 10) / 1000000.0;
- result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL_DESIGN', '=', true, true), 10) / 1000.0 * (desingedMinVoltage || result.voltage || 1));
- result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10) / 1000.0 * (result.voltage || 1));
- if (!result.maxCapacity) {
- result.maxCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL', '=', true, true), 10) / 1000.0;
- result.designedCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL_DESIGN', '=', true, true), 10) / 1000.0 | result.maxCapacity;
- result.currentCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10) / 1000.0;
- }
- const percent = util.getValue(lines, 'POWER_SUPPLY_CAPACITY', '=');
- const energy = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10);
- const power = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_POWER_NOW', '='), 10);
- const current = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CURRENT_NOW', '='), 10);
- const charge = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10);
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
+ var e = new Error(message);
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
+ };
- result.percent = parseInt('0' + percent, 10);
- if (result.maxCapacity && result.currentCapacity) {
- result.hasBattery = true;
- if (!percent) {
- result.percent = 100.0 * result.currentCapacity / result.maxCapacity;
- }
- }
- if (result.isCharging) {
- result.hasBattery = true;
- }
- if (energy && power) {
- result.timeRemaining = Math.floor(energy / power * 60);
- } else if (current && charge) {
- result.timeRemaining = Math.floor(charge / current * 60);
- } else if (current && result.currentCapacity) {
- result.timeRemaining = Math.floor(result.currentCapacity / current * 60);
- }
- result.type = util.getValue(lines, 'POWER_SUPPLY_TECHNOLOGY', '=');
- result.model = util.getValue(lines, 'POWER_SUPPLY_MODEL_NAME', '=');
- result.manufacturer = util.getValue(lines, 'POWER_SUPPLY_MANUFACTURER', '=');
- result.serial = util.getValue(lines, 'POWER_SUPPLY_SERIAL_NUMBER', '=');
- if (callback) { callback(result); }
- resolve(result);
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
+ __disposeResources = function (env) {
+ function fail(e) {
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
+ env.hasError = true;
}
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('sysctl -i hw.acpi.battery hw.acpi.acline', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- const batteries = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.units'), 10);
- const percent = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.life'), 10);
- result.hasBattery = (batteries > 0);
- result.cycleCount = null;
- result.isCharging = util.getValue(lines, 'hw.acpi.acline') !== '1';
- result.acConnected = result.isCharging;
- result.maxCapacity = null;
- result.currentCapacity = null;
- result.capacityUnit = 'unknown';
- result.percent = batteries ? percent : null;
- if (callback) { callback(result); }
- resolve(result);
- });
- }
-
- if (_darwin) {
- exec('ioreg -n AppleSmartBattery -r | egrep "CycleCount|IsCharging|DesignCapacity|MaxCapacity|CurrentCapacity|BatterySerialNumber|TimeRemaining|Voltage"; pmset -g batt | grep %', function (error, stdout) {
- if (stdout) {
- let lines = stdout.toString().replace(/ +/g, '').replace(/"+/g, '').replace(/-/g, '').split('\n');
- result.cycleCount = parseInt('0' + util.getValue(lines, 'cyclecount', '='), 10);
- result.voltage = parseInt('0' + util.getValue(lines, 'voltage', '='), 10) / 1000.0;
- result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
- result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'applerawmaxcapacity', '='), 10) * (result.voltage || 1));
- result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'applerawcurrentcapacity', '='), 10) * (result.voltage || 1));
- result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'DesignCapacity', '='), 10) * (result.voltage || 1));
- result.manufacturer = 'Apple';
- result.serial = util.getValue(lines, 'BatterySerialNumber', '=');
- let percent = null;
- const line = util.getValue(lines, 'internal', 'Battery');
- let parts = line.split(';');
- if (parts && parts[0]) {
- let parts2 = parts[0].split('\t');
- if (parts2 && parts2[1]) {
- percent = parseFloat(parts2[1].trim().replace(/%/g, ''));
- }
- }
- if (parts && parts[1]) {
- result.isCharging = (parts[1].trim() === 'charging');
- result.acConnected = (parts[1].trim() !== 'discharging');
- } else {
- result.isCharging = util.getValue(lines, 'ischarging', '=').toLowerCase() === 'yes';
- result.acConnected = result.isCharging;
- }
- if (result.maxCapacity && result.currentCapacity) {
- result.hasBattery = true;
- result.type = 'Li-ion';
- result.percent = percent !== null ? percent : Math.round(100.0 * result.currentCapacity / result.maxCapacity);
- if (!result.isCharging) {
- result.timeRemaining = parseInt('0' + util.getValue(lines, 'TimeRemaining', '='), 10);
- }
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance Win32_Battery | select BatteryStatus, DesignCapacity, DesignVoltage, EstimatedChargeRemaining, DeviceID | fl'));
- workload.push(util.powerShell('(Get-WmiObject -Class BatteryStaticData -Namespace ROOT/WMI).DesignedCapacity'));
- workload.push(util.powerShell('(Get-CimInstance -Class BatteryFullChargedCapacity -Namespace ROOT/WMI).FullChargedCapacity'));
- util.promiseAll(
- workload
- ).then((data) => {
- if (data) {
- let parts = data.results[0].split(/\n\s*\n/);
- let batteries = [];
- const hasValue = value => /\S/.test(value);
- for (let i = 0; i < parts.length; i++) {
- if (hasValue(parts[i]) && (!batteries.length || !hasValue(parts[i - 1]))) {
- batteries.push([]);
- }
- if (hasValue(parts[i])) {
- batteries[batteries.length - 1].push(parts[i]);
- }
- }
- let designCapacities = data.results[1].split('\r\n').filter(e => e);
- let fullChargeCapacities = data.results[2].split('\r\n').filter(e => e);
- if (batteries.length) {
- let first = false;
- let additionalBatteries = [];
- for (let i = 0; i < batteries.length; i++) {
- let lines = batteries[i][0].split('\r\n');
- const designedCapacity = designCapacities && designCapacities.length >= (i + 1) && designCapacities[i] ? util.toInt(designCapacities[i]) : 0;
- const fullChargeCapacity = fullChargeCapacities && fullChargeCapacities.length >= (i + 1) && fullChargeCapacities[i] ? util.toInt(fullChargeCapacities[i]) : 0;
- const parsed = parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity);
- if (!first && parsed.status > 0 && parsed.status !== 10) {
- result.hasBattery = parsed.hasBattery;
- result.maxCapacity = parsed.maxCapacity;
- result.designedCapacity = parsed.designedCapacity;
- result.voltage = parsed.voltage;
- result.capacityUnit = parsed.capacityUnit;
- result.percent = parsed.percent;
- result.currentCapacity = parsed.currentCapacity;
- result.isCharging = parsed.isCharging;
- result.acConnected = parsed.acConnected;
- result.model = parsed.model;
- first = true;
- } else if (parsed.status !== -1) {
- additionalBatteries.push(
- {
- hasBattery: parsed.hasBattery,
- maxCapacity: parsed.maxCapacity,
- designedCapacity: parsed.designedCapacity,
- voltage: parsed.voltage,
- capacityUnit: parsed.capacityUnit,
- percent: parsed.percent,
- currentCapacity: parsed.currentCapacity,
- isCharging: parsed.isCharging,
- timeRemaining: null,
- acConnected: parsed.acConnected,
- model: parsed.model,
- type: '',
- manufacturer: '',
- serial: ''
- }
- );
- }
- }
- if (!first && additionalBatteries.length) {
- result = additionalBatteries[0];
- additionalBatteries.shift();
+ var r, s = 0;
+ function next() {
+ while (r = env.stack.pop()) {
+ try {
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
+ if (r.dispose) {
+ var result = r.dispose.call(r.value);
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
+ }
+ else s |= 1;
}
- if (additionalBatteries.length) {
- result.additionalBatteries = additionalBatteries;
+ catch (e) {
+ fail(e);
}
- }
}
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
+ if (env.hasError) throw env.error;
}
- }
- });
- });
-};
+ return next();
+ };
+ __rewriteRelativeImportExtension = function (path, preserveJsx) {
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
+ });
+ }
+ return path;
+ };
-/***/ }),
+ exporter("__extends", __extends);
+ exporter("__assign", __assign);
+ exporter("__rest", __rest);
+ exporter("__decorate", __decorate);
+ exporter("__param", __param);
+ exporter("__esDecorate", __esDecorate);
+ exporter("__runInitializers", __runInitializers);
+ exporter("__propKey", __propKey);
+ exporter("__setFunctionName", __setFunctionName);
+ exporter("__metadata", __metadata);
+ exporter("__awaiter", __awaiter);
+ exporter("__generator", __generator);
+ exporter("__exportStar", __exportStar);
+ exporter("__createBinding", __createBinding);
+ exporter("__values", __values);
+ exporter("__read", __read);
+ exporter("__spread", __spread);
+ exporter("__spreadArrays", __spreadArrays);
+ exporter("__spreadArray", __spreadArray);
+ exporter("__await", __await);
+ exporter("__asyncGenerator", __asyncGenerator);
+ exporter("__asyncDelegator", __asyncDelegator);
+ exporter("__asyncValues", __asyncValues);
+ exporter("__makeTemplateObject", __makeTemplateObject);
+ exporter("__importStar", __importStar);
+ exporter("__importDefault", __importDefault);
+ exporter("__classPrivateFieldGet", __classPrivateFieldGet);
+ exporter("__classPrivateFieldSet", __classPrivateFieldSet);
+ exporter("__classPrivateFieldIn", __classPrivateFieldIn);
+ exporter("__addDisposableResource", __addDisposableResource);
+ exporter("__disposeResources", __disposeResources);
+ exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
+});
-/***/ 45595:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+0 && (0);
-// @ts-check
-// ==================================================================================
-// audio.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 17. bluetooth
-// ----------------------------------------------------------------------------------
+/***/ }),
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const path = __nccwpck_require__(16928);
-const util = __nccwpck_require__(33225);
-const bluetoothVendors = __nccwpck_require__(55848);
-const fs = __nccwpck_require__(79896);
+/***/ 5070:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-let _platform = process.platform;
+module.exports = __nccwpck_require__(35862);
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-function parseBluetoothType(str) {
- let result = '';
+/***/ }),
- if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
- if (str.indexOf('mouse') >= 0) { result = 'Mouse'; }
- if (str.indexOf('trackpad') >= 0) { result = 'Trackpad'; }
- if (str.indexOf('speaker') >= 0) { result = 'Speaker'; }
- if (str.indexOf('headset') >= 0) { result = 'Headset'; }
- if (str.indexOf('phone') >= 0) { result = 'Phone'; }
- if (str.indexOf('macbook') >= 0) { result = 'Computer'; }
- if (str.indexOf('imac') >= 0) { result = 'Computer'; }
- if (str.indexOf('ipad') >= 0) { result = 'Tablet'; }
- if (str.indexOf('watch') >= 0) { result = 'Watch'; }
- if (str.indexOf('headphone') >= 0) { result = 'Headset'; }
- // to be continued ...
+/***/ 35862:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return result;
-}
-function parseBluetoothManufacturer(str) {
- let result = str.split(' ')[0];
- str = str.toLowerCase();
- if (str.indexOf('apple') >= 0) { result = 'Apple'; }
- if (str.indexOf('ipad') >= 0) { result = 'Apple'; }
- if (str.indexOf('imac') >= 0) { result = 'Apple'; }
- if (str.indexOf('iphone') >= 0) { result = 'Apple'; }
- if (str.indexOf('magic mouse') >= 0) { result = 'Apple'; }
- if (str.indexOf('magic track') >= 0) { result = 'Apple'; }
- if (str.indexOf('macbook') >= 0) { result = 'Apple'; }
- // to be continued ...
- return result;
-}
+var net = __nccwpck_require__(69278);
+var tls = __nccwpck_require__(64756);
+var http = __nccwpck_require__(58611);
+var https = __nccwpck_require__(65692);
+var events = __nccwpck_require__(24434);
+var assert = __nccwpck_require__(42613);
+var util = __nccwpck_require__(39023);
-function parseBluetoothVendor(str) {
- const id = parseInt(str);
- if (!isNaN(id)) return bluetoothVendors[id];
-}
-function parseLinuxBluetoothInfo(lines, macAddr1, macAddr2) {
- const result = {};
+exports.httpOverHttp = httpOverHttp;
+exports.httpsOverHttp = httpsOverHttp;
+exports.httpOverHttps = httpOverHttps;
+exports.httpsOverHttps = httpsOverHttps;
- result.device = null;
- result.name = util.getValue(lines, 'name', '=');
- result.manufacturer = null;
- result.macDevice = macAddr1;
- result.macHost = macAddr2;
- result.batteryPercent = null;
- result.type = parseBluetoothType(result.name.toLowerCase());
- result.connected = false;
- return result;
+function httpOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ return agent;
}
-function parseDarwinBluetoothDevices(bluetoothObject, macAddr2) {
- const result = {};
- const typeStr = ((bluetoothObject.device_minorClassOfDevice_string || bluetoothObject.device_majorClassOfDevice_string || bluetoothObject.device_minorType || '') + (bluetoothObject.device_name || '')).toLowerCase();
+function httpsOverHttp(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = http.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
+}
- result.device = bluetoothObject.device_services || '';
- result.name = bluetoothObject.device_name || '';
- result.manufacturer = bluetoothObject.device_manufacturer || parseBluetoothVendor(bluetoothObject.device_vendorID) || parseBluetoothManufacturer(bluetoothObject.device_name || '') || '';
- result.macDevice = (bluetoothObject.device_addr || bluetoothObject.device_address || '').toLowerCase().replace(/-/g, ':');
- result.macHost = macAddr2;
- result.batteryPercent = bluetoothObject.device_batteryPercent || null;
- result.type = parseBluetoothType(typeStr);
- result.connected = bluetoothObject.device_isconnected === 'attrib_Yes' || false;
+function httpOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ return agent;
+}
- return result;
+function httpsOverHttps(options) {
+ var agent = new TunnelingAgent(options);
+ agent.request = https.request;
+ agent.createSocket = createSecureSocket;
+ agent.defaultPort = 443;
+ return agent;
}
-function parseWindowsBluetooth(lines) {
- const result = {};
- result.device = null;
- result.name = util.getValue(lines, 'name', ':');
- result.manufacturer = util.getValue(lines, 'manufacturer', ':');
- result.macDevice = null;
- result.macHost = null;
- result.batteryPercent = null;
- result.type = parseBluetoothType(result.name.toLowerCase());
- result.connected = null;
+function TunnelingAgent(options) {
+ var self = this;
+ self.options = options || {};
+ self.proxyOptions = self.options.proxy || {};
+ self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
+ self.requests = [];
+ self.sockets = [];
- return result;
+ self.on('free', function onFree(socket, host, port, localAddress) {
+ var options = toOptions(host, port, localAddress);
+ for (var i = 0, len = self.requests.length; i < len; ++i) {
+ var pending = self.requests[i];
+ if (pending.host === options.host && pending.port === options.port) {
+ // Detect the request to connect same origin server,
+ // reuse the connection.
+ self.requests.splice(i, 1);
+ pending.request.onSocket(socket);
+ return;
+ }
+ }
+ socket.destroy();
+ self.removeSocket(socket);
+ });
}
+util.inherits(TunnelingAgent, events.EventEmitter);
-function bluetoothDevices(callback) {
+TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
+ var self = this;
+ var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux) {
- // get files in /var/lib/bluetooth/ recursive
- const btFiles = util.getFilesInPath('/var/lib/bluetooth/');
- btFiles.forEach((element) => {
- const filename = path.basename(element);
- const pathParts = element.split('/');
- const macAddr1 = pathParts.length >= 6 ? pathParts[pathParts.length - 2] : null;
- const macAddr2 = pathParts.length >= 7 ? pathParts[pathParts.length - 3] : null;
- if (filename === 'info') {
- const infoFile = fs.readFileSync(element, { encoding: 'utf8' }).split('\n');
- result.push(parseLinuxBluetoothInfo(infoFile, macAddr1, macAddr2));
- }
- });
- // determine "connected" with hcitool con
- try {
- const hdicon = execSync('hcitool con', util.execOptsLinux).toString().toLowerCase();
- for (let i = 0; i < result.length; i++) {
- if (result[i].macDevice && result[i].macDevice.length > 10 && hdicon.indexOf(result[i].macDevice.toLowerCase()) >= 0) {
- result[i].connected = true;
- }
- }
- } catch (e) {
- util.noop();
- }
+ if (self.sockets.length >= this.maxSockets) {
+ // We are over limit so we'll add it to the queue.
+ self.requests.push(options);
+ return;
+ }
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- if (_darwin) {
- let cmd = 'system_profiler SPBluetoothDataType -json';
- exec(cmd, function (error, stdout) {
- if (!error) {
- try {
- const outObj = JSON.parse(stdout.toString());
- if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_title'] && outObj.SPBluetoothDataType[0]['device_title'].length) {
- // missing: host BT Adapter macAddr ()
- let macAddr2 = null;
- if (outObj.SPBluetoothDataType[0]['local_device_title'] && outObj.SPBluetoothDataType[0].local_device_title.general_address) {
- macAddr2 = outObj.SPBluetoothDataType[0].local_device_title.general_address.toLowerCase().replace(/-/g, ':');
- }
- outObj.SPBluetoothDataType[0]['device_title'].forEach((element) => {
- const obj = element;
- const objKey = Object.keys(obj);
- if (objKey && objKey.length === 1) {
- const innerObject = obj[objKey[0]];
- innerObject.device_name = objKey[0];
- const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
- result.push(bluetoothDevice);
- }
- });
- }
- if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_connected'] && outObj.SPBluetoothDataType[0]['device_connected'].length) {
- const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null;
- outObj.SPBluetoothDataType[0]['device_connected'].forEach((element) => {
- const obj = element;
- const objKey = Object.keys(obj);
- if (objKey && objKey.length === 1) {
- const innerObject = obj[objKey[0]];
- innerObject.device_name = objKey[0];
- innerObject.device_isconnected = 'attrib_Yes';
- const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
- result.push(bluetoothDevice);
- }
- });
- }
- if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_not_connected'] && outObj.SPBluetoothDataType[0]['device_not_connected'].length) {
- const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null;
- outObj.SPBluetoothDataType[0]['device_not_connected'].forEach((element) => {
- const obj = element;
- const objKey = Object.keys(obj);
- if (objKey && objKey.length === 1) {
- const innerObject = obj[objKey[0]];
- innerObject.device_name = objKey[0];
- innerObject.device_isconnected = 'attrib_No';
- const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
- result.push(bluetoothDevice);
- }
- });
- }
- } catch (e) {
- util.noop();
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_windows) {
- util.powerShell('Get-CimInstance Win32_PNPEntity | select PNPClass, Name, Manufacturer | fl').then((stdout, error) => {
- if (!error) {
- const parts = stdout.toString().split(/\n\s*\n/);
- parts.forEach((part) => {
- if (util.getValue(part.split('\n'), 'PNPClass', ':') === 'Bluetooth') {
- result.push(parseWindowsBluetooth(part.split('\n')));
- }
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_freebsd || _netbsd || _openbsd || _sunos) {
- resolve(null);
- }
+ // If we are under maxSockets create a new one.
+ self.createSocket(options, function(socket) {
+ socket.on('free', onFree);
+ socket.on('close', onCloseOrRemove);
+ socket.on('agentRemove', onCloseOrRemove);
+ req.onSocket(socket);
+
+ function onFree() {
+ self.emit('free', socket, options);
+ }
+
+ function onCloseOrRemove(err) {
+ self.removeSocket(socket);
+ socket.removeListener('free', onFree);
+ socket.removeListener('close', onCloseOrRemove);
+ socket.removeListener('agentRemove', onCloseOrRemove);
+ }
+ });
+};
+
+TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
+ var self = this;
+ var placeholder = {};
+ self.sockets.push(placeholder);
+
+ var connectOptions = mergeOptions({}, self.proxyOptions, {
+ method: 'CONNECT',
+ path: options.host + ':' + options.port,
+ agent: false,
+ headers: {
+ host: options.host + ':' + options.port
+ }
+ });
+ if (options.localAddress) {
+ connectOptions.localAddress = options.localAddress;
+ }
+ if (connectOptions.proxyAuth) {
+ connectOptions.headers = connectOptions.headers || {};
+ connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
+ new Buffer(connectOptions.proxyAuth).toString('base64');
+ }
+
+ debug('making CONNECT request');
+ var connectReq = self.request(connectOptions);
+ connectReq.useChunkedEncodingByDefault = false; // for v0.6
+ connectReq.once('response', onResponse); // for v0.6
+ connectReq.once('upgrade', onUpgrade); // for v0.6
+ connectReq.once('connect', onConnect); // for v0.7 or later
+ connectReq.once('error', onError);
+ connectReq.end();
+
+ function onResponse(res) {
+ // Very hacky. This is necessary to avoid http-parser leaks.
+ res.upgrade = true;
+ }
+
+ function onUpgrade(res, socket, head) {
+ // Hacky.
+ process.nextTick(function() {
+ onConnect(res, socket, head);
+ });
+ }
+
+ function onConnect(res, socket, head) {
+ connectReq.removeAllListeners();
+ socket.removeAllListeners();
+
+ if (res.statusCode !== 200) {
+ debug('tunneling socket could not be established, statusCode=%d',
+ res.statusCode);
+ socket.destroy();
+ var error = new Error('tunneling socket could not be established, ' +
+ 'statusCode=' + res.statusCode);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ if (head.length > 0) {
+ debug('got illegal response body from proxy');
+ socket.destroy();
+ var error = new Error('got illegal response body from proxy');
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ return;
+ }
+ debug('tunneling connection has established');
+ self.sockets[self.sockets.indexOf(placeholder)] = socket;
+ return cb(socket);
+ }
+
+ function onError(cause) {
+ connectReq.removeAllListeners();
+
+ debug('tunneling socket could not be established, cause=%s\n',
+ cause.message, cause.stack);
+ var error = new Error('tunneling socket could not be established, ' +
+ 'cause=' + cause.message);
+ error.code = 'ECONNRESET';
+ options.request.emit('error', error);
+ self.removeSocket(placeholder);
+ }
+};
+
+TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
+ var pos = this.sockets.indexOf(socket)
+ if (pos === -1) {
+ return;
+ }
+ this.sockets.splice(pos, 1);
+
+ var pending = this.requests.shift();
+ if (pending) {
+ // If we have pending requests and a socket gets closed a new one
+ // needs to be created to take over in the pool for the one that closed.
+ this.createSocket(pending, function(socket) {
+ pending.request.onSocket(socket);
+ });
+ }
+};
+
+function createSecureSocket(options, cb) {
+ var self = this;
+ TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
+ var hostHeader = options.request.getHeader('host');
+ var tlsOptions = mergeOptions({}, self.options, {
+ socket: socket,
+ servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
});
+
+ // 0 is dummy port for v0.6
+ var secureSocket = tls.connect(0, tlsOptions);
+ self.sockets[self.sockets.indexOf(socket)] = secureSocket;
+ cb(secureSocket);
});
}
-exports.bluetoothDevices = bluetoothDevices;
+
+function toOptions(host, port, localAddress) {
+ if (typeof host === 'string') { // since v0.10
+ return {
+ host: host,
+ port: port,
+ localAddress: localAddress
+ };
+ }
+ return host; // for v0.11 or later
+}
+
+function mergeOptions(target) {
+ for (var i = 1, len = arguments.length; i < len; ++i) {
+ var overrides = arguments[i];
+ if (typeof overrides === 'object') {
+ var keys = Object.keys(overrides);
+ for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
+ var k = keys[j];
+ if (overrides[k] !== undefined) {
+ target[k] = overrides[k];
+ }
+ }
+ }
+ }
+ return target;
+}
+
+
+var debug;
+if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
+ debug = function() {
+ var args = Array.prototype.slice.call(arguments);
+ if (typeof args[0] === 'string') {
+ args[0] = 'TUNNEL: ' + args[0];
+ } else {
+ args.unshift('TUNNEL:');
+ }
+ console.error.apply(console, args);
+ }
+} else {
+ debug = function() {};
+}
+exports.debug = debug; // for test
/***/ }),
-/***/ 55848:
-/***/ ((module) => {
+/***/ 99069:
+/***/ ((__unused_webpack_module, exports) => {
-// @ts-check
-module.exports = {
- 0x0000: 'Ericsson Technology Licensing',
- 0x0001: 'Nokia Mobile Phones',
- 0x0002: 'Intel Corp.',
- 0x0003: 'IBM Corp.',
- 0x0004: 'Toshiba Corp.',
- 0x0005: '3Com',
- 0x0006: 'Microsoft',
- 0x0007: 'Lucent',
- 0x0008: 'Motorola',
- 0x0009: 'Infineon Technologies AG',
- 0x000a: 'Cambridge Silicon Radio',
- 0x000b: 'Silicon Wave',
- 0x000c: 'Digianswer A/S',
- 0x000d: 'Texas Instruments Inc.',
- 0x000e: 'Ceva, Inc. (formerly Parthus Technologies, Inc.)',
- 0x000f: 'Broadcom Corporation',
- 0x0010: 'Mitel Semiconductor',
- 0x0011: 'Widcomm, Inc',
- 0x0012: 'Zeevo, Inc.',
- 0x0013: 'Atmel Corporation',
- 0x0014: 'Mitsubishi Electric Corporation',
- 0x0015: 'RTX Telecom A/S',
- 0x0016: 'KC Technology Inc.',
- 0x0017: 'NewLogic',
- 0x0018: 'Transilica, Inc.',
- 0x0019: 'Rohde & Schwarz GmbH & Co. KG',
- 0x001a: 'TTPCom Limited',
- 0x001b: 'Signia Technologies, Inc.',
- 0x001c: 'Conexant Systems Inc.',
- 0x001d: 'Qualcomm',
- 0x001e: 'Inventel',
- 0x001f: 'AVM Berlin',
- 0x0020: 'BandSpeed, Inc.',
- 0x0021: 'Mansella Ltd',
- 0x0022: 'NEC Corporation',
- 0x0023: 'WavePlus Technology Co., Ltd.',
- 0x0024: 'Alcatel',
- 0x0025: 'NXP Semiconductors (formerly Philips Semiconductors)',
- 0x0026: 'C Technologies',
- 0x0027: 'Open Interface',
- 0x0028: 'R F Micro Devices',
- 0x0029: 'Hitachi Ltd',
- 0x002a: 'Symbol Technologies, Inc.',
- 0x002b: 'Tenovis',
- 0x002c: 'Macronix International Co. Ltd.',
- 0x002d: 'GCT Semiconductor',
- 0x002e: 'Norwood Systems',
- 0x002f: 'MewTel Technology Inc.',
- 0x0030: 'ST Microelectronics',
- 0x0031: 'Synopsis',
- 0x0032: 'Red-M (Communications) Ltd',
- 0x0033: 'Commil Ltd',
- 0x0034: 'Computer Access Technology Corporation (CATC)',
- 0x0035: 'Eclipse (HQ Espana) S.L.',
- 0x0036: 'Renesas Electronics Corporation',
- 0x0037: 'Mobilian Corporation',
- 0x0038: 'Terax',
- 0x0039: 'Integrated System Solution Corp.',
- 0x003a: 'Matsushita Electric Industrial Co., Ltd.',
- 0x003b: 'Gennum Corporation',
- 0x003c: 'BlackBerry Limited (formerly Research In Motion)',
- 0x003d: 'IPextreme, Inc.',
- 0x003e: 'Systems and Chips, Inc.',
- 0x003f: 'Bluetooth SIG, Inc.',
- 0x0040: 'Seiko Epson Corporation',
- 0x0041: 'Integrated Silicon Solution Taiwan, Inc.',
- 0x0042: 'CONWISE Technology Corporation Ltd',
- 0x0043: 'PARROT SA',
- 0x0044: 'Socket Mobile',
- 0x0045: 'Atheros Communications, Inc.',
- 0x0046: 'MediaTek, Inc.',
- 0x0047: 'Bluegiga',
- 0x0048: 'Marvell Technology Group Ltd.',
- 0x0049: '3DSP Corporation',
- 0x004a: 'Accel Semiconductor Ltd.',
- 0x004b: 'Continental Automotive Systems',
- 0x004c: 'Apple, Inc.',
- 0x004d: 'Staccato Communications, Inc.',
- 0x004e: 'Avago Technologies',
- 0x004f: 'APT Licensing Ltd.',
- 0x0050: 'SiRF Technology',
- 0x0051: 'Tzero Technologies, Inc.',
- 0x0052: 'J&M Corporation',
- 0x0053: 'Free2move AB',
- 0x0054: '3DiJoy Corporation',
- 0x0055: 'Plantronics, Inc.',
- 0x0056: 'Sony Ericsson Mobile Communications',
- 0x0057: 'Harman International Industries, Inc.',
- 0x0058: 'Vizio, Inc.',
- 0x0059: 'Nordic Semiconductor ASA',
- 0x005a: 'EM Microelectronic-Marin SA',
- 0x005b: 'Ralink Technology Corporation',
- 0x005c: 'Belkin International, Inc.',
- 0x005d: 'Realtek Semiconductor Corporation',
- 0x005e: 'Stonestreet One, LLC',
- 0x005f: 'Wicentric, Inc.',
- 0x0060: 'RivieraWaves S.A.S',
- 0x0061: 'RDA Microelectronics',
- 0x0062: 'Gibson Guitars',
- 0x0063: 'MiCommand Inc.',
- 0x0064: 'Band XI International, LLC',
- 0x0065: 'Hewlett-Packard Company',
- 0x0066: '9Solutions Oy',
- 0x0067: 'GN Netcom A/S',
- 0x0068: 'General Motors',
- 0x0069: 'A&D Engineering, Inc.',
- 0x006a: 'MindTree Ltd.',
- 0x006b: 'Polar Electro OY',
- 0x006c: 'Beautiful Enterprise Co., Ltd.',
- 0x006d: 'BriarTek, Inc.',
- 0x006e: 'Summit Data Communications, Inc.',
- 0x006f: 'Sound ID',
- 0x0070: 'Monster, LLC',
- 0x0071: 'connectBlue AB',
- 0x0072: 'ShangHai Super Smart Electronics Co. Ltd.',
- 0x0073: 'Group Sense Ltd.',
- 0x0074: 'Zomm, LLC',
- 0x0075: 'Samsung Electronics Co. Ltd.',
- 0x0076: 'Creative Technology Ltd.',
- 0x0077: 'Laird Technologies',
- 0x0078: 'Nike, Inc.',
- 0x0079: 'lesswire AG',
- 0x007a: 'MStar Semiconductor, Inc.',
- 0x007b: 'Hanlynn Technologies',
- 0x007c: 'A & R Cambridge',
- 0x007d: 'Seers Technology Co. Ltd',
- 0x007e: 'Sports Tracking Technologies Ltd.',
- 0x007f: 'Autonet Mobile',
- 0x0080: 'DeLorme Publishing Company, Inc.',
- 0x0081: 'WuXi Vimicro',
- 0x0082: 'Sennheiser Communications A/S',
- 0x0083: 'TimeKeeping Systems, Inc.',
- 0x0084: 'Ludus Helsinki Ltd.',
- 0x0085: 'BlueRadios, Inc.',
- 0x0086: 'equinox AG',
- 0x0087: 'Garmin International, Inc.',
- 0x0088: 'Ecotest',
- 0x0089: 'GN ReSound A/S',
- 0x008a: 'Jawbone',
- 0x008b: 'Topcorn Positioning Systems, LLC',
- 0x008c: 'Gimbal Inc. (formerly Qualcomm Labs, Inc. and Qualcomm Retail Solutions, Inc.)',
- 0x008d: 'Zscan Software',
- 0x008e: 'Quintic Corp.',
- 0x008f: 'Stollman E+V GmbH',
- 0x0090: 'Funai Electric Co., Ltd.',
- 0x0091: 'Advanced PANMOBIL Systems GmbH & Co. KG',
- 0x0092: 'ThinkOptics, Inc.',
- 0x0093: 'Universal Electronics, Inc.',
- 0x0094: 'Airoha Technology Corp.',
- 0x0095: 'NEC Lighting, Ltd.',
- 0x0096: 'ODM Technology, Inc.',
- 0x0097: 'ConnecteDevice Ltd.',
- 0x0098: 'zer01.tv GmbH',
- 0x0099: 'i.Tech Dynamic Global Distribution Ltd.',
- 0x009a: 'Alpwise',
- 0x009b: 'Jiangsu Toppower Automotive Electronics Co., Ltd.',
- 0x009c: 'Colorfy, Inc.',
- 0x009d: 'Geoforce Inc.',
- 0x009e: 'Bose Corporation',
- 0x009f: 'Suunto Oy',
- 0x00a0: 'Kensington Computer Products Group',
- 0x00a1: 'SR-Medizinelektronik',
- 0x00a2: 'Vertu Corporation Limited',
- 0x00a3: 'Meta Watch Ltd.',
- 0x00a4: 'LINAK A/S',
- 0x00a5: 'OTL Dynamics LLC',
- 0x00a6: 'Panda Ocean Inc.',
- 0x00a7: 'Visteon Corporation',
- 0x00a8: 'ARP Devices Limited',
- 0x00a9: 'Magneti Marelli S.p.A',
- 0x00aa: 'CAEN RFID srl',
- 0x00ab: 'Ingenieur-Systemgruppe Zahn GmbH',
- 0x00ac: 'Green Throttle Games',
- 0x00ad: 'Peter Systemtechnik GmbH',
- 0x00ae: 'Omegawave Oy',
- 0x00af: 'Cinetix',
- 0x00b0: 'Passif Semiconductor Corp',
- 0x00b1: 'Saris Cycling Group, Inc',
- 0x00b2: 'Bekey A/S',
- 0x00b3: 'Clarinox Technologies Pty. Ltd.',
- 0x00b4: 'BDE Technology Co., Ltd.',
- 0x00b5: 'Swirl Networks',
- 0x00b6: 'Meso international',
- 0x00b7: 'TreLab Ltd',
- 0x00b8: 'Qualcomm Innovation Center, Inc. (QuIC)',
- 0x00b9: 'Johnson Controls, Inc.',
- 0x00ba: 'Starkey Laboratories Inc.',
- 0x00bb: 'S-Power Electronics Limited',
- 0x00bc: 'Ace Sensor Inc',
- 0x00bd: 'Aplix Corporation',
- 0x00be: 'AAMP of America',
- 0x00bf: 'Stalmart Technology Limited',
- 0x00c0: 'AMICCOM Electronics Corporation',
- 0x00c1: 'Shenzhen Excelsecu Data Technology Co.,Ltd',
- 0x00c2: 'Geneq Inc.',
- 0x00c3: 'adidas AG',
- 0x00c4: 'LG Electronics',
- 0x00c5: 'Onset Computer Corporation',
- 0x00c6: 'Selfly BV',
- 0x00C7: 'Quuppa Oy.',
- 0x00C8: 'GeLo Inc',
- 0x00C9: 'Evluma',
- 0x00CA: 'MC10',
- 0x00CB: 'Binauric SE',
- 0x00CC: 'Beats Electronics',
- 0x00CD: 'Microchip Technology Inc.',
- 0x00CE: 'Elgato Systems GmbH',
- 0x00CF: 'ARCHOS SA',
- 0x00D0: 'Dexcom, Inc.',
- 0x00D1: 'Polar Electro Europe B.V.',
- 0x00D2: 'Dialog Semiconductor B.V.',
- 0x00D3: 'Taixingbang Technology (HK) Co,. LTD.',
- 0x00D4: 'Kawantech',
- 0x00D5: 'Austco Communication Systems',
- 0x00D6: 'Timex Group USA, Inc.',
- 0x00D7: 'Qualcomm Technologies, Inc.',
- 0x00D8: 'Qualcomm Connected Experiences, Inc.',
- 0x00D9: 'Voyetra Turtle Beach',
- 0x00DA: 'txtr GmbH',
- 0x00DB: 'Biosentronics',
- 0x00DC: 'Procter & Gamble',
- 0x00DD: 'Hosiden Corporation',
- 0x00DE: 'Muzik LLC',
- 0x00DF: 'Misfit Wearables Corp',
- 0x00E0: 'Google',
- 0x00E1: 'Danlers Ltd',
- 0x00E2: 'Semilink Inc',
- 0x00E3: 'inMusic Brands, Inc',
- 0x00E4: 'L.S. Research Inc.',
- 0x00E5: 'Eden Software Consultants Ltd.',
- 0x00E6: 'Freshtemp',
- 0x00e7: 'KS Technologies',
- 0x00e8: 'ACTS Technologies',
- 0x00e9: 'Vtrack Systems',
- 0x00ea: 'Nielsen-Kellerman Company',
- 0x00eb: 'Server Technology, Inc.',
- 0x00ec: 'BioResearch Associates',
- 0x00ed: 'Jolly Logic, LLC',
- 0x00ee: 'Above Average Outcomes, Inc.',
- 0x00ef: 'Bitsplitters GmbH',
- 0x00f0: 'PayPal, Inc.',
- 0x00f1: 'Witron Technology Limited',
- 0x00f2: 'Aether Things Inc. (formerly Morse Project Inc.)',
- 0x00f3: 'Kent Displays Inc.',
- 0x00f4: 'Nautilus Inc.',
- 0x00f5: 'Smartifier Oy',
- 0x00f6: 'Elcometer Limited',
- 0x00f7: 'VSN Technologies Inc.',
- 0x00f8: 'AceUni Corp., Ltd.',
- 0x00f9: 'StickNFind',
- 0x00fa: 'Crystal Code AB',
- 0x00fb: 'KOUKAAM a.s.',
- 0x00fc: 'Delphi Corporation',
- 0x00fd: 'ValenceTech Limited',
- 0x00fe: 'Reserved',
- 0x00ff: 'Typo Products, LLC',
- 0x0100: 'TomTom International BV',
- 0x0101: 'Fugoo, Inc',
- 0x0102: 'Keiser Corporation',
- 0x0103: 'Bang & Olufsen A/S',
- 0x0104: 'PLUS Locations Systems Pty Ltd',
- 0x0105: 'Ubiquitous Computing Technology Corporation',
- 0x0106: 'Innovative Yachtter Solutions',
- 0x0107: 'William Demant Holding A/S',
- 0x0108: 'Chicony Electronics Co., Ltd.',
- 0x0109: 'Atus BV',
- 0x010a: 'Codegate Ltd.',
- 0x010b: 'ERi, Inc.',
- 0x010c: 'Transducers Direct, LLC',
- 0x010d: 'Fujitsu Ten Limited',
- 0x010e: 'Audi AG',
- 0x010f: 'HiSilicon Technologies Co., Ltd.',
- 0x0110: 'Nippon Seiki Co., Ltd.',
- 0x0111: 'Steelseries ApS',
- 0x0112: 'vyzybl Inc.',
- 0x0113: 'Openbrain Technologies, Co., Ltd.',
- 0x0114: 'Xensr',
- 0x0115: 'e.solutions',
- 0x0116: '1OAK Technologies',
- 0x0117: 'Wimoto Technologies Inc',
- 0x0118: 'Radius Networks, Inc.',
- 0x0119: 'Wize Technology Co., Ltd.',
- 0x011a: 'Qualcomm Labs, Inc.',
- 0x011b: 'Aruba Networks',
- 0x011c: 'Baidu',
- 0x011d: 'Arendi AG',
- 0x011e: 'Skoda Auto a.s.',
- 0x011f: 'Volkswagon AG',
- 0x0120: 'Porsche AG',
- 0x0121: 'Sino Wealth Electronic Ltd.',
- 0x0122: 'AirTurn, Inc.',
- 0x0123: 'Kinsa, Inc.',
- 0x0124: 'HID Global',
- 0x0125: 'SEAT es',
- 0x0126: 'Promethean Ltd.',
- 0x0127: 'Salutica Allied Solutions',
- 0x0128: 'GPSI Group Pty Ltd',
- 0x0129: 'Nimble Devices Oy',
- 0x012a: 'Changzhou Yongse Infotech Co., Ltd',
- 0x012b: 'SportIQ',
- 0x012c: 'TEMEC Instruments B.V.',
- 0x012d: 'Sony Corporation',
- 0x012e: 'ASSA ABLOY',
- 0x012f: 'Clarion Co., Ltd.',
- 0x0130: 'Warehouse Innovations',
- 0x0131: 'Cypress Semiconductor Corporation',
- 0x0132: 'MADS Inc',
- 0x0133: 'Blue Maestro Limited',
- 0x0134: 'Resolution Products, Inc.',
- 0x0135: 'Airewear LLC',
- 0x0136: 'Seed Labs, Inc. (formerly ETC sp. z.o.o.)',
- 0x0137: 'Prestigio Plaza Ltd.',
- 0x0138: 'NTEO Inc.',
- 0x0139: 'Focus Systems Corporation',
- 0x013a: 'Tencent Holdings Limited',
- 0x013b: 'Allegion',
- 0x013c: 'Murata Manufacuring Co., Ltd.',
- 0x013e: 'Nod, Inc.',
- 0x013f: 'B&B Manufacturing Company',
- 0x0140: 'Alpine Electronics (China) Co., Ltd',
- 0x0141: 'FedEx Services',
- 0x0142: 'Grape Systems Inc.',
- 0x0143: 'Bkon Connect',
- 0x0144: 'Lintech GmbH',
- 0x0145: 'Novatel Wireless',
- 0x0146: 'Ciright',
- 0x0147: 'Mighty Cast, Inc.',
- 0x0148: 'Ambimat Electronics',
- 0x0149: 'Perytons Ltd.',
- 0x014a: 'Tivoli Audio, LLC',
- 0x014b: 'Master Lock',
- 0x014c: 'Mesh-Net Ltd',
- 0x014d: 'Huizhou Desay SV Automotive CO., LTD.',
- 0x014e: 'Tangerine, Inc.',
- 0x014f: 'B&W Group Ltd.',
- 0x0150: 'Pioneer Corporation',
- 0x0151: 'OnBeep',
- 0x0152: 'Vernier Software & Technology',
- 0x0153: 'ROL Ergo',
- 0x0154: 'Pebble Technology',
- 0x0155: 'NETATMO',
- 0x0156: 'Accumulate AB',
- 0x0157: 'Anhui Huami Information Technology Co., Ltd.',
- 0x0158: 'Inmite s.r.o.',
- 0x0159: 'ChefSteps, Inc.',
- 0x015a: 'micas AG',
- 0x015b: 'Biomedical Research Ltd.',
- 0x015c: 'Pitius Tec S.L.',
- 0x015d: 'Estimote, Inc.',
- 0x015e: 'Unikey Technologies, Inc.',
- 0x015f: 'Timer Cap Co.',
- 0x0160: 'AwoX',
- 0x0161: 'yikes',
- 0x0162: 'MADSGlobal NZ Ltd.',
- 0x0163: 'PCH International',
- 0x0164: 'Qingdao Yeelink Information Technology Co., Ltd.',
- 0x0165: 'Milwaukee Tool (formerly Milwaukee Electric Tools)',
- 0x0166: 'MISHIK Pte Ltd',
- 0x0167: 'Bayer HealthCare',
- 0x0168: 'Spicebox LLC',
- 0x0169: 'emberlight',
- 0x016a: 'Cooper-Atkins Corporation',
- 0x016b: 'Qblinks',
- 0x016c: 'MYSPHERA',
- 0x016d: 'LifeScan Inc',
- 0x016e: 'Volantic AB',
- 0x016f: 'Podo Labs, Inc',
- 0x0170: 'Roche Diabetes Care AG',
- 0x0171: 'Amazon Fulfillment Service',
- 0x0172: 'Connovate Technology Private Limited',
- 0x0173: 'Kocomojo, LLC',
- 0x0174: 'Everykey LLC',
- 0x0175: 'Dynamic Controls',
- 0x0176: 'SentriLock',
- 0x0177: 'I-SYST inc.',
- 0x0178: 'CASIO COMPUTER CO., LTD.',
- 0x0179: 'LAPIS Semiconductor Co., Ltd.',
- 0x017a: 'Telemonitor, Inc.',
- 0x017b: 'taskit GmbH',
- 0x017c: 'Daimler AG',
- 0x017d: 'BatAndCat',
- 0x017e: 'BluDotz Ltd',
- 0x017f: 'XTel ApS',
- 0x0180: 'Gigaset Communications GmbH',
- 0x0181: 'Gecko Health Innovations, Inc.',
- 0x0182: 'HOP Ubiquitous',
- 0x0183: 'To Be Assigned',
- 0x0184: 'Nectar',
- 0x0185: 'bel’apps LLC',
- 0x0186: 'CORE Lighting Ltd',
- 0x0187: 'Seraphim Sense Ltd',
- 0x0188: 'Unico RBC',
- 0x0189: 'Physical Enterprises Inc.',
- 0x018a: 'Able Trend Technology Limited',
- 0x018b: 'Konica Minolta, Inc.',
- 0x018c: 'Wilo SE',
- 0x018d: 'Extron Design Services',
- 0x018e: 'Fitbit, Inc.',
- 0x018f: 'Fireflies Systems',
- 0x0190: 'Intelletto Technologies Inc.',
- 0x0191: 'FDK CORPORATION',
- 0x0192: 'Cloudleaf, Inc',
- 0x0193: 'Maveric Automation LLC',
- 0x0194: 'Acoustic Stream Corporation',
- 0x0195: 'Zuli',
- 0x0196: 'Paxton Access Ltd',
- 0x0197: 'WiSilica Inc',
- 0x0198: 'Vengit Limited',
- 0x0199: 'SALTO SYSTEMS S.L.',
- 0x019a: 'TRON Forum (formerly T-Engine Forum)',
- 0x019b: 'CUBETECH s.r.o.',
- 0x019c: 'Cokiya Incorporated',
- 0x019d: 'CVS Health',
- 0x019e: 'Ceruus',
- 0x019f: 'Strainstall Ltd',
- 0x01a0: 'Channel Enterprises (HK) Ltd.',
- 0x01a1: 'FIAMM',
- 0x01a2: 'GIGALANE.CO.,LTD',
- 0x01a3: 'EROAD',
- 0x01a4: 'Mine Safety Appliances',
- 0x01a5: 'Icon Health and Fitness',
- 0x01a6: 'Asandoo GmbH',
- 0x01a7: 'ENERGOUS CORPORATION',
- 0x01a8: 'Taobao',
- 0x01a9: 'Canon Inc.',
- 0x01aa: 'Geophysical Technology Inc.',
- 0x01ab: 'Facebook, Inc.',
- 0x01ac: 'Nipro Diagnostics, Inc.',
- 0x01ad: 'FlightSafety International',
- 0x01ae: 'Earlens Corporation',
- 0x01af: 'Sunrise Micro Devices, Inc.',
- 0x01b0: 'Star Micronics Co., Ltd.',
- 0x01b1: 'Netizens Sp. z o.o.',
- 0x01b2: 'Nymi Inc.',
- 0x01b3: 'Nytec, Inc.',
- 0x01b4: 'Trineo Sp. z o.o.',
- 0x01b5: 'Nest Labs Inc.',
- 0x01b6: 'LM Technologies Ltd',
- 0x01b7: 'General Electric Company',
- 0x01b8: 'i+D3 S.L.',
- 0x01b9: 'HANA Micron',
- 0x01ba: 'Stages Cycling LLC',
- 0x01bb: 'Cochlear Bone Anchored Solutions AB',
- 0x01bc: 'SenionLab AB',
- 0x01bd: 'Syszone Co., Ltd',
- 0x01be: 'Pulsate Mobile Ltd.',
- 0x01bf: 'Hong Kong HunterSun Electronic Limited',
- 0x01c0: 'pironex GmbH',
- 0x01c1: 'BRADATECH Corp.',
- 0x01c2: 'Transenergooil AG',
- 0x01c3: 'Bunch',
- 0x01c4: 'DME Microelectronics',
- 0x01c5: 'Bitcraze AB',
- 0x01c6: 'HASWARE Inc.',
- 0x01c7: 'Abiogenix Inc.',
- 0x01c8: 'Poly-Control ApS',
- 0x01c9: 'Avi-on',
- 0x01ca: 'Laerdal Medical AS',
- 0x01cb: 'Fetch My Pet',
- 0x01cc: 'Sam Labs Ltd.',
- 0x01cd: 'Chengdu Synwing Technology Ltd',
- 0x01ce: 'HOUWA SYSTEM DESIGN, k.k.',
- 0x01cf: 'BSH',
- 0x01d0: 'Primus Inter Pares Ltd',
- 0x01d1: 'August',
- 0x01d2: 'Gill Electronics',
- 0x01d3: 'Sky Wave Design',
- 0x01d4: 'Newlab S.r.l.',
- 0x01d5: 'ELAD srl',
- 0x01d6: 'G-wearables inc.',
- 0x01d7: 'Squadrone Systems Inc.',
- 0x01d8: 'Code Corporation',
- 0x01d9: 'Savant Systems LLC',
- 0x01da: 'Logitech International SA',
- 0x01db: 'Innblue Consulting',
- 0x01dc: 'iParking Ltd.',
- 0x01dd: 'Koninklijke Philips Electronics N.V.',
- 0x01de: 'Minelab Electronics Pty Limited',
- 0x01df: 'Bison Group Ltd.',
- 0x01e0: 'Widex A/S',
- 0x01e1: 'Jolla Ltd',
- 0x01e2: 'Lectronix, Inc.',
- 0x01e3: 'Caterpillar Inc',
- 0x01e4: 'Freedom Innovations',
- 0x01e5: 'Dynamic Devices Ltd',
- 0x01e6: 'Technology Solutions (UK) Ltd',
- 0x01e7: 'IPS Group Inc.',
- 0x01e8: 'STIR',
- 0x01e9: 'Sano, Inc',
- 0x01ea: 'Advanced Application Design, Inc.',
- 0x01eb: 'AutoMap LLC',
- 0x01ec: 'Spreadtrum Communications Shanghai Ltd',
- 0x01ed: 'CuteCircuit LTD',
- 0x01ee: 'Valeo Service',
- 0x01ef: 'Fullpower Technologies, Inc.',
- 0x01f0: 'KloudNation',
- 0x01f1: 'Zebra Technologies Corporation',
- 0x01f2: 'Itron, Inc.',
- 0x01f3: 'The University of Tokyo',
- 0x01f4: 'UTC Fire and Security',
- 0x01f5: 'Cool Webthings Limited',
- 0x01f6: 'DJO Global',
- 0x01f7: 'Gelliner Limited',
- 0x01f8: 'Anyka (Guangzhou) Microelectronics Technology Co, LTD',
- 0x01f9: 'Medtronic, Inc.',
- 0x01fa: 'Gozio, Inc.',
- 0x01fb: 'Form Lifting, LLC',
- 0x01fc: 'Wahoo Fitness, LLC',
- 0x01fd: 'Kontakt Micro-Location Sp. z o.o.',
- 0x01fe: 'Radio System Corporation',
- 0x01ff: 'Freescale Semiconductor, Inc.',
- 0x0200: 'Verifone Systems PTe Ltd. Taiwan Branch',
- 0x0201: 'AR Timing',
- 0x0202: 'Rigado LLC',
- 0x0203: 'Kemppi Oy',
- 0x0204: 'Tapcentive Inc.',
- 0x0205: 'Smartbotics Inc.',
- 0x0206: 'Otter Products, LLC',
- 0x0207: 'STEMP Inc.',
- 0x0208: 'LumiGeek LLC',
- 0x0209: 'InvisionHeart Inc.',
- 0x020A: 'Macnica Inc. ',
- 0x020b: 'Jaguar Land Rover Limited',
- 0x020c: 'CoroWare Technologies, Inc',
- 0x020d: 'Simplo Technology Co., LTD',
- 0x020e: 'Omron Healthcare Co., LTD',
- 0x020f: 'Comodule GMBH',
- 0x0210: 'ikeGPS',
- 0x0211: 'Telink Semiconductor Co. Ltd',
- 0x0212: 'Interplan Co., Ltd',
- 0x0213: 'Wyler AG',
- 0x0214: 'IK Multimedia Production srl',
- 0x0215: 'Lukoton Experience Oy',
- 0x0216: 'MTI Ltd',
- 0x0217: 'Tech4home, Lda',
- 0x0218: 'Hiotech AB',
- 0x0219: 'DOTT Limited',
- 0x021A: 'Blue Speck Labs, LLC',
- 0x021B: 'Cisco Systems, Inc',
- 0x021C: 'Mobicomm Inc',
- 0x021D: 'Edamic',
- 0x021E: 'Goodnet, Ltd',
- 0x021F: 'Luster Leaf Products Inc',
- 0x0220: 'Manus Machina BV',
- 0x0221: 'Mobiquity Networks Inc',
- 0x0222: 'Praxis Dynamics',
- 0x0223: 'Philip Morris Products S.A.',
- 0x0224: 'Comarch SA',
- 0x0225: 'Nestl Nespresso S.A.',
- 0x0226: 'Merlinia A/S',
- 0x0227: 'LifeBEAM Technologies',
- 0x0228: 'Twocanoes Labs, LLC',
- 0x0229: 'Muoverti Limited',
- 0x022A: 'Stamer Musikanlagen GMBH',
- 0x022B: 'Tesla Motors',
- 0x022C: 'Pharynks Corporation',
- 0x022D: 'Lupine',
- 0x022E: 'Siemens AG',
- 0x022F: 'Huami (Shanghai) Culture Communication CO., LTD',
- 0x0230: 'Foster Electric Company, Ltd',
- 0x0231: 'ETA SA',
- 0x0232: 'x-Senso Solutions Kft',
- 0x0233: 'Shenzhen SuLong Communication Ltd',
- 0x0234: 'FengFan (BeiJing) Technology Co, Ltd',
- 0x0235: 'Qrio Inc',
- 0x0236: 'Pitpatpet Ltd',
- 0x0237: 'MSHeli s.r.l.',
- 0x0238: 'Trakm8 Ltd',
- 0x0239: 'JIN CO, Ltd',
- 0x023A: 'Alatech Tehnology',
- 0x023B: 'Beijing CarePulse Electronic Technology Co, Ltd',
- 0x023C: 'Awarepoint',
- 0x023D: 'ViCentra B.V.',
- 0x023E: 'Raven Industries',
- 0x023F: 'WaveWare Technologies Inc.',
- 0x0240: 'Argenox Technologies',
- 0x0241: 'Bragi GmbH',
- 0x0242: '16Lab Inc',
- 0x0243: 'Masimo Corp',
- 0x0244: 'Iotera Inc',
- 0x0245: 'Endress+Hauser',
- 0x0246: 'ACKme Networks, Inc.',
- 0x0247: 'FiftyThree Inc.',
- 0x0248: 'Parker Hannifin Corp',
- 0x0249: 'Transcranial Ltd',
- 0x024A: 'Uwatec AG',
- 0x024B: 'Orlan LLC',
- 0x024C: 'Blue Clover Devices',
- 0x024D: 'M-Way Solutions GmbH',
- 0x024E: 'Microtronics Engineering GmbH',
- 0x024F: 'Schneider Schreibgerte GmbH',
- 0x0250: 'Sapphire Circuits LLC',
- 0x0251: 'Lumo Bodytech Inc.',
- 0x0252: 'UKC Technosolution',
- 0x0253: 'Xicato Inc.',
- 0x0254: 'Playbrush',
- 0x0255: 'Dai Nippon Printing Co., Ltd.',
- 0x0256: 'G24 Power Limited',
- 0x0257: 'AdBabble Local Commerce Inc.',
- 0x0258: 'Devialet SA',
- 0x0259: 'ALTYOR',
- 0x025A: 'University of Applied Sciences Valais/Haute Ecole Valaisanne',
- 0x025B: 'Five Interactive, LLC dba Zendo',
- 0x025C: 'NetEaseHangzhouNetwork co.Ltd.',
- 0x025D: 'Lexmark International Inc.',
- 0x025E: 'Fluke Corporation',
- 0x025F: 'Yardarm Technologies',
- 0x0260: 'SensaRx',
- 0x0261: 'SECVRE GmbH',
- 0x0262: 'Glacial Ridge Technologies',
- 0x0263: 'Identiv, Inc.',
- 0x0264: 'DDS, Inc.',
- 0x0265: 'SMK Corporation',
- 0x0266: 'Schawbel Technologies LLC',
- 0x0267: 'XMI Systems SA',
- 0x0268: 'Cerevo',
- 0x0269: 'Torrox GmbH & Co KG',
- 0x026A: 'Gemalto',
- 0x026B: 'DEKA Research & Development Corp.',
- 0x026C: 'Domster Tadeusz Szydlowski',
- 0x026D: 'Technogym SPA',
- 0x026E: 'FLEURBAEY BVBA',
- 0x026F: 'Aptcode Solutions',
- 0x0270: 'LSI ADL Technology',
- 0x0271: 'Animas Corp',
- 0x0272: 'Alps Electric Co., Ltd.',
- 0x0273: 'OCEASOFT',
- 0x0274: 'Motsai Research',
- 0x0275: 'Geotab',
- 0x0276: 'E.G.O. Elektro-Gertebau GmbH',
- 0x0277: 'bewhere inc',
- 0x0278: 'Johnson Outdoors Inc',
- 0x0279: 'steute Schaltgerate GmbH & Co. KG',
- 0x027A: 'Ekomini inc.',
- 0x027B: 'DEFA AS',
- 0x027C: 'Aseptika Ltd',
- 0x027D: 'HUAWEI Technologies Co., Ltd. ( )',
- 0x027E: 'HabitAware, LLC',
- 0x027F: 'ruwido austria gmbh',
- 0x0280: 'ITEC corporation',
- 0x0281: 'StoneL',
- 0x0282: 'Sonova AG',
- 0x0283: 'Maven Machines, Inc.',
- 0x0284: 'Synapse Electronics',
- 0x0285: 'Standard Innovation Inc.',
- 0x0286: 'RF Code, Inc.',
- 0x0287: 'Wally Ventures S.L.',
- 0x0288: 'Willowbank Electronics Ltd',
- 0x0289: 'SK Telecom',
- 0x028A: 'Jetro AS',
- 0x028B: 'Code Gears LTD',
- 0x028C: 'NANOLINK APS',
- 0x028D: 'IF, LLC',
- 0x028E: 'RF Digital Corp',
- 0x028F: 'Church & Dwight Co., Inc',
- 0x0290: 'Multibit Oy',
- 0x0291: 'CliniCloud Inc',
- 0x0292: 'SwiftSensors',
- 0x0293: 'Blue Bite',
- 0x0294: 'ELIAS GmbH',
- 0x0295: 'Sivantos GmbH',
- 0x0296: 'Petzl',
- 0x0297: 'storm power ltd',
- 0x0298: 'EISST Ltd',
- 0x0299: 'Inexess Technology Simma KG',
- 0x029A: 'Currant, Inc.',
- 0x029B: 'C2 Development, Inc.',
- 0x029C: 'Blue Sky Scientific, LLC',
- 0x029D: 'ALOTTAZS LABS, LLC',
- 0x029E: 'Kupson spol. s r.o.',
- 0x029F: 'Areus Engineering GmbH',
- 0x02A0: 'Impossible Camera GmbH',
- 0x02A1: 'InventureTrack Systems',
- 0x02A2: 'LockedUp',
- 0x02A3: 'Itude',
- 0x02A4: 'Pacific Lock Company',
- 0x02A5: 'Tendyron Corporation ( )',
- 0x02A6: 'Robert Bosch GmbH',
- 0x02A7: 'Illuxtron international B.V.',
- 0x02A8: 'miSport Ltd.',
- 0x02A9: 'Chargelib',
- 0x02AA: 'Doppler Lab',
- 0x02AB: 'BBPOS Limited',
- 0x02AC: 'RTB Elektronik GmbH & Co. KG',
- 0x02AD: 'Rx Networks, Inc.',
- 0x02AE: 'WeatherFlow, Inc.',
- 0x02AF: 'Technicolor USA Inc.',
- 0x02B0: 'Bestechnic(Shanghai),Ltd',
- 0x02B1: 'Raden Inc',
- 0x02B2: 'JouZen Oy',
- 0x02B3: 'CLABER S.P.A.',
- 0x02B4: 'Hyginex, Inc.',
- 0x02B5: 'HANSHIN ELECTRIC RAILWAY CO.,LTD.',
- 0x02B6: 'Schneider Electric',
- 0x02B7: 'Oort Technologies LLC',
- 0x02B8: 'Chrono Therapeutics',
- 0x02B9: 'Rinnai Corporation',
- 0x02BA: 'Swissprime Technologies AG',
- 0x02BB: 'Koha.,Co.Ltd',
- 0x02BC: 'Genevac Ltd',
- 0x02BD: 'Chemtronics',
- 0x02BE: 'Seguro Technology Sp. z o.o.',
- 0x02BF: 'Redbird Flight Simulations',
- 0x02C0: 'Dash Robotics',
- 0x02C1: 'LINE Corporation',
- 0x02C2: 'Guillemot Corporation',
- 0x02C3: 'Techtronic Power Tools Technology Limited',
- 0x02C4: 'Wilson Sporting Goods',
- 0x02C5: 'Lenovo (Singapore) Pte Ltd. ( )',
- 0x02C6: 'Ayatan Sensors',
- 0x02C7: 'Electronics Tomorrow Limited',
- 0x02C8: 'VASCO Data Security International, Inc.',
- 0x02C9: 'PayRange Inc.',
- 0x02CA: 'ABOV Semiconductor',
- 0x02CB: 'AINA-Wireless Inc.',
- 0x02CC: 'Eijkelkamp Soil & Water',
- 0x02CD: 'BMA ergonomics b.v.',
- 0x02CE: 'Teva Branded Pharmaceutical Products R&D, Inc.',
- 0x02CF: 'Anima',
- 0x02D0: '3M',
- 0x02D1: 'Empatica Srl',
- 0x02D2: 'Afero, Inc.',
- 0x02D3: 'Powercast Corporation',
- 0x02D4: 'Secuyou ApS',
- 0x02D5: 'OMRON Corporation',
- 0x02D6: 'Send Solutions',
- 0x02D7: 'NIPPON SYSTEMWARE CO.,LTD.',
- 0x02D8: 'Neosfar',
- 0x02D9: 'Fliegl Agrartechnik GmbH',
- 0x02DA: 'Gilvader',
- 0x02DB: 'Digi International Inc (R)',
- 0x02DC: 'DeWalch Technologies, Inc.',
- 0x02DD: 'Flint Rehabilitation Devices, LLC',
- 0x02DE: 'Samsung SDS Co., Ltd.',
- 0x02DF: 'Blur Product Development',
- 0x02E0: 'University of Michigan',
- 0x02E1: 'Victron Energy BV',
- 0x02E2: 'NTT docomo',
- 0x02E3: 'Carmanah Technologies Corp.',
- 0x02E4: 'Bytestorm Ltd.',
- 0x02E5: 'Espressif Incorporated ( () )',
- 0x02E6: 'Unwire',
- 0x02E7: 'Connected Yard, Inc.',
- 0x02E8: 'American Music Environments',
- 0x02E9: 'Sensogram Technologies, Inc.',
- 0x02EA: 'Fujitsu Limited',
- 0x02EB: 'Ardic Technology',
- 0x02EC: 'Delta Systems, Inc',
- 0x02ED: 'HTC Corporation',
- 0x02EE: 'Citizen Holdings Co., Ltd.',
- 0x02EF: 'SMART-INNOVATION.inc',
- 0x02F0: 'Blackrat Software',
- 0x02F1: 'The Idea Cave, LLC',
- 0x02F2: 'GoPro, Inc.',
- 0x02F3: 'AuthAir, Inc',
- 0x02F4: 'Vensi, Inc.',
- 0x02F5: 'Indagem Tech LLC',
- 0x02F6: 'Intemo Technologies',
- 0x02F7: 'DreamVisions co., Ltd.',
- 0x02F8: 'Runteq Oy Ltd',
- 0x02F9: 'IMAGINATION TECHNOLOGIES LTD',
- 0x02FA: 'CoSTAR TEchnologies',
- 0x02FB: 'Clarius Mobile Health Corp.',
- 0x02FC: 'Shanghai Frequen Microelectronics Co., Ltd.',
- 0x02FD: 'Uwanna, Inc.',
- 0x02FE: 'Lierda Science & Technology Group Co., Ltd.',
- 0x02FF: 'Silicon Laboratories',
- 0x0300: 'World Moto Inc.',
- 0x0301: 'Giatec Scientific Inc.',
- 0x0302: 'Loop Devices, Inc',
- 0x0303: 'IACA electronique',
- 0x0304: 'Martians Inc',
- 0x0305: 'Swipp ApS',
- 0x0306: 'Life Laboratory Inc.',
- 0x0307: 'FUJI INDUSTRIAL CO.,LTD.',
- 0x0308: 'Surefire, LLC',
- 0x0309: 'Dolby Labs',
- 0x030A: 'Ellisys',
- 0x030B: 'Magnitude Lighting Converters',
- 0x030C: 'Hilti AG',
- 0x030D: 'Devdata S.r.l.',
- 0x030E: 'Deviceworx',
- 0x030F: 'Shortcut Labs',
- 0x0310: 'SGL Italia S.r.l.',
- 0x0311: 'PEEQ DATA',
- 0x0312: 'Ducere Technologies Pvt Ltd',
- 0x0313: 'DiveNav, Inc.',
- 0x0314: 'RIIG AI Sp. z o.o.',
- 0x0315: 'Thermo Fisher Scientific',
- 0x0316: 'AG Measurematics Pvt. Ltd.',
- 0x0317: 'CHUO Electronics CO., LTD.',
- 0x0318: 'Aspenta International',
- 0x0319: 'Eugster Frismag AG',
- 0x031A: 'Amber wireless GmbH',
- 0x031B: 'HQ Inc',
- 0x031C: 'Lab Sensor Solutions',
- 0x031D: 'Enterlab ApS',
- 0x031E: 'Eyefi, Inc.',
- 0x031F: 'MetaSystem S.p.A.',
- 0x0320: 'SONO ELECTRONICS. CO., LTD',
- 0x0321: 'Jewelbots',
- 0x0322: 'Compumedics Limited',
- 0x0323: 'Rotor Bike Components',
- 0x0324: 'Astro, Inc.',
- 0x0325: 'Amotus Solutions',
- 0x0326: 'Healthwear Technologies (Changzhou)Ltd',
- 0x0327: 'Essex Electronics',
- 0x0328: 'Grundfos A/S',
- 0x0329: 'Eargo, Inc.',
- 0x032A: 'Electronic Design Lab',
- 0x032B: 'ESYLUX',
- 0x032C: 'NIPPON SMT.CO.,Ltd',
- 0x032D: 'BM innovations GmbH',
- 0x032E: 'indoormap',
- 0x032F: 'OttoQ Inc',
- 0x0330: 'North Pole Engineering',
- 0x0331: '3flares Technologies Inc.',
- 0x0332: 'Electrocompaniet A.S.',
- 0x0333: 'Mul-T-Lock',
- 0x0334: 'Corentium AS',
- 0x0335: 'Enlighted Inc',
- 0x0336: 'GISTIC',
- 0x0337: 'AJP2 Holdings, LLC',
- 0x0338: 'COBI GmbH',
- 0x0339: 'Blue Sky Scientific, LLC',
- 0x033A: 'Appception, Inc.',
- 0x033B: 'Courtney Thorne Limited',
- 0x033C: 'Virtuosys',
- 0x033D: 'TPV Technology Limited',
- 0x033E: 'Monitra SA',
- 0x033F: 'Automation Components, Inc.',
- 0x0340: 'Letsense s.r.l.',
- 0x0341: 'Etesian Technologies LLC',
- 0x0342: 'GERTEC BRASIL LTDA.',
- 0x0343: 'Drekker Development Pty. Ltd.',
- 0x0344: 'Whirl Inc',
- 0x0345: 'Locus Positioning',
- 0x0346: 'Acuity Brands Lighting, Inc',
- 0x0347: 'Prevent Biometrics',
- 0x0348: 'Arioneo',
- 0x0349: 'VersaMe',
- 0x034A: 'Vaddio',
- 0x034B: 'Libratone A/S',
- 0x034C: 'HM Electronics, Inc.',
- 0x034D: 'TASER International, Inc.',
- 0x034E: 'SafeTrust Inc.',
- 0x034F: 'Heartland Payment Systems',
- 0x0350: 'Bitstrata Systems Inc.',
- 0x0351: 'Pieps GmbH',
- 0x0352: 'iRiding(Xiamen)Technology Co.,Ltd.',
- 0x0353: 'Alpha Audiotronics, Inc.',
- 0x0354: 'TOPPAN FORMS CO.,LTD.',
- 0x0355: 'Sigma Designs, Inc.',
- 0x0356: 'Spectrum Brands, Inc.',
- 0x0357: 'Polymap Wireless',
- 0x0358: 'MagniWare Ltd.',
- 0x0359: 'Novotec Medical GmbH',
- 0x035A: 'Medicom Innovation Partner a/s',
- 0x035B: 'Matrix Inc.',
- 0x035C: 'Eaton Corporation',
- 0x035D: 'KYS',
- 0x035E: 'Naya Health, Inc.',
- 0x035F: 'Acromag',
- 0x0360: 'Insulet Corporation',
- 0x0361: 'Wellinks Inc.',
- 0x0362: 'ON Semiconductor',
- 0x0363: 'FREELAP SA',
- 0x0364: 'Favero Electronics Srl',
- 0x0365: 'BioMech Sensor LLC',
- 0x0366: 'BOLTT Sports technologies Private limited',
- 0x0367: 'Saphe International',
- 0x0368: 'Metormote AB',
- 0x0369: 'littleBits',
- 0x036A: 'SetPoint Medical',
- 0x036B: 'BRControls Products BV',
- 0x036C: 'Zipcar',
- 0x036D: 'AirBolt Pty Ltd',
- 0x036E: 'KeepTruckin Inc',
- 0x036F: 'Motiv, Inc.',
- 0x0370: 'Wazombi Labs O',
- 0x0371: 'ORBCOMM',
- 0x0372: 'Nixie Labs, Inc.',
- 0x0373: 'AppNearMe Ltd',
- 0x0374: 'Holman Industries',
- 0x0375: 'Expain AS',
- 0x0376: 'Electronic Temperature Instruments Ltd',
- 0x0377: 'Plejd AB',
- 0x0378: 'Propeller Health',
- 0x0379: 'Shenzhen iMCO Electronic Technology Co.,Ltd',
- 0x037A: 'Algoria',
- 0x037B: 'Apption Labs Inc.',
- 0x037C: 'Cronologics Corporation',
- 0x037D: 'MICRODIA Ltd.',
- 0x037E: 'lulabytes S.L.',
- 0x037F: 'Nestec S.A.',
- 0x0380: 'LLC MEGA - F service',
- 0x0381: 'Sharp Corporation',
- 0x0382: 'Precision Outcomes Ltd',
- 0x0383: 'Kronos Incorporated',
- 0x0384: 'OCOSMOS Co., Ltd.',
- 0x0385: 'Embedded Electronic Solutions Ltd. dba e2Solutions',
- 0x0386: 'Aterica Inc.',
- 0x0387: 'BluStor PMC, Inc.',
- 0x0388: 'Kapsch TrafficCom AB',
- 0x0389: 'ActiveBlu Corporation',
- 0x038A: 'Kohler Mira Limited',
- 0x038B: 'Noke',
- 0x038C: 'Appion Inc.',
- 0x038D: 'Resmed Ltd',
- 0x038E: 'Crownstone B.V.',
- 0x038F: 'Xiaomi Inc.',
- 0x0390: 'INFOTECH s.r.o.',
- 0x0391: 'Thingsquare AB',
- 0x0392: 'T&D',
- 0x0393: 'LAVAZZA S.p.A.',
- 0x0394: 'Netclearance Systems, Inc.',
- 0x0395: 'SDATAWAY',
- 0x0396: 'BLOKS GmbH',
- 0x0397: 'LEGO System A/S',
- 0x0398: 'Thetatronics Ltd',
- 0x0399: 'Nikon Corporation',
- 0x039A: 'NeST',
- 0x039B: 'South Silicon Valley Microelectronics',
- 0x039C: 'ALE International',
- 0x039D: 'CareView Communications, Inc.',
- 0x039E: 'SchoolBoard Limited',
- 0x039F: 'Molex Corporation',
- 0x03A0: 'IVT Wireless Limited',
- 0x03A1: 'Alpine Labs LLC',
- 0x03A2: 'Candura Instruments',
- 0x03A3: 'SmartMovt Technology Co., Ltd',
- 0x03A4: 'Token Zero Ltd',
- 0x03A5: 'ACE CAD Enterprise Co., Ltd. (ACECAD)',
- 0x03A6: 'Medela, Inc',
- 0x03A7: 'AeroScout',
- 0x03A8: 'Esrille Inc.',
- 0x03A9: 'THINKERLY SRL',
- 0x03AA: 'Exon Sp. z o.o.',
- 0x03AB: 'Meizu Technology Co., Ltd.',
- 0x03AC: 'Smablo LTD',
- 0x03AD: 'XiQ',
- 0x03AE: 'Allswell Inc.',
- 0x03AF: 'Comm-N-Sense Corp DBA Verigo',
- 0x03B0: 'VIBRADORM GmbH',
- 0x03B1: 'Otodata Wireless Network Inc.',
- 0x03B2: 'Propagation Systems Limited',
- 0x03B3: 'Midwest Instruments & Controls',
- 0x03B4: 'Alpha Nodus, inc.',
- 0x03B5: 'petPOMM, Inc',
- 0x03B6: 'Mattel',
- 0x03B7: 'Airbly Inc.',
- 0x03B8: 'A-Safe Limited',
- 0x03B9: 'FREDERIQUE CONSTANT SA',
- 0x03BA: 'Maxscend Microelectronics Company Limited',
- 0x03BB: 'Abbott Diabetes Care',
- 0x03BC: 'ASB Bank Ltd',
- 0x03BD: 'amadas',
- 0x03BE: 'Applied Science, Inc.',
- 0x03BF: 'iLumi Solutions Inc.',
- 0x03C0: 'Arch Systems Inc.',
- 0x03C1: 'Ember Technologies, Inc.',
- 0x03C2: 'Snapchat Inc',
- 0x03C3: 'Casambi Technologies Oy',
- 0x03C4: 'Pico Technology Inc.',
- 0x03C5: 'St. Jude Medical, Inc.',
- 0x03C6: 'Intricon',
- 0x03C7: 'Structural Health Systems, Inc.',
- 0x03C8: 'Avvel International',
- 0x03C9: 'Gallagher Group',
- 0x03CA: 'In2things Automation Pvt. Ltd.',
- 0x03CB: 'SYSDEV Srl',
- 0x03CC: 'Vonkil Technologies Ltd',
- 0x03CD: 'Wynd Technologies, Inc.',
- 0x03CE: 'CONTRINEX S.A.',
- 0x03CF: 'MIRA, Inc.',
- 0x03D0: 'Watteam Ltd',
- 0x03D1: 'Density Inc.',
- 0x03D2: 'IOT Pot India Private Limited',
- 0x03D3: 'Sigma Connectivity AB',
- 0x03D4: 'PEG PEREGO SPA',
- 0x03D5: 'Wyzelink Systems Inc.',
- 0x03D6: 'Yota Devices LTD',
- 0x03D7: 'FINSECUR',
- 0x03D8: 'Zen-Me Labs Ltd',
- 0x03D9: '3IWare Co., Ltd.',
- 0x03DA: 'EnOcean GmbH',
- 0x03DB: 'Instabeat, Inc',
- 0x03DC: 'Nima Labs',
- 0x03DD: 'Andreas Stihl AG & Co. KG',
- 0x03DE: 'Nathan Rhoades LLC',
- 0x03DF: 'Grob Technologies, LLC',
- 0x03E0: 'Actions (Zhuhai) Technology Co., Limited',
- 0x03E1: 'SPD Development Company Ltd',
- 0x03E2: 'Sensoan Oy',
- 0x03E3: 'Qualcomm Life Inc',
- 0x03E4: 'Chip-ing AG',
- 0x03E5: 'ffly4u',
- 0x03E6: 'IoT Instruments Oy',
- 0x03E7: 'TRUE Fitness Technology',
- 0x03E8: 'Reiner Kartengeraete GmbH & Co. KG.',
- 0x03E9: 'SHENZHEN LEMONJOY TECHNOLOGY CO., LTD.',
- 0x03EA: 'Hello Inc.',
- 0x03EB: 'Evollve Inc.',
- 0x03EC: 'Jigowatts Inc.',
- 0x03ED: 'BASIC MICRO.COM,INC.',
- 0x03EE: 'CUBE TECHNOLOGIES',
- 0x03EF: 'foolography GmbH',
- 0x03F0: 'CLINK',
- 0x03F1: 'Hestan Smart Cooking Inc.',
- 0x03F2: 'WindowMaster A/S',
- 0x03F3: 'Flowscape AB',
- 0x03F4: 'PAL Technologies Ltd',
- 0x03F5: 'WHERE, Inc.',
- 0x03F6: 'Iton Technology Corp.',
- 0x03F7: 'Owl Labs Inc.',
- 0x03F8: 'Rockford Corp.',
- 0x03F9: 'Becon Technologies Co.,Ltd.',
- 0x03FA: 'Vyassoft Technologies Inc',
- 0x03FB: 'Nox Medical',
- 0x03FC: 'Kimberly-Clark',
- 0x03FD: 'Trimble Navigation Ltd.',
- 0x03FE: 'Littelfuse',
- 0x03FF: 'Withings',
- 0x0400: 'i-developer IT Beratung UG',
- 0x0402: 'Sears Holdings Corporation',
- 0x0403: 'Gantner Electronic GmbH',
- 0x0404: 'Authomate Inc',
- 0x0405: 'Vertex International, Inc.',
- 0x0406: 'Airtago',
- 0x0407: 'Swiss Audio SA',
- 0x0408: 'ToGetHome Inc.',
- 0x0409: 'AXIS',
- 0x040A: 'Openmatics',
- 0x040B: 'Jana Care Inc.',
- 0x040C: 'Senix Corporation',
- 0x040D: 'NorthStar Battery Company, LLC',
- 0x040E: 'SKF (U.K.) Limited',
- 0x040F: 'CO-AX Technology, Inc.',
- 0x0410: 'Fender Musical Instruments',
- 0x0411: 'Luidia Inc',
- 0x0412: 'SEFAM',
- 0x0413: 'Wireless Cables Inc',
- 0x0414: 'Lightning Protection International Pty Ltd',
- 0x0415: 'Uber Technologies Inc',
- 0x0416: 'SODA GmbH',
- 0x0417: 'Fatigue Science',
- 0x0418: 'Alpine Electronics Inc.',
- 0x0419: 'Novalogy LTD',
- 0x041A: 'Friday Labs Limited',
- 0x041B: 'OrthoAccel Technologies',
- 0x041C: 'WaterGuru, Inc.',
- 0x041D: 'Benning Elektrotechnik und Elektronik GmbH & Co. KG',
- 0x041E: 'Dell Computer Corporation',
- 0x041F: 'Kopin Corporation',
- 0x0420: 'TecBakery GmbH',
- 0x0421: 'Backbone Labs, Inc.',
- 0x0422: 'DELSEY SA',
- 0x0423: 'Chargifi Limited',
- 0x0424: 'Trainesense Ltd.',
- 0x0425: 'Unify Software and Solutions GmbH & Co. KG',
- 0x0426: 'Husqvarna AB',
- 0x0427: 'Focus fleet and fuel management inc',
- 0x0428: 'SmallLoop, LLC',
- 0x0429: 'Prolon Inc.',
- 0x042A: 'BD Medical',
- 0x042B: 'iMicroMed Incorporated',
- 0x042C: 'Ticto N.V.',
- 0x042D: 'Meshtech AS',
- 0x042E: 'MemCachier Inc.',
- 0x042F: 'Danfoss A/S',
- 0x0430: 'SnapStyk Inc.',
- 0x0431: 'Amyway Corporation',
- 0x0432: 'Silk Labs, Inc.',
- 0x0433: 'Pillsy Inc.',
- 0x0434: 'Hatch Baby, Inc.',
- 0x0435: 'Blocks Wearables Ltd.',
- 0x0436: 'Drayson Technologies (Europe) Limited',
- 0x0437: 'eBest IOT Inc.',
- 0x0438: 'Helvar Ltd',
- 0x0439: 'Radiance Technologies',
- 0x043A: 'Nuheara Limited',
- 0x043B: 'Appside co., ltd.',
- 0x043C: 'DeLaval',
- 0x043D: 'Coiler Corporation',
- 0x043E: 'Thermomedics, Inc.',
- 0x043F: 'Tentacle Sync GmbH',
- 0x0440: 'Valencell, Inc.',
- 0x0441: 'iProtoXi Oy',
- 0x0442: 'SECOM CO., LTD.',
- 0x0443: 'Tucker International LLC',
- 0x0444: 'Metanate Limited',
- 0x0445: 'Kobian Canada Inc.',
- 0x0446: 'NETGEAR, Inc.',
- 0x0447: 'Fabtronics Australia Pty Ltd',
- 0x0448: 'Grand Centrix GmbH',
- 0x0449: '1UP USA.com llc',
- 0x044A: 'SHIMANO INC.',
- 0x044B: 'Nain Inc.',
- 0x044C: 'LifeStyle Lock, LLC',
- 0x044D: 'VEGA Grieshaber KG',
- 0x044E: 'Xtrava Inc.',
- 0x044F: 'TTS Tooltechnic Systems AG & Co. KG',
- 0x0450: 'Teenage Engineering AB',
- 0x0451: 'Tunstall Nordic AB',
- 0x0452: 'Svep Design Center AB',
- 0x0453: 'GreenPeak Technologies BV',
- 0x0454: 'Sphinx Electronics GmbH & Co KG',
- 0x0455: 'Atomation',
- 0x0456: 'Nemik Consulting Inc',
- 0x0457: 'RF INNOVATION',
- 0x0458: 'Mini Solution Co., Ltd.',
- 0x0459: 'Lumenetix, Inc',
- 0x045A: '2048450 Ontario Inc',
- 0x045B: 'SPACEEK LTD',
- 0x045C: 'Delta T Corporation',
- 0x045D: 'Boston Scientific Corporation',
- 0x045E: 'Nuviz, Inc.',
- 0x045F: 'Real Time Automation, Inc.',
- 0x0460: 'Kolibree',
- 0x0461: 'vhf elektronik GmbH',
- 0x0462: 'Bonsai Systems GmbH',
- 0x0463: 'Fathom Systems Inc.',
- 0x0464: 'Bellman & Symfon',
- 0x0465: 'International Forte Group LLC',
- 0x0466: 'CycleLabs Solutions inc.',
- 0x0467: 'Codenex Oy',
- 0x0468: 'Kynesim Ltd',
- 0x0469: 'Palago AB',
- 0x046A: 'INSIGMA INC.',
- 0x046B: 'PMD Solutions',
- 0x046C: 'Qingdao Realtime Technology Co., Ltd.',
- 0x046D: 'BEGA Gantenbrink-Leuchten KG',
- 0x046E: 'Pambor Ltd.',
- 0xFFFF: 'SPECIAL USE/DEFAULT'
-};
-
-
-/***/ }),
-
-/***/ 93739:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// cpu.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 4. CPU
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const fs = __nccwpck_require__(79896);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-let _cpu_speed = 0;
-let _current_cpu = {
- user: 0,
- nice: 0,
- system: 0,
- idle: 0,
- irq: 0,
- steal: 0,
- guest: 0,
- load: 0,
- tick: 0,
- ms: 0,
- currentLoad: 0,
- currentLoadUser: 0,
- currentLoadSystem: 0,
- currentLoadNice: 0,
- currentLoadIdle: 0,
- currentLoadIrq: 0,
- currentLoadSteal: 0,
- currentLoadGuest: 0,
- rawCurrentLoad: 0,
- rawCurrentLoadUser: 0,
- rawCurrentLoadSystem: 0,
- rawCurrentLoadNice: 0,
- rawCurrentLoadIdle: 0,
- rawCurrentLoadIrq: 0,
- rawCurrentLoadSteal: 0,
- rawCurrentLoadGuest: 0
-};
-let _cpus = [];
-let _corecount = 0;
-
-const AMDBaseFrequencies = {
- '8346': '1.8',
- '8347': '1.9',
- '8350': '2.0',
- '8354': '2.2',
- '8356|SE': '2.4',
- '8356': '2.3',
- '8360': '2.5',
- '2372': '2.1',
- '2373': '2.1',
- '2374': '2.2',
- '2376': '2.3',
- '2377': '2.3',
- '2378': '2.4',
- '2379': '2.4',
- '2380': '2.5',
- '2381': '2.5',
- '2382': '2.6',
- '2384': '2.7',
- '2386': '2.8',
- '2387': '2.8',
- '2389': '2.9',
- '2393': '3.1',
- '8374': '2.2',
- '8376': '2.3',
- '8378': '2.4',
- '8379': '2.4',
- '8380': '2.5',
- '8381': '2.5',
- '8382': '2.6',
- '8384': '2.7',
- '8386': '2.8',
- '8387': '2.8',
- '8389': '2.9',
- '8393': '3.1',
- '2419EE': '1.8',
- '2423HE': '2.0',
- '2425HE': '2.1',
- '2427': '2.2',
- '2431': '2.4',
- '2435': '2.6',
- '2439SE': '2.8',
- '8425HE': '2.1',
- '8431': '2.4',
- '8435': '2.6',
- '8439SE': '2.8',
- '4122': '2.2',
- '4130': '2.6',
- '4162EE': '1.7',
- '4164EE': '1.8',
- '4170HE': '2.1',
- '4174HE': '2.3',
- '4176HE': '2.4',
- '4180': '2.6',
- '4184': '2.8',
- '6124HE': '1.8',
- '6128HE': '2.0',
- '6132HE': '2.2',
- '6128': '2.0',
- '6134': '2.3',
- '6136': '2.4',
- '6140': '2.6',
- '6164HE': '1.7',
- '6166HE': '1.8',
- '6168': '1.9',
- '6172': '2.1',
- '6174': '2.2',
- '6176': '2.3',
- '6176SE': '2.3',
- '6180SE': '2.5',
- '3250': '2.5',
- '3260': '2.7',
- '3280': '2.4',
- '4226': '2.7',
- '4228': '2.8',
- '4230': '2.9',
- '4234': '3.1',
- '4238': '3.3',
- '4240': '3.4',
- '4256': '1.6',
- '4274': '2.5',
- '4276': '2.6',
- '4280': '2.8',
- '4284': '3.0',
- '6204': '3.3',
- '6212': '2.6',
- '6220': '3.0',
- '6234': '2.4',
- '6238': '2.6',
- '6262HE': '1.6',
- '6272': '2.1',
- '6274': '2.2',
- '6276': '2.3',
- '6278': '2.4',
- '6282SE': '2.6',
- '6284SE': '2.7',
- '6308': '3.5',
- '6320': '2.8',
- '6328': '3.2',
- '6338P': '2.3',
- '6344': '2.6',
- '6348': '2.8',
- '6366': '1.8',
- '6370P': '2.0',
- '6376': '2.3',
- '6378': '2.4',
- '6380': '2.5',
- '6386': '2.8',
- 'FX|4100': '3.6',
- 'FX|4120': '3.9',
- 'FX|4130': '3.8',
- 'FX|4150': '3.8',
- 'FX|4170': '4.2',
- 'FX|6100': '3.3',
- 'FX|6120': '3.6',
- 'FX|6130': '3.6',
- 'FX|6200': '3.8',
- 'FX|8100': '2.8',
- 'FX|8120': '3.1',
- 'FX|8140': '3.2',
- 'FX|8150': '3.6',
- 'FX|8170': '3.9',
- 'FX|4300': '3.8',
- 'FX|4320': '4.0',
- 'FX|4350': '4.2',
- 'FX|6300': '3.5',
- 'FX|6350': '3.9',
- 'FX|8300': '3.3',
- 'FX|8310': '3.4',
- 'FX|8320': '3.5',
- 'FX|8350': '4.0',
- 'FX|8370': '4.0',
- 'FX|9370': '4.4',
- 'FX|9590': '4.7',
- 'FX|8320E': '3.2',
- 'FX|8370E': '3.3',
-
- // ZEN Desktop CPUs
- '1200': '3.1',
- 'Pro 1200': '3.1',
- '1300X': '3.5',
- 'Pro 1300': '3.5',
- '1400': '3.2',
- '1500X': '3.5',
- 'Pro 1500': '3.5',
- '1600': '3.2',
- '1600X': '3.6',
- 'Pro 1600': '3.2',
- '1700': '3.0',
- 'Pro 1700': '3.0',
- '1700X': '3.4',
- 'Pro 1700X': '3.4',
- '1800X': '3.6',
- '1900X': '3.8',
- '1920': '3.2',
- '1920X': '3.5',
- '1950X': '3.4',
-
- // ZEN Desktop APUs
- '200GE': '3.2',
- 'Pro 200GE': '3.2',
- '220GE': '3.4',
- '240GE': '3.5',
- '3000G': '3.5',
- '300GE': '3.4',
- '3050GE': '3.4',
- '2200G': '3.5',
- 'Pro 2200G': '3.5',
- '2200GE': '3.2',
- 'Pro 2200GE': '3.2',
- '2400G': '3.6',
- 'Pro 2400G': '3.6',
- '2400GE': '3.2',
- 'Pro 2400GE': '3.2',
-
- // ZEN Mobile APUs
- 'Pro 200U': '2.3',
- '300U': '2.4',
- '2200U': '2.5',
- '3200U': '2.6',
- '2300U': '2.0',
- 'Pro 2300U': '2.0',
- '2500U': '2.0',
- 'Pro 2500U': '2.2',
- '2600H': '3.2',
- '2700U': '2.0',
- 'Pro 2700U': '2.2',
- '2800H': '3.3',
-
- // ZEN Server Processors
- '7351': '2.4',
- '7351P': '2.4',
- '7401': '2.0',
- '7401P': '2.0',
- '7551P': '2.0',
- '7551': '2.0',
- '7251': '2.1',
- '7261': '2.5',
- '7281': '2.1',
- '7301': '2.2',
- '7371': '3.1',
- '7451': '2.3',
- '7501': '2.0',
- '7571': '2.2',
- '7601': '2.2',
-
- // ZEN Embedded Processors
- 'V1500B': '2.2',
- 'V1780B': '3.35',
- 'V1202B': '2.3',
- 'V1404I': '2.0',
- 'V1605B': '2.0',
- 'V1756B': '3.25',
- 'V1807B': '3.35',
-
- '3101': '2.1',
- '3151': '2.7',
- '3201': '1.5',
- '3251': '2.5',
- '3255': '2.5',
- '3301': '2.0',
- '3351': '1.9',
- '3401': '1.85',
- '3451': '2.15',
-
- // ZEN+ Desktop
- '1200|AF': '3.1',
- '2300X': '3.5',
- '2500X': '3.6',
- '2600': '3.4',
- '2600E': '3.1',
- '1600|AF': '3.2',
- '2600X': '3.6',
- '2700': '3.2',
- '2700E': '2.8',
- 'Pro 2700': '3.2',
- '2700X': '3.7',
- 'Pro 2700X': '3.6',
- '2920X': '3.5',
- '2950X': '3.5',
- '2970WX': '3.0',
- '2990WX': '3.0',
-
- // ZEN+ Desktop APU
- 'Pro 300GE': '3.4',
- 'Pro 3125GE': '3.4',
- '3150G': '3.5',
- 'Pro 3150G': '3.5',
- '3150GE': '3.3',
- 'Pro 3150GE': '3.3',
- '3200G': '3.6',
- 'Pro 3200G': '3.6',
- '3200GE': '3.3',
- 'Pro 3200GE': '3.3',
- '3350G': '3.6',
- 'Pro 3350G': '3.6',
- '3350GE': '3.3',
- 'Pro 3350GE': '3.3',
- '3400G': '3.7',
- 'Pro 3400G': '3.7',
- '3400GE': '3.3',
- 'Pro 3400GE': '3.3',
-
- // ZEN+ Mobile
- '3300U': '2.1',
- 'PRO 3300U': '2.1',
- '3450U': '2.1',
- '3500U': '2.1',
- 'PRO 3500U': '2.1',
- '3500C': '2.1',
- '3550H': '2.1',
- '3580U': '2.1',
- '3700U': '2.3',
- 'PRO 3700U': '2.3',
- '3700C': '2.3',
- '3750H': '2.3',
- '3780U': '2.3',
-
- // ZEN2 Desktop CPUS
- '3100': '3.6',
- '3300X': '3.8',
- '3500': '3.6',
- '3500X': '3.6',
- '3600': '3.6',
- 'Pro 3600': '3.6',
- '3600X': '3.8',
- '3600XT': '3.8',
- 'Pro 3700': '3.6',
- '3700X': '3.6',
- '3800X': '3.9',
- '3800XT': '3.9',
- '3900': '3.1',
- 'Pro 3900': '3.1',
- '3900X': '3.8',
- '3900XT': '3.8',
- '3950X': '3.5',
- '3960X': '3.8',
- '3970X': '3.7',
- '3990X': '2.9',
- '3945WX': '4.0',
- '3955WX': '3.9',
- '3975WX': '3.5',
- '3995WX': '2.7',
-
- // ZEN2 Desktop APUs
- '4300GE': '3.5',
- 'Pro 4300GE': '3.5',
- '4300G': '3.8',
- 'Pro 4300G': '3.8',
- '4600GE': '3.3',
- 'Pro 4650GE': '3.3',
- '4600G': '3.7',
- 'Pro 4650G': '3.7',
- '4700GE': '3.1',
- 'Pro 4750GE': '3.1',
- '4700G': '3.6',
- 'Pro 4750G': '3.6',
- '4300U': '2.7',
- '4450U': '2.5',
- 'Pro 4450U': '2.5',
- '4500U': '2.3',
- '4600U': '2.1',
- 'PRO 4650U': '2.1',
- '4680U': '2.1',
- '4600HS': '3.0',
- '4600H': '3.0',
- '4700U': '2.0',
- 'PRO 4750U': '1.7',
- '4800U': '1.8',
- '4800HS': '2.9',
- '4800H': '2.9',
- '4900HS': '3.0',
- '4900H': '3.3',
- '5300U': '2.6',
- '5500U': '2.1',
- '5700U': '1.8',
-
- // ZEN2 - EPYC
- '7232P': '3.1',
- '7302P': '3.0',
- '7402P': '2.8',
- '7502P': '2.5',
- '7702P': '2.0',
- '7252': '3.1',
- '7262': '3.2',
- '7272': '2.9',
- '7282': '2.8',
- '7302': '3.0',
- '7352': '2.3',
- '7402': '2.8',
- '7452': '2.35',
- '7502': '2.5',
- '7532': '2.4',
- '7542': '2.9',
- '7552': '2.2',
- '7642': '2.3',
- '7662': '2.0',
- '7702': '2.0',
- '7742': '2.25',
- '7H12': '2.6',
- '7F32': '3.7',
- '7F52': '3.5',
- '7F72': '3.2',
-
- // Epyc (Milan)
-
- '7773X': '2.2',
- '7763': '2.45',
- '7713': '2.0',
- '7713P': '2.0',
- '7663': '2.0',
- '7643': '2.3',
- '7573X': '2.8',
- '75F3': '2.95',
- '7543': '2.8',
- '7543P': '2.8',
- '7513': '2.6',
- '7473X': '2.8',
- '7453': '2.75',
- '74F3': '3.2',
- '7443': '2.85',
- '7443P': '2.85',
- '7413': '2.65',
- '7373X': '3.05',
- '73F3': '3.5',
- '7343': '3.2',
- '7313': '3.0',
- '7313P': '3.0',
- '72F3': '3.7',
-
- // ZEN3
- '5600X': '3.7',
- '5800X': '3.8',
- '5900X': '3.7',
- '5950X': '3.4',
- '5945WX': '4.1',
- '5955WX': '4.0',
- '5965WX': '3.8',
- '5975WX': '3.6',
- '5995WX': '2.7',
-
- '7960X': '4.2',
- '7970X': '4.0',
- '7980X': '3.2',
-
- '7965WX': '4.2',
- '7975WX': '4.0',
- '7985WX': '3.2',
- '7995WX': '2.5',
-
- // ZEN4
- '9754': '2.25',
- '9754S': '2.25',
- '9734': '2.2',
- '9684X': '2.55',
- '9384X': '3.1',
- '9184X': '3.55',
- '9654P': '2.4',
- '9654': '2.4',
- '9634': '2.25',
- '9554P': '3.1',
- '9554': '3.1',
- '9534': '2.45',
- '9474F': '3.6',
- '9454P': '2.75',
- '9454': '2.75',
- '9374F': '3.85',
- '9354P': '3.25',
- '9354': '3.25',
- '9334': '2.7',
- '9274F': '4.05',
- '9254': '2.9',
- '9224': '2.5',
- '9174F': '4.1',
- '9124': '3.0'
-};
-
-const socketTypes = {
- 1: 'Other',
- 2: 'Unknown',
- 3: 'Daughter Board',
- 4: 'ZIF Socket',
- 5: 'Replacement/Piggy Back',
- 6: 'None',
- 7: 'LIF Socket',
- 8: 'Slot 1',
- 9: 'Slot 2',
- 10: '370 Pin Socket',
- 11: 'Slot A',
- 12: 'Slot M',
- 13: '423',
- 14: 'A (Socket 462)',
- 15: '478',
- 16: '754',
- 17: '940',
- 18: '939',
- 19: 'mPGA604',
- 20: 'LGA771',
- 21: 'LGA775',
- 22: 'S1',
- 23: 'AM2',
- 24: 'F (1207)',
- 25: 'LGA1366',
- 26: 'G34',
- 27: 'AM3',
- 28: 'C32',
- 29: 'LGA1156',
- 30: 'LGA1567',
- 31: 'PGA988A',
- 32: 'BGA1288',
- 33: 'rPGA988B',
- 34: 'BGA1023',
- 35: 'BGA1224',
- 36: 'LGA1155',
- 37: 'LGA1356',
- 38: 'LGA2011',
- 39: 'FS1',
- 40: 'FS2',
- 41: 'FM1',
- 42: 'FM2',
- 43: 'LGA2011-3',
- 44: 'LGA1356-3',
- 45: 'LGA1150',
- 46: 'BGA1168',
- 47: 'BGA1234',
- 48: 'BGA1364',
- 49: 'AM4',
- 50: 'LGA1151',
- 51: 'BGA1356',
- 52: 'BGA1440',
- 53: 'BGA1515',
- 54: 'LGA3647-1',
- 55: 'SP3',
- 56: 'SP3r2',
- 57: 'LGA2066',
- 58: 'BGA1392',
- 59: 'BGA1510',
- 60: 'BGA1528',
- 61: 'LGA4189',
- 62: 'LGA1200',
- 63: 'LGA4677',
- 64: 'LGA1700',
- 65: 'BGA1744',
- 66: 'BGA1781',
- 67: 'BGA1211',
- 68: 'BGA2422',
- 69: 'LGA1211',
- 70: 'LGA2422',
- 71: 'LGA5773',
- 72: 'BGA5773',
-};
-
-const socketTypesByName = {
- 'LGA1150': 'i7-5775C i3-4340 i3-4170 G3250 i3-4160T i3-4160 E3-1231 G3258 G3240 i7-4790S i7-4790K i7-4790 i5-4690K i5-4690 i5-4590T i5-4590S i5-4590 i5-4460 i3-4360 i3-4150 G1820 G3420 G3220 i7-4771 i5-4440 i3-4330 i3-4130T i3-4130 E3-1230 i7-4770S i7-4770K i7-4770 i5-4670K i5-4670 i5-4570T i5-4570S i5-4570 i5-4430',
- 'LGA1151': 'i9-9900KS E-2288G E-2224 G5420 i9-9900T i9-9900 i7-9700T i7-9700F i7-9700E i7-9700 i5-9600 i5-9500T i5-9500F i5-9500 i5-9400T i3-9350K i3-9300 i3-9100T i3-9100F i3-9100 G4930 i9-9900KF i7-9700KF i5-9600KF i5-9400F i5-9400 i3-9350KF i9-9900K i7-9700K i5-9600K G5500 G5400 i7-8700T i7-8086K i5-8600 i5-8500T i5-8500 i5-8400T i3-8300 i3-8100T G4900 i7-8700K i7-8700 i5-8600K i5-8400 i3-8350K i3-8100 E3-1270 G4600 G4560 i7-7700T i7-7700K i7-7700 i5-7600K i5-7600 i5-7500T i5-7500 i5-7400 i3-7350K i3-7300 i3-7100T i3-7100 G3930 G3900 G4400 i7-6700T i7-6700K i7-6700 i5-6600K i5-6600 i5-6500T i5-6500 i5-6400T i5-6400 i3-6300 i3-6100T i3-6100 E3-1270 E3-1270 T4500 T4400',
- '1155': 'G440 G460 G465 G470 G530T G540T G550T G1610T G1620T G530 G540 G1610 G550 G1620 G555 G1630 i3-2100T i3-2120T i3-3220T i3-3240T i3-3250T i3-2100 i3-2105 i3-2102 i3-3210 i3-3220 i3-2125 i3-2120 i3-3225 i3-2130 i3-3245 i3-3240 i3-3250 i5-3570T i5-2500T i5-2400S i5-2405S i5-2390T i5-3330S i5-2500S i5-3335S i5-2300 i5-3450S i5-3340S i5-3470S i5-3475S i5-3470T i5-2310 i5-3550S i5-2320 i5-3330 i5-3350P i5-3450 i5-2400 i5-3340 i5-3570S i5-2380P i5-2450P i5-3470 i5-2500K i5-3550 i5-2500 i5-3570 i5-3570K i5-2550K i7-3770T i7-2600S i7-3770S i7-2600K i7-2600 i7-3770 i7-3770K i7-2700K G620T G630T G640T G2020T G645T G2100T G2030T G622 G860T G620 G632 G2120T G630 G640 G2010 G840 G2020 G850 G645 G2030 G860 G2120 G870 G2130 G2140 E3-1220L E3-1220L E3-1260L E3-1265L E3-1220 E3-1225 E3-1220 E3-1235 E3-1225 E3-1230 E3-1230 E3-1240 E3-1245 E3-1270 E3-1275 E3-1240 E3-1245 E3-1270 E3-1280 E3-1275 E3-1290 E3-1280 E3-1290'
-};
-
-function getSocketTypesByName(str) {
- let result = '';
- for (const key in socketTypesByName) {
- const names = socketTypesByName[key].split(' ');
- names.forEach(element => {
- if (str.indexOf(element) >= 0) {
- result = key;
- }
- });
- }
- return result;
-}
-
-function cpuManufacturer(str) {
- let result = str;
- str = str.toLowerCase();
-
- if (str.indexOf('intel') >= 0) { result = 'Intel'; }
- if (str.indexOf('amd') >= 0) { result = 'AMD'; }
- if (str.indexOf('qemu') >= 0) { result = 'QEMU'; }
- if (str.indexOf('hygon') >= 0) { result = 'Hygon'; }
- if (str.indexOf('centaur') >= 0) { result = 'WinChip/Via'; }
- if (str.indexOf('vmware') >= 0) { result = 'VMware'; }
- if (str.indexOf('Xen') >= 0) { result = 'Xen Hypervisor'; }
- if (str.indexOf('tcg') >= 0) { result = 'QEMU'; }
- if (str.indexOf('apple') >= 0) { result = 'Apple'; }
- if (str.indexOf('sifive') >= 0) { result = 'SiFive'; }
- if (str.indexOf('thead') >= 0) { result = 'T-Head'; }
- if (str.indexOf('andestech') >= 0) { result = 'Andes Technology'; }
-
- return result;
-}
-
-function cpuBrandManufacturer(res) {
- res.brand = res.brand.replace(/\(R\)+/g, '®').replace(/\s+/g, ' ').trim();
- res.brand = res.brand.replace(/\(TM\)+/g, '™').replace(/\s+/g, ' ').trim();
- res.brand = res.brand.replace(/\(C\)+/g, '©').replace(/\s+/g, ' ').trim();
- res.brand = res.brand.replace(/CPU+/g, '').replace(/\s+/g, ' ').trim();
- res.manufacturer = cpuManufacturer(res.brand);
-
- let parts = res.brand.split(' ');
- parts.shift();
- res.brand = parts.join(' ');
- return res;
-}
-
-function getAMDSpeed(brand) {
- let result = '0';
- for (let key in AMDBaseFrequencies) {
- if ({}.hasOwnProperty.call(AMDBaseFrequencies, key)) {
- let parts = key.split('|');
- let found = 0;
- parts.forEach(item => {
- if (brand.indexOf(item) > -1) {
- found++;
- }
- });
- if (found === parts.length) {
- result = AMDBaseFrequencies[key];
- }
- }
- }
- return parseFloat(result);
-}
-
-// --------------------------
-// CPU - brand, speed
-
-function getCpu() {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- const UNKNOWN = 'unknown';
- let result = {
- manufacturer: UNKNOWN,
- brand: UNKNOWN,
- vendor: '',
- family: '',
- model: '',
- stepping: '',
- revision: '',
- voltage: '',
- speed: 0,
- speedMin: 0,
- speedMax: 0,
- governor: '',
- cores: util.cores(),
- physicalCores: util.cores(),
- performanceCores: util.cores(),
- efficiencyCores: 0,
- processors: 1,
- socket: '',
- flags: '',
- virtualization: false,
- cache: {}
- };
- cpuFlags().then(flags => {
- result.flags = flags;
- result.virtualization = flags.indexOf('vmx') > -1 || flags.indexOf('svm') > -1;
- if (_darwin) {
- exec('sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min hw.packages hw.physicalcpu_max hw.ncpu hw.tbfrequency hw.cpufamily hw.cpusubfamily', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- const modelline = util.getValue(lines, 'machdep.cpu.brand_string');
- const modellineParts = modelline.split('@');
- result.brand = modellineParts[0].trim();
- const speed = modellineParts[1] ? modellineParts[1].trim() : '0';
- result.speed = parseFloat(speed.replace(/GHz+/g, ''));
- let tbFrequency = util.getValue(lines, 'hw.tbfrequency') / 1000000000.0;
- tbFrequency = tbFrequency < 0.1 ? tbFrequency * 100 : tbFrequency;
- result.speed = result.speed === 0 ? tbFrequency : result.speed;
-
- _cpu_speed = result.speed;
- result = cpuBrandManufacturer(result);
- result.speedMin = util.getValue(lines, 'hw.cpufrequency_min') ? (util.getValue(lines, 'hw.cpufrequency_min') / 1000000000.0) : result.speed;
- result.speedMax = util.getValue(lines, 'hw.cpufrequency_max') ? (util.getValue(lines, 'hw.cpufrequency_max') / 1000000000.0) : result.speed;
- result.vendor = util.getValue(lines, 'machdep.cpu.vendor') || 'Apple';
- result.family = util.getValue(lines, 'machdep.cpu.family') || util.getValue(lines, 'hw.cpufamily');
- result.model = util.getValue(lines, 'machdep.cpu.model');
- result.stepping = util.getValue(lines, 'machdep.cpu.stepping') || util.getValue(lines, 'hw.cpusubfamily');
- result.virtualization = true;
- const countProcessors = util.getValue(lines, 'hw.packages');
- const countCores = util.getValue(lines, 'hw.physicalcpu_max');
- const countThreads = util.getValue(lines, 'hw.ncpu');
- if (os.arch() === 'arm64') {
- result.socket = 'SOC';
- try {
- const clusters = execSync('ioreg -c IOPlatformDevice -d 3 -r | grep cluster-type').toString().split('\n');
- const efficiencyCores = clusters.filter(line => line.indexOf('"E"') >= 0).length;
- const performanceCores = clusters.filter(line => line.indexOf('"P"') >= 0).length;
- result.efficiencyCores = efficiencyCores;
- result.performanceCores = performanceCores;
- } catch (e) {
- util.noop();
- }
- }
- if (countProcessors) {
- result.processors = parseInt(countProcessors) || 1;
- }
- if (countCores && countThreads) {
- result.cores = parseInt(countThreads) || util.cores();
- result.physicalCores = parseInt(countCores) || util.cores();
- }
- cpuCache().then((res) => {
- result.cache = res;
- resolve(result);
- });
- });
- }
- if (_linux) {
- let modelline = '';
- let lines = [];
- if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; }
- exec('export LC_ALL=C; lscpu; echo -n "Governor: "; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null; echo; unset LC_ALL', function (error, stdout) {
- if (!error) {
- lines = stdout.toString().split('\n');
- }
- modelline = util.getValue(lines, 'model name') || modelline;
- modelline = util.getValue(lines, 'bios model name') || modelline;
- const modellineParts = modelline.split('@');
- result.brand = modellineParts[0].trim();
- result.speed = modellineParts[1] ? parseFloat(modellineParts[1].trim()) : 0;
- if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
- result.speed = getAMDSpeed(result.brand);
- }
- if (result.speed === 0) {
- const current = getCpuCurrentSpeedSync();
- if (current.avg !== 0) { result.speed = current.avg; }
- }
- _cpu_speed = result.speed;
- result.speedMin = Math.round(parseFloat(util.getValue(lines, 'cpu min mhz').replace(/,/g, '.')) / 10.0) / 100;
- result.speedMax = Math.round(parseFloat(util.getValue(lines, 'cpu max mhz').replace(/,/g, '.')) / 10.0) / 100;
-
- result = cpuBrandManufacturer(result);
- result.vendor = cpuManufacturer(util.getValue(lines, 'vendor id'));
-
- result.family = util.getValue(lines, 'cpu family');
- result.model = util.getValue(lines, 'model:');
- result.stepping = util.getValue(lines, 'stepping');
- result.revision = util.getValue(lines, 'cpu revision');
- result.cache.l1d = util.getValue(lines, 'l1d cache');
- if (result.cache.l1d) { result.cache.l1d = parseInt(result.cache.l1d) * (result.cache.l1d.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1d.indexOf('K') !== -1 ? 1024 : 1)); }
- result.cache.l1i = util.getValue(lines, 'l1i cache');
- if (result.cache.l1i) { result.cache.l1i = parseInt(result.cache.l1i) * (result.cache.l1i.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1i.indexOf('K') !== -1 ? 1024 : 1)); }
- result.cache.l2 = util.getValue(lines, 'l2 cache');
- if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2) * (result.cache.l2.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l2.indexOf('K') !== -1 ? 1024 : 1)); }
- result.cache.l3 = util.getValue(lines, 'l3 cache');
- if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3) * (result.cache.l3.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l3.indexOf('K') !== -1 ? 1024 : 1)); }
-
- const threadsPerCore = util.getValue(lines, 'thread(s) per core') || '1';
- const processors = util.getValue(lines, 'socket(s)') || '1';
- const threadsPerCoreInt = parseInt(threadsPerCore, 10); // threads per code (normally only for performance cores)
- const processorsInt = parseInt(processors, 10) || 1; // number of sockets / processor units in machine (normally 1)
- const coresPerSocket = parseInt(util.getValue(lines, 'core(s) per socket'), 10); // number of cores (e.g. 16 on i12900)
- result.physicalCores = coresPerSocket ? coresPerSocket * processorsInt : result.cores / threadsPerCoreInt;
- result.performanceCores = threadsPerCoreInt > 1 ? result.cores - result.physicalCores : result.cores;
- result.efficiencyCores = threadsPerCoreInt > 1 ? result.cores - (threadsPerCoreInt * result.performanceCores) : 0;
- result.processors = processorsInt;
- result.governor = util.getValue(lines, 'governor') || '';
-
- // Test Raspberry
- if (result.vendor === 'ARM') {
- const linesRpi = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
- const rPIRevision = util.decodePiCpuinfo(linesRpi);
- if (rPIRevision.model.toLowerCase().indexOf('raspberry') >= 0) {
- result.family = result.manufacturer;
- result.manufacturer = rPIRevision.manufacturer;
- result.brand = rPIRevision.processor;
- result.revision = rPIRevision.revisionCode;
- result.socket = 'SOC';
- }
- }
-
- // Test RISC-V
- if (util.getValue(lines, 'architecture') === 'riscv64') {
- const linesRiscV = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
- const uarch = util.getValue(linesRiscV, 'uarch') || '';
- if (uarch.indexOf(',') > -1) {
- const split = uarch.split(',');
- result.manufacturer = cpuManufacturer(split[0]);
- result.brand = split[1];
- }
- }
-
- // socket type
- let lines2 = [];
- exec('export LC_ALL=C; dmidecode –t 4 2>/dev/null | grep "Upgrade: Socket"; unset LC_ALL', function (error2, stdout2) {
- lines2 = stdout2.toString().split('\n');
- if (lines2 && lines2.length) {
- result.socket = util.getValue(lines2, 'Upgrade').replace('Socket', '').trim() || result.socket;
- }
- resolve(result);
- });
- });
- }
- if (_freebsd || _openbsd || _netbsd) {
- let modelline = '';
- let lines = [];
- if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; }
- exec('export LC_ALL=C; dmidecode -t 4; dmidecode -t 7 unset LC_ALL', function (error, stdout) {
- let cache = [];
- if (!error) {
- const data = stdout.toString().split('# dmidecode');
- const processor = data.length > 1 ? data[1] : '';
- cache = data.length > 2 ? data[2].split('Cache Information') : [];
-
- lines = processor.split('\n');
- }
- result.brand = modelline.split('@')[0].trim();
- result.speed = modelline.split('@')[1] ? parseFloat(modelline.split('@')[1].trim()) : 0;
- if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
- result.speed = getAMDSpeed(result.brand);
- }
- if (result.speed === 0) {
- const current = getCpuCurrentSpeedSync();
- if (current.avg !== 0) { result.speed = current.avg; }
- }
- _cpu_speed = result.speed;
- result.speedMin = result.speed;
- result.speedMax = Math.round(parseFloat(util.getValue(lines, 'max speed').replace(/Mhz/g, '')) / 10.0) / 100;
-
- result = cpuBrandManufacturer(result);
- result.vendor = cpuManufacturer(util.getValue(lines, 'manufacturer'));
- let sig = util.getValue(lines, 'signature');
- sig = sig.split(',');
- for (let i = 0; i < sig.length; i++) {
- sig[i] = sig[i].trim();
- }
- result.family = util.getValue(sig, 'Family', ' ', true);
- result.model = util.getValue(sig, 'Model', ' ', true);
- result.stepping = util.getValue(sig, 'Stepping', ' ', true);
- result.revision = '';
- const voltage = parseFloat(util.getValue(lines, 'voltage'));
- result.voltage = isNaN(voltage) ? '' : voltage.toFixed(2);
- for (let i = 0; i < cache.length; i++) {
- lines = cache[i].split('\n');
- let cacheType = util.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-');
- cacheType = cacheType.length ? cacheType[0] : '';
- const sizeParts = util.getValue(lines, 'Installed Size').split(' ');
- let size = parseInt(sizeParts[0], 10);
- const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb';
- size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1)));
- if (cacheType) {
- if (cacheType === 'l1') {
- result.cache[cacheType + 'd'] = size / 2;
- result.cache[cacheType + 'i'] = size / 2;
- } else {
- result.cache[cacheType] = size;
- }
- }
- }
- // socket type
- result.socket = util.getValue(lines, 'Upgrade').replace('Socket', '').trim();
- // # threads / # cores
- const threadCount = util.getValue(lines, 'thread count').trim();
- const coreCount = util.getValue(lines, 'core count').trim();
- if (coreCount && threadCount) {
- result.cores = parseInt(threadCount, 10);
- result.physicalCores = parseInt(coreCount, 10);
- }
- resolve(result);
- });
- }
- if (_sunos) {
- resolve(result);
- }
- if (_windows) {
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance Win32_processor | select Name, Revision, L2CacheSize, L3CacheSize, Manufacturer, MaxClockSpeed, Description, UpgradeMethod, Caption, NumberOfLogicalProcessors, NumberOfCores | fl'));
- workload.push(util.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl'));
- workload.push(util.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent'));
-
- Promise.all(
- workload
- ).then((data) => {
- let lines = data[0].split('\r\n');
- let name = util.getValue(lines, 'name', ':') || '';
- if (name.indexOf('@') >= 0) {
- result.brand = name.split('@')[0].trim();
- result.speed = name.split('@')[1] ? parseFloat(name.split('@')[1].trim()) : 0;
- _cpu_speed = result.speed;
- } else {
- result.brand = name.trim();
- result.speed = 0;
- }
- result = cpuBrandManufacturer(result);
- result.revision = util.getValue(lines, 'revision', ':');
- result.vendor = util.getValue(lines, 'manufacturer', ':');
- result.speedMax = Math.round(parseFloat(util.getValue(lines, 'maxclockspeed', ':').replace(/,/g, '.')) / 10.0) / 100;
- if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
- result.speed = getAMDSpeed(result.brand);
- }
- if (result.speed === 0) {
- result.speed = result.speedMax;
- }
- result.speedMin = result.speed;
-
- let description = util.getValue(lines, 'description', ':').split(' ');
- for (let i = 0; i < description.length; i++) {
- if (description[i].toLowerCase().startsWith('family') && (i + 1) < description.length && description[i + 1]) {
- result.family = description[i + 1];
- }
- if (description[i].toLowerCase().startsWith('model') && (i + 1) < description.length && description[i + 1]) {
- result.model = description[i + 1];
- }
- if (description[i].toLowerCase().startsWith('stepping') && (i + 1) < description.length && description[i + 1]) {
- result.stepping = description[i + 1];
- }
- }
- // socket type
- const socketId = util.getValue(lines, 'UpgradeMethod', ':');
- if (socketTypes[socketId]) {
- result.socket = socketTypes[socketId];
- }
- const socketByName = getSocketTypesByName(name);
- if (socketByName) {
- result.socket = socketByName;
- }
- // # threads / # cores
- const countProcessors = util.countLines(lines, 'Caption');
- const countThreads = util.getValue(lines, 'NumberOfLogicalProcessors', ':');
- const countCores = util.getValue(lines, 'NumberOfCores', ':');
- if (countProcessors) {
- result.processors = parseInt(countProcessors) || 1;
- }
- if (countCores && countThreads) {
- result.cores = parseInt(countThreads) || util.cores();
- result.physicalCores = parseInt(countCores) || util.cores();
- }
- if (countProcessors > 1) {
- result.cores = result.cores * countProcessors;
- result.physicalCores = result.physicalCores * countProcessors;
- }
- result.cache = parseWinCache(data[0], data[1]);
- const hyperv = data[2] ? data[2].toString().toLowerCase() : '';
- result.virtualization = hyperv.indexOf('true') !== -1;
-
- resolve(result);
- });
- } catch (e) {
- resolve(result);
- }
- }
- });
- });
- });
-}
-
-// --------------------------
-// CPU - Processor Data
-
-function cpu(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- getCpu().then(result => {
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- });
-}
-
-exports.cpu = cpu;
-
-// --------------------------
-// CPU - current speed - in GHz
-
-function getCpuCurrentSpeedSync() {
-
- let cpus = os.cpus();
- let minFreq = 999999999;
- let maxFreq = 0;
- let avgFreq = 0;
- let cores = [];
-
- if (cpus && cpus.length) {
- for (let i in cpus) {
- if ({}.hasOwnProperty.call(cpus, i)) {
- let freq = cpus[i].speed > 100 ? (cpus[i].speed + 1) / 1000 : cpus[i].speed / 10;
- avgFreq = avgFreq + freq;
- if (freq > maxFreq) { maxFreq = freq; }
- if (freq < minFreq) { minFreq = freq; }
- cores.push(parseFloat(freq.toFixed(2)));
- }
- }
- avgFreq = avgFreq / cpus.length;
- return {
- min: parseFloat(minFreq.toFixed(2)),
- max: parseFloat(maxFreq.toFixed(2)),
- avg: parseFloat((avgFreq).toFixed(2)),
- cores: cores
- };
- } else {
- return {
- min: 0,
- max: 0,
- avg: 0,
- cores: cores
- };
- }
-}
-
-function cpuCurrentSpeed(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = getCpuCurrentSpeedSync();
- if (result.avg === 0 && _cpu_speed !== 0) {
- const currCpuSpeed = parseFloat(_cpu_speed);
- result = {
- min: currCpuSpeed,
- max: currCpuSpeed,
- avg: currCpuSpeed,
- cores: []
- };
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- });
-}
-
-exports.cpuCurrentSpeed = cpuCurrentSpeed;
-
-// --------------------------
-// CPU - temperature
-// if sensors are installed
-
-function cpuTemperature(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
- main: null,
- cores: [],
- max: null,
- socket: [],
- chipset: null
- };
- if (_linux) {
- // CPU Chipset, Socket
- try {
- const cmd = 'cat /sys/class/thermal/thermal_zone*/type 2>/dev/null; echo "-----"; cat /sys/class/thermal/thermal_zone*/temp 2>/dev/null;';
- const parts = execSync(cmd, util.execOptsLinux).toString().split('-----\n');
- if (parts.length === 2) {
- const lines = parts[0].split('\n');
- const lines2 = parts[1].split('\n');
- for (let i = 0; i < lines.length; i++) {
- const line = lines[i].trim();
- if (line.startsWith('acpi') && lines2[i]) {
- result.socket.push(Math.round(parseInt(lines2[i], 10) / 100) / 10);
- }
- if (line.startsWith('pch') && lines2[i]) {
- result.chipset = Math.round(parseInt(lines2[i], 10) / 100) / 10;
- }
- }
- }
- } catch (e) {
- util.noop();
- }
-
- const cmd = 'for mon in /sys/class/hwmon/hwmon*; do for label in "$mon"/temp*_label; do if [ -f $label ]; then value=${label%_*}_input; echo $(cat "$label")___$(cat "$value"); fi; done; done;';
- try {
- exec(cmd, function (error, stdout) {
- stdout = stdout.toString();
- const tdiePos = stdout.toLowerCase().indexOf('tdie');
- if (tdiePos !== -1) {
- stdout = stdout.substring(tdiePos);
- }
- let lines = stdout.split('\n');
- let tctl = 0;
- lines.forEach(line => {
- const parts = line.split('___');
- const label = parts[0];
- const value = parts.length > 1 && parts[1] ? parts[1] : '0';
- if (value && label && label.toLowerCase() === 'tctl') {
- tctl = result.main = Math.round(parseInt(value, 10) / 100) / 10;
- }
- if (value && (label === undefined || (label && label.toLowerCase().startsWith('core')))) {
- result.cores.push(Math.round(parseInt(value, 10) / 100) / 10);
- } else if (value && label && result.main === null && (label.toLowerCase().indexOf('package') >= 0 || label.toLowerCase().indexOf('physical') >= 0 || label.toLowerCase() === 'tccd1')) {
- result.main = Math.round(parseInt(value, 10) / 100) / 10;
- }
- });
- if (tctl && result.main === null) {
- result.main = tctl;
- }
-
- if (result.cores.length > 0) {
- if (result.main === null) {
- result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length);
- }
- let maxtmp = Math.max.apply(Math, result.cores);
- result.max = (maxtmp > result.main) ? maxtmp : result.main;
- }
- if (result.main !== null) {
- if (result.max === null) {
- result.max = result.main;
- }
- if (callback) { callback(result); }
- resolve(result);
- return;
- }
- exec('sensors', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- let tdieTemp = null;
- let newSectionStarts = true;
- let section = '';
- lines.forEach(function (line) {
- // determine section
- if (line.trim() === '') {
- newSectionStarts = true;
- } else if (newSectionStarts) {
- if (line.trim().toLowerCase().startsWith('acpi')) { section = 'acpi'; }
- if (line.trim().toLowerCase().startsWith('pch')) { section = 'pch'; }
- if (line.trim().toLowerCase().startsWith('core')) { section = 'core'; }
- newSectionStarts = false;
- }
- let regex = /[+-]([^°]*)/g;
- let temps = line.match(regex);
- let firstPart = line.split(':')[0].toUpperCase();
- if (section === 'acpi') {
- // socket temp
- if (firstPart.indexOf('TEMP') !== -1) {
- result.socket.push(parseFloat(temps));
- }
- } else if (section === 'pch') {
- // chipset temp
- if (firstPart.indexOf('TEMP') !== -1 && !result.chipset) {
- result.chipset = parseFloat(temps);
- }
- }
- // cpu temp
- if (firstPart.indexOf('PHYSICAL') !== -1 || firstPart.indexOf('PACKAGE') !== -1) {
- result.main = parseFloat(temps);
- }
- if (firstPart.indexOf('CORE ') !== -1) {
- result.cores.push(parseFloat(temps));
- }
- if (firstPart.indexOf('TDIE') !== -1 && tdieTemp === null) {
- tdieTemp = parseFloat(temps);
- }
- });
- if (result.cores.length > 0) {
- result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length);
- let maxtmp = Math.max.apply(Math, result.cores);
- result.max = (maxtmp > result.main) ? maxtmp : result.main;
- } else {
- if (result.main === null && tdieTemp !== null) {
- result.main = tdieTemp;
- result.max = tdieTemp;
- }
- }
- if (result.main !== null || result.max !== null) {
- if (callback) { callback(result); }
- resolve(result);
- return;
- }
- }
- fs.stat('/sys/class/thermal/thermal_zone0/temp', function (err) {
- if (err === null) {
- fs.readFile('/sys/class/thermal/thermal_zone0/temp', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines.length > 0) {
- result.main = parseFloat(lines[0]) / 1000.0;
- result.max = result.main;
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- exec('/opt/vc/bin/vcgencmd measure_temp', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines.length > 0 && lines[0].indexOf('=')) {
- result.main = parseFloat(lines[0].split('=')[1]);
- result.max = result.main;
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- });
- });
- });
- } catch (er) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('sysctl dev.cpu | grep temp', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- let sum = 0;
- lines.forEach(function (line) {
- const parts = line.split(':');
- if (parts.length > 1) {
- const temp = parseFloat(parts[1].replace(',', '.'));
- if (temp > result.max) { result.max = temp; }
- sum = sum + temp;
- result.cores.push(temp);
- }
- });
- if (result.cores.length) {
- result.main = Math.round(sum / result.cores.length * 100) / 100;
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- let osxTemp = null;
- try {
- osxTemp = __nccwpck_require__(73700);
- } catch (er) {
- osxTemp = null;
- }
- if (osxTemp) {
- result = osxTemp.cpuTemperature();
- // round to 2 digits
- if (result.main) {
- result.main = Math.round(result.main * 100) / 100;
- }
- if (result.max) {
- result.max = Math.round(result.max * 100) / 100;
- }
- if (result.cores && result.cores.length) {
- for (let i = 0; i < result.cores.length; i++) {
- result.cores[i] = Math.round(result.cores[i] * 100) / 100;
- }
- }
- }
-
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- util.powerShell('Get-CimInstance MSAcpi_ThermalZoneTemperature -Namespace "root/wmi" | Select CurrentTemperature').then((stdout, error) => {
- if (!error) {
- let sum = 0;
- let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
- lines.forEach(function (line) {
- let value = (parseInt(line, 10) - 2732) / 10;
- if (!isNaN(value)) {
- sum = sum + value;
- if (value > result.max) { result.max = value; }
- result.cores.push(value);
- }
- });
- if (result.cores.length) {
- result.main = sum / result.cores.length;
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.cpuTemperature = cpuTemperature;
-
-// --------------------------
-// CPU Flags
-
-function cpuFlags(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = '';
- if (_windows) {
- try {
- exec('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', util.execOptsWin, function (error, stdout) {
- if (!error) {
- let flag_hex = stdout.split('0x').pop().trim();
- let flag_bin_unpadded = parseInt(flag_hex, 16).toString(2);
- let flag_bin = '0'.repeat(32 - flag_bin_unpadded.length) + flag_bin_unpadded;
- // empty flags are the reserved fields in the CPUID feature bit list
- // as found on wikipedia:
- // https://en.wikipedia.org/wiki/CPUID
- let all_flags = [
- 'fpu', 'vme', 'de', 'pse', 'tsc', 'msr', 'pae', 'mce', 'cx8', 'apic',
- '', 'sep', 'mtrr', 'pge', 'mca', 'cmov', 'pat', 'pse-36', 'psn', 'clfsh',
- '', 'ds', 'acpi', 'mmx', 'fxsr', 'sse', 'sse2', 'ss', 'htt', 'tm', 'ia64', 'pbe'
- ];
- for (let f = 0; f < all_flags.length; f++) {
- if (flag_bin[f] === '1' && all_flags[f] !== '') {
- result += ' ' + all_flags[f];
- }
- }
- result = result.trim().toLowerCase();
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_linux) {
- try {
-
- exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- if (line.split(':')[0].toUpperCase().indexOf('FLAGS') !== -1) {
- result = line.split(':')[1].trim().toLowerCase();
- }
- });
- }
- if (!result) {
- fs.readFile('/proc/cpuinfo', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result = util.getValue(lines, 'features', ':', true).toLowerCase();
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('export LC_ALL=C; dmidecode -t 4 2>/dev/null; unset LC_ALL', function (error, stdout) {
- let flags = [];
- if (!error) {
- let parts = stdout.toString().split('\tFlags:');
- const lines = parts.length > 1 ? parts[1].split('\tVersion:')[0].split('\n') : [];
- lines.forEach(function (line) {
- let flag = (line.indexOf('(') ? line.split('(')[0].toLowerCase() : '').trim().replace(/\t/g, '');
- if (flag) {
- flags.push(flag);
- }
- });
- }
- result = flags.join(' ').trim().toLowerCase();
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- exec('sysctl machdep.cpu.features', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines.length > 0 && lines[0].indexOf('machdep.cpu.features:') !== -1) {
- result = lines[0].split(':')[1].trim().toLowerCase();
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
-}
-
-exports.cpuFlags = cpuFlags;
-
-// --------------------------
-// CPU Cache
-
-function cpuCache(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- l1d: null,
- l1i: null,
- l2: null,
- l3: null,
- };
- if (_linux) {
- try {
- exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- let parts = line.split(':');
- if (parts[0].toUpperCase().indexOf('L1D CACHE') !== -1) {
- result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
- }
- if (parts[0].toUpperCase().indexOf('L1I CACHE') !== -1) {
- result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
- }
- if (parts[0].toUpperCase().indexOf('L2 CACHE') !== -1) {
- result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
- }
- if (parts[0].toUpperCase().indexOf('L3 CACHE') !== -1) {
- result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
- }
- });
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('export LC_ALL=C; dmidecode -t 7 2>/dev/null; unset LC_ALL', function (error, stdout) {
- let cache = [];
- if (!error) {
- const data = stdout.toString();
- cache = data.split('Cache Information');
- cache.shift();
- }
- for (let i = 0; i < cache.length; i++) {
- const lines = cache[i].split('\n');
- let cacheType = util.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-');
- cacheType = cacheType.length ? cacheType[0] : '';
- const sizeParts = util.getValue(lines, 'Installed Size').split(' ');
- let size = parseInt(sizeParts[0], 10);
- const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb';
- size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1)));
- if (cacheType) {
- if (cacheType === 'l1') {
- result.cache[cacheType + 'd'] = size / 2;
- result.cache[cacheType + 'i'] = size / 2;
- } else {
- result.cache[cacheType] = size;
- }
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- exec('sysctl hw.l1icachesize hw.l1dcachesize hw.l2cachesize hw.l3cachesize', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- let parts = line.split(':');
- if (parts[0].toLowerCase().indexOf('hw.l1icachesize') !== -1) {
- result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
- }
- if (parts[0].toLowerCase().indexOf('hw.l1dcachesize') !== -1) {
- result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
- }
- if (parts[0].toLowerCase().indexOf('hw.l2cachesize') !== -1) {
- result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
- }
- if (parts[0].toLowerCase().indexOf('hw.l3cachesize') !== -1) {
- result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
- }
- });
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance Win32_processor | select L2CacheSize, L3CacheSize | fl'));
- workload.push(util.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl'));
-
- Promise.all(
- workload
- ).then((data) => {
- result = parseWinCache(data[0], data[1]);
-
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-function parseWinCache(linesProc, linesCache) {
- let result = {
- l1d: null,
- l1i: null,
- l2: null,
- l3: null,
- };
-
- // Win32_processor
- let lines = linesProc.split('\r\n');
- result.l1d = 0;
- result.l1i = 0;
- result.l2 = util.getValue(lines, 'l2cachesize', ':');
- result.l3 = util.getValue(lines, 'l3cachesize', ':');
- if (result.l2) { result.l2 = parseInt(result.l2, 10) * 1024; } else { result.l2 = 0; }
- if (result.l3) { result.l3 = parseInt(result.l3, 10) * 1024; } else { result.l3 = 0; }
-
- // Win32_CacheMemory
- const parts = linesCache.split(/\n\s*\n/);
- let l1i = 0;
- let l1d = 0;
- let l2 = 0;
- parts.forEach(function (part) {
- const lines = part.split('\r\n');
- const cacheType = util.getValue(lines, 'CacheType');
- const level = util.getValue(lines, 'Level');
- const installedSize = util.getValue(lines, 'InstalledSize');
- // L1 Instructions
- if (level === '3' && cacheType === '3') {
- result.l1i = result.l1i + parseInt(installedSize, 10) * 1024;
- }
- // L1 Data
- if (level === '3' && cacheType === '4') {
- result.l1d = result.l1d + parseInt(installedSize, 10) * 1024;
- }
- // L1 all
- if (level === '3' && cacheType === '5') {
- l1i = parseInt(installedSize, 10) / 2;
- l1d = parseInt(installedSize, 10) / 2;
- }
- // L2
- if (level === '4' && cacheType === '5') {
- l2 = l2 + parseInt(installedSize, 10) * 1024;
- }
- });
- if (!result.l1i && !result.l1d) {
- result.l1i = l1i;
- result.l1d = l1d;
- }
- if (l2) {
- result.l2 = l2;
- }
- return result;
-}
-
-exports.cpuCache = cpuCache;
-
-// --------------------------
-// CPU - current load - in %
-
-function getLoad() {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let loads = os.loadavg().map(function (x) { return x / util.cores(); });
- let avgLoad = parseFloat((Math.max.apply(Math, loads)).toFixed(2));
- let result = {};
-
- let now = Date.now() - _current_cpu.ms;
- if (now >= 200) {
- _current_cpu.ms = Date.now();
- const cpus = os.cpus().map(function (cpu) {
- cpu.times.steal = 0;
- cpu.times.guest = 0;
- return cpu;
- });
- let totalUser = 0;
- let totalSystem = 0;
- let totalNice = 0;
- let totalIrq = 0;
- let totalIdle = 0;
- let totalSteal = 0;
- let totalGuest = 0;
- let cores = [];
- _corecount = (cpus && cpus.length) ? cpus.length : 0;
-
- // linux: try to get other cpu stats
- if (_linux) {
- try {
- const lines = execSync('cat /proc/stat 2>/dev/null | grep cpu', util.execOptsLinux).toString().split('\n');
- if (lines.length > 1) {
- lines.shift();
- if (lines.length === cpus.length) {
- for (let i = 0; i < lines.length; i++) {
- let parts = lines[i].split(' ');
- if (parts.length >= 10) {
- const steal = parseFloat(parts[8]) || 0;
- const guest = parseFloat(parts[9]) || 0;
- cpus[i].times.steal = steal;
- cpus[i].times.guest = guest;
- }
- }
- }
- }
- } catch (e) {
- util.noop();
- }
- }
-
- for (let i = 0; i < _corecount; i++) {
- const cpu = cpus[i].times;
- totalUser += cpu.user;
- totalSystem += cpu.sys;
- totalNice += cpu.nice;
- totalIdle += cpu.idle;
- totalIrq += cpu.irq;
- totalSteal += cpu.steal || 0;
- totalGuest += cpu.guest || 0;
- let tmpTick = (_cpus && _cpus[i] && _cpus[i].totalTick ? _cpus[i].totalTick : 0);
- let tmpLoad = (_cpus && _cpus[i] && _cpus[i].totalLoad ? _cpus[i].totalLoad : 0);
- let tmpUser = (_cpus && _cpus[i] && _cpus[i].user ? _cpus[i].user : 0);
- let tmpSystem = (_cpus && _cpus[i] && _cpus[i].sys ? _cpus[i].sys : 0);
- let tmpNice = (_cpus && _cpus[i] && _cpus[i].nice ? _cpus[i].nice : 0);
- let tmpIdle = (_cpus && _cpus[i] && _cpus[i].idle ? _cpus[i].idle : 0);
- let tmpIrq = (_cpus && _cpus[i] && _cpus[i].irq ? _cpus[i].irq : 0);
- let tmpSteal = (_cpus && _cpus[i] && _cpus[i].steal ? _cpus[i].steal : 0);
- let tmpGuest = (_cpus && _cpus[i] && _cpus[i].guest ? _cpus[i].guest : 0);
- _cpus[i] = cpu;
- _cpus[i].totalTick = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest + _cpus[i].idle;
- _cpus[i].totalLoad = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest;
- _cpus[i].currentTick = _cpus[i].totalTick - tmpTick;
- _cpus[i].load = (_cpus[i].totalLoad - tmpLoad);
- _cpus[i].loadUser = (_cpus[i].user - tmpUser);
- _cpus[i].loadSystem = (_cpus[i].sys - tmpSystem);
- _cpus[i].loadNice = (_cpus[i].nice - tmpNice);
- _cpus[i].loadIdle = (_cpus[i].idle - tmpIdle);
- _cpus[i].loadIrq = (_cpus[i].irq - tmpIrq);
- _cpus[i].loadSteal = (_cpus[i].steal - tmpSteal);
- _cpus[i].loadGuest = (_cpus[i].guest - tmpGuest);
- cores[i] = {};
- cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
- cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100;
- cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100;
- cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100;
- cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100;
- cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100;
- cores[i].loadSteal = _cpus[i].loadSteal / _cpus[i].currentTick * 100;
- cores[i].loadGuest = _cpus[i].loadGuest / _cpus[i].currentTick * 100;
- cores[i].rawLoad = _cpus[i].load;
- cores[i].rawLoadUser = _cpus[i].loadUser;
- cores[i].rawLoadSystem = _cpus[i].loadSystem;
- cores[i].rawLoadNice = _cpus[i].loadNice;
- cores[i].rawLoadIdle = _cpus[i].loadIdle;
- cores[i].rawLoadIrq = _cpus[i].loadIrq;
- cores[i].rawLoadSteal = _cpus[i].loadSteal;
- cores[i].rawLoadGuest = _cpus[i].loadGuest;
- }
- let totalTick = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest + totalIdle;
- let totalLoad = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest;
- let currentTick = totalTick - _current_cpu.tick;
- result = {
- avgLoad: avgLoad,
- currentLoad: (totalLoad - _current_cpu.load) / currentTick * 100,
- currentLoadUser: (totalUser - _current_cpu.user) / currentTick * 100,
- currentLoadSystem: (totalSystem - _current_cpu.system) / currentTick * 100,
- currentLoadNice: (totalNice - _current_cpu.nice) / currentTick * 100,
- currentLoadIdle: (totalIdle - _current_cpu.idle) / currentTick * 100,
- currentLoadIrq: (totalIrq - _current_cpu.irq) / currentTick * 100,
- currentLoadSteal: (totalSteal - _current_cpu.steal) / currentTick * 100,
- currentLoadGuest: (totalGuest - _current_cpu.guest) / currentTick * 100,
- rawCurrentLoad: (totalLoad - _current_cpu.load),
- rawCurrentLoadUser: (totalUser - _current_cpu.user),
- rawCurrentLoadSystem: (totalSystem - _current_cpu.system),
- rawCurrentLoadNice: (totalNice - _current_cpu.nice),
- rawCurrentLoadIdle: (totalIdle - _current_cpu.idle),
- rawCurrentLoadIrq: (totalIrq - _current_cpu.irq),
- rawCurrentLoadSteal: (totalSteal - _current_cpu.steal),
- rawCurrentLoadGuest: (totalGuest - _current_cpu.guest),
- cpus: cores
- };
- _current_cpu = {
- user: totalUser,
- nice: totalNice,
- system: totalSystem,
- idle: totalIdle,
- irq: totalIrq,
- steal: totalSteal,
- guest: totalGuest,
- tick: totalTick,
- load: totalLoad,
- ms: _current_cpu.ms,
- currentLoad: result.currentLoad,
- currentLoadUser: result.currentLoadUser,
- currentLoadSystem: result.currentLoadSystem,
- currentLoadNice: result.currentLoadNice,
- currentLoadIdle: result.currentLoadIdle,
- currentLoadIrq: result.currentLoadIrq,
- currentLoadSteal: result.currentLoadSteal,
- currentLoadGuest: result.currentLoadGuest,
- rawCurrentLoad: result.rawCurrentLoad,
- rawCurrentLoadUser: result.rawCurrentLoadUser,
- rawCurrentLoadSystem: result.rawCurrentLoadSystem,
- rawCurrentLoadNice: result.rawCurrentLoadNice,
- rawCurrentLoadIdle: result.rawCurrentLoadIdle,
- rawCurrentLoadIrq: result.rawCurrentLoadIrq,
- rawCurrentLoadSteal: result.rawCurrentLoadSteal,
- rawCurrentLoadGuest: result.rawCurrentLoadGuest,
- };
- } else {
- let cores = [];
- for (let i = 0; i < _corecount; i++) {
- cores[i] = {};
- cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
- cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100;
- cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100;
- cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100;
- cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100;
- cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100;
- cores[i].rawLoad = _cpus[i].load;
- cores[i].rawLoadUser = _cpus[i].loadUser;
- cores[i].rawLoadSystem = _cpus[i].loadSystem;
- cores[i].rawLoadNice = _cpus[i].loadNice;
- cores[i].rawLoadIdle = _cpus[i].loadIdle;
- cores[i].rawLoadIrq = _cpus[i].loadIrq;
- cores[i].rawLoadSteal = _cpus[i].loadSteal;
- cores[i].rawLoadGuest = _cpus[i].loadGuest;
- }
- result = {
- avgLoad: avgLoad,
- currentLoad: _current_cpu.currentLoad,
- currentLoadUser: _current_cpu.currentLoadUser,
- currentLoadSystem: _current_cpu.currentLoadSystem,
- currentLoadNice: _current_cpu.currentLoadNice,
- currentLoadIdle: _current_cpu.currentLoadIdle,
- currentLoadIrq: _current_cpu.currentLoadIrq,
- currentLoadSteal: _current_cpu.currentLoadSteal,
- currentLoadGuest: _current_cpu.currentLoadGuest,
- rawCurrentLoad: _current_cpu.rawCurrentLoad,
- rawCurrentLoadUser: _current_cpu.rawCurrentLoadUser,
- rawCurrentLoadSystem: _current_cpu.rawCurrentLoadSystem,
- rawCurrentLoadNice: _current_cpu.rawCurrentLoadNice,
- rawCurrentLoadIdle: _current_cpu.rawCurrentLoadIdle,
- rawCurrentLoadIrq: _current_cpu.rawCurrentLoadIrq,
- rawCurrentLoadSteal: _current_cpu.rawCurrentLoadSteal,
- rawCurrentLoadGuest: _current_cpu.rawCurrentLoadGuest,
- cpus: cores
- };
- }
- resolve(result);
- });
- });
-}
-
-function currentLoad(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- getLoad().then(result => {
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- });
-}
-
-exports.currentLoad = currentLoad;
-
-// --------------------------
-// PS - full load
-// since bootup
-
-function getFullLoad() {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- const cpus = os.cpus();
- let totalUser = 0;
- let totalSystem = 0;
- let totalNice = 0;
- let totalIrq = 0;
- let totalIdle = 0;
-
- let result = 0;
-
- if (cpus && cpus.length) {
- for (let i = 0, len = cpus.length; i < len; i++) {
- const cpu = cpus[i].times;
- totalUser += cpu.user;
- totalSystem += cpu.sys;
- totalNice += cpu.nice;
- totalIrq += cpu.irq;
- totalIdle += cpu.idle;
- }
- let totalTicks = totalIdle + totalIrq + totalNice + totalSystem + totalUser;
- result = (totalTicks - totalIdle) / totalTicks * 100.0;
-
- }
- resolve(result);
- });
- });
-}
-
-function fullLoad(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- getFullLoad().then(result => {
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- });
-}
-
-exports.fullLoad = fullLoad;
-
-
-/***/ }),
-
-/***/ 31865:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// docker.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 13. Docker
-// ----------------------------------------------------------------------------------
-
-const util = __nccwpck_require__(33225);
-const DockerSocket = __nccwpck_require__(89364);
-
-let _platform = process.platform;
-const _windows = (_platform === 'win32');
-
-let _docker_container_stats = {};
-let _docker_socket;
-let _docker_last_read = 0;
-
-
-// --------------------------
-// get containers (parameter all: get also inactive/exited containers)
-
-function dockerInfo(callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
- const result = {};
-
- _docker_socket.getInfo((data) => {
- result.id = data.ID;
- result.containers = data.Containers;
- result.containersRunning = data.ContainersRunning;
- result.containersPaused = data.ContainersPaused;
- result.containersStopped = data.ContainersStopped;
- result.images = data.Images;
- result.driver = data.Driver;
- result.memoryLimit = data.MemoryLimit;
- result.swapLimit = data.SwapLimit;
- result.kernelMemory = data.KernelMemory;
- result.cpuCfsPeriod = data.CpuCfsPeriod;
- result.cpuCfsQuota = data.CpuCfsQuota;
- result.cpuShares = data.CPUShares;
- result.cpuSet = data.CPUSet;
- result.ipv4Forwarding = data.IPv4Forwarding;
- result.bridgeNfIptables = data.BridgeNfIptables;
- result.bridgeNfIp6tables = data.BridgeNfIp6tables;
- result.debug = data.Debug;
- result.nfd = data.NFd;
- result.oomKillDisable = data.OomKillDisable;
- result.ngoroutines = data.NGoroutines;
- result.systemTime = data.SystemTime;
- result.loggingDriver = data.LoggingDriver;
- result.cgroupDriver = data.CgroupDriver;
- result.nEventsListener = data.NEventsListener;
- result.kernelVersion = data.KernelVersion;
- result.operatingSystem = data.OperatingSystem;
- result.osType = data.OSType;
- result.architecture = data.Architecture;
- result.ncpu = data.NCPU;
- result.memTotal = data.MemTotal;
- result.dockerRootDir = data.DockerRootDir;
- result.httpProxy = data.HttpProxy;
- result.httpsProxy = data.HttpsProxy;
- result.noProxy = data.NoProxy;
- result.name = data.Name;
- result.labels = data.Labels;
- result.experimentalBuild = data.ExperimentalBuild;
- result.serverVersion = data.ServerVersion;
- result.clusterStore = data.ClusterStore;
- result.clusterAdvertise = data.ClusterAdvertise;
- result.defaultRuntime = data.DefaultRuntime;
- result.liveRestoreEnabled = data.LiveRestoreEnabled;
- result.isolation = data.Isolation;
- result.initBinary = data.InitBinary;
- result.productLicense = data.ProductLicense;
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- });
-}
-
-exports.dockerInfo = dockerInfo;
-
-function dockerImages(all, callback) {
-
- // fallback - if only callback is given
- if (util.isFunction(all) && !callback) {
- callback = all;
- all = false;
- }
- if (typeof all === 'string' && all === 'true') {
- all = true;
- }
- if (typeof all !== 'boolean' && all !== undefined) {
- all = false;
- }
-
- all = all || false;
- let result = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
- const workload = [];
-
- _docker_socket.listImages(all, data => {
- let dockerImages = {};
- try {
- dockerImages = data;
- if (dockerImages && Object.prototype.toString.call(dockerImages) === '[object Array]' && dockerImages.length > 0) {
-
- dockerImages.forEach(function (element) {
-
- if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) {
- element.Name = element.Names[0].replace(/^\/|\/$/g, '');
- }
- workload.push(dockerImagesInspect(element.Id.trim(), element));
- });
- if (workload.length) {
- Promise.all(
- workload
- ).then((data) => {
- if (callback) { callback(data); }
- resolve(data);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } catch (err) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
- });
-}
-
-// --------------------------
-// container inspect (for one container)
-
-function dockerImagesInspect(imageID, payload) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- imageID = imageID || '';
- if (typeof imageID !== 'string') {
- return resolve();
- }
- const imageIDSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(imageID, true)).trim();
- if (imageIDSanitized) {
-
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
-
- _docker_socket.inspectImage(imageIDSanitized.trim(), data => {
- try {
- resolve({
- id: payload.Id,
- container: data.Container,
- comment: data.Comment,
- os: data.Os,
- architecture: data.Architecture,
- parent: data.Parent,
- dockerVersion: data.DockerVersion,
- size: data.Size,
- sharedSize: payload.SharedSize,
- virtualSize: data.VirtualSize,
- author: data.Author,
- created: data.Created ? Math.round(new Date(data.Created).getTime() / 1000) : 0,
- containerConfig: data.ContainerConfig ? data.ContainerConfig : {},
- graphDriver: data.GraphDriver ? data.GraphDriver : {},
- repoDigests: data.RepoDigests ? data.RepoDigests : {},
- repoTags: data.RepoTags ? data.RepoTags : {},
- config: data.Config ? data.Config : {},
- rootFS: data.RootFS ? data.RootFS : {},
- });
- } catch (err) {
- resolve();
- }
- });
- } else {
- resolve();
- }
- });
- });
-}
-
-exports.dockerImages = dockerImages;
-
-function dockerContainers(all, callback) {
-
- function inContainers(containers, id) {
- let filtered = containers.filter(obj => {
- /**
- * @namespace
- * @property {string} Id
- */
- return (obj.Id && (obj.Id === id));
- });
- return (filtered.length > 0);
- }
-
- // fallback - if only callback is given
- if (util.isFunction(all) && !callback) {
- callback = all;
- all = false;
- }
- if (typeof all === 'string' && all === 'true') {
- all = true;
- }
- if (typeof all !== 'boolean' && all !== undefined) {
- all = false;
- }
-
- all = all || false;
- let result = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
- const workload = [];
-
- _docker_socket.listContainers(all, data => {
- let docker_containers = {};
- try {
- docker_containers = data;
- if (docker_containers && Object.prototype.toString.call(docker_containers) === '[object Array]' && docker_containers.length > 0) {
- // GC in _docker_container_stats
- for (let key in _docker_container_stats) {
- if ({}.hasOwnProperty.call(_docker_container_stats, key)) {
- if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; }
- }
- }
-
- docker_containers.forEach(function (element) {
-
- if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) {
- element.Name = element.Names[0].replace(/^\/|\/$/g, '');
- }
- workload.push(dockerContainerInspect(element.Id.trim(), element));
- });
- if (workload.length) {
- Promise.all(
- workload
- ).then((data) => {
- if (callback) { callback(data); }
- resolve(data);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } catch (err) {
- // GC in _docker_container_stats
- for (let key in _docker_container_stats) {
- if ({}.hasOwnProperty.call(_docker_container_stats, key)) {
- if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; }
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
- });
-}
-
-// --------------------------
-// container inspect (for one container)
-
-function dockerContainerInspect(containerID, payload) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- containerID = containerID || '';
- if (typeof containerID !== 'string') {
- return resolve();
- }
- const containerIdSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerID, true)).trim();
- if (containerIdSanitized) {
-
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
-
- _docker_socket.getInspect(containerIdSanitized.trim(), data => {
- try {
- resolve({
- id: payload.Id,
- name: payload.Name,
- image: payload.Image,
- imageID: payload.ImageID,
- command: payload.Command,
- created: payload.Created,
- started: data.State && data.State.StartedAt ? Math.round(new Date(data.State.StartedAt).getTime() / 1000) : 0,
- finished: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? Math.round(new Date(data.State.FinishedAt).getTime() / 1000) : 0,
- createdAt: data.Created ? data.Created : '',
- startedAt: data.State && data.State.StartedAt ? data.State.StartedAt : '',
- finishedAt: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? data.State.FinishedAt : '',
- state: payload.State,
- restartCount: data.RestartCount || 0,
- platform: data.Platform || '',
- driver: data.Driver || '',
- ports: payload.Ports,
- mounts: payload.Mounts,
- // hostconfig: payload.HostConfig,
- // network: payload.NetworkSettings
- });
- } catch (err) {
- resolve();
- }
- });
- } else {
- resolve();
- }
- });
- });
-}
-
-exports.dockerContainers = dockerContainers;
-
-// --------------------------
-// helper functions for calculation of docker stats
-
-function docker_calcCPUPercent(cpu_stats, precpu_stats) {
- /**
- * @namespace
- * @property {object} cpu_usage
- * @property {number} cpu_usage.total_usage
- * @property {number} system_cpu_usage
- * @property {object} cpu_usage
- * @property {Array} cpu_usage.percpu_usage
- */
-
- if (!_windows) {
- let cpuPercent = 0.0;
- // calculate the change for the cpu usage of the container in between readings
- let cpuDelta = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
- // calculate the change for the entire system between readings
- let systemDelta = cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage;
-
- if (systemDelta > 0.0 && cpuDelta > 0.0) {
- // calculate the change for the cpu usage of the container in between readings
- if (precpu_stats.online_cpus) {
- cpuPercent = (cpuDelta / systemDelta) * precpu_stats.online_cpus * 100.0;
- }
- else {
- cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0;
- }
- }
-
- return cpuPercent;
- } else {
- let nanoSecNow = util.nanoSeconds();
- let cpuPercent = 0.0;
- if (_docker_last_read > 0) {
- let possIntervals = (nanoSecNow - _docker_last_read); // / 100 * os.cpus().length;
- let intervalsUsed = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
- if (possIntervals > 0) {
- cpuPercent = 100.0 * intervalsUsed / possIntervals;
- }
- }
- _docker_last_read = nanoSecNow;
- return cpuPercent;
- }
-}
-
-function docker_calcNetworkIO(networks) {
- let rx;
- let wx;
- for (let key in networks) {
- // skip loop if the property is from prototype
- if (!{}.hasOwnProperty.call(networks, key)) { continue; }
-
- /**
- * @namespace
- * @property {number} rx_bytes
- * @property {number} tx_bytes
- */
- let obj = networks[key];
- rx = +obj.rx_bytes;
- wx = +obj.tx_bytes;
- }
- return {
- rx,
- wx
- };
-}
-
-function docker_calcBlockIO(blkio_stats) {
- let result = {
- r: 0,
- w: 0
- };
-
- /**
- * @namespace
- * @property {Array} io_service_bytes_recursive
- */
- if (blkio_stats && blkio_stats.io_service_bytes_recursive && Object.prototype.toString.call(blkio_stats.io_service_bytes_recursive) === '[object Array]' && blkio_stats.io_service_bytes_recursive.length > 0) {
- blkio_stats.io_service_bytes_recursive.forEach(function (element) {
- /**
- * @namespace
- * @property {string} op
- * @property {number} value
- */
-
- if (element.op && element.op.toLowerCase() === 'read' && element.value) {
- result.r += element.value;
- }
- if (element.op && element.op.toLowerCase() === 'write' && element.value) {
- result.w += element.value;
- }
- });
- }
- return result;
-}
-
-function dockerContainerStats(containerIDs, callback) {
-
- let containerArray = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- // fallback - if only callback is given
- if (util.isFunction(containerIDs) && !callback) {
- callback = containerIDs;
- containerArray = ['*'];
- } else {
- containerIDs = containerIDs || '*';
- if (typeof containerIDs !== 'string') {
- if (callback) { callback([]); }
- return resolve([]);
- }
- let containerIDsSanitized = '';
- try {
- containerIDsSanitized.__proto__.toLowerCase = util.stringToLower;
- containerIDsSanitized.__proto__.replace = util.stringReplace;
- containerIDsSanitized.__proto__.trim = util.stringTrim;
- } catch (e) {
- Object.setPrototypeOf(containerIDsSanitized, util.stringObj);
- }
-
- containerIDsSanitized = containerIDs;
- containerIDsSanitized = containerIDsSanitized.trim();
- if (containerIDsSanitized !== '*') {
- containerIDsSanitized = '';
- const s = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerIDs, true)).trim();
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- s[i].__proto__.toLowerCase = util.stringToLower;
- const sl = s[i].toLowerCase();
- if (sl && sl[0] && !sl[1]) {
- containerIDsSanitized = containerIDsSanitized + sl[0];
- }
- }
- }
- }
-
- containerIDsSanitized = containerIDsSanitized.trim().toLowerCase().replace(/,+/g, '|');
- containerArray = containerIDsSanitized.split('|');
- }
-
- const result = [];
-
- const workload = [];
- if (containerArray.length && containerArray[0].trim() === '*') {
- containerArray = [];
- dockerContainers().then(allContainers => {
- for (let container of allContainers) {
- containerArray.push(container.id.substring(0, 12));
- }
- if (containerArray.length) {
- dockerContainerStats(containerArray.join(',')).then(result => {
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } else {
- for (let containerID of containerArray) {
- workload.push(dockerContainerStatsSingle(containerID.trim()));
- }
- if (workload.length) {
- Promise.all(
- workload
- ).then((data) => {
- if (callback) { callback(data); }
- resolve(data);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-// --------------------------
-// container stats (for one container)
-
-function dockerContainerStatsSingle(containerID) {
- containerID = containerID || '';
- let result = {
- id: containerID,
- memUsage: 0,
- memLimit: 0,
- memPercent: 0,
- cpuPercent: 0,
- pids: 0,
- netIO: {
- rx: 0,
- wx: 0
- },
- blockIO: {
- r: 0,
- w: 0
- },
- restartCount: 0,
- cpuStats: {},
- precpuStats: {},
- memoryStats: {},
- networks: {},
- };
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (containerID) {
-
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
-
- _docker_socket.getInspect(containerID, dataInspect => {
- try {
- _docker_socket.getStats(containerID, data => {
- try {
- let stats = data;
- if (!stats.message) {
- if (data.id) { result.id = data.id; }
- result.memUsage = (stats.memory_stats && stats.memory_stats.usage ? stats.memory_stats.usage : 0);
- result.memLimit = (stats.memory_stats && stats.memory_stats.limit ? stats.memory_stats.limit : 0);
- result.memPercent = (stats.memory_stats && stats.memory_stats.usage && stats.memory_stats.limit ? stats.memory_stats.usage / stats.memory_stats.limit * 100.0 : 0);
- result.cpuPercent = (stats.cpu_stats && stats.precpu_stats ? docker_calcCPUPercent(stats.cpu_stats, stats.precpu_stats) : 0);
- result.pids = (stats.pids_stats && stats.pids_stats.current ? stats.pids_stats.current : 0);
- result.restartCount = (dataInspect.RestartCount ? dataInspect.RestartCount : 0);
- if (stats.networks) { result.netIO = docker_calcNetworkIO(stats.networks); }
- if (stats.blkio_stats) { result.blockIO = docker_calcBlockIO(stats.blkio_stats); }
- result.cpuStats = (stats.cpu_stats ? stats.cpu_stats : {});
- result.precpuStats = (stats.precpu_stats ? stats.precpu_stats : {});
- result.memoryStats = (stats.memory_stats ? stats.memory_stats : {});
- result.networks = (stats.networks ? stats.networks : {});
- }
- } catch (err) {
- util.noop();
- }
- // }
- resolve(result);
- });
- } catch (err) {
- util.noop();
- }
- });
- } else {
- resolve(result);
- }
- });
- });
-}
-
-exports.dockerContainerStats = dockerContainerStats;
-
-// --------------------------
-// container processes (for one container)
-
-function dockerContainerProcesses(containerID, callback) {
- let result = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
- containerID = containerID || '';
- if (typeof containerID !== 'string') {
- return resolve(result);
- }
- const containerIdSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerID, true)).trim();
-
- if (containerIdSanitized) {
-
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
-
- _docker_socket.getProcesses(containerIdSanitized, data => {
- /**
- * @namespace
- * @property {Array} Titles
- * @property {Array} Processes
- **/
- try {
- if (data && data.Titles && data.Processes) {
- let titles = data.Titles.map(function (value) {
- return value.toUpperCase();
- });
- let pos_pid = titles.indexOf('PID');
- let pos_ppid = titles.indexOf('PPID');
- let pos_pgid = titles.indexOf('PGID');
- let pos_vsz = titles.indexOf('VSZ');
- let pos_time = titles.indexOf('TIME');
- let pos_elapsed = titles.indexOf('ELAPSED');
- let pos_ni = titles.indexOf('NI');
- let pos_ruser = titles.indexOf('RUSER');
- let pos_user = titles.indexOf('USER');
- let pos_rgroup = titles.indexOf('RGROUP');
- let pos_group = titles.indexOf('GROUP');
- let pos_stat = titles.indexOf('STAT');
- let pos_rss = titles.indexOf('RSS');
- let pos_command = titles.indexOf('COMMAND');
-
- data.Processes.forEach(process => {
- result.push({
- pidHost: (pos_pid >= 0 ? process[pos_pid] : ''),
- ppid: (pos_ppid >= 0 ? process[pos_ppid] : ''),
- pgid: (pos_pgid >= 0 ? process[pos_pgid] : ''),
- user: (pos_user >= 0 ? process[pos_user] : ''),
- ruser: (pos_ruser >= 0 ? process[pos_ruser] : ''),
- group: (pos_group >= 0 ? process[pos_group] : ''),
- rgroup: (pos_rgroup >= 0 ? process[pos_rgroup] : ''),
- stat: (pos_stat >= 0 ? process[pos_stat] : ''),
- time: (pos_time >= 0 ? process[pos_time] : ''),
- elapsed: (pos_elapsed >= 0 ? process[pos_elapsed] : ''),
- nice: (pos_ni >= 0 ? process[pos_ni] : ''),
- rss: (pos_rss >= 0 ? process[pos_rss] : ''),
- vsz: (pos_vsz >= 0 ? process[pos_vsz] : ''),
- command: (pos_command >= 0 ? process[pos_command] : '')
- });
- });
- }
- } catch (err) {
- util.noop();
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
-}
-
-exports.dockerContainerProcesses = dockerContainerProcesses;
-
-function dockerVolumes(callback) {
-
- let result = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (!_docker_socket) {
- _docker_socket = new DockerSocket();
- }
- _docker_socket.listVolumes((data) => {
- let dockerVolumes = {};
- try {
- dockerVolumes = data;
- if (dockerVolumes && dockerVolumes.Volumes && Object.prototype.toString.call(dockerVolumes.Volumes) === '[object Array]' && dockerVolumes.Volumes.length > 0) {
-
- dockerVolumes.Volumes.forEach(function (element) {
-
- result.push({
- name: element.Name,
- driver: element.Driver,
- labels: element.Labels,
- mountpoint: element.Mountpoint,
- options: element.Options,
- scope: element.Scope,
- created: element.CreatedAt ? Math.round(new Date(element.CreatedAt).getTime() / 1000) : 0,
- });
- });
- if (callback) { callback(result); }
- resolve(result);
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } catch (err) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
- });
-}
-
-exports.dockerVolumes = dockerVolumes;
-
-function dockerAll(callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- dockerContainers(true).then(result => {
- if (result && Object.prototype.toString.call(result) === '[object Array]' && result.length > 0) {
- let l = result.length;
- result.forEach(function (element) {
- dockerContainerStats(element.id).then((res) => {
- // include stats in array
- element.memUsage = res[0].memUsage;
- element.memLimit = res[0].memLimit;
- element.memPercent = res[0].memPercent;
- element.cpuPercent = res[0].cpuPercent;
- element.pids = res[0].pids;
- element.netIO = res[0].netIO;
- element.blockIO = res[0].blockIO;
- element.cpuStats = res[0].cpuStats;
- element.precpuStats = res[0].precpuStats;
- element.memoryStats = res[0].memoryStats;
- element.networks = res[0].networks;
-
- dockerContainerProcesses(element.id).then(processes => {
- element.processes = processes;
-
- l -= 1;
- if (l === 0) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- // all done??
- });
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
- });
-}
-
-exports.dockerAll = dockerAll;
-
-
-/***/ }),
-
-/***/ 89364:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// dockerSockets.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 13. DockerSockets
-// ----------------------------------------------------------------------------------
-
-const net = __nccwpck_require__(69278);
-const isWin = (__nccwpck_require__(70857).type)() === 'Windows_NT';
-const socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock';
-
-class DockerSocket {
-
- getInfo(callback) {
- try {
-
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/info HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- }
-
- listImages(all, callback) {
- try {
-
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/images/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- }
-
- inspectImage(id, callback) {
- id = id || '';
- if (id) {
- try {
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/images/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- } else {
- callback({});
- }
- }
-
- listContainers(all, callback) {
- try {
-
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/containers/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- }
-
- getStats(id, callback) {
- id = id || '';
- if (id) {
- try {
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/containers/' + id + '/stats?stream=0 HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- } else {
- callback({});
- }
- }
-
- getInspect(id, callback) {
- id = id || '';
- if (id) {
- try {
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/containers/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- } else {
- callback({});
- }
- }
-
- getProcesses(id, callback) {
- id = id || '';
- if (id) {
- try {
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/containers/' + id + '/top?ps_args=-opid,ppid,pgid,vsz,time,etime,nice,ruser,user,rgroup,group,stat,rss,args HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- } else {
- callback({});
- }
- }
-
- listVolumes(callback) {
- try {
-
- let socket = net.createConnection({ path: socketPath });
- let alldata = '';
- let data;
-
- socket.on('connect', () => {
- socket.write('GET http:/volumes HTTP/1.0\r\n\r\n');
- });
-
- socket.on('data', data => {
- alldata = alldata + data.toString();
- });
-
- socket.on('error', () => {
- socket = false;
- callback({});
- });
-
- socket.on('end', () => {
- let startbody = alldata.indexOf('\r\n\r\n');
- alldata = alldata.substring(startbody + 4);
- socket = false;
- try {
- data = JSON.parse(alldata);
- callback(data);
- } catch (err) {
- callback({});
- }
- });
- } catch (err) {
- callback({});
- }
- }
-}
-
-module.exports = DockerSocket;
-
-
-/***/ }),
-
-/***/ 43022:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// filesystem.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 8. File System
-// ----------------------------------------------------------------------------------
-
-const util = __nccwpck_require__(33225);
-const fs = __nccwpck_require__(79896);
-
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const execPromiseSave = util.promisifySave((__nccwpck_require__(35317).exec));
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-let _fs_speed = {};
-let _disk_io = {};
-
-// --------------------------
-// FS - mounted file systems
-
-function fsSize(drive, callback) {
-
- if (util.isFunction(drive)) {
- callback = drive;
- drive = '';
- }
-
- let macOsDisks = [];
- let osMounts = [];
-
- function getmacOsFsType(fs) {
- if (!fs.startsWith('/')) { return 'NFS'; }
- const parts = fs.split('/');
- const fsShort = parts[parts.length - 1];
- const macOsDisksSingle = macOsDisks.filter(item => item.indexOf(fsShort) >= 0);
- if (macOsDisksSingle.length === 1 && macOsDisksSingle[0].indexOf('APFS') >= 0) { return 'APFS'; }
- return 'HFS';
- }
-
- function isLinuxTmpFs(fs) {
- const linuxTmpFileSystems = ['rootfs', 'unionfs', 'squashfs', 'cramfs', 'initrd', 'initramfs', 'devtmpfs', 'tmpfs', 'udev', 'devfs', 'specfs', 'type', 'appimaged'];
- let result = false;
- linuxTmpFileSystems.forEach(linuxFs => {
- if (fs.toLowerCase().indexOf(linuxFs) >= 0) { result = true; }
- });
- return result;
- }
-
- function filterLines(stdout) {
- let lines = stdout.toString().split('\n');
- lines.shift();
- if (stdout.toString().toLowerCase().indexOf('filesystem')) {
- let removeLines = 0;
- for (let i = 0; i < lines.length; i++) {
- if (lines[i] && lines[i].toLowerCase().startsWith('filesystem')) {
- removeLines = i;
- }
- }
- for (let i = 0; i < removeLines; i++) {
- lines.shift();
- }
- }
- return lines;
- }
-
- function parseDf(lines) {
- let data = [];
- lines.forEach(function (line) {
- if (line !== '') {
- line = line.replace(/ +/g, ' ').split(' ');
- if (line && ((line[0].startsWith('/')) || (line[6] && line[6] === '/') || (line[0].indexOf('/') > 0) || (line[0].indexOf(':') === 1) || !_darwin && !isLinuxTmpFs(line[1]))) {
- const fs = line[0];
- const fsType = ((_linux || _freebsd || _openbsd || _netbsd) ? line[1] : getmacOsFsType(line[0]));
- const size = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[2] : line[1])) * 1024;
- const used = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[3] : line[2])) * 1024;
- const available = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[4] : line[3])) * 1024;
- const use = parseFloat((100.0 * (used / (used + available))).toFixed(2));
- let rw = osMounts && Object.keys(osMounts).length > 0 ? osMounts[fs] || false : null;
- line.splice(0, (_linux || _freebsd || _openbsd || _netbsd) ? 6 : 5);
- const mount = line.join(' ');
- if (!data.find(el => (el.fs === fs && el.type === fsType))) {
- data.push({
- fs,
- type: fsType,
- size,
- used,
- available,
- use,
- mount,
- rw
- });
- }
- }
- }
- });
- return data;
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let data = [];
- if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
- let cmd = '';
- macOsDisks = [];
- osMounts = {};
- if (_darwin) {
- cmd = 'df -kP';
- try {
- macOsDisks = execSync('diskutil list').toString().split('\n').filter(line => {
- return !line.startsWith('/') && line.indexOf(':') > 0;
- });
- execSync('mount').toString().split('\n').filter(line => {
- return line.startsWith('/');
- }).forEach((line) => {
- osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1;
- });
- } catch (e) {
- util.noop();
- }
- }
- if (_linux) {
- try {
- cmd = 'export LC_ALL=C; df -lkPTx squashfs; unset LC_ALL';
- execSync('cat /proc/mounts 2>/dev/null', util.execOptsLinux).toString().split('\n').filter(line => {
- return line.startsWith('/');
- }).forEach((line) => {
- osMounts[line.split(' ')[0]] = osMounts[line.split(' ')[0]] || false;
- if (line.toLowerCase().indexOf('/snap/') === -1) {
- osMounts[line.split(' ')[0]] = ((line.toLowerCase().indexOf('rw,') >= 0 || line.toLowerCase().indexOf(' rw ') >= 0));
- }
- });
- } catch (e) {
- util.noop();
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- try {
- cmd = 'df -lkPT';
- execSync('mount').toString().split('\n').forEach((line) => {
- osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1;
- });
- } catch (e) {
- util.noop();
- }
- }
- exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- let lines = filterLines(stdout);
- data = parseDf(lines);
- if (drive) {
- data = data.filter(item => {
- return item.fs.toLowerCase().indexOf(drive.toLowerCase()) >= 0 || item.mount.toLowerCase().indexOf(drive.toLowerCase()) >= 0;
- });
- }
- if ((!error || data.length) && stdout.toString().trim() !== '') {
- if (callback) {
- callback(data);
- }
- resolve(data);
- } else {
- exec('df -kPT', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = filterLines(stdout);
- data = parseDf(lines);
- }
- if (callback) {
- callback(data);
- }
- resolve(data);
- });
- }
- });
- }
- if (_sunos) {
- if (callback) { callback(data); }
- resolve(data);
- }
- if (_windows) {
- try {
- const cmd = `Get-WmiObject Win32_logicaldisk | select Access,Caption,FileSystem,FreeSpace,Size ${drive ? '| where -property Caption -eq ' + drive : ''} | fl`;
- util.powerShell(cmd).then((stdout, error) => {
- if (!error) {
- let devices = stdout.toString().split(/\n\s*\n/);
- devices.forEach(function (device) {
- let lines = device.split('\r\n');
- const size = util.toInt(util.getValue(lines, 'size', ':'));
- const free = util.toInt(util.getValue(lines, 'freespace', ':'));
- const caption = util.getValue(lines, 'caption', ':');
- const rwValue = util.getValue(lines, 'access', ':');
- const rw = rwValue ? (util.toInt(rwValue) !== 1) : null;
- if (size) {
- data.push({
- fs: caption,
- type: util.getValue(lines, 'filesystem', ':'),
- size,
- used: size - free,
- available: free,
- use: parseFloat(((100.0 * (size - free)) / size).toFixed(2)),
- mount: caption,
- rw
- });
- }
- });
- }
- if (callback) {
- callback(data);
- }
- resolve(data);
- });
- } catch (e) {
- if (callback) { callback(data); }
- resolve(data);
- }
- }
- });
- });
-}
-
-exports.fsSize = fsSize;
-
-// --------------------------
-// FS - open files count
-
-function fsOpenFiles(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- const result = {
- max: null,
- allocated: null,
- available: null
- };
- if (_freebsd || _openbsd || _netbsd || _darwin) {
- let cmd = 'sysctl -i kern.maxfiles kern.num_files kern.open_files';
- exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result.max = parseInt(util.getValue(lines, 'kern.maxfiles', ':'), 10);
- result.allocated = parseInt(util.getValue(lines, 'kern.num_files', ':'), 10) || parseInt(util.getValue(lines, 'kern.open_files', ':'), 10);
- result.available = result.max - result.allocated;
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_linux) {
- fs.readFile('/proc/sys/fs/file-nr', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines[0]) {
- const parts = lines[0].replace(/\s+/g, ' ').split(' ');
- if (parts.length === 3) {
- result.allocated = parseInt(parts[0], 10);
- result.available = parseInt(parts[1], 10);
- result.max = parseInt(parts[2], 10);
- if (!result.available) { result.available = result.max - result.allocated; }
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else {
- fs.readFile('/proc/sys/fs/file-max', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines[0]) {
- result.max = parseInt(lines[0], 10);
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- });
- }
- if (_sunos) {
- if (callback) { callback(null); }
- resolve(null);
- }
- if (_windows) {
- if (callback) { callback(null); }
- resolve(null);
- }
- });
- });
-}
-
-exports.fsOpenFiles = fsOpenFiles;
-
-// --------------------------
-// disks
-
-function parseBytes(s) {
- return parseInt(s.substr(s.indexOf(' (') + 2, s.indexOf(' Bytes)') - 10));
-}
-
-function parseDevices(lines) {
- let devices = [];
- let i = 0;
- lines.forEach(line => {
- if (line.length > 0) {
- if (line[0] === '*') {
- i++;
- } else {
- let parts = line.split(':');
- if (parts.length > 1) {
- if (!devices[i]) {
- devices[i] = {
- name: '',
- identifier: '',
- type: 'disk',
- fsType: '',
- mount: '',
- size: 0,
- physical: 'HDD',
- uuid: '',
- label: '',
- model: '',
- serial: '',
- removable: false,
- protocol: '',
- group: '',
- device: ''
- };
- }
- parts[0] = parts[0].trim().toUpperCase().replace(/ +/g, '');
- parts[1] = parts[1].trim();
- if ('DEVICEIDENTIFIER' === parts[0]) { devices[i].identifier = parts[1]; }
- if ('DEVICENODE' === parts[0]) { devices[i].name = parts[1]; }
- if ('VOLUMENAME' === parts[0]) {
- if (parts[1].indexOf('Not applicable') === -1) { devices[i].label = parts[1]; }
- }
- if ('PROTOCOL' === parts[0]) { devices[i].protocol = parts[1]; }
- if ('DISKSIZE' === parts[0]) { devices[i].size = parseBytes(parts[1]); }
- if ('FILESYSTEMPERSONALITY' === parts[0]) { devices[i].fsType = parts[1]; }
- if ('MOUNTPOINT' === parts[0]) { devices[i].mount = parts[1]; }
- if ('VOLUMEUUID' === parts[0]) { devices[i].uuid = parts[1]; }
- if ('READ-ONLYMEDIA' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'CD/DVD'; }
- if ('SOLIDSTATE' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'SSD'; }
- if ('VIRTUAL' === parts[0]) { devices[i].type = 'virtual'; }
- if ('REMOVABLEMEDIA' === parts[0]) { devices[i].removable = (parts[1] === 'Removable'); }
- if ('PARTITIONTYPE' === parts[0]) { devices[i].type = 'part'; }
- if ('DEVICE/MEDIANAME' === parts[0]) { devices[i].model = parts[1]; }
- }
- }
- }
- });
- return devices;
-}
-
-function parseBlk(lines) {
- let data = [];
-
- lines.filter(line => line !== '').forEach((line) => {
- try {
- line = decodeURIComponent(line.replace(/\\x/g, '%'));
- line = line.replace(/\\/g, '\\\\');
- let disk = JSON.parse(line);
- data.push({
- 'name': disk.name,
- 'type': disk.type,
- 'fsType': disk.fsType,
- 'mount': disk.mountpoint,
- 'size': parseInt(disk.size),
- 'physical': (disk.type === 'disk' ? (disk.rota === '0' ? 'SSD' : 'HDD') : (disk.type === 'rom' ? 'CD/DVD' : '')),
- 'uuid': disk.uuid,
- 'label': disk.label,
- 'model': (disk.model || '').trim(),
- 'serial': disk.serial,
- 'removable': disk.rm === '1',
- 'protocol': disk.tran,
- 'group': disk.group || '',
- });
- } catch (e) {
- util.noop();
- }
- });
- data = util.unique(data);
- data = util.sortByKey(data, ['type', 'name']);
- return data;
-}
-
-function decodeMdabmData(lines) {
- const raid = util.getValue(lines, 'md_level', '=');
- const label = util.getValue(lines, 'md_name', '='); // <- get label info
- const uuid = util.getValue(lines, 'md_uuid', '='); // <- get uuid info
- const members = [];
- lines.forEach(line => {
- if (line.toLowerCase().startsWith('md_device_dev') && line.toLowerCase().indexOf('/dev/') > 0) {
- members.push(line.split('/dev/')[1]);
- }
- });
- return {
- raid,
- label,
- uuid,
- members
- };
-}
-
-function raidMatchLinux(data) {
- // for all block devices of type "raid%"
- let result = data;
- try {
- data.forEach(element => {
- if (element.type.startsWith('raid')) {
- const lines = execSync(`mdadm --export --detail /dev/${element.name}`, util.execOptsLinux).toString().split('\n');
- const mdData = decodeMdabmData(lines);
-
- element.label = mdData.label; // <- assign label info
- element.uuid = mdData.uuid; // <- assign uuid info
-
- if (mdData.members && mdData.members.length && mdData.raid === element.type) {
- result = result.map(blockdevice => {
- if (blockdevice.fsType === 'linux_raid_member' && mdData.members.indexOf(blockdevice.name) >= 0) {
- blockdevice.group = element.name;
- }
- return blockdevice;
- });
- }
- }
- });
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function getDevicesLinux(data) {
- const result = [];
- data.forEach(element => {
- if (element.type.startsWith('disk')) {
- result.push(element.name);
- }
- });
- return result;
-}
-
-function matchDevicesLinux(data) {
- let result = data;
- try {
- const devices = getDevicesLinux(data);
- result = result.map(blockdevice => {
- if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk')) {
- devices.forEach(element => {
- if (blockdevice.name.startsWith(element)) {
- blockdevice.device = '/dev/' + element;
- }
- });
- }
- return blockdevice;
- });
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function getDevicesMac(data) {
- const result = [];
- data.forEach(element => {
- if (element.type.startsWith('disk')) {
- result.push({ name: element.name, model: element.model, device: element.name });
- }
- if (element.type.startsWith('virtual')) {
- let device = '';
- result.forEach(e => {
- if (e.model === element.model) {
- device = e.device;
- }
- });
- if (device) {
- result.push({ name: element.name, model: element.model, device });
- }
- }
- });
- return result;
-}
-
-function matchDevicesMac(data) {
- let result = data;
- try {
- const devices = getDevicesMac(data);
- result = result.map(blockdevice => {
- if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk') || blockdevice.type.startsWith('virtual')) {
- devices.forEach(element => {
- if (blockdevice.name.startsWith(element.name)) {
- blockdevice.device = element.device;
- }
- });
- }
- return blockdevice;
- });
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function getDevicesWin(diskDrives) {
- const result = [];
- diskDrives.forEach(element => {
- const lines = element.split('\r\n');
- const device = util.getValue(lines, 'DeviceID', ':');
- let partitions = element.split('@{DeviceID=');
- if (partitions.length > 1) {
- partitions = partitions.slice(1);
- partitions.forEach(partition => {
- result.push({ name: partition.split(';')[0].toUpperCase(), device });
- });
- }
- });
- return result;
-}
-
-function matchDevicesWin(data, diskDrives) {
- const devices = getDevicesWin(diskDrives);
- data.map(element => {
- const filteresDevices = devices.filter((e) => { return e.name === element.name.toUpperCase(); });
- if (filteresDevices.length > 0) {
- element.device = filteresDevices[0].device;
- }
- return element;
- });
- return data;
-}
-
-function blkStdoutToObject(stdout) {
- return stdout.toString()
- .replace(/NAME=/g, '{"name":')
- .replace(/FSTYPE=/g, ',"fsType":')
- .replace(/TYPE=/g, ',"type":')
- .replace(/SIZE=/g, ',"size":')
- .replace(/MOUNTPOINT=/g, ',"mountpoint":')
- .replace(/UUID=/g, ',"uuid":')
- .replace(/ROTA=/g, ',"rota":')
- .replace(/RO=/g, ',"ro":')
- .replace(/RM=/g, ',"rm":')
- .replace(/TRAN=/g, ',"tran":')
- .replace(/SERIAL=/g, ',"serial":')
- .replace(/LABEL=/g, ',"label":')
- .replace(/MODEL=/g, ',"model":')
- .replace(/OWNER=/g, ',"owner":')
- .replace(/GROUP=/g, ',"group":')
- .replace(/\n/g, '}\n');
-}
-
-function blockDevices(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let data = [];
- if (_linux) {
- // see https://wiki.ubuntuusers.de/lsblk/
- // exec("lsblk -bo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,TRAN,SERIAL,LABEL,MODEL,OWNER,GROUP,MODE,ALIGNMENT,MIN-IO,OPT-IO,PHY-SEC,LOG-SEC,SCHED,RQ-SIZE,RA,WSAME", function (error, stdout) {
- exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,TRAN,SERIAL,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = blkStdoutToObject(stdout).split('\n');
- data = parseBlk(lines);
- data = raidMatchLinux(data);
- data = matchDevicesLinux(data);
- if (callback) {
- callback(data);
- }
- resolve(data);
- } else {
- exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = blkStdoutToObject(stdout).split('\n');
- data = parseBlk(lines);
- data = raidMatchLinux(data);
- }
- if (callback) {
- callback(data);
- }
- resolve(data);
- });
- }
- });
- }
- if (_darwin) {
- exec('diskutil info -all', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- // parse lines into temp array of devices
- data = parseDevices(lines);
- data = matchDevicesMac(data);
- }
- if (callback) {
- callback(data);
- }
- resolve(data);
- });
- }
- if (_sunos) {
- if (callback) { callback(data); }
- resolve(data);
- }
- if (_windows) {
- let drivetypes = ['Unknown', 'NoRoot', 'Removable', 'Local', 'Network', 'CD/DVD', 'RAM'];
- try {
- // util.wmic('logicaldisk get Caption,Description,DeviceID,DriveType,FileSystem,FreeSpace,Name,Size,VolumeName,VolumeSerialNumber /value').then((stdout, error) => {
- // util.powerShell('Get-CimInstance Win32_logicaldisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl').then((stdout, error) => {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance -ClassName Win32_LogicalDisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl'));
- workload.push(util.powerShell('Get-WmiObject -Class Win32_diskdrive | Select-Object -Property PNPDeviceId,DeviceID, Model, Size, @{L=\'Partitions\'; E={$_.GetRelated(\'Win32_DiskPartition\').GetRelated(\'Win32_LogicalDisk\') | Select-Object -Property DeviceID, VolumeName, Size, FreeSpace}} | fl'));
- util.promiseAll(
- workload
- ).then((res) => {
- let logicalDisks = res.results[0].toString().split(/\n\s*\n/);
- let diskDrives = res.results[1].toString().split(/\n\s*\n/);
- logicalDisks.forEach(function (device) {
- let lines = device.split('\r\n');
- let drivetype = util.getValue(lines, 'drivetype', ':');
- if (drivetype) {
- data.push({
- name: util.getValue(lines, 'name', ':'),
- identifier: util.getValue(lines, 'caption', ':'),
- type: 'disk',
- fsType: util.getValue(lines, 'filesystem', ':').toLowerCase(),
- mount: util.getValue(lines, 'caption', ':'),
- size: util.getValue(lines, 'size', ':'),
- physical: (drivetype >= 0 && drivetype <= 6) ? drivetypes[drivetype] : drivetypes[0],
- uuid: util.getValue(lines, 'volumeserialnumber', ':'),
- label: util.getValue(lines, 'volumename', ':'),
- model: '',
- serial: util.getValue(lines, 'volumeserialnumber', ':'),
- removable: drivetype === '2',
- protocol: '',
- group: '',
- device: ''
- });
- }
- });
- // match devices
- data = matchDevicesWin(data, diskDrives);
- if (callback) {
- callback(data);
- }
- resolve(data);
- });
- } catch (e) {
- if (callback) { callback(data); }
- resolve(data);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- // will follow
- if (callback) { callback(null); }
- resolve(null);
- }
-
- });
- });
-}
-
-exports.blockDevices = blockDevices;
-
-// --------------------------
-// FS - speed
-
-function calcFsSpeed(rx, wx) {
- let result = {
- rx: 0,
- wx: 0,
- tx: 0,
- rx_sec: null,
- wx_sec: null,
- tx_sec: null,
- ms: 0
- };
-
- if (_fs_speed && _fs_speed.ms) {
- result.rx = rx;
- result.wx = wx;
- result.tx = result.rx + result.wx;
- result.ms = Date.now() - _fs_speed.ms;
- result.rx_sec = (result.rx - _fs_speed.bytes_read) / (result.ms / 1000);
- result.wx_sec = (result.wx - _fs_speed.bytes_write) / (result.ms / 1000);
- result.tx_sec = result.rx_sec + result.wx_sec;
- _fs_speed.rx_sec = result.rx_sec;
- _fs_speed.wx_sec = result.wx_sec;
- _fs_speed.tx_sec = result.tx_sec;
- _fs_speed.bytes_read = result.rx;
- _fs_speed.bytes_write = result.wx;
- _fs_speed.bytes_overall = result.rx + result.wx;
- _fs_speed.ms = Date.now();
- _fs_speed.last_ms = result.ms;
- } else {
- result.rx = rx;
- result.wx = wx;
- result.tx = result.rx + result.wx;
- _fs_speed.rx_sec = null;
- _fs_speed.wx_sec = null;
- _fs_speed.tx_sec = null;
- _fs_speed.bytes_read = result.rx;
- _fs_speed.bytes_write = result.wx;
- _fs_speed.bytes_overall = result.rx + result.wx;
- _fs_speed.ms = Date.now();
- _fs_speed.last_ms = 0;
- }
- return result;
-}
-
-function fsStats(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (_windows || _freebsd || _openbsd || _netbsd || _sunos) {
- return resolve(null);
- }
-
- let result = {
- rx: 0,
- wx: 0,
- tx: 0,
- rx_sec: null,
- wx_sec: null,
- tx_sec: null,
- ms: 0
- };
-
- let rx = 0;
- let wx = 0;
- if ((_fs_speed && !_fs_speed.ms) || (_fs_speed && _fs_speed.ms && Date.now() - _fs_speed.ms >= 500)) {
- if (_linux) {
- // exec("df -k | grep /dev/", function(error, stdout) {
- exec('lsblk -r 2>/dev/null | grep /', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- let fs_filter = [];
- lines.forEach(function (line) {
- if (line !== '') {
- line = line.trim().split(' ');
- if (fs_filter.indexOf(line[0]) === -1) { fs_filter.push(line[0]); }
- }
- });
-
- let output = fs_filter.join('|');
- exec('cat /proc/diskstats | egrep "' + output + '"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- line = line.trim();
- if (line !== '') {
- line = line.replace(/ +/g, ' ').split(' ');
-
- rx += parseInt(line[5]) * 512;
- wx += parseInt(line[9]) * 512;
- }
- });
- result = calcFsSpeed(rx, wx);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- }
- if (_darwin) {
- exec('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- line = line.trim();
- if (line !== '') {
- line = line.split(',');
-
- rx += parseInt(line[2]);
- wx += parseInt(line[9]);
- }
- });
- result = calcFsSpeed(rx, wx);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- } else {
- result.ms = _fs_speed.last_ms;
- result.rx = _fs_speed.bytes_read;
- result.wx = _fs_speed.bytes_write;
- result.tx = _fs_speed.bytes_read + _fs_speed.bytes_write;
- result.rx_sec = _fs_speed.rx_sec;
- result.wx_sec = _fs_speed.wx_sec;
- result.tx_sec = _fs_speed.tx_sec;
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- });
-}
-
-exports.fsStats = fsStats;
-
-function calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime) {
- let result = {
- rIO: 0,
- wIO: 0,
- tIO: 0,
- rIO_sec: null,
- wIO_sec: null,
- tIO_sec: null,
- rWaitTime: 0,
- wWaitTime: 0,
- tWaitTime: 0,
- rWaitPercent: null,
- wWaitPercent: null,
- tWaitPercent: null,
- ms: 0
- };
- if (_disk_io && _disk_io.ms) {
- result.rIO = rIO;
- result.wIO = wIO;
- result.tIO = rIO + wIO;
- result.ms = Date.now() - _disk_io.ms;
- result.rIO_sec = (result.rIO - _disk_io.rIO) / (result.ms / 1000);
- result.wIO_sec = (result.wIO - _disk_io.wIO) / (result.ms / 1000);
- result.tIO_sec = result.rIO_sec + result.wIO_sec;
- result.rWaitTime = rWaitTime;
- result.wWaitTime = wWaitTime;
- result.tWaitTime = tWaitTime;
- result.rWaitPercent = (result.rWaitTime - _disk_io.rWaitTime) * 100 / (result.ms);
- result.wWaitPercent = (result.wWaitTime - _disk_io.wWaitTime) * 100 / (result.ms);
- result.tWaitPercent = (result.tWaitTime - _disk_io.tWaitTime) * 100 / (result.ms);
- _disk_io.rIO = rIO;
- _disk_io.wIO = wIO;
- _disk_io.rIO_sec = result.rIO_sec;
- _disk_io.wIO_sec = result.wIO_sec;
- _disk_io.tIO_sec = result.tIO_sec;
- _disk_io.rWaitTime = rWaitTime;
- _disk_io.wWaitTime = wWaitTime;
- _disk_io.tWaitTime = tWaitTime;
- _disk_io.rWaitPercent = result.rWaitPercent;
- _disk_io.wWaitPercent = result.wWaitPercent;
- _disk_io.tWaitPercent = result.tWaitPercent;
- _disk_io.last_ms = result.ms;
- _disk_io.ms = Date.now();
- } else {
- result.rIO = rIO;
- result.wIO = wIO;
- result.tIO = rIO + wIO;
- result.rWaitTime = rWaitTime;
- result.wWaitTime = wWaitTime;
- result.tWaitTime = tWaitTime;
- _disk_io.rIO = rIO;
- _disk_io.wIO = wIO;
- _disk_io.rIO_sec = null;
- _disk_io.wIO_sec = null;
- _disk_io.tIO_sec = null;
- _disk_io.rWaitTime = rWaitTime;
- _disk_io.wWaitTime = wWaitTime;
- _disk_io.tWaitTime = tWaitTime;
- _disk_io.rWaitPercent = null;
- _disk_io.wWaitPercent = null;
- _disk_io.tWaitPercent = null;
- _disk_io.last_ms = 0;
- _disk_io.ms = Date.now();
- }
- return result;
-}
-
-function disksIO(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (_windows) {
- return resolve(null);
- }
- if (_sunos) {
- return resolve(null);
- }
-
- let result = {
- rIO: 0,
- wIO: 0,
- tIO: 0,
- rIO_sec: null,
- wIO_sec: null,
- tIO_sec: null,
- rWaitTime: 0,
- wWaitTime: 0,
- tWaitTime: 0,
- rWaitPercent: null,
- wWaitPercent: null,
- tWaitPercent: null,
- ms: 0
- };
- let rIO = 0;
- let wIO = 0;
- let rWaitTime = 0;
- let wWaitTime = 0;
- let tWaitTime = 0;
-
- if ((_disk_io && !_disk_io.ms) || (_disk_io && _disk_io.ms && Date.now() - _disk_io.ms >= 500)) {
- if (_linux || _freebsd || _openbsd || _netbsd) {
- // prints Block layer statistics for all mounted volumes
- // var cmd = "for mount in `lsblk | grep / | sed -r 's/│ └─//' | cut -d ' ' -f 1`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done";
- // var cmd = "for mount in `lsblk | grep / | sed 's/[│└─├]//g' | awk '{$1=$1};1' | cut -d ' ' -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done";
- let cmd = 'for mount in `lsblk 2>/dev/null | grep " disk " | sed "s/[│└─├]//g" | awk \'{$1=$1};1\' | cut -d " " -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r "s/ +/;/g" | sed -r "s/^;//"; done';
-
- exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.split('\n');
- lines.forEach(function (line) {
- // ignore empty lines
- if (!line) { return; }
-
- // sum r/wIO of all disks to compute all disks IO
- let stats = line.split(';');
- rIO += parseInt(stats[0]);
- wIO += parseInt(stats[4]);
- rWaitTime += parseInt(stats[3]);
- wWaitTime += parseInt(stats[7]);
- tWaitTime += parseInt(stats[10]);
- });
- result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime);
-
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- }
- if (_darwin) {
- exec('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- line = line.trim();
- if (line !== '') {
- line = line.split(',');
-
- rIO += parseInt(line[10]);
- wIO += parseInt(line[0]);
- }
- });
- result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- } else {
- result.rIO = _disk_io.rIO;
- result.wIO = _disk_io.wIO;
- result.tIO = _disk_io.rIO + _disk_io.wIO;
- result.ms = _disk_io.last_ms;
- result.rIO_sec = _disk_io.rIO_sec;
- result.wIO_sec = _disk_io.wIO_sec;
- result.tIO_sec = _disk_io.tIO_sec;
- result.rWaitTime = _disk_io.rWaitTime;
- result.wWaitTime = _disk_io.wWaitTime;
- result.tWaitTime = _disk_io.tWaitTime;
- result.rWaitPercent = _disk_io.rWaitPercent;
- result.wWaitPercent = _disk_io.wWaitPercent;
- result.tWaitPercent = _disk_io.tWaitPercent;
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- });
-}
-
-exports.disksIO = disksIO;
-
-function diskLayout(callback) {
-
- function getVendorFromModel(model) {
- const diskManufacturers = [
- { pattern: 'WESTERN.*', manufacturer: 'Western Digital' },
- { pattern: '^WDC.*', manufacturer: 'Western Digital' },
- { pattern: 'WD.*', manufacturer: 'Western Digital' },
- { pattern: 'TOSHIBA.*', manufacturer: 'Toshiba' },
- { pattern: 'HITACHI.*', manufacturer: 'Hitachi' },
- { pattern: '^IC.*', manufacturer: 'Hitachi' },
- { pattern: '^HTS.*', manufacturer: 'Hitachi' },
- { pattern: 'SANDISK.*', manufacturer: 'SanDisk' },
- { pattern: 'KINGSTON.*', manufacturer: 'Kingston Technology' },
- { pattern: '^SONY.*', manufacturer: 'Sony' },
- { pattern: 'TRANSCEND.*', manufacturer: 'Transcend' },
- { pattern: 'SAMSUNG.*', manufacturer: 'Samsung' },
- { pattern: '^ST(?!I\\ ).*', manufacturer: 'Seagate' },
- { pattern: '^STI\\ .*', manufacturer: 'SimpleTech' },
- { pattern: '^D...-.*', manufacturer: 'IBM' },
- { pattern: '^IBM.*', manufacturer: 'IBM' },
- { pattern: '^FUJITSU.*', manufacturer: 'Fujitsu' },
- { pattern: '^MP.*', manufacturer: 'Fujitsu' },
- { pattern: '^MK.*', manufacturer: 'Toshiba' },
- { pattern: 'MAXTO.*', manufacturer: 'Maxtor' },
- { pattern: 'PIONEER.*', manufacturer: 'Pioneer' },
- { pattern: 'PHILIPS.*', manufacturer: 'Philips' },
- { pattern: 'QUANTUM.*', manufacturer: 'Quantum Technology' },
- { pattern: 'FIREBALL.*', manufacturer: 'Quantum Technology' },
- { pattern: '^VBOX.*', manufacturer: 'VirtualBox' },
- { pattern: 'CORSAIR.*', manufacturer: 'Corsair Components' },
- { pattern: 'CRUCIAL.*', manufacturer: 'Crucial' },
- { pattern: 'ECM.*', manufacturer: 'ECM' },
- { pattern: 'INTEL.*', manufacturer: 'INTEL' },
- { pattern: 'EVO.*', manufacturer: 'Samsung' },
- { pattern: 'APPLE.*', manufacturer: 'Apple' },
- ];
-
- let result = '';
- if (model) {
- model = model.toUpperCase();
- diskManufacturers.forEach((manufacturer) => {
- const re = RegExp(manufacturer.pattern);
- if (re.test(model)) { result = manufacturer.manufacturer; }
- });
- }
- return result;
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- const commitResult = res => {
- for (let i = 0; i < res.length; i++) {
- delete res[i].BSDName;
- }
- if (callback) {
- callback(res);
- }
- resolve(res);
- };
-
- let result = [];
- let cmd = '';
-
- if (_linux) {
- let cmdFullSmart = '';
-
- exec('export LC_ALL=C; lsblk -ablJO 2>/dev/null; unset LC_ALL', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- try {
- const out = stdout.toString().trim();
- let devices = [];
- try {
- const outJSON = JSON.parse(out);
- if (outJSON && {}.hasOwnProperty.call(outJSON, 'blockdevices')) {
- devices = outJSON.blockdevices.filter(item => { return (item.type === 'disk') && item.size > 0 && (item.model !== null || (item.mountpoint === null && item.label === null && item.fstype === null && item.parttype === null && item.path && item.path.indexOf('/ram') !== 0 && item.path.indexOf('/loop') !== 0 && item['disc-max'] && item['disc-max'] !== 0)); });
- }
- } catch (e) {
- // fallback to older version of lsblk
- try {
- const out2 = execSync('export LC_ALL=C; lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER,GROUP 2>/dev/null; unset LC_ALL', util.execOptsLinux).toString();
- let lines = blkStdoutToObject(out2).split('\n');
- const data = parseBlk(lines);
- devices = data.filter(item => { return (item.type === 'disk') && item.size > 0 && ((item.model !== null && item.model !== '') || (item.mount === '' && item.label === '' && item.fsType === '')); });
- } catch (e) {
- util.noop();
- }
- }
- devices.forEach((device) => {
- let mediumType = '';
- const BSDName = '/dev/' + device.name;
- const logical = device.name;
- try {
- mediumType = execSync('cat /sys/block/' + logical + '/queue/rotational 2>/dev/null', util.execOptsLinux).toString().split('\n')[0];
- } catch (e) {
- util.noop();
- }
- let interfaceType = device.tran ? device.tran.toUpperCase().trim() : '';
- if (interfaceType === 'NVME') {
- mediumType = '2';
- interfaceType = 'PCIe';
- }
- result.push({
- device: BSDName,
- type: (mediumType === '0' ? 'SSD' : (mediumType === '1' ? 'HD' : (mediumType === '2' ? 'NVMe' : (device.model && device.model.indexOf('SSD') > -1 ? 'SSD' : (device.model && device.model.indexOf('NVM') > -1 ? 'NVMe' : 'HD'))))),
- name: device.model || '',
- vendor: getVendorFromModel(device.model) || (device.vendor ? device.vendor.trim() : ''),
- size: device.size || 0,
- bytesPerSector: null,
- totalCylinders: null,
- totalHeads: null,
- totalSectors: null,
- totalTracks: null,
- tracksPerCylinder: null,
- sectorsPerTrack: null,
- firmwareRevision: device.rev ? device.rev.trim() : '',
- serialNum: device.serial ? device.serial.trim() : '',
- interfaceType: interfaceType,
- smartStatus: 'unknown',
- temperature: null,
- BSDName: BSDName
- });
- cmd += `printf "\n${BSDName}|"; smartctl -H ${BSDName} | grep overall;`;
- cmdFullSmart += `${cmdFullSmart ? 'printf ",";' : ''}smartctl -a -j ${BSDName};`;
- });
- } catch (e) {
- util.noop();
- }
- }
- // check S.M.A.R.T. status
- if (cmdFullSmart) {
- exec(cmdFullSmart, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- try {
- const data = JSON.parse(`[${stdout}]`);
- data.forEach(disk => {
- const diskBSDName = disk.smartctl.argv[disk.smartctl.argv.length - 1];
-
- for (let i = 0; i < result.length; i++) {
- if (result[i].BSDName === diskBSDName) {
- result[i].smartStatus = (disk.smart_status.passed ? 'Ok' : (disk.smart_status.passed === false ? 'Predicted Failure' : 'unknown'));
- if (disk.temperature && disk.temperature.current) {
- result[i].temperature = disk.temperature.current;
- }
- result[i].smartData = disk;
- }
- }
- });
- commitResult(result);
- } catch (e) {
- if (cmd) {
- cmd = cmd + 'printf "\n"';
- exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- lines.forEach(line => {
- if (line) {
- let parts = line.split('|');
- if (parts.length === 2) {
- let BSDName = parts[0];
- parts[1] = parts[1].trim();
- let parts2 = parts[1].split(':');
- if (parts2.length === 2) {
- parts2[1] = parts2[1].trim();
- let status = parts2[1].toLowerCase();
- for (let i = 0; i < result.length; i++) {
- if (result[i].BSDName === BSDName) {
- result[i].smartStatus = (status === 'passed' ? 'Ok' : (status === 'failed!' ? 'Predicted Failure' : 'unknown'));
- }
- }
- }
- }
- }
- });
- commitResult(result);
- });
- } else {
- commitResult(result);
- }
- }
- });
- } else {
- commitResult(result);
- }
- });
- }
- if (_freebsd || _openbsd || _netbsd) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_darwin) {
- exec('system_profiler SPSerialATADataType SPNVMeDataType SPUSBDataType', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- if (!error) {
- // split by type:
- let lines = stdout.toString().split('\n');
- let linesSATA = [];
- let linesNVMe = [];
- let linesUSB = [];
- let dataType = 'SATA';
- lines.forEach(line => {
- if (line === 'NVMExpress:') { dataType = 'NVMe'; }
- else if (line === 'USB:') { dataType = 'USB'; }
- else if (line === 'SATA/SATA Express:') { dataType = 'SATA'; }
- else if (dataType === 'SATA') { linesSATA.push(line); }
- else if (dataType === 'NVMe') { linesNVMe.push(line); }
- else if (dataType === 'USB') { linesUSB.push(line); }
- });
- try {
- // Serial ATA Drives
- let devices = linesSATA.join('\n').split(' Physical Interconnect: ');
- devices.shift();
- devices.forEach(function (device) {
- device = 'InterfaceType: ' + device;
- let lines = device.split('\n');
- const mediumType = util.getValue(lines, 'Medium Type', ':', true).trim();
- const sizeStr = util.getValue(lines, 'capacity', ':', true).trim();
- const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
- if (sizeStr) {
- let sizeValue = 0;
- if (sizeStr.indexOf('(') >= 0) {
- sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
- }
- if (!sizeValue) {
- sizeValue = parseInt(sizeStr);
- }
- if (sizeValue) {
- const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
- result.push({
- device: BSDName,
- type: mediumType.startsWith('Solid') ? 'SSD' : 'HD',
- name: util.getValue(lines, 'Model', ':', true).trim(),
- vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()) || util.getValue(lines, 'Manufacturer', ':', true),
- size: sizeValue,
- bytesPerSector: null,
- totalCylinders: null,
- totalHeads: null,
- totalSectors: null,
- totalTracks: null,
- tracksPerCylinder: null,
- sectorsPerTrack: null,
- firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
- serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
- interfaceType: util.getValue(lines, 'InterfaceType', ':', true).trim(),
- smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
- temperature: null,
- BSDName: BSDName
- });
- cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
- }
- }
- });
- } catch (e) {
- util.noop();
- }
-
- // NVME Drives
- try {
- let devices = linesNVMe.join('\n').split('\n\n Capacity:');
- devices.shift();
- devices.forEach(function (device) {
- device = '!Capacity: ' + device;
- let lines = device.split('\n');
- const linkWidth = util.getValue(lines, 'link width', ':', true).trim();
- const sizeStr = util.getValue(lines, '!capacity', ':', true).trim();
- const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
- if (sizeStr) {
- let sizeValue = 0;
- if (sizeStr.indexOf('(') >= 0) {
- sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
- }
- if (!sizeValue) {
- sizeValue = parseInt(sizeStr);
- }
- if (sizeValue) {
- const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
- result.push({
- device: BSDName,
- type: 'NVMe',
- name: util.getValue(lines, 'Model', ':', true).trim(),
- vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()),
- size: sizeValue,
- bytesPerSector: null,
- totalCylinders: null,
- totalHeads: null,
- totalSectors: null,
- totalTracks: null,
- tracksPerCylinder: null,
- sectorsPerTrack: null,
- firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
- serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
- interfaceType: ('PCIe ' + linkWidth).trim(),
- smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
- temperature: null,
- BSDName: BSDName
- });
- cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
- }
- }
- });
- } catch (e) {
- util.noop();
- }
- // USB Drives
- try {
- let devices = linesUSB.join('\n').replaceAll('Media:\n ', 'Model:').split('\n\n Product ID:');
- devices.shift();
- devices.forEach(function (device) {
- let lines = device.split('\n');
- const sizeStr = util.getValue(lines, 'Capacity', ':', true).trim();
- const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
- if (sizeStr) {
- let sizeValue = 0;
- if (sizeStr.indexOf('(') >= 0) {
- sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
- }
- if (!sizeValue) {
- sizeValue = parseInt(sizeStr);
- }
- if (sizeValue) {
- const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
- result.push({
- device: BSDName,
- type: 'USB',
- name: util.getValue(lines, 'Model', ':', true).trim().replaceAll(':', ''),
- vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()),
- size: sizeValue,
- bytesPerSector: null,
- totalCylinders: null,
- totalHeads: null,
- totalSectors: null,
- totalTracks: null,
- tracksPerCylinder: null,
- sectorsPerTrack: null,
- firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
- serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
- interfaceType: 'USB',
- smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
- temperature: null,
- BSDName: BSDName
- });
- cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
- }
- }
- });
- } catch (e) {
- util.noop();
- }
- if (cmd) {
- cmd = cmd + 'printf "\n"';
- exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- lines.forEach(line => {
- if (line) {
- let parts = line.split('|');
- if (parts.length === 2) {
- let BSDName = parts[0];
- parts[1] = parts[1].trim();
- let parts2 = parts[1].split(':');
- if (parts2.length === 2) {
- parts2[1] = parts2[1].trim();
- let status = parts2[1].toLowerCase();
- for (let i = 0; i < result.length; i++) {
- if (result[i].BSDName === BSDName) {
- result[i].smartStatus = (status === 'not supported' ? 'not supported' : (status === 'verified' ? 'Ok' : (status === 'failing' ? 'Predicted Failure' : 'unknown')));
- }
- }
- }
- }
- }
- });
- for (let i = 0; i < result.length; i++) {
- delete result[i].BSDName;
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- for (let i = 0; i < result.length; i++) {
- delete result[i].BSDName;
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- }
- });
- }
- if (_windows) {
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance Win32_DiskDrive | select Caption,Size,Status,PNPDeviceId,DeviceId,BytesPerSector,TotalCylinders,TotalHeads,TotalSectors,TotalTracks,TracksPerCylinder,SectorsPerTrack,FirmwareRevision,SerialNumber,InterfaceType | fl'));
- workload.push(util.powerShell('Get-PhysicalDisk | select BusType,MediaType,FriendlyName,Model,SerialNumber,Size | fl'));
- if (util.smartMonToolsInstalled()) {
- try {
- const smartDev = JSON.parse(execSync('smartctl --scan -j').toString());
- if (smartDev && smartDev.devices && smartDev.devices.length > 0) {
- smartDev.devices.forEach((dev) => {
- workload.push(execPromiseSave(`smartctl -j -a ${dev.name}`, util.execOptsWin));
- });
- }
- } catch (e) {
- util.noop();
- }
- }
- util.promiseAll(
- workload
- ).then((data) => {
- let devices = data.results[0].toString().split(/\n\s*\n/);
- devices.forEach(function (device) {
- let lines = device.split('\r\n');
- const size = util.getValue(lines, 'Size', ':').trim();
- const status = util.getValue(lines, 'Status', ':').trim().toLowerCase();
- if (size) {
- result.push({
- device: util.getValue(lines, 'DeviceId', ':'), // changed from PNPDeviceId to DeviceID (be be able to match devices)
- type: device.indexOf('SSD') > -1 ? 'SSD' : 'HD', // just a starting point ... better: MSFT_PhysicalDisk - Media Type ... see below
- name: util.getValue(lines, 'Caption', ':'),
- vendor: getVendorFromModel(util.getValue(lines, 'Caption', ':', true).trim()),
- size: parseInt(size),
- bytesPerSector: parseInt(util.getValue(lines, 'BytesPerSector', ':')),
- totalCylinders: parseInt(util.getValue(lines, 'TotalCylinders', ':')),
- totalHeads: parseInt(util.getValue(lines, 'TotalHeads', ':')),
- totalSectors: parseInt(util.getValue(lines, 'TotalSectors', ':')),
- totalTracks: parseInt(util.getValue(lines, 'TotalTracks', ':')),
- tracksPerCylinder: parseInt(util.getValue(lines, 'TracksPerCylinder', ':')),
- sectorsPerTrack: parseInt(util.getValue(lines, 'SectorsPerTrack', ':')),
- firmwareRevision: util.getValue(lines, 'FirmwareRevision', ':').trim(),
- serialNum: util.getValue(lines, 'SerialNumber', ':').trim(),
- interfaceType: util.getValue(lines, 'InterfaceType', ':').trim(),
- smartStatus: (status === 'ok' ? 'Ok' : (status === 'degraded' ? 'Degraded' : (status === 'pred fail' ? 'Predicted Failure' : 'Unknown'))),
- temperature: null,
- });
- }
- });
- devices = data.results[1].split(/\n\s*\n/);
- devices.forEach(function (device) {
- let lines = device.split('\r\n');
- const serialNum = util.getValue(lines, 'SerialNumber', ':').trim();
- const name = util.getValue(lines, 'FriendlyName', ':').trim().replace('Msft ', 'Microsoft');
- const size = util.getValue(lines, 'Size', ':').trim();
- const model = util.getValue(lines, 'Model', ':').trim();
- const interfaceType = util.getValue(lines, 'BusType', ':').trim();
- let mediaType = util.getValue(lines, 'MediaType', ':').trim();
- if (mediaType === '3' || mediaType === 'HDD') { mediaType = 'HD'; }
- if (mediaType === '4') { mediaType = 'SSD'; }
- if (mediaType === '5') { mediaType = 'SCM'; }
- if (mediaType === 'Unspecified' && (model.toLowerCase().indexOf('virtual') > -1 || model.toLowerCase().indexOf('vbox') > -1)) { mediaType = 'Virtual'; }
- if (size) {
- let i = util.findObjectByKey(result, 'serialNum', serialNum);
- if (i === -1 || serialNum === '') {
- i = util.findObjectByKey(result, 'name', name);
- }
- if (i != -1) {
- result[i].type = mediaType;
- result[i].interfaceType = interfaceType;
- }
- }
- });
- // S.M.A.R.T
- data.results.shift();
- data.results.shift();
- if (data.results.length) {
- data.results.forEach((smartStr) => {
- try {
- const smartData = JSON.parse(smartStr);
- if (smartData.serial_number) {
- const serialNum = smartData.serial_number;
- let i = util.findObjectByKey(result, 'serialNum', serialNum);
- if (i != -1) {
- result[i].smartStatus = (smartData.smart_status && smartData.smart_status.passed ? 'Ok' : (smartData.smart_status && smartData.smart_status.passed === false ? 'Predicted Failure' : 'unknown'));
- if (smartData.temperature && smartData.temperature.current) {
- result[i].temperature = smartData.temperature.current;
- }
- result[i].smartData = smartData;
- }
- }
- } catch (e) {
- util.noop();
- }
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.diskLayout = diskLayout;
-
-
-/***/ }),
-
-/***/ 49404:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// graphics.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 7. Graphics (controller, display)
-// ----------------------------------------------------------------------------------
-
-const fs = __nccwpck_require__(79896);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-let _nvidiaSmiPath = '';
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-let _resolutionX = 0;
-let _resolutionY = 0;
-let _pixelDepth = 0;
-let _refreshRate = 0;
-
-const videoTypes = {
- '-2': 'UNINITIALIZED',
- '-1': 'OTHER',
- '0': 'HD15',
- '1': 'SVIDEO',
- '2': 'Composite video',
- '3': 'Component video',
- '4': 'DVI',
- '5': 'HDMI',
- '6': 'LVDS',
- '8': 'D_JPN',
- '9': 'SDI',
- '10': 'DP',
- '11': 'DP embedded',
- '12': 'UDI',
- '13': 'UDI embedded',
- '14': 'SDTVDONGLE',
- '15': 'MIRACAST',
- '2147483648': 'INTERNAL'
-};
-
-function getVendorFromModel(model) {
- const manufacturers = [
- { pattern: '^LG.+', manufacturer: 'LG' },
- { pattern: '^BENQ.+', manufacturer: 'BenQ' },
- { pattern: '^ASUS.+', manufacturer: 'Asus' },
- { pattern: '^DELL.+', manufacturer: 'Dell' },
- { pattern: '^SAMSUNG.+', manufacturer: 'Samsung' },
- { pattern: '^VIEWSON.+', manufacturer: 'ViewSonic' },
- { pattern: '^SONY.+', manufacturer: 'Sony' },
- { pattern: '^ACER.+', manufacturer: 'Acer' },
- { pattern: '^AOC.+', manufacturer: 'AOC Monitors' },
- { pattern: '^HP.+', manufacturer: 'HP' },
- { pattern: '^EIZO.?', manufacturer: 'Eizo' },
- { pattern: '^PHILIPS.?', manufacturer: 'Philips' },
- { pattern: '^IIYAMA.?', manufacturer: 'Iiyama' },
- { pattern: '^SHARP.?', manufacturer: 'Sharp' },
- { pattern: '^NEC.?', manufacturer: 'NEC' },
- { pattern: '^LENOVO.?', manufacturer: 'Lenovo' },
- { pattern: 'COMPAQ.?', manufacturer: 'Compaq' },
- { pattern: 'APPLE.?', manufacturer: 'Apple' },
- { pattern: 'INTEL.?', manufacturer: 'Intel' },
- { pattern: 'AMD.?', manufacturer: 'AMD' },
- { pattern: 'NVIDIA.?', manufacturer: 'NVDIA' },
- ];
-
- let result = '';
- if (model) {
- model = model.toUpperCase();
- manufacturers.forEach((manufacturer) => {
- const re = RegExp(manufacturer.pattern);
- if (re.test(model)) { result = manufacturer.manufacturer; }
- });
- }
- return result;
-}
-
-function getVendorFromId(id) {
- const vendors = {
- '610': 'Apple',
- '1e6d': 'LG',
- '10ac': 'DELL',
- '4dd9': 'Sony',
- '38a3': 'NEC',
- };
- return vendors[id] || '';
-}
-
-function vendorToId(str) {
- let result = '';
- str = (str || '').toLowerCase();
- if (str.indexOf('apple') >= 0) { result = '0x05ac'; }
- else if (str.indexOf('nvidia') >= 0) { result = '0x10de'; }
- else if (str.indexOf('intel') >= 0) { result = '0x8086'; }
- else if (str.indexOf('ati') >= 0 || str.indexOf('amd') >= 0) { result = '0x1002'; }
-
- return result;
-}
-
-function getMetalVersion(id) {
- const families = {
- 'spdisplays_mtlgpufamilymac1': 'mac1',
- 'spdisplays_mtlgpufamilymac2': 'mac2',
- 'spdisplays_mtlgpufamilyapple1': 'apple1',
- 'spdisplays_mtlgpufamilyapple2': 'apple2',
- 'spdisplays_mtlgpufamilyapple3': 'apple3',
- 'spdisplays_mtlgpufamilyapple4': 'apple4',
- 'spdisplays_mtlgpufamilyapple5': 'apple5',
- 'spdisplays_mtlgpufamilyapple6': 'apple6',
- 'spdisplays_mtlgpufamilyapple7': 'apple7',
- 'spdisplays_metalfeaturesetfamily11': 'family1_v1',
- 'spdisplays_metalfeaturesetfamily12': 'family1_v2',
- 'spdisplays_metalfeaturesetfamily13': 'family1_v3',
- 'spdisplays_metalfeaturesetfamily14': 'family1_v4',
- 'spdisplays_metalfeaturesetfamily21': 'family2_v1'
- };
- return families[id] || '';
-}
-
-function graphics(callback) {
-
- function parseLinesDarwin(graphicsArr) {
- const res = {
- controllers: [],
- displays: []
- };
- try {
- graphicsArr.forEach(function (item) {
- // controllers
- const bus = ((item.sppci_bus || '').indexOf('builtin') > -1 ? 'Built-In' : ((item.sppci_bus || '').indexOf('pcie') > -1 ? 'PCIe' : ''));
- const vram = (parseInt((item.spdisplays_vram || ''), 10) || 0) * (((item.spdisplays_vram || '').indexOf('GB') > -1) ? 1024 : 1);
- const vramDyn = (parseInt((item.spdisplays_vram_shared || ''), 10) || 0) * (((item.spdisplays_vram_shared || '').indexOf('GB') > -1) ? 1024 : 1);
- let metalVersion = getMetalVersion(item.spdisplays_metal || item.spdisplays_metalfamily || '');
- res.controllers.push({
- vendor: getVendorFromModel(item.spdisplays_vendor || '') || item.spdisplays_vendor || '',
- model: item.sppci_model || '',
- bus,
- vramDynamic: bus === 'Built-In',
- vram: vram || vramDyn || null,
- deviceId: item['spdisplays_device-id'] || '',
- vendorId: item['spdisplays_vendor-id'] || vendorToId((item['spdisplays_vendor'] || '') + (item.sppci_model || '')),
- external: (item.sppci_device_type === 'spdisplays_egpu'),
- cores: item['sppci_cores'] || null,
- metalVersion
- });
-
- // displays
- if (item.spdisplays_ndrvs && item.spdisplays_ndrvs.length) {
- item.spdisplays_ndrvs.forEach(function (displayItem) {
- const connectionType = displayItem['spdisplays_connection_type'] || '';
- const currentResolutionParts = (displayItem['_spdisplays_resolution'] || '').split('@');
- const currentResolution = currentResolutionParts[0].split('x');
- const pixelParts = (displayItem['_spdisplays_pixels'] || '').split('x');
- const pixelDepthString = displayItem['spdisplays_depth'] || '';
- const serial = displayItem['_spdisplays_display-serial-number'] || displayItem['_spdisplays_display-serial-number2'] || null;
- res.displays.push({
- vendor: getVendorFromId(displayItem['_spdisplays_display-vendor-id'] || '') || getVendorFromModel(displayItem['_name'] || ''),
- vendorId: displayItem['_spdisplays_display-vendor-id'] || '',
- model: displayItem['_name'] || '',
- productionYear: displayItem['_spdisplays_display-year'] || null,
- serial: serial !== '0' ? serial : null,
- displayId: displayItem['_spdisplays_displayID'] || null,
- main: displayItem['spdisplays_main'] ? displayItem['spdisplays_main'] === 'spdisplays_yes' : false,
- builtin: (displayItem['spdisplays_display_type'] || '').indexOf('built-in') > -1,
- connection: ((connectionType.indexOf('_internal') > -1) ? 'Internal' : ((connectionType.indexOf('_displayport') > -1) ? 'Display Port' : ((connectionType.indexOf('_hdmi') > -1) ? 'HDMI' : null))),
- sizeX: null,
- sizeY: null,
- pixelDepth: (pixelDepthString === 'CGSThirtyBitColor' ? 30 : (pixelDepthString === 'CGSThirtytwoBitColor' ? 32 : (pixelDepthString === 'CGSTwentyfourBitColor' ? 24 : null))),
- resolutionX: pixelParts.length > 1 ? parseInt(pixelParts[0], 10) : null,
- resolutionY: pixelParts.length > 1 ? parseInt(pixelParts[1], 10) : null,
- currentResX: currentResolution.length > 1 ? parseInt(currentResolution[0], 10) : null,
- currentResY: currentResolution.length > 1 ? parseInt(currentResolution[1], 10) : null,
- positionX: 0,
- positionY: 0,
- currentRefreshRate: currentResolutionParts.length > 1 ? parseInt(currentResolutionParts[1], 10) : null,
-
- });
- });
- }
- });
- return res;
- } catch (e) {
- return res;
- }
- }
-
- function parseLinesLinuxControllers(lines) {
- let controllers = [];
- let currentController = {
- vendor: '',
- subVendor: '',
- model: '',
- bus: '',
- busAddress: '',
- vram: null,
- vramDynamic: false,
- pciID: ''
- };
- let isGraphicsController = false;
- // PCI bus IDs
- let pciIDs = [];
- try {
- pciIDs = execSync('export LC_ALL=C; dmidecode -t 9 2>/dev/null; unset LC_ALL | grep "Bus Address: "', util.execOptsLinux).toString().split('\n');
- for (let i = 0; i < pciIDs.length; i++) {
- pciIDs[i] = pciIDs[i].replace('Bus Address:', '').replace('0000:', '').trim();
- }
- pciIDs = pciIDs.filter(function (el) {
- return el != null && el;
- });
- } catch (e) {
- util.noop();
- }
- let i = 1;
- lines.forEach((line) => {
- let subsystem = '';
- if (i < lines.length && lines[i]) { // get next line;
- subsystem = lines[i];
- if (subsystem.indexOf(':') > 0) {
- subsystem = subsystem.split(':')[1];
- }
- }
- if ('' !== line.trim()) {
- if (' ' !== line[0] && '\t' !== line[0]) { // first line of new entry
- let isExternal = (pciIDs.indexOf(line.split(' ')[0]) >= 0);
- let vgapos = line.toLowerCase().indexOf(' vga ');
- let _3dcontrollerpos = line.toLowerCase().indexOf('3d controller');
- if (vgapos !== -1 || _3dcontrollerpos !== -1) { // VGA
- if (_3dcontrollerpos !== -1 && vgapos === -1) {
- vgapos = _3dcontrollerpos;
- }
- if (currentController.vendor || currentController.model || currentController.bus || currentController.vram !== null || currentController.vramDynamic) { // already a controller found
- controllers.push(currentController);
- currentController = {
- vendor: '',
- model: '',
- bus: '',
- busAddress: '',
- vram: null,
- vramDynamic: false,
- };
- }
-
- const pciIDCandidate = line.split(' ')[0];
- if (/[\da-fA-F]{2}:[\da-fA-F]{2}\.[\da-fA-F]/.test(pciIDCandidate)) {
- currentController.busAddress = pciIDCandidate;
- }
- isGraphicsController = true;
- let endpos = line.search(/\[[0-9a-f]{4}:[0-9a-f]{4}]|$/);
- let parts = line.substr(vgapos, endpos - vgapos).split(':');
- currentController.busAddress = line.substr(0, vgapos).trim();
- if (parts.length > 1) {
- parts[1] = parts[1].trim();
- if (parts[1].toLowerCase().indexOf('corporation') >= 0) {
- currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf('corporation') + 11).trim();
- currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf('corporation') + 11, 200).split('(')[0].trim();
- currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard';
- currentController.vram = null;
- currentController.vramDynamic = false;
- } else if (parts[1].toLowerCase().indexOf(' inc.') >= 0) {
- if ((parts[1].match(/]/g) || []).length > 1) {
- currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim();
- currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim();
- } else {
- currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' inc.') + 5).trim();
- currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' inc.') + 5, 200).trim().split('(')[0].trim();
- }
- currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard';
- currentController.vram = null;
- currentController.vramDynamic = false;
- } else if (parts[1].toLowerCase().indexOf(' ltd.') >= 0) {
- if ((parts[1].match(/]/g) || []).length > 1) {
- currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim();
- currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim();
- } else {
- currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' ltd.') + 5).trim();
- currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' ltd.') + 5, 200).trim().split('(')[0].trim();
- }
- }
- if (currentController.model && subsystem.indexOf(currentController.model) !== -1) {
- const subVendor = subsystem.split(currentController.model)[0].trim();
- if (subVendor) {
- currentController.subVendor = subVendor;
- }
- }
- }
-
- } else {
- isGraphicsController = false;
- }
- }
- if (isGraphicsController) { // within VGA details
- let parts = line.split(':');
- if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('devicename') !== -1 && parts[1].toLowerCase().indexOf('onboard') !== -1) { currentController.bus = 'Onboard'; }
- if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('region') !== -1 && parts[1].toLowerCase().indexOf('memory') !== -1) {
- let memparts = parts[1].split('=');
- if (memparts.length > 1) {
- currentController.vram = parseInt(memparts[1]);
- }
- }
- }
- }
- i++;
- });
-
- if (currentController.vendor || currentController.model || currentController.bus || currentController.busAddress || currentController.vram !== null || currentController.vramDynamic) { // already a controller found
- controllers.push(currentController);
- }
- return (controllers);
- }
-
- function parseLinesLinuxClinfo(controllers, lines) {
- const fieldPattern = /\[([^\]]+)\]\s+(\w+)\s+(.*)/;
- const devices = lines.reduce((devices, line) => {
- const field = fieldPattern.exec(line.trim());
- if (field) {
- if (!devices[field[1]]) {
- devices[field[1]] = {};
- }
- devices[field[1]][field[2]] = field[3];
- }
- return devices;
- }, {});
- for (let deviceId in devices) {
- const device = devices[deviceId];
- if (device['CL_DEVICE_TYPE'] === 'CL_DEVICE_TYPE_GPU') {
- let busAddress;
- if (device['CL_DEVICE_TOPOLOGY_AMD']) {
- const bdf = device['CL_DEVICE_TOPOLOGY_AMD'].match(/[a-zA-Z0-9]+:\d+\.\d+/);
- if (bdf) {
- busAddress = bdf[0];
- }
- } else if (device['CL_DEVICE_PCI_BUS_ID_NV'] && device['CL_DEVICE_PCI_SLOT_ID_NV']) {
- const bus = parseInt(device['CL_DEVICE_PCI_BUS_ID_NV']);
- const slot = parseInt(device['CL_DEVICE_PCI_SLOT_ID_NV']);
- if (!isNaN(bus) && !isNaN(slot)) {
- const b = bus & 0xff;
- const d = (slot >> 3) & 0xff;
- const f = slot & 0x07;
- busAddress = `${b.toString().padStart(2, '0')}:${d.toString().padStart(2, '0')}.${f}`;
- }
- }
- if (busAddress) {
- let controller = controllers.find(controller => controller.busAddress === busAddress);
- if (!controller) {
- controller = {
- vendor: '',
- model: '',
- bus: '',
- busAddress,
- vram: null,
- vramDynamic: false
- };
- controllers.push(controller);
- }
- controller.vendor = device['CL_DEVICE_VENDOR'];
- if (device['CL_DEVICE_BOARD_NAME_AMD']) {
- controller.model = device['CL_DEVICE_BOARD_NAME_AMD'];
- } else {
- controller.model = device['CL_DEVICE_NAME'];
- }
- const memory = parseInt(device['CL_DEVICE_GLOBAL_MEM_SIZE']);
- if (!isNaN(memory)) {
- controller.vram = Math.round(memory / 1024 / 1024);
- }
- }
- }
- }
- return controllers;
- }
-
- function getNvidiaSmi() {
- if (_nvidiaSmiPath) {
- return _nvidiaSmiPath;
- }
-
- if (_windows) {
- try {
- const basePath = util.WINDIR + '\\System32\\DriverStore\\FileRepository';
- // find all directories that have an nvidia-smi.exe file
- const candidateDirs = fs.readdirSync(basePath).filter(dir => {
- return fs.readdirSync([basePath, dir].join('/')).includes('nvidia-smi.exe');
- });
- // use the directory with the most recently created nvidia-smi.exe file
- const targetDir = candidateDirs.reduce((prevDir, currentDir) => {
- const previousNvidiaSmi = fs.statSync([basePath, prevDir, 'nvidia-smi.exe'].join('/'));
- const currentNvidiaSmi = fs.statSync([basePath, currentDir, 'nvidia-smi.exe'].join('/'));
- return (previousNvidiaSmi.ctimeMs > currentNvidiaSmi.ctimeMs) ? prevDir : currentDir;
- });
-
- if (targetDir) {
- _nvidiaSmiPath = [basePath, targetDir, 'nvidia-smi.exe'].join('/');
- }
- } catch (e) {
- util.noop();
- }
- } else if (_linux) {
- _nvidiaSmiPath = 'nvidia-smi';
- }
- return _nvidiaSmiPath;
- }
-
- function nvidiaSmi(options) {
- const nvidiaSmiExe = getNvidiaSmi();
- options = options || util.execOptsWin;
- if (nvidiaSmiExe) {
- const nvidiaSmiOpts = '--query-gpu=driver_version,pci.sub_device_id,name,pci.bus_id,fan.speed,memory.total,memory.used,memory.free,utilization.gpu,utilization.memory,temperature.gpu,temperature.memory,power.draw,power.limit,clocks.gr,clocks.mem --format=csv,noheader,nounits';
- const cmd = nvidiaSmiExe + ' ' + nvidiaSmiOpts + (_linux ? ' 2>/dev/null' : '');
- if (_linux) {
- options.stdio = ['pipe', 'pipe', 'ignore'];
- }
- try {
- const res = execSync(cmd, options).toString();
- return res;
- } catch (e) {
- util.noop();
- }
- }
- return '';
- }
-
- function nvidiaDevices() {
-
- function safeParseNumber(value) {
- if ([null, undefined].includes(value)) {
- return value;
- }
- return parseFloat(value);
- }
-
- const stdout = nvidiaSmi();
- if (!stdout) {
- return [];
- }
-
- const gpus = stdout.split('\n').filter(Boolean);
- let results = gpus.map(gpu => {
- const splittedData = gpu.split(', ').map(value => value.includes('N/A') ? undefined : value);
- if (splittedData.length === 16) {
- return {
- driverVersion: splittedData[0],
- subDeviceId: splittedData[1],
- name: splittedData[2],
- pciBus: splittedData[3],
- fanSpeed: safeParseNumber(splittedData[4]),
- memoryTotal: safeParseNumber(splittedData[5]),
- memoryUsed: safeParseNumber(splittedData[6]),
- memoryFree: safeParseNumber(splittedData[7]),
- utilizationGpu: safeParseNumber(splittedData[8]),
- utilizationMemory: safeParseNumber(splittedData[9]),
- temperatureGpu: safeParseNumber(splittedData[10]),
- temperatureMemory: safeParseNumber(splittedData[11]),
- powerDraw: safeParseNumber(splittedData[12]),
- powerLimit: safeParseNumber(splittedData[13]),
- clockCore: safeParseNumber(splittedData[14]),
- clockMemory: safeParseNumber(splittedData[15]),
- };
- } else {
- return {};
- }
- });
- results = results.filter((item) => {
- return ('pciBus' in item);
- });
- return results;
- }
-
- function mergeControllerNvidia(controller, nvidia) {
- if (nvidia.driverVersion) { controller.driverVersion = nvidia.driverVersion; }
- if (nvidia.subDeviceId) { controller.subDeviceId = nvidia.subDeviceId; }
- if (nvidia.name) { controller.name = nvidia.name; }
- if (nvidia.pciBus) { controller.pciBus = nvidia.pciBus; }
- if (nvidia.fanSpeed) { controller.fanSpeed = nvidia.fanSpeed; }
- if (nvidia.memoryTotal) {
- controller.memoryTotal = nvidia.memoryTotal;
- controller.vram = nvidia.memoryTotal;
- controller.vramDynamic = false;
- }
- if (nvidia.memoryUsed) { controller.memoryUsed = nvidia.memoryUsed; }
- if (nvidia.memoryFree) { controller.memoryFree = nvidia.memoryFree; }
- if (nvidia.utilizationGpu) { controller.utilizationGpu = nvidia.utilizationGpu; }
- if (nvidia.utilizationMemory) { controller.utilizationMemory = nvidia.utilizationMemory; }
- if (nvidia.temperatureGpu) { controller.temperatureGpu = nvidia.temperatureGpu; }
- if (nvidia.temperatureMemory) { controller.temperatureMemory = nvidia.temperatureMemory; }
- if (nvidia.powerDraw) { controller.powerDraw = nvidia.powerDraw; }
- if (nvidia.powerLimit) { controller.powerLimit = nvidia.powerLimit; }
- if (nvidia.clockCore) { controller.clockCore = nvidia.clockCore; }
- if (nvidia.clockMemory) { controller.clockMemory = nvidia.clockMemory; }
- return controller;
- }
-
- function parseLinesLinuxEdid(edid) {
- // parsen EDID
- // --> model
- // --> resolutionx
- // --> resolutiony
- // --> builtin = false
- // --> pixeldepth (?)
- // --> sizex
- // --> sizey
- let result = {
- vendor: '',
- model: '',
- deviceName: '',
- main: false,
- builtin: false,
- connection: '',
- sizeX: null,
- sizeY: null,
- pixelDepth: null,
- resolutionX: null,
- resolutionY: null,
- currentResX: null,
- currentResY: null,
- positionX: 0,
- positionY: 0,
- currentRefreshRate: null
- };
- // find first "Detailed Timing Description"
- let start = 108;
- if (edid.substr(start, 6) === '000000') {
- start += 36;
- }
- if (edid.substr(start, 6) === '000000') {
- start += 36;
- }
- if (edid.substr(start, 6) === '000000') {
- start += 36;
- }
- if (edid.substr(start, 6) === '000000') {
- start += 36;
- }
- result.resolutionX = parseInt('0x0' + edid.substr(start + 8, 1) + edid.substr(start + 4, 2));
- result.resolutionY = parseInt('0x0' + edid.substr(start + 14, 1) + edid.substr(start + 10, 2));
- result.sizeX = parseInt('0x0' + edid.substr(start + 28, 1) + edid.substr(start + 24, 2));
- result.sizeY = parseInt('0x0' + edid.substr(start + 29, 1) + edid.substr(start + 26, 2));
- // monitor name
- start = edid.indexOf('000000fc00'); // find first "Monitor Description Data"
- if (start >= 0) {
- let model_raw = edid.substr(start + 10, 26);
- if (model_raw.indexOf('0a') !== -1) {
- model_raw = model_raw.substr(0, model_raw.indexOf('0a'));
- }
- try {
- if (model_raw.length > 2) {
- result.model = model_raw.match(/.{1,2}/g).map(function (v) {
- return String.fromCharCode(parseInt(v, 16));
- }).join('');
- }
- } catch (e) {
- util.noop();
- }
- } else {
- result.model = '';
- }
- return result;
- }
-
- function parseLinesLinuxDisplays(lines, depth) {
- let displays = [];
- let currentDisplay = {
- vendor: '',
- model: '',
- deviceName: '',
- main: false,
- builtin: false,
- connection: '',
- sizeX: null,
- sizeY: null,
- pixelDepth: null,
- resolutionX: null,
- resolutionY: null,
- currentResX: null,
- currentResY: null,
- positionX: 0,
- positionY: 0,
- currentRefreshRate: null
- };
- let is_edid = false;
- let is_current = false;
- let edid_raw = '';
- let start = 0;
- for (let i = 1; i < lines.length; i++) { // start with second line
- if ('' !== lines[i].trim()) {
- if (' ' !== lines[i][0] && '\t' !== lines[i][0] && lines[i].toLowerCase().indexOf(' connected ') !== -1) { // first line of new entry
- if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // push last display to array
- displays.push(currentDisplay);
- currentDisplay = {
- vendor: '',
- model: '',
- main: false,
- builtin: false,
- connection: '',
- sizeX: null,
- sizeY: null,
- pixelDepth: null,
- resolutionX: null,
- resolutionY: null,
- currentResX: null,
- currentResY: null,
- positionX: 0,
- positionY: 0,
- currentRefreshRate: null
- };
- }
- let parts = lines[i].split(' ');
- currentDisplay.connection = parts[0];
- currentDisplay.main = lines[i].toLowerCase().indexOf(' primary ') >= 0;
- currentDisplay.builtin = (parts[0].toLowerCase().indexOf('edp') >= 0);
- }
-
- // try to read EDID information
- if (is_edid) {
- if (lines[i].search(/\S|$/) > start) {
- edid_raw += lines[i].toLowerCase().trim();
- } else {
- // parsen EDID
- let edid_decoded = parseLinesLinuxEdid(edid_raw);
- currentDisplay.vendor = edid_decoded.vendor;
- currentDisplay.model = edid_decoded.model;
- currentDisplay.resolutionX = edid_decoded.resolutionX;
- currentDisplay.resolutionY = edid_decoded.resolutionY;
- currentDisplay.sizeX = edid_decoded.sizeX;
- currentDisplay.sizeY = edid_decoded.sizeY;
- currentDisplay.pixelDepth = depth;
- is_edid = false;
- }
- }
- if (lines[i].toLowerCase().indexOf('edid:') >= 0) {
- is_edid = true;
- start = lines[i].search(/\S|$/);
- }
- if (lines[i].toLowerCase().indexOf('*current') >= 0) {
- const parts1 = lines[i].split('(');
- if (parts1 && parts1.length > 1 && parts1[0].indexOf('x') >= 0) {
- const resParts = parts1[0].trim().split('x');
- currentDisplay.currentResX = util.toInt(resParts[0]);
- currentDisplay.currentResY = util.toInt(resParts[1]);
- }
- is_current = true;
- }
- if (is_current && lines[i].toLowerCase().indexOf('clock') >= 0 && lines[i].toLowerCase().indexOf('hz') >= 0 && lines[i].toLowerCase().indexOf('v: height') >= 0) {
- const parts1 = lines[i].split('clock');
- if (parts1 && parts1.length > 1 && parts1[1].toLowerCase().indexOf('hz') >= 0) {
- currentDisplay.currentRefreshRate = util.toInt(parts1[1]);
- }
- is_current = false;
- }
- }
- }
-
- // pushen displays
- if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // still information there
- displays.push(currentDisplay);
- }
- return displays;
- }
-
- // function starts here
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
- controllers: [],
- displays: []
- };
- if (_darwin) {
- let cmd = 'system_profiler -xml -detailLevel full SPDisplaysDataType';
- exec(cmd, function (error, stdout) {
- if (!error) {
- try {
- const output = stdout.toString();
- result = parseLinesDarwin(util.plistParser(output)[0]._items);
- } catch (e) {
- util.noop();
- }
- try {
- stdout = execSync('defaults read /Library/Preferences/com.apple.windowserver.plist 2>/dev/null;defaults read /Library/Preferences/com.apple.windowserver.displays.plist 2>/dev/null; echo ""', { maxBuffer: 1024 * 20000 });
- const output = (stdout || '').toString();
- const obj = util.plistReader(output);
- if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets']['Configs'] && obj['DisplayAnyUserSets']['Configs'][0] && obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig']) {
- const current = obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig'];
- let i = 0;
- current.forEach((o) => {
- if (o['CurrentInfo'] && o['CurrentInfo']['OriginX'] !== undefined && result.displays && result.displays[i]) {
- result.displays[i].positionX = o['CurrentInfo']['OriginX'];
- }
- if (o['CurrentInfo'] && o['CurrentInfo']['OriginY'] !== undefined && result.displays && result.displays[i]) {
- result.displays[i].positionY = o['CurrentInfo']['OriginY'];
- }
- i++;
- });
- }
- if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets'].length > 0 && obj['DisplayAnyUserSets'][0].length > 0 && obj['DisplayAnyUserSets'][0][0]['DisplayID']) {
- const current = obj['DisplayAnyUserSets'][0];
- let i = 0;
- current.forEach((o) => {
- if ('OriginX' in o && result.displays && result.displays[i]) {
- result.displays[i].positionX = o['OriginX'];
- }
- if ('OriginY' in o && result.displays && result.displays[i]) {
- result.displays[i].positionY = o['OriginY'];
- }
- if (o['Mode'] && o['Mode']['BitsPerPixel'] !== undefined && result.displays && result.displays[i]) {
- result.displays[i].pixelDepth = o['Mode']['BitsPerPixel'];
- }
- i++;
- });
- }
- } catch (e) {
- util.noop();
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_linux) {
- // Raspberry: https://elinux.org/RPI_vcgencmd_usage
- if (util.isRaspberry() && util.isRaspbian()) {
- let cmd = 'fbset -s | grep \'mode "\'; vcgencmd get_mem gpu; tvservice -s; tvservice -n;';
- exec(cmd, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- if (lines.length > 3 && lines[0].indexOf('mode "') >= -1 && lines[2].indexOf('0x12000a') > -1) {
- const parts = lines[0].replace('mode', '').replace(/"/g, '').trim().split('x');
- if (parts.length === 2) {
- result.displays.push({
- vendor: '',
- model: util.getValue(lines, 'device_name', '='),
- main: true,
- builtin: false,
- connection: 'HDMI',
- sizeX: null,
- sizeY: null,
- pixelDepth: null,
- resolutionX: parseInt(parts[0], 10),
- resolutionY: parseInt(parts[1], 10),
- currentResX: null,
- currentResY: null,
- positionX: 0,
- positionY: 0,
- currentRefreshRate: null
- });
- }
- }
- if (lines.length > 1 && stdout.toString().indexOf('gpu=') >= -1) {
- result.controllers.push({
- vendor: 'Broadcom',
- model: util.getRpiGpu(),
- bus: '',
- vram: util.getValue(lines, 'gpu', '=').replace('M', ''),
- vramDynamic: true
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- let cmd = 'lspci -vvv 2>/dev/null';
- exec(cmd, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result.controllers = parseLinesLinuxControllers(lines);
- const nvidiaData = nvidiaDevices();
- // needs to be rewritten ... using no spread operators
- result.controllers = result.controllers.map((controller) => { // match by busAddress
- return mergeControllerNvidia(controller, nvidiaData.find((contr) => contr.pciBus.toLowerCase().endsWith(controller.busAddress.toLowerCase())) || {});
- });
- }
- let cmd = 'clinfo --raw';
- exec(cmd, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result.controllers = parseLinesLinuxClinfo(result.controllers, lines);
- }
- let cmd = 'xdpyinfo 2>/dev/null | grep \'depth of root window\' | awk \'{ print $5 }\'';
- exec(cmd, function (error, stdout) {
- let depth = 0;
- if (!error) {
- let lines = stdout.toString().split('\n');
- depth = parseInt(lines[0]) || 0;
- }
- let cmd = 'xrandr --verbose 2>/dev/null';
- exec(cmd, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result.displays = parseLinesLinuxDisplays(lines, depth);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- });
- });
- });
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- if (callback) { callback(null); }
- resolve(null);
- }
- if (_sunos) {
- if (callback) { callback(null); }
- resolve(null);
- }
- if (_windows) {
-
- // https://blogs.technet.microsoft.com/heyscriptingguy/2013/10/03/use-powershell-to-discover-multi-monitor-information/
- // https://devblogs.microsoft.com/scripting/use-powershell-to-discover-multi-monitor-information/
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance win32_VideoController | fl *'));
- workload.push(util.powerShell('gp "HKLM:\\SYSTEM\\ControlSet001\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}\\*" -ErrorAction SilentlyContinue | where MatchingDeviceId $null -NE | select MatchingDeviceId,HardwareInformation.qwMemorySize | fl'));
- workload.push(util.powerShell('Get-CimInstance win32_desktopmonitor | fl *'));
- workload.push(util.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorBasicDisplayParams | fl'));
- workload.push(util.powerShell('Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Screen]::AllScreens'));
- workload.push(util.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorConnectionParams | fl'));
- workload.push(util.powerShell('gwmi WmiMonitorID -Namespace root\\wmi | ForEach-Object {(($_.ManufacturerName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.ProductCodeID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.UserFriendlyName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.SerialNumberID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + $_.InstanceName}'));
-
- const nvidiaData = nvidiaDevices();
-
- Promise.all(
- workload
- ).then((data) => {
- // controller + vram
- let csections = data[0].replace(/\r/g, '').split(/\n\s*\n/);
- let vsections = data[1].replace(/\r/g, '').split(/\n\s*\n/);
- result.controllers = parseLinesWindowsControllers(csections, vsections);
- result.controllers = result.controllers.map((controller) => { // match by subDeviceId
- if (controller.vendor.toLowerCase() === 'nvidia') {
- return mergeControllerNvidia(controller, nvidiaData.find(device => {
- let windowsSubDeviceId = (controller.subDeviceId || '').toLowerCase();
- const nvidiaSubDeviceIdParts = device.subDeviceId.split('x');
- let nvidiaSubDeviceId = nvidiaSubDeviceIdParts.length > 1 ? nvidiaSubDeviceIdParts[1].toLowerCase() : nvidiaSubDeviceIdParts[0].toLowerCase();
- const lengthDifference = Math.abs(windowsSubDeviceId.length - nvidiaSubDeviceId.length);
- if (windowsSubDeviceId.length > nvidiaSubDeviceId.length) {
- for (let i = 0; i < lengthDifference; i++) {
- nvidiaSubDeviceId = '0' + nvidiaSubDeviceId;
- }
- } else if (windowsSubDeviceId.length < nvidiaSubDeviceId.length) {
- for (let i = 0; i < lengthDifference; i++) {
- windowsSubDeviceId = '0' + windowsSubDeviceId;
- }
- }
- return windowsSubDeviceId === nvidiaSubDeviceId;
- }) || {});
- } else {
- return controller;
- }
- });
-
- // displays
- let dsections = data[2].replace(/\r/g, '').split(/\n\s*\n/);
- // result.displays = parseLinesWindowsDisplays(dsections);
- if (dsections[0].trim() === '') { dsections.shift(); }
- if (dsections.length && dsections[dsections.length - 1].trim() === '') { dsections.pop(); }
-
- // monitor (powershell)
- let msections = data[3].replace(/\r/g, '').split('Active ');
- msections.shift();
-
- // forms.screens (powershell)
- let ssections = data[4].replace(/\r/g, '').split('BitsPerPixel ');
- ssections.shift();
-
- // connection params (powershell) - video type
- let tsections = data[5].replace(/\r/g, '').split(/\n\s*\n/);
- tsections.shift();
-
- // monitor ID (powershell) - model / vendor
- const res = data[6].replace(/\r/g, '').split(/\n/);
- let isections = [];
- res.forEach(element => {
- const parts = element.split('|');
- if (parts.length === 5) {
- isections.push({
- vendor: parts[0],
- code: parts[1],
- model: parts[2],
- serial: parts[3],
- instanceId: parts[4]
- });
- }
- });
-
- result.displays = parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections);
-
- if (result.displays.length === 1) {
- if (_resolutionX) {
- result.displays[0].resolutionX = _resolutionX;
- if (!result.displays[0].currentResX) {
- result.displays[0].currentResX = _resolutionX;
- }
- }
- if (_resolutionY) {
- result.displays[0].resolutionY = _resolutionY;
- if (result.displays[0].currentResY === 0) {
- result.displays[0].currentResY = _resolutionY;
- }
- }
- if (_pixelDepth) {
- result.displays[0].pixelDepth = _pixelDepth;
- }
- }
- result.displays = result.displays.map(element => {
- if (_refreshRate && !element.currentRefreshRate) {
- element.currentRefreshRate = _refreshRate;
- }
- return element;
- });
-
- if (callback) {
- callback(result);
- }
- resolve(result);
- })
- .catch(() => {
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-
- function parseLinesWindowsControllers(sections, vections) {
- const memorySizes = {};
- for (const i in vections) {
- if ({}.hasOwnProperty.call(vections, i)) {
- if (vections[i].trim() !== '') {
- const lines = vections[i].trim().split('\n');
- const matchingDeviceId = util.getValue(lines, 'MatchingDeviceId').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i);
- if (matchingDeviceId) {
- const quadWordmemorySize = parseInt(util.getValue(lines, 'HardwareInformation.qwMemorySize'));
- if (!isNaN(quadWordmemorySize)) {
- let deviceId = matchingDeviceId[1].toUpperCase() + '&' + matchingDeviceId[2].toUpperCase();
- if (matchingDeviceId[3]) {
- deviceId += '&' + matchingDeviceId[3].toUpperCase();
- }
- if (matchingDeviceId[4]) {
- deviceId += '&' + matchingDeviceId[4].toUpperCase();
- }
- memorySizes[deviceId] = quadWordmemorySize;
- }
- }
- }
- }
- }
-
- let controllers = [];
- for (let i in sections) {
- if ({}.hasOwnProperty.call(sections, i)) {
- if (sections[i].trim() !== '') {
- let lines = sections[i].trim().split('\n');
- let pnpDeviceId = util.getValue(lines, 'PNPDeviceID', ':').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i);
- let subDeviceId = null;
- let memorySize = null;
- if (pnpDeviceId) {
- subDeviceId = pnpDeviceId[3] || '';
- if (subDeviceId) {
- subDeviceId = subDeviceId.split('_')[1];
- }
-
- // Match PCI device identifier (there's an order of increasing generality):
- // https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
-
- // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4)&REV_r(2)
- if (memorySize == null && pnpDeviceId[3] && pnpDeviceId[4]) {
- const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase();
- if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
- memorySize = memorySizes[deviceId];
- }
- }
-
- // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4)
- if (memorySize == null && pnpDeviceId[3]) {
- const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase();
- if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
- memorySize = memorySizes[deviceId];
- }
- }
-
- // PCI\VEN_v(4)&DEV_d(4)&REV_r(2)
- if (memorySize == null && pnpDeviceId[4]) {
- const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase();
- if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
- memorySize = memorySizes[deviceId];
- }
- }
-
- // PCI\VEN_v(4)&DEV_d(4)
- if (memorySize == null) {
- const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase();
- if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
- memorySize = memorySizes[deviceId];
- }
- }
- }
-
- controllers.push({
- vendor: util.getValue(lines, 'AdapterCompatibility', ':'),
- model: util.getValue(lines, 'name', ':'),
- bus: util.getValue(lines, 'PNPDeviceID', ':').startsWith('PCI') ? 'PCI' : '',
- vram: (memorySize == null ? util.toInt(util.getValue(lines, 'AdapterRAM', ':')) : memorySize) / 1024 / 1024,
- vramDynamic: (util.getValue(lines, 'VideoMemoryType', ':') === '2'),
- subDeviceId
- });
- _resolutionX = util.toInt(util.getValue(lines, 'CurrentHorizontalResolution', ':')) || _resolutionX;
- _resolutionY = util.toInt(util.getValue(lines, 'CurrentVerticalResolution', ':')) || _resolutionY;
- _refreshRate = util.toInt(util.getValue(lines, 'CurrentRefreshRate', ':')) || _refreshRate;
- _pixelDepth = util.toInt(util.getValue(lines, 'CurrentBitsPerPixel', ':')) || _pixelDepth;
- }
- }
- }
- return controllers;
- }
-
- function parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections) {
- let displays = [];
- let vendor = '';
- let model = '';
- let deviceID = '';
- let resolutionX = 0;
- let resolutionY = 0;
- if (dsections && dsections.length) {
- let linesDisplay = dsections[0].split('\n');
- vendor = util.getValue(linesDisplay, 'MonitorManufacturer', ':');
- model = util.getValue(linesDisplay, 'Name', ':');
- deviceID = util.getValue(linesDisplay, 'PNPDeviceID', ':').replace(/&/g, '&').toLowerCase();
- resolutionX = util.toInt(util.getValue(linesDisplay, 'ScreenWidth', ':'));
- resolutionY = util.toInt(util.getValue(linesDisplay, 'ScreenHeight', ':'));
- }
- for (let i = 0; i < ssections.length; i++) {
- if (ssections[i].trim() !== '') {
- ssections[i] = 'BitsPerPixel ' + ssections[i];
- msections[i] = 'Active ' + msections[i];
- // tsections can be empty OR undefined on earlier versions of powershell (<=2.0)
- // Tag connection type as UNKNOWN by default if this information is missing
- if (tsections.length === 0 || tsections[i] === undefined) {
- tsections[i] = 'Unknown';
- }
- let linesScreen = ssections[i].split('\n');
- let linesMonitor = msections[i].split('\n');
-
- let linesConnection = tsections[i].split('\n');
- const bitsPerPixel = util.getValue(linesScreen, 'BitsPerPixel');
- const bounds = util.getValue(linesScreen, 'Bounds').replace('{', '').replace('}', '').replace(/=/g, ':').split(',');
- const primary = util.getValue(linesScreen, 'Primary');
- const sizeX = util.getValue(linesMonitor, 'MaxHorizontalImageSize');
- const sizeY = util.getValue(linesMonitor, 'MaxVerticalImageSize');
- const instanceName = util.getValue(linesMonitor, 'InstanceName').toLowerCase();
- const videoOutputTechnology = util.getValue(linesConnection, 'VideoOutputTechnology');
- const deviceName = util.getValue(linesScreen, 'DeviceName');
- let displayVendor = '';
- let displayModel = '';
- isections.forEach(element => {
- if (element.instanceId.toLowerCase().startsWith(instanceName) && vendor.startsWith('(') && model.startsWith('PnP')) {
- displayVendor = element.vendor;
- displayModel = element.model;
- }
- });
- displays.push({
- vendor: instanceName.startsWith(deviceID) && displayVendor === '' ? vendor : displayVendor,
- model: instanceName.startsWith(deviceID) && displayModel === '' ? model : displayModel,
- deviceName,
- main: primary.toLowerCase() === 'true',
- builtin: videoOutputTechnology === '2147483648',
- connection: videoOutputTechnology && videoTypes[videoOutputTechnology] ? videoTypes[videoOutputTechnology] : '',
- resolutionX: util.toInt(util.getValue(bounds, 'Width', ':')),
- resolutionY: util.toInt(util.getValue(bounds, 'Height', ':')),
- sizeX: sizeX ? parseInt(sizeX, 10) : null,
- sizeY: sizeY ? parseInt(sizeY, 10) : null,
- pixelDepth: bitsPerPixel,
- currentResX: util.toInt(util.getValue(bounds, 'Width', ':')),
- currentResY: util.toInt(util.getValue(bounds, 'Height', ':')),
- positionX: util.toInt(util.getValue(bounds, 'X', ':')),
- positionY: util.toInt(util.getValue(bounds, 'Y', ':')),
- });
- }
- }
- if (ssections.length === 0) {
- displays.push({
- vendor,
- model,
- main: true,
- sizeX: null,
- sizeY: null,
- resolutionX,
- resolutionY,
- pixelDepth: null,
- currentResX: resolutionX,
- currentResY: resolutionY,
- positionX: 0,
- positionY: 0
- });
- }
- return displays;
- }
-}
-
-exports.graphics = graphics;
-
-
-/***/ }),
-
-/***/ 70657:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// index.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// Contributors: Guillaume Legrain (https://github.com/glegrain)
-// Riccardo Novaglia (https://github.com/richy24)
-// Quentin Busuttil (https://github.com/Buzut)
-// Lapsio (https://github.com/lapsio)
-// csy (https://github.com/csy1983)
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-
-// ----------------------------------------------------------------------------------
-// Dependencies
-// ----------------------------------------------------------------------------------
-
-const lib_version = (__nccwpck_require__(15460)/* .version */ .rE);
-const util = __nccwpck_require__(33225);
-const system = __nccwpck_require__(50936);
-const osInfo = __nccwpck_require__(70255);
-const cpu = __nccwpck_require__(93739);
-const memory = __nccwpck_require__(30958);
-const battery = __nccwpck_require__(35552);
-const graphics = __nccwpck_require__(49404);
-const filesystem = __nccwpck_require__(43022);
-const network = __nccwpck_require__(20287);
-const wifi = __nccwpck_require__(81180);
-const processes = __nccwpck_require__(76340);
-const users = __nccwpck_require__(93069);
-const internet = __nccwpck_require__(27336);
-const docker = __nccwpck_require__(31865);
-const vbox = __nccwpck_require__(3881);
-const printer = __nccwpck_require__(14497);
-const usb = __nccwpck_require__(66223);
-const audio = __nccwpck_require__(47411);
-const bluetooth = __nccwpck_require__(45595);
-
-let _platform = process.platform;
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-// ----------------------------------------------------------------------------------
-// init
-// ----------------------------------------------------------------------------------
-
-if (_windows) {
- util.getCodepage();
-}
-
-// ----------------------------------------------------------------------------------
-// General
-// ----------------------------------------------------------------------------------
-
-function version() {
- return lib_version;
-}
-
-// ----------------------------------------------------------------------------------
-// Get static and dynamic data (all)
-// ----------------------------------------------------------------------------------
-
-// --------------------------
-// get static data - they should not change until restarted
-
-function getStaticData(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let data = {};
-
- data.version = version();
-
- Promise.all([
- system.system(),
- system.bios(),
- system.baseboard(),
- system.chassis(),
- osInfo.osInfo(),
- osInfo.uuid(),
- osInfo.versions(),
- cpu.cpu(),
- cpu.cpuFlags(),
- graphics.graphics(),
- network.networkInterfaces(),
- memory.memLayout(),
- filesystem.diskLayout()
- ]).then((res) => {
- data.system = res[0];
- data.bios = res[1];
- data.baseboard = res[2];
- data.chassis = res[3];
- data.os = res[4];
- data.uuid = res[5];
- data.versions = res[6];
- data.cpu = res[7];
- data.cpu.flags = res[8];
- data.graphics = res[9];
- data.net = res[10];
- data.memLayout = res[11];
- data.diskLayout = res[12];
- if (callback) { callback(data); }
- resolve(data);
- });
- });
- });
-}
-
-
-// --------------------------
-// get all dynamic data - e.g. for monitoring agents
-// may take some seconds to get all data
-// --------------------------
-// 2 additional parameters needed
-// - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql"
-// - iface: define network interface for which you like to monitor network speed e.g. "eth0"
-
-function getDynamicData(srv, iface, callback) {
-
- if (util.isFunction(iface)) {
- callback = iface;
- iface = '';
- }
- if (util.isFunction(srv)) {
- callback = srv;
- srv = '';
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- iface = iface || network.getDefaultNetworkInterface();
- srv = srv || '';
-
- // use closure to track ƒ completion
- let functionProcessed = (function () {
- let totalFunctions = 15;
- if (_windows) { totalFunctions = 13; }
- if (_freebsd || _openbsd || _netbsd) { totalFunctions = 11; }
- if (_sunos) { totalFunctions = 6; }
-
- return function () {
- if (--totalFunctions === 0) {
- if (callback) {
- callback(data);
- }
- resolve(data);
- }
- };
- })();
-
- let data = {};
-
- // get time
- data.time = osInfo.time();
-
- /**
- * @namespace
- * @property {Object} versions
- * @property {string} versions.node
- * @property {string} versions.v8
- */
- data.node = process.versions.node;
- data.v8 = process.versions.v8;
-
- cpu.cpuCurrentSpeed().then((res) => {
- data.cpuCurrentSpeed = res;
- functionProcessed();
- });
-
- users.users().then((res) => {
- data.users = res;
- functionProcessed();
- });
-
- processes.processes().then((res) => {
- data.processes = res;
- functionProcessed();
- });
-
- cpu.currentLoad().then((res) => {
- data.currentLoad = res;
- functionProcessed();
- });
-
- if (!_sunos) {
- cpu.cpuTemperature().then((res) => {
- data.temp = res;
- functionProcessed();
- });
- }
-
- if (!_openbsd && !_freebsd && !_netbsd && !_sunos) {
- network.networkStats(iface).then((res) => {
- data.networkStats = res;
- functionProcessed();
- });
- }
-
- if (!_sunos) {
- network.networkConnections().then((res) => {
- data.networkConnections = res;
- functionProcessed();
- });
- }
-
- memory.mem().then((res) => {
- data.mem = res;
- functionProcessed();
- });
-
- if (!_sunos) {
- battery().then((res) => {
- data.battery = res;
- functionProcessed();
- });
- }
-
- if (!_sunos) {
- processes.services(srv).then((res) => {
- data.services = res;
- functionProcessed();
- });
- }
-
- if (!_sunos) {
- filesystem.fsSize().then((res) => {
- data.fsSize = res;
- functionProcessed();
- });
- }
-
- if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) {
- filesystem.fsStats().then((res) => {
- data.fsStats = res;
- functionProcessed();
- });
- }
-
- if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) {
- filesystem.disksIO().then((res) => {
- data.disksIO = res;
- functionProcessed();
- });
- }
-
- if (!_openbsd && !_freebsd && !_netbsd && !_sunos) {
- wifi.wifiNetworks().then((res) => {
- data.wifiNetworks = res;
- functionProcessed();
- });
- }
-
- internet.inetLatency().then((res) => {
- data.inetLatency = res;
- functionProcessed();
- });
- });
- });
-}
-
-// --------------------------
-// get all data at once
-// --------------------------
-// 2 additional parameters needed
-// - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql"
-// - iface: define network interface for which you like to monitor network speed e.g. "eth0"
-
-function getAllData(srv, iface, callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let data = {};
-
- if (iface && util.isFunction(iface) && !callback) {
- callback = iface;
- iface = '';
- }
-
- if (srv && util.isFunction(srv) && !iface && !callback) {
- callback = srv;
- srv = '';
- iface = '';
- }
-
- getStaticData().then((res) => {
- data = res;
- getDynamicData(srv, iface).then((res) => {
- for (let key in res) {
- if ({}.hasOwnProperty.call(res, key)) {
- data[key] = res[key];
- }
- }
- if (callback) { callback(data); }
- resolve(data);
- });
- });
- });
- });
-}
-
-function get(valueObject, callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- const allPromises = Object.keys(valueObject)
- .filter(func => ({}.hasOwnProperty.call(exports, func)))
- .map(func => {
- const params = valueObject[func].substring(valueObject[func].lastIndexOf('(') + 1, valueObject[func].lastIndexOf(')'));
- let funcWithoutParams = func.indexOf(')') >= 0 ? func.split(')')[1].trim() : func;
- funcWithoutParams = func.indexOf('|') >= 0 ? func.split('|')[0].trim() : funcWithoutParams;
- if (params) {
- return exports[funcWithoutParams](params);
- } else {
- return exports[funcWithoutParams]('');
- }
- });
-
- Promise.all(allPromises).then((data) => {
- const result = {};
- let i = 0;
- for (let key in valueObject) {
- if ({}.hasOwnProperty.call(valueObject, key) && {}.hasOwnProperty.call(exports, key) && data.length > i) {
- if (valueObject[key] === '*' || valueObject[key] === 'all') {
- result[key] = data[i];
- } else {
- let keys = valueObject[key];
- let filter = '';
- let filterParts = [];
- // remove params
- if (keys.indexOf(')') >= 0) {
- keys = keys.split(')')[1].trim();
- }
- // extract filter and remove it from keys
- if (keys.indexOf('|') >= 0) {
- filter = keys.split('|')[1].trim();
- filterParts = filter.split(':');
-
- keys = keys.split('|')[0].trim();
- }
- keys = keys.replace(/,/g, ' ').replace(/ +/g, ' ').split(' ');
- if (data[i]) {
- if (Array.isArray(data[i])) {
- // result is in an array, go through all elements of array and pick only the right ones
- const partialArray = [];
- data[i].forEach(element => {
- let partialRes = {};
- if (keys.length === 1 && (keys[0] === '*' || keys[0] === 'all')) {
- partialRes = element;
- } else {
- keys.forEach(k => {
- if ({}.hasOwnProperty.call(element, k)) {
- partialRes[k] = element[k];
- }
- });
- }
- // if there is a filter, then just take those elements
- if (filter && filterParts.length === 2) {
- if ({}.hasOwnProperty.call(partialRes, filterParts[0].trim())) {
- const val = partialRes[filterParts[0].trim()];
- if (typeof val == 'number') {
- if (val === parseFloat(filterParts[1].trim())) {
- partialArray.push(partialRes);
- }
- } else if (typeof val == 'string') {
- if (val.toLowerCase() === filterParts[1].trim().toLowerCase()) {
- partialArray.push(partialRes);
- }
- }
- }
- } else {
- partialArray.push(partialRes);
- }
-
- });
- result[key] = partialArray;
- } else {
- const partialRes = {};
- keys.forEach(k => {
- if ({}.hasOwnProperty.call(data[i], k)) {
- partialRes[k] = data[i][k];
- }
- });
- result[key] = partialRes;
- }
- } else {
- result[key] = {};
- }
- }
- i++;
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- });
-}
-
-function observe(valueObject, interval, callback) {
- let _data = null;
-
- const result = setInterval(() => {
- get(valueObject).then((data) => {
- if (JSON.stringify(_data) !== JSON.stringify(data)) {
- _data = Object.assign({}, data);
- callback(data);
- }
- });
- }, interval);
- return result;
-}
-
-// ----------------------------------------------------------------------------------
-// export all libs
-// ----------------------------------------------------------------------------------
-
-exports.version = version;
-exports.system = system.system;
-exports.bios = system.bios;
-exports.baseboard = system.baseboard;
-exports.chassis = system.chassis;
-
-exports.time = osInfo.time;
-exports.osInfo = osInfo.osInfo;
-exports.versions = osInfo.versions;
-exports.shell = osInfo.shell;
-exports.uuid = osInfo.uuid;
-
-exports.cpu = cpu.cpu;
-exports.cpuFlags = cpu.cpuFlags;
-exports.cpuCache = cpu.cpuCache;
-exports.cpuCurrentSpeed = cpu.cpuCurrentSpeed;
-exports.cpuTemperature = cpu.cpuTemperature;
-exports.currentLoad = cpu.currentLoad;
-exports.fullLoad = cpu.fullLoad;
-
-exports.mem = memory.mem;
-exports.memLayout = memory.memLayout;
-
-exports.battery = battery;
-
-exports.graphics = graphics.graphics;
-
-exports.fsSize = filesystem.fsSize;
-exports.fsOpenFiles = filesystem.fsOpenFiles;
-exports.blockDevices = filesystem.blockDevices;
-exports.fsStats = filesystem.fsStats;
-exports.disksIO = filesystem.disksIO;
-exports.diskLayout = filesystem.diskLayout;
-
-exports.networkInterfaceDefault = network.networkInterfaceDefault;
-exports.networkGatewayDefault = network.networkGatewayDefault;
-exports.networkInterfaces = network.networkInterfaces;
-exports.networkStats = network.networkStats;
-exports.networkConnections = network.networkConnections;
-
-exports.wifiNetworks = wifi.wifiNetworks;
-exports.wifiInterfaces = wifi.wifiInterfaces;
-exports.wifiConnections = wifi.wifiConnections;
-
-exports.services = processes.services;
-exports.processes = processes.processes;
-exports.processLoad = processes.processLoad;
-
-exports.users = users.users;
-
-exports.inetChecksite = internet.inetChecksite;
-exports.inetLatency = internet.inetLatency;
-
-exports.dockerInfo = docker.dockerInfo;
-exports.dockerImages = docker.dockerImages;
-exports.dockerContainers = docker.dockerContainers;
-exports.dockerContainerStats = docker.dockerContainerStats;
-exports.dockerContainerProcesses = docker.dockerContainerProcesses;
-exports.dockerVolumes = docker.dockerVolumes;
-exports.dockerAll = docker.dockerAll;
-
-exports.vboxInfo = vbox.vboxInfo;
-
-exports.printer = printer.printer;
-
-exports.usb = usb.usb;
-
-exports.audio = audio.audio;
-exports.bluetoothDevices = bluetooth.bluetoothDevices;
-
-exports.getStaticData = getStaticData;
-exports.getDynamicData = getDynamicData;
-exports.getAllData = getAllData;
-exports.get = get;
-exports.observe = observe;
-
-exports.powerShellStart = util.powerShellStart;
-exports.powerShellRelease = util.powerShellRelease;
-
-
-/***/ }),
-
-/***/ 27336:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// internet.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 12. Internet
-// ----------------------------------------------------------------------------------
-
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-// --------------------------
-// check if external site is available
-
-function inetChecksite(url, callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
- url: url,
- ok: false,
- status: 404,
- ms: null
- };
- if (typeof url !== 'string') {
- if (callback) { callback(result); }
- return resolve(result);
- }
- let urlSanitized = '';
- const s = util.sanitizeShellString(url, true);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- try {
- s[i].__proto__.toLowerCase = util.stringToLower;
- } catch (e) {
- Object.setPrototypeOf(s[i], util.stringObj);
- }
-
- const sl = s[i].toLowerCase();
- if (sl && sl[0] && !sl[1] && sl[0].length === 1) {
- urlSanitized = urlSanitized + sl[0];
- }
- }
- }
- result.url = urlSanitized;
- try {
- if (urlSanitized && !util.isPrototypePolluted()) {
- try {
- urlSanitized.__proto__.startsWith = util.stringStartWith;
- } catch (e) {
- Object.setPrototypeOf(urlSanitized, util.stringObj);
- }
-
- if (urlSanitized.startsWith('file:') || urlSanitized.startsWith('gopher:') || urlSanitized.startsWith('telnet:') || urlSanitized.startsWith('mailto:') || urlSanitized.startsWith('news:') || urlSanitized.startsWith('nntp:')) {
- if (callback) { callback(result); }
- return resolve(result);
- }
-
- util.checkWebsite(urlSanitized).then((res) => {
- result.status = res.statusCode;
- result.ok = res.statusCode >= 200 && res.statusCode <= 399;;
- result.ms = (result.ok ? res.time : null);
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } catch (err) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
-}
-
-exports.inetChecksite = inetChecksite;
-
-// --------------------------
-// check inet latency
-
-function inetLatency(host, callback) {
-
- // fallback - if only callback is given
- if (util.isFunction(host) && !callback) {
- callback = host;
- host = '';
- }
-
- host = host || '8.8.8.8';
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (typeof host !== 'string') {
- if (callback) { callback(null); }
- return resolve(null);
- }
- let hostSanitized = '';
- const s = (util.isPrototypePolluted() ? '8.8.8.8' : util.sanitizeShellString(host, true)).trim();
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (!(s[i] === undefined)) {
- try {
- s[i].__proto__.toLowerCase = util.stringToLower;
- } catch (e) {
- Object.setPrototypeOf(s[i], util.stringObj);
- }
-
- const sl = s[i].toLowerCase();
- if (sl && sl[0] && !sl[1]) {
- hostSanitized = hostSanitized + sl[0];
- }
- }
- }
- try {
- hostSanitized.__proto__.startsWith = util.stringStartWith;
- } catch (e) {
- Object.setPrototypeOf(hostSanitized, util.stringObj);
- }
-
- if (hostSanitized.startsWith('file:') || hostSanitized.startsWith('gopher:') || hostSanitized.startsWith('telnet:') || hostSanitized.startsWith('mailto:') || hostSanitized.startsWith('news:') || hostSanitized.startsWith('nntp:')) {
- if (callback) { callback(null); }
- return resolve(null);
- }
- let params;
- if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
- if (_linux) {
- params = ['-c', '2', '-w', '3', hostSanitized];
- }
- if (_freebsd || _openbsd || _netbsd) {
- params = ['-c', '2', '-t', '3', hostSanitized];
- }
- if (_darwin) {
- params = ['-c2', '-t3', hostSanitized];
- }
- util.execSafe('ping', params).then((stdout) => {
- let result = null;
- if (stdout) {
- const lines = stdout.split('\n').filter((line) => (line.indexOf('rtt') >= 0 || line.indexOf('round-trip') >= 0 || line.indexOf('avg') >= 0)).join('\n');
-
- const line = lines.split('=');
- if (line.length > 1) {
- const parts = line[1].split('/');
- if (parts.length > 1) {
- result = parseFloat(parts[1]);
- }
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- const params = ['-s', '-a', hostSanitized, '56', '2'];
- const filt = 'avg';
- util.execSafe('ping', params, { timeout: 3000 }).then((stdout) => {
- let result = null;
- if (stdout) {
- const lines = stdout.split('\n').filter(line => line.indexOf(filt) >= 0).join('\n');
- const line = lines.split('=');
- if (line.length > 1) {
- const parts = line[1].split('/');
- if (parts.length > 1) {
- result = parseFloat(parts[1].replace(',', '.'));
- }
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_windows) {
- let result = null;
- try {
- const params = [hostSanitized, '-n', '1'];
- util.execSafe('ping', params, util.execOptsWin).then((stdout) => {
- if (stdout) {
- let lines = stdout.split('\r\n');
- lines.shift();
- lines.forEach(function (line) {
- if ((line.toLowerCase().match(/ms/g) || []).length === 3) {
- let l = line.replace(/ +/g, ' ').split(' ');
- if (l.length > 6) {
- result = parseFloat(l[l.length - 1]);
- }
- }
- });
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.inetLatency = inetLatency;
-
-
-/***/ }),
-
-/***/ 30958:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// memory.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 5. Memory
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const util = __nccwpck_require__(33225);
-const fs = __nccwpck_require__(79896);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-const OSX_RAM_manufacturers = {
- '0x014F': 'Transcend Information',
- '0x2C00': 'Micron Technology Inc.',
- '0x802C': 'Micron Technology Inc.',
- '0x80AD': 'Hynix Semiconductor Inc.',
- '0x80CE': 'Samsung Electronics Inc.',
- '0xAD00': 'Hynix Semiconductor Inc.',
- '0xCE00': 'Samsung Electronics Inc.',
- '0x02FE': 'Elpida',
- '0x5105': 'Qimonda AG i. In.',
- '0x8551': 'Qimonda AG i. In.',
- '0x859B': 'Crucial',
- '0x04CD': 'G-Skill'
-};
-
-const LINUX_RAM_manufacturers = {
- '017A': 'Apacer',
- '0198': 'HyperX',
- '029E': 'Corsair',
- '04CB': 'A-DATA',
- '04CD': 'G-Skill',
- '059B': 'Crucial',
- '00CE': 'Samsung',
- '1315': 'Crucial',
- '014F': 'Transcend Information',
- '2C00': 'Micron Technology Inc.',
- '802C': 'Micron Technology Inc.',
- '80AD': 'Hynix Semiconductor Inc.',
- '80CE': 'Samsung Electronics Inc.',
- 'AD00': 'Hynix Semiconductor Inc.',
- 'CE00': 'Samsung Electronics Inc.',
- '02FE': 'Elpida',
- '5105': 'Qimonda AG i. In.',
- '8551': 'Qimonda AG i. In.',
- '859B': 'Crucial'
-};
-
-// _______________________________________________________________________________________
-// | R A M | H D |
-// |______________________|_________________________| | |
-// | active buffers/cache | | |
-// |________________________________________________|___________|_________|______________|
-// | used free | used free |
-// |____________________________________________________________|________________________|
-// | total | swap |
-// |____________________________________________________________|________________________|
-
-// free (older versions)
-// ----------------------------------
-// # free
-// total used free shared buffers cached
-// Mem: 16038 (1) 15653 (2) 384 (3) 0 (4) 236 (5) 14788 (6)
-// -/+ buffers/cache: 628 (7) 15409 (8)
-// Swap: 16371 83 16288
-//
-// |------------------------------------------------------------|
-// | R A M |
-// |______________________|_____________________________________|
-// | active (2-(5+6) = 7) | available (3+5+6 = 8) |
-// |______________________|_________________________|___________|
-// | active | buffers/cache (5+6) | |
-// |________________________________________________|___________|
-// | used (2) | free (3) |
-// |____________________________________________________________|
-// | total (1) |
-// |____________________________________________________________|
-
-//
-// free (since free von procps-ng 3.3.10)
-// ----------------------------------
-// # free
-// total used free shared buffers/cache available
-// Mem: 16038 (1) 628 (2) 386 (3) 0 (4) 15024 (5) 14788 (6)
-// Swap: 16371 83 16288
-//
-// |------------------------------------------------------------|
-// | R A M |
-// |______________________|_____________________________________|
-// | | available (6) estimated |
-// |______________________|_________________________|___________|
-// | active (2) | buffers/cache (5) | free (3) |
-// |________________________________________________|___________|
-// | total (1) |
-// |____________________________________________________________|
-//
-// Reference: http://www.software-architect.net/blog/article/date/2015/06/12/-826c6e5052.html
-
-// /procs/meminfo - sample (all in kB)
-//
-// MemTotal: 32806380 kB
-// MemFree: 17977744 kB
-// MemAvailable: 19768972 kB
-// Buffers: 517028 kB
-// Cached: 2161876 kB
-// SwapCached: 456 kB
-// Active: 12081176 kB
-// Inactive: 2164616 kB
-// Active(anon): 10832884 kB
-// Inactive(anon): 1477272 kB
-// Active(file): 1248292 kB
-// Inactive(file): 687344 kB
-// Unevictable: 0 kB
-// Mlocked: 0 kB
-// SwapTotal: 16768892 kB
-// SwapFree: 16768304 kB
-// Dirty: 268 kB
-// Writeback: 0 kB
-// AnonPages: 11568832 kB
-// Mapped: 719992 kB
-// Shmem: 743272 kB
-// Slab: 335716 kB
-// SReclaimable: 256364 kB
-// SUnreclaim: 79352 kB
-
-function mem(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- total: os.totalmem(),
- free: os.freemem(),
- used: os.totalmem() - os.freemem(),
-
- active: os.totalmem() - os.freemem(), // temporarily (fallback)
- available: os.freemem(), // temporarily (fallback)
- buffers: 0,
- cached: 0,
- slab: 0,
- buffcache: 0,
-
- swaptotal: 0,
- swapused: 0,
- swapfree: 0,
- writeback: null,
- dirty: null
- };
-
- if (_linux) {
- try {
- fs.readFile('/proc/meminfo', function (error, stdout) {
- if (!error) {
- const lines = stdout.toString().split('\n');
- result.total = parseInt(util.getValue(lines, 'memtotal'), 10);
- result.total = result.total ? result.total * 1024 : os.totalmem();
- result.free = parseInt(util.getValue(lines, 'memfree'), 10);
- result.free = result.free ? result.free * 1024 : os.freemem();
- result.used = result.total - result.free;
-
- result.buffers = parseInt(util.getValue(lines, 'buffers'), 10);
- result.buffers = result.buffers ? result.buffers * 1024 : 0;
- result.cached = parseInt(util.getValue(lines, 'cached'), 10);
- result.cached = result.cached ? result.cached * 1024 : 0;
- result.slab = parseInt(util.getValue(lines, 'slab'), 10);
- result.slab = result.slab ? result.slab * 1024 : 0;
- result.buffcache = result.buffers + result.cached + result.slab;
-
- let available = parseInt(util.getValue(lines, 'memavailable'), 10);
- result.available = available ? available * 1024 : result.free + result.buffcache;
- result.active = result.total - result.available;
-
- result.swaptotal = parseInt(util.getValue(lines, 'swaptotal'), 10);
- result.swaptotal = result.swaptotal ? result.swaptotal * 1024 : 0;
- result.swapfree = parseInt(util.getValue(lines, 'swapfree'), 10);
- result.swapfree = result.swapfree ? result.swapfree * 1024 : 0;
- result.swapused = result.swaptotal - result.swapfree;
- result.writeback = parseInt(util.getValue(lines, 'writeback'), 10);
- result.writeback = result.writeback ? result.writeback * 1024 : 0;
- result.dirty = parseInt(util.getValue(lines, 'dirty'), 10);
- result.dirty = result.dirty ? result.dirty * 1024 : 0;
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- try {
- exec('/sbin/sysctl hw.realmem hw.physmem vm.stats.vm.v_page_count vm.stats.vm.v_wire_count vm.stats.vm.v_active_count vm.stats.vm.v_inactive_count vm.stats.vm.v_cache_count vm.stats.vm.v_free_count vm.stats.vm.v_page_size', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- const pagesize = parseInt(util.getValue(lines, 'vm.stats.vm.v_page_size'), 10);
- const inactive = parseInt(util.getValue(lines, 'vm.stats.vm.v_inactive_count'), 10) * pagesize;
- const cache = parseInt(util.getValue(lines, 'vm.stats.vm.v_cache_count'), 10) * pagesize;
-
- result.total = parseInt(util.getValue(lines, 'hw.realmem'), 10);
- if (isNaN(result.total)) { result.total = parseInt(util.getValue(lines, 'hw.physmem'), 10); }
- result.free = parseInt(util.getValue(lines, 'vm.stats.vm.v_free_count'), 10) * pagesize;
- result.buffcache = inactive + cache;
- result.available = result.buffcache + result.free;
- result.active = result.total - result.free - result.buffcache;
-
- result.swaptotal = 0;
- result.swapfree = 0;
- result.swapused = 0;
-
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_darwin) {
- let pageSize = 4096;
- try {
- let sysPpageSize = util.toInt(execSync('sysctl -n vm.pagesize').toString());
- pageSize = sysPpageSize || pageSize;
- } catch (e) {
- util.noop();
- }
- try {
- exec('vm_stat 2>/dev/null | grep "Pages active"', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
-
- result.active = parseInt(lines[0].split(':')[1], 10) * pageSize;
- result.buffcache = result.used - result.active;
- result.available = result.free + result.buffcache;
- }
- exec('sysctl -n vm.swapusage 2>/dev/null', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- if (lines.length > 0) {
- let firstline = lines[0].replace(/,/g, '.').replace(/M/g, '');
- let lineArray = firstline.trim().split(' ');
- lineArray.forEach(line => {
- if (line.toLowerCase().indexOf('total') !== -1) { result.swaptotal = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
- if (line.toLowerCase().indexOf('used') !== -1) { result.swapused = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
- if (line.toLowerCase().indexOf('free') !== -1) { result.swapfree = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
- });
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_windows) {
- let swaptotal = 0;
- let swapused = 0;
- try {
- util.powerShell('Get-CimInstance Win32_PageFileUsage | Select AllocatedBaseSize, CurrentUsage').then((stdout, error) => {
- if (!error) {
- let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
- lines.forEach(function (line) {
- if (line !== '') {
- line = line.trim().split(/\s\s+/);
- swaptotal = swaptotal + (parseInt(line[0], 10) || 0);
- swapused = swapused + (parseInt(line[1], 10) || 0);
- }
- });
- }
- result.swaptotal = swaptotal * 1024 * 1024;
- result.swapused = swapused * 1024 * 1024;
- result.swapfree = result.swaptotal - result.swapused;
-
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.mem = mem;
-
-function memLayout(callback) {
-
- function getManufacturerDarwin(manId) {
- if ({}.hasOwnProperty.call(OSX_RAM_manufacturers, manId)) {
- return (OSX_RAM_manufacturers[manId]);
- }
- return manId;
- }
-
- function getManufacturerLinux(manId) {
- const manIdSearch = manId.replace('0x', '').toUpperCase();
- if (manIdSearch.length === 4 && {}.hasOwnProperty.call(LINUX_RAM_manufacturers, manIdSearch)) {
- return (LINUX_RAM_manufacturers[manIdSearch]);
- }
- return manId;
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = [];
-
- if (_linux || _freebsd || _openbsd || _netbsd) {
- exec('export LC_ALL=C; dmidecode -t memory 2>/dev/null | grep -iE "Size:|Type|Speed|Manufacturer|Form Factor|Locator|Memory Device|Serial Number|Voltage|Part Number"; unset LC_ALL', function (error, stdout) {
- if (!error) {
- let devices = stdout.toString().split('Memory Device');
- devices.shift();
- devices.forEach(function (device) {
- let lines = device.split('\n');
- const sizeString = util.getValue(lines, 'Size');
- const size = sizeString.indexOf('GB') >= 0 ? parseInt(sizeString, 10) * 1024 * 1024 * 1024 : parseInt(sizeString, 10) * 1024 * 1024;
- let bank = util.getValue(lines, 'Bank Locator');
- if (bank.toLowerCase().indexOf('bad') >= 0) {
- bank = '';
- }
- if (parseInt(util.getValue(lines, 'Size'), 10) > 0) {
- const totalWidth = util.toInt(util.getValue(lines, 'Total Width'));
- const dataWidth = util.toInt(util.getValue(lines, 'Data Width'));
- result.push({
- size,
- bank,
- type: util.getValue(lines, 'Type:'),
- ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false,
- clockSpeed: (util.getValue(lines, 'Configured Clock Speed:') ? parseInt(util.getValue(lines, 'Configured Clock Speed:'), 10) : (util.getValue(lines, 'Speed:') ? parseInt(util.getValue(lines, 'Speed:'), 10) : null)),
- formFactor: util.getValue(lines, 'Form Factor:'),
- manufacturer: getManufacturerLinux(util.getValue(lines, 'Manufacturer:')),
- partNum: util.getValue(lines, 'Part Number:'),
- serialNum: util.getValue(lines, 'Serial Number:'),
- voltageConfigured: parseFloat(util.getValue(lines, 'Configured Voltage:')) || null,
- voltageMin: parseFloat(util.getValue(lines, 'Minimum Voltage:')) || null,
- voltageMax: parseFloat(util.getValue(lines, 'Maximum Voltage:')) || null,
- });
- } else {
- result.push({
- size: 0,
- bank,
- type: 'Empty',
- ecc: null,
- clockSpeed: 0,
- formFactor: util.getValue(lines, 'Form Factor:'),
- partNum: '',
- serialNum: '',
- voltageConfigured: null,
- voltageMin: null,
- voltageMax: null,
- });
- }
- });
- }
- if (!result.length) {
- result.push({
- size: os.totalmem(),
- bank: '',
- type: '',
- ecc: null,
- clockSpeed: 0,
- formFactor: '',
- partNum: '',
- serialNum: '',
- voltageConfigured: null,
- voltageMin: null,
- voltageMax: null,
- });
-
- // Try Raspberry PI
- try {
- let stdout = execSync('cat /proc/cpuinfo 2>/dev/null', util.execOptsLinux);
- let lines = stdout.toString().split('\n');
- let model = util.getValue(lines, 'hardware', ':', true).toUpperCase();
- let version = util.getValue(lines, 'revision', ':', true).toLowerCase();
-
- if (model === 'BCM2835' || model === 'BCM2708' || model === 'BCM2709' || model === 'BCM2835' || model === 'BCM2837') {
-
- const clockSpeed = {
- '0': 400,
- '1': 450,
- '2': 450,
- '3': 3200
- };
- result[0].type = 'LPDDR2';
- result[0].type = version && version[2] && version[2] === '3' ? 'LPDDR4' : result[0].type;
- result[0].ecc = false;
- result[0].clockSpeed = version && version[2] && clockSpeed[version[2]] || 400;
- result[0].clockSpeed = version && version[4] && version[4] === 'd' ? 500 : result[0].clockSpeed;
- result[0].formFactor = 'SoC';
-
- stdout = execSync('vcgencmd get_config sdram_freq 2>/dev/null', util.execOptsLinux);
- lines = stdout.toString().split('\n');
- let freq = parseInt(util.getValue(lines, 'sdram_freq', '=', true), 10) || 0;
- if (freq) {
- result[0].clockSpeed = freq;
- }
-
- stdout = execSync('vcgencmd measure_volts sdram_p 2>/dev/null', util.execOptsLinux);
- lines = stdout.toString().split('\n');
- let voltage = parseFloat(util.getValue(lines, 'volt', '=', true)) || 0;
- if (voltage) {
- result[0].voltageConfigured = voltage;
- result[0].voltageMin = voltage;
- result[0].voltageMax = voltage;
- }
- }
- } catch (e) {
- util.noop();
- }
-
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
-
- if (_darwin) {
- exec('system_profiler SPMemoryDataType', function (error, stdout) {
- if (!error) {
- const allLines = stdout.toString().split('\n');
- const eccStatus = util.getValue(allLines, 'ecc', ':', true).toLowerCase();
- let devices = stdout.toString().split(' BANK ');
- let hasBank = true;
- if (devices.length === 1) {
- devices = stdout.toString().split(' DIMM');
- hasBank = false;
- }
- devices.shift();
- devices.forEach(function (device) {
- let lines = device.split('\n');
- const bank = (hasBank ? 'BANK ' : 'DIMM') + lines[0].trim().split('/')[0];
- const size = parseInt(util.getValue(lines, ' Size'));
- if (size) {
- result.push({
- size: size * 1024 * 1024 * 1024,
- bank: bank,
- type: util.getValue(lines, ' Type:'),
- ecc: eccStatus ? eccStatus === 'enabled' : null,
- clockSpeed: parseInt(util.getValue(lines, ' Speed:'), 10),
- formFactor: '',
- manufacturer: getManufacturerDarwin(util.getValue(lines, ' Manufacturer:')),
- partNum: util.getValue(lines, ' Part Number:'),
- serialNum: util.getValue(lines, ' Serial Number:'),
- voltageConfigured: null,
- voltageMin: null,
- voltageMax: null,
- });
- } else {
- result.push({
- size: 0,
- bank: bank,
- type: 'Empty',
- ecc: null,
- clockSpeed: 0,
- formFactor: '',
- manufacturer: '',
- partNum: '',
- serialNum: '',
- voltageConfigured: null,
- voltageMin: null,
- voltageMax: null,
- });
- }
- });
- }
- if (!result.length) {
- const lines = stdout.toString().split('\n');
- const size = parseInt(util.getValue(lines, ' Memory:'));
- const type = util.getValue(lines, ' Type:');
- const manufacturerId = util.getValue(lines, ' Manufacturer:');
- if (size && type) {
- result.push({
- size: size * 1024 * 1024 * 1024,
- bank: '0',
- type,
- ecc: false,
- clockSpeed: null,
- formFactor: 'SOC',
- manufacturer: getManufacturerDarwin(manufacturerId),
- partNum: '',
- serialNum: '',
- voltageConfigured: null,
- voltageMin: null,
- voltageMax: null,
- });
-
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- // https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0a.pdf
- const memoryTypes = 'Unknown|Other|DRAM|Synchronous DRAM|Cache DRAM|EDO|EDRAM|VRAM|SRAM|RAM|ROM|FLASH|EEPROM|FEPROM|EPROM|CDRAM|3DRAM|SDRAM|SGRAM|RDRAM|DDR|DDR2|DDR2 FB-DIMM|Reserved|DDR3|FBD2|DDR4|LPDDR|LPDDR2|LPDDR3|LPDDR4|Logical non-volatile device|HBM|HBM2|DDR5|LPDDR5'.split('|');
- const FormFactors = 'Unknown|Other|SIP|DIP|ZIP|SOJ|Proprietary|SIMM|DIMM|TSOP|PGA|RIMM|SODIMM|SRIMM|SMD|SSMP|QFP|TQFP|SOIC|LCC|PLCC|BGA|FPBGA|LGA'.split('|');
-
- try {
- util.powerShell('Get-CimInstance Win32_PhysicalMemory | select DataWidth,TotalWidth,Capacity,BankLabel,MemoryType,SMBIOSMemoryType,ConfiguredClockSpeed,FormFactor,Manufacturer,PartNumber,SerialNumber,ConfiguredVoltage,MinVoltage,MaxVoltage,Tag | fl').then((stdout, error) => {
- if (!error) {
- let devices = stdout.toString().split(/\n\s*\n/);
- devices.shift();
- devices.forEach(function (device) {
- let lines = device.split('\r\n');
- const dataWidth = util.toInt(util.getValue(lines, 'DataWidth', ':'));
- const totalWidth = util.toInt(util.getValue(lines, 'TotalWidth', ':'));
- const size = parseInt(util.getValue(lines, 'Capacity', ':'), 10) || 0;
- const tag = util.getValue(lines, 'Tag', ':');
- const tagInt = util.splitByNumber(tag);
- if (size) {
- result.push({
- size,
- bank: util.getValue(lines, 'BankLabel', ':') + (tagInt[1] ? '/' + tagInt[1] : ''), // BankLabel
- type: memoryTypes[parseInt(util.getValue(lines, 'MemoryType', ':'), 10) || parseInt(util.getValue(lines, 'SMBIOSMemoryType', ':'), 10)],
- ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false,
- clockSpeed: parseInt(util.getValue(lines, 'ConfiguredClockSpeed', ':'), 10) || parseInt(util.getValue(lines, 'Speed', ':'), 10) || 0,
- formFactor: FormFactors[parseInt(util.getValue(lines, 'FormFactor', ':'), 10) || 0],
- manufacturer: util.getValue(lines, 'Manufacturer', ':'),
- partNum: util.getValue(lines, 'PartNumber', ':'),
- serialNum: util.getValue(lines, 'SerialNumber', ':'),
- voltageConfigured: (parseInt(util.getValue(lines, 'ConfiguredVoltage', ':'), 10) || 0) / 1000.0,
- voltageMin: (parseInt(util.getValue(lines, 'MinVoltage', ':'), 10) || 0) / 1000.0,
- voltageMax: (parseInt(util.getValue(lines, 'MaxVoltage', ':'), 10) || 0) / 1000.0,
- });
- }
- });
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.memLayout = memLayout;
-
-
-
-/***/ }),
-
-/***/ 20287:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// network.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 9. Network
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const fs = __nccwpck_require__(79896);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-let _network = {};
-let _default_iface = '';
-let _ifaces = {};
-let _dhcpNics = [];
-let _networkInterfaces = [];
-let _mac = {};
-let pathToIp;
-
-function getDefaultNetworkInterface() {
-
- let ifacename = '';
- let ifacenameFirst = '';
- try {
- let ifaces = os.networkInterfaces();
-
- let scopeid = 9999;
-
- // fallback - "first" external interface (sorted by scopeid)
- for (let dev in ifaces) {
- if ({}.hasOwnProperty.call(ifaces, dev)) {
- ifaces[dev].forEach(function (details) {
- if (details && details.internal === false) {
- ifacenameFirst = ifacenameFirst || dev; // fallback if no scopeid
- if (details.scopeid && details.scopeid < scopeid) {
- ifacename = dev;
- scopeid = details.scopeid;
- }
- }
- });
- }
- }
- ifacename = ifacename || ifacenameFirst || '';
-
- if (_windows) {
- // https://www.inetdaemon.com/tutorials/internet/ip/routing/default_route.shtml
- let defaultIp = '';
- const cmd = 'netstat -r';
- const result = execSync(cmd, util.execOptsWin);
- const lines = result.toString().split(os.EOL);
- lines.forEach(line => {
- line = line.replace(/\s+/g, ' ').trim();
- if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) {
- const parts = line.split(' ');
- if (parts.length >= 5) {
- defaultIp = parts[parts.length - 2];
- }
- }
- });
- if (defaultIp) {
- for (let dev in ifaces) {
- if ({}.hasOwnProperty.call(ifaces, dev)) {
- ifaces[dev].forEach(function (details) {
- if (details && details.address && details.address === defaultIp) {
- ifacename = dev;
- }
- });
- }
- }
- }
- }
- if (_linux) {
- let cmd = 'ip route 2> /dev/null | grep default';
- let result = execSync(cmd, util.execOptsLinux);
- let parts = result.toString().split('\n')[0].split(/\s+/);
- if (parts[0] === 'none' && parts[5]) {
- ifacename = parts[5];
- } else if (parts[4]) {
- ifacename = parts[4];
- }
-
- if (ifacename.indexOf(':') > -1) {
- ifacename = ifacename.split(':')[1].trim();
- }
- }
- if (_darwin || _freebsd || _openbsd || _netbsd || _sunos) {
- let cmd = '';
- if (_linux) { cmd = 'ip route 2> /dev/null | grep default | awk \'{print $5}\''; }
- if (_darwin) { cmd = 'route -n get default 2>/dev/null | grep interface: | awk \'{print $2}\''; }
- if (_freebsd || _openbsd || _netbsd || _sunos) { cmd = 'route get 0.0.0.0 | grep interface:'; }
- let result = execSync(cmd);
- ifacename = result.toString().split('\n')[0];
- if (ifacename.indexOf(':') > -1) {
- ifacename = ifacename.split(':')[1].trim();
- }
- }
- } catch (e) {
- util.noop();
- }
- if (ifacename) { _default_iface = ifacename; }
- return _default_iface;
-}
-
-exports.getDefaultNetworkInterface = getDefaultNetworkInterface;
-
-function getMacAddresses() {
- let iface = '';
- let mac = '';
- let result = {};
- if (_linux || _freebsd || _openbsd || _netbsd) {
- if (typeof pathToIp === 'undefined') {
- try {
- const lines = execSync('which ip', util.execOptsLinux).toString().split('\n');
- if (lines.length && lines[0].indexOf(':') === -1 && lines[0].indexOf('/') === 0) {
- pathToIp = lines[0];
- } else {
- pathToIp = '';
- }
- } catch (e) {
- pathToIp = '';
- }
- }
- try {
- const cmd = 'export LC_ALL=C; ' + ((pathToIp) ? pathToIp + ' link show up' : '/sbin/ifconfig') + '; unset LC_ALL';
- let res = execSync(cmd, util.execOptsLinux);
- const lines = res.toString().split('\n');
- for (let i = 0; i < lines.length; i++) {
- if (lines[i] && lines[i][0] !== ' ') {
- if (pathToIp) {
- let nextline = lines[i + 1].trim().split(' ');
- if (nextline[0] === 'link/ether') {
- iface = lines[i].split(' ')[1];
- iface = iface.slice(0, iface.length - 1);
- mac = nextline[1];
- }
- } else {
- iface = lines[i].split(' ')[0];
- mac = lines[i].split('HWaddr ')[1];
- }
-
- if (iface && mac) {
- result[iface] = mac.trim();
- iface = '';
- mac = '';
- }
- }
- }
- } catch (e) {
- util.noop();
- }
- }
- if (_darwin) {
- try {
- const cmd = '/sbin/ifconfig';
- let res = execSync(cmd);
- const lines = res.toString().split('\n');
- for (let i = 0; i < lines.length; i++) {
- if (lines[i] && lines[i][0] !== '\t' && lines[i].indexOf(':') > 0) {
- iface = lines[i].split(':')[0];
- } else if (lines[i].indexOf('\tether ') === 0) {
- mac = lines[i].split('\tether ')[1];
- if (iface && mac) {
- result[iface] = mac.trim();
- iface = '';
- mac = '';
- }
- }
- }
- } catch (e) {
- util.noop();
- }
- }
- return result;
-}
-
-function networkInterfaceDefault(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = getDefaultNetworkInterface();
- if (callback) { callback(result); }
- resolve(result);
- });
- });
-}
-
-exports.networkInterfaceDefault = networkInterfaceDefault;
-
-// --------------------------
-// NET - interfaces
-
-function parseLinesWindowsNics(sections, nconfigsections) {
- let nics = [];
- for (let i in sections) {
- try {
- if ({}.hasOwnProperty.call(sections, i)) {
-
- if (sections[i].trim() !== '') {
-
- let lines = sections[i].trim().split('\r\n');
- let linesNicConfig = null;
- try {
- linesNicConfig = nconfigsections && nconfigsections[i] ? nconfigsections[i].trim().split('\r\n') : [];
- } catch (e) {
- util.noop();
- }
- let netEnabled = util.getValue(lines, 'NetEnabled', ':');
- let adapterType = util.getValue(lines, 'AdapterTypeID', ':') === '9' ? 'wireless' : 'wired';
- let ifacename = util.getValue(lines, 'Name', ':').replace(/\]/g, ')').replace(/\[/g, '(');
- let iface = util.getValue(lines, 'NetConnectionID', ':').replace(/\]/g, ')').replace(/\[/g, '(');
- if (ifacename.toLowerCase().indexOf('wi-fi') >= 0 || ifacename.toLowerCase().indexOf('wireless') >= 0) {
- adapterType = 'wireless';
- }
- if (netEnabled !== '') {
- const speed = parseInt(util.getValue(lines, 'speed', ':').trim(), 10) / 1000000;
- nics.push({
- mac: util.getValue(lines, 'MACAddress', ':').toLowerCase(),
- dhcp: util.getValue(linesNicConfig, 'dhcpEnabled', ':').toLowerCase() === 'true',
- name: ifacename,
- iface,
- netEnabled: netEnabled === 'TRUE',
- speed: isNaN(speed) ? null : speed,
- operstate: util.getValue(lines, 'NetConnectionStatus', ':') === '2' ? 'up' : 'down',
- type: adapterType
- });
- }
- }
- }
- } catch (e) {
- util.noop();
- }
- }
- return nics;
-}
-
-function getWindowsNics() {
- return new Promise((resolve) => {
- process.nextTick(() => {
- let cmd = 'Get-CimInstance Win32_NetworkAdapter | fl *' + '; echo \'#-#-#-#\';';
- cmd += 'Get-CimInstance Win32_NetworkAdapterConfiguration | fl DHCPEnabled' + '';
- try {
- util.powerShell(cmd).then((data) => {
- data = data.split('#-#-#-#');
- const nsections = (data[0] || '').split(/\n\s*\n/);
- const nconfigsections = (data[1] || '').split(/\n\s*\n/);
- resolve(parseLinesWindowsNics(nsections, nconfigsections));
- });
- } catch (e) {
- resolve([]);
- }
- });
- });
-}
-
-function getWindowsDNSsuffixes() {
-
- let iface = {};
-
- let dnsSuffixes = {
- primaryDNS: '',
- exitCode: 0,
- ifaces: [],
- };
-
- try {
- const ipconfig = execSync('ipconfig /all', util.execOptsWin);
- const ipconfigArray = ipconfig.split('\r\n\r\n');
-
- ipconfigArray.forEach((element, index) => {
-
- if (index == 1) {
- const longPrimaryDNS = element.split('\r\n').filter((element) => {
- return element.toUpperCase().includes('DNS');
- });
- const primaryDNS = longPrimaryDNS[0].substring(longPrimaryDNS[0].lastIndexOf(':') + 1);
- dnsSuffixes.primaryDNS = primaryDNS.trim();
- if (!dnsSuffixes.primaryDNS) { dnsSuffixes.primaryDNS = 'Not defined'; }
- }
- if (index > 1) {
- if (index % 2 == 0) {
- const name = element.substring(element.lastIndexOf(' ') + 1).replace(':', '');
- iface.name = name;
- } else {
- const connectionSpecificDNS = element.split('\r\n').filter((element) => {
- return element.toUpperCase().includes('DNS');
- });
- const dnsSuffix = connectionSpecificDNS[0].substring(connectionSpecificDNS[0].lastIndexOf(':') + 1);
- iface.dnsSuffix = dnsSuffix.trim();
- dnsSuffixes.ifaces.push(iface);
- iface = {};
- }
- }
- });
-
- return dnsSuffixes;
- } catch (error) {
- return {
- primaryDNS: '',
- exitCode: 0,
- ifaces: [],
- };
- }
-}
-
-function getWindowsIfaceDNSsuffix(ifaces, ifacename) {
- let dnsSuffix = '';
- // Adding (.) to ensure ifacename compatibility when duplicated iface-names
- const interfaceName = ifacename + '.';
- try {
- const connectionDnsSuffix = ifaces.filter((iface) => {
- return interfaceName.includes(iface.name + '.');
- }).map((iface) => iface.dnsSuffix);
- if (connectionDnsSuffix[0]) {
- dnsSuffix = connectionDnsSuffix[0];
- }
- if (!dnsSuffix) { dnsSuffix = ''; }
- return dnsSuffix;
- } catch (error) {
- return 'Unknown';
- }
-}
-
-function getWindowsWiredProfilesInformation() {
- try {
- const result = execSync('netsh lan show profiles', util.execOptsWin);
- const profileList = result.split('\r\nProfile on interface');
- return profileList;
- } catch (error) {
- if (error.status === 1 && error.stdout.includes('AutoConfig')) {
- return 'Disabled';
- }
- return [];
- }
-}
-
-function getWindowsWirelessIfaceSSID(interfaceName) {
- try {
- const result = execSync(`netsh wlan show interface name="${interfaceName}" | findstr "SSID"`, util.execOptsWin);
- const SSID = result.split('\r\n').shift();
- const parseSSID = SSID.split(':').pop().trim();
- return parseSSID;
- } catch (error) {
- return 'Unknown';
- }
-}
-function getWindowsIEEE8021x(connectionType, iface, ifaces) {
- let i8021x = {
- state: 'Unknown',
- protocol: 'Unknown',
- };
-
- if (ifaces === 'Disabled') {
- i8021x.state = 'Disabled';
- i8021x.protocol = 'Not defined';
- return i8021x;
- }
-
- if (connectionType == 'wired' && ifaces.length > 0) {
- try {
- // Get 802.1x information by interface name
- const iface8021xInfo = ifaces.find((element) => {
- return element.includes(iface + '\r\n');
- });
- const arrayIface8021xInfo = iface8021xInfo.split('\r\n');
- const state8021x = arrayIface8021xInfo.find((element) => {
- return element.includes('802.1x');
- });
-
- if (state8021x.includes('Disabled')) {
- i8021x.state = 'Disabled';
- i8021x.protocol = 'Not defined';
- } else if (state8021x.includes('Enabled')) {
- const protocol8021x = arrayIface8021xInfo.find((element) => {
- return element.includes('EAP');
- });
- i8021x.protocol = protocol8021x.split(':').pop();
- i8021x.state = 'Enabled';
- }
- } catch (error) {
- return i8021x;
- }
- } else if (connectionType == 'wireless') {
-
- let i8021xState = '';
- let i8021xProtocol = '';
-
-
-
- try {
- const SSID = getWindowsWirelessIfaceSSID(iface);
- if (SSID !== 'Unknown') {
-
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(SSID);
- const l = util.mathMin(s.length, 32);
-
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
- i8021xState = execSync(`netsh wlan show profiles "${ifaceSanitized}" | findstr "802.1X"`, util.execOptsWin);
- i8021xProtocol = execSync(`netsh wlan show profiles "${ifaceSanitized}" | findstr "EAP"`, util.execOptsWin);
- }
-
- if (i8021xState.includes(':') && i8021xProtocol.includes(':')) {
- i8021x.state = i8021xState.split(':').pop();
- i8021x.protocol = i8021xProtocol.split(':').pop();
- }
- } catch (error) {
- if (error.status === 1 && error.stdout.includes('AutoConfig')) {
- i8021x.state = 'Disabled';
- i8021x.protocol = 'Not defined';
- }
- return i8021x;
- }
- }
-
- return i8021x;
-}
-
-function splitSectionsNics(lines) {
- const result = [];
- let section = [];
- lines.forEach(function (line) {
- if (!line.startsWith('\t') && !line.startsWith(' ')) {
- if (section.length) {
- result.push(section);
- section = [];
- }
- }
- section.push(line);
- });
- if (section.length) {
- result.push(section);
- }
- return result;
-}
-
-function parseLinesDarwinNics(sections) {
- let nics = [];
- sections.forEach(section => {
- let nic = {
- iface: '',
- mtu: null,
- mac: '',
- ip6: '',
- ip4: '',
- speed: null,
- type: '',
- operstate: '',
- duplex: '',
- internal: false
- };
- const first = section[0];
- nic.iface = first.split(':')[0].trim();
- let parts = first.split('> mtu');
- nic.mtu = parts.length > 1 ? parseInt(parts[1], 10) : null;
- if (isNaN(nic.mtu)) {
- nic.mtu = null;
- }
- nic.internal = parts[0].toLowerCase().indexOf('loopback') > -1;
- section.forEach(line => {
- if (line.trim().startsWith('ether ')) {
- nic.mac = line.split('ether ')[1].toLowerCase().trim();
- }
- if (line.trim().startsWith('inet6 ') && !nic.ip6) {
- nic.ip6 = line.split('inet6 ')[1].toLowerCase().split('%')[0].split(' ')[0];
- }
- if (line.trim().startsWith('inet ') && !nic.ip4) {
- nic.ip4 = line.split('inet ')[1].toLowerCase().split(' ')[0];
- }
- });
- let speed = util.getValue(section, 'link rate');
- nic.speed = speed ? parseFloat(speed) : null;
- if (nic.speed === null) {
- speed = util.getValue(section, 'uplink rate');
- nic.speed = speed ? parseFloat(speed) : null;
- if (nic.speed !== null && speed.toLowerCase().indexOf('gbps') >= 0) {
- nic.speed = nic.speed * 1000;
- }
- } else {
- if (speed.toLowerCase().indexOf('gbps') >= 0) {
- nic.speed = nic.speed * 1000;
- }
- }
- nic.type = util.getValue(section, 'type').toLowerCase().indexOf('wi-fi') > -1 ? 'wireless' : 'wired';
- const operstate = util.getValue(section, 'status').toLowerCase();
- nic.operstate = (operstate === 'active' ? 'up' : (operstate === 'inactive' ? 'down' : 'unknown'));
- nic.duplex = util.getValue(section, 'media').toLowerCase().indexOf('half-duplex') > -1 ? 'half' : 'full';
- if (nic.ip6 || nic.ip4 || nic.mac) {
- nics.push(nic);
- }
- });
- return nics;
-}
-
-function getDarwinNics() {
- const cmd = '/sbin/ifconfig -v';
- try {
- const lines = execSync(cmd, { maxBuffer: 1024 * 20000 }).toString().split('\n');
- const nsections = splitSectionsNics(lines);
- return (parseLinesDarwinNics(nsections));
- } catch (e) {
- return [];
- }
-}
-
-function getLinuxIfaceConnectionName(interfaceName) {
- const cmd = `nmcli device status 2>/dev/null | grep ${interfaceName}`;
-
- try {
- const result = execSync(cmd, util.execOptsLinux).toString();
- const resultFormat = result.replace(/\s+/g, ' ').trim();
- const connectionNameLines = resultFormat.split(' ').slice(3);
- const connectionName = connectionNameLines.join(' ');
- return connectionName != '--' ? connectionName : '';
- } catch (e) {
- return '';
- }
-}
-
-function checkLinuxDCHPInterfaces(file) {
- let result = [];
- try {
- let cmd = `cat ${file} 2> /dev/null | grep 'iface\\|source'`;
- const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
-
- lines.forEach(line => {
- const parts = line.replace(/\s+/g, ' ').trim().split(' ');
- if (parts.length >= 4) {
- if (line.toLowerCase().indexOf(' inet ') >= 0 && line.toLowerCase().indexOf('dhcp') >= 0) {
- result.push(parts[1]);
- }
- }
- if (line.toLowerCase().includes('source')) {
- let file = line.split(' ')[1];
- result = result.concat(checkLinuxDCHPInterfaces(file));
- }
- });
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function getLinuxDHCPNics() {
- // alternate methods getting interfaces using DHCP
- let cmd = 'ip a 2> /dev/null';
- let result = [];
- try {
- const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- const nsections = splitSectionsNics(lines);
- result = (parseLinuxDHCPNics(nsections));
- } catch (e) {
- util.noop();
- }
- try {
- result = checkLinuxDCHPInterfaces('/etc/network/interfaces');
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function parseLinuxDHCPNics(sections) {
- const result = [];
- if (sections && sections.length) {
- sections.forEach(lines => {
- if (lines && lines.length) {
- const parts = lines[0].split(':');
- if (parts.length > 2) {
- for (let line of lines) {
- if (line.indexOf(' inet ') >= 0 && line.indexOf(' dynamic ') >= 0) {
- const parts2 = line.split(' ');
- const nic = parts2[parts2.length - 1].trim();
- result.push(nic);
- break;
- }
- }
- }
- }
- });
- }
- return result;
-}
-
-function getLinuxIfaceDHCPstatus(iface, connectionName, DHCPNics) {
- let result = false;
- if (connectionName) {
- const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.method;`;
- try {
- const lines = execSync(cmd, util.execOptsLinux).toString();
- const resultFormat = lines.replace(/\s+/g, ' ').trim();
-
- let dhcStatus = resultFormat.split(' ').slice(1).toString();
- switch (dhcStatus) {
- case 'auto':
- result = true;
- break;
-
- default:
- result = false;
- break;
- }
- return result;
- } catch (e) {
- return (DHCPNics.indexOf(iface) >= 0);
- }
- } else {
- return (DHCPNics.indexOf(iface) >= 0);
- }
-}
-
-function getDarwinIfaceDHCPstatus(iface) {
- let result = false;
- const cmd = `ipconfig getpacket "${iface}" 2>/dev/null | grep lease_time;`;
- try {
- const lines = execSync(cmd).toString().split('\n');
- if (lines.length && lines[0].startsWith('lease_time')) {
- result = true;
- }
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-function getLinuxIfaceDNSsuffix(connectionName) {
- if (connectionName) {
- const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep ipv4.dns-search;`;
- try {
- const result = execSync(cmd, util.execOptsLinux).toString();
- const resultFormat = result.replace(/\s+/g, ' ').trim();
- const dnsSuffix = resultFormat.split(' ').slice(1).toString();
- return dnsSuffix == '--' ? 'Not defined' : dnsSuffix;
- } catch (e) {
- return 'Unknown';
- }
- } else {
- return 'Unknown';
- }
-}
-
-function getLinuxIfaceIEEE8021xAuth(connectionName) {
- if (connectionName) {
- const cmd = `nmcli connection show "${connectionName}" 2>/dev/null | grep 802-1x.eap;`;
- try {
- const result = execSync(cmd, util.execOptsLinux).toString();
- const resultFormat = result.replace(/\s+/g, ' ').trim();
- const authenticationProtocol = resultFormat.split(' ').slice(1).toString();
-
-
- return authenticationProtocol == '--' ? '' : authenticationProtocol;
- } catch (e) {
- return 'Not defined';
- }
- } else {
- return 'Not defined';
- }
-}
-
-function getLinuxIfaceIEEE8021xState(authenticationProtocol) {
- if (authenticationProtocol) {
- if (authenticationProtocol == 'Not defined') {
- return 'Disabled';
- }
- return 'Enabled';
- } else {
- return 'Unknown';
- }
-}
-
-function testVirtualNic(iface, ifaceName, mac) {
- const virtualMacs = ['00:00:00:00:00:00', '00:03:FF', '00:05:69', '00:0C:29', '00:0F:4B', '00:13:07', '00:13:BE', '00:15:5d', '00:16:3E', '00:1C:42', '00:21:F6', '00:24:0B', '00:50:56', '00:A0:B1', '00:E0:C8', '08:00:27', '0A:00:27', '18:92:2C', '16:DF:49', '3C:F3:92', '54:52:00', 'FC:15:97'];
- if (mac) {
- return virtualMacs.filter(item => { return mac.toUpperCase().toUpperCase().startsWith(item.substring(0, mac.length)); }).length > 0 ||
- iface.toLowerCase().indexOf(' virtual ') > -1 ||
- ifaceName.toLowerCase().indexOf(' virtual ') > -1 ||
- iface.toLowerCase().indexOf('vethernet ') > -1 ||
- ifaceName.toLowerCase().indexOf('vethernet ') > -1 ||
- iface.toLowerCase().startsWith('veth') ||
- ifaceName.toLowerCase().startsWith('veth') ||
- iface.toLowerCase().startsWith('vboxnet') ||
- ifaceName.toLowerCase().startsWith('vboxnet');
- } else { return false; }
-}
-
-function networkInterfaces(callback, rescan, defaultString) {
-
- if (typeof callback === 'string') {
- defaultString = callback;
- rescan = true;
- callback = null;
- }
-
- if (typeof callback === 'boolean') {
- rescan = callback;
- callback = null;
- defaultString = '';
- }
- if (typeof rescan === 'undefined') {
- rescan = true;
- }
- defaultString = defaultString || '';
- defaultString = '' + defaultString;
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let ifaces = os.networkInterfaces();
-
- let result = [];
- let nics = [];
- let dnsSuffixes = [];
- let nics8021xInfo = [];
- // seperate handling in OSX
- if (_darwin || _freebsd || _openbsd || _netbsd) {
- if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
- // no changes - just return object
- result = _networkInterfaces;
-
- if (callback) { callback(result); }
- resolve(result);
- } else {
- const defaultInterface = getDefaultNetworkInterface();
- _ifaces = JSON.parse(JSON.stringify(ifaces));
-
- nics = getDarwinNics();
-
-
- nics.forEach(nic => {
-
- if ({}.hasOwnProperty.call(ifaces, nic.iface)) {
- ifaces[nic.iface].forEach(function (details) {
- if (details.family === 'IPv4' || details.family === 4) {
- nic.ip4subnet = details.netmask;
- }
- if (details.family === 'IPv6' || details.family === 6) {
- nic.ip6subnet = details.netmask;
- }
- });
- }
-
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(nic.iface);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
-
- result.push({
- iface: nic.iface,
- ifaceName: nic.iface,
- default: nic.iface === defaultInterface,
- ip4: nic.ip4,
- ip4subnet: nic.ip4subnet || '',
- ip6: nic.ip6,
- ip6subnet: nic.ip6subnet || '',
- mac: nic.mac,
- internal: nic.internal,
- virtual: nic.internal ? false : testVirtualNic(nic.iface, nic.iface, nic.mac),
- operstate: nic.operstate,
- type: nic.type,
- duplex: nic.duplex,
- mtu: nic.mtu,
- speed: nic.speed,
- dhcp: getDarwinIfaceDHCPstatus(ifaceSanitized),
- dnsSuffix: '',
- ieee8021xAuth: '',
- ieee8021xState: '',
- carrierChanges: 0
- });
- });
- _networkInterfaces = result;
- if (defaultString.toLowerCase().indexOf('default') >= 0) {
- result = result.filter(item => item.default);
- if (result.length > 0) {
- result = result[0];
- } else {
- result = [];
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_linux) {
- if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
- // no changes - just return object
- result = _networkInterfaces;
-
- if (callback) { callback(result); }
- resolve(result);
- } else {
- _ifaces = JSON.parse(JSON.stringify(ifaces));
- _dhcpNics = getLinuxDHCPNics();
- const defaultInterface = getDefaultNetworkInterface();
- for (let dev in ifaces) {
- let ip4 = '';
- let ip4subnet = '';
- let ip6 = '';
- let ip6subnet = '';
- let mac = '';
- let duplex = '';
- let mtu = '';
- let speed = null;
- let carrierChanges = 0;
- let dhcp = false;
- let dnsSuffix = '';
- let ieee8021xAuth = '';
- let ieee8021xState = '';
- let type = '';
-
- if ({}.hasOwnProperty.call(ifaces, dev)) {
- let ifaceName = dev;
- ifaces[dev].forEach(function (details) {
- if (details.family === 'IPv4' || details.family === 4) {
- ip4 = details.address;
- ip4subnet = details.netmask;
- }
- if (details.family === 'IPv6' || details.family === 6) {
- if (!ip6 || ip6.match(/^fe80::/i)) {
- ip6 = details.address;
- ip6subnet = details.netmask;
- }
- }
- mac = details.mac;
- // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2)
- const nodeMainVersion = parseInt(process.versions.node.split('.'), 10);
- if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) {
- if (Object.keys(_mac).length === 0) {
- _mac = getMacAddresses();
- }
- mac = _mac[dev] || '';
- }
- });
- let iface = dev.split(':')[0].trim().toLowerCase();
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
- const cmd = `echo -n "addr_assign_type: "; cat /sys/class/net/${ifaceSanitized}/addr_assign_type 2>/dev/null; echo;
- echo -n "address: "; cat /sys/class/net/${ifaceSanitized}/address 2>/dev/null; echo;
- echo -n "addr_len: "; cat /sys/class/net/${ifaceSanitized}/addr_len 2>/dev/null; echo;
- echo -n "broadcast: "; cat /sys/class/net/${ifaceSanitized}/broadcast 2>/dev/null; echo;
- echo -n "carrier: "; cat /sys/class/net/${ifaceSanitized}/carrier 2>/dev/null; echo;
- echo -n "carrier_changes: "; cat /sys/class/net/${ifaceSanitized}/carrier_changes 2>/dev/null; echo;
- echo -n "dev_id: "; cat /sys/class/net/${ifaceSanitized}/dev_id 2>/dev/null; echo;
- echo -n "dev_port: "; cat /sys/class/net/${ifaceSanitized}/dev_port 2>/dev/null; echo;
- echo -n "dormant: "; cat /sys/class/net/${ifaceSanitized}/dormant 2>/dev/null; echo;
- echo -n "duplex: "; cat /sys/class/net/${ifaceSanitized}/duplex 2>/dev/null; echo;
- echo -n "flags: "; cat /sys/class/net/${ifaceSanitized}/flags 2>/dev/null; echo;
- echo -n "gro_flush_timeout: "; cat /sys/class/net/${ifaceSanitized}/gro_flush_timeout 2>/dev/null; echo;
- echo -n "ifalias: "; cat /sys/class/net/${ifaceSanitized}/ifalias 2>/dev/null; echo;
- echo -n "ifindex: "; cat /sys/class/net/${ifaceSanitized}/ifindex 2>/dev/null; echo;
- echo -n "iflink: "; cat /sys/class/net/${ifaceSanitized}/iflink 2>/dev/null; echo;
- echo -n "link_mode: "; cat /sys/class/net/${ifaceSanitized}/link_mode 2>/dev/null; echo;
- echo -n "mtu: "; cat /sys/class/net/${ifaceSanitized}/mtu 2>/dev/null; echo;
- echo -n "netdev_group: "; cat /sys/class/net/${ifaceSanitized}/netdev_group 2>/dev/null; echo;
- echo -n "operstate: "; cat /sys/class/net/${ifaceSanitized}/operstate 2>/dev/null; echo;
- echo -n "proto_down: "; cat /sys/class/net/${ifaceSanitized}/proto_down 2>/dev/null; echo;
- echo -n "speed: "; cat /sys/class/net/${ifaceSanitized}/speed 2>/dev/null; echo;
- echo -n "tx_queue_len: "; cat /sys/class/net/${ifaceSanitized}/tx_queue_len 2>/dev/null; echo;
- echo -n "type: "; cat /sys/class/net/${ifaceSanitized}/type 2>/dev/null; echo;
- echo -n "wireless: "; cat /proc/net/wireless 2>/dev/null | grep ${ifaceSanitized}; echo;
- echo -n "wirelessspeed: "; iw dev ${ifaceSanitized} link 2>&1 | grep bitrate; echo;`;
-
- let lines = [];
- try {
- lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- const connectionName = getLinuxIfaceConnectionName(ifaceSanitized);
- dhcp = getLinuxIfaceDHCPstatus(ifaceSanitized, connectionName, _dhcpNics);
- dnsSuffix = getLinuxIfaceDNSsuffix(connectionName);
- ieee8021xAuth = getLinuxIfaceIEEE8021xAuth(connectionName);
- ieee8021xState = getLinuxIfaceIEEE8021xState(ieee8021xAuth);
- } catch (e) {
- util.noop();
- }
- duplex = util.getValue(lines, 'duplex');
- duplex = duplex.startsWith('cat') ? '' : duplex;
- mtu = parseInt(util.getValue(lines, 'mtu'), 10);
- let myspeed = parseInt(util.getValue(lines, 'speed'), 10);
- speed = isNaN(myspeed) ? null : myspeed;
- let wirelessspeed = util.getValue(lines, 'wirelessspeed').split('tx bitrate: ');
- if (speed === null && wirelessspeed.length === 2) {
- myspeed = parseFloat(wirelessspeed[1]);
- speed = isNaN(myspeed) ? null : myspeed;
- }
- carrierChanges = parseInt(util.getValue(lines, 'carrier_changes'), 10);
- const operstate = util.getValue(lines, 'operstate');
- type = operstate === 'up' ? (util.getValue(lines, 'wireless').trim() ? 'wireless' : 'wired') : 'unknown';
- if (ifaceSanitized === 'lo' || ifaceSanitized.startsWith('bond')) { type = 'virtual'; }
-
- let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false;
- if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) {
- internal = true;
- }
- const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac);
- result.push({
- iface: ifaceSanitized,
- ifaceName,
- default: iface === defaultInterface,
- ip4,
- ip4subnet,
- ip6,
- ip6subnet,
- mac,
- internal,
- virtual,
- operstate,
- type,
- duplex,
- mtu,
- speed,
- dhcp,
- dnsSuffix,
- ieee8021xAuth,
- ieee8021xState,
- carrierChanges,
- });
- }
- }
- _networkInterfaces = result;
- if (defaultString.toLowerCase().indexOf('default') >= 0) {
- result = result.filter(item => item.default);
- if (result.length > 0) {
- result = result[0];
- } else {
- result = [];
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_windows) {
- if ((JSON.stringify(ifaces) === JSON.stringify(_ifaces)) && !rescan) {
- // no changes - just return object
- result = _networkInterfaces;
-
- if (callback) { callback(result); }
- resolve(result);
- } else {
- _ifaces = JSON.parse(JSON.stringify(ifaces));
- const defaultInterface = getDefaultNetworkInterface();
-
- getWindowsNics().then(function (nics) {
- nics.forEach(nic => {
- let found = false;
- Object.keys(ifaces).forEach(key => {
- if (!found) {
- ifaces[key].forEach(value => {
- if (Object.keys(value).indexOf('mac') >= 0) {
- found = value['mac'] === nic.mac;
- }
- });
- }
- });
-
- if (!found) {
- ifaces[nic.name] = [{ mac: nic.mac }];
- }
- });
- nics8021xInfo = getWindowsWiredProfilesInformation();
- dnsSuffixes = getWindowsDNSsuffixes();
- for (let dev in ifaces) {
-
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(dev);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
-
- let iface = dev;
- let ip4 = '';
- let ip4subnet = '';
- let ip6 = '';
- let ip6subnet = '';
- let mac = '';
- let duplex = '';
- let mtu = '';
- let speed = null;
- let carrierChanges = 0;
- let operstate = 'down';
- let dhcp = false;
- let dnsSuffix = '';
- let ieee8021xAuth = '';
- let ieee8021xState = '';
- let type = '';
-
- if ({}.hasOwnProperty.call(ifaces, dev)) {
- let ifaceName = dev;
- ifaces[dev].forEach(function (details) {
- if (details.family === 'IPv4' || details.family === 4) {
- ip4 = details.address;
- ip4subnet = details.netmask;
- }
- if (details.family === 'IPv6' || details.family === 6) {
- if (!ip6 || ip6.match(/^fe80::/i)) {
- ip6 = details.address;
- ip6subnet = details.netmask;
- }
- }
- mac = details.mac;
- // fallback due to https://github.com/nodejs/node/issues/13581 (node 8.1 - node 8.2)
- const nodeMainVersion = parseInt(process.versions.node.split('.'), 10);
- if (mac.indexOf('00:00:0') > -1 && (_linux || _darwin) && (!details.internal) && nodeMainVersion >= 8 && nodeMainVersion <= 11) {
- if (Object.keys(_mac).length === 0) {
- _mac = getMacAddresses();
- }
- mac = _mac[dev] || '';
- }
- });
-
-
-
- dnsSuffix = getWindowsIfaceDNSsuffix(dnsSuffixes.ifaces, ifaceSanitized);
- let foundFirst = false;
- nics.forEach(detail => {
- if (detail.mac === mac && !foundFirst) {
- iface = detail.iface || iface;
- ifaceName = detail.name;
- dhcp = detail.dhcp;
- operstate = detail.operstate;
- speed = operstate === 'up' ? detail.speed : 0;
- type = detail.type;
- foundFirst = true;
- }
- });
-
- if (dev.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('wlan') >= 0 || ifaceName.toLowerCase().indexOf('802.11n') >= 0 || ifaceName.toLowerCase().indexOf('wireless') >= 0 || ifaceName.toLowerCase().indexOf('wi-fi') >= 0 || ifaceName.toLowerCase().indexOf('wifi') >= 0) {
- type = 'wireless';
- }
-
- const IEEE8021x = getWindowsIEEE8021x(type, ifaceSanitized, nics8021xInfo);
- ieee8021xAuth = IEEE8021x.protocol;
- ieee8021xState = IEEE8021x.state;
- let internal = (ifaces[dev] && ifaces[dev][0]) ? ifaces[dev][0].internal : false;
- if (dev.toLowerCase().indexOf('loopback') > -1 || ifaceName.toLowerCase().indexOf('loopback') > -1) {
- internal = true;
- }
- const virtual = internal ? false : testVirtualNic(dev, ifaceName, mac);
- result.push({
- iface,
- ifaceName,
- default: iface === defaultInterface,
- ip4,
- ip4subnet,
- ip6,
- ip6subnet,
- mac,
- internal,
- virtual,
- operstate,
- type,
- duplex,
- mtu,
- speed,
- dhcp,
- dnsSuffix,
- ieee8021xAuth,
- ieee8021xState,
- carrierChanges,
- });
- }
- }
- _networkInterfaces = result;
- if (defaultString.toLowerCase().indexOf('default') >= 0) {
- result = result.filter(item => item.default);
- if (result.length > 0) {
- result = result[0];
- } else {
- result = [];
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- }
- });
- });
-}
-
-exports.networkInterfaces = networkInterfaces;
-
-// --------------------------
-// NET - Speed
-
-function calcNetworkSpeed(iface, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors) {
- let result = {
- iface,
- operstate,
- rx_bytes,
- rx_dropped,
- rx_errors,
- tx_bytes,
- tx_dropped,
- tx_errors,
- rx_sec: null,
- tx_sec: null,
- ms: 0
- };
-
- if (_network[iface] && _network[iface].ms) {
- result.ms = Date.now() - _network[iface].ms;
- result.rx_sec = (rx_bytes - _network[iface].rx_bytes) >= 0 ? (rx_bytes - _network[iface].rx_bytes) / (result.ms / 1000) : 0;
- result.tx_sec = (tx_bytes - _network[iface].tx_bytes) >= 0 ? (tx_bytes - _network[iface].tx_bytes) / (result.ms / 1000) : 0;
- _network[iface].rx_bytes = rx_bytes;
- _network[iface].tx_bytes = tx_bytes;
- _network[iface].rx_sec = result.rx_sec;
- _network[iface].tx_sec = result.tx_sec;
- _network[iface].ms = Date.now();
- _network[iface].last_ms = result.ms;
- _network[iface].operstate = operstate;
- } else {
- if (!_network[iface]) { _network[iface] = {}; }
- _network[iface].rx_bytes = rx_bytes;
- _network[iface].tx_bytes = tx_bytes;
- _network[iface].rx_sec = null;
- _network[iface].tx_sec = null;
- _network[iface].ms = Date.now();
- _network[iface].last_ms = 0;
- _network[iface].operstate = operstate;
- }
- return result;
-}
-
-function networkStats(ifaces, callback) {
-
- let ifacesArray = [];
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- // fallback - if only callback is given
- if (util.isFunction(ifaces) && !callback) {
- callback = ifaces;
- ifacesArray = [getDefaultNetworkInterface()];
- } else {
- if (typeof ifaces !== 'string' && ifaces !== undefined) {
- if (callback) { callback([]); }
- return resolve([]);
- }
- ifaces = ifaces || getDefaultNetworkInterface();
-
- try {
- ifaces.__proto__.toLowerCase = util.stringToLower;
- ifaces.__proto__.replace = util.stringReplace;
- ifaces.__proto__.trim = util.stringTrim;
- } catch (e) {
- Object.setPrototypeOf(ifaces, util.stringObj);
- }
-
- ifaces = ifaces.trim().toLowerCase().replace(/,+/g, '|');
- ifacesArray = ifaces.split('|');
- }
-
- const result = [];
-
- const workload = [];
- if (ifacesArray.length && ifacesArray[0].trim() === '*') {
- ifacesArray = [];
- networkInterfaces(false).then(allIFaces => {
- for (let iface of allIFaces) {
- ifacesArray.push(iface.iface);
- }
- networkStats(ifacesArray.join(',')).then(result => {
- if (callback) { callback(result); }
- resolve(result);
- });
- });
- } else {
- for (let iface of ifacesArray) {
- workload.push(networkStatsSingle(iface.trim()));
- }
- if (workload.length) {
- Promise.all(
- workload
- ).then((data) => {
- if (callback) { callback(data); }
- resolve(data);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-function networkStatsSingle(iface) {
-
- function parseLinesWindowsPerfData(sections) {
- let perfData = [];
- for (let i in sections) {
- if ({}.hasOwnProperty.call(sections, i)) {
- if (sections[i].trim() !== '') {
- let lines = sections[i].trim().split('\r\n');
- perfData.push({
- name: util.getValue(lines, 'Name', ':').replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase(),
- rx_bytes: parseInt(util.getValue(lines, 'BytesReceivedPersec', ':'), 10),
- rx_errors: parseInt(util.getValue(lines, 'PacketsReceivedErrors', ':'), 10),
- rx_dropped: parseInt(util.getValue(lines, 'PacketsReceivedDiscarded', ':'), 10),
- tx_bytes: parseInt(util.getValue(lines, 'BytesSentPersec', ':'), 10),
- tx_errors: parseInt(util.getValue(lines, 'PacketsOutboundErrors', ':'), 10),
- tx_dropped: parseInt(util.getValue(lines, 'PacketsOutboundDiscarded', ':'), 10)
- });
- }
- }
- }
- return perfData;
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
-
- let result = {
- iface: ifaceSanitized,
- operstate: 'unknown',
- rx_bytes: 0,
- rx_dropped: 0,
- rx_errors: 0,
- tx_bytes: 0,
- tx_dropped: 0,
- tx_errors: 0,
- rx_sec: null,
- tx_sec: null,
- ms: 0
- };
-
- let operstate = 'unknown';
- let rx_bytes = 0;
- let tx_bytes = 0;
- let rx_dropped = 0;
- let rx_errors = 0;
- let tx_dropped = 0;
- let tx_errors = 0;
-
- let cmd, lines, stats;
- if (!_network[ifaceSanitized] || (_network[ifaceSanitized] && !_network[ifaceSanitized].ms) || (_network[ifaceSanitized] && _network[ifaceSanitized].ms && Date.now() - _network[ifaceSanitized].ms >= 500)) {
- if (_linux) {
- if (fs.existsSync('/sys/class/net/' + ifaceSanitized)) {
- cmd =
- 'cat /sys/class/net/' + ifaceSanitized + '/operstate; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_bytes; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_bytes; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_dropped; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/rx_errors; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_dropped; ' +
- 'cat /sys/class/net/' + ifaceSanitized + '/statistics/tx_errors; ';
- exec(cmd, function (error, stdout) {
- if (!error) {
- lines = stdout.toString().split('\n');
- operstate = lines[0].trim();
- rx_bytes = parseInt(lines[1], 10);
- tx_bytes = parseInt(lines[2], 10);
- rx_dropped = parseInt(lines[3], 10);
- rx_errors = parseInt(lines[4], 10);
- tx_dropped = parseInt(lines[5], 10);
- tx_errors = parseInt(lines[6], 10);
-
- result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
-
- }
- resolve(result);
- });
- } else {
- resolve(result);
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- cmd = 'netstat -ibndI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input]
- exec(cmd, function (error, stdout) {
- if (!error) {
- lines = stdout.toString().split('\n');
- for (let i = 1; i < lines.length; i++) {
- const line = lines[i].replace(/ +/g, ' ').split(' ');
- if (line && line[0] && line[7] && line[10]) {
- rx_bytes = rx_bytes + parseInt(line[7]);
- if (line[6].trim() !== '-') { rx_dropped = rx_dropped + parseInt(line[6]); }
- if (line[5].trim() !== '-') { rx_errors = rx_errors + parseInt(line[5]); }
- tx_bytes = tx_bytes + parseInt(line[10]);
- if (line[12].trim() !== '-') { tx_dropped = tx_dropped + parseInt(line[12]); }
- if (line[9].trim() !== '-') { tx_errors = tx_errors + parseInt(line[9]); }
- operstate = 'up';
- }
- }
- result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
- }
- resolve(result);
- });
- }
- if (_darwin) {
- cmd = 'ifconfig ' + ifaceSanitized + ' | grep "status"'; // lgtm [js/shell-command-constructed-from-input]
- exec(cmd, function (error, stdout) {
- result.operstate = (stdout.toString().split(':')[1] || '').trim();
- result.operstate = (result.operstate || '').toLowerCase();
- result.operstate = (result.operstate === 'active' ? 'up' : (result.operstate === 'inactive' ? 'down' : 'unknown'));
- cmd = 'netstat -bdI ' + ifaceSanitized; // lgtm [js/shell-command-constructed-from-input]
- exec(cmd, function (error, stdout) {
- if (!error) {
- lines = stdout.toString().split('\n');
- // if there is less than 2 lines, no information for this interface was found
- if (lines.length > 1 && lines[1].trim() !== '') {
- // skip header line
- // use the second line because it is tied to the NIC instead of the ipv4 or ipv6 address
- stats = lines[1].replace(/ +/g, ' ').split(' ');
- const offset = stats.length > 11 ? 1 : 0;
- rx_bytes = parseInt(stats[offset + 5]);
- rx_dropped = parseInt(stats[offset + 10]);
- rx_errors = parseInt(stats[offset + 4]);
- tx_bytes = parseInt(stats[offset + 8]);
- tx_dropped = parseInt(stats[offset + 10]);
- tx_errors = parseInt(stats[offset + 7]);
- result = calcNetworkSpeed(ifaceSanitized, rx_bytes, tx_bytes, result.operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
- }
- }
- resolve(result);
- });
- });
- }
- if (_windows) {
- let perfData = [];
- let ifaceName = ifaceSanitized;
-
- // Performance Data
- util.powerShell('Get-CimInstance Win32_PerfRawData_Tcpip_NetworkInterface | select Name,BytesReceivedPersec,PacketsReceivedErrors,PacketsReceivedDiscarded,BytesSentPersec,PacketsOutboundErrors,PacketsOutboundDiscarded | fl').then((stdout, error) => {
- if (!error) {
- const psections = stdout.toString().split(/\n\s*\n/);
- perfData = parseLinesWindowsPerfData(psections);
- }
-
- // Network Interfaces
- networkInterfaces(false).then(interfaces => {
- // get bytes sent, received from perfData by name
- rx_bytes = 0;
- tx_bytes = 0;
- perfData.forEach(detail => {
- interfaces.forEach(det => {
- if ((det.iface.toLowerCase() === ifaceSanitized.toLowerCase() ||
- det.mac.toLowerCase() === ifaceSanitized.toLowerCase() ||
- det.ip4.toLowerCase() === ifaceSanitized.toLowerCase() ||
- det.ip6.toLowerCase() === ifaceSanitized.toLowerCase() ||
- det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === ifaceSanitized.replace(/[()[\] ]+/g, '').replace('#', '_').toLowerCase()) &&
- (det.ifaceName.replace(/[()[\] ]+/g, '').replace(/#|\//g, '_').toLowerCase() === detail.name)) {
- ifaceName = det.iface;
- rx_bytes = detail.rx_bytes;
- rx_dropped = detail.rx_dropped;
- rx_errors = detail.rx_errors;
- tx_bytes = detail.tx_bytes;
- tx_dropped = detail.tx_dropped;
- tx_errors = detail.tx_errors;
- operstate = det.operstate;
- }
- });
- });
- if (rx_bytes && tx_bytes) {
- result = calcNetworkSpeed(ifaceName, parseInt(rx_bytes), parseInt(tx_bytes), operstate, rx_dropped, rx_errors, tx_dropped, tx_errors);
- }
- resolve(result);
- });
- });
- }
- } else {
- result.rx_bytes = _network[ifaceSanitized].rx_bytes;
- result.tx_bytes = _network[ifaceSanitized].tx_bytes;
- result.rx_sec = _network[ifaceSanitized].rx_sec;
- result.tx_sec = _network[ifaceSanitized].tx_sec;
- result.ms = _network[ifaceSanitized].last_ms;
- result.operstate = _network[ifaceSanitized].operstate;
- resolve(result);
- }
- });
- });
-}
-
-exports.networkStats = networkStats;
-
-// --------------------------
-// NET - connections (sockets)
-
-function getProcessName(processes, pid) {
- let cmd = '';
- processes.forEach(line => {
- const parts = line.split(' ');
- const id = parseInt(parts[0], 10) || -1;
- if (id === pid) {
- parts.shift();
- cmd = parts.join(' ').split(':')[0];
- }
- });
- cmd = cmd.split(' -')[0];
- cmd = cmd.split(' /')[0];
- return cmd;
- // const cmdParts = cmd.split('/');
- // return cmdParts[cmdParts.length - 1];
-}
-
-function networkConnections(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux || _freebsd || _openbsd || _netbsd) {
- let cmd = 'export LC_ALL=C; netstat -tunap | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL';
- if (_freebsd || _openbsd || _netbsd) { cmd = 'export LC_ALL=C; netstat -na | grep "ESTABLISHED\\|SYN_SENT\\|SYN_RECV\\|FIN_WAIT1\\|FIN_WAIT2\\|TIME_WAIT\\|CLOSE\\|CLOSE_WAIT\\|LAST_ACK\\|LISTEN\\|CLOSING\\|UNKNOWN"; unset LC_ALL'; }
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- if (!error && (lines.length > 1 || lines[0] != '')) {
- lines.forEach(function (line) {
- line = line.replace(/ +/g, ' ').split(' ');
- if (line.length >= 7) {
- let localip = line[3];
- let localport = '';
- let localaddress = line[3].split(':');
- if (localaddress.length > 1) {
- localport = localaddress[localaddress.length - 1];
- localaddress.pop();
- localip = localaddress.join(':');
- }
- let peerip = line[4];
- let peerport = '';
- let peeraddress = line[4].split(':');
- if (peeraddress.length > 1) {
- peerport = peeraddress[peeraddress.length - 1];
- peeraddress.pop();
- peerip = peeraddress.join(':');
- }
- let connstate = line[5];
- let proc = line[6].split('/');
-
- if (connstate) {
- result.push({
- protocol: line[0],
- localAddress: localip,
- localPort: localport,
- peerAddress: peerip,
- peerPort: peerport,
- state: connstate,
- pid: proc[0] && proc[0] !== '-' ? parseInt(proc[0], 10) : null,
- process: proc[1] ? proc[1].split(' ')[0].split(':')[0] : ''
- });
- }
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else {
- cmd = 'ss -tunap | grep "ESTAB\\|SYN-SENT\\|SYN-RECV\\|FIN-WAIT1\\|FIN-WAIT2\\|TIME-WAIT\\|CLOSE\\|CLOSE-WAIT\\|LAST-ACK\\|LISTEN\\|CLOSING"';
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
-
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- line = line.replace(/ +/g, ' ').split(' ');
- if (line.length >= 6) {
- let localip = line[4];
- let localport = '';
- let localaddress = line[4].split(':');
- if (localaddress.length > 1) {
- localport = localaddress[localaddress.length - 1];
- localaddress.pop();
- localip = localaddress.join(':');
- }
- let peerip = line[5];
- let peerport = '';
- let peeraddress = line[5].split(':');
- if (peeraddress.length > 1) {
- peerport = peeraddress[peeraddress.length - 1];
- peeraddress.pop();
- peerip = peeraddress.join(':');
- }
- let connstate = line[1];
- if (connstate === 'ESTAB') { connstate = 'ESTABLISHED'; }
- if (connstate === 'TIME-WAIT') { connstate = 'TIME_WAIT'; }
- let pid = null;
- let process = '';
- if (line.length >= 7 && line[6].indexOf('users:') > -1) {
- let proc = line[6].replace('users:(("', '').replace(/"/g, '').split(',');
- if (proc.length > 2) {
- process = proc[0].split(' ')[0].split(':')[0];
- pid = parseInt(proc[1], 10);
- }
- }
- if (connstate) {
- result.push({
- protocol: line[0],
- localAddress: localip,
- localPort: localport,
- peerAddress: peerip,
- peerPort: peerport,
- state: connstate,
- pid,
- process
- });
- }
- }
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- });
- }
- if (_darwin) {
- let cmd = 'netstat -natvln | head -n2; netstat -natvln | grep "tcp4\\|tcp6\\|udp4\\|udp6"';
- const states = 'ESTABLISHED|SYN_SENT|SYN_RECV|FIN_WAIT1|FIN_WAIT_1|FIN_WAIT2|FIN_WAIT_2|TIME_WAIT|CLOSE|CLOSE_WAIT|LAST_ACK|LISTEN|CLOSING|UNKNOWN'.split('|');
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- if (!error) {
- exec('ps -axo pid,command', { maxBuffer: 1024 * 20000 }, function (err2, stdout2) {
- let processes = stdout2.toString().split('\n');
- processes = processes.map((line => { return line.trim().replace(/ +/g, ' '); }));
- let lines = stdout.toString().split('\n');
- lines.shift();
- let pidPos = 8;
- if (lines.length > 1 && lines[0].indexOf('pid') > 0) {
- const header = (lines.shift() || '').replace(/ Address/g, '_Address').replace(/ +/g, ' ').split(' ');
- pidPos = header.indexOf('pid');
- }
- lines.forEach(function (line) {
- line = line.replace(/ +/g, ' ').split(' ');
- if (line.length >= 8) {
- let localip = line[3];
- let localport = '';
- let localaddress = line[3].split('.');
- if (localaddress.length > 1) {
- localport = localaddress[localaddress.length - 1];
- localaddress.pop();
- localip = localaddress.join('.');
- }
- let peerip = line[4];
- let peerport = '';
- let peeraddress = line[4].split('.');
- if (peeraddress.length > 1) {
- peerport = peeraddress[peeraddress.length - 1];
- peeraddress.pop();
- peerip = peeraddress.join('.');
- }
- const hasState = states.indexOf(line[5]) >= 0;
- let connstate = hasState ? line[5] : 'UNKNOWN';
- let pid = parseInt(line[pidPos + (hasState ? 0 : -1)], 10);
- if (connstate) {
- result.push({
- protocol: line[0],
- localAddress: localip,
- localPort: localport,
- peerAddress: peerip,
- peerPort: peerport,
- state: connstate,
- pid: pid,
- process: getProcessName(processes, pid)
- });
- }
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
-
- }
- });
- }
- if (_windows) {
- let cmd = 'netstat -nao';
- try {
- exec(cmd, util.execOptsWin, function (error, stdout) {
- if (!error) {
-
- let lines = stdout.toString().split('\r\n');
-
- lines.forEach(function (line) {
- line = line.trim().replace(/ +/g, ' ').split(' ');
- if (line.length >= 4) {
- let localip = line[1];
- let localport = '';
- let localaddress = line[1].split(':');
- if (localaddress.length > 1) {
- localport = localaddress[localaddress.length - 1];
- localaddress.pop();
- localip = localaddress.join(':');
- }
- localip = localip.replace(/\[/g, '').replace(/\]/g, '');
- let peerip = line[2];
- let peerport = '';
- let peeraddress = line[2].split(':');
- if (peeraddress.length > 1) {
- peerport = peeraddress[peeraddress.length - 1];
- peeraddress.pop();
- peerip = peeraddress.join(':');
- }
- peerip = peerip.replace(/\[/g, '').replace(/\]/g, '');
- let pid = util.toInt(line[4]);
- let connstate = line[3];
- if (connstate === 'HERGESTELLT') { connstate = 'ESTABLISHED'; }
- if (connstate.startsWith('ABH')) { connstate = 'LISTEN'; }
- if (connstate === 'SCHLIESSEN_WARTEN') { connstate = 'CLOSE_WAIT'; }
- if (connstate === 'WARTEND') { connstate = 'TIME_WAIT'; }
- if (connstate === 'SYN_GESENDET') { connstate = 'SYN_SENT'; }
-
- if (connstate === 'LISTENING') { connstate = 'LISTEN'; }
- if (connstate === 'SYN_RECEIVED') { connstate = 'SYN_RECV'; }
- if (connstate === 'FIN_WAIT_1') { connstate = 'FIN_WAIT1'; }
- if (connstate === 'FIN_WAIT_2') { connstate = 'FIN_WAIT2'; }
- if (line[0].toLowerCase() !== 'udp' && connstate) {
- result.push({
- protocol: line[0].toLowerCase(),
- localAddress: localip,
- localPort: localport,
- peerAddress: peerip,
- peerPort: peerport,
- state: connstate,
- pid,
- process: ''
- });
- } else if (line[0].toLowerCase() === 'udp') {
- result.push({
- protocol: line[0].toLowerCase(),
- localAddress: localip,
- localPort: localport,
- peerAddress: peerip,
- peerPort: peerport,
- state: '',
- pid: parseInt(line[3], 10),
- process: ''
- });
- }
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.networkConnections = networkConnections;
-
-function networkGatewayDefault(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = '';
- if (_linux || _freebsd || _openbsd || _netbsd) {
- let cmd = 'ip route get 1';
- try {
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- const line = lines && lines[0] ? lines[0] : '';
- let parts = line.split(' via ');
- if (parts && parts[1]) {
- parts = parts[1].split(' ');
- result = parts[0];
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_darwin) {
- let cmd = 'route -n get default';
- try {
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- if (!error) {
- const lines = stdout.toString().split('\n').map(line => line.trim());
- result = util.getValue(lines, 'gateway');
- }
- if (!result) {
- cmd = 'netstat -rn | awk \'/default/ {print $2}\'';
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- const lines = stdout.toString().split('\n').map(line => line.trim());
- result = lines.find(line => (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(line)));
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_windows) {
- try {
- exec('netstat -r', util.execOptsWin, function (error, stdout) {
- const lines = stdout.toString().split(os.EOL);
- lines.forEach(line => {
- line = line.replace(/\s+/g, ' ').trim();
- if (line.indexOf('0.0.0.0 0.0.0.0') > -1 && !(/[a-zA-Z]/.test(line))) {
- const parts = line.split(' ');
- if (parts.length >= 5 && (parts[parts.length - 3]).indexOf('.') > -1) {
- result = parts[parts.length - 3];
- }
- }
- });
- if (!result) {
- util.powerShell('Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq \'0.0.0.0\' -and $_.Mask -eq \'0.0.0.0\' }')
- .then((data) => {
- let lines = data.toString().split('\r\n');
- if (lines.length > 1 && !result) {
- result = util.getValue(lines, 'NextHop');
- if (callback) {
- callback(result);
- }
- resolve(result);
- // } else {
- // exec('ipconfig', util.execOptsWin, function (error, stdout) {
- // let lines = stdout.toString().split('\r\n');
- // lines.forEach(function (line) {
- // line = line.trim().replace(/\. /g, '');
- // line = line.trim().replace(/ +/g, '');
- // const parts = line.split(':');
- // if ((parts[0].toLowerCase().startsWith('standardgate') || parts[0].toLowerCase().indexOf('gateway') > -1 || parts[0].toLowerCase().indexOf('enlace') > -1) && parts[1]) {
- // result = parts[1];
- // }
- // });
- // if (callback) { callback(result); }
- // resolve(result);
- // });
- }
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.networkGatewayDefault = networkGatewayDefault;
-
-
-/***/ }),
-
-/***/ 70255:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// osinfo.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 3. Operating System
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const fs = __nccwpck_require__(79896);
-const util = __nccwpck_require__(33225);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-// --------------------------
-// Get current time and OS uptime
-
-function time() {
- let t = new Date().toString().split(' ');
- const result = {
- current: Date.now(),
- uptime: os.uptime(),
- timezone: (t.length >= 7) ? t[5] : '',
- timezoneName: Intl ? Intl.DateTimeFormat().resolvedOptions().timeZone : (t.length >= 7) ? t.slice(6).join(' ').replace(/\(/g, '').replace(/\)/g, '') : ''
- };
- if (_darwin || _linux) {
- try {
- const stdout = execSync('date +%Z && date +%z && ls -l /etc/localtime 2>/dev/null', util.execOptsLinux);
- const lines = stdout.toString().split(os.EOL);
- if (lines.length > 3 && !lines[0]) {
- lines.shift();
- }
- let timezone = lines[0] || '';
- if (timezone.startsWith('+') || timezone.startsWith('-')) {
- timezone = 'GMT';
- }
- return {
- current: Date.now(),
- uptime: os.uptime(),
- timezone: lines[1] ? timezone + lines[1] : timezone,
- timezoneName: lines[2] && lines[2].indexOf('/zoneinfo/') > 0 ? (lines[2].split('/zoneinfo/')[1] || '') : ''
- };
- } catch (e) {
- util.noop();
- }
- }
- return result;
-}
-
-exports.time = time;
-
-// --------------------------
-// Get logo filename of OS distribution
-
-function getLogoFile(distro) {
- distro = distro || '';
- distro = distro.toLowerCase();
- let result = _platform;
- if (_windows) {
- result = 'windows';
- }
- else if (distro.indexOf('mac os') !== -1 || distro.indexOf('macos') !== -1) {
- result = 'apple';
- }
- else if (distro.indexOf('arch') !== -1) {
- result = 'arch';
- }
- else if (distro.indexOf('cachy') !== -1) {
- result = 'cachy';
- }
- else if (distro.indexOf('centos') !== -1) {
- result = 'centos';
- }
- else if (distro.indexOf('coreos') !== -1) {
- result = 'coreos';
- }
- else if (distro.indexOf('debian') !== -1) {
- result = 'debian';
- }
- else if (distro.indexOf('deepin') !== -1) {
- result = 'deepin';
- }
- else if (distro.indexOf('elementary') !== -1) {
- result = 'elementary';
- }
- else if (distro.indexOf('endeavour') !== -1) {
- result = 'endeavour';
- }
- else if (distro.indexOf('fedora') !== -1) {
- result = 'fedora';
- }
- else if (distro.indexOf('gentoo') !== -1) {
- result = 'gentoo';
- }
- else if (distro.indexOf('mageia') !== -1) {
- result = 'mageia';
- }
- else if (distro.indexOf('mandriva') !== -1) {
- result = 'mandriva';
- }
- else if (distro.indexOf('manjaro') !== -1) {
- result = 'manjaro';
- }
- else if (distro.indexOf('mint') !== -1) {
- result = 'mint';
- }
- else if (distro.indexOf('mx') !== -1) {
- result = 'mx';
- }
- else if (distro.indexOf('openbsd') !== -1) {
- result = 'openbsd';
- }
- else if (distro.indexOf('freebsd') !== -1) {
- result = 'freebsd';
- }
- else if (distro.indexOf('opensuse') !== -1) {
- result = 'opensuse';
- }
- else if (distro.indexOf('pclinuxos') !== -1) {
- result = 'pclinuxos';
- }
- else if (distro.indexOf('puppy') !== -1) {
- result = 'puppy';
- }
- else if (distro.indexOf('popos') !== -1) {
- result = 'popos';
- }
- else if (distro.indexOf('raspbian') !== -1) {
- result = 'raspbian';
- }
- else if (distro.indexOf('reactos') !== -1) {
- result = 'reactos';
- }
- else if (distro.indexOf('redhat') !== -1) {
- result = 'redhat';
- }
- else if (distro.indexOf('slackware') !== -1) {
- result = 'slackware';
- }
- else if (distro.indexOf('sugar') !== -1) {
- result = 'sugar';
- }
- else if (distro.indexOf('steam') !== -1) {
- result = 'steam';
- }
- else if (distro.indexOf('suse') !== -1) {
- result = 'suse';
- }
- else if (distro.indexOf('mate') !== -1) {
- result = 'ubuntu-mate';
- }
- else if (distro.indexOf('lubuntu') !== -1) {
- result = 'lubuntu';
- }
- else if (distro.indexOf('xubuntu') !== -1) {
- result = 'xubuntu';
- }
- else if (distro.indexOf('ubuntu') !== -1) {
- result = 'ubuntu';
- }
- else if (distro.indexOf('solaris') !== -1) {
- result = 'solaris';
- }
- else if (distro.indexOf('tails') !== -1) {
- result = 'tails';
- }
- else if (distro.indexOf('feren') !== -1) {
- result = 'ferenos';
- }
- else if (distro.indexOf('robolinux') !== -1) {
- result = 'robolinux';
- } else if (_linux && distro) {
- result = distro.toLowerCase().trim().replace(/\s+/g, '-');
- }
- return result;
-}
-
-// --------------------------
-// FQDN
-
-function getFQDN() {
- let fqdn = os.hostname;
- if (_linux || _darwin) {
- try {
- const stdout = execSync('hostname -f 2>/dev/null', util.execOptsLinux);
- fqdn = stdout.toString().split(os.EOL)[0];
- } catch (e) {
- util.noop();
- }
- }
- if (_freebsd || _openbsd || _netbsd) {
- try {
- const stdout = execSync('hostname 2>/dev/null');
- fqdn = stdout.toString().split(os.EOL)[0];
- } catch (e) {
- util.noop();
- }
- }
- if (_windows) {
- try {
- const stdout = execSync('echo %COMPUTERNAME%.%USERDNSDOMAIN%', util.execOptsWin);
- fqdn = stdout.toString().replace('.%USERDNSDOMAIN%', '').split(os.EOL)[0];
- } catch (e) {
- util.noop();
- }
- }
- return fqdn;
-}
-
-// --------------------------
-// OS Information
-
-function osInfo(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
-
- platform: (_platform === 'win32' ? 'Windows' : _platform),
- distro: 'unknown',
- release: 'unknown',
- codename: '',
- kernel: os.release(),
- arch: os.arch(),
- hostname: os.hostname(),
- fqdn: getFQDN(),
- codepage: '',
- logofile: '',
- serial: '',
- build: '',
- servicepack: '',
- uefi: false
- };
-
- if (_linux) {
-
- exec('cat /etc/*-release; cat /usr/lib/os-release; cat /etc/openwrt_release', function (error, stdout) {
- /**
- * @namespace
- * @property {string} DISTRIB_ID
- * @property {string} NAME
- * @property {string} DISTRIB_RELEASE
- * @property {string} VERSION_ID
- * @property {string} DISTRIB_CODENAME
- */
- let release = {};
- let lines = stdout.toString().split('\n');
- lines.forEach(function (line) {
- if (line.indexOf('=') !== -1) {
- release[line.split('=')[0].trim().toUpperCase()] = line.split('=')[1].trim();
- }
- });
- result.distro = (release.DISTRIB_ID || release.NAME || 'unknown').replace(/"/g, '');
- result.logofile = getLogoFile(result.distro);
- let releaseVersion = (release.VERSION || '').replace(/"/g, '');
- let codename = (release.DISTRIB_CODENAME || release.VERSION_CODENAME || '').replace(/"/g, '');
- const prettyName = (release.PRETTY_NAME || '').replace(/"/g, '');
- if (prettyName.indexOf(result.distro + ' ') === 0) {
- releaseVersion = prettyName.replace(result.distro + ' ', '').trim();
- }
- if (releaseVersion.indexOf('(') >= 0) {
- codename = releaseVersion.split('(')[1].replace(/[()]/g, '').trim();
- releaseVersion = releaseVersion.split('(')[0].trim();
- }
- result.release = (releaseVersion || release.DISTRIB_RELEASE || release.VERSION_ID || 'unknown').replace(/"/g, '');
- result.codename = codename;
- result.codepage = util.getCodepage();
- result.build = (release.BUILD_ID || '').replace(/"/g, '').trim();
- isUefiLinux().then(uefi => {
- result.uefi = uefi;
- uuid().then((data) => {
- result.serial = data.os;
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- });
- });
- }
- if (_freebsd || _openbsd || _netbsd) {
-
- exec('sysctl kern.ostype kern.osrelease kern.osrevision kern.hostuuid machdep.bootmethod kern.geom.confxml', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- const distro = util.getValue(lines, 'kern.ostype');
- const logofile = getLogoFile(distro);
- const release = util.getValue(lines, 'kern.osrelease').split('-')[0];
- const serial = util.getValue(lines, 'kern.uuid');
- const bootmethod = util.getValue(lines, 'machdep.bootmethod');
- const uefiConf = stdout.toString().indexOf('efi') >= 0;
- const uefi = bootmethod ? bootmethod.toLowerCase().indexOf('uefi') >= 0 : (uefiConf ? uefiConf : null);
- result.distro = distro || result.distro;
- result.logofile = logofile || result.logofile;
- result.release = release || result.release;
- result.serial = serial || result.serial;
- result.codename = '';
- result.codepage = util.getCodepage();
- result.uefi = uefi || null;
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_darwin) {
- exec('sw_vers; sysctl kern.ostype kern.osrelease kern.osrevision kern.uuid', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- result.serial = util.getValue(lines, 'kern.uuid');
- result.distro = util.getValue(lines, 'ProductName');
- result.release = (util.getValue(lines, 'ProductVersion', ':', true, true) + ' ' + util.getValue(lines, 'ProductVersionExtra', ':', true, true)).trim();
- result.build = util.getValue(lines, 'BuildVersion');
- result.logofile = getLogoFile(result.distro);
- result.codename = 'macOS';
- result.codename = (result.release.indexOf('10.4') > -1 ? 'OS X Tiger' : result.codename);
- result.codename = (result.release.indexOf('10.5') > -1 ? 'OS X Leopard' : result.codename);
- result.codename = (result.release.indexOf('10.6') > -1 ? 'OS X Snow Leopard' : result.codename);
- result.codename = (result.release.indexOf('10.7') > -1 ? 'OS X Lion' : result.codename);
- result.codename = (result.release.indexOf('10.8') > -1 ? 'OS X Mountain Lion' : result.codename);
- result.codename = (result.release.indexOf('10.9') > -1 ? 'OS X Mavericks' : result.codename);
- result.codename = (result.release.indexOf('10.10') > -1 ? 'OS X Yosemite' : result.codename);
- result.codename = (result.release.indexOf('10.11') > -1 ? 'OS X El Capitan' : result.codename);
- result.codename = (result.release.indexOf('10.12') > -1 ? 'Sierra' : result.codename);
- result.codename = (result.release.indexOf('10.13') > -1 ? 'High Sierra' : result.codename);
- result.codename = (result.release.indexOf('10.14') > -1 ? 'Mojave' : result.codename);
- result.codename = (result.release.indexOf('10.15') > -1 ? 'Catalina' : result.codename);
- result.codename = (result.release.startsWith('11.') ? 'Big Sur' : result.codename);
- result.codename = (result.release.startsWith('12.') ? 'Monterey' : result.codename);
- result.codename = (result.release.startsWith('13.') ? 'Ventura' : result.codename);
- result.codename = (result.release.startsWith('14.') ? 'Sonoma' : result.codename);
- result.codename = (result.release.startsWith('15.') ? 'Sequoia' : result.codename);
- result.uefi = true;
- result.codepage = util.getCodepage();
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_sunos) {
- result.release = result.kernel;
- exec('uname -o', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- result.distro = lines[0];
- result.logofile = getLogoFile(result.distro);
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_windows) {
- result.logofile = getLogoFile();
- result.release = result.kernel;
- try {
- const workload = [];
- workload.push(util.powerShell('Get-CimInstance Win32_OperatingSystem | select Caption,SerialNumber,BuildNumber,ServicePackMajorVersion,ServicePackMinorVersion | fl'));
- workload.push(util.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent'));
- workload.push(util.powerShell('Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.SystemInformation]::TerminalServerSession'));
- util.promiseAll(
- workload
- ).then((data) => {
- let lines = data.results[0] ? data.results[0].toString().split('\r\n') : [''];
- result.distro = util.getValue(lines, 'Caption', ':').trim();
- result.serial = util.getValue(lines, 'SerialNumber', ':').trim();
- result.build = util.getValue(lines, 'BuildNumber', ':').trim();
- result.servicepack = util.getValue(lines, 'ServicePackMajorVersion', ':').trim() + '.' + util.getValue(lines, 'ServicePackMinorVersion', ':').trim();
- result.codepage = util.getCodepage();
- const hyperv = data.results[1] ? data.results[1].toString().toLowerCase() : '';
- result.hypervisor = hyperv.indexOf('true') !== -1;
- const term = data.results[2] ? data.results[2].toString() : '';
- result.remoteSession = (term.toString().toLowerCase().indexOf('true') >= 0);
- isUefiWindows().then(uefi => {
- result.uefi = uefi;
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.osInfo = osInfo;
-
-function isUefiLinux() {
- return new Promise((resolve) => {
- process.nextTick(() => {
- fs.stat('/sys/firmware/efi', function (err) {
- if (!err) {
- return resolve(true);
- } else {
- exec('dmesg | grep -E "EFI v"', function (error, stdout) {
- if (!error) {
- const lines = stdout.toString().split('\n');
- return resolve(lines.length > 0);
- }
- return resolve(false);
- });
- }
- });
- });
- });
-}
-
-function isUefiWindows() {
- return new Promise((resolve) => {
- process.nextTick(() => {
- try {
- exec('findstr /C:"Detected boot environment" "%windir%\\Panther\\setupact.log"', util.execOptsWin, function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n\r')[0];
- return resolve(line.toLowerCase().indexOf('efi') >= 0);
- } else {
- exec('echo %firmware_type%', util.execOptsWin, function (error, stdout) {
- if (!error) {
- const line = stdout.toString() || '';
- return resolve(line.toLowerCase().indexOf('efi') >= 0);
- } else {
- return resolve(false);
- }
- });
- }
- });
- } catch (e) {
- return resolve(false);
- }
- });
- });
-}
-
-function versions(apps, callback) {
- let versionObject = {
- kernel: os.release(),
- apache: '',
- bash: '',
- bun: '',
- deno: '',
- docker: '',
- dotnet: '',
- fish: '',
- gcc: '',
- git: '',
- grunt: '',
- gulp: '',
- java: '',
- mongodb: '',
- mysql: '',
- nginx: '',
- node: '', //process.versions.node,
- npm: '',
- openssl: '',
- perl: '',
- php: '',
- pip3: '',
- pip: '',
- pm2: '',
- postfix: '',
- postgresql: '',
- powershell: '',
- python3: '',
- python: '',
- redis: '',
- systemOpenssl: '',
- systemOpensslLib: '',
- tsc: '',
- v8: process.versions.v8,
- virtualbox: '',
- yarn: '',
- zsh: ''
- };
-
- function checkVersionParam(apps) {
- if (apps === '*') {
- return {
- versions: versionObject,
- counter: 32
- };
- }
- if (!Array.isArray(apps)) {
- apps = apps.trim().toLowerCase().replace(/,+/g, '|').replace(/ /g, '|');
- apps = apps.split('|');
- const result = {
- versions: {},
- counter: 0
- };
- apps.forEach(el => {
- if (el) {
- for (let key in versionObject) {
- if ({}.hasOwnProperty.call(versionObject, key)) {
- if (key.toLowerCase() === el.toLowerCase() && !{}.hasOwnProperty.call(result.versions, key)) {
- result.versions[key] = versionObject[key];
- if (key === 'openssl') {
- result.versions.systemOpenssl = '';
- result.versions.systemOpensslLib = '';
- }
-
- if (!result.versions[key]) { result.counter++; }
- }
- }
- }
- }
- });
- return result;
- }
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (util.isFunction(apps) && !callback) {
- callback = apps;
- apps = '*';
- } else {
- apps = apps || '*';
- if (typeof apps !== 'string') {
- if (callback) { callback({}); }
- return resolve({});
- }
- }
- const appsObj = checkVersionParam(apps);
- let totalFunctions = appsObj.counter;
-
- let functionProcessed = (function () {
- return function () {
- if (--totalFunctions === 0) {
- if (callback) {
- callback(appsObj.versions);
- }
- resolve(appsObj.versions);
- }
- };
- })();
-
- let cmd = '';
- try {
- if ({}.hasOwnProperty.call(appsObj.versions, 'openssl')) {
- appsObj.versions.openssl = process.versions.openssl;
- exec('openssl version', function (error, stdout) {
- if (!error) {
- let openssl_string = stdout.toString().split('\n')[0].trim();
- let openssl = openssl_string.split(' ');
- appsObj.versions.systemOpenssl = openssl.length > 0 ? openssl[1] : openssl[0];
- appsObj.versions.systemOpensslLib = openssl.length > 0 ? openssl[0] : 'openssl';
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'npm')) {
- exec('npm -v', function (error, stdout) {
- if (!error) {
- appsObj.versions.npm = stdout.toString().split('\n')[0];
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'pm2')) {
- cmd = 'pm2';
- if (_windows) {
- cmd += '.cmd';
- }
- exec(`${cmd} -v`, function (error, stdout) {
- if (!error) {
- let pm2 = stdout.toString().split('\n')[0].trim();
- if (!pm2.startsWith('[PM2]')) {
- appsObj.versions.pm2 = pm2;
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'yarn')) {
- exec('yarn --version', function (error, stdout) {
- if (!error) {
- appsObj.versions.yarn = stdout.toString().split('\n')[0];
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'gulp')) {
- cmd = 'gulp';
- if (_windows) {
- cmd += '.cmd';
- }
- exec(`${cmd} --version`, function (error, stdout) {
- if (!error) {
- const gulp = stdout.toString().split('\n')[0] || '';
- appsObj.versions.gulp = (gulp.toLowerCase().split('version')[1] || '').trim();
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'tsc')) {
- cmd = 'tsc';
- if (_windows) {
- cmd += '.cmd';
- }
- exec(`${cmd} --version`, function (error, stdout) {
- if (!error) {
- const tsc = stdout.toString().split('\n')[0] || '';
- appsObj.versions.tsc = (tsc.toLowerCase().split('version')[1] || '').trim();
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'grunt')) {
- cmd = 'grunt';
- if (_windows) {
- cmd += '.cmd';
- }
- exec(`${cmd} --version`, function (error, stdout) {
- if (!error) {
- const grunt = stdout.toString().split('\n')[0] || '';
- appsObj.versions.grunt = (grunt.toLowerCase().split('cli v')[1] || '').trim();
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'git')) {
- if (_darwin) {
- const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/git') || fs.existsSync('/opt/homebrew/bin/git');
- if (util.darwinXcodeExists() || gitHomebrewExists) {
- exec('git --version', function (error, stdout) {
- if (!error) {
- let git = stdout.toString().split('\n')[0] || '';
- git = (git.toLowerCase().split('version')[1] || '').trim();
- appsObj.versions.git = (git.split(' ')[0] || '').trim();
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } else {
- exec('git --version', function (error, stdout) {
- if (!error) {
- let git = stdout.toString().split('\n')[0] || '';
- git = (git.toLowerCase().split('version')[1] || '').trim();
- appsObj.versions.git = (git.split(' ')[0] || '').trim();
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'apache')) {
- exec('apachectl -v 2>&1', function (error, stdout) {
- if (!error) {
- const apache = (stdout.toString().split('\n')[0] || '').split(':');
- appsObj.versions.apache = (apache.length > 1 ? apache[1].replace('Apache', '').replace('/', '').split('(')[0].trim() : '');
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'nginx')) {
- exec('nginx -v 2>&1', function (error, stdout) {
- if (!error) {
- const nginx = stdout.toString().split('\n')[0] || '';
- appsObj.versions.nginx = (nginx.toLowerCase().split('/')[1] || '').trim();
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'mysql')) {
- exec('mysql -V', function (error, stdout) {
- if (!error) {
- let mysql = stdout.toString().split('\n')[0] || '';
- mysql = mysql.toLowerCase();
- if (mysql.indexOf(',') > -1) {
- mysql = (mysql.split(',')[0] || '').trim();
- const parts = mysql.split(' ');
- appsObj.versions.mysql = (parts[parts.length - 1] || '').trim();
- } else {
- if (mysql.indexOf(' ver ') > -1) {
- mysql = mysql.split(' ver ')[1];
- appsObj.versions.mysql = mysql.split(' ')[0];
- }
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'php')) {
- exec('php -v', function (error, stdout) {
- if (!error) {
- const php = stdout.toString().split('\n')[0] || '';
- let parts = php.split('(');
- if (parts[0].indexOf('-')) {
- parts = parts[0].split('-');
- }
- appsObj.versions.php = parts[0].replace(/[^0-9.]/g, '');
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'redis')) {
- exec('redis-server --version', function (error, stdout) {
- if (!error) {
- const redis = stdout.toString().split('\n')[0] || '';
- const parts = redis.split(' ');
- appsObj.versions.redis = util.getValue(parts, 'v', '=', true);
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'docker')) {
- exec('docker --version', function (error, stdout) {
- if (!error) {
- const docker = stdout.toString().split('\n')[0] || '';
- const parts = docker.split(' ');
- appsObj.versions.docker = parts.length > 2 && parts[2].endsWith(',') ? parts[2].slice(0, -1) : '';
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'postfix')) {
- exec('postconf -d | grep mail_version', function (error, stdout) {
- if (!error) {
- const postfix = stdout.toString().split('\n') || [];
- appsObj.versions.postfix = util.getValue(postfix, 'mail_version', '=', true);
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'mongodb')) {
- exec('mongod --version', function (error, stdout) {
- if (!error) {
- const mongodb = stdout.toString().split('\n')[0] || '';
- appsObj.versions.mongodb = (mongodb.toLowerCase().split(',')[0] || '').replace(/[^0-9.]/g, '');
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'postgresql')) {
- if (_linux) {
- exec('locate bin/postgres', function (error, stdout) {
- if (!error) {
- const postgresqlBin = stdout.toString().split('\n').sort();
- if (postgresqlBin.length) {
- exec(postgresqlBin[postgresqlBin.length - 1] + ' -V', function (error, stdout) {
- if (!error) {
- const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
- appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } else {
- exec('psql -V', function (error, stdout) {
- if (!error) {
- const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
- appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
- appsObj.versions.postgresql = appsObj.versions.postgresql.split('-')[0];
- }
- functionProcessed();
- });
- }
- });
- } else {
- if (_windows) {
- util.powerShell('Get-CimInstance Win32_Service | select caption | fl').then((stdout) => {
- let serviceSections = stdout.split(/\n\s*\n/);
- serviceSections.forEach((item) => {
- if (item.trim() !== '') {
- let lines = item.trim().split('\r\n');
- let srvCaption = util.getValue(lines, 'caption', ':', true).toLowerCase();
- if (srvCaption.indexOf('postgresql') > -1) {
- const parts = srvCaption.split(' server ');
- if (parts.length > 1) {
- appsObj.versions.postgresql = parts[1];
- }
- }
- }
- });
- functionProcessed();
- });
- } else {
- exec('postgres -V', function (error, stdout) {
- if (!error) {
- const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
- appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
- } else {
- exec('pg_config --version', function (error, stdout) {
- if (!error) {
- const postgresql = stdout.toString().split('\n')[0].split(' ') || [];
- appsObj.versions.postgresql = postgresql.length ? postgresql[postgresql.length - 1] : '';
- }
- });
- }
- functionProcessed();
- });
- }
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'perl')) {
- exec('perl -v', function (error, stdout) {
- if (!error) {
- const perl = stdout.toString().split('\n') || '';
- while (perl.length > 0 && perl[0].trim() === '') {
- perl.shift();
- }
- if (perl.length > 0) {
- appsObj.versions.perl = perl[0].split('(').pop().split(')')[0].replace('v', '');
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'python')) {
- if (_darwin) {
- try {
- const stdout = execSync('sw_vers');
- const lines = stdout.toString().split('\n');
- const osVersion = util.getValue(lines, 'ProductVersion', ':');
- const gitHomebrewExists1 = fs.existsSync('/usr/local/Cellar/python');
- const gitHomebrewExists2 = fs.existsSync('/opt/homebrew/bin/python');
- if ((util.darwinXcodeExists() && util.semverCompare('12.0.1', osVersion) < 0) || gitHomebrewExists1 || gitHomebrewExists2) {
- const cmd = gitHomebrewExists1 ? '/usr/local/Cellar/python -V 2>&1' : (gitHomebrewExists2 ? '/opt/homebrew/bin/python -V 2>&1' : 'python -V 2>&1');
- exec(cmd, function (error, stdout) {
- if (!error) {
- const python = stdout.toString().split('\n')[0] || '';
- appsObj.versions.python = python.toLowerCase().replace('python', '').trim();
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } catch (e) {
- functionProcessed();
- }
-
- } else {
- exec('python -V 2>&1', function (error, stdout) {
- if (!error) {
- const python = stdout.toString().split('\n')[0] || '';
- appsObj.versions.python = python.toLowerCase().replace('python', '').trim();
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'python3')) {
- if (_darwin) {
- const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/python3') || fs.existsSync('/opt/homebrew/bin/python3');
- if (util.darwinXcodeExists() || gitHomebrewExists) {
- exec('python3 -V 2>&1', function (error, stdout) {
- if (!error) {
- const python = stdout.toString().split('\n')[0] || '';
- appsObj.versions.python3 = python.toLowerCase().replace('python', '').trim();
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } else {
- exec('python3 -V 2>&1', function (error, stdout) {
- if (!error) {
- const python = stdout.toString().split('\n')[0] || '';
- appsObj.versions.python3 = python.toLowerCase().replace('python', '').trim();
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'pip')) {
- if (_darwin) {
- const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/pip') || fs.existsSync('/opt/homebrew/bin/pip');
- if (util.darwinXcodeExists() || gitHomebrewExists) {
- exec('pip -V 2>&1', function (error, stdout) {
- if (!error) {
- const pip = stdout.toString().split('\n')[0] || '';
- const parts = pip.split(' ');
- appsObj.versions.pip = parts.length >= 2 ? parts[1] : '';
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } else {
- exec('pip -V 2>&1', function (error, stdout) {
- if (!error) {
- const pip = stdout.toString().split('\n')[0] || '';
- const parts = pip.split(' ');
- appsObj.versions.pip = parts.length >= 2 ? parts[1] : '';
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'pip3')) {
- if (_darwin) {
- const gitHomebrewExists = fs.existsSync('/usr/local/Cellar/pip3') || fs.existsSync('/opt/homebrew/bin/pip3');
- if (util.darwinXcodeExists() || gitHomebrewExists) {
- exec('pip3 -V 2>&1', function (error, stdout) {
- if (!error) {
- const pip = stdout.toString().split('\n')[0] || '';
- const parts = pip.split(' ');
- appsObj.versions.pip3 = parts.length >= 2 ? parts[1] : '';
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- } else {
- exec('pip3 -V 2>&1', function (error, stdout) {
- if (!error) {
- const pip = stdout.toString().split('\n')[0] || '';
- const parts = pip.split(' ');
- appsObj.versions.pip3 = parts.length >= 2 ? parts[1] : '';
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'java')) {
- if (_darwin) {
- // check if any JVM is installed but avoid dialog box that Java needs to be installed
- exec('/usr/libexec/java_home -V 2>&1', function (error, stdout) {
- if (!error && stdout.toString().toLowerCase().indexOf('no java runtime') === -1) {
- // now this can be done savely
- exec('java -version 2>&1', function (error, stdout) {
- if (!error) {
- const java = stdout.toString().split('\n')[0] || '';
- const parts = java.split('"');
- appsObj.versions.java = parts.length === 3 ? parts[1].trim() : '';
- }
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- });
- } else {
- exec('java -version 2>&1', function (error, stdout) {
- if (!error) {
- const java = stdout.toString().split('\n')[0] || '';
- const parts = java.split('"');
- appsObj.versions.java = parts.length === 3 ? parts[1].trim() : '';
- }
- functionProcessed();
- });
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'gcc')) {
- if ((_darwin && util.darwinXcodeExists()) || !_darwin) {
- exec('gcc -dumpversion', function (error, stdout) {
- if (!error) {
- appsObj.versions.gcc = stdout.toString().split('\n')[0].trim() || '';
- }
- if (appsObj.versions.gcc.indexOf('.') > -1) {
- functionProcessed();
- } else {
- exec('gcc --version', function (error, stdout) {
- if (!error) {
- const gcc = stdout.toString().split('\n')[0].trim();
- if (gcc.indexOf('gcc') > -1 && gcc.indexOf(')') > -1) {
- const parts = gcc.split(')');
- appsObj.versions.gcc = parts[1].trim() || appsObj.versions.gcc;
- }
- }
- functionProcessed();
- });
- }
- });
- } else {
- functionProcessed();
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'virtualbox')) {
- exec(util.getVboxmanage() + ' -v 2>&1', function (error, stdout) {
- if (!error) {
- const vbox = stdout.toString().split('\n')[0] || '';
- const parts = vbox.split('r');
- appsObj.versions.virtualbox = parts[0];
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'bash')) {
- exec('bash --version', function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n')[0];
- const parts = line.split(' version ');
- if (parts.length > 1) {
- appsObj.versions.bash = parts[1].split(' ')[0].split('(')[0];
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'zsh')) {
- exec('zsh --version', function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n')[0];
- const parts = line.split('zsh ');
- if (parts.length > 1) {
- appsObj.versions.zsh = parts[1].split(' ')[0];
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'fish')) {
- exec('fish --version', function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n')[0];
- const parts = line.split(' version ');
- if (parts.length > 1) {
- appsObj.versions.fish = parts[1].split(' ')[0];
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'bun')) {
- exec('bun -v', function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n')[0].trim();
- appsObj.versions.bun = line;
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'deno')) {
- exec('deno -v', function (error, stdout) {
- if (!error) {
- const line = stdout.toString().split('\n')[0].trim();
- const parts = line.split(' ');
- if (parts.length > 1) {
- appsObj.versions.deno = parts[1];
- }
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'node')) {
- exec('node -v', function (error, stdout) {
- if (!error) {
- let line = stdout.toString().split('\n')[0].trim();
- if (line.startsWith('v')) { line = line.slice(1); }
- appsObj.versions.node = line;
- }
- functionProcessed();
- });
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'powershell')) {
- if (_windows) {
- util.powerShell('$PSVersionTable').then(stdout => {
- const lines = stdout.toString().split('\n').map(line => line.replace(/ +/g, ' ').replace(/ +/g, ':'));
- appsObj.versions.powershell = util.getValue(lines, 'psversion');
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- }
- if ({}.hasOwnProperty.call(appsObj.versions, 'dotnet')) {
- if (_windows) {
- util.powerShell('gci "HKLM:\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP" -recurse | gp -name Version,Release -EA 0 | where { $_.PSChildName -match "^(?!S)\\p{L}"} | select PSChildName, Version, Release').then(stdout => {
- const lines = stdout.toString().split('\r\n');
- let dotnet = '';
- lines.forEach(line => {
- line = line.replace(/ +/g, ' ');
- const parts = line.split(' ');
- dotnet = dotnet || (parts[0].toLowerCase().startsWith('client') && parts.length > 2 ? parts[1].trim() : (parts[0].toLowerCase().startsWith('full') && parts.length > 2 ? parts[1].trim() : ''));
- });
- appsObj.versions.dotnet = dotnet.trim();
- functionProcessed();
- });
- } else {
- functionProcessed();
- }
- }
- } catch (e) {
- if (callback) { callback(appsObj.versions); }
- resolve(appsObj.versions);
- }
- });
- });
-}
-
-exports.versions = versions;
-
-function shell(callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (_windows) {
- resolve('cmd');
- } else {
- let result = '';
- exec('echo $SHELL', function (error, stdout) {
- if (!error) {
- result = stdout.toString().split('\n')[0];
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- });
- });
-}
-
-exports.shell = shell;
-
-function getUniqueMacAdresses() {
- let macs = [];
- try {
- const ifaces = os.networkInterfaces();
- for (let dev in ifaces) {
- if ({}.hasOwnProperty.call(ifaces, dev)) {
- ifaces[dev].forEach(function (details) {
- if (details && details.mac && details.mac !== '00:00:00:00:00:00') {
- const mac = details.mac.toLowerCase();
- if (macs.indexOf(mac) === -1) {
- macs.push(mac);
- }
- }
- });
- }
- }
- macs = macs.sort(function (a, b) {
- if (a < b) { return -1; }
- if (a > b) { return 1; }
- return 0;
- });
- } catch (e) {
- macs.push('00:00:00:00:00:00');
- }
- return macs;
-}
-
-function uuid(callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- os: '',
- hardware: '',
- macs: getUniqueMacAdresses()
- };
- let parts;
-
- if (_darwin) {
- exec('system_profiler SPHardwareDataType -json', function (error, stdout) {
- if (!error) {
- try {
- const jsonObj = JSON.parse(stdout.toString());
- if (jsonObj.SPHardwareDataType && jsonObj.SPHardwareDataType.length > 0) {
- const spHardware = jsonObj.SPHardwareDataType[0];
- result.os = spHardware.platform_UUID.toLowerCase();
- result.hardware = spHardware.serial_number;
- }
- } catch (e) {
- util.noop();
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_linux) {
- const cmd = `echo -n "os: "; cat /var/lib/dbus/machine-id 2> /dev/null ||
-cat /etc/machine-id 2> /dev/null; echo;
-echo -n "hardware: "; cat /sys/class/dmi/id/product_uuid 2> /dev/null; echo;`;
- exec(cmd, function (error, stdout) {
- const lines = stdout.toString().split('\n');
- result.os = util.getValue(lines, 'os').toLowerCase();
- result.hardware = util.getValue(lines, 'hardware').toLowerCase();
- if (!result.hardware) {
- const lines = fs.readFileSync('/proc/cpuinfo', { encoding: 'utf8' }).toString().split('\n');
- const serial = util.getValue(lines, 'serial');
- result.hardware = serial || '';
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('sysctl -i kern.hostid kern.hostuuid', function (error, stdout) {
- const lines = stdout.toString().split('\n');
- result.os = util.getValue(lines, 'kern.hostid', ':').toLowerCase();
- result.hardware = util.getValue(lines, 'kern.hostuuid', ':').toLowerCase();
- if (result.os.indexOf('unknown') >= 0) { result.os = ''; }
- if (result.hardware.indexOf('unknown') >= 0) { result.hardware = ''; }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_windows) {
- let sysdir = '%windir%\\System32';
- if (process.arch === 'ia32' && Object.prototype.hasOwnProperty.call(process.env, 'PROCESSOR_ARCHITEW6432')) {
- sysdir = '%windir%\\sysnative\\cmd.exe /c %windir%\\System32';
- }
- util.powerShell('Get-CimInstance Win32_ComputerSystemProduct | select UUID | fl').then((stdout) => {
- let lines = stdout.split('\r\n');
- result.hardware = util.getValue(lines, 'uuid', ':').toLowerCase();
- exec(`${sysdir}\\reg query "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid`, util.execOptsWin, function (error, stdout) {
- parts = stdout.toString().split('\n\r')[0].split('REG_SZ');
- result.os = parts.length > 1 ? parts[1].replace(/\r+|\n+|\s+/ig, '').toLowerCase() : '';
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- });
- }
- });
- });
-}
-
-exports.uuid = uuid;
-
-
-/***/ }),
-
-/***/ 14497:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// printers.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 15. printers
-// ----------------------------------------------------------------------------------
-
-const exec = (__nccwpck_require__(35317).exec);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-const winPrinterStatus = {
- 1: 'Other',
- 2: 'Unknown',
- 3: 'Idle',
- 4: 'Printing',
- 5: 'Warmup',
- 6: 'Stopped Printing',
- 7: 'Offline',
-};
-
-function parseLinuxCupsHeader(lines) {
- const result = {};
- if (lines && lines.length) {
- if (lines[0].indexOf(' CUPS v') > 0) {
- const parts = lines[0].split(' CUPS v');
- result.cupsVersion = parts[1];
- }
- }
- return result;
-}
-
-function parseLinuxCupsPrinter(lines) {
- const result = {};
- const printerId = util.getValue(lines, 'PrinterId', ' ');
- result.id = printerId ? parseInt(printerId, 10) : null;
- result.name = util.getValue(lines, 'Info', ' ');
- result.model = lines.length > 0 && lines[0] ? lines[0].split(' ')[0] : '';
- result.uri = util.getValue(lines, 'DeviceURI', ' ');
- result.uuid = util.getValue(lines, 'UUID', ' ');
- result.status = util.getValue(lines, 'State', ' ');
- result.local = util.getValue(lines, 'Location', ' ').toLowerCase().startsWith('local');
- result.default = null;
- result.shared = util.getValue(lines, 'Shared', ' ').toLowerCase().startsWith('yes');
-
- return result;
-}
-
-function parseLinuxLpstatPrinter(lines, id) {
- const result = {};
- result.id = id;
- result.name = util.getValue(lines, 'Description', ':', true);
- result.model = lines.length > 0 && lines[0] ? lines[0].split(' ')[0] : '';
- result.uri = null;
- result.uuid = null;
- result.status = lines.length > 0 && lines[0] ? (lines[0].indexOf(' idle') > 0 ? 'idle' : (lines[0].indexOf(' printing') > 0 ? 'printing' : 'unknown')) : null;
- result.local = util.getValue(lines, 'Location', ':', true).toLowerCase().startsWith('local');
- result.default = null;
- result.shared = util.getValue(lines, 'Shared', ' ').toLowerCase().startsWith('yes');
-
- return result;
-}
-
-function parseDarwinPrinters(printerObject, id) {
- const result = {};
- const uriParts = printerObject.uri.split('/');
- result.id = id;
- result.name = printerObject._name;
- result.model = uriParts.length ? uriParts[uriParts.length - 1] : '';
- result.uri = printerObject.uri;
- result.uuid = null;
- result.status = printerObject.status;
- result.local = printerObject.printserver === 'local';
- result.default = printerObject.default === 'yes';
- result.shared = printerObject.shared === 'yes';
-
- return result;
-}
-
-function parseWindowsPrinters(lines, id) {
- const result = {};
- const status = parseInt(util.getValue(lines, 'PrinterStatus', ':'), 10);
-
- result.id = id;
- result.name = util.getValue(lines, 'name', ':');
- result.model = util.getValue(lines, 'DriverName', ':');
- result.uri = null;
- result.uuid = null;
- result.status = winPrinterStatus[status] ? winPrinterStatus[status] : null;
- result.local = util.getValue(lines, 'Local', ':').toUpperCase() === 'TRUE';
- result.default = util.getValue(lines, 'Default', ':').toUpperCase() === 'TRUE';
- result.shared = util.getValue(lines, 'Shared', ':').toUpperCase() === 'TRUE';
-
- return result;
-}
-
-function printer(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux || _freebsd || _openbsd || _netbsd) {
- let cmd = 'cat /etc/cups/printers.conf 2>/dev/null';
- exec(cmd, function (error, stdout) {
- // printers.conf
- if (!error) {
- const parts = stdout.toString().split(' {
- if (!error) {
- const parts = stdout.toString().split(/\n\s*\n/);
- for (let i = 0; i < parts.length; i++) {
- const printer = parseWindowsPrinters(parts[i].split('\n'), i);
- if (printer.name || printer.model) {
- result.push(printer);
- }
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_sunos) {
- resolve(null);
- }
- });
- });
-}
-
-exports.printer = printer;
-
-
-/***/ }),
-
-/***/ 76340:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// processes.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 10. Processes
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const fs = __nccwpck_require__(79896);
-const path = __nccwpck_require__(16928);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-const _processes_cpu = {
- all: 0,
- all_utime: 0,
- all_stime: 0,
- list: {},
- ms: 0,
- result: {}
-};
-const _services_cpu = {
- all: 0,
- all_utime: 0,
- all_stime: 0,
- list: {},
- ms: 0,
- result: {}
-};
-const _process_cpu = {
- all: 0,
- all_utime: 0,
- all_stime: 0,
- list: {},
- ms: 0,
- result: {}
-};
-
-const _winStatusValues = {
- '0': 'unknown',
- '1': 'other',
- '2': 'ready',
- '3': 'running',
- '4': 'blocked',
- '5': 'suspended blocked',
- '6': 'suspended ready',
- '7': 'terminated',
- '8': 'stopped',
- '9': 'growing',
-};
-
-function parseTimeUnix(time) {
- let result = time;
- let parts = time.replace(/ +/g, ' ').split(' ');
- if (parts.length === 5) {
- result = parts[4] + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(parts[1].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + parts[2]).slice(-2) + ' ' + parts[3];
- }
- return result;
-}
-
-function parseElapsedTime(etime) {
- let current = new Date();
- current = new Date(current.getTime() - current.getTimezoneOffset() * 60000);
-
- const elapsed = etime.split('-');
-
- const timeIndex = elapsed.length - 1;
- const days = timeIndex > 0 ? parseInt(elapsed[timeIndex - 1]) : 0;
-
- const timeStr = elapsed[timeIndex].split(':');
- const hours = timeStr.length === 3 ? parseInt(timeStr[0] || 0) : 0;
- const mins = parseInt(timeStr[timeStr.length === 3 ? 1 : 0] || 0);
- const secs = parseInt(timeStr[timeStr.length === 3 ? 2 : 1] || 0);
- const ms = (((((days * 24 + hours) * 60) + mins) * 60 + secs) * 1000);
-
- let res = new Date(current.getTime());
- let result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19);
- try {
- res = new Date(current.getTime() - ms);
- result = res.toISOString().substring(0, 10) + ' ' + res.toISOString().substring(11, 19);
- } catch (e) {
- util.noop();
- }
- return result;
-}
-
-// --------------------------
-// PS - services
-// pass a comma separated string with services to check (mysql, apache, postgresql, ...)
-// this function gives an array back, if the services are running.
-
-function services(srv, callback) {
-
- // fallback - if only callback is given
- if (util.isFunction(srv) && !callback) {
- callback = srv;
- srv = '';
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- if (typeof srv !== 'string') {
- if (callback) { callback([]); }
- return resolve([]);
- }
-
- if (srv) {
- let srvString = '';
- try {
- srvString.__proto__.toLowerCase = util.stringToLower;
- srvString.__proto__.replace = util.stringReplace;
- srvString.__proto__.trim = util.stringTrim;
- } catch (e) {
- Object.setPrototypeOf(srvString, util.stringObj);
- }
-
- const s = util.sanitizeShellString(srv);
- const l = util.mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- srvString = srvString + s[i];
- }
- }
-
- srvString = srvString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|');
- if (srvString === '') {
- srvString = '*';
- }
- if (util.isPrototypePolluted() && srvString !== '*') {
- srvString = '------';
- }
- let srvs = srvString.split('|');
- let result = [];
- let dataSrv = [];
-
- if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
- if ((_linux || _freebsd || _openbsd || _netbsd) && srvString === '*') {
- try {
- const tmpsrv = execSync('systemctl --all --type=service --no-legend 2> /dev/null', util.execOptsLinux).toString().split('\n');
- srvs = [];
- for (const s of tmpsrv) {
- const name = s.split('.service')[0];
- if (name && s.indexOf(' not-found ') === -1) {
- srvs.push(name.trim());
- }
- }
- srvString = srvs.join('|');
- } catch (d) {
- try {
- srvString = '';
- const tmpsrv = execSync('service --status-all 2> /dev/null', util.execOptsLinux).toString().split('\n');
- for (const s of tmpsrv) {
- const parts = s.split(']');
- if (parts.length === 2) {
- srvString += (srvString !== '' ? '|' : '') + parts[1].trim();
- }
- }
- srvs = srvString.split('|');
- } catch (e) {
- try {
- const srvStr = execSync('ls /etc/init.d/ -m 2> /dev/null', util.execOptsLinux).toString().split('\n').join('');
- srvString = '';
- if (srvStr) {
- const tmpsrv = srvStr.split(',');
- for (const s of tmpsrv) {
- const name = s.trim();
- if (name) {
- srvString += (srvString !== '' ? '|' : '') + name;
- }
- }
- srvs = srvString.split('|');
- }
- } catch (f) {
- srvString = '';
- srvs = [];
- }
- }
- }
- }
- if ((_darwin) && srvString === '*') { // service enumeration not yet suported on mac OS
- if (callback) { callback(result); }
- resolve(result);
- }
- let args = (_darwin) ? ['-caxo', 'pcpu,pmem,pid,command'] : ['-axo', 'pcpu,pmem,pid,command'];
- if (srvString !== '' && srvs.length > 0) {
- util.execSafe('ps', args).then((stdout) => {
- if (stdout) {
- let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n');
- srvs.forEach(function (srv) {
- let ps;
- if (_darwin) {
- ps = lines.filter(function (e) {
- return (e.toLowerCase().indexOf(srv) !== -1);
- });
-
- } else {
- ps = lines.filter(function (e) {
- return (e.toLowerCase().indexOf(' ' + srv.toLowerCase() + ':') !== -1) || (e.toLowerCase().indexOf('/' + srv.toLowerCase()) !== -1);
- });
- }
- const pids = [];
- for (const p of ps) {
- const pid = p.trim().split(' ')[2];
- if (pid) {
- pids.push(parseInt(pid, 10));
- }
- }
- result.push({
- name: srv,
- running: ps.length > 0,
- startmode: '',
- pids: pids,
- cpu: parseFloat((ps.reduce(function (pv, cv) {
- return pv + parseFloat(cv.trim().split(' ')[0]);
- }, 0)).toFixed(2)),
- mem: parseFloat((ps.reduce(function (pv, cv) {
- return pv + parseFloat(cv.trim().split(' ')[1]);
- }, 0)).toFixed(2))
- });
- });
- if (_linux) {
- // calc process_cpu - ps is not accurate in linux!
- let cmd = 'cat /proc/stat | grep "cpu "';
- for (let i in result) {
- for (let j in result[i].pids) {
- cmd += (';cat /proc/' + result[i].pids[j] + '/stat');
- }
- }
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- let curr_processes = stdout.toString().split('\n');
-
- // first line (all - /proc/stat)
- let all = parseProcStat(curr_processes.shift());
-
- // process
- let list_new = {};
- let resultProcess = {};
- curr_processes.forEach((element) => {
- resultProcess = calcProcStatLinux(element, all, _services_cpu);
-
- if (resultProcess.pid) {
- let listPos = -1;
- for (let i in result) {
- for (let j in result[i].pids) {
- if (parseInt(result[i].pids[j]) === parseInt(resultProcess.pid)) {
- listPos = i;
- }
- }
- }
- if (listPos >= 0) {
- result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus;
- }
-
- // save new values
- list_new[resultProcess.pid] = {
- cpuu: resultProcess.cpuu,
- cpus: resultProcess.cpus,
- utime: resultProcess.utime,
- stime: resultProcess.stime,
- cutime: resultProcess.cutime,
- cstime: resultProcess.cstime
- };
- }
- });
-
- // store old values
- _services_cpu.all = all;
- _services_cpu.list = Object.assign({}, list_new);
- _services_cpu.ms = Date.now() - _services_cpu.ms;
- _services_cpu.result = Object.assign({}, result);
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- args = ['-o', 'comm'];
- util.execSafe('ps', args).then((stdout) => {
- if (stdout) {
- let lines = stdout.replace(/ +/g, ' ').replace(/,+/g, '.').split('\n');
- srvs.forEach(function (srv) {
- let ps = lines.filter(function (e) {
- return e.indexOf(srv) !== -1;
- });
- result.push({
- name: srv,
- running: ps.length > 0,
- startmode: '',
- cpu: 0,
- mem: 0
- });
- });
- if (callback) { callback(result); }
- resolve(result);
- } else {
- srvs.forEach(function (srv) {
- result.push({
- name: srv,
- running: false,
- startmode: '',
- cpu: 0,
- mem: 0
- });
- });
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- }
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- if (_windows) {
- try {
- let wincommand = 'Get-CimInstance Win32_Service';
- if (srvs[0] !== '*') {
- wincommand += ' -Filter "';
- srvs.forEach((srv) => {
- wincommand += `Name='${srv}' or `;
- });
- wincommand = `${wincommand.slice(0, -4)}"`;
- }
- wincommand += ' | select Name,Caption,Started,StartMode,ProcessId | fl';
- util.powerShell(wincommand).then((stdout, error) => {
- if (!error) {
- let serviceSections = stdout.split(/\n\s*\n/);
- serviceSections.forEach((element) => {
- if (element.trim() !== '') {
- let lines = element.trim().split('\r\n');
- let srvName = util.getValue(lines, 'Name', ':', true).toLowerCase();
- let srvCaption = util.getValue(lines, 'Caption', ':', true).toLowerCase();
- let started = util.getValue(lines, 'Started', ':', true);
- let startMode = util.getValue(lines, 'StartMode', ':', true);
- let pid = util.getValue(lines, 'ProcessId', ':', true);
- if (srvString === '*' || srvs.indexOf(srvName) >= 0 || srvs.indexOf(srvCaption) >= 0) {
- result.push({
- name: srvName,
- running: (started.toLowerCase() === 'true'),
- startmode: startMode,
- pids: [pid],
- cpu: 0,
- mem: 0
- });
- dataSrv.push(srvName);
- dataSrv.push(srvCaption);
- }
- }
-
- });
-
- if (srvString !== '*') {
- let srvsMissing = srvs.filter(function (e) {
- return dataSrv.indexOf(e) === -1;
- });
- srvsMissing.forEach(function (srvName) {
- result.push({
- name: srvName,
- running: false,
- startmode: '',
- pids: [],
- cpu: 0,
- mem: 0
- });
- });
- }
- if (callback) { callback(result); }
- resolve(result);
- } else {
- srvs.forEach(function (srvName) {
- result.push({
- name: srvName,
- running: false,
- startmode: '',
- cpu: 0,
- mem: 0
- });
- });
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- } else {
- if (callback) { callback([]); }
- resolve([]);
- }
- });
- });
-}
-
-exports.services = services;
-
-function parseProcStat(line) {
- let parts = line.replace(/ +/g, ' ').split(' ');
- let user = (parts.length >= 2 ? parseInt(parts[1]) : 0);
- let nice = (parts.length >= 3 ? parseInt(parts[2]) : 0);
- let system = (parts.length >= 4 ? parseInt(parts[3]) : 0);
- let idle = (parts.length >= 5 ? parseInt(parts[4]) : 0);
- let iowait = (parts.length >= 6 ? parseInt(parts[5]) : 0);
- let irq = (parts.length >= 7 ? parseInt(parts[6]) : 0);
- let softirq = (parts.length >= 8 ? parseInt(parts[7]) : 0);
- let steal = (parts.length >= 9 ? parseInt(parts[8]) : 0);
- let guest = (parts.length >= 10 ? parseInt(parts[9]) : 0);
- let guest_nice = (parts.length >= 11 ? parseInt(parts[10]) : 0);
- return user + nice + system + idle + iowait + irq + softirq + steal + guest + guest_nice;
-}
-
-function calcProcStatLinux(line, all, _cpu_old) {
- let statparts = line.replace(/ +/g, ' ').split(')');
- if (statparts.length >= 2) {
- let parts = statparts[1].split(' ');
- if (parts.length >= 16) {
- let pid = parseInt(statparts[0].split(' ')[0]);
- let utime = parseInt(parts[12]);
- let stime = parseInt(parts[13]);
- let cutime = parseInt(parts[14]);
- let cstime = parseInt(parts[15]);
-
- // calc
- let cpuu = 0;
- let cpus = 0;
- if (_cpu_old.all > 0 && _cpu_old.list[pid]) {
- cpuu = (utime + cutime - _cpu_old.list[pid].utime - _cpu_old.list[pid].cutime) / (all - _cpu_old.all) * 100; // user
- cpus = (stime + cstime - _cpu_old.list[pid].stime - _cpu_old.list[pid].cstime) / (all - _cpu_old.all) * 100; // system
- } else {
- cpuu = (utime + cutime) / (all) * 100; // user
- cpus = (stime + cstime) / (all) * 100; // system
- }
- return {
- pid: pid,
- utime: utime,
- stime: stime,
- cutime: cutime,
- cstime: cstime,
- cpuu: cpuu,
- cpus: cpus
- };
- } else {
- return {
- pid: 0,
- utime: 0,
- stime: 0,
- cutime: 0,
- cstime: 0,
- cpuu: 0,
- cpus: 0
- };
- }
- } else {
- return {
- pid: 0,
- utime: 0,
- stime: 0,
- cutime: 0,
- cstime: 0,
- cpuu: 0,
- cpus: 0
- };
- }
-}
-
-function calcProcStatWin(procStat, all, _cpu_old) {
- // calc
- let cpuu = 0;
- let cpus = 0;
- if (_cpu_old.all > 0 && _cpu_old.list[procStat.pid]) {
- cpuu = (procStat.utime - _cpu_old.list[procStat.pid].utime) / (all - _cpu_old.all) * 100; // user
- cpus = (procStat.stime - _cpu_old.list[procStat.pid].stime) / (all - _cpu_old.all) * 100; // system
- } else {
- cpuu = (procStat.utime) / (all) * 100; // user
- cpus = (procStat.stime) / (all) * 100; // system
- }
- return {
- pid: procStat.pid,
- utime: procStat.utime,
- stime: procStat.stime,
- cpuu: cpuu > 0 ? cpuu : 0,
- cpus: cpus > 0 ? cpus : 0
- };
-}
-
-
-
-// --------------------------
-// running processes
-
-function processes(callback) {
-
- let parsedhead = [];
-
- function getName(command) {
- command = command || '';
- let result = command.split(' ')[0];
- if (result.substr(-1) === ':') {
- result = result.substr(0, result.length - 1);
- }
- if (result.substr(0, 1) !== '[') {
- let parts = result.split('/');
- if (isNaN(parseInt(parts[parts.length - 1]))) {
- result = parts[parts.length - 1];
- } else {
- result = parts[0];
- }
- }
- return result;
- }
-
- function parseLine(line) {
-
- let offset = 0;
- let offset2 = 0;
-
- function checkColumn(i) {
- offset = offset2;
- if (parsedhead[i]) {
- offset2 = line.substring(parsedhead[i].to + offset, 10000).indexOf(' ');
- } else {
- offset2 = 10000;
- }
- }
-
- checkColumn(0);
- const pid = parseInt(line.substring(parsedhead[0].from + offset, parsedhead[0].to + offset2));
- checkColumn(1);
- const ppid = parseInt(line.substring(parsedhead[1].from + offset, parsedhead[1].to + offset2));
- checkColumn(2);
- const cpu = parseFloat(line.substring(parsedhead[2].from + offset, parsedhead[2].to + offset2).replace(/,/g, '.'));
- checkColumn(3);
- const mem = parseFloat(line.substring(parsedhead[3].from + offset, parsedhead[3].to + offset2).replace(/,/g, '.'));
- checkColumn(4);
- const priority = parseInt(line.substring(parsedhead[4].from + offset, parsedhead[4].to + offset2));
- checkColumn(5);
- const vsz = parseInt(line.substring(parsedhead[5].from + offset, parsedhead[5].to + offset2));
- checkColumn(6);
- const rss = parseInt(line.substring(parsedhead[6].from + offset, parsedhead[6].to + offset2));
- checkColumn(7);
- const nice = parseInt(line.substring(parsedhead[7].from + offset, parsedhead[7].to + offset2)) || 0;
- checkColumn(8);
- const started = !_sunos ? parseElapsedTime(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim()) : parseTimeUnix(line.substring(parsedhead[8].from + offset, parsedhead[8].to + offset2).trim());
- checkColumn(9);
- let state = line.substring(parsedhead[9].from + offset, parsedhead[9].to + offset2).trim();
- state = (state[0] === 'R' ? 'running' : (state[0] === 'S' ? 'sleeping' : (state[0] === 'T' ? 'stopped' : (state[0] === 'W' ? 'paging' : (state[0] === 'X' ? 'dead' : (state[0] === 'Z' ? 'zombie' : ((state[0] === 'D' || state[0] === 'U') ? 'blocked' : 'unknown')))))));
- checkColumn(10);
- let tty = line.substring(parsedhead[10].from + offset, parsedhead[10].to + offset2).trim();
- if (tty === '?' || tty === '??') { tty = ''; }
- checkColumn(11);
- const user = line.substring(parsedhead[11].from + offset, parsedhead[11].to + offset2).trim();
- checkColumn(12);
- let cmdPath = '';
- let command = '';
- let params = '';
- let fullcommand = line.substring(parsedhead[12].from + offset, parsedhead[12].to + offset2).trim();
- if (fullcommand.substr(fullcommand.length - 1) === ']') { fullcommand = fullcommand.slice(0, -1); }
- if (fullcommand.substr(0, 1) === '[') { command = fullcommand.substring(1); }
- else {
- const p1 = fullcommand.indexOf('(');
- const p2 = fullcommand.indexOf(')');
- const p3 = fullcommand.indexOf('/');
- const p4 = fullcommand.indexOf(':');
- if (p1 < p2 && p1 < p3 && p3 < p2) {
- command = fullcommand.split(' ')[0];
- command = command.replace(/:/g, '');
- } else {
- if (p4 > 0 && (p3 === -1 || p3 > 3)) {
- command = fullcommand.split(' ')[0];
- command = command.replace(/:/g, '');
- } else {
- // try to figure out where parameter starts
- let firstParamPos = fullcommand.indexOf(' -');
- let firstParamPathPos = fullcommand.indexOf(' /');
- firstParamPos = (firstParamPos >= 0 ? firstParamPos : 10000);
- firstParamPathPos = (firstParamPathPos >= 0 ? firstParamPathPos : 10000);
- const firstPos = Math.min(firstParamPos, firstParamPathPos);
- let tmpCommand = fullcommand.substr(0, firstPos);
- const tmpParams = fullcommand.substr(firstPos);
- const lastSlashPos = tmpCommand.lastIndexOf('/');
- if (lastSlashPos >= 0) {
- cmdPath = tmpCommand.substr(0, lastSlashPos);
- tmpCommand = tmpCommand.substr(lastSlashPos + 1);
- }
-
- if (firstPos === 10000 && tmpCommand.indexOf(' ') > -1) {
- const parts = tmpCommand.split(' ');
- if (fs.existsSync(path.join(cmdPath, parts[0]))) {
- command = parts.shift();
- params = (parts.join(' ') + ' ' + tmpParams).trim();
- } else {
- command = tmpCommand.trim();
- params = tmpParams.trim();
- }
- } else {
- command = tmpCommand.trim();
- params = tmpParams.trim();
- }
- }
- }
-
- }
-
- return ({
- pid: pid,
- parentPid: ppid,
- name: _linux ? getName(command) : command,
- cpu: cpu,
- cpuu: 0,
- cpus: 0,
- mem: mem,
- priority: priority,
- memVsz: vsz,
- memRss: rss,
- nice: nice,
- started: started,
- state: state,
- tty: tty,
- user: user,
- command: command,
- params: params,
- path: cmdPath
- });
- }
-
- function parseProcesses(lines) {
- let result = [];
- if (lines.length > 1) {
- let head = lines[0];
- parsedhead = util.parseHead(head, 8);
- lines.shift();
- lines.forEach(function (line) {
- if (line.trim() !== '') {
- result.push(parseLine(line));
- }
- });
- }
- return result;
- }
- function parseProcesses2(lines) {
-
- function formatDateTime(time) {
- const month = ('0' + (time.getMonth() + 1).toString()).slice(-2);
- const year = time.getFullYear().toString();
- const day = ('0' + time.getDate().toString()).slice(-2);
- const hours = ('0' + time.getHours().toString()).slice(-2);
- const mins = ('0' + time.getMinutes().toString()).slice(-2);
- const secs = ('0' + time.getSeconds().toString()).slice(-2);
-
- return (year + '-' + month + '-' + day + ' ' + hours + ':' + mins + ':' + secs);
- }
-
- function parseElapsed(etime) {
- let started = '';
- if (etime.indexOf('d') >= 0) {
- const elapsed_parts = etime.split('d');
- started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 24 + elapsed_parts[1] * 1) * 60 * 60 * 1000));
- } else if (etime.indexOf('h') >= 0) {
- const elapsed_parts = etime.split('h');
- started = formatDateTime(new Date(Date.now() - (elapsed_parts[0] * 60 + elapsed_parts[1] * 1) * 60 * 1000));
- } else if (etime.indexOf(':') >= 0) {
- const elapsed_parts = etime.split(':');
- started = formatDateTime(new Date(Date.now() - (elapsed_parts.length > 1 ? (elapsed_parts[0] * 60 + elapsed_parts[1]) * 1000 : elapsed_parts[0] * 1000)));
- }
- return started;
- }
-
- let result = [];
- lines.forEach(function (line) {
- if (line.trim() !== '') {
- line = line.trim().replace(/ +/g, ' ').replace(/,+/g, '.');
- const parts = line.split(' ');
- const command = parts.slice(9).join(' ');
- const pmem = parseFloat((1.0 * parseInt(parts[3]) * 1024 / os.totalmem()).toFixed(1));
- const started = parseElapsed(parts[5]);
-
- result.push({
- pid: parseInt(parts[0]),
- parentPid: parseInt(parts[1]),
- name: getName(command),
- cpu: 0,
- cpuu: 0,
- cpus: 0,
- mem: pmem,
- priority: 0,
- memVsz: parseInt(parts[2]),
- memRss: parseInt(parts[3]),
- nice: parseInt(parts[4]),
- started: started,
- state: (parts[6] === 'R' ? 'running' : (parts[6] === 'S' ? 'sleeping' : (parts[6] === 'T' ? 'stopped' : (parts[6] === 'W' ? 'paging' : (parts[6] === 'X' ? 'dead' : (parts[6] === 'Z' ? 'zombie' : ((parts[6] === 'D' || parts[6] === 'U') ? 'blocked' : 'unknown'))))))),
- tty: parts[7],
- user: parts[8],
- command: command
- });
- }
- });
- return result;
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = {
- all: 0,
- running: 0,
- blocked: 0,
- sleeping: 0,
- unknown: 0,
- list: []
- };
-
- let cmd = '';
-
- if ((_processes_cpu.ms && Date.now() - _processes_cpu.ms >= 500) || _processes_cpu.ms === 0) {
- if (_linux || _freebsd || _openbsd || _netbsd || _darwin || _sunos) {
- if (_linux) { cmd = 'export LC_ALL=C; ps -axo pid:11,ppid:11,pcpu:6,pmem:6,pri:5,vsz:11,rss:11,ni:5,etime:30,state:5,tty:15,user:20,command; unset LC_ALL'; }
- if (_freebsd || _openbsd || _netbsd) { cmd = 'export LC_ALL=C; ps -axo pid,ppid,pcpu,pmem,pri,vsz,rss,ni,etime,state,tty,user,command; unset LC_ALL'; }
- if (_darwin) { cmd = 'ps -axo pid,ppid,pcpu,pmem,pri,vsz=temp_title_1,rss=temp_title_2,nice,etime=temp_title_3,state,tty,user,command -r'; }
- if (_sunos) { cmd = 'ps -Ao pid,ppid,pcpu,pmem,pri,vsz,rss,nice,stime,s,tty,user,comm'; }
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- if (!error && stdout.toString().trim()) {
- result.list = (parseProcesses(stdout.toString().split('\n'))).slice();
- result.all = result.list.length;
- result.running = result.list.filter(function (e) {
- return e.state === 'running';
- }).length;
- result.blocked = result.list.filter(function (e) {
- return e.state === 'blocked';
- }).length;
- result.sleeping = result.list.filter(function (e) {
- return e.state === 'sleeping';
- }).length;
-
- if (_linux) {
- // calc process_cpu - ps is not accurate in linux!
- cmd = 'cat /proc/stat | grep "cpu "';
- result.list.forEach((element) => {
- cmd += (';cat /proc/' + element.pid + '/stat');
- });
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- let curr_processes = stdout.toString().split('\n');
-
- // first line (all - /proc/stat)
- let all = parseProcStat(curr_processes.shift());
-
- // process
- let list_new = {};
- let resultProcess = {};
- curr_processes.forEach((element) => {
- resultProcess = calcProcStatLinux(element, all, _processes_cpu);
-
- if (resultProcess.pid) {
-
- // store pcpu in outer array
- let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid);
- if (listPos >= 0) {
- result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus;
- result.list[listPos].cpuu = resultProcess.cpuu;
- result.list[listPos].cpus = resultProcess.cpus;
- }
-
- // save new values
- list_new[resultProcess.pid] = {
- cpuu: resultProcess.cpuu,
- cpus: resultProcess.cpus,
- utime: resultProcess.utime,
- stime: resultProcess.stime,
- cutime: resultProcess.cutime,
- cstime: resultProcess.cstime
- };
- }
- });
-
- // store old values
- _processes_cpu.all = all;
- _processes_cpu.list = Object.assign({}, list_new);
- _processes_cpu.ms = Date.now() - _processes_cpu.ms;
- _processes_cpu.result = Object.assign({}, result);
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,stat,tty,user,comm';
- if (_sunos) {
- cmd = 'ps -o pid,ppid,vsz,rss,nice,etime,s,tty,user,comm';
- }
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- lines.shift();
-
- result.list = parseProcesses2(lines).slice();
- result.all = result.list.length;
- result.running = result.list.filter(function (e) {
- return e.state === 'running';
- }).length;
- result.blocked = result.list.filter(function (e) {
- return e.state === 'blocked';
- }).length;
- result.sleeping = result.list.filter(function (e) {
- return e.state === 'sleeping';
- }).length;
- if (callback) { callback(result); }
- resolve(result);
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- }
- });
- } else if (_windows) {
- try {
- util.powerShell('Get-CimInstance Win32_Process | select-Object ProcessId,ParentProcessId,ExecutionState,Caption,CommandLine,ExecutablePath,UserModeTime,KernelModeTime,WorkingSetSize,Priority,PageFileUsage, @{n="CreationDate";e={$_.CreationDate.ToString("yyyy-MM-dd HH:mm:ss")}} | fl').then((stdout, error) => {
- if (!error) {
- let processSections = stdout.split(/\n\s*\n/);
- let procs = [];
- let procStats = [];
- let list_new = {};
- let allcpuu = 0;
- let allcpus = 0;
- processSections.forEach((element) => {
- if (element.trim() !== '') {
- let lines = element.trim().split('\r\n');
- let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10);
- let parentPid = parseInt(util.getValue(lines, 'ParentProcessId', ':', true), 10);
- let statusValue = util.getValue(lines, 'ExecutionState', ':');
- let name = util.getValue(lines, 'Caption', ':', true);
- let commandLine = util.getValue(lines, 'CommandLine', ':', true);
- // get additional command line data
- let additionalCommand = false;
- lines.forEach((line) => {
- if (additionalCommand && line.toLowerCase().startsWith(' ')) {
- commandLine += ' ' + line.trim();
- } else {
- additionalCommand = false;
- }
- if (line.toLowerCase().startsWith('commandline')) {
- additionalCommand = true;
- }
- });
- let commandPath = util.getValue(lines, 'ExecutablePath', ':', true);
- let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10);
- let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10);
- let memw = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10);
- allcpuu = allcpuu + utime;
- allcpus = allcpus + stime;
- result.all++;
- if (!statusValue) { result.unknown++; }
- if (statusValue === '3') { result.running++; }
- if (statusValue === '4' || statusValue === '5') { result.blocked++; }
-
- procStats.push({
- pid: pid,
- utime: utime,
- stime: stime,
- cpu: 0,
- cpuu: 0,
- cpus: 0,
- });
- procs.push({
- pid: pid,
- parentPid: parentPid,
- name: name,
- cpu: 0,
- cpuu: 0,
- cpus: 0,
- mem: memw / os.totalmem() * 100,
- priority: parseInt(util.getValue(lines, 'Priority', ':', true), 10),
- memVsz: parseInt(util.getValue(lines, 'PageFileUsage', ':', true), 10),
- memRss: Math.floor(parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10) / 1024),
- nice: 0,
- started: util.getValue(lines, 'CreationDate', ':', true),
- state: (!statusValue ? _winStatusValues[0] : _winStatusValues[statusValue]),
- tty: '',
- user: '',
- command: commandLine || name,
- path: commandPath,
- params: ''
- });
- }
- });
-
- result.sleeping = result.all - result.running - result.blocked - result.unknown;
- result.list = procs;
- procStats.forEach((element) => {
- let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _processes_cpu);
-
- // store pcpu in outer array
- let listPos = result.list.map(function (e) { return e.pid; }).indexOf(resultProcess.pid);
- if (listPos >= 0) {
- result.list[listPos].cpu = resultProcess.cpuu + resultProcess.cpus;
- result.list[listPos].cpuu = resultProcess.cpuu;
- result.list[listPos].cpus = resultProcess.cpus;
- }
-
- // save new values
- list_new[resultProcess.pid] = {
- cpuu: resultProcess.cpuu,
- cpus: resultProcess.cpus,
- utime: resultProcess.utime,
- stime: resultProcess.stime
- };
- });
-
- // store old values
- _processes_cpu.all = allcpuu + allcpus;
- _processes_cpu.all_utime = allcpuu;
- _processes_cpu.all_stime = allcpus;
- _processes_cpu.list = Object.assign({}, list_new);
- _processes_cpu.ms = Date.now() - _processes_cpu.ms;
- _processes_cpu.result = Object.assign({}, result);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(_processes_cpu.result); }
- resolve(_processes_cpu.result);
- }
- });
- });
-}
-
-exports.processes = processes;
-
-// --------------------------
-// PS - process load
-// get detailed information about a certain process
-// (PID, CPU-Usage %, Mem-Usage %)
-
-function processLoad(proc, callback) {
-
- // fallback - if only callback is given
- if (util.isFunction(proc) && !callback) {
- callback = proc;
- proc = '';
- }
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- proc = proc || '';
-
- if (typeof proc !== 'string') {
- if (callback) { callback([]); }
- return resolve([]);
- }
-
- let processesString = '';
- try {
- processesString.__proto__.toLowerCase = util.stringToLower;
- processesString.__proto__.replace = util.stringReplace;
- processesString.__proto__.trim = util.stringTrim;
- } catch (e) {
- Object.setPrototypeOf(processesString, util.stringObj);
- }
-
- const s = util.sanitizeShellString(proc);
- const l = util.mathMin(s.length, 2000);
-
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- processesString = processesString + s[i];
- }
- }
-
- processesString = processesString.trim().toLowerCase().replace(/, /g, '|').replace(/,+/g, '|');
- if (processesString === '') {
- processesString = '*';
- }
- if (util.isPrototypePolluted() && processesString !== '*') {
- processesString = '------';
- }
- let processes = processesString.split('|');
- let result = [];
-
- const procSanitized = util.isPrototypePolluted() ? '' : (util.sanitizeShellString(proc) || '*');
-
- // from here new
- // let result = {
- // 'proc': procSanitized,
- // 'pid': null,
- // 'cpu': 0,
- // 'mem': 0
- // };
- if (procSanitized && processes.length && processes[0] !== '------') {
- if (_windows) {
- try {
- util.powerShell('Get-CimInstance Win32_Process | select ProcessId,Caption,UserModeTime,KernelModeTime,WorkingSetSize | fl').then((stdout, error) => {
- if (!error) {
- let processSections = stdout.split(/\n\s*\n/);
- let procStats = [];
- let list_new = {};
- let allcpuu = 0;
- let allcpus = 0;
-
- // go through all processes
- processSections.forEach((element) => {
- if (element.trim() !== '') {
- let lines = element.trim().split('\r\n');
- let pid = parseInt(util.getValue(lines, 'ProcessId', ':', true), 10);
- let name = util.getValue(lines, 'Caption', ':', true);
- let utime = parseInt(util.getValue(lines, 'UserModeTime', ':', true), 10);
- let stime = parseInt(util.getValue(lines, 'KernelModeTime', ':', true), 10);
- let mem = parseInt(util.getValue(lines, 'WorkingSetSize', ':', true), 10);
- allcpuu = allcpuu + utime;
- allcpus = allcpus + stime;
-
- procStats.push({
- pid: pid,
- name,
- utime: utime,
- stime: stime,
- cpu: 0,
- cpuu: 0,
- cpus: 0,
- mem
- });
- let pname = '';
- let inList = false;
- processes.forEach(function (proc) {
- if (name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) {
- inList = true;
- pname = proc;
- }
- });
-
- if (processesString === '*' || inList) {
- let processFound = false;
- result.forEach(function (item) {
- if (item.proc.toLowerCase() === pname.toLowerCase()) {
- item.pids.push(pid);
- item.mem += mem / os.totalmem() * 100;
- processFound = true;
- }
- });
- if (!processFound) {
- result.push({
- proc: pname,
- pid: pid,
- pids: [pid],
- cpu: 0,
- mem: mem / os.totalmem() * 100
- });
- }
- }
- }
- });
-
- // add missing processes
- if (processesString !== '*') {
- let processesMissing = processes.filter(function (name) {
- return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0;
-
- });
- processesMissing.forEach(function (procName) {
- result.push({
- proc: procName,
- pid: null,
- pids: [],
- cpu: 0,
- mem: 0
- });
- });
- }
-
- // calculate proc stats for each proc
- procStats.forEach((element) => {
- let resultProcess = calcProcStatWin(element, allcpuu + allcpus, _process_cpu);
-
- let listPos = -1;
- for (let j = 0; j < result.length; j++) {
- if (result[j].pid === resultProcess.pid || result[j].pids.indexOf(resultProcess.pid) >= 0) { listPos = j; }
- }
- if (listPos >= 0) {
- result[listPos].cpu += resultProcess.cpuu + resultProcess.cpus;
- }
-
- // save new values
- list_new[resultProcess.pid] = {
- cpuu: resultProcess.cpuu,
- cpus: resultProcess.cpus,
- utime: resultProcess.utime,
- stime: resultProcess.stime
- };
- });
-
- // store old values
- _process_cpu.all = allcpuu + allcpus;
- _process_cpu.all_utime = allcpuu;
- _process_cpu.all_stime = allcpus;
- _process_cpu.list = Object.assign({}, list_new);
- _process_cpu.ms = Date.now() - _process_cpu.ms;
- _process_cpu.result = JSON.parse(JSON.stringify(result));
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
-
- if (_darwin || _linux || _freebsd || _openbsd || _netbsd) {
- const params = ['-axo', 'pid,ppid,pcpu,pmem,comm'];
- util.execSafe('ps', params).then((stdout) => {
- if (stdout) {
- let procStats = [];
- let lines = stdout.toString().split('\n').filter(function (line) {
- if (processesString === '*') { return true; }
- if (line.toLowerCase().indexOf('grep') !== -1) { return false; } // remove this??
- let found = false;
- processes.forEach(function (item) {
- found = found || (line.toLowerCase().indexOf(item.toLowerCase()) >= 0);
- });
- return found;
- });
- lines.shift();
- lines.forEach(function (line) {
- let data = line.trim().replace(/ +/g, ' ').split(' ');
- if (data.length > 4) {
- const linuxName = data[4].indexOf('/') >= 0 ? data[4].substring(0, data[4].indexOf('/')) : data[4];
- const name = _linux ? (linuxName) : data[4].substring(data[4].lastIndexOf('/') + 1);
- procStats.push({
- name,
- pid: parseInt(data[0]) || 0,
- ppid: parseInt(data[1]) || 0,
- cpu: parseFloat(data[2].replace(',', '.')),
- mem: parseFloat(data[3].replace(',', '.'))
- });
- }
- });
-
- procStats.forEach(function (item) {
- let listPos = -1;
- let inList = false;
- let name = item.name;
- for (let j = 0; j < result.length; j++) {
- if (item.name.toLowerCase().indexOf(result[j].proc.toLowerCase()) >= 0) {
- listPos = j;
- }
- }
- processes.forEach(function (proc) {
-
- if (item.name.toLowerCase().indexOf(proc.toLowerCase()) >= 0 && !inList) {
- inList = true;
- name = proc;
- }
- });
- if ((processesString === '*') || inList) {
- if (listPos < 0) {
- if (name) {
- result.push({
- proc: name,
- pid: item.pid,
- pids: [item.pid],
- cpu: item.cpu,
- mem: item.mem
- });
- }
- } else {
- if (item.ppid < 10) {
- result[listPos].pid = item.pid;
- }
- result[listPos].pids.push(item.pid);
- result[listPos].cpu += item.cpu;
- result[listPos].mem += item.mem;
- }
- }
- });
-
- if (processesString !== '*') {
- // add missing processes
- let processesMissing = processes.filter(function (name) {
- return procStats.filter(function (item) { return item.name.toLowerCase().indexOf(name) >= 0; }).length === 0;
- });
- processesMissing.forEach(function (procName) {
- result.push({
- proc: procName,
- pid: null,
- pids: [],
- cpu: 0,
- mem: 0
- });
- });
- }
- if (_linux) {
- // calc process_cpu - ps is not accurate in linux!
- result.forEach(function (item) {
- item.cpu = 0;
- });
- let cmd = 'cat /proc/stat | grep "cpu "';
- for (let i in result) {
- for (let j in result[i].pids) {
- cmd += (';cat /proc/' + result[i].pids[j] + '/stat');
- }
- }
- exec(cmd, { maxBuffer: 1024 * 20000 }, function (error, stdout) {
- let curr_processes = stdout.toString().split('\n');
-
- // first line (all - /proc/stat)
- let all = parseProcStat(curr_processes.shift());
-
- // process
- let list_new = {};
- let resultProcess = {};
- curr_processes.forEach((element) => {
- resultProcess = calcProcStatLinux(element, all, _process_cpu);
-
- if (resultProcess.pid) {
-
- // find result item
- let resultItemId = -1;
- for (let i in result) {
- if (result[i].pids.indexOf(resultProcess.pid) >= 0) {
- resultItemId = i;
- }
- }
- // store pcpu in outer result
- if (resultItemId >= 0) {
- result[resultItemId].cpu += resultProcess.cpuu + resultProcess.cpus;
- }
-
- // save new values
- list_new[resultProcess.pid] = {
- cpuu: resultProcess.cpuu,
- cpus: resultProcess.cpus,
- utime: resultProcess.utime,
- stime: resultProcess.stime,
- cutime: resultProcess.cutime,
- cstime: resultProcess.cstime
- };
- }
- });
-
- result.forEach(function (item) {
- item.cpu = Math.round(item.cpu * 100) / 100;
- });
-
- _process_cpu.all = all;
- _process_cpu.list = Object.assign({}, list_new);
- _process_cpu.ms = Date.now() - _process_cpu.ms;
- _process_cpu.result = Object.assign({}, result);
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- }
- }
- });
- });
-}
-
-exports.processLoad = processLoad;
-
-
-/***/ }),
-
-/***/ 50936:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// system.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 2. System (Hardware, BIOS, Base Board)
-// ----------------------------------------------------------------------------------
-
-const fs = __nccwpck_require__(79896);
-const os = __nccwpck_require__(70857);
-const util = __nccwpck_require__(33225);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const execPromise = util.promisify((__nccwpck_require__(35317).exec));
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-function system(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- manufacturer: '',
- model: 'Computer',
- version: '',
- serial: '-',
- uuid: '-',
- sku: '-',
- virtual: false
- };
-
- if (_linux || _freebsd || _openbsd || _netbsd) {
- exec('export LC_ALL=C; dmidecode -t system 2>/dev/null; unset LC_ALL', function (error, stdout) {
- let lines = stdout.toString().split('\n');
- result.manufacturer = util.getValue(lines, 'manufacturer');
- result.model = util.getValue(lines, 'product name');
- result.version = cleanDefaults(util.getValue(lines, 'version'));
- result.serial = cleanDefaults(util.getValue(lines, 'serial number'));
- result.uuid = cleanDefaults((util.getValue(lines, 'uuid').toLowerCase()));
- result.sku = cleanDefaults(util.getValue(lines, 'sku number'));
- // Non-Root values
- const cmd = `echo -n "product_name: "; cat /sys/devices/virtual/dmi/id/product_name 2>/dev/null; echo;
- echo -n "product_serial: "; cat /sys/devices/virtual/dmi/id/product_serial 2>/dev/null; echo;
- echo -n "product_uuid: "; cat /sys/devices/virtual/dmi/id/product_uuid 2>/dev/null; echo;
- echo -n "product_version: "; cat /sys/devices/virtual/dmi/id/product_version 2>/dev/null; echo;
- echo -n "sys_vendor: "; cat /sys/devices/virtual/dmi/id/sys_vendor 2>/dev/null; echo;`;
- try {
- lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- result.manufacturer = result.manufacturer === '' ? util.getValue(lines, 'sys_vendor') : result.manufacturer;
- result.model = result.model === '' ? util.getValue(lines, 'product_name') : result.model;
- result.version = cleanDefaults(result.version === '' ? util.getValue(lines, 'product_version') : result.version);
- result.serial = cleanDefaults(result.serial === '' ? util.getValue(lines, 'product_serial') : result.serial);
- result.uuid = cleanDefaults(result.uuid === '' ? util.getValue(lines, 'product_uuid').toLowerCase() : result.uuid);
- } catch (e) {
- util.noop();
- }
- if (!result.serial) { result.serial = '-'; }
- if (!result.manufacturer) { result.manufacturer = ''; }
- if (!result.model) { result.model = 'Computer'; }
- if (!result.version) { result.version = ''; }
- if (!result.sku) { result.sku = '-'; }
-
- // detect virtual (1)
- if (result.model.toLowerCase() === 'virtualbox' || result.model.toLowerCase() === 'kvm' || result.model.toLowerCase() === 'virtual machine' || result.model.toLowerCase() === 'bochs' || result.model.toLowerCase().startsWith('vmware') || result.model.toLowerCase().startsWith('droplet')) {
- result.virtual = true;
- switch (result.model.toLowerCase()) {
- case 'virtualbox':
- result.virtualHost = 'VirtualBox';
- break;
- case 'vmware':
- result.virtualHost = 'VMware';
- break;
- case 'kvm':
- result.virtualHost = 'KVM';
- break;
- case 'bochs':
- result.virtualHost = 'bochs';
- break;
- }
- }
- if (result.manufacturer.toLowerCase().startsWith('vmware') || result.manufacturer.toLowerCase() === 'xen') {
- result.virtual = true;
- switch (result.manufacturer.toLowerCase()) {
- case 'vmware':
- result.virtualHost = 'VMware';
- break;
- case 'xen':
- result.virtualHost = 'Xen';
- break;
- }
- }
- if (!result.virtual) {
- try {
- const disksById = execSync('ls -1 /dev/disk/by-id/ 2>/dev/null', util.execOptsLinux).toString();
- if (disksById.indexOf('_QEMU_') >= 0) {
- result.virtual = true;
- result.virtualHost = 'QEMU';
- }
- if (disksById.indexOf('_VBOX_') >= 0) {
- result.virtual = true;
- result.virtualHost = 'VirtualBox';
- }
- } catch (e) {
- util.noop();
- }
- }
- if (!result.virtual && (os.release().toLowerCase().indexOf('microsoft') >= 0 || os.release().toLowerCase().endsWith('wsl2'))) {
- const kernelVersion = parseFloat(os.release().toLowerCase());
- result.virtual = true;
- result.manufacturer = 'Microsoft';
- result.model = 'WSL';
- result.version = kernelVersion < 4.19 ? '1' : '2';
- }
- if ((_freebsd || _openbsd || _netbsd) && !result.virtualHost) {
- try {
- const procInfo = execSync('dmidecode -t 4', util.execOptsLinux);
- const procLines = procInfo.toString().split('\n');
- const procManufacturer = util.getValue(procLines, 'manufacturer', ':', true);
- switch (procManufacturer.toLowerCase()) {
- case 'virtualbox':
- result.virtualHost = 'VirtualBox';
- break;
- case 'vmware':
- result.virtualHost = 'VMware';
- break;
- case 'kvm':
- result.virtualHost = 'KVM';
- break;
- case 'bochs':
- result.virtualHost = 'bochs';
- break;
- }
- } catch (e) {
- util.noop();
- }
- }
- // detect docker
- if (fs.existsSync('/.dockerenv') || fs.existsSync('/.dockerinit')) {
- result.model = 'Docker Container';
- }
- try {
- const stdout = execSync('dmesg 2>/dev/null | grep -iE "virtual|hypervisor" | grep -iE "vmware|qemu|kvm|xen" | grep -viE "Nested Virtualization|/virtual/"');
- // detect virtual machines
- let lines = stdout.toString().split('\n');
- if (lines.length > 0) {
- if (result.model === 'Computer') { result.model = 'Virtual machine'; }
- result.virtual = true;
- if (stdout.toString().toLowerCase().indexOf('vmware') >= 0 && !result.virtualHost) {
- result.virtualHost = 'VMware';
- }
- if (stdout.toString().toLowerCase().indexOf('qemu') >= 0 && !result.virtualHost) {
- result.virtualHost = 'QEMU';
- }
- if (stdout.toString().toLowerCase().indexOf('xen') >= 0 && !result.virtualHost) {
- result.virtualHost = 'Xen';
- }
- if (stdout.toString().toLowerCase().indexOf('kvm') >= 0 && !result.virtualHost) {
- result.virtualHost = 'KVM';
- }
- }
- } catch (e) {
- util.noop();
- }
-
- if (result.manufacturer === '' && result.model === 'Computer' && result.version === '') {
- // Check Raspberry Pi
- fs.readFile('/proc/cpuinfo', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().split('\n');
- result.model = util.getValue(lines, 'hardware', ':', true).toUpperCase();
- result.version = util.getValue(lines, 'revision', ':', true).toLowerCase();
- result.serial = util.getValue(lines, 'serial', ':', true);
- const model = util.getValue(lines, 'model:', ':', true);
- // reference values: https://elinux.org/RPi_HardwareHistory
- // https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
- if ((result.model === 'BCM2835' || result.model === 'BCM2708' || result.model === 'BCM2709' || result.model === 'BCM2710' || result.model === 'BCM2711' || result.model === 'BCM2836' || result.model === 'BCM2837') && model.toLowerCase().indexOf('raspberry') >= 0) {
- const rPIRevision = util.decodePiCpuinfo(lines);
- result.model = rPIRevision.model;
- result.version = rPIRevision.revisionCode;
- result.manufacturer = 'Raspberry Pi Foundation';
- result.raspberry = {
- manufacturer: rPIRevision.manufacturer,
- processor: rPIRevision.processor,
- type: rPIRevision.type,
- revision: rPIRevision.revision
- };
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- }
- if (_darwin) {
- exec('ioreg -c IOPlatformExpertDevice -d 2', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().replace(/[<>"]/g, '').split('\n');
-
- const model = util.getAppleModel(util.getValue(lines, 'model', '=', true));
- // const modelParts = util.splitByNumber(model);
- // const version = util.getValue(lines, 'version', '=', true);
- result.manufacturer = util.getValue(lines, 'manufacturer', '=', true);
- result.model = model.key;
- result.type = macOsChassisType(model.model);
- result.version = model.version;
- result.serial = util.getValue(lines, 'ioplatformserialnumber', '=', true);
- result.uuid = util.getValue(lines, 'ioplatformuuid', '=', true).toLowerCase();
- result.sku = util.getValue(lines, 'board-id', '=', true) || util.getValue(lines, 'target-sub-type', '=', true);
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- util.powerShell('Get-CimInstance Win32_ComputerSystemProduct | select Name,Vendor,Version,IdentifyingNumber,UUID | fl').then((stdout, error) => {
- if (!error) {
- let lines = stdout.split('\r\n');
- result.manufacturer = util.getValue(lines, 'vendor', ':');
- result.model = util.getValue(lines, 'name', ':');
- result.version = util.getValue(lines, 'version', ':');
- result.serial = util.getValue(lines, 'identifyingnumber', ':');
- result.uuid = util.getValue(lines, 'uuid', ':').toLowerCase();
- // detect virtual (1)
- const model = result.model.toLowerCase();
- if (model === 'virtualbox' || model === 'kvm' || model === 'virtual machine' || model === 'bochs' || model.startsWith('vmware') || model.startsWith('qemu') || model.startsWith('parallels')) {
- result.virtual = true;
- if (model.startsWith('virtualbox')) { result.virtualHost = 'VirtualBox'; }
- if (model.startsWith('vmware')) { result.virtualHost = 'VMware'; }
- if (model.startsWith('kvm')) { result.virtualHost = 'KVM'; }
- if (model.startsWith('bochs')) { result.virtualHost = 'bochs'; }
- if (model.startsWith('qemu')) { result.virtualHost = 'KVM'; }
- if (model.startsWith('parallels')) { result.virtualHost = 'Parallels'; }
- }
- const manufacturer = result.manufacturer.toLowerCase();
- if (manufacturer.startsWith('vmware') || manufacturer.startsWith('qemu') || manufacturer === 'xen' || manufacturer.startsWith('parallels')) {
- result.virtual = true;
- if (manufacturer.startsWith('vmware')) { result.virtualHost = 'VMware'; }
- if (manufacturer.startsWith('xen')) { result.virtualHost = 'Xen'; }
- if (manufacturer.startsWith('qemu')) { result.virtualHost = 'KVM'; }
- if (manufacturer.startsWith('parallels')) { result.virtualHost = 'Parallels'; }
- }
- util.powerShell('Get-CimInstance MS_Systeminformation -Namespace "root/wmi" | select systemsku | fl ').then((stdout, error) => {
- if (!error) {
- let lines = stdout.split('\r\n');
- result.sku = util.getValue(lines, 'systemsku', ':');
- }
- if (!result.virtual) {
- util.powerShell('Get-CimInstance Win32_bios | select Version, SerialNumber, SMBIOSBIOSVersion').then((stdout, error) => {
- if (!error) {
- let lines = stdout.toString();
- if (lines.indexOf('VRTUAL') >= 0 || lines.indexOf('A M I ') >= 0 || lines.indexOf('VirtualBox') >= 0 || lines.indexOf('VMWare') >= 0 || lines.indexOf('Xen') >= 0 || lines.indexOf('Parallels') >= 0) {
- result.virtual = true;
- if (lines.indexOf('VirtualBox') >= 0 && !result.virtualHost) {
- result.virtualHost = 'VirtualBox';
- }
- if (lines.indexOf('VMware') >= 0 && !result.virtualHost) {
- result.virtualHost = 'VMware';
- }
- if (lines.indexOf('Xen') >= 0 && !result.virtualHost) {
- result.virtualHost = 'Xen';
- }
- if (lines.indexOf('VRTUAL') >= 0 && !result.virtualHost) {
- result.virtualHost = 'Hyper-V';
- }
- if (lines.indexOf('A M I') >= 0 && !result.virtualHost) {
- result.virtualHost = 'Virtual PC';
- }
- if (lines.indexOf('Parallels') >= 0 && !result.virtualHost) {
- result.virtualHost = 'Parallels';
- }
- }
- if (callback) { callback(result); }
- resolve(result);
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.system = system;
-
-function cleanDefaults(s) {
- const cmpStr = s.toLowerCase();
- if (cmpStr.indexOf('o.e.m.') === -1 && cmpStr.indexOf('default string') === -1 && cmpStr !== 'default') {
- return s || '';
- }
- return '';
-}
-function bios(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- vendor: '',
- version: '',
- releaseDate: '',
- revision: '',
- };
- let cmd = '';
- if (_linux || _freebsd || _openbsd || _netbsd) {
- if (process.arch === 'arm') {
- cmd = 'cat /proc/cpuinfo | grep Serial';
- } else {
- cmd = 'export LC_ALL=C; dmidecode -t bios 2>/dev/null; unset LC_ALL';
- }
- exec(cmd, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- result.vendor = util.getValue(lines, 'Vendor');
- result.version = util.getValue(lines, 'Version');
- let datetime = util.getValue(lines, 'Release Date');
- result.releaseDate = util.parseDateTime(datetime).date;
- result.revision = util.getValue(lines, 'BIOS Revision');
- result.serial = util.getValue(lines, 'SerialNumber');
- let language = util.getValue(lines, 'Currently Installed Language').split('|')[0];
- if (language) {
- result.language = language;
- }
- if (lines.length && stdout.toString().indexOf('Characteristics:') >= 0) {
- const features = [];
- lines.forEach(line => {
- if (line.indexOf(' is supported') >= 0) {
- const feature = line.split(' is supported')[0].trim();
- features.push(feature);
- }
- });
- result.features = features;
- }
- // Non-Root values
- const cmd = `echo -n "bios_date: "; cat /sys/devices/virtual/dmi/id/bios_date 2>/dev/null; echo;
- echo -n "bios_vendor: "; cat /sys/devices/virtual/dmi/id/bios_vendor 2>/dev/null; echo;
- echo -n "bios_version: "; cat /sys/devices/virtual/dmi/id/bios_version 2>/dev/null; echo;`;
- try {
- lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- result.vendor = !result.vendor ? util.getValue(lines, 'bios_vendor') : result.vendor;
- result.version = !result.version ? util.getValue(lines, 'bios_version') : result.version;
- datetime = util.getValue(lines, 'bios_date');
- result.releaseDate = !result.releaseDate ? util.parseDateTime(datetime).date : result.releaseDate;
- } catch (e) {
- util.noop();
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- result.vendor = 'Apple Inc.';
- exec(
- 'system_profiler SPHardwareDataType -json', function (error, stdout) {
- try {
- const hardwareData = JSON.parse(stdout.toString());
- if (hardwareData && hardwareData.SPHardwareDataType && hardwareData.SPHardwareDataType.length) {
- let bootRomVersion = hardwareData.SPHardwareDataType[0].boot_rom_version;
- bootRomVersion = bootRomVersion ? bootRomVersion.split('(')[0].trim() : null;
- result.version = bootRomVersion;
- }
- } catch (e) {
- util.noop();
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- result.vendor = 'Sun Microsystems';
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- util.powerShell('Get-CimInstance Win32_bios | select Description,Version,Manufacturer,@{n="ReleaseDate";e={$_.ReleaseDate.ToString("yyyy-MM-dd")}},BuildNumber,SerialNumber,SMBIOSBIOSVersion | fl').then((stdout, error) => {
- if (!error) {
- let lines = stdout.toString().split('\r\n');
- const description = util.getValue(lines, 'description', ':');
- const version = util.getValue(lines, 'SMBIOSBIOSVersion', ':');
- if (description.indexOf(' Version ') !== -1) {
- // ... Phoenix ROM BIOS PLUS Version 1.10 A04
- result.vendor = description.split(' Version ')[0].trim();
- result.version = description.split(' Version ')[1].trim();
- } else if (description.indexOf(' Ver: ') !== -1) {
- // ... BIOS Date: 06/27/16 17:50:16 Ver: 1.4.5
- result.vendor = util.getValue(lines, 'manufacturer', ':');
- result.version = description.split(' Ver: ')[1].trim();
- } else {
- result.vendor = util.getValue(lines, 'manufacturer', ':');
- result.version = version || util.getValue(lines, 'version', ':');
- }
- result.releaseDate = util.getValue(lines, 'releasedate', ':');
- result.revision = util.getValue(lines, 'buildnumber', ':');
- result.serial = cleanDefaults(util.getValue(lines, 'serialnumber', ':'));
- }
-
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.bios = bios;
-
-function baseboard(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- manufacturer: '',
- model: '',
- version: '',
- serial: '-',
- assetTag: '-',
- memMax: null,
- memSlots: null
- };
- let cmd = '';
- if (_linux || _freebsd || _openbsd || _netbsd) {
- if (process.arch === 'arm') {
- cmd = 'cat /proc/cpuinfo | grep Serial';
- // 'BCM2709', 'BCM2835', 'BCM2708' -->
- } else {
- cmd = 'export LC_ALL=C; dmidecode -t 2 2>/dev/null; unset LC_ALL';
- }
- const workload = [];
- workload.push(execPromise(cmd));
- workload.push(execPromise('export LC_ALL=C; dmidecode -t memory 2>/dev/null'));
- util.promiseAll(
- workload
- ).then((data) => {
- let lines = data.results[0] ? data.results[0].toString().split('\n') : [''];
- result.manufacturer = cleanDefaults(util.getValue(lines, 'Manufacturer'));
- result.model = cleanDefaults(util.getValue(lines, 'Product Name'));
- result.version = cleanDefaults(util.getValue(lines, 'Version'));
- result.serial = cleanDefaults(util.getValue(lines, 'Serial Number'));
- result.assetTag = cleanDefaults(util.getValue(lines, 'Asset Tag'));
- // Non-Root values
- const cmd = `echo -n "board_asset_tag: "; cat /sys/devices/virtual/dmi/id/board_asset_tag 2>/dev/null; echo;
- echo -n "board_name: "; cat /sys/devices/virtual/dmi/id/board_name 2>/dev/null; echo;
- echo -n "board_serial: "; cat /sys/devices/virtual/dmi/id/board_serial 2>/dev/null; echo;
- echo -n "board_vendor: "; cat /sys/devices/virtual/dmi/id/board_vendor 2>/dev/null; echo;
- echo -n "board_version: "; cat /sys/devices/virtual/dmi/id/board_version 2>/dev/null; echo;`;
- try {
- lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- result.manufacturer = cleanDefaults(!result.manufacturer ? util.getValue(lines, 'board_vendor') : result.manufacturer);
- result.model = cleanDefaults(!result.model ? util.getValue(lines, 'board_name') : result.model);
- result.version = cleanDefaults(!result.version ? util.getValue(lines, 'board_version') : result.version);
- result.serial = cleanDefaults(!result.serial ? util.getValue(lines, 'board_serial') : result.serial);
- result.assetTag = cleanDefaults(!result.assetTag ? util.getValue(lines, 'board_asset_tag') : result.assetTag);
- } catch (e) {
- util.noop();
- }
-
- // mem
- lines = data.results[1] ? data.results[1].toString().split('\n') : [''];
- result.memMax = util.toInt(util.getValue(lines, 'Maximum Capacity')) * 1024 * 1024 * 1024 || null;
- result.memSlots = util.toInt(util.getValue(lines, 'Number Of Devices')) || null;
-
- // raspberry
- let linesRpi = '';
- try {
- linesRpi = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
- } catch (e) {
- util.noop();
- }
- if (linesRpi) {
- const hardware = util.getValue(linesRpi, 'hardware');
- if (hardware.startsWith('BCM')) {
- const rpi = util.decodePiCpuinfo(linesRpi);
- result.manufacturer = rpi.manufacturer;
- result.model = 'Raspberry Pi';
- result.serial = rpi.serial;
- result.version = rpi.type + ' - ' + rpi.revision;
- result.memMax = os.totalmem();
- result.memSlots = 0;
- }
- }
-
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- const workload = [];
- workload.push(execPromise('ioreg -c IOPlatformExpertDevice -d 2'));
- workload.push(execPromise('system_profiler SPMemoryDataType'));
- util.promiseAll(
- workload
- ).then((data) => {
- let lines = data.results[0] ? data.results[0].toString().replace(/[<>"]/g, '').split('\n') : [''];
- result.manufacturer = util.getValue(lines, 'manufacturer', '=', true);
- result.model = util.getValue(lines, 'model', '=', true);
- result.version = util.getValue(lines, 'version', '=', true);
- result.serial = util.getValue(lines, 'ioplatformserialnumber', '=', true);
- result.assetTag = util.getValue(lines, 'board-id', '=', true);
-
- // mem
- let devices = data.results[1] ? data.results[1].toString().split(' BANK ') : [''];
- if (devices.length === 1) {
- devices = data.results[1] ? data.results[1].toString().split(' DIMM') : [''];
- }
- devices.shift();
- result.memSlots = devices.length;
-
- if (os.arch() === 'arm64') {
- result.memSlots = 0;
- result.memMax = os.totalmem();
- }
-
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- const workload = [];
- const win10plus = parseInt(os.release()) >= 10;
- const maxCapacityAttribute = win10plus ? 'MaxCapacityEx' : 'MaxCapacity';
- workload.push(util.powerShell('Get-CimInstance Win32_baseboard | select Model,Manufacturer,Product,Version,SerialNumber,PartNumber,SKU | fl'));
- workload.push(util.powerShell(`Get-CimInstance Win32_physicalmemoryarray | select ${maxCapacityAttribute}, MemoryDevices | fl`));
- util.promiseAll(
- workload
- ).then((data) => {
- let lines = data.results[0] ? data.results[0].toString().split('\r\n') : [''];
-
- result.manufacturer = cleanDefaults(util.getValue(lines, 'manufacturer', ':'));
- result.model = cleanDefaults(util.getValue(lines, 'model', ':'));
- if (!result.model) {
- result.model = cleanDefaults(util.getValue(lines, 'product', ':'));
- }
- result.version = cleanDefaults(util.getValue(lines, 'version', ':'));
- result.serial = cleanDefaults(util.getValue(lines, 'serialnumber', ':'));
- result.assetTag = cleanDefaults(util.getValue(lines, 'partnumber', ':'));
- if (!result.assetTag) {
- result.assetTag = cleanDefaults(util.getValue(lines, 'sku', ':'));
- }
-
- // memphysical
- lines = data.results[1] ? data.results[1].toString().split('\r\n') : [''];
- result.memMax = util.toInt(util.getValue(lines, maxCapacityAttribute, ':')) * (win10plus ? 1024 : 1) || null;
- result.memSlots = util.toInt(util.getValue(lines, 'MemoryDevices', ':')) || null;
-
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.baseboard = baseboard;
-
-function macOsChassisType(model) {
- model = model.toLowerCase();
- if (model.startsWith('macbookair')) { return 'Notebook'; }
- if (model.startsWith('macbookpro')) { return 'Laptop'; }
- if (model.startsWith('macbook')) { return 'Notebook'; }
- if (model.startsWith('macmini')) { return 'Desktop'; }
- if (model.startsWith('imac')) { return 'Desktop'; }
- if (model.startsWith('macstudio')) { return 'Desktop'; }
- if (model.startsWith('macpro')) { return 'Tower'; }
- return 'Other';
-}
-
-function chassis(callback) {
- const chassisTypes = ['Other',
- 'Unknown',
- 'Desktop',
- 'Low Profile Desktop',
- 'Pizza Box',
- 'Mini Tower',
- 'Tower',
- 'Portable',
- 'Laptop',
- 'Notebook',
- 'Hand Held',
- 'Docking Station',
- 'All in One',
- 'Sub Notebook',
- 'Space-Saving',
- 'Lunch Box',
- 'Main System Chassis',
- 'Expansion Chassis',
- 'SubChassis',
- 'Bus Expansion Chassis',
- 'Peripheral Chassis',
- 'Storage Chassis',
- 'Rack Mount Chassis',
- 'Sealed-Case PC',
- 'Multi-System Chassis',
- 'Compact PCI',
- 'Advanced TCA',
- 'Blade',
- 'Blade Enclosure',
- 'Tablet',
- 'Convertible',
- 'Detachable',
- 'IoT Gateway ',
- 'Embedded PC',
- 'Mini PC',
- 'Stick PC',
- ];
-
- return new Promise((resolve) => {
- process.nextTick(() => {
-
- let result = {
- manufacturer: '',
- model: '',
- type: '',
- version: '',
- serial: '-',
- assetTag: '-',
- sku: '',
- };
- if (_linux || _freebsd || _openbsd || _netbsd) {
- const cmd = `echo -n "chassis_asset_tag: "; cat /sys/devices/virtual/dmi/id/chassis_asset_tag 2>/dev/null; echo;
- echo -n "chassis_serial: "; cat /sys/devices/virtual/dmi/id/chassis_serial 2>/dev/null; echo;
- echo -n "chassis_type: "; cat /sys/devices/virtual/dmi/id/chassis_type 2>/dev/null; echo;
- echo -n "chassis_vendor: "; cat /sys/devices/virtual/dmi/id/chassis_vendor 2>/dev/null; echo;
- echo -n "chassis_version: "; cat /sys/devices/virtual/dmi/id/chassis_version 2>/dev/null; echo;`;
- exec(cmd, function (error, stdout) {
- let lines = stdout.toString().split('\n');
- result.manufacturer = cleanDefaults(util.getValue(lines, 'chassis_vendor'));
- const ctype = parseInt(util.getValue(lines, 'chassis_type').replace(/\D/g, ''));
- result.type = cleanDefaults((ctype && !isNaN(ctype) && ctype < chassisTypes.length) ? chassisTypes[ctype - 1] : '');
- result.version = cleanDefaults(util.getValue(lines, 'chassis_version'));
- result.serial = cleanDefaults(util.getValue(lines, 'chassis_serial'));
- result.assetTag = cleanDefaults(util.getValue(lines, 'chassis_asset_tag'));
-
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_darwin) {
- exec('ioreg -c IOPlatformExpertDevice -d 2', function (error, stdout) {
- if (!error) {
- let lines = stdout.toString().replace(/[<>"]/g, '').split('\n');
- const model = util.getAppleModel(util.getValue(lines, 'model', '=', true));
- // const modelParts = util.splitByNumber(model);
- // const version = util.getValue(lines, 'version', '=', true);
- result.manufacturer = util.getValue(lines, 'manufacturer', '=', true);
- result.model = model.key;
- result.type = macOsChassisType(model.model);
- result.version = model.version;
- result.serial = util.getValue(lines, 'ioplatformserialnumber', '=', true);
- result.assetTag = util.getValue(lines, 'board-id', '=', true) || util.getValue(lines, 'target-type', '=', true);
- result.sku = util.getValue(lines, 'target-sub-type', '=', true);
- }
-
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- if (callback) { callback(result); }
- resolve(result);
- }
- if (_windows) {
- try {
- util.powerShell('Get-CimInstance Win32_SystemEnclosure | select Model,Manufacturer,ChassisTypes,Version,SerialNumber,PartNumber,SKU,SMBIOSAssetTag | fl').then((stdout, error) => {
- if (!error) {
- let lines = stdout.toString().split('\r\n');
-
- result.manufacturer = cleanDefaults(util.getValue(lines, 'manufacturer', ':'));
- result.model = cleanDefaults(util.getValue(lines, 'model', ':'));
- const ctype = parseInt(util.getValue(lines, 'ChassisTypes', ':').replace(/\D/g, ''));
- result.type = (ctype && !isNaN(ctype) && ctype < chassisTypes.length) ? chassisTypes[ctype - 1] : '';
- result.version = cleanDefaults(util.getValue(lines, 'version', ':'));
- result.serial = cleanDefaults(util.getValue(lines, 'serialnumber', ':'));
- result.assetTag = cleanDefaults(util.getValue(lines, 'partnumber', ':'));
- if (!result.assetTag) {
- result.assetTag = cleanDefaults(util.getValue(lines, 'SMBIOSAssetTag', ':'));
- }
- result.sku = cleanDefaults(util.getValue(lines, 'sku', ':'));
- }
-
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-exports.chassis = chassis;
-
-
-/***/ }),
-
-/***/ 66223:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// usb.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 16. usb
-// ----------------------------------------------------------------------------------
-
-const exec = (__nccwpck_require__(35317).exec);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-function getLinuxUsbType(type, name) {
- let result = type;
- const str = (name + ' ' + type).toLowerCase();
- if (str.indexOf('camera') >= 0) { result = 'Camera'; }
- else if (str.indexOf('hub') >= 0) { result = 'Hub'; }
- else if (str.indexOf('keybrd') >= 0) { result = 'Keyboard'; }
- else if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
- else if (str.indexOf('mouse') >= 0) { result = 'Mouse'; }
- else if (str.indexOf('stora') >= 0) { result = 'Storage'; }
- else if (str.indexOf('microp') >= 0) { result = 'Microphone'; }
- else if (str.indexOf('headset') >= 0) { result = 'Audio'; }
- else if (str.indexOf('audio') >= 0) { result = 'Audio'; }
-
- return result;
-}
-
-function parseLinuxUsb(usb) {
- const result = {};
- const lines = usb.split('\n');
- if (lines && lines.length && lines[0].indexOf('Device') >= 0) {
- const parts = lines[0].split(' ');
- result.bus = parseInt(parts[0], 10);
- if (parts[2]) {
- result.deviceId = parseInt(parts[2], 10);
- } else {
- result.deviceId = null;
- }
- } else {
- result.bus = null;
- result.deviceId = null;
- }
- const idVendor = util.getValue(lines, 'idVendor', ' ', true).trim();
- let vendorParts = idVendor.split(' ');
- vendorParts.shift();
- const vendor = vendorParts.join(' ');
-
- const idProduct = util.getValue(lines, 'idProduct', ' ', true).trim();
- let productParts = idProduct.split(' ');
- productParts.shift();
- const product = productParts.join(' ');
-
- const interfaceClass = util.getValue(lines, 'bInterfaceClass', ' ', true).trim();
- let interfaceClassParts = interfaceClass.split(' ');
- interfaceClassParts.shift();
- const usbType = interfaceClassParts.join(' ');
-
- const iManufacturer = util.getValue(lines, 'iManufacturer', ' ', true).trim();
- let iManufacturerParts = iManufacturer.split(' ');
- iManufacturerParts.shift();
- const manufacturer = iManufacturerParts.join(' ');
-
- const iSerial = util.getValue(lines, 'iSerial', ' ', true).trim();
- let iSerialParts = iSerial.split(' ');
- iSerialParts.shift();
- const serial = iSerialParts.join(' ');
-
- result.id = (idVendor.startsWith('0x') ? idVendor.split(' ')[0].substr(2, 10) : '') + ':' + (idProduct.startsWith('0x') ? idProduct.split(' ')[0].substr(2, 10) : '');
- result.name = product;
- result.type = getLinuxUsbType(usbType, product);
- result.removable = null;
- result.vendor = vendor;
- result.manufacturer = manufacturer;
- result.maxPower = util.getValue(lines, 'MaxPower', ' ', true);
- result.serialNumber = serial;
-
- return result;
-}
-
-function getDarwinUsbType(name) {
- let result = '';
- if (name.indexOf('camera') >= 0) { result = 'Camera'; }
- else if (name.indexOf('touch bar') >= 0) { result = 'Touch Bar'; }
- else if (name.indexOf('controller') >= 0) { result = 'Controller'; }
- else if (name.indexOf('headset') >= 0) { result = 'Audio'; }
- else if (name.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
- else if (name.indexOf('trackpad') >= 0) { result = 'Trackpad'; }
- else if (name.indexOf('sensor') >= 0) { result = 'Sensor'; }
- else if (name.indexOf('bthusb') >= 0) { result = 'Bluetooth'; }
- else if (name.indexOf('bth') >= 0) { result = 'Bluetooth'; }
- else if (name.indexOf('rfcomm') >= 0) { result = 'Bluetooth'; }
- else if (name.indexOf('usbhub') >= 0) { result = 'Hub'; }
- else if (name.indexOf(' hub') >= 0) { result = 'Hub'; }
- else if (name.indexOf('mouse') >= 0) { result = 'Mouse'; }
- else if (name.indexOf('microp') >= 0) { result = 'Microphone'; }
- else if (name.indexOf('removable') >= 0) { result = 'Storage'; }
- return result;
-}
-
-function parseDarwinUsb(usb, id) {
- const result = {};
- result.id = id;
-
- usb = usb.replace(/ \|/g, '');
- usb = usb.trim();
- let lines = usb.split('\n');
- lines.shift();
- try {
- for (let i = 0; i < lines.length; i++) {
- lines[i] = lines[i].trim();
- lines[i] = lines[i].replace(/=/g, ':');
- if (lines[i] !== '{' && lines[i] !== '}' && lines[i + 1] && lines[i + 1].trim() !== '}') {
- lines[i] = lines[i] + ',';
- }
-
- lines[i] = lines[i].replace(':Yes,', ':"Yes",');
- lines[i] = lines[i].replace(': Yes,', ': "Yes",');
- lines[i] = lines[i].replace(': Yes', ': "Yes"');
- lines[i] = lines[i].replace(':No,', ':"No",');
- lines[i] = lines[i].replace(': No,', ': "No",');
- lines[i] = lines[i].replace(': No', ': "No"');
-
- // In this case (("com.apple.developer.driverkit.transport.usb"))
- lines[i] = lines[i].replace('((', '').replace('))', '');
-
- // In case we have <923c11> we need make it "<923c11>" for correct JSON parse
- const match = /<(\w+)>/.exec(lines[i]);
- if (match) {
- const number = match[0];
- lines[i] = lines[i].replace(number, `"${number}"`);
- }
- }
- const usbObj = JSON.parse(lines.join('\n'));
- const removableDrive = (usbObj['Built-In'] ? usbObj['Built-In'].toLowerCase() !== 'yes' : true) && (usbObj['non-removable'] ? usbObj['non-removable'].toLowerCase() === 'no' : true);
-
- result.bus = null;
- result.deviceId = null;
- result.id = usbObj['USB Address'] || null;
- result.name = usbObj['kUSBProductString'] || usbObj['USB Product Name'] || null;
- result.type = getDarwinUsbType((usbObj['kUSBProductString'] || usbObj['USB Product Name'] || '').toLowerCase() + (removableDrive ? ' removable' : ''));
- result.removable = usbObj['non-removable'] ? usbObj['non-removable'].toLowerCase() || '' === 'no' : true;
- result.vendor = usbObj['kUSBVendorString'] || usbObj['USB Vendor Name'] || null;
- result.manufacturer = usbObj['kUSBVendorString'] || usbObj['USB Vendor Name'] || null;
-
- result.maxPower = null;
- result.serialNumber = usbObj['kUSBSerialNumberString'] || null;
-
- if (result.name) {
- return result;
- } else {
- return null;
- }
- } catch (e) {
- return null;
- }
-}
-
-function getWindowsUsbTypeCreation(creationclass, name) {
- let result = '';
- if (name.indexOf('storage') >= 0) { result = 'Storage'; }
- else if (name.indexOf('speicher') >= 0) { result = 'Storage'; }
- else if (creationclass.indexOf('usbhub') >= 0) { result = 'Hub'; }
- else if (creationclass.indexOf('storage') >= 0) { result = 'Storage'; }
- else if (creationclass.indexOf('usbcontroller') >= 0) { result = 'Controller'; }
- else if (creationclass.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
- else if (creationclass.indexOf('pointing') >= 0) { result = 'Mouse'; }
- else if (creationclass.indexOf('microp') >= 0) { result = 'Microphone'; }
- else if (creationclass.indexOf('disk') >= 0) { result = 'Storage'; }
- return result;
-}
-
-function parseWindowsUsb(lines, id) {
- const usbType = getWindowsUsbTypeCreation(util.getValue(lines, 'CreationClassName', ':').toLowerCase(), util.getValue(lines, 'name', ':').toLowerCase());
-
- if (usbType) {
- const result = {};
- result.bus = null;
- result.deviceId = util.getValue(lines, 'deviceid', ':');
- result.id = id;
- result.name = util.getValue(lines, 'name', ':');
- result.type = usbType;
- result.removable = null;
- result.vendor = null;
- result.manufacturer = util.getValue(lines, 'Manufacturer', ':');
- result.maxPower = null;
- result.serialNumber = null;
-
- return result;
- } else {
- return null;
- }
-}
-
-function usb(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux) {
- const cmd = 'export LC_ALL=C; lsusb -v 2>/dev/null; unset LC_ALL';
- exec(cmd, { maxBuffer: 1024 * 1024 * 128 }, function (error, stdout) {
- if (!error) {
- const parts = ('\n\n' + stdout.toString()).split('\n\nBus ');
- for (let i = 1; i < parts.length; i++) {
- const usb = parseLinuxUsb(parts[i]);
- result.push(usb);
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_darwin) {
- let cmd = 'ioreg -p IOUSB -c AppleUSBRootHubDevice -w0 -l';
- exec(cmd, { maxBuffer: 1024 * 1024 * 128 }, function (error, stdout) {
- if (!error) {
- const parts = (stdout.toString()).split(' +-o ');
- for (let i = 1; i < parts.length; i++) {
- const usb = parseDarwinUsb(parts[i]);
- if (usb) {
- result.push(usb);
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_windows) {
- util.powerShell('Get-CimInstance CIM_LogicalDevice | where { $_.Description -match "USB"} | select Name,CreationClassName,DeviceId,Manufacturer | fl').then((stdout, error) => {
- if (!error) {
- const parts = stdout.toString().split(/\n\s*\n/);
- for (let i = 0; i < parts.length; i++) {
- const usb = parseWindowsUsb(parts[i].split('\n'), i);
- if (usb && result.filter(x => x.deviceId === usb.deviceId).length === 0) {
- result.push(usb);
- }
- }
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- }
- if (_sunos || _freebsd || _openbsd || _netbsd) {
- resolve(null);
- }
- });
- });
-}
-
-exports.usb = usb;
-
-
-
-/***/ }),
-
-/***/ 93069:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// users.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 11. Users/Sessions
-// ----------------------------------------------------------------------------------
-
-const exec = (__nccwpck_require__(35317).exec);
-const util = __nccwpck_require__(33225);
-
-let _platform = process.platform;
-
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-const _sunos = (_platform === 'sunos');
-
-function parseUsersLinux(lines, phase) {
- let result = [];
- let result_who = [];
- let result_w = {};
- let w_first = true;
- let w_header = [];
- let w_pos = [];
- let who_line = {};
-
- let is_whopart = true;
- lines.forEach(function (line) {
- if (line === '---') {
- is_whopart = false;
- } else {
- let l = line.replace(/ +/g, ' ').split(' ');
-
- // who part
- if (is_whopart) {
- result_who.push({
- user: l[0],
- tty: l[1],
- date: l[2],
- time: l[3],
- ip: (l && l.length > 4) ? l[4].replace(/\(/g, '').replace(/\)/g, '') : ''
- });
- } else {
- // w part
- if (w_first) { // header
- w_header = l;
- w_header.forEach(function (item) {
- w_pos.push(line.indexOf(item));
- });
- w_first = false;
- } else {
- // split by w_pos
- result_w.user = line.substring(w_pos[0], w_pos[1] - 1).trim();
- result_w.tty = line.substring(w_pos[1], w_pos[2] - 1).trim();
- result_w.ip = line.substring(w_pos[2], w_pos[3] - 1).replace(/\(/g, '').replace(/\)/g, '').trim();
- result_w.command = line.substring(w_pos[7], 1000).trim();
- // find corresponding 'who' line
- who_line = result_who.filter(function (obj) {
- return (obj.user.substring(0, 8).trim() === result_w.user && obj.tty === result_w.tty);
- });
- if (who_line.length === 1) {
- result.push({
- user: who_line[0].user,
- tty: who_line[0].tty,
- date: who_line[0].date,
- time: who_line[0].time,
- ip: who_line[0].ip,
- command: result_w.command
- });
- }
- }
- }
- }
- });
- if (result.length === 0 && phase === 2) {
- return result_who;
- } else {
- return result;
- }
-}
-
-function parseUsersDarwin(lines) {
- let result = [];
- let result_who = [];
- let result_w = {};
- let who_line = {};
-
- let is_whopart = true;
- lines.forEach(function (line) {
- if (line === '---') {
- is_whopart = false;
- } else {
- let l = line.replace(/ +/g, ' ').split(' ');
-
- // who part
- if (is_whopart) {
- result_who.push({
- user: l[0],
- tty: l[1],
- date: ('' + new Date().getFullYear()) + '-' + ('0' + ('JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'.indexOf(l[2].toUpperCase()) / 3 + 1)).slice(-2) + '-' + ('0' + l[3]).slice(-2),
- time: l[4],
- });
- } else {
- // w part
- // split by w_pos
- result_w.user = l[0];
- result_w.tty = l[1];
- result_w.ip = (l[2] !== '-') ? l[2] : '';
- result_w.command = l.slice(5, 1000).join(' ');
- // find corresponding 'who' line
- who_line = result_who.filter(function (obj) {
- return (obj.user.substring(0, 10) === result_w.user.substring(0, 10) && (obj.tty.substring(3, 1000) === result_w.tty || obj.tty === result_w.tty));
- });
- if (who_line.length === 1) {
- result.push({
- user: who_line[0].user,
- tty: who_line[0].tty,
- date: who_line[0].date,
- time: who_line[0].time,
- ip: result_w.ip,
- command: result_w.command
- });
- }
- }
- }
- });
- return result;
-}
-
-function users(callback) {
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
-
- // linux
- if (_linux) {
- exec('who --ips; echo "---"; w | tail -n +2', function (error, stdout) {
- if (!error) {
- // lines / split
- let lines = stdout.toString().split('\n');
- result = parseUsersLinux(lines, 1);
- if (result.length === 0) {
- exec('who; echo "---"; w | tail -n +2', function (error, stdout) {
- if (!error) {
- // lines / split
- lines = stdout.toString().split('\n');
- result = parseUsersLinux(lines, 2);
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- } else {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- }
- if (_freebsd || _openbsd || _netbsd) {
- exec('who; echo "---"; w -ih', function (error, stdout) {
- if (!error) {
- // lines / split
- let lines = stdout.toString().split('\n');
- result = parseUsersDarwin(lines);
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_sunos) {
- exec('who; echo "---"; w -h', function (error, stdout) {
- if (!error) {
- // lines / split
- let lines = stdout.toString().split('\n');
- result = parseUsersDarwin(lines);
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
-
- if (_darwin) {
- exec('who; echo "---"; w -ih', function (error, stdout) {
- if (!error) {
- // lines / split
- let lines = stdout.toString().split('\n');
- result = parseUsersDarwin(lines);
- }
- if (callback) { callback(result); }
- resolve(result);
- });
- }
- if (_windows) {
- try {
- let cmd = 'Get-CimInstance Win32_LogonSession | select LogonId,@{n="StartTime";e={$_.StartTime.ToString("yyyy-MM-dd HH:mm:ss")}} | fl' + '; echo \'#-#-#-#\';';
- cmd += 'Get-CimInstance Win32_LoggedOnUser | select antecedent,dependent | fl ' + '; echo \'#-#-#-#\';';
- cmd += '$process = (Get-CimInstance Win32_Process -Filter "name = \'explorer.exe\'"); Invoke-CimMethod -InputObject $process[0] -MethodName GetOwner | select user, domain | fl; get-process -name explorer | select-object sessionid | fl; echo \'#-#-#-#\';';
- cmd += 'query user';
- util.powerShell(cmd).then((data) => {
- if (data) {
- data = data.split('#-#-#-#');
- let sessions = parseWinSessions((data[0] || '').split(/\n\s*\n/));
- let loggedons = parseWinLoggedOn((data[1] || '').split(/\n\s*\n/));
- let queryUser = parseWinUsersQuery((data[3] || '').split('\r\n'));
- let users = parseWinUsers((data[2] || '').split(/\n\s*\n/), queryUser);
- for (let id in loggedons) {
- if ({}.hasOwnProperty.call(loggedons, id)) {
- loggedons[id].dateTime = {}.hasOwnProperty.call(sessions, id) ? sessions[id] : '';
- }
- }
- users.forEach(user => {
- let dateTime = '';
- for (let id in loggedons) {
- if ({}.hasOwnProperty.call(loggedons, id)) {
- if (loggedons[id].user === user.user && (!dateTime || dateTime < loggedons[id].dateTime)) {
- dateTime = loggedons[id].dateTime;
- }
- }
- }
-
- result.push({
- user: user.user,
- tty: user.tty,
- date: `${dateTime.substring(0, 10)}`,
- time: `${dateTime.substring(11, 19)}`,
- ip: '',
- command: ''
- });
- });
- }
- if (callback) { callback(result); }
- resolve(result);
-
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- }
- });
- });
-}
-
-function parseWinSessions(sessionParts) {
- const sessions = {};
- sessionParts.forEach(session => {
- const lines = session.split('\r\n');
- const id = util.getValue(lines, 'LogonId');
- const starttime = util.getValue(lines, 'starttime');
- if (id) {
- sessions[id] = starttime;
- }
- });
- return sessions;
-}
-
-function fuzzyMatch(name1, name2) {
- name1 = name1.toLowerCase();
- name2 = name2.toLowerCase();
- let eq = 0;
- let len = name1.length;
- if (name2.length > len) { len = name2.length; }
-
- for (let i = 0; i < len; i++) {
- const c1 = name1[i] || '';
- const c2 = name2[i] || '';
- if (c1 === c2) { eq++; }
- }
- return (len > 10 ? eq / len > 0.9 : (len > 0 ? eq / len > 0.8 : false));
-}
-
-function parseWinUsers(userParts, userQuery) {
- const users = [];
- userParts.forEach(user => {
- const lines = user.split('\r\n');
-
- const domain = util.getValue(lines, 'domain', ':', true);
- const username = util.getValue(lines, 'user', ':', true);
- const sessionid = util.getValue(lines, 'sessionid', ':', true);
-
- if (username) {
- const quser = userQuery.filter(item => fuzzyMatch(item.user, username));
- users.push({
- domain,
- user: username,
- tty: quser && quser[0] && quser[0].tty ? quser[0].tty : sessionid
- });
- }
- });
- return users;
-}
-
-function parseWinLoggedOn(loggedonParts) {
- const loggedons = {};
- loggedonParts.forEach(loggedon => {
- const lines = loggedon.split('\r\n');
-
- const antecendent = util.getValue(lines, 'antecedent', ':', true);
- let parts = antecendent.split('=');
- const name = parts.length > 2 ? parts[1].split(',')[0].replace(/"/g, '').trim() : '';
- const domain = parts.length > 2 ? parts[2].replace(/"/g, '').replace(/\)/g, '').trim() : '';
- const dependent = util.getValue(lines, 'dependent', ':', true);
- parts = dependent.split('=');
- const id = parts.length > 1 ? parts[1].replace(/"/g, '').replace(/\)/g, '').trim() : '';
- if (id) {
- loggedons[id] = {
- domain,
- user: name
- };
- }
- });
- return loggedons;
-}
-
-function parseWinUsersQuery(lines) {
- lines = lines.filter(item => item);
- let result = [];
- const header = lines[0];
- const headerDelimiter = [];
- if (header) {
- const start = (header[0] === ' ') ? 1 : 0;
- headerDelimiter.push(start - 1);
- let nextSpace = 0;
- for (let i = start + 1; i < header.length; i++) {
- if (header[i] === ' ' && ((header[i - 1] === ' ') || (header[i - 1] === '.'))) {
- nextSpace = i;
- } else {
- if (nextSpace) {
- headerDelimiter.push(nextSpace);
- nextSpace = 0;
- }
- }
- }
- for (let i = 1; i < lines.length; i++) {
- if (lines[i].trim()) {
- const user = lines[i].substring(headerDelimiter[0] + 1, headerDelimiter[1]).trim() || '';
- const tty = lines[i].substring(headerDelimiter[1] + 1, headerDelimiter[2] - 2).trim() || '';
- result.push({
- user: user,
- tty: tty,
- });
- }
- }
- }
- return result;
-}
-
-exports.users = users;
-
-
-/***/ }),
-
-/***/ 33225:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-
-
-// @ts-check
-// ==================================================================================
-// utils.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 0. helper functions
-// ----------------------------------------------------------------------------------
-
-const os = __nccwpck_require__(70857);
-const fs = __nccwpck_require__(79896);
-const path = __nccwpck_require__(16928);
-const spawn = (__nccwpck_require__(35317).spawn);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const util = __nccwpck_require__(39023);
-
-let _platform = process.platform;
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
-const _freebsd = (_platform === 'freebsd');
-const _openbsd = (_platform === 'openbsd');
-const _netbsd = (_platform === 'netbsd');
-
-let _cores = 0;
-let wmicPath = '';
-let codepage = '';
-let _smartMonToolsInstalled = null;
-let _rpi_cpuinfo = null;
-
-const WINDIR = process.env.WINDIR || 'C:\\Windows';
-
-// powerShell
-let _psChild;
-let _psResult = '';
-let _psCmds = [];
-let _psPersistent = false;
-const _psToUTF8 = '$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8 ; ';
-const _psCmdStart = '--###START###--';
-const _psError = '--ERROR--';
-const _psCmdSeperator = '--###ENDCMD###--';
-const _psIdSeperator = '--##ID##--';
-
-const execOptsWin = {
- windowsHide: true,
- maxBuffer: 1024 * 20000,
- encoding: 'UTF-8',
- env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' })
-};
-
-const execOptsLinux = {
- maxBuffer: 1024 * 20000,
- encoding: 'UTF-8',
- stdio: ['pipe', 'pipe', 'ignore']
-};
-
-function toInt(value) {
- let result = parseInt(value, 10);
- if (isNaN(result)) {
- result = 0;
- }
- return result;
-}
-
-function splitByNumber(str) {
- let numberStarted = false;
- let num = '';
- let cpart = '';
- for (const c of str) {
- if ((c >= '0' && c <= '9') || numberStarted) {
- numberStarted = true;
- num += c;
- } else {
- cpart += c;
- }
- }
- return [cpart, num];
-}
-
-const stringObj = new String();
-const stringReplace = new String().replace;
-const stringToLower = new String().toLowerCase;
-const stringToString = new String().toString;
-const stringSubstr = new String().substr;
-const stringTrim = new String().trim;
-const stringStartWith = new String().startsWith;
-const mathMin = Math.min;
-
-function isFunction(functionToCheck) {
- let getType = {};
- return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
-}
-
-function unique(obj) {
- let uniques = [];
- let stringify = {};
- for (let i = 0; i < obj.length; i++) {
- let keys = Object.keys(obj[i]);
- keys.sort(function (a, b) { return a - b; });
- let str = '';
- for (let j = 0; j < keys.length; j++) {
- str += JSON.stringify(keys[j]);
- str += JSON.stringify(obj[i][keys[j]]);
- }
- if (!{}.hasOwnProperty.call(stringify, str)) {
- uniques.push(obj[i]);
- stringify[str] = true;
- }
- }
- return uniques;
-}
-
-function sortByKey(array, keys) {
- return array.sort(function (a, b) {
- let x = '';
- let y = '';
- keys.forEach(function (key) {
- x = x + a[key]; y = y + b[key];
- });
- return ((x < y) ? -1 : ((x > y) ? 1 : 0));
- });
-}
-
-function cores() {
- if (_cores === 0) {
- _cores = os.cpus().length;
- }
- return _cores;
-}
-
-function getValue(lines, property, separator, trimmed, lineMatch) {
- separator = separator || ':';
- property = property.toLowerCase();
- trimmed = trimmed || false;
- lineMatch = lineMatch || false;
- let result = '';
- lines.some((line) => {
- let lineLower = line.toLowerCase().replace(/\t/g, '');
- if (trimmed) {
- lineLower = lineLower.trim();
- }
- if (lineLower.startsWith(property) && (lineMatch ? (lineLower.match(property + separator)) || (lineLower.match(property + ' ' + separator)) : true)) {
- const parts = trimmed ? line.trim().split(separator) : line.split(separator);
- if (parts.length >= 2) {
- parts.shift();
- result = parts.join(separator).trim();
- return true;
- }
- }
- });
- return result;
-}
-
-function decodeEscapeSequence(str, base) {
- base = base || 16;
- return str.replace(/\\x([0-9A-Fa-f]{2})/g, function () {
- return String.fromCharCode(parseInt(arguments[1], base));
- });
-}
-
-function detectSplit(str) {
- let seperator = '';
- let part = 0;
- str.split('').forEach(element => {
- if (element >= '0' && element <= '9') {
- if (part === 1) { part++; }
- } else {
- if (part === 0) { part++; }
- if (part === 1) {
- seperator += element;
- }
- }
- });
- return seperator;
-}
-
-function parseTime(t, pmDesignator) {
- pmDesignator = pmDesignator || '';
- t = t.toUpperCase();
- let hour = 0;
- let min = 0;
- let splitter = detectSplit(t);
- let parts = t.split(splitter);
- if (parts.length >= 2) {
- if (parts[2]) {
- parts[1] += parts[2];
- }
- let isPM = (parts[1] && (parts[1].toLowerCase().indexOf('pm') > -1) || (parts[1].toLowerCase().indexOf('p.m.') > -1) || (parts[1].toLowerCase().indexOf('p. m.') > -1) || (parts[1].toLowerCase().indexOf('n') > -1) || (parts[1].toLowerCase().indexOf('ch') > -1) || (parts[1].toLowerCase().indexOf('ös') > -1) || (pmDesignator && parts[1].toLowerCase().indexOf(pmDesignator) > -1));
- hour = parseInt(parts[0], 10);
- min = parseInt(parts[1], 10);
- hour = isPM && hour < 12 ? hour + 12 : hour;
- return ('0' + hour).substr(-2) + ':' + ('0' + min).substr(-2);
- }
-}
-
-function parseDateTime(dt, culture) {
- const result = {
- date: '',
- time: ''
- };
- culture = culture || {};
- let dateFormat = (culture.dateFormat || '').toLowerCase();
- let pmDesignator = (culture.pmDesignator || '');
-
- const parts = dt.split(' ');
- if (parts[0]) {
- if (parts[0].indexOf('/') >= 0) {
- // Dateformat: mm/dd/yyyy or dd/mm/yyyy or dd/mm/yy or yyyy/mm/dd
- const dtparts = parts[0].split('/');
- if (dtparts.length === 3) {
- if (dtparts[0].length === 4) {
- // Dateformat: yyyy/mm/dd
- result.date = dtparts[0] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[2]).substr(-2);
- } else if (dtparts[2].length === 2) {
- if ((dateFormat.indexOf('/d/') > -1 || dateFormat.indexOf('/dd/') > -1)) {
- // Dateformat: mm/dd/yy
- result.date = '20' + dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
- } else {
- // Dateformat: dd/mm/yy
- result.date = '20' + dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
- }
- } else {
- // Dateformat: mm/dd/yyyy or dd/mm/yyyy
- const isEN = ((dt.toLowerCase().indexOf('pm') > -1) || (dt.toLowerCase().indexOf('p.m.') > -1) || (dt.toLowerCase().indexOf('p. m.') > -1) || (dt.toLowerCase().indexOf('am') > -1) || (dt.toLowerCase().indexOf('a.m.') > -1) || (dt.toLowerCase().indexOf('a. m.') > -1));
- if ((isEN || dateFormat.indexOf('/d/') > -1 || dateFormat.indexOf('/dd/') > -1) && dateFormat.indexOf('dd/') !== 0) {
- // Dateformat: mm/dd/yyyy
- result.date = dtparts[2] + '-' + ('0' + dtparts[0]).substr(-2) + '-' + ('0' + dtparts[1]).substr(-2);
- } else {
- // Dateformat: dd/mm/yyyy
- result.date = dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
- }
- }
- }
- }
- if (parts[0].indexOf('.') >= 0) {
- const dtparts = parts[0].split('.');
- if (dtparts.length === 3) {
- if (dateFormat.indexOf('.d.') > -1 || dateFormat.indexOf('.dd.') > -1) {
- // Dateformat: mm.dd.yyyy
- result.date = dtparts[2] + '-' + ('0' + dtparts[0]).substr(-2) + '-' + ('0' + dtparts[1]).substr(-2);
- } else {
- // Dateformat: dd.mm.yyyy
- result.date = dtparts[2] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[0]).substr(-2);
- }
- }
- }
- if (parts[0].indexOf('-') >= 0) {
- // Dateformat: yyyy-mm-dd
- const dtparts = parts[0].split('-');
- if (dtparts.length === 3) {
- result.date = dtparts[0] + '-' + ('0' + dtparts[1]).substr(-2) + '-' + ('0' + dtparts[2]).substr(-2);
- }
- }
- }
- if (parts[1]) {
- parts.shift();
- let time = parts.join(' ');
- result.time = parseTime(time, pmDesignator);
- }
- return result;
-}
-
-function parseHead(head, rights) {
- let space = (rights > 0);
- let count = 1;
- let from = 0;
- let to = 0;
- let result = [];
- for (let i = 0; i < head.length; i++) {
- if (count <= rights) {
- if (/\s/.test(head[i]) && !space) {
- to = i - 1;
- result.push({
- from: from,
- to: to + 1,
- cap: head.substring(from, to + 1)
- });
- from = to + 2;
- count++;
- }
- space = head[i] === ' ';
- } else {
- if (!/\s/.test(head[i]) && space) {
- to = i - 1;
- if (from < to) {
- result.push({
- from: from,
- to: to,
- cap: head.substring(from, to)
- });
- }
- from = to + 1;
- count++;
- }
- space = head[i] === ' ';
- }
- }
- to = 5000;
- result.push({
- from: from,
- to: to,
- cap: head.substring(from, to)
- });
- let len = result.length;
- for (let i = 0; i < len; i++) {
- if (result[i].cap.replace(/\s/g, '').length === 0) {
- if (i + 1 < len) {
- result[i].to = result[i + 1].to;
- result[i].cap = result[i].cap + result[i + 1].cap;
- result.splice(i + 1, 1);
- len = len - 1;
- }
- }
- }
- return result;
-}
-
-function findObjectByKey(array, key, value) {
- for (let i = 0; i < array.length; i++) {
- if (array[i][key] === value) {
- return i;
- }
- }
- return -1;
-}
-
-function getWmic() {
- if (os.type() === 'Windows_NT' && !wmicPath) {
- wmicPath = WINDIR + '\\system32\\wbem\\wmic.exe';
- if (!fs.existsSync(wmicPath)) {
- try {
- const wmicPathArray = execSync('WHERE WMIC', execOptsWin).toString().split('\r\n');
- if (wmicPathArray && wmicPathArray.length) {
- wmicPath = wmicPathArray[0];
- } else {
- wmicPath = 'wmic';
- }
- } catch (e) {
- wmicPath = 'wmic';
- }
- }
- }
- return wmicPath;
-}
-
-function wmic(command) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- try {
- powerShell(getWmic() + ' ' + command).then(stdout => {
- resolve(stdout, '');
- });
- } catch (e) {
- resolve('', e);
- }
- });
- });
-}
-
-function getVboxmanage() {
- return _windows ? `"${process.env.VBOX_INSTALL_PATH || process.env.VBOX_MSI_INSTALL_PATH}\\VBoxManage.exe"` : 'vboxmanage';
-}
-
-function powerShellProceedResults(data) {
- let id = '';
- let parts;
- let res = '';
- // startID
- if (data.indexOf(_psCmdStart) >= 0) {
- parts = data.split(_psCmdStart);
- const parts2 = parts[1].split(_psIdSeperator);
- id = parts2[0];
- if (parts2.length > 1) {
- data = parts2.slice(1).join(_psIdSeperator);
- }
- }
- // result;
- if (data.indexOf(_psCmdSeperator) >= 0) {
- parts = data.split(_psCmdSeperator);
- res = parts[0];
- }
- let remove = -1;
- for (let i = 0; i < _psCmds.length; i++) {
- if (_psCmds[i].id === id) {
- remove = i;
- _psCmds[i].callback(res);
- }
- }
- if (remove >= 0) {
- _psCmds.splice(remove, 1);
- }
-}
-
-function powerShellStart() {
- if (!_psChild) {
- _psChild = spawn('powershell.exe', ['-NoProfile', '-NoLogo', '-InputFormat', 'Text', '-NoExit', '-Command', '-'], {
- stdio: 'pipe',
- windowsHide: true,
- maxBuffer: 1024 * 20000,
- encoding: 'UTF-8',
- env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' })
- });
- if (_psChild && _psChild.pid) {
- _psPersistent = true;
- _psChild.stdout.on('data', function (data) {
- _psResult = _psResult + data.toString('utf8');
- if (data.indexOf(_psCmdSeperator) >= 0) {
- powerShellProceedResults(_psResult);
- _psResult = '';
- }
- });
- _psChild.stderr.on('data', function () {
- powerShellProceedResults(_psResult + _psError);
- });
- _psChild.on('error', function () {
- powerShellProceedResults(_psResult + _psError);
- });
- _psChild.on('close', function () {
- if (_psChild) { _psChild.kill(); }
- });
- }
- }
-}
-
-function powerShellRelease() {
- try {
- if (_psChild) {
- _psChild.stdin.write('exit' + os.EOL);
- _psChild.stdin.end();
- _psPersistent = false;
- }
- } catch (e) {
- if (_psChild) { _psChild.kill(); }
- }
- _psChild = null;
-}
-
-function powerShell(cmd) {
-
- /// const pattern = [
- /// '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
- /// '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))'
- /// ].join('|');
-
- if (_psPersistent) {
- const id = Math.random().toString(36).substring(2, 12);
- return new Promise((resolve) => {
- process.nextTick(() => {
- function callback(data) {
- resolve(data);
- }
- _psCmds.push({
- id,
- cmd,
- callback,
- start: new Date()
- });
- try {
- if (_psChild && _psChild.pid) {
- _psChild.stdin.write(_psToUTF8 + 'echo ' + _psCmdStart + id + _psIdSeperator + '; ' + os.EOL + cmd + os.EOL + 'echo ' + _psCmdSeperator + os.EOL);
- }
- } catch (e) {
- resolve('');
- }
- });
- });
-
- } else {
- let result = '';
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- try {
- const child = spawn('powershell.exe', ['-NoProfile', '-NoLogo', '-InputFormat', 'Text', '-NoExit', '-ExecutionPolicy', 'Unrestricted', '-Command', '-'], {
- stdio: 'pipe',
- windowsHide: true,
- maxBuffer: 1024 * 20000,
- encoding: 'UTF-8',
- env: Object.assign({}, process.env, { LANG: 'en_US.UTF-8' })
- });
-
- if (child && !child.pid) {
- child.on('error', function () {
- resolve(result);
- });
- }
- if (child && child.pid) {
- child.stdout.on('data', function (data) {
- result = result + data.toString('utf8');
- });
- child.stderr.on('data', function () {
- child.kill();
- resolve(result);
- });
- child.on('close', function () {
- child.kill();
-
- resolve(result);
- });
- child.on('error', function () {
- child.kill();
- resolve(result);
- });
- try {
- child.stdin.write(_psToUTF8 + cmd + os.EOL);
- child.stdin.write('exit' + os.EOL);
- child.stdin.end();
- } catch (e) {
- child.kill();
- resolve(result);
- }
- } else {
- resolve(result);
- }
- } catch (e) {
- resolve(result);
- }
- });
- });
- }
-}
-
-function execSafe(cmd, args, options) {
- let result = '';
- options = options || {};
-
- return new Promise((resolve) => {
- process.nextTick(() => {
- try {
- const child = spawn(cmd, args, options);
-
- if (child && !child.pid) {
- child.on('error', function () {
- resolve(result);
- });
- }
- if (child && child.pid) {
- child.stdout.on('data', function (data) {
- result += data.toString();
- });
- child.on('close', function () {
- child.kill();
- resolve(result);
- });
- child.on('error', function () {
- child.kill();
- resolve(result);
- });
- } else {
- resolve(result);
- }
- } catch (e) {
- resolve(result);
- }
- });
- });
-}
-
-function getCodepage() {
- if (_windows) {
- if (!codepage) {
- try {
- const stdout = execSync('chcp', execOptsWin);
- const lines = stdout.toString().split('\r\n');
- const parts = lines[0].split(':');
- codepage = parts.length > 1 ? parts[1].replace('.', '').trim() : '';
- } catch (err) {
- codepage = '437';
- }
- }
- return codepage;
- }
- if (_linux || _darwin || _freebsd || _openbsd || _netbsd) {
- if (!codepage) {
- try {
- const stdout = execSync('echo $LANG', execOptsLinux);
- const lines = stdout.toString().split('\r\n');
- const parts = lines[0].split('.');
- codepage = parts.length > 1 ? parts[1].trim() : '';
- if (!codepage) {
- codepage = 'UTF-8';
- }
- } catch (err) {
- codepage = 'UTF-8';
- }
- }
- return codepage;
- }
-}
-
-function smartMonToolsInstalled() {
- if (_smartMonToolsInstalled !== null) {
- return _smartMonToolsInstalled;
- }
- _smartMonToolsInstalled = false;
- if (_windows) {
- try {
- const pathArray = execSync('WHERE smartctl 2>nul', execOptsWin).toString().split('\r\n');
- if (pathArray && pathArray.length) {
- _smartMonToolsInstalled = pathArray[0].indexOf(':\\') >= 0;
- } else {
- _smartMonToolsInstalled = false;
- }
- } catch (e) {
- _smartMonToolsInstalled = false;
- }
- }
- if (_linux || _darwin || _freebsd || _openbsd || _netbsd) {
- try {
- const pathArray = execSync('which smartctl 2>/dev/null', execOptsLinux).toString().split('\r\n');
- _smartMonToolsInstalled = pathArray.length > 0;
- } catch (e) {
- util.noop();
- }
- }
- return _smartMonToolsInstalled;
-}
-
-function isRaspberry() {
- const PI_MODEL_NO = [
- 'BCM2708',
- 'BCM2709',
- 'BCM2710',
- 'BCM2711',
- 'BCM2712',
- 'BCM2835',
- 'BCM2836',
- 'BCM2837',
- 'BCM2837B0'
- ];
- let cpuinfo = [];
-
- if (_rpi_cpuinfo !== null) {
- cpuinfo = _rpi_cpuinfo;
- } else {
- try {
- cpuinfo = fs.readFileSync('/proc/cpuinfo', { encoding: 'utf8' }).toString().split('\n');
- _rpi_cpuinfo = cpuinfo;
- } catch (e) {
- return false;
- }
- }
-
- const hardware = getValue(cpuinfo, 'hardware');
- return (hardware && PI_MODEL_NO.indexOf(hardware) > -1);
-}
-
-function isRaspbian() {
- let osrelease = [];
- try {
- osrelease = fs.readFileSync('/etc/os-release', { encoding: 'utf8' }).toString().split('\n');
- } catch (e) {
- return false;
- }
- const id = getValue(osrelease, 'id', '=');
- return (id && id.indexOf('raspbian') > -1);
-}
-
-function execWin(cmd, opts, callback) {
- if (!callback) {
- callback = opts;
- opts = execOptsWin;
- }
- let newCmd = 'chcp 65001 > nul && cmd /C ' + cmd + ' && chcp ' + codepage + ' > nul';
- exec(newCmd, opts, function (error, stdout) {
- callback(error, stdout);
- });
-}
-
-function darwinXcodeExists() {
- const cmdLineToolsExists = fs.existsSync('/Library/Developer/CommandLineTools/usr/bin/');
- const xcodeAppExists = fs.existsSync('/Applications/Xcode.app/Contents/Developer/Tools');
- const xcodeExists = fs.existsSync('/Library/Developer/Xcode/');
- return (cmdLineToolsExists || xcodeExists || xcodeAppExists);
-}
-
-function nanoSeconds() {
- const time = process.hrtime();
- if (!Array.isArray(time) || time.length !== 2) {
- return 0;
- }
- return +time[0] * 1e9 + +time[1];
-}
-
-function countUniqueLines(lines, startingWith) {
- startingWith = startingWith || '';
- const uniqueLines = [];
- lines.forEach(line => {
- if (line.startsWith(startingWith)) {
- if (uniqueLines.indexOf(line) === -1) {
- uniqueLines.push(line);
- }
- }
- });
- return uniqueLines.length;
-}
-
-function countLines(lines, startingWith) {
- startingWith = startingWith || '';
- const uniqueLines = [];
- lines.forEach(line => {
- if (line.startsWith(startingWith)) {
- uniqueLines.push(line);
- }
- });
- return uniqueLines.length;
-}
-
-function sanitizeShellString(str, strict) {
- if (typeof strict === 'undefined') { strict = false; }
- const s = str || '';
- let result = '';
- const l = mathMin(s.length, 2000);
- for (let i = 0; i <= l; i++) {
- if (!(s[i] === undefined ||
- s[i] === '>' ||
- s[i] === '<' ||
- s[i] === '*' ||
- s[i] === '?' ||
- s[i] === '[' ||
- s[i] === ']' ||
- s[i] === '|' ||
- s[i] === '˚' ||
- s[i] === '$' ||
- s[i] === ';' ||
- s[i] === '&' ||
- s[i] === ']' ||
- s[i] === '#' ||
- s[i] === '\\' ||
- s[i] === '\t' ||
- s[i] === '\n' ||
- s[i] === '\r' ||
- s[i] === '\'' ||
- s[i] === '`' ||
- s[i] === '"' ||
- s[i].length > 1 ||
- (strict && s[i] === '(') ||
- (strict && s[i] === ')') ||
- (strict && s[i] === '@') ||
- (strict && s[i] === ' ') ||
- (strict && s[i] == '{') ||
- (strict && s[i] == ';') ||
- (strict && s[i] == '}'))) {
- result = result + s[i];
- }
- }
- return result;
-}
-
-function isPrototypePolluted() {
- const s = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
- let notPolluted = true;
- let st = '';
-
- try {
- st.__proto__.replace = stringReplace;
- st.__proto__.toLowerCase = stringToLower;
- st.__proto__.toString = stringToString;
- st.__proto__.substr = stringSubstr;
- } catch (e) {
- Object.setPrototypeOf(st, stringObj);
- }
- notPolluted = notPolluted || (s.length !== 62);
- const ms = Date.now();
- if (typeof ms === 'number' && ms > 1600000000000) {
- const l = ms % 100 + 15;
- for (let i = 0; i < l; i++) {
- const r = Math.random() * 61.99999999 + 1;
- const rs = parseInt(Math.floor(r).toString(), 10);
- const rs2 = parseInt(r.toString().split('.')[0], 10);
- const q = Math.random() * 61.99999999 + 1;
- const qs = parseInt(Math.floor(q).toString(), 10);
- const qs2 = parseInt(q.toString().split('.')[0], 10);
- notPolluted = notPolluted && (r !== q);
- notPolluted = notPolluted && rs === rs2 && qs === qs2;
- st += s[rs - 1];
- }
- notPolluted = notPolluted && st.length === l;
- // string manipulation
- let p = Math.random() * l * 0.9999999999;
- let stm = st.substr(0, p) + ' ' + st.substr(p, 2000);
- try {
- stm.__proto__.replace = stringReplace;
- } catch (e) {
- Object.setPrototypeOf(stm, stringObj);
- }
- let sto = stm.replace(/ /g, '');
- notPolluted = notPolluted && st === sto;
- p = Math.random() * l * 0.9999999999;
- stm = st.substr(0, p) + '{' + st.substr(p, 2000);
- sto = stm.replace(/{/g, '');
- notPolluted = notPolluted && st === sto;
- p = Math.random() * l * 0.9999999999;
- stm = st.substr(0, p) + '*' + st.substr(p, 2000);
- sto = stm.replace(/\*/g, '');
- notPolluted = notPolluted && st === sto;
- p = Math.random() * l * 0.9999999999;
- stm = st.substr(0, p) + '$' + st.substr(p, 2000);
- sto = stm.replace(/\$/g, '');
- notPolluted = notPolluted && st === sto;
-
- // lower
- const stl = st.toLowerCase();
- notPolluted = notPolluted && (stl.length === l) && stl[l - 1] && !(stl[l]);
- for (let i = 0; i < l; i++) {
- const s1 = st[i];
- try {
- s1.__proto__.toLowerCase = stringToLower;
- } catch (e) {
- Object.setPrototypeOf(st, stringObj);
- }
- const s2 = stl ? stl[i] : '';
- const s1l = s1.toLowerCase();
- notPolluted = notPolluted && s1l[0] === s2 && s1l[0] && !(s1l[1]);
- }
- }
- return !notPolluted;
-}
-
-function hex2bin(hex) {
- return ('00000000' + (parseInt(hex, 16)).toString(2)).substr(-8);
-}
-
-function getFilesInPath(source) {
- const lstatSync = fs.lstatSync;
- const readdirSync = fs.readdirSync;
- const join = path.join;
-
- function isDirectory(source) {
- return lstatSync(source).isDirectory();
- }
- function isFile(source) { return lstatSync(source).isFile(); }
-
- function getDirectories(source) {
- return readdirSync(source).map(function (name) { return join(source, name); }).filter(isDirectory);
- }
- function getFiles(source) {
- return readdirSync(source).map(function (name) { return join(source, name); }).filter(isFile);
- }
-
- function getFilesRecursively(source) {
- try {
- let dirs = getDirectories(source);
- let files = dirs
- .map(function (dir) { return getFilesRecursively(dir); })
- .reduce(function (a, b) { return a.concat(b); }, []);
- return files.concat(getFiles(source));
- } catch (e) {
- return [];
- }
- }
-
- if (fs.existsSync(source)) {
- return getFilesRecursively(source);
- } else {
- return [];
- }
-}
-
-function decodePiCpuinfo(lines) {
-
- if (_rpi_cpuinfo === null) {
- _rpi_cpuinfo = lines;
- }
-
- // https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md
-
- const oldRevisionCodes = {
- '0002': {
- type: 'B',
- revision: '1.0',
- memory: 256,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '0003': {
- type: 'B',
- revision: '1.0',
- memory: 256,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '0004': {
- type: 'B',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '0005': {
- type: 'B',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Qisda',
- processor: 'BCM2835'
- },
- '0006': {
- type: 'B',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '0007': {
- type: 'A',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '0008': {
- type: 'A',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '0009': {
- type: 'A',
- revision: '2.0',
- memory: 256,
- manufacturer: 'Qisda',
- processor: 'BCM2835'
- },
- '000d': {
- type: 'B',
- revision: '2.0',
- memory: 512,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '000e': {
- type: 'B',
- revision: '2.0',
- memory: 512,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '000f': {
- type: 'B',
- revision: '2.0',
- memory: 512,
- manufacturer: 'Egoman',
- processor: 'BCM2835'
- },
- '0010': {
- type: 'B+',
- revision: '1.2',
- memory: 512,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '0011': {
- type: 'CM1',
- revision: '1.0',
- memory: 512,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '0012': {
- type: 'A+',
- revision: '1.1',
- memory: 256,
- manufacturer: 'Sony UK',
- processor: 'BCM2835'
- },
- '0013': {
- type: 'B+',
- revision: '1.2',
- memory: 512,
- manufacturer: 'Embest',
- processor: 'BCM2835'
- },
- '0014': {
- type: 'CM1',
- revision: '1.0',
- memory: 512,
- manufacturer: 'Embest',
- processor: 'BCM2835'
- },
- '0015': {
- type: 'A+',
- revision: '1.1',
- memory: 256,
- manufacturer: '512MB Embest',
- processor: 'BCM2835'
- }
- };
-
- const processorList = [
- 'BCM2835',
- 'BCM2836',
- 'BCM2837',
- 'BCM2711',
- 'BCM2712',
- ];
- const manufacturerList = [
- 'Sony UK',
- 'Egoman',
- 'Embest',
- 'Sony Japan',
- 'Embest',
- 'Stadium'
- ];
- const typeList = {
- '00': 'A',
- '01': 'B',
- '02': 'A+',
- '03': 'B+',
- '04': '2B',
- '05': 'Alpha (early prototype)',
- '06': 'CM1',
- '08': '3B',
- '09': 'Zero',
- '0a': 'CM3',
- '0c': 'Zero W',
- '0d': '3B+',
- '0e': '3A+',
- '0f': 'Internal use only',
- '10': 'CM3+',
- '11': '4B',
- '12': 'Zero 2 W',
- '13': '400',
- '14': 'CM4',
- '15': 'CM4S',
- '16': 'Internal use only',
- '17': '5',
- '18': 'CM5',
- '19': '500',
- '1a': 'CM5 Lite',
- };
-
- const revisionCode = getValue(lines, 'revision', ':', true);
- const model = getValue(lines, 'model:', ':', true);
- const serial = getValue(lines, 'serial', ':', true);
-
- let result = {};
- if ({}.hasOwnProperty.call(oldRevisionCodes, revisionCode)) {
- // old revision codes
- result = {
- model,
- serial,
- revisionCode,
- memory: oldRevisionCodes[revisionCode].memory,
- manufacturer: oldRevisionCodes[revisionCode].manufacturer,
- processor: oldRevisionCodes[revisionCode].processor,
- type: oldRevisionCodes[revisionCode].type,
- revision: oldRevisionCodes[revisionCode].revision,
- };
-
- } else {
- // new revision code
- const revision = ('00000000' + getValue(lines, 'revision', ':', true).toLowerCase()).substr(-8);
- const memSizeCode = parseInt(hex2bin(revision.substr(2, 1)).substr(5, 3), 2) || 0;
- const manufacturer = manufacturerList[parseInt(revision.substr(3, 1), 10)];
- const processor = processorList[parseInt(revision.substr(4, 1), 10)];
- const typeCode = revision.substr(5, 2);
-
-
- result = {
- model,
- serial,
- revisionCode,
- memory: 256 * Math.pow(2, memSizeCode),
- manufacturer,
- processor,
- type: {}.hasOwnProperty.call(typeList, typeCode) ? typeList[typeCode] : '',
- revision: '1.' + revision.substr(7, 1),
- };
- }
- return result;
-}
-
-function getRpiGpu() {
- let cpuinfo = null;
- if (_rpi_cpuinfo !== null) {
- cpuinfo = _rpi_cpuinfo;
- } else {
- try {
- cpuinfo = fs.readFileSync('/proc/cpuinfo', { encoding: 'utf8' }).toString().split('\n');
- _rpi_cpuinfo = cpuinfo;
- } catch (e) {
- return false;
- }
- }
-
- const rpi = decodePiCpuinfo(cpuinfo);
- if (rpi.type === '4B' || rpi.type === 'CM4' || rpi.type === 'CM4S' || rpi.type === '400') { return 'VideoCore VI'; }
- if (rpi.type === '5') { return 'VideoCore VII'; }
- return 'VideoCore IV';
-}
-
-function promiseAll(promises) {
- const resolvingPromises = promises.map(function (promise) {
- return new Promise(function (resolve) {
- let payload = new Array(2);
- promise.then(function (result) {
- payload[0] = result;
- })
- .catch(function (error) {
- payload[1] = error;
- })
- .then(function () {
- // The wrapped Promise returns an array: 0 = result, 1 = error ... we resolve all
- resolve(payload);
- });
- });
- });
- const errors = [];
- const results = [];
-
- // Execute all wrapped Promises
- return Promise.all(resolvingPromises)
- .then(function (items) {
- items.forEach(function (payload) {
- if (payload[1]) {
- errors.push(payload[1]);
- results.push(null);
- } else {
- errors.push(null);
- results.push(payload[0]);
- }
- });
-
- return {
- errors: errors,
- results: results
- };
- });
-}
-
-function promisify(nodeStyleFunction) {
- return function () {
- const args = Array.prototype.slice.call(arguments);
- return new Promise(function (resolve, reject) {
- args.push(function (err, data) {
- if (err) {
- reject(err);
- } else {
- resolve(data);
- }
- });
- nodeStyleFunction.apply(null, args);
- });
- };
-}
-
-function promisifySave(nodeStyleFunction) {
- return function () {
- const args = Array.prototype.slice.call(arguments);
- return new Promise(function (resolve) {
- args.push(function (err, data) {
- resolve(data);
- });
- nodeStyleFunction.apply(null, args);
- });
- };
-}
-
-function linuxVersion() {
- let result = '';
- if (_linux) {
- try {
- result = execSync('uname -v', execOptsLinux).toString();
- } catch (e) {
- result = '';
- }
- }
- return result;
-}
-
-function plistParser(xmlStr) {
- const tags = ['array', 'dict', 'key', 'string', 'integer', 'date', 'real', 'data', 'boolean', 'arrayEmpty'];
- const startStr = '' && pos < len) {
- pos++;
- }
-
- let depth = 0;
- let inTagStart = false;
- let inTagContent = false;
- let inTagEnd = false;
- let metaData = [{ tagStart: '', tagEnd: '', tagContent: '', key: '', data: null }];
- let c = '';
- let cn = xmlStr[pos];
-
- while (pos < len) {
- c = cn;
- if (pos + 1 < len) { cn = xmlStr[pos + 1]; }
- if (c === '<') {
- inTagContent = false;
- if (cn === '/') { inTagEnd = true; }
- else if (metaData[depth].tagStart) {
- metaData[depth].tagContent = '';
- if (!metaData[depth].data) { metaData[depth].data = metaData[depth].tagStart === 'array' ? [] : {}; }
- depth++;
- metaData.push({ tagStart: '', tagEnd: '', tagContent: '', key: null, data: null });
- inTagStart = true;
- inTagContent = false;
- }
- else if (!inTagStart) { inTagStart = true; }
- } else if (c === '>') {
- if (metaData[depth].tagStart === 'true/') { inTagStart = false; inTagEnd = true; metaData[depth].tagStart = ''; metaData[depth].tagEnd = '/boolean'; metaData[depth].data = true; }
- if (metaData[depth].tagStart === 'false/') { inTagStart = false; inTagEnd = true; metaData[depth].tagStart = ''; metaData[depth].tagEnd = '/boolean'; metaData[depth].data = false; }
- if (metaData[depth].tagStart === 'array/') { inTagStart = false; inTagEnd = true; metaData[depth].tagStart = ''; metaData[depth].tagEnd = '/arrayEmpty'; metaData[depth].data = []; }
- if (inTagContent) { inTagContent = false; }
- if (inTagStart) {
- inTagStart = false;
- inTagContent = true;
- if (metaData[depth].tagStart === 'array') {
- metaData[depth].data = [];
- }
- if (metaData[depth].tagStart === 'dict') {
- metaData[depth].data = {};
- }
- }
- if (inTagEnd) {
- inTagEnd = false;
- if (metaData[depth].tagEnd && tags.indexOf(metaData[depth].tagEnd.substr(1)) >= 0) {
- if (metaData[depth].tagEnd === '/dict' || metaData[depth].tagEnd === '/array') {
- if (depth > 1 && metaData[depth - 2].tagStart === 'array') {
- metaData[depth - 2].data.push(metaData[depth - 1].data);
- }
- if (depth > 1 && metaData[depth - 2].tagStart === 'dict') {
- metaData[depth - 2].data[metaData[depth - 1].key] = metaData[depth - 1].data;
- }
- depth--;
- metaData.pop();
- metaData[depth].tagContent = '';
- metaData[depth].tagStart = '';
- metaData[depth].tagEnd = '';
- }
- else {
- if (metaData[depth].tagEnd === '/key' && metaData[depth].tagContent) {
- metaData[depth].key = metaData[depth].tagContent;
- } else {
- if (metaData[depth].tagEnd === '/real' && metaData[depth].tagContent) { metaData[depth].data = parseFloat(metaData[depth].tagContent) || 0; }
- if (metaData[depth].tagEnd === '/integer' && metaData[depth].tagContent) { metaData[depth].data = parseInt(metaData[depth].tagContent) || 0; }
- if (metaData[depth].tagEnd === '/string' && metaData[depth].tagContent) { metaData[depth].data = metaData[depth].tagContent || ''; }
- if (metaData[depth].tagEnd === '/boolean') { metaData[depth].data = metaData[depth].tagContent || false; }
- if (metaData[depth].tagEnd === '/arrayEmpty') { metaData[depth].data = metaData[depth].tagContent || []; }
- if (depth > 0 && metaData[depth - 1].tagStart === 'array') { metaData[depth - 1].data.push(metaData[depth].data); }
- if (depth > 0 && metaData[depth - 1].tagStart === 'dict') { metaData[depth - 1].data[metaData[depth].key] = metaData[depth].data; }
- }
- metaData[depth].tagContent = '';
- metaData[depth].tagStart = '';
- metaData[depth].tagEnd = '';
- }
- }
- metaData[depth].tagEnd = '';
- inTagStart = false;
- inTagContent = false;
- }
- } else {
- if (inTagStart) { metaData[depth].tagStart += c; }
- if (inTagEnd) { metaData[depth].tagEnd += c; }
- if (inTagContent) { metaData[depth].tagContent += c; }
- }
- pos++;
- }
- return metaData[0].data;
-}
-
-function strIsNumeric(str) {
- return typeof str === 'string' && !isNaN(str) && !isNaN(parseFloat(str));
-}
-
-function plistReader(output) {
- const lines = output.split('\n');
- for (let i = 0; i < lines.length; i++) {
- if (lines[i].indexOf(' = ') >= 0) {
- const lineParts = lines[i].split(' = ');
- lineParts[0] = lineParts[0].trim();
- if (!lineParts[0].startsWith('"')) {
- lineParts[0] = '"' + lineParts[0] + '"';
- }
- lineParts[1] = lineParts[1].trim();
- if (lineParts[1].indexOf('"') === -1 && lineParts[1].endsWith(';')) {
- const valueString = lineParts[1].substring(0, lineParts[1].length - 1);
- if (!strIsNumeric(valueString)) {
- lineParts[1] = `"${valueString}";`;
- }
- }
- if (lineParts[1].indexOf('"') >= 0 && lineParts[1].endsWith(';')) {
- const valueString = lineParts[1].substring(0, lineParts[1].length - 1).replace(/"/g, '');
- if (strIsNumeric(valueString)) {
- lineParts[1] = `${valueString};`;
- }
- }
- lines[i] = lineParts.join(' : ');
- }
- lines[i] = lines[i].replace(/\(/g, '[').replace(/\)/g, ']').replace(/;/g, ',').trim();
- if (lines[i].startsWith('}') && lines[i - 1] && lines[i - 1].endsWith(',')) {
- lines[i - 1] = lines[i - 1].substring(0, lines[i - 1].length - 1);
- }
- }
- output = lines.join('');
- let obj = {};
- try {
- obj = JSON.parse(output);
- } catch (e) {
- noop();
- }
- return obj;
-}
-
-function semverCompare(v1, v2) {
- let res = 0;
- const parts1 = v1.split('.');
- const parts2 = v2.split('.');
- if (parts1[0] < parts2[0]) { res = 1; }
- else if (parts1[0] > parts2[0]) { res = -1; }
- else if (parts1[0] === parts2[0] && parts1.length >= 2 && parts2.length >= 2) {
- if (parts1[1] < parts2[1]) { res = 1; }
- else if (parts1[1] > parts2[1]) { res = -1; }
- else if (parts1[1] === parts2[1]) {
- if (parts1.length >= 3 && parts2.length >= 3) {
- if (parts1[2] < parts2[2]) { res = 1; }
- else if (parts1[2] > parts2[2]) { res = -1; }
- } else if (parts2.length >= 3) {
- res = 1;
- }
- }
- }
- return res;
-}
-
-function getAppleModel(key) {
- const appleModelIds = [
- {
- key: 'Mac15,12',
- name: 'MacBook Air',
- size: '13-inch',
- processor: 'M3',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac14,15',
- name: 'MacBook Air',
- size: '15-inch',
- processor: 'M2',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac14,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: 'M2',
- year: '2022',
- additional: ''
- },
- {
- key: 'MacBookAir10,1',
- name: 'MacBook Air',
- size: '13-inch',
- processor: 'M1',
- year: '2020',
- additional: ''
- },
- {
- key: 'MacBookAir9,1',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: '2020',
- additional: ''
- },
- {
- key: 'MacBookAir8,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookAir8,1',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: '2018',
- additional: ''
- },
- {
- key: 'MacBookAir7,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: '2017',
- additional: ''
- },
- {
- key: 'MacBookAir7,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Early 2015',
- additional: ''
- },
- {
- key: 'MacBookAir7,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Early 2015',
- additional: ''
- },
- {
- key: 'MacBookAir6,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Early 2014',
- additional: ''
- },
- {
- key: 'MacBookAir6,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Early 2014',
- additional: ''
- },
- {
- key: 'MacBookAir6,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Mid 2013',
- additional: ''
- },
- {
- key: 'MacBookAir6,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Mid 2013',
- additional: ''
- },
- {
- key: 'MacBookAir5,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacBookAir5,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacBookAir4,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'MacBookAir4,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'MacBookAir3,2',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Late 2010',
- additional: ''
- },
- {
- key: 'MacBookAir3,1',
- name: 'MacBook Air',
- size: '11-inch',
- processor: '',
- year: 'Late 2010',
- additional: ''
- },
- {
- key: 'MacBookAir2,1',
- name: 'MacBook Air',
- size: '13-inch',
- processor: '',
- year: 'Mid 2009',
- additional: ''
- },
- {
- key: 'Mac16,1',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M4',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac16,6',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M4 Pro',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac16,8',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M4 Max',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac16,5',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M4 Pro',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac16,6',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M4 Max',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac15,3',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M3',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,6',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M3 Pro',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,8',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M3 Pro',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,10',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M3 Max',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,7',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M3 Pro',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,9',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M3 Pro',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac15,11',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M3 Max',
- year: 'Nov 2023',
- additional: ''
- },
- {
- key: 'Mac14,5',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M2 Max',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,9',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M2 Max',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,6',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M2 Max',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,10',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M2 Max',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,7',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: 'M2',
- year: '2022',
- additional: ''
- },
- {
- key: 'MacBookPro18,3',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M1 Pro',
- year: '2021',
- additional: ''
- },
- {
- key: 'MacBookPro18,4',
- name: 'MacBook Pro',
- size: '14-inch',
- processor: 'M1 Max',
- year: '2021',
- additional: ''
- },
- {
- key: 'MacBookPro18,1',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M1 Pro',
- year: '2021',
- additional: ''
- },
- {
- key: 'MacBookPro18,2',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: 'M1 Max',
- year: '2021',
- additional: ''
- },
- {
- key: 'MacBookPro17,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: 'M1',
- year: '2020',
- additional: ''
- },
- {
- key: 'MacBookPro16,3',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2020',
- additional: 'Two Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro16,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2020',
- additional: 'Four Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro16,1',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookPro16,4',
- name: 'MacBook Pro',
- size: '16-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookPro15,3',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookPro15,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookPro15,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacBookPro15,4',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2019',
- additional: 'Two Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro15,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: '2018',
- additional: ''
- },
- {
- key: 'MacBookPro15,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2018',
- additional: 'Four Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro14,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2017',
- additional: 'Two Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro14,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2017',
- additional: 'Four Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro14,3',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: '2017',
- additional: ''
- },
- {
- key: 'MacBookPro13,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2016',
- additional: 'Two Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro13,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: '2016',
- additional: 'Four Thunderbolt 3 ports'
- },
- {
- key: 'MacBookPro13,3',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: '2016',
- additional: ''
- },
- {
- key: 'MacBookPro11,4',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2015',
- additional: ''
- },
- {
- key: 'MacBookPro11,5',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2015',
- additional: ''
- },
- {
- key: 'MacBookPro12,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Early 2015',
- additional: ''
- },
- {
- key: 'MacBookPro11,2',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'MacBookPro11,3',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'MacBookPro11,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'MacBookPro10,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacBookPro10,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Late 2012',
- additional: ''
- },
- {
- key: 'MacBookPro9,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacBookPro9,2',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacBookPro8,3',
- name: 'MacBook Pro',
- size: '17-inch',
- processor: '',
- year: 'Early 2011',
- additional: ''
- },
- {
- key: 'MacBookPro8,2',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Early 2011',
- additional: ''
- },
- {
- key: 'MacBookPro8,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Early 2011',
- additional: ''
- },
- {
- key: 'MacBookPro6,1',
- name: 'MacBook Pro',
- size: '17-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'MacBookPro6,2',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'MacBookPro7,1',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'MacBookPro5,2',
- name: 'MacBook Pro',
- size: '17-inch',
- processor: '',
- year: 'Early 2009',
- additional: ''
- },
- {
- key: 'MacBookPro5,3',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Mid 2009',
- additional: ''
- },
- {
- key: 'MacBookPro5,5',
- name: 'MacBook Pro',
- size: '13-inch',
- processor: '',
- year: 'Mid 2009',
- additional: ''
- },
- {
- key: 'MacBookPro5,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Late 2008',
- additional: ''
- },
- {
- key: 'MacBookPro4,1',
- name: 'MacBook Pro',
- size: '15-inch',
- processor: '',
- year: 'Early 2008',
- additional: ''
- },
- {
- key: 'MacBook10,1',
- name: 'MacBook',
- size: '12-inch',
- processor: '',
- year: '2017',
- additional: ''
- },
- {
- key: 'MacBook9,1',
- name: 'MacBook',
- size: '12-inch',
- processor: '',
- year: 'Early 2016',
- additional: ''
- },
- {
- key: 'MacBook8,1',
- name: 'MacBook',
- size: '12-inch',
- processor: '',
- year: 'Early 2015',
- additional: ''
- },
- {
- key: 'MacBook7,1',
- name: 'MacBook',
- size: '13-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'MacBook6,1',
- name: 'MacBook',
- size: '13-inch',
- processor: '',
- year: 'Late 2009',
- additional: ''
- },
- {
- key: 'MacBook5,2',
- name: 'MacBook',
- size: '13-inch',
- processor: '',
- year: 'Early 2009',
- additional: ''
- },
- {
- key: 'Mac14,13',
- name: 'Mac Studio',
- size: '',
- processor: '',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,14',
- name: 'Mac Studio',
- size: '',
- processor: '',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac13,1',
- name: 'Mac Studio',
- size: '',
- processor: '',
- year: '2022',
- additional: ''
- },
- {
- key: 'Mac13,2',
- name: 'Mac Studio',
- size: '',
- processor: '',
- year: '2022',
- additional: ''
- },
- {
- key: 'Mac16,11',
- name: 'Mac mini',
- size: '',
- processor: 'M4 Pro',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac16,10',
- name: 'Mac mini',
- size: '',
- processor: 'M4',
- year: '2024',
- additional: ''
- },
- {
- key: 'Mac14,3',
- name: 'Mac mini',
- size: '',
- processor: 'M2',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,12',
- name: 'Mac mini',
- size: '',
- processor: 'M2 Pro',
- year: '2023',
- additional: ''
- },
- {
- key: 'Macmini9,1',
- name: 'Mac mini',
- size: '',
- processor: 'M1',
- year: '2020',
- additional: ''
- },
- {
- key: 'Macmini8,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Late 2018',
- additional: ''
- },
- {
- key: 'Macmini7,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Late 2014',
- additional: ''
- },
- {
- key: 'Macmini6,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Late 2012',
- additional: ''
- },
- {
- key: 'Macmini6,2',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Late 2012',
- additional: ''
- },
- {
- key: 'Macmini5,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'Macmini5,2',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'Macmini4,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'Macmini3,1',
- name: 'Mac mini',
- size: '',
- processor: '',
- year: 'Early 2009',
- additional: ''
- },
- {
- key: 'Mac16,3',
- name: 'iMac',
- size: '24-inch',
- processor: 'M4',
- year: '2024',
- additional: 'Four ports'
- },
- {
- key: 'Mac16,2',
- name: 'iMac',
- size: '24-inch',
- processor: 'M4',
- year: '2024',
- additional: 'Two ports'
- },
- {
- key: 'Mac15,5',
- name: 'iMac',
- size: '24-inch',
- processor: 'M3',
- year: '2023',
- additional: 'Four ports'
- },
- {
- key: 'Mac15,4',
- name: 'iMac',
- size: '24-inch',
- processor: 'M3',
- year: '2023',
- additional: 'Two ports'
- },
- {
- key: 'iMac21,1',
- name: 'iMac',
- size: '24-inch',
- processor: 'M1',
- year: '2021',
- additional: ''
- },
- {
- key: 'iMac21,2',
- name: 'iMac',
- size: '24-inch',
- processor: 'M1',
- year: '2021',
- additional: ''
- },
- {
- key: 'iMac20,1',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: '2020',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac20,2',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: '2020',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac19,1',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: '2019',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac19,2',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: '2019',
- additional: 'Retina 4K'
- },
- {
- key: 'iMacPro1,1',
- name: 'iMac Pro',
- size: '',
- processor: '',
- year: '2017',
- additional: ''
- },
- {
- key: 'iMac18,3',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: '2017',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac18,2',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: '2017',
- additional: 'Retina 4K'
- },
- {
- key: 'iMac18,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: '2017',
- additional: ''
- },
- {
- key: 'iMac17,1',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Late 2015',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac16,2',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Late 2015',
- additional: 'Retina 4K'
- },
- {
- key: 'iMac16,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Late 2015',
- additional: ''
- },
- {
- key: 'iMac15,1',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Late 2014',
- additional: 'Retina 5K'
- },
- {
- key: 'iMac14,4',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Mid 2014',
- additional: ''
- },
- {
- key: 'iMac14,2',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'iMac14,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'iMac13,2',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Late 2012',
- additional: ''
- },
- {
- key: 'iMac13,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Late 2012',
- additional: ''
- },
- {
- key: 'iMac12,2',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'iMac12,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Mid 2011',
- additional: ''
- },
- {
- key: 'iMac11,3',
- name: 'iMac',
- size: '27-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'iMac11,2',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Mid 2010',
- additional: ''
- },
- {
- key: 'iMac10,1',
- name: 'iMac',
- size: '21.5-inch',
- processor: '',
- year: 'Late 2009',
- additional: ''
- },
- {
- key: 'iMac9,1',
- name: 'iMac',
- size: '20-inch',
- processor: '',
- year: 'Early 2009',
- additional: ''
- },
- {
- key: 'Mac14,8',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: '2023',
- additional: ''
- },
- {
- key: 'Mac14,8',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: '2023',
- additional: 'Rack'
- },
- {
- key: 'MacPro7,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: '2019',
- additional: ''
- },
- {
- key: 'MacPro7,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: '2019',
- additional: 'Rack'
- },
- {
- key: 'MacPro6,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: 'Late 2013',
- additional: ''
- },
- {
- key: 'MacPro5,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: 'Mid 2012',
- additional: ''
- },
- {
- key: 'MacPro5,1',
- name: 'Mac Pro Server',
- size: '',
- processor: '',
- year: 'Mid 2012',
- additional: 'Server'
- },
- {
- key: 'MacPro5,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: 'Mid 2010',
- additional: ''
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+
+
+/***/ }),
+
+/***/ 28775:
+/***/ ((__unused_webpack_module, exports) => {
+
+
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isValidErrorCode = exports.httpStatusFromErrorCode = exports.TwirpErrorCode = exports.BadRouteError = exports.InternalServerErrorWith = exports.InternalServerError = exports.RequiredArgumentError = exports.InvalidArgumentError = exports.NotFoundError = exports.TwirpError = void 0;
+/**
+ * Represents a twirp error
+ */
+class TwirpError extends Error {
+ constructor(code, msg) {
+ super(msg);
+ this.code = TwirpErrorCode.Internal;
+ this.meta = {};
+ this.code = code;
+ this.msg = msg;
+ Object.setPrototypeOf(this, TwirpError.prototype);
+ }
+ /**
+ * Adds a metadata kv to the error
+ * @param key
+ * @param value
+ */
+ withMeta(key, value) {
+ this.meta[key] = value;
+ return this;
+ }
+ /**
+ * Returns a single metadata value
+ * return "" if not found
+ * @param key
+ */
+ getMeta(key) {
+ return this.meta[key] || "";
+ }
+ /**
+ * Add the original error cause
+ * @param err
+ * @param addMeta
+ */
+ withCause(err, addMeta = false) {
+ this._originalCause = err;
+ if (addMeta) {
+ this.withMeta("cause", err.message);
+ }
+ return this;
+ }
+ cause() {
+ return this._originalCause;
+ }
+ /**
+ * Returns the error representation to JSON
+ */
+ toJSON() {
+ try {
+ return JSON.stringify({
+ code: this.code,
+ msg: this.msg,
+ meta: this.meta,
+ });
+ }
+ catch (e) {
+ return `{"code": "internal", "msg": "There was an error but it could not be serialized into JSON"}`;
+ }
+ }
+ /**
+ * Create a twirp error from an object
+ * @param obj
+ */
+ static fromObject(obj) {
+ const code = obj["code"] || TwirpErrorCode.Unknown;
+ const msg = obj["msg"] || "unknown";
+ const error = new TwirpError(code, msg);
+ if (obj["meta"]) {
+ Object.keys(obj["meta"]).forEach((key) => {
+ error.withMeta(key, obj["meta"][key]);
+ });
+ }
+ return error;
+ }
+}
+exports.TwirpError = TwirpError;
+/**
+ * NotFoundError constructor for the common NotFound error.
+ */
+class NotFoundError extends TwirpError {
+ constructor(msg) {
+ super(TwirpErrorCode.NotFound, msg);
+ }
+}
+exports.NotFoundError = NotFoundError;
+/**
+ * InvalidArgumentError constructor for the common InvalidArgument error. Can be
+ * used when an argument has invalid format, is a number out of range, is a bad
+ * option, etc).
+ */
+class InvalidArgumentError extends TwirpError {
+ constructor(argument, validationMsg) {
+ super(TwirpErrorCode.InvalidArgument, argument + " " + validationMsg);
+ this.withMeta("argument", argument);
+ }
+}
+exports.InvalidArgumentError = InvalidArgumentError;
+/**
+ * RequiredArgumentError is a more specific constructor for InvalidArgument
+ * error. Should be used when the argument is required (expected to have a
+ * non-zero value).
+ */
+class RequiredArgumentError extends InvalidArgumentError {
+ constructor(argument) {
+ super(argument, "is required");
+ }
+}
+exports.RequiredArgumentError = RequiredArgumentError;
+/**
+ * InternalError constructor for the common Internal error. Should be used to
+ * specify that something bad or unexpected happened.
+ */
+class InternalServerError extends TwirpError {
+ constructor(msg) {
+ super(TwirpErrorCode.Internal, msg);
+ }
+}
+exports.InternalServerError = InternalServerError;
+/**
+ * InternalErrorWith makes an internal error, wrapping the original error and using it
+ * for the error message, and with metadata "cause" with the original error type.
+ * This function is used by Twirp services to wrap non-Twirp errors as internal errors.
+ * The wrapped error can be extracted later with err.cause()
+ */
+class InternalServerErrorWith extends InternalServerError {
+ constructor(err) {
+ super(err.message);
+ this.withMeta("cause", err.name);
+ this.withCause(err);
+ }
+}
+exports.InternalServerErrorWith = InternalServerErrorWith;
+/**
+ * A standard BadRoute Error
+ */
+class BadRouteError extends TwirpError {
+ constructor(msg, method, url) {
+ super(TwirpErrorCode.BadRoute, msg);
+ this.withMeta("twirp_invalid_route", method + " " + url);
+ }
+}
+exports.BadRouteError = BadRouteError;
+var TwirpErrorCode;
+(function (TwirpErrorCode) {
+ // Canceled indicates the operation was cancelled (typically by the caller).
+ TwirpErrorCode["Canceled"] = "canceled";
+ // Unknown error. For example when handling errors raised by APIs that do not
+ // return enough error information.
+ TwirpErrorCode["Unknown"] = "unknown";
+ // InvalidArgument indicates client specified an invalid argument. It
+ // indicates arguments that are problematic regardless of the state of the
+ // system (i.e. a malformed file name, required argument, number out of range,
+ // etc.).
+ TwirpErrorCode["InvalidArgument"] = "invalid_argument";
+ // Malformed indicates an error occurred while decoding the client's request.
+ // This may mean that the message was encoded improperly, or that there is a
+ // disagreement in message format between the client and server.
+ TwirpErrorCode["Malformed"] = "malformed";
+ // DeadlineExceeded means operation expired before completion. For operations
+ // that change the state of the system, this error may be returned even if the
+ // operation has completed successfully (timeout).
+ TwirpErrorCode["DeadlineExceeded"] = "deadline_exceeded";
+ // NotFound means some requested entity was not found.
+ TwirpErrorCode["NotFound"] = "not_found";
+ // BadRoute means that the requested URL path wasn't routable to a Twirp
+ // service and method. This is returned by the generated server, and usually
+ // shouldn't be returned by applications. Instead, applications should use
+ // NotFound or Unimplemented.
+ TwirpErrorCode["BadRoute"] = "bad_route";
+ // AlreadyExists means an attempt to create an entity failed because one
+ // already exists.
+ TwirpErrorCode["AlreadyExists"] = "already_exists";
+ // PermissionDenied indicates the caller does not have permission to execute
+ // the specified operation. It must not be used if the caller cannot be
+ // identified (Unauthenticated).
+ TwirpErrorCode["PermissionDenied"] = "permission_denied";
+ // Unauthenticated indicates the request does not have valid authentication
+ // credentials for the operation.
+ TwirpErrorCode["Unauthenticated"] = "unauthenticated";
+ // ResourceExhausted indicates some resource has been exhausted, perhaps a
+ // per-user quota, or perhaps the entire file system is out of space.
+ TwirpErrorCode["ResourceExhausted"] = "resource_exhausted";
+ // FailedPrecondition indicates operation was rejected because the system is
+ // not in a state required for the operation's execution. For example, doing
+ // an rmdir operation on a directory that is non-empty, or on a non-directory
+ // object, or when having conflicting read-modify-write on the same resource.
+ TwirpErrorCode["FailedPrecondition"] = "failed_precondition";
+ // Aborted indicates the operation was aborted, typically due to a concurrency
+ // issue like sequencer check failures, transaction aborts, etc.
+ TwirpErrorCode["Aborted"] = "aborted";
+ // OutOfRange means operation was attempted past the valid range. For example,
+ // seeking or reading past end of a paginated collection.
+ //
+ // Unlike InvalidArgument, this error indicates a problem that may be fixed if
+ // the system state changes (i.e. adding more items to the collection).
+ //
+ // There is a fair bit of overlap between FailedPrecondition and OutOfRange.
+ // We recommend using OutOfRange (the more specific error) when it applies so
+ // that callers who are iterating through a space can easily look for an
+ // OutOfRange error to detect when they are done.
+ TwirpErrorCode["OutOfRange"] = "out_of_range";
+ // Unimplemented indicates operation is not implemented or not
+ // supported/enabled in this service.
+ TwirpErrorCode["Unimplemented"] = "unimplemented";
+ // Internal errors. When some invariants expected by the underlying system
+ // have been broken. In other words, something bad happened in the library or
+ // backend service. Do not confuse with HTTP Internal Server Error; an
+ // Internal error could also happen on the client code, i.e. when parsing a
+ // server response.
+ TwirpErrorCode["Internal"] = "internal";
+ // Unavailable indicates the service is currently unavailable. This is a most
+ // likely a transient condition and may be corrected by retrying with a
+ // backoff.
+ TwirpErrorCode["Unavailable"] = "unavailable";
+ // DataLoss indicates unrecoverable data loss or corruption.
+ TwirpErrorCode["DataLoss"] = "data_loss";
+})(TwirpErrorCode = exports.TwirpErrorCode || (exports.TwirpErrorCode = {}));
+// ServerHTTPStatusFromErrorCode maps a Twirp error type into a similar HTTP
+// response status. It is used by the Twirp server handler to set the HTTP
+// response status code. Returns 0 if the ErrorCode is invalid.
+function httpStatusFromErrorCode(code) {
+ switch (code) {
+ case TwirpErrorCode.Canceled:
+ return 408; // RequestTimeout
+ case TwirpErrorCode.Unknown:
+ return 500; // Internal Server Error
+ case TwirpErrorCode.InvalidArgument:
+ return 400; // BadRequest
+ case TwirpErrorCode.Malformed:
+ return 400; // BadRequest
+ case TwirpErrorCode.DeadlineExceeded:
+ return 408; // RequestTimeout
+ case TwirpErrorCode.NotFound:
+ return 404; // Not Found
+ case TwirpErrorCode.BadRoute:
+ return 404; // Not Found
+ case TwirpErrorCode.AlreadyExists:
+ return 409; // Conflict
+ case TwirpErrorCode.PermissionDenied:
+ return 403; // Forbidden
+ case TwirpErrorCode.Unauthenticated:
+ return 401; // Unauthorized
+ case TwirpErrorCode.ResourceExhausted:
+ return 429; // Too Many Requests
+ case TwirpErrorCode.FailedPrecondition:
+ return 412; // Precondition Failed
+ case TwirpErrorCode.Aborted:
+ return 409; // Conflict
+ case TwirpErrorCode.OutOfRange:
+ return 400; // Bad Request
+ case TwirpErrorCode.Unimplemented:
+ return 501; // Not Implemented
+ case TwirpErrorCode.Internal:
+ return 500; // Internal Server Error
+ case TwirpErrorCode.Unavailable:
+ return 503; // Service Unavailable
+ case TwirpErrorCode.DataLoss:
+ return 500; // Internal Server Error
+ default:
+ return 0; // Invalid!
+ }
+}
+exports.httpStatusFromErrorCode = httpStatusFromErrorCode;
+// IsValidErrorCode returns true if is one of the valid predefined constants.
+function isValidErrorCode(code) {
+ return httpStatusFromErrorCode(code) != 0;
+}
+exports.isValidErrorCode = isValidErrorCode;
+
+
+/***/ }),
+
+/***/ 70048:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+var __rest = (this && this.__rest) || function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Gateway = exports.Pattern = void 0;
+const querystring_1 = __nccwpck_require__(83480);
+const dotObject = __importStar(__nccwpck_require__(98749));
+const request_1 = __nccwpck_require__(21179);
+const errors_1 = __nccwpck_require__(28775);
+const http_client_1 = __nccwpck_require__(52503);
+const server_1 = __nccwpck_require__(1991);
+var Pattern;
+(function (Pattern) {
+ Pattern["POST"] = "post";
+ Pattern["GET"] = "get";
+ Pattern["PATCH"] = "patch";
+ Pattern["PUT"] = "put";
+ Pattern["DELETE"] = "delete";
+})(Pattern = exports.Pattern || (exports.Pattern = {}));
+/**
+ * The Gateway proxies http requests to Twirp Compliant
+ * handlers
+ */
+class Gateway {
+ constructor(routes) {
+ this.routes = routes;
+ }
+ /**
+ * Middleware that rewrite the current request
+ * to a Twirp compliant request
+ */
+ twirpRewrite(prefix = "/twirp") {
+ return (req, resp, next) => {
+ this.rewrite(req, resp, prefix)
+ .then(() => next())
+ .catch((e) => {
+ if (e instanceof errors_1.TwirpError) {
+ if (e.code !== errors_1.TwirpErrorCode.NotFound) {
+ server_1.writeError(resp, e);
+ }
+ else {
+ next();
+ }
+ }
+ });
+ };
+ }
+ /**
+ * Rewrite an incoming request to a Twirp compliant request
+ * @param req
+ * @param resp
+ * @param prefix
+ */
+ rewrite(req, resp, prefix = "/twirp") {
+ return __awaiter(this, void 0, void 0, function* () {
+ const [match, route] = this.matchRoute(req);
+ const body = yield this.prepareTwirpBody(req, match, route);
+ const twirpUrl = `${prefix}/${route.packageName}.${route.serviceName}/${route.methodName}`;
+ req.url = twirpUrl;
+ req.originalUrl = twirpUrl;
+ req.method = "POST";
+ req.headers["content-type"] = "application/json";
+ req.rawBody = Buffer.from(JSON.stringify(body));
+ if (route.responseBodyKey) {
+ const endFn = resp.end.bind(resp);
+ resp.end = function (chunk) {
+ if (resp.statusCode === 200) {
+ endFn(`{ "${route.responseBodyKey}": ${chunk} }`);
+ }
+ else {
+ endFn(chunk);
+ }
+ };
+ }
+ });
+ }
+ /**
+ * Create a reverse proxy handler to
+ * proxy http requests to Twirp Compliant handlers
+ * @param httpClientOption
+ */
+ reverseProxy(httpClientOption) {
+ const client = http_client_1.NodeHttpRPC(httpClientOption);
+ return (req, res) => __awaiter(this, void 0, void 0, function* () {
+ try {
+ const [match, route] = this.matchRoute(req);
+ const body = yield this.prepareTwirpBody(req, match, route);
+ const response = yield client.request(`${route.packageName}.${route.serviceName}`, route.methodName, "application/json", body);
+ res.statusCode = 200;
+ res.setHeader("content-type", "application/json");
+ let jsonResponse;
+ if (route.responseBodyKey) {
+ jsonResponse = JSON.stringify({ [route.responseBodyKey]: response });
+ }
+ else {
+ jsonResponse = JSON.stringify(response);
+ }
+ res.end(jsonResponse);
+ }
+ catch (e) {
+ server_1.writeError(res, e);
+ }
+ });
+ }
+ /**
+ * Prepares twirp body requests using http.google.annotions
+ * compliant spec
+ *
+ * @param req
+ * @param match
+ * @param route
+ * @protected
+ */
+ prepareTwirpBody(req, match, route) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const _a = match.params, { query_string } = _a, params = __rest(_a, ["query_string"]);
+ let requestBody = Object.assign({}, params);
+ if (query_string && route.bodyKey !== "*") {
+ const queryParams = this.parseQueryString(query_string);
+ requestBody = Object.assign(Object.assign({}, queryParams), requestBody);
+ }
+ let body = {};
+ if (route.bodyKey) {
+ const data = yield request_1.getRequestData(req);
+ try {
+ const jsonBody = JSON.parse(data.toString() || "{}");
+ if (route.bodyKey === "*") {
+ body = jsonBody;
+ }
+ else {
+ body[route.bodyKey] = jsonBody;
+ }
+ }
+ catch (e) {
+ const msg = "the json request could not be decoded";
+ throw new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
+ }
+ }
+ return Object.assign(Object.assign({}, body), requestBody);
+ });
+ }
+ /**
+ * Matches a route
+ * @param req
+ */
+ matchRoute(req) {
+ var _a;
+ const httpMethod = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toLowerCase();
+ if (!httpMethod) {
+ throw new errors_1.BadRouteError(`method not allowed`, req.method || "", req.url || "");
+ }
+ const routes = this.routes[httpMethod];
+ for (const route of routes) {
+ const match = route.matcher(req.url || "/");
+ if (match) {
+ return [match, route];
+ }
+ }
+ throw new errors_1.NotFoundError(`url ${req.url} not found`);
+ }
+ /**
+ * Parse query string
+ * @param queryString
+ */
+ parseQueryString(queryString) {
+ const queryParams = querystring_1.parse(queryString.replace("?", ""));
+ return dotObject.object(queryParams);
+ }
+}
+exports.Gateway = Gateway;
+
+
+/***/ }),
+
+/***/ 99462:
+/***/ (function(__unused_webpack_module, exports) {
+
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isHook = exports.chainHooks = void 0;
+// ChainHooks creates a new ServerHook which chains the callbacks in
+// each of the constituent hooks passed in. Each hook function will be
+// called in the order of the ServerHooks values passed in.
+//
+// For the erroring hooks, RequestReceived and RequestRouted, any returned
+// errors prevent processing by later hooks.
+function chainHooks(...hooks) {
+ if (hooks.length === 0) {
+ return null;
+ }
+ if (hooks.length === 1) {
+ return hooks[0];
+ }
+ const serverHook = {
+ requestReceived(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestReceived) {
+ continue;
+ }
+ yield hook.requestReceived(ctx);
+ }
+ });
+ },
+ requestPrepared(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestPrepared) {
+ continue;
+ }
+ console.warn("hook requestPrepared is deprecated and will be removed in the next release. " +
+ "Please use responsePrepared instead.");
+ yield hook.requestPrepared(ctx);
+ }
+ });
+ },
+ responsePrepared(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.responsePrepared) {
+ continue;
+ }
+ yield hook.responsePrepared(ctx);
+ }
+ });
+ },
+ requestSent(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestSent) {
+ continue;
+ }
+ console.warn("hook requestSent is deprecated and will be removed in the next release. " +
+ "Please use responseSent instead.");
+ yield hook.requestSent(ctx);
+ }
+ });
+ },
+ responseSent(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.responseSent) {
+ continue;
+ }
+ yield hook.responseSent(ctx);
+ }
+ });
+ },
+ requestRouted(ctx) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.requestRouted) {
+ continue;
+ }
+ yield hook.requestRouted(ctx);
+ }
+ });
+ },
+ error(ctx, err) {
+ return __awaiter(this, void 0, void 0, function* () {
+ for (const hook of hooks) {
+ if (!hook.error) {
+ continue;
+ }
+ yield hook.error(ctx, err);
+ }
+ });
+ },
+ };
+ return serverHook;
+}
+exports.chainHooks = chainHooks;
+function isHook(object) {
+ return ("requestReceived" in object ||
+ "requestPrepared" in object ||
+ "requestSent" in object ||
+ "requestRouted" in object ||
+ "responsePrepared" in object ||
+ "responseSent" in object ||
+ "error" in object);
+}
+exports.isHook = isHook;
+
+
+/***/ }),
+
+/***/ 52503:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+};
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.FetchRPC = exports.wrapErrorResponseToTwirpError = exports.NodeHttpRPC = void 0;
+const http = __importStar(__nccwpck_require__(58611));
+const https = __importStar(__nccwpck_require__(65692));
+const url_1 = __nccwpck_require__(87016);
+const errors_1 = __nccwpck_require__(28775);
+/**
+ * a node HTTP RPC implementation
+ * @param options
+ * @constructor
+ */
+const NodeHttpRPC = (options) => ({
+ request(service, method, contentType, data) {
+ let client;
+ return new Promise((resolve, rejected) => {
+ const responseChunks = [];
+ const requestData = contentType === "application/protobuf"
+ ? Buffer.from(data)
+ : JSON.stringify(data);
+ const url = new url_1.URL(options.baseUrl);
+ const isHttps = url.protocol === "https:";
+ if (isHttps) {
+ client = https;
+ }
+ else {
+ client = http;
+ }
+ const prefix = url.pathname !== "/" ? url.pathname : "";
+ const req = client
+ .request(Object.assign(Object.assign({}, (options ? options : {})), { method: "POST", protocol: url.protocol, host: url.hostname, port: url.port ? url.port : isHttps ? 443 : 80, path: `${prefix}/${service}/${method}`, headers: Object.assign(Object.assign({}, (options.headers ? options.headers : {})), { "Content-Type": contentType, "Content-Length": contentType === "application/protobuf"
+ ? Buffer.byteLength(requestData)
+ : Buffer.from(requestData).byteLength }) }), (res) => {
+ res.on("data", (chunk) => responseChunks.push(chunk));
+ res.on("end", () => {
+ const data = Buffer.concat(responseChunks);
+ if (res.statusCode != 200) {
+ rejected(wrapErrorResponseToTwirpError(data.toString()));
+ }
+ else {
+ if (contentType === "application/json") {
+ resolve(JSON.parse(data.toString()));
+ }
+ else {
+ resolve(data);
+ }
+ }
+ });
+ res.on("error", (err) => {
+ rejected(err);
+ });
+ })
+ .on("error", (err) => {
+ rejected(err);
+ });
+ req.end(requestData);
+ });
},
- {
- key: 'MacPro5,1',
- name: 'Mac Pro Server',
- size: '',
- processor: '',
- year: 'Mid 2010',
- additional: 'Server'
+});
+exports.NodeHttpRPC = NodeHttpRPC;
+function wrapErrorResponseToTwirpError(errorResponse) {
+ return errors_1.TwirpError.fromObject(JSON.parse(errorResponse));
+}
+exports.wrapErrorResponseToTwirpError = wrapErrorResponseToTwirpError;
+/**
+ * a browser fetch RPC implementation
+ */
+const FetchRPC = (options) => ({
+ request(service, method, contentType, data) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const headers = new Headers(options.headers);
+ headers.set("content-type", contentType);
+ const response = yield fetch(`${options.baseUrl}/${service}/${method}`, Object.assign(Object.assign({}, options), { method: "POST", headers, body: data instanceof Uint8Array ? data : JSON.stringify(data) }));
+ if (response.status === 200) {
+ if (contentType === "application/json") {
+ return yield response.json();
+ }
+ return new Uint8Array(yield response.arrayBuffer());
+ }
+ throw errors_1.TwirpError.fromObject(yield response.json());
+ });
},
- {
- key: 'MacPro4,1',
- name: 'Mac Pro',
- size: '',
- processor: '',
- year: 'Early 2009',
- additional: ''
+});
+exports.FetchRPC = FetchRPC;
+
+
+/***/ }),
+
+/***/ 33874:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __exportStar = (this && this.__exportStar) || function(m, exports) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TwirpContentType = void 0;
+__exportStar(__nccwpck_require__(99069), exports);
+__exportStar(__nccwpck_require__(1991), exports);
+__exportStar(__nccwpck_require__(51816), exports);
+__exportStar(__nccwpck_require__(99462), exports);
+__exportStar(__nccwpck_require__(28775), exports);
+__exportStar(__nccwpck_require__(70048), exports);
+__exportStar(__nccwpck_require__(52503), exports);
+var request_1 = __nccwpck_require__(21179);
+Object.defineProperty(exports, "TwirpContentType", ({ enumerable: true, get: function () { return request_1.TwirpContentType; } }));
+
+
+/***/ }),
+
+/***/ 51816:
+/***/ (function(__unused_webpack_module, exports) {
+
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.chainInterceptors = void 0;
+// chains multiple Interceptors into a single Interceptor.
+// The first interceptor wraps the second one, and so on.
+// Returns null if interceptors is empty.
+function chainInterceptors(...interceptors) {
+ if (interceptors.length === 0) {
+ return;
+ }
+ if (interceptors.length === 1) {
+ return interceptors[0];
+ }
+ const first = interceptors[0];
+ return (ctx, request, handler) => __awaiter(this, void 0, void 0, function* () {
+ let next = handler;
+ for (let i = interceptors.length - 1; i > 0; i--) {
+ next = ((next) => (ctx, typedRequest) => {
+ return interceptors[i](ctx, typedRequest, next);
+ })(next);
+ }
+ return first(ctx, request, next);
+ });
+}
+exports.chainInterceptors = chainInterceptors;
+
+
+/***/ }),
+
+/***/ 21179:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.parseTwirpPath = exports.getRequestData = exports.validateRequest = exports.getContentType = exports.TwirpContentType = void 0;
+const errors_1 = __nccwpck_require__(28775);
+/**
+ * Supported Twirp Content-Type
+ */
+var TwirpContentType;
+(function (TwirpContentType) {
+ TwirpContentType[TwirpContentType["Protobuf"] = 0] = "Protobuf";
+ TwirpContentType[TwirpContentType["JSON"] = 1] = "JSON";
+ TwirpContentType[TwirpContentType["Unknown"] = 2] = "Unknown";
+})(TwirpContentType = exports.TwirpContentType || (exports.TwirpContentType = {}));
+/**
+ * Get supported content-type
+ * @param mimeType
+ */
+function getContentType(mimeType) {
+ switch (mimeType) {
+ case "application/protobuf":
+ return TwirpContentType.Protobuf;
+ case "application/json":
+ return TwirpContentType.JSON;
+ default:
+ return TwirpContentType.Unknown;
+ }
+}
+exports.getContentType = getContentType;
+/**
+ * Validate a twirp request
+ * @param ctx
+ * @param request
+ * @param pathPrefix
+ */
+function validateRequest(ctx, request, pathPrefix) {
+ if (request.method !== "POST") {
+ const msg = `unsupported method ${request.method} (only POST is allowed)`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ const path = parseTwirpPath(request.url || "");
+ if (path.pkgService !==
+ (ctx.packageName ? ctx.packageName + "." : "") + ctx.serviceName) {
+ const msg = `no handler for path ${request.url}`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ if (path.prefix !== pathPrefix) {
+ const msg = `invalid path prefix ${path.prefix}, expected ${pathPrefix}, on path ${request.url}`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ const mimeContentType = request.headers["content-type"] || "";
+ if (ctx.contentType === TwirpContentType.Unknown) {
+ const msg = `unexpected Content-Type: ${request.headers["content-type"]}`;
+ throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ }
+ return Object.assign(Object.assign({}, path), { mimeContentType, contentType: ctx.contentType });
+}
+exports.validateRequest = validateRequest;
+/**
+ * Get request data from the body
+ * @param req
+ */
+function getRequestData(req) {
+ return new Promise((resolve, reject) => {
+ const reqWithRawBody = req;
+ if (reqWithRawBody.rawBody instanceof Buffer) {
+ resolve(reqWithRawBody.rawBody);
+ return;
+ }
+ const chunks = [];
+ req.on("data", (chunk) => chunks.push(chunk));
+ req.on("end", () => __awaiter(this, void 0, void 0, function* () {
+ const data = Buffer.concat(chunks);
+ resolve(data);
+ }));
+ req.on("error", (err) => {
+ if (req.aborted) {
+ reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.DeadlineExceeded, "failed to read request: deadline exceeded"));
+ }
+ else {
+ reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, err.message).withCause(err));
+ }
+ });
+ req.on("close", () => {
+ reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Canceled, "failed to read request: context canceled"));
+ });
+ });
+}
+exports.getRequestData = getRequestData;
+/**
+ * Parses twirp url path
+ * @param path
+ */
+function parseTwirpPath(path) {
+ const parts = path.split("/");
+ if (parts.length < 2) {
+ return {
+ pkgService: "",
+ method: "",
+ prefix: "",
+ };
+ }
+ return {
+ method: parts[parts.length - 1],
+ pkgService: parts[parts.length - 2],
+ prefix: parts.slice(0, parts.length - 2).join("/"),
+ };
+}
+exports.parseTwirpPath = parseTwirpPath;
+
+
+/***/ }),
+
+/***/ 1991:
+/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+
+
+var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+};
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.writeError = exports.TwirpServer = void 0;
+const hooks_1 = __nccwpck_require__(99462);
+const request_1 = __nccwpck_require__(21179);
+const errors_1 = __nccwpck_require__(28775);
+/**
+ * Runtime server implementation of a TwirpServer
+ */
+class TwirpServer {
+ constructor(options) {
+ this.pathPrefix = "/twirp";
+ this.hooks = [];
+ this.interceptors = [];
+ this.packageName = options.packageName;
+ this.serviceName = options.serviceName;
+ this.methodList = options.methodList;
+ this.matchRoute = options.matchRoute;
+ this.service = options.service;
+ }
+ /**
+ * Returns the prefix for this server
+ */
+ get prefix() {
+ return this.pathPrefix;
+ }
+ /**
+ * The http handler for twirp complaint endpoints
+ * @param options
+ */
+ httpHandler(options) {
+ return (req, resp) => {
+ // setup prefix
+ if ((options === null || options === void 0 ? void 0 : options.prefix) !== undefined) {
+ this.withPrefix(options.prefix);
+ }
+ return this._httpHandler(req, resp);
+ };
+ }
+ /**
+ * Adds interceptors or hooks to the request stack
+ * @param middlewares
+ */
+ use(...middlewares) {
+ middlewares.forEach((middleware) => {
+ if (hooks_1.isHook(middleware)) {
+ this.hooks.push(middleware);
+ return this;
+ }
+ this.interceptors.push(middleware);
+ });
+ return this;
+ }
+ /**
+ * Adds a prefix to the service url path
+ * @param prefix
+ */
+ withPrefix(prefix) {
+ if (prefix === false) {
+ this.pathPrefix = "";
+ }
+ else {
+ this.pathPrefix = prefix;
+ }
+ return this;
+ }
+ /**
+ * Returns the regex matching path for this twirp server
+ */
+ matchingPath() {
+ const baseRegex = this.baseURI().replace(/\./g, "\\.");
+ return new RegExp(`${baseRegex}\/(${this.methodList.join("|")})`);
+ }
+ /**
+ * Returns the base URI for this twirp server
+ */
+ baseURI() {
+ return `${this.pathPrefix}/${this.packageName ? this.packageName + "." : ""}${this.serviceName}`;
+ }
+ /**
+ * Create a twirp context
+ * @param req
+ * @param res
+ * @private
+ */
+ createContext(req, res) {
+ return {
+ packageName: this.packageName,
+ serviceName: this.serviceName,
+ methodName: "",
+ contentType: request_1.getContentType(req.headers["content-type"]),
+ req: req,
+ res: res,
+ };
+ }
+ /**
+ * Twrip server http handler implementation
+ * @param req
+ * @param resp
+ * @private
+ */
+ _httpHandler(req, resp) {
+ return __awaiter(this, void 0, void 0, function* () {
+ const ctx = this.createContext(req, resp);
+ try {
+ yield this.invokeHook("requestReceived", ctx);
+ const { method, mimeContentType } = request_1.validateRequest(ctx, req, this.pathPrefix || "");
+ const handler = this.matchRoute(method, {
+ onMatch: (ctx) => {
+ return this.invokeHook("requestRouted", ctx);
+ },
+ onNotFound: () => {
+ const msg = `no handler for path ${req.url}`;
+ throw new errors_1.BadRouteError(msg, req.method || "", req.url || "");
+ },
+ });
+ const body = yield request_1.getRequestData(req);
+ const response = yield handler(ctx, this.service, body, this.interceptors);
+ yield Promise.all([
+ this.invokeHook("responsePrepared", ctx),
+ // keep backwards compatibility till next release
+ this.invokeHook("requestPrepared", ctx),
+ ]);
+ resp.statusCode = 200;
+ resp.setHeader("Content-Type", mimeContentType);
+ resp.end(response);
+ }
+ catch (e) {
+ yield this.invokeHook("error", ctx, mustBeTwirpError(e));
+ if (!resp.headersSent) {
+ writeError(resp, e);
+ }
+ }
+ finally {
+ yield Promise.all([
+ this.invokeHook("responseSent", ctx),
+ // keep backwards compatibility till next release
+ this.invokeHook("requestSent", ctx),
+ ]);
+ }
+ });
+ }
+ /**
+ * Invoke a hook
+ * @param hookName
+ * @param ctx
+ * @param err
+ * @protected
+ */
+ invokeHook(hookName, ctx, err) {
+ return __awaiter(this, void 0, void 0, function* () {
+ if (this.hooks.length === 0) {
+ return;
+ }
+ const chainedHooks = hooks_1.chainHooks(...this.hooks);
+ const hook = chainedHooks === null || chainedHooks === void 0 ? void 0 : chainedHooks[hookName];
+ if (hook) {
+ yield hook(ctx, err || new errors_1.InternalServerError("internal server error"));
+ }
+ });
+ }
+}
+exports.TwirpServer = TwirpServer;
+/**
+ * Write http error response
+ * @param res
+ * @param error
+ */
+function writeError(res, error) {
+ const twirpError = mustBeTwirpError(error);
+ res.setHeader("Content-Type", "application/json");
+ res.statusCode = errors_1.httpStatusFromErrorCode(twirpError.code);
+ res.end(twirpError.toJSON());
+}
+exports.writeError = writeError;
+/**
+ * Make sure that the error passed is a TwirpError
+ * otherwise it will wrap it into an InternalError
+ * @param err
+ */
+function mustBeTwirpError(err) {
+ if (err instanceof errors_1.TwirpError) {
+ return err;
+ }
+ return new errors_1.InternalServerErrorWith(err);
+}
+
+
+/***/ }),
+
+/***/ 61684:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const Client = __nccwpck_require__(45513)
+const Dispatcher = __nccwpck_require__(20303)
+const errors = __nccwpck_require__(53959)
+const Pool = __nccwpck_require__(44288)
+const BalancedPool = __nccwpck_require__(95377)
+const Agent = __nccwpck_require__(92121)
+const util = __nccwpck_require__(89500)
+const { InvalidArgumentError } = errors
+const api = __nccwpck_require__(82531)
+const buildConnector = __nccwpck_require__(91332)
+const MockClient = __nccwpck_require__(72361)
+const MockAgent = __nccwpck_require__(77017)
+const MockPool = __nccwpck_require__(36480)
+const mockErrors = __nccwpck_require__(12673)
+const ProxyAgent = __nccwpck_require__(79276)
+const RetryHandler = __nccwpck_require__(49569)
+const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(61481)
+const DecoratorHandler = __nccwpck_require__(41468)
+const RedirectHandler = __nccwpck_require__(8591)
+const createRedirectInterceptor = __nccwpck_require__(99299)
+
+let hasCrypto
+try {
+ __nccwpck_require__(76982)
+ hasCrypto = true
+} catch {
+ hasCrypto = false
+}
+
+Object.assign(Dispatcher.prototype, api)
+
+module.exports.Dispatcher = Dispatcher
+module.exports.Client = Client
+module.exports.Pool = Pool
+module.exports.BalancedPool = BalancedPool
+module.exports.Agent = Agent
+module.exports.ProxyAgent = ProxyAgent
+module.exports.RetryHandler = RetryHandler
+
+module.exports.DecoratorHandler = DecoratorHandler
+module.exports.RedirectHandler = RedirectHandler
+module.exports.createRedirectInterceptor = createRedirectInterceptor
+
+module.exports.buildConnector = buildConnector
+module.exports.errors = errors
+
+function makeDispatcher (fn) {
+ return (url, opts, handler) => {
+ if (typeof opts === 'function') {
+ handler = opts
+ opts = null
+ }
+
+ if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
+ throw new InvalidArgumentError('invalid url')
+ }
+
+ if (opts != null && typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ if (opts && opts.path != null) {
+ if (typeof opts.path !== 'string') {
+ throw new InvalidArgumentError('invalid opts.path')
+ }
+
+ let path = opts.path
+ if (!opts.path.startsWith('/')) {
+ path = `/${path}`
+ }
+
+ url = new URL(util.parseOrigin(url).origin + path)
+ } else {
+ if (!opts) {
+ opts = typeof url === 'object' ? url : {}
+ }
+
+ url = util.parseURL(url)
+ }
+
+ const { agent, dispatcher = getGlobalDispatcher() } = opts
+
+ if (agent) {
+ throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
+ }
+
+ return fn.call(dispatcher, {
+ ...opts,
+ origin: url.origin,
+ path: url.search ? `${url.pathname}${url.search}` : url.pathname,
+ method: opts.method || (opts.body ? 'PUT' : 'GET')
+ }, handler)
+ }
+}
+
+module.exports.setGlobalDispatcher = setGlobalDispatcher
+module.exports.getGlobalDispatcher = getGlobalDispatcher
+
+if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {
+ let fetchImpl = null
+ module.exports.fetch = async function fetch (resource) {
+ if (!fetchImpl) {
+ fetchImpl = (__nccwpck_require__(11503).fetch)
+ }
+
+ try {
+ return await fetchImpl(...arguments)
+ } catch (err) {
+ if (typeof err === 'object') {
+ Error.captureStackTrace(err, this)
+ }
+
+ throw err
+ }
+ }
+ module.exports.Headers = __nccwpck_require__(12801).Headers
+ module.exports.Response = __nccwpck_require__(89928).Response
+ module.exports.Request = __nccwpck_require__(2630).Request
+ module.exports.FormData = __nccwpck_require__(47453).FormData
+ module.exports.File = __nccwpck_require__(17005).File
+ module.exports.FileReader = __nccwpck_require__(30052).FileReader
+
+ const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(62896)
+
+ module.exports.setGlobalOrigin = setGlobalOrigin
+ module.exports.getGlobalOrigin = getGlobalOrigin
+
+ const { CacheStorage } = __nccwpck_require__(66446)
+ const { kConstruct } = __nccwpck_require__(68652)
+
+ // Cache & CacheStorage are tightly coupled with fetch. Even if it may run
+ // in an older version of Node, it doesn't have any use without fetch.
+ module.exports.caches = new CacheStorage(kConstruct)
+}
+
+if (util.nodeMajor >= 16) {
+ const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(64276)
+
+ module.exports.deleteCookie = deleteCookie
+ module.exports.getCookies = getCookies
+ module.exports.getSetCookies = getSetCookies
+ module.exports.setCookie = setCookie
+
+ const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
+
+ module.exports.parseMIMEType = parseMIMEType
+ module.exports.serializeAMimeType = serializeAMimeType
+}
+
+if (util.nodeMajor >= 18 && hasCrypto) {
+ const { WebSocket } = __nccwpck_require__(90551)
+
+ module.exports.WebSocket = WebSocket
+}
+
+module.exports.request = makeDispatcher(api.request)
+module.exports.stream = makeDispatcher(api.stream)
+module.exports.pipeline = makeDispatcher(api.pipeline)
+module.exports.connect = makeDispatcher(api.connect)
+module.exports.upgrade = makeDispatcher(api.upgrade)
+
+module.exports.MockClient = MockClient
+module.exports.MockPool = MockPool
+module.exports.MockAgent = MockAgent
+module.exports.mockErrors = mockErrors
+
+
+/***/ }),
+
+/***/ 92121:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { InvalidArgumentError } = __nccwpck_require__(53959)
+const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(68031)
+const DispatcherBase = __nccwpck_require__(52421)
+const Pool = __nccwpck_require__(44288)
+const Client = __nccwpck_require__(45513)
+const util = __nccwpck_require__(89500)
+const createRedirectInterceptor = __nccwpck_require__(99299)
+const { WeakRef, FinalizationRegistry } = __nccwpck_require__(90022)()
+
+const kOnConnect = Symbol('onConnect')
+const kOnDisconnect = Symbol('onDisconnect')
+const kOnConnectionError = Symbol('onConnectionError')
+const kMaxRedirections = Symbol('maxRedirections')
+const kOnDrain = Symbol('onDrain')
+const kFactory = Symbol('factory')
+const kFinalizer = Symbol('finalizer')
+const kOptions = Symbol('options')
+
+function defaultFactory (origin, opts) {
+ return opts && opts.connections === 1
+ ? new Client(origin, opts)
+ : new Pool(origin, opts)
+}
+
+class Agent extends DispatcherBase {
+ constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
+ super()
+
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
+ }
+
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
+ }
+
+ if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
+ }
+
+ if (connect && typeof connect !== 'function') {
+ connect = { ...connect }
+ }
+
+ this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)
+ ? options.interceptors.Agent
+ : [createRedirectInterceptor({ maxRedirections })]
+
+ this[kOptions] = { ...util.deepClone(options), connect }
+ this[kOptions].interceptors = options.interceptors
+ ? { ...options.interceptors }
+ : undefined
+ this[kMaxRedirections] = maxRedirections
+ this[kFactory] = factory
+ this[kClients] = new Map()
+ this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {
+ const ref = this[kClients].get(key)
+ if (ref !== undefined && ref.deref() === undefined) {
+ this[kClients].delete(key)
+ }
+ })
+
+ const agent = this
+
+ this[kOnDrain] = (origin, targets) => {
+ agent.emit('drain', origin, [agent, ...targets])
+ }
+
+ this[kOnConnect] = (origin, targets) => {
+ agent.emit('connect', origin, [agent, ...targets])
+ }
+
+ this[kOnDisconnect] = (origin, targets, err) => {
+ agent.emit('disconnect', origin, [agent, ...targets], err)
+ }
+
+ this[kOnConnectionError] = (origin, targets, err) => {
+ agent.emit('connectionError', origin, [agent, ...targets], err)
+ }
+ }
+
+ get [kRunning] () {
+ let ret = 0
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore next: gc is undeterministic */
+ if (client) {
+ ret += client[kRunning]
+ }
+ }
+ return ret
+ }
+
+ [kDispatch] (opts, handler) {
+ let key
+ if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
+ key = String(opts.origin)
+ } else {
+ throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
+ }
+
+ const ref = this[kClients].get(key)
+
+ let dispatcher = ref ? ref.deref() : null
+ if (!dispatcher) {
+ dispatcher = this[kFactory](opts.origin, this[kOptions])
+ .on('drain', this[kOnDrain])
+ .on('connect', this[kOnConnect])
+ .on('disconnect', this[kOnDisconnect])
+ .on('connectionError', this[kOnConnectionError])
+
+ this[kClients].set(key, new WeakRef(dispatcher))
+ this[kFinalizer].register(dispatcher, key)
+ }
+
+ return dispatcher.dispatch(opts, handler)
+ }
+
+ async [kClose] () {
+ const closePromises = []
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore else: gc is undeterministic */
+ if (client) {
+ closePromises.push(client.close())
+ }
+ }
+
+ await Promise.all(closePromises)
+ }
+
+ async [kDestroy] (err) {
+ const destroyPromises = []
+ for (const ref of this[kClients].values()) {
+ const client = ref.deref()
+ /* istanbul ignore else: gc is undeterministic */
+ if (client) {
+ destroyPromises.push(client.destroy(err))
+ }
+ }
+
+ await Promise.all(destroyPromises)
+ }
+}
+
+module.exports = Agent
+
+
+/***/ }),
+
+/***/ 52730:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const { addAbortListener } = __nccwpck_require__(89500)
+const { RequestAbortedError } = __nccwpck_require__(53959)
+
+const kListener = Symbol('kListener')
+const kSignal = Symbol('kSignal')
+
+function abort (self) {
+ if (self.abort) {
+ self.abort()
+ } else {
+ self.onError(new RequestAbortedError())
+ }
+}
+
+function addSignal (self, signal) {
+ self[kSignal] = null
+ self[kListener] = null
+
+ if (!signal) {
+ return
+ }
+
+ if (signal.aborted) {
+ abort(self)
+ return
+ }
+
+ self[kSignal] = signal
+ self[kListener] = () => {
+ abort(self)
+ }
+
+ addAbortListener(self[kSignal], self[kListener])
+}
+
+function removeSignal (self) {
+ if (!self[kSignal]) {
+ return
+ }
+
+ if ('removeEventListener' in self[kSignal]) {
+ self[kSignal].removeEventListener('abort', self[kListener])
+ } else {
+ self[kSignal].removeListener('abort', self[kListener])
+ }
+
+ self[kSignal] = null
+ self[kListener] = null
+}
+
+module.exports = {
+ addSignal,
+ removeSignal
+}
+
+
+/***/ }),
+
+/***/ 73192:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { AsyncResource } = __nccwpck_require__(90290)
+const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { addSignal, removeSignal } = __nccwpck_require__(52730)
+
+class ConnectHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
+
+ const { signal, opaque, responseHeaders } = opts
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ super('UNDICI_CONNECT')
+
+ this.opaque = opaque || null
+ this.responseHeaders = responseHeaders || null
+ this.callback = callback
+ this.abort = null
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
+
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders () {
+ throw new SocketError('bad connect', null)
+ }
+
+ onUpgrade (statusCode, rawHeaders, socket) {
+ const { callback, opaque, context } = this
+
+ removeSignal(this)
+
+ this.callback = null
+
+ let headers = rawHeaders
+ // Indicates is an HTTP2Session
+ if (headers != null) {
+ headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ }
+
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ headers,
+ socket,
+ opaque,
+ context
+ })
+ }
+
+ onError (err) {
+ const { callback, opaque } = this
+
+ removeSignal(this)
+
+ if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+ }
+}
+
+function connect (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ connect.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
+
+ try {
+ const connectHandler = new ConnectHandler(opts, callback)
+ this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
+
+module.exports = connect
+
+
+/***/ }),
+
+/***/ 62466:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const {
+ Readable,
+ Duplex,
+ PassThrough
+} = __nccwpck_require__(2203)
+const {
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError
+} = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { AsyncResource } = __nccwpck_require__(90290)
+const { addSignal, removeSignal } = __nccwpck_require__(52730)
+const assert = __nccwpck_require__(42613)
+
+const kResume = Symbol('resume')
+
+class PipelineRequest extends Readable {
+ constructor () {
+ super({ autoDestroy: true })
+
+ this[kResume] = null
+ }
+
+ _read () {
+ const { [kResume]: resume } = this
+
+ if (resume) {
+ this[kResume] = null
+ resume()
+ }
+ }
+
+ _destroy (err, callback) {
+ this._read()
+
+ callback(err)
+ }
+}
+
+class PipelineResponse extends Readable {
+ constructor (resume) {
+ super({ autoDestroy: true })
+ this[kResume] = resume
+ }
+
+ _read () {
+ this[kResume]()
+ }
+
+ _destroy (err, callback) {
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError()
+ }
+
+ callback(err)
+ }
+}
+
+class PipelineHandler extends AsyncResource {
+ constructor (opts, handler) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ if (typeof handler !== 'function') {
+ throw new InvalidArgumentError('invalid handler')
+ }
+
+ const { signal, method, opaque, onInfo, responseHeaders } = opts
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
+
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
+
+ super('UNDICI_PIPELINE')
+
+ this.opaque = opaque || null
+ this.responseHeaders = responseHeaders || null
+ this.handler = handler
+ this.abort = null
+ this.context = null
+ this.onInfo = onInfo || null
+
+ this.req = new PipelineRequest().on('error', util.nop)
+
+ this.ret = new Duplex({
+ readableObjectMode: opts.objectMode,
+ autoDestroy: true,
+ read: () => {
+ const { body } = this
+
+ if (body && body.resume) {
+ body.resume()
+ }
+ },
+ write: (chunk, encoding, callback) => {
+ const { req } = this
+
+ if (req.push(chunk, encoding) || req._readableState.destroyed) {
+ callback()
+ } else {
+ req[kResume] = callback
+ }
+ },
+ destroy: (err, callback) => {
+ const { body, req, res, ret, abort } = this
+
+ if (!err && !ret._readableState.endEmitted) {
+ err = new RequestAbortedError()
+ }
+
+ if (abort && err) {
+ abort()
+ }
+
+ util.destroy(body, err)
+ util.destroy(req, err)
+ util.destroy(res, err)
+
+ removeSignal(this)
+
+ callback(err)
+ }
+ }).on('prefinish', () => {
+ const { req } = this
+
+ // Node < 15 does not call _final in same tick.
+ req.push(null)
+ })
+
+ this.res = null
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ const { ret, res } = this
+
+ assert(!res, 'pipeline cannot be retried')
+
+ if (ret.destroyed) {
+ throw new RequestAbortedError()
+ }
+
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders (statusCode, rawHeaders, resume) {
+ const { opaque, handler, context } = this
+
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ this.onInfo({ statusCode, headers })
+ }
+ return
+ }
+
+ this.res = new PipelineResponse(resume)
+
+ let body
+ try {
+ this.handler = null
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ body = this.runInAsyncScope(handler, null, {
+ statusCode,
+ headers,
+ opaque,
+ body: this.res,
+ context
+ })
+ } catch (err) {
+ this.res.on('error', util.nop)
+ throw err
+ }
+
+ if (!body || typeof body.on !== 'function') {
+ throw new InvalidReturnValueError('expected Readable')
+ }
+
+ body
+ .on('data', (chunk) => {
+ const { ret, body } = this
+
+ if (!ret.push(chunk) && body.pause) {
+ body.pause()
+ }
+ })
+ .on('error', (err) => {
+ const { ret } = this
+
+ util.destroy(ret, err)
+ })
+ .on('end', () => {
+ const { ret } = this
+
+ ret.push(null)
+ })
+ .on('close', () => {
+ const { ret } = this
+
+ if (!ret._readableState.ended) {
+ util.destroy(ret, new RequestAbortedError())
+ }
+ })
+
+ this.body = body
+ }
+
+ onData (chunk) {
+ const { res } = this
+ return res.push(chunk)
+ }
+
+ onComplete (trailers) {
+ const { res } = this
+ res.push(null)
+ }
+
+ onError (err) {
+ const { ret } = this
+ this.handler = null
+ util.destroy(ret, err)
+ }
+}
+
+function pipeline (opts, handler) {
+ try {
+ const pipelineHandler = new PipelineHandler(opts, handler)
+ this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
+ return pipelineHandler.ret
+ } catch (err) {
+ return new PassThrough().destroy(err)
+ }
+}
+
+module.exports = pipeline
+
+
+/***/ }),
+
+/***/ 50887:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const Readable = __nccwpck_require__(38947)
+const {
+ InvalidArgumentError,
+ RequestAbortedError
+} = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { getResolveErrorBodyCallback } = __nccwpck_require__(80363)
+const { AsyncResource } = __nccwpck_require__(90290)
+const { addSignal, removeSignal } = __nccwpck_require__(52730)
+
+class RequestHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
+
+ try {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
+
+ if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
+ throw new InvalidArgumentError('invalid highWaterMark')
+ }
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
+
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
+
+ super('UNDICI_REQUEST')
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on('error', util.nop), err)
+ }
+ throw err
+ }
+
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.callback = callback
+ this.res = null
+ this.abort = null
+ this.body = body
+ this.trailers = {}
+ this.context = null
+ this.onInfo = onInfo || null
+ this.throwOnError = throwOnError
+ this.highWaterMark = highWaterMark
+
+ if (util.isStream(body)) {
+ body.on('error', (err) => {
+ this.onError(err)
+ })
+ }
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
+
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
+
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers })
+ }
+ return
+ }
+
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
+ const contentType = parsedHeaders['content-type']
+ const body = new Readable({ resume, abort, contentType, highWaterMark })
+
+ this.callback = null
+ this.res = body
+ if (callback !== null) {
+ if (this.throwOnError && statusCode >= 400) {
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
+ { callback, body, contentType, statusCode, statusMessage, headers }
+ )
+ } else {
+ this.runInAsyncScope(callback, null, null, {
+ statusCode,
+ headers,
+ trailers: this.trailers,
+ opaque,
+ body,
+ context
+ })
+ }
+ }
+ }
+
+ onData (chunk) {
+ const { res } = this
+ return res.push(chunk)
+ }
+
+ onComplete (trailers) {
+ const { res } = this
+
+ removeSignal(this)
+
+ util.parseHeaders(trailers, this.trailers)
+
+ res.push(null)
+ }
+
+ onError (err) {
+ const { res, callback, body, opaque } = this
+
+ removeSignal(this)
+
+ if (callback) {
+ // TODO: Does this need queueMicrotask?
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+
+ if (res) {
+ this.res = null
+ // Ensure all queued handlers are invoked before destroying res.
+ queueMicrotask(() => {
+ util.destroy(res, err)
+ })
+ }
+
+ if (body) {
+ this.body = null
+ util.destroy(body, err)
+ }
+ }
+}
+
+function request (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ request.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
+
+ try {
+ this.dispatch(opts, new RequestHandler(opts, callback))
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
+
+module.exports = request
+module.exports.RequestHandler = RequestHandler
+
+
+/***/ }),
+
+/***/ 44388:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { finished, PassThrough } = __nccwpck_require__(2203)
+const {
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError
+} = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { getResolveErrorBodyCallback } = __nccwpck_require__(80363)
+const { AsyncResource } = __nccwpck_require__(90290)
+const { addSignal, removeSignal } = __nccwpck_require__(52730)
+
+class StreamHandler extends AsyncResource {
+ constructor (opts, factory, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
+
+ try {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
+
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('invalid factory')
+ }
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ if (method === 'CONNECT') {
+ throw new InvalidArgumentError('invalid method')
+ }
+
+ if (onInfo && typeof onInfo !== 'function') {
+ throw new InvalidArgumentError('invalid onInfo callback')
+ }
+
+ super('UNDICI_STREAM')
+ } catch (err) {
+ if (util.isStream(body)) {
+ util.destroy(body.on('error', util.nop), err)
+ }
+ throw err
+ }
+
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.factory = factory
+ this.callback = callback
+ this.res = null
+ this.abort = null
+ this.context = null
+ this.trailers = null
+ this.body = body
+ this.onInfo = onInfo || null
+ this.throwOnError = throwOnError || false
+
+ if (util.isStream(body)) {
+ body.on('error', (err) => {
+ this.onError(err)
+ })
+ }
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
+
+ this.abort = abort
+ this.context = context
+ }
+
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const { factory, opaque, context, callback, responseHeaders } = this
+
+ const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+
+ if (statusCode < 200) {
+ if (this.onInfo) {
+ this.onInfo({ statusCode, headers })
+ }
+ return
+ }
+
+ this.factory = null
+
+ let res
+
+ if (this.throwOnError && statusCode >= 400) {
+ const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
+ const contentType = parsedHeaders['content-type']
+ res = new PassThrough()
+
+ this.callback = null
+ this.runInAsyncScope(getResolveErrorBodyCallback, null,
+ { callback, body: res, contentType, statusCode, statusMessage, headers }
+ )
+ } else {
+ if (factory === null) {
+ return
+ }
+
+ res = this.runInAsyncScope(factory, null, {
+ statusCode,
+ headers,
+ opaque,
+ context
+ })
+
+ if (
+ !res ||
+ typeof res.write !== 'function' ||
+ typeof res.end !== 'function' ||
+ typeof res.on !== 'function'
+ ) {
+ throw new InvalidReturnValueError('expected Writable')
+ }
+
+ // TODO: Avoid finished. It registers an unnecessary amount of listeners.
+ finished(res, { readable: false }, (err) => {
+ const { callback, res, opaque, trailers, abort } = this
+
+ this.res = null
+ if (err || !res.readable) {
+ util.destroy(res, err)
+ }
+
+ this.callback = null
+ this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
+
+ if (err) {
+ abort()
+ }
+ })
+ }
+
+ res.on('drain', resume)
+
+ this.res = res
+
+ const needDrain = res.writableNeedDrain !== undefined
+ ? res.writableNeedDrain
+ : res._writableState && res._writableState.needDrain
+
+ return needDrain !== true
+ }
+
+ onData (chunk) {
+ const { res } = this
+
+ return res ? res.write(chunk) : true
+ }
+
+ onComplete (trailers) {
+ const { res } = this
+
+ removeSignal(this)
+
+ if (!res) {
+ return
+ }
+
+ this.trailers = util.parseHeaders(trailers)
+
+ res.end()
+ }
+
+ onError (err) {
+ const { res, callback, opaque, body } = this
+
+ removeSignal(this)
+
+ this.factory = null
+
+ if (res) {
+ this.res = null
+ util.destroy(res, err)
+ } else if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+
+ if (body) {
+ this.body = null
+ util.destroy(body, err)
+ }
+ }
+}
+
+function stream (opts, factory, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ stream.call(this, opts, factory, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
+
+ try {
+ this.dispatch(opts, new StreamHandler(opts, factory, callback))
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
+
+module.exports = stream
+
+
+/***/ }),
+
+/***/ 56342:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(53959)
+const { AsyncResource } = __nccwpck_require__(90290)
+const util = __nccwpck_require__(89500)
+const { addSignal, removeSignal } = __nccwpck_require__(52730)
+const assert = __nccwpck_require__(42613)
+
+class UpgradeHandler extends AsyncResource {
+ constructor (opts, callback) {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('invalid opts')
+ }
+
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
+
+ const { signal, opaque, responseHeaders } = opts
+
+ if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
+ throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ }
+
+ super('UNDICI_UPGRADE')
+
+ this.responseHeaders = responseHeaders || null
+ this.opaque = opaque || null
+ this.callback = callback
+ this.abort = null
+ this.context = null
+
+ addSignal(this, signal)
+ }
+
+ onConnect (abort, context) {
+ if (!this.callback) {
+ throw new RequestAbortedError()
+ }
+
+ this.abort = abort
+ this.context = null
+ }
+
+ onHeaders () {
+ throw new SocketError('bad upgrade', null)
+ }
+
+ onUpgrade (statusCode, rawHeaders, socket) {
+ const { callback, opaque, context } = this
+
+ assert.strictEqual(statusCode, 101)
+
+ removeSignal(this)
+
+ this.callback = null
+ const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ this.runInAsyncScope(callback, null, null, {
+ headers,
+ socket,
+ opaque,
+ context
+ })
+ }
+
+ onError (err) {
+ const { callback, opaque } = this
+
+ removeSignal(this)
+
+ if (callback) {
+ this.callback = null
+ queueMicrotask(() => {
+ this.runInAsyncScope(callback, null, err, { opaque })
+ })
+ }
+ }
+}
+
+function upgrade (opts, callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ upgrade.call(this, opts, (err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
+
+ try {
+ const upgradeHandler = new UpgradeHandler(opts, callback)
+ this.dispatch({
+ ...opts,
+ method: opts.method || 'GET',
+ upgrade: opts.protocol || 'Websocket'
+ }, upgradeHandler)
+ } catch (err) {
+ if (typeof callback !== 'function') {
+ throw err
+ }
+ const opaque = opts && opts.opaque
+ queueMicrotask(() => callback(err, { opaque }))
+ }
+}
+
+module.exports = upgrade
+
+
+/***/ }),
+
+/***/ 82531:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+module.exports.request = __nccwpck_require__(50887)
+module.exports.stream = __nccwpck_require__(44388)
+module.exports.pipeline = __nccwpck_require__(62466)
+module.exports.upgrade = __nccwpck_require__(56342)
+module.exports.connect = __nccwpck_require__(73192)
+
+
+/***/ }),
+
+/***/ 38947:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+// Ported from https://github.com/nodejs/undici/pull/907
+
+
+
+const assert = __nccwpck_require__(42613)
+const { Readable } = __nccwpck_require__(2203)
+const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(89500)
+
+let Blob
+
+const kConsume = Symbol('kConsume')
+const kReading = Symbol('kReading')
+const kBody = Symbol('kBody')
+const kAbort = Symbol('abort')
+const kContentType = Symbol('kContentType')
+
+const noop = () => {}
+
+module.exports = class BodyReadable extends Readable {
+ constructor ({
+ resume,
+ abort,
+ contentType = '',
+ highWaterMark = 64 * 1024 // Same as nodejs fs streams.
+ }) {
+ super({
+ autoDestroy: true,
+ read: resume,
+ highWaterMark
+ })
+
+ this._readableState.dataEmitted = false
+
+ this[kAbort] = abort
+ this[kConsume] = null
+ this[kBody] = null
+ this[kContentType] = contentType
+
+ // Is stream being consumed through Readable API?
+ // This is an optimization so that we avoid checking
+ // for 'data' and 'readable' listeners in the hot path
+ // inside push().
+ this[kReading] = false
+ }
+
+ destroy (err) {
+ if (this.destroyed) {
+ // Node < 16
+ return this
+ }
+
+ if (!err && !this._readableState.endEmitted) {
+ err = new RequestAbortedError()
+ }
+
+ if (err) {
+ this[kAbort]()
+ }
+
+ return super.destroy(err)
+ }
+
+ emit (ev, ...args) {
+ if (ev === 'data') {
+ // Node < 16.7
+ this._readableState.dataEmitted = true
+ } else if (ev === 'error') {
+ // Node < 16
+ this._readableState.errorEmitted = true
+ }
+ return super.emit(ev, ...args)
+ }
+
+ on (ev, ...args) {
+ if (ev === 'data' || ev === 'readable') {
+ this[kReading] = true
+ }
+ return super.on(ev, ...args)
+ }
+
+ addListener (ev, ...args) {
+ return this.on(ev, ...args)
+ }
+
+ off (ev, ...args) {
+ const ret = super.off(ev, ...args)
+ if (ev === 'data' || ev === 'readable') {
+ this[kReading] = (
+ this.listenerCount('data') > 0 ||
+ this.listenerCount('readable') > 0
+ )
+ }
+ return ret
+ }
+
+ removeListener (ev, ...args) {
+ return this.off(ev, ...args)
+ }
+
+ push (chunk) {
+ if (this[kConsume] && chunk !== null && this.readableLength === 0) {
+ consumePush(this[kConsume], chunk)
+ return this[kReading] ? super.push(chunk) : true
+ }
+ return super.push(chunk)
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-text
+ async text () {
+ return consume(this, 'text')
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-json
+ async json () {
+ return consume(this, 'json')
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-blob
+ async blob () {
+ return consume(this, 'blob')
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
+ async arrayBuffer () {
+ return consume(this, 'arrayBuffer')
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-formdata
+ async formData () {
+ // TODO: Implement.
+ throw new NotSupportedError()
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-bodyused
+ get bodyUsed () {
+ return util.isDisturbed(this)
+ }
+
+ // https://fetch.spec.whatwg.org/#dom-body-body
+ get body () {
+ if (!this[kBody]) {
+ this[kBody] = ReadableStreamFrom(this)
+ if (this[kConsume]) {
+ // TODO: Is this the best way to force a lock?
+ this[kBody].getReader() // Ensure stream is locked.
+ assert(this[kBody].locked)
+ }
+ }
+ return this[kBody]
+ }
+
+ dump (opts) {
+ let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144
+ const signal = opts && opts.signal
+
+ if (signal) {
+ try {
+ if (typeof signal !== 'object' || !('aborted' in signal)) {
+ throw new InvalidArgumentError('signal must be an AbortSignal')
+ }
+ util.throwIfAborted(signal)
+ } catch (err) {
+ return Promise.reject(err)
+ }
+ }
+
+ if (this.closed) {
+ return Promise.resolve(null)
+ }
+
+ return new Promise((resolve, reject) => {
+ const signalListenerCleanup = signal
+ ? util.addAbortListener(signal, () => {
+ this.destroy()
+ })
+ : noop
+
+ this
+ .on('close', function () {
+ signalListenerCleanup()
+ if (signal && signal.aborted) {
+ reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))
+ } else {
+ resolve(null)
+ }
+ })
+ .on('error', noop)
+ .on('data', function (chunk) {
+ limit -= chunk.length
+ if (limit <= 0) {
+ this.destroy()
+ }
+ })
+ .resume()
+ })
+ }
+}
+
+// https://streams.spec.whatwg.org/#readablestream-locked
+function isLocked (self) {
+ // Consume is an implicit lock.
+ return (self[kBody] && self[kBody].locked === true) || self[kConsume]
+}
+
+// https://fetch.spec.whatwg.org/#body-unusable
+function isUnusable (self) {
+ return util.isDisturbed(self) || isLocked(self)
+}
+
+async function consume (stream, type) {
+ if (isUnusable(stream)) {
+ throw new TypeError('unusable')
+ }
+
+ assert(!stream[kConsume])
+
+ return new Promise((resolve, reject) => {
+ stream[kConsume] = {
+ type,
+ stream,
+ resolve,
+ reject,
+ length: 0,
+ body: []
+ }
+
+ stream
+ .on('error', function (err) {
+ consumeFinish(this[kConsume], err)
+ })
+ .on('close', function () {
+ if (this[kConsume].body !== null) {
+ consumeFinish(this[kConsume], new RequestAbortedError())
+ }
+ })
+
+ process.nextTick(consumeStart, stream[kConsume])
+ })
+}
+
+function consumeStart (consume) {
+ if (consume.body === null) {
+ return
+ }
+
+ const { _readableState: state } = consume.stream
+
+ for (const chunk of state.buffer) {
+ consumePush(consume, chunk)
+ }
+
+ if (state.endEmitted) {
+ consumeEnd(this[kConsume])
+ } else {
+ consume.stream.on('end', function () {
+ consumeEnd(this[kConsume])
+ })
+ }
+
+ consume.stream.resume()
+
+ while (consume.stream.read() != null) {
+ // Loop
+ }
+}
+
+function consumeEnd (consume) {
+ const { type, body, resolve, stream, length } = consume
+
+ try {
+ if (type === 'text') {
+ resolve(toUSVString(Buffer.concat(body)))
+ } else if (type === 'json') {
+ resolve(JSON.parse(Buffer.concat(body)))
+ } else if (type === 'arrayBuffer') {
+ const dst = new Uint8Array(length)
+
+ let pos = 0
+ for (const buf of body) {
+ dst.set(buf, pos)
+ pos += buf.byteLength
+ }
+
+ resolve(dst.buffer)
+ } else if (type === 'blob') {
+ if (!Blob) {
+ Blob = (__nccwpck_require__(20181).Blob)
+ }
+ resolve(new Blob(body, { type: stream[kContentType] }))
+ }
+
+ consumeFinish(consume)
+ } catch (err) {
+ stream.destroy(err)
+ }
+}
+
+function consumePush (consume, chunk) {
+ consume.length += chunk.length
+ consume.body.push(chunk)
+}
+
+function consumeFinish (consume, err) {
+ if (consume.body === null) {
+ return
+ }
+
+ if (err) {
+ consume.reject(err)
+ } else {
+ consume.resolve()
+ }
+
+ consume.type = null
+ consume.stream = null
+ consume.resolve = null
+ consume.reject = null
+ consume.length = 0
+ consume.body = null
+}
+
+
+/***/ }),
+
+/***/ 80363:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+const assert = __nccwpck_require__(42613)
+const {
+ ResponseStatusCodeError
+} = __nccwpck_require__(53959)
+const { toUSVString } = __nccwpck_require__(89500)
+
+async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
+ assert(body)
+
+ let chunks = []
+ let limit = 0
+
+ for await (const chunk of body) {
+ chunks.push(chunk)
+ limit += chunk.length
+ if (limit > 128 * 1024) {
+ chunks = null
+ break
+ }
+ }
+
+ if (statusCode === 204 || !contentType || !chunks) {
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
+ return
+ }
+
+ try {
+ if (contentType.startsWith('application/json')) {
+ const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
+ return
+ }
+
+ if (contentType.startsWith('text/')) {
+ const payload = toUSVString(Buffer.concat(chunks))
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
+ return
+ }
+ } catch (err) {
+ // Process in a fallback if error
+ }
+
+ process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
+}
+
+module.exports = { getResolveErrorBodyCallback }
+
+
+/***/ }),
+
+/***/ 95377:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const {
+ BalancedPoolMissingUpstreamError,
+ InvalidArgumentError
+} = __nccwpck_require__(53959)
+const {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+} = __nccwpck_require__(18804)
+const Pool = __nccwpck_require__(44288)
+const { kUrl, kInterceptors } = __nccwpck_require__(68031)
+const { parseOrigin } = __nccwpck_require__(89500)
+const kFactory = Symbol('factory')
+
+const kOptions = Symbol('options')
+const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
+const kCurrentWeight = Symbol('kCurrentWeight')
+const kIndex = Symbol('kIndex')
+const kWeight = Symbol('kWeight')
+const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
+const kErrorPenalty = Symbol('kErrorPenalty')
+
+function getGreatestCommonDivisor (a, b) {
+ if (b === 0) return a
+ return getGreatestCommonDivisor(b, a % b)
+}
+
+function defaultFactory (origin, opts) {
+ return new Pool(origin, opts)
+}
+
+class BalancedPool extends PoolBase {
+ constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
+ super()
+
+ this[kOptions] = opts
+ this[kIndex] = -1
+ this[kCurrentWeight] = 0
+
+ this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
+ this[kErrorPenalty] = this[kOptions].errorPenalty || 15
+
+ if (!Array.isArray(upstreams)) {
+ upstreams = [upstreams]
+ }
+
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
+ }
+
+ this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
+ ? opts.interceptors.BalancedPool
+ : []
+ this[kFactory] = factory
+
+ for (const upstream of upstreams) {
+ this.addUpstream(upstream)
+ }
+ this._updateBalancedPoolStats()
+ }
+
+ addUpstream (upstream) {
+ const upstreamOrigin = parseOrigin(upstream).origin
+
+ if (this[kClients].find((pool) => (
+ pool[kUrl].origin === upstreamOrigin &&
+ pool.closed !== true &&
+ pool.destroyed !== true
+ ))) {
+ return this
+ }
+ const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
+
+ this[kAddClient](pool)
+ pool.on('connect', () => {
+ pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
+ })
+
+ pool.on('connectionError', () => {
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
+ this._updateBalancedPoolStats()
+ })
+
+ pool.on('disconnect', (...args) => {
+ const err = args[2]
+ if (err && err.code === 'UND_ERR_SOCKET') {
+ // decrease the weight of the pool.
+ pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
+ this._updateBalancedPoolStats()
+ }
+ })
+
+ for (const client of this[kClients]) {
+ client[kWeight] = this[kMaxWeightPerServer]
+ }
+
+ this._updateBalancedPoolStats()
+
+ return this
+ }
+
+ _updateBalancedPoolStats () {
+ this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
+ }
+
+ removeUpstream (upstream) {
+ const upstreamOrigin = parseOrigin(upstream).origin
+
+ const pool = this[kClients].find((pool) => (
+ pool[kUrl].origin === upstreamOrigin &&
+ pool.closed !== true &&
+ pool.destroyed !== true
+ ))
+
+ if (pool) {
+ this[kRemoveClient](pool)
+ }
+
+ return this
+ }
+
+ get upstreams () {
+ return this[kClients]
+ .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
+ .map((p) => p[kUrl].origin)
+ }
+
+ [kGetDispatcher] () {
+ // We validate that pools is greater than 0,
+ // otherwise we would have to wait until an upstream
+ // is added, which might never happen.
+ if (this[kClients].length === 0) {
+ throw new BalancedPoolMissingUpstreamError()
+ }
+
+ const dispatcher = this[kClients].find(dispatcher => (
+ !dispatcher[kNeedDrain] &&
+ dispatcher.closed !== true &&
+ dispatcher.destroyed !== true
+ ))
+
+ if (!dispatcher) {
+ return
+ }
+
+ const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
+
+ if (allClientsBusy) {
+ return
+ }
+
+ let counter = 0
+
+ let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
+
+ while (counter++ < this[kClients].length) {
+ this[kIndex] = (this[kIndex] + 1) % this[kClients].length
+ const pool = this[kClients][this[kIndex]]
+
+ // find pool index with the largest weight
+ if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
+ maxWeightIndex = this[kIndex]
+ }
+
+ // decrease the current weight every `this[kClients].length`.
+ if (this[kIndex] === 0) {
+ // Set the current weight to the next lower weight.
+ this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
+
+ if (this[kCurrentWeight] <= 0) {
+ this[kCurrentWeight] = this[kMaxWeightPerServer]
+ }
+ }
+ if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
+ return pool
+ }
+ }
+
+ this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
+ this[kIndex] = maxWeightIndex
+ return this[kClients][maxWeightIndex]
+ }
+}
+
+module.exports = BalancedPool
+
+
+/***/ }),
+
+/***/ 40611:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { kConstruct } = __nccwpck_require__(68652)
+const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(71173)
+const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(89500)
+const { kHeadersList } = __nccwpck_require__(68031)
+const { webidl } = __nccwpck_require__(94354)
+const { Response, cloneResponse } = __nccwpck_require__(89928)
+const { Request } = __nccwpck_require__(2630)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
+const { fetching } = __nccwpck_require__(11503)
+const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(72847)
+const assert = __nccwpck_require__(42613)
+const { getGlobalDispatcher } = __nccwpck_require__(61481)
+
+/**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
+ * @typedef {Object} CacheBatchOperation
+ * @property {'delete' | 'put'} type
+ * @property {any} request
+ * @property {any} response
+ * @property {import('../../types/cache').CacheQueryOptions} options
+ */
+
+/**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
+ * @typedef {[any, any][]} requestResponseList
+ */
+
+class Cache {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
+ * @type {requestResponseList}
+ */
+ #relevantRequestResponseList
+
+ constructor () {
+ if (arguments[0] !== kConstruct) {
+ webidl.illegalConstructor()
+ }
+
+ this.#relevantRequestResponseList = arguments[1]
+ }
+
+ async match (request, options = {}) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })
+
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
+
+ const p = await this.matchAll(request, options)
+
+ if (p.length === 0) {
+ return
+ }
+
+ return p[0]
+ }
+
+ async matchAll (request = undefined, options = {}) {
+ webidl.brandCheck(this, Cache)
+
+ if (request !== undefined) request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
+
+ // 1.
+ let r = null
+
+ // 2.
+ if (request !== undefined) {
+ if (request instanceof Request) {
+ // 2.1.1
+ r = request[kState]
+
+ // 2.1.2
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return []
+ }
+ } else if (typeof request === 'string') {
+ // 2.2.1
+ r = new Request(request)[kState]
+ }
+ }
+
+ // 5.
+ // 5.1
+ const responses = []
+
+ // 5.2
+ if (request === undefined) {
+ // 5.2.1
+ for (const requestResponse of this.#relevantRequestResponseList) {
+ responses.push(requestResponse[1])
+ }
+ } else { // 5.3
+ // 5.3.1
+ const requestResponses = this.#queryCache(r, options)
+
+ // 5.3.2
+ for (const requestResponse of requestResponses) {
+ responses.push(requestResponse[1])
+ }
+ }
+
+ // 5.4
+ // We don't implement CORs so we don't need to loop over the responses, yay!
+
+ // 5.5.1
+ const responseList = []
+
+ // 5.5.2
+ for (const response of responses) {
+ // 5.5.2.1
+ const responseObject = new Response(response.body?.source ?? null)
+ const body = responseObject[kState].body
+ responseObject[kState] = response
+ responseObject[kState].body = body
+ responseObject[kHeaders][kHeadersList] = response.headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
+
+ responseList.push(responseObject)
+ }
+
+ // 6.
+ return Object.freeze(responseList)
+ }
+
+ async add (request) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })
+
+ request = webidl.converters.RequestInfo(request)
+
+ // 1.
+ const requests = [request]
+
+ // 2.
+ const responseArrayPromise = this.addAll(requests)
+
+ // 3.
+ return await responseArrayPromise
+ }
+
+ async addAll (requests) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })
+
+ requests = webidl.converters['sequence'](requests)
+
+ // 1.
+ const responsePromises = []
+
+ // 2.
+ const requestList = []
+
+ // 3.
+ for (const request of requests) {
+ if (typeof request === 'string') {
+ continue
+ }
+
+ // 3.1
+ const r = request[kState]
+
+ // 3.2
+ if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'Expected http/s scheme when method is not GET.'
+ })
+ }
+ }
+
+ // 4.
+ /** @type {ReturnType[]} */
+ const fetchControllers = []
+
+ // 5.
+ for (const request of requests) {
+ // 5.1
+ const r = new Request(request)[kState]
+
+ // 5.2
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'Expected http/s scheme.'
+ })
+ }
+
+ // 5.4
+ r.initiator = 'fetch'
+ r.destination = 'subresource'
+
+ // 5.5
+ requestList.push(r)
+
+ // 5.6
+ const responsePromise = createDeferredPromise()
+
+ // 5.7
+ fetchControllers.push(fetching({
+ request: r,
+ dispatcher: getGlobalDispatcher(),
+ processResponse (response) {
+ // 1.
+ if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
+ responsePromise.reject(webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'Received an invalid status code or the request failed.'
+ }))
+ } else if (response.headersList.contains('vary')) { // 2.
+ // 2.1
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
+
+ // 2.2
+ for (const fieldValue of fieldValues) {
+ // 2.2.1
+ if (fieldValue === '*') {
+ responsePromise.reject(webidl.errors.exception({
+ header: 'Cache.addAll',
+ message: 'invalid vary field value'
+ }))
+
+ for (const controller of fetchControllers) {
+ controller.abort()
+ }
+
+ return
+ }
+ }
+ }
+ },
+ processResponseEndOfBody (response) {
+ // 1.
+ if (response.aborted) {
+ responsePromise.reject(new DOMException('aborted', 'AbortError'))
+ return
+ }
+
+ // 2.
+ responsePromise.resolve(response)
+ }
+ }))
+
+ // 5.8
+ responsePromises.push(responsePromise.promise)
+ }
+
+ // 6.
+ const p = Promise.all(responsePromises)
+
+ // 7.
+ const responses = await p
+
+ // 7.1
+ const operations = []
+
+ // 7.2
+ let index = 0
+
+ // 7.3
+ for (const response of responses) {
+ // 7.3.1
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'put', // 7.3.2
+ request: requestList[index], // 7.3.3
+ response // 7.3.4
+ }
+
+ operations.push(operation) // 7.3.5
+
+ index++ // 7.3.6
+ }
+
+ // 7.5
+ const cacheJobPromise = createDeferredPromise()
+
+ // 7.6.1
+ let errorData = null
+
+ // 7.6.2
+ try {
+ this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
+
+ // 7.6.3
+ queueMicrotask(() => {
+ // 7.6.3.1
+ if (errorData === null) {
+ cacheJobPromise.resolve(undefined)
+ } else {
+ // 7.6.3.2
+ cacheJobPromise.reject(errorData)
+ }
+ })
+
+ // 7.7
+ return cacheJobPromise.promise
+ }
+
+ async put (request, response) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })
+
+ request = webidl.converters.RequestInfo(request)
+ response = webidl.converters.Response(response)
+
+ // 1.
+ let innerRequest = null
+
+ // 2.
+ if (request instanceof Request) {
+ innerRequest = request[kState]
+ } else { // 3.
+ innerRequest = new Request(request)[kState]
+ }
+
+ // 4.
+ if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Expected an http/s scheme when method is not GET'
+ })
+ }
+
+ // 5.
+ const innerResponse = response[kState]
+
+ // 6.
+ if (innerResponse.status === 206) {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Got 206 status'
+ })
+ }
+
+ // 7.
+ if (innerResponse.headersList.contains('vary')) {
+ // 7.1.
+ const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
+
+ // 7.2.
+ for (const fieldValue of fieldValues) {
+ // 7.2.1
+ if (fieldValue === '*') {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Got * vary field value'
+ })
+ }
+ }
+ }
+
+ // 8.
+ if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
+ throw webidl.errors.exception({
+ header: 'Cache.put',
+ message: 'Response body is locked or disturbed'
+ })
+ }
+
+ // 9.
+ const clonedResponse = cloneResponse(innerResponse)
+
+ // 10.
+ const bodyReadPromise = createDeferredPromise()
+
+ // 11.
+ if (innerResponse.body != null) {
+ // 11.1
+ const stream = innerResponse.body.stream
+
+ // 11.2
+ const reader = stream.getReader()
+
+ // 11.3
+ readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
+ } else {
+ bodyReadPromise.resolve(undefined)
+ }
+
+ // 12.
+ /** @type {CacheBatchOperation[]} */
+ const operations = []
+
+ // 13.
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'put', // 14.
+ request: innerRequest, // 15.
+ response: clonedResponse // 16.
+ }
+
+ // 17.
+ operations.push(operation)
+
+ // 19.
+ const bytes = await bodyReadPromise.promise
+
+ if (clonedResponse.body != null) {
+ clonedResponse.body.source = bytes
+ }
+
+ // 19.1
+ const cacheJobPromise = createDeferredPromise()
+
+ // 19.2.1
+ let errorData = null
+
+ // 19.2.2
+ try {
+ this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
+
+ // 19.2.3
+ queueMicrotask(() => {
+ // 19.2.3.1
+ if (errorData === null) {
+ cacheJobPromise.resolve()
+ } else { // 19.2.3.2
+ cacheJobPromise.reject(errorData)
+ }
+ })
+
+ return cacheJobPromise.promise
+ }
+
+ async delete (request, options = {}) {
+ webidl.brandCheck(this, Cache)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })
+
+ request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
+
+ /**
+ * @type {Request}
+ */
+ let r = null
+
+ if (request instanceof Request) {
+ r = request[kState]
+
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return false
+ }
+ } else {
+ assert(typeof request === 'string')
+
+ r = new Request(request)[kState]
+ }
+
+ /** @type {CacheBatchOperation[]} */
+ const operations = []
+
+ /** @type {CacheBatchOperation} */
+ const operation = {
+ type: 'delete',
+ request: r,
+ options
+ }
+
+ operations.push(operation)
+
+ const cacheJobPromise = createDeferredPromise()
+
+ let errorData = null
+ let requestResponses
+
+ try {
+ requestResponses = this.#batchCacheOperations(operations)
+ } catch (e) {
+ errorData = e
+ }
+
+ queueMicrotask(() => {
+ if (errorData === null) {
+ cacheJobPromise.resolve(!!requestResponses?.length)
+ } else {
+ cacheJobPromise.reject(errorData)
+ }
+ })
+
+ return cacheJobPromise.promise
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
+ * @param {any} request
+ * @param {import('../../types/cache').CacheQueryOptions} options
+ * @returns {readonly Request[]}
+ */
+ async keys (request = undefined, options = {}) {
+ webidl.brandCheck(this, Cache)
+
+ if (request !== undefined) request = webidl.converters.RequestInfo(request)
+ options = webidl.converters.CacheQueryOptions(options)
+
+ // 1.
+ let r = null
+
+ // 2.
+ if (request !== undefined) {
+ // 2.1
+ if (request instanceof Request) {
+ // 2.1.1
+ r = request[kState]
+
+ // 2.1.2
+ if (r.method !== 'GET' && !options.ignoreMethod) {
+ return []
+ }
+ } else if (typeof request === 'string') { // 2.2
+ r = new Request(request)[kState]
+ }
+ }
+
+ // 4.
+ const promise = createDeferredPromise()
+
+ // 5.
+ // 5.1
+ const requests = []
+
+ // 5.2
+ if (request === undefined) {
+ // 5.2.1
+ for (const requestResponse of this.#relevantRequestResponseList) {
+ // 5.2.1.1
+ requests.push(requestResponse[0])
+ }
+ } else { // 5.3
+ // 5.3.1
+ const requestResponses = this.#queryCache(r, options)
+
+ // 5.3.2
+ for (const requestResponse of requestResponses) {
+ // 5.3.2.1
+ requests.push(requestResponse[0])
+ }
+ }
+
+ // 5.4
+ queueMicrotask(() => {
+ // 5.4.1
+ const requestList = []
+
+ // 5.4.2
+ for (const request of requests) {
+ const requestObject = new Request('https://a')
+ requestObject[kState] = request
+ requestObject[kHeaders][kHeadersList] = request.headersList
+ requestObject[kHeaders][kGuard] = 'immutable'
+ requestObject[kRealm] = request.client
+
+ // 5.4.2.1
+ requestList.push(requestObject)
+ }
+
+ // 5.4.3
+ promise.resolve(Object.freeze(requestList))
+ })
+
+ return promise.promise
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
+ * @param {CacheBatchOperation[]} operations
+ * @returns {requestResponseList}
+ */
+ #batchCacheOperations (operations) {
+ // 1.
+ const cache = this.#relevantRequestResponseList
+
+ // 2.
+ const backupCache = [...cache]
+
+ // 3.
+ const addedItems = []
+
+ // 4.1
+ const resultList = []
+
+ try {
+ // 4.2
+ for (const operation of operations) {
+ // 4.2.1
+ if (operation.type !== 'delete' && operation.type !== 'put') {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'operation type does not match "delete" or "put"'
+ })
+ }
+
+ // 4.2.2
+ if (operation.type === 'delete' && operation.response != null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'delete operation should not have an associated response'
+ })
+ }
+
+ // 4.2.3
+ if (this.#queryCache(operation.request, operation.options, addedItems).length) {
+ throw new DOMException('???', 'InvalidStateError')
+ }
+
+ // 4.2.4
+ let requestResponses
+
+ // 4.2.5
+ if (operation.type === 'delete') {
+ // 4.2.5.1
+ requestResponses = this.#queryCache(operation.request, operation.options)
+
+ // TODO: the spec is wrong, this is needed to pass WPTs
+ if (requestResponses.length === 0) {
+ return []
+ }
+
+ // 4.2.5.2
+ for (const requestResponse of requestResponses) {
+ const idx = cache.indexOf(requestResponse)
+ assert(idx !== -1)
+
+ // 4.2.5.2.1
+ cache.splice(idx, 1)
+ }
+ } else if (operation.type === 'put') { // 4.2.6
+ // 4.2.6.1
+ if (operation.response == null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'put operation should have an associated response'
+ })
+ }
+
+ // 4.2.6.2
+ const r = operation.request
+
+ // 4.2.6.3
+ if (!urlIsHttpHttpsScheme(r.url)) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'expected http or https scheme'
+ })
+ }
+
+ // 4.2.6.4
+ if (r.method !== 'GET') {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'not get method'
+ })
+ }
+
+ // 4.2.6.5
+ if (operation.options != null) {
+ throw webidl.errors.exception({
+ header: 'Cache.#batchCacheOperations',
+ message: 'options must not be defined'
+ })
+ }
+
+ // 4.2.6.6
+ requestResponses = this.#queryCache(operation.request)
+
+ // 4.2.6.7
+ for (const requestResponse of requestResponses) {
+ const idx = cache.indexOf(requestResponse)
+ assert(idx !== -1)
+
+ // 4.2.6.7.1
+ cache.splice(idx, 1)
+ }
+
+ // 4.2.6.8
+ cache.push([operation.request, operation.response])
+
+ // 4.2.6.10
+ addedItems.push([operation.request, operation.response])
+ }
+
+ // 4.2.7
+ resultList.push([operation.request, operation.response])
+ }
+
+ // 4.3
+ return resultList
+ } catch (e) { // 5.
+ // 5.1
+ this.#relevantRequestResponseList.length = 0
+
+ // 5.2
+ this.#relevantRequestResponseList = backupCache
+
+ // 5.3
+ throw e
+ }
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#query-cache
+ * @param {any} requestQuery
+ * @param {import('../../types/cache').CacheQueryOptions} options
+ * @param {requestResponseList} targetStorage
+ * @returns {requestResponseList}
+ */
+ #queryCache (requestQuery, options, targetStorage) {
+ /** @type {requestResponseList} */
+ const resultList = []
+
+ const storage = targetStorage ?? this.#relevantRequestResponseList
+
+ for (const requestResponse of storage) {
+ const [cachedRequest, cachedResponse] = requestResponse
+ if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
+ resultList.push(requestResponse)
+ }
+ }
+
+ return resultList
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
+ * @param {any} requestQuery
+ * @param {any} request
+ * @param {any | null} response
+ * @param {import('../../types/cache').CacheQueryOptions | undefined} options
+ * @returns {boolean}
+ */
+ #requestMatchesCachedItem (requestQuery, request, response = null, options) {
+ // if (options?.ignoreMethod === false && request.method === 'GET') {
+ // return false
+ // }
+
+ const queryURL = new URL(requestQuery.url)
+
+ const cachedURL = new URL(request.url)
+
+ if (options?.ignoreSearch) {
+ cachedURL.search = ''
+
+ queryURL.search = ''
+ }
+
+ if (!urlEquals(queryURL, cachedURL, true)) {
+ return false
+ }
+
+ if (
+ response == null ||
+ options?.ignoreVary ||
+ !response.headersList.contains('vary')
+ ) {
+ return true
+ }
+
+ const fieldValues = getFieldValues(response.headersList.get('vary'))
+
+ for (const fieldValue of fieldValues) {
+ if (fieldValue === '*') {
+ return false
+ }
+
+ const requestValue = request.headersList.get(fieldValue)
+ const queryValue = requestQuery.headersList.get(fieldValue)
+
+ // If one has the header and the other doesn't, or one has
+ // a different value than the other, return false
+ if (requestValue !== queryValue) {
+ return false
+ }
+ }
+
+ return true
+ }
+}
+
+Object.defineProperties(Cache.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'Cache',
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ matchAll: kEnumerableProperty,
+ add: kEnumerableProperty,
+ addAll: kEnumerableProperty,
+ put: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+})
+
+const cacheQueryOptionConverters = [
+ {
+ key: 'ignoreSearch',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'ignoreMethod',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'ignoreVary',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ }
+]
+
+webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
+
+webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
+ ...cacheQueryOptionConverters,
+ {
+ key: 'cacheName',
+ converter: webidl.converters.DOMString
+ }
+])
+
+webidl.converters.Response = webidl.interfaceConverter(Response)
+
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.RequestInfo
+)
+
+module.exports = {
+ Cache
+}
+
+
+/***/ }),
+
+/***/ 66446:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { kConstruct } = __nccwpck_require__(68652)
+const { Cache } = __nccwpck_require__(40611)
+const { webidl } = __nccwpck_require__(94354)
+const { kEnumerableProperty } = __nccwpck_require__(89500)
+
+class CacheStorage {
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
+ * @type {Map}
+ */
+ async has (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })
+
+ cacheName = webidl.converters.DOMString(cacheName)
+
+ // 2.1.1
+ // 2.2
+ return this.#caches.has(cacheName)
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async open (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })
+
+ cacheName = webidl.converters.DOMString(cacheName)
+
+ // 2.1
+ if (this.#caches.has(cacheName)) {
+ // await caches.open('v1') !== await caches.open('v1')
+
+ // 2.1.1
+ const cache = this.#caches.get(cacheName)
+
+ // 2.1.1.1
+ return new Cache(kConstruct, cache)
+ }
+
+ // 2.2
+ const cache = []
+
+ // 2.3
+ this.#caches.set(cacheName, cache)
+
+ // 2.4
+ return new Cache(kConstruct, cache)
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
+ * @param {string} cacheName
+ * @returns {Promise}
+ */
+ async delete (cacheName) {
+ webidl.brandCheck(this, CacheStorage)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })
+
+ cacheName = webidl.converters.DOMString(cacheName)
+
+ return this.#caches.delete(cacheName)
+ }
+
+ /**
+ * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
+ * @returns {string[]}
+ */
+ async keys () {
+ webidl.brandCheck(this, CacheStorage)
+
+ // 2.1
+ const keys = this.#caches.keys()
+
+ // 2.2
+ return [...keys]
+ }
+}
+
+Object.defineProperties(CacheStorage.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'CacheStorage',
+ configurable: true
+ },
+ match: kEnumerableProperty,
+ has: kEnumerableProperty,
+ open: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ keys: kEnumerableProperty
+})
+
+module.exports = {
+ CacheStorage
+}
+
+
+/***/ }),
+
+/***/ 68652:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+module.exports = {
+ kConstruct: (__nccwpck_require__(68031).kConstruct)
+}
+
+
+/***/ }),
+
+/***/ 71173:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const assert = __nccwpck_require__(42613)
+const { URLSerializer } = __nccwpck_require__(37246)
+const { isValidHeaderName } = __nccwpck_require__(72847)
+
+/**
+ * @see https://url.spec.whatwg.org/#concept-url-equals
+ * @param {URL} A
+ * @param {URL} B
+ * @param {boolean | undefined} excludeFragment
+ * @returns {boolean}
+ */
+function urlEquals (A, B, excludeFragment = false) {
+ const serializedA = URLSerializer(A, excludeFragment)
+
+ const serializedB = URLSerializer(B, excludeFragment)
+
+ return serializedA === serializedB
+}
+
+/**
+ * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
+ * @param {string} header
+ */
+function fieldValues (header) {
+ assert(header !== null)
+
+ const values = []
+
+ for (let value of header.split(',')) {
+ value = value.trim()
+
+ if (!value.length) {
+ continue
+ } else if (!isValidHeaderName(value)) {
+ continue
+ }
+
+ values.push(value)
+ }
+
+ return values
+}
+
+module.exports = {
+ urlEquals,
+ fieldValues
+}
+
+
+/***/ }),
+
+/***/ 45513:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+// @ts-check
+
+
+
+/* global WebAssembly */
+
+const assert = __nccwpck_require__(42613)
+const net = __nccwpck_require__(69278)
+const http = __nccwpck_require__(58611)
+const { pipeline } = __nccwpck_require__(2203)
+const util = __nccwpck_require__(89500)
+const timers = __nccwpck_require__(82576)
+const Request = __nccwpck_require__(69691)
+const DispatcherBase = __nccwpck_require__(52421)
+const {
+ RequestContentLengthMismatchError,
+ ResponseContentLengthMismatchError,
+ InvalidArgumentError,
+ RequestAbortedError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ SocketError,
+ InformationalError,
+ BodyTimeoutError,
+ HTTPParserError,
+ ResponseExceededMaxSizeError,
+ ClientDestroyedError
+} = __nccwpck_require__(53959)
+const buildConnector = __nccwpck_require__(91332)
+const {
+ kUrl,
+ kReset,
+ kServerName,
+ kClient,
+ kBusy,
+ kParser,
+ kConnect,
+ kBlocking,
+ kResuming,
+ kRunning,
+ kPending,
+ kSize,
+ kWriting,
+ kQueue,
+ kConnected,
+ kConnecting,
+ kNeedDrain,
+ kNoRef,
+ kKeepAliveDefaultTimeout,
+ kHostHeader,
+ kPendingIdx,
+ kRunningIdx,
+ kError,
+ kPipelining,
+ kSocket,
+ kKeepAliveTimeoutValue,
+ kMaxHeadersSize,
+ kKeepAliveMaxTimeout,
+ kKeepAliveTimeoutThreshold,
+ kHeadersTimeout,
+ kBodyTimeout,
+ kStrictContentLength,
+ kConnector,
+ kMaxRedirections,
+ kMaxRequests,
+ kCounter,
+ kClose,
+ kDestroy,
+ kDispatch,
+ kInterceptors,
+ kLocalAddress,
+ kMaxResponseSize,
+ kHTTPConnVersion,
+ // HTTP2
+ kHost,
+ kHTTP2Session,
+ kHTTP2SessionState,
+ kHTTP2BuildRequest,
+ kHTTP2CopyHeaders,
+ kHTTP1BuildRequest
+} = __nccwpck_require__(68031)
+
+/** @type {import('http2')} */
+let http2
+try {
+ http2 = __nccwpck_require__(85675)
+} catch {
+ // @ts-ignore
+ http2 = { constants: {} }
+}
+
+const {
+ constants: {
+ HTTP2_HEADER_AUTHORITY,
+ HTTP2_HEADER_METHOD,
+ HTTP2_HEADER_PATH,
+ HTTP2_HEADER_SCHEME,
+ HTTP2_HEADER_CONTENT_LENGTH,
+ HTTP2_HEADER_EXPECT,
+ HTTP2_HEADER_STATUS
+ }
+} = http2
+
+// Experimental
+let h2ExperimentalWarned = false
+
+const FastBuffer = Buffer[Symbol.species]
+
+const kClosedResolve = Symbol('kClosedResolve')
+
+const channels = {}
+
+try {
+ const diagnosticsChannel = __nccwpck_require__(31637)
+ channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')
+ channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')
+ channels.connectError = diagnosticsChannel.channel('undici:client:connectError')
+ channels.connected = diagnosticsChannel.channel('undici:client:connected')
+} catch {
+ channels.sendHeaders = { hasSubscribers: false }
+ channels.beforeConnect = { hasSubscribers: false }
+ channels.connectError = { hasSubscribers: false }
+ channels.connected = { hasSubscribers: false }
+}
+
+/**
+ * @type {import('../types/client').default}
+ */
+class Client extends DispatcherBase {
+ /**
+ *
+ * @param {string|URL} url
+ * @param {import('../types/client').Client.Options} options
+ */
+ constructor (url, {
+ interceptors,
+ maxHeaderSize,
+ headersTimeout,
+ socketTimeout,
+ requestTimeout,
+ connectTimeout,
+ bodyTimeout,
+ idleTimeout,
+ keepAlive,
+ keepAliveTimeout,
+ maxKeepAliveTimeout,
+ keepAliveMaxTimeout,
+ keepAliveTimeoutThreshold,
+ socketPath,
+ pipelining,
+ tls,
+ strictContentLength,
+ maxCachedSessions,
+ maxRedirections,
+ connect,
+ maxRequestsPerClient,
+ localAddress,
+ maxResponseSize,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ // h2
+ allowH2,
+ maxConcurrentStreams
+ } = {}) {
+ super()
+
+ if (keepAlive !== undefined) {
+ throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
+ }
+
+ if (socketTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
+ }
+
+ if (requestTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
+ }
+
+ if (idleTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
+ }
+
+ if (maxKeepAliveTimeout !== undefined) {
+ throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
+ }
+
+ if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
+ throw new InvalidArgumentError('invalid maxHeaderSize')
+ }
+
+ if (socketPath != null && typeof socketPath !== 'string') {
+ throw new InvalidArgumentError('invalid socketPath')
+ }
+
+ if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
+ throw new InvalidArgumentError('invalid connectTimeout')
+ }
+
+ if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
+ throw new InvalidArgumentError('invalid keepAliveTimeout')
+ }
+
+ if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
+ throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
+ }
+
+ if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
+ throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
+ }
+
+ if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
+ }
+
+ if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
+ }
+
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
+ }
+
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
+ }
+
+ if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
+ throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
+ }
+
+ if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
+ throw new InvalidArgumentError('localAddress must be valid string IP address')
+ }
+
+ if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
+ throw new InvalidArgumentError('maxResponseSize must be a positive number')
+ }
+
+ if (
+ autoSelectFamilyAttemptTimeout != null &&
+ (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
+ ) {
+ throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
+ }
+
+ // h2
+ if (allowH2 != null && typeof allowH2 !== 'boolean') {
+ throw new InvalidArgumentError('allowH2 must be a valid boolean value')
+ }
+
+ if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
+ throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')
+ }
+
+ if (typeof connect !== 'function') {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
+ ...connect
+ })
+ }
+
+ this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)
+ ? interceptors.Client
+ : [createRedirectInterceptor({ maxRedirections })]
+ this[kUrl] = util.parseOrigin(url)
+ this[kConnector] = connect
+ this[kSocket] = null
+ this[kPipelining] = pipelining != null ? pipelining : 1
+ this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
+ this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
+ this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
+ this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold
+ this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
+ this[kServerName] = null
+ this[kLocalAddress] = localAddress != null ? localAddress : null
+ this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
+ this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
+ this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
+ this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
+ this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
+ this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
+ this[kMaxRedirections] = maxRedirections
+ this[kMaxRequests] = maxRequestsPerClient
+ this[kClosedResolve] = null
+ this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
+ this[kHTTPConnVersion] = 'h1'
+
+ // HTTP/2
+ this[kHTTP2Session] = null
+ this[kHTTP2SessionState] = !allowH2
+ ? null
+ : {
+ // streams: null, // Fixed queue of streams - For future support of `push`
+ openStreams: 0, // Keep track of them to decide wether or not unref the session
+ maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
+ }
+ this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`
+
+ // kQueue is built up of 3 sections separated by
+ // the kRunningIdx and kPendingIdx indices.
+ // | complete | running | pending |
+ // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
+ // kRunningIdx points to the first running element.
+ // kPendingIdx points to the first pending element.
+ // This implements a fast queue with an amortized
+ // time of O(1).
+
+ this[kQueue] = []
+ this[kRunningIdx] = 0
+ this[kPendingIdx] = 0
+ }
+
+ get pipelining () {
+ return this[kPipelining]
+ }
+
+ set pipelining (value) {
+ this[kPipelining] = value
+ resume(this, true)
+ }
+
+ get [kPending] () {
+ return this[kQueue].length - this[kPendingIdx]
+ }
+
+ get [kRunning] () {
+ return this[kPendingIdx] - this[kRunningIdx]
+ }
+
+ get [kSize] () {
+ return this[kQueue].length - this[kRunningIdx]
+ }
+
+ get [kConnected] () {
+ return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed
+ }
+
+ get [kBusy] () {
+ const socket = this[kSocket]
+ return (
+ (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||
+ (this[kSize] >= (this[kPipelining] || 1)) ||
+ this[kPending] > 0
+ )
+ }
+
+ /* istanbul ignore: only used for test */
+ [kConnect] (cb) {
+ connect(this)
+ this.once('connect', cb)
+ }
+
+ [kDispatch] (opts, handler) {
+ const origin = opts.origin || this[kUrl].origin
+
+ const request = this[kHTTPConnVersion] === 'h2'
+ ? Request[kHTTP2BuildRequest](origin, opts, handler)
+ : Request[kHTTP1BuildRequest](origin, opts, handler)
+
+ this[kQueue].push(request)
+ if (this[kResuming]) {
+ // Do nothing.
+ } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
+ // Wait a tick in case stream/iterator is ended in the same tick.
+ this[kResuming] = 1
+ process.nextTick(resume, this)
+ } else {
+ resume(this, true)
+ }
+
+ if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
+ this[kNeedDrain] = 2
+ }
+
+ return this[kNeedDrain] < 2
+ }
+
+ async [kClose] () {
+ // TODO: for H2 we need to gracefully flush the remaining enqueued
+ // request and close each stream.
+ return new Promise((resolve) => {
+ if (!this[kSize]) {
+ resolve(null)
+ } else {
+ this[kClosedResolve] = resolve
+ }
+ })
+ }
+
+ async [kDestroy] (err) {
+ return new Promise((resolve) => {
+ const requests = this[kQueue].splice(this[kPendingIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(this, request, err)
+ }
+
+ const callback = () => {
+ if (this[kClosedResolve]) {
+ // TODO (fix): Should we error here with ClientDestroyedError?
+ this[kClosedResolve]()
+ this[kClosedResolve] = null
+ }
+ resolve()
+ }
+
+ if (this[kHTTP2Session] != null) {
+ util.destroy(this[kHTTP2Session], err)
+ this[kHTTP2Session] = null
+ this[kHTTP2SessionState] = null
+ }
+
+ if (!this[kSocket]) {
+ queueMicrotask(callback)
+ } else {
+ util.destroy(this[kSocket].on('close', callback), err)
+ }
+
+ resume(this)
+ })
+ }
+}
+
+function onHttp2SessionError (err) {
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+
+ this[kSocket][kError] = err
+
+ onError(this[kClient], err)
+}
+
+function onHttp2FrameError (type, code, id) {
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
+
+ if (id === 0) {
+ this[kSocket][kError] = err
+ onError(this[kClient], err)
+ }
+}
+
+function onHttp2SessionEnd () {
+ util.destroy(this, new SocketError('other side closed'))
+ util.destroy(this[kSocket], new SocketError('other side closed'))
+}
+
+function onHTTP2GoAway (code) {
+ const client = this[kClient]
+ const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`)
+ client[kSocket] = null
+ client[kHTTP2Session] = null
+
+ if (client.destroyed) {
+ assert(this[kPending] === 0)
+
+ // Fail entire queue.
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(this, request, err)
+ }
+ } else if (client[kRunning] > 0) {
+ // Fail head of pipeline.
+ const request = client[kQueue][client[kRunningIdx]]
+ client[kQueue][client[kRunningIdx]++] = null
+
+ errorRequest(client, request, err)
+ }
+
+ client[kPendingIdx] = client[kRunningIdx]
+
+ assert(client[kRunning] === 0)
+
+ client.emit('disconnect',
+ client[kUrl],
+ [client],
+ err
+ )
+
+ resume(client)
+}
+
+const constants = __nccwpck_require__(40748)
+const createRedirectInterceptor = __nccwpck_require__(99299)
+const EMPTY_BUF = Buffer.alloc(0)
+
+async function lazyllhttp () {
+ const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(63922) : undefined
+
+ let mod
+ try {
+ mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(53742), 'base64'))
+ } catch (e) {
+ /* istanbul ignore next */
+
+ // We could check if the error was caused by the simd option not
+ // being enabled, but the occurring of this other error
+ // * https://github.com/emscripten-core/emscripten/issues/11495
+ // got me to remove that check to avoid breaking Node 12.
+ mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(63922), 'base64'))
+ }
+
+ return await WebAssembly.instantiate(mod, {
+ env: {
+ /* eslint-disable camelcase */
+
+ wasm_on_url: (p, at, len) => {
+ /* istanbul ignore next */
+ return 0
+ },
+ wasm_on_status: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_message_begin: (p) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onMessageBegin() || 0
+ },
+ wasm_on_header_field: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_header_value: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
+ },
+ wasm_on_body: (p, at, len) => {
+ assert.strictEqual(currentParser.ptr, p)
+ const start = at - currentBufferPtr + currentBufferRef.byteOffset
+ return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
+ },
+ wasm_on_message_complete: (p) => {
+ assert.strictEqual(currentParser.ptr, p)
+ return currentParser.onMessageComplete() || 0
+ }
+
+ /* eslint-enable camelcase */
+ }
+ })
+}
+
+let llhttpInstance = null
+let llhttpPromise = lazyllhttp()
+llhttpPromise.catch()
+
+let currentParser = null
+let currentBufferRef = null
+let currentBufferSize = 0
+let currentBufferPtr = null
+
+const TIMEOUT_HEADERS = 1
+const TIMEOUT_BODY = 2
+const TIMEOUT_IDLE = 3
+
+class Parser {
+ constructor (client, socket, { exports }) {
+ assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
+
+ this.llhttp = exports
+ this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
+ this.client = client
+ this.socket = socket
+ this.timeout = null
+ this.timeoutValue = null
+ this.timeoutType = null
+ this.statusCode = null
+ this.statusText = ''
+ this.upgrade = false
+ this.headers = []
+ this.headersSize = 0
+ this.headersMaxSize = client[kMaxHeadersSize]
+ this.shouldKeepAlive = false
+ this.paused = false
+ this.resume = this.resume.bind(this)
+
+ this.bytesRead = 0
+
+ this.keepAlive = ''
+ this.contentLength = ''
+ this.connection = ''
+ this.maxResponseSize = client[kMaxResponseSize]
+ }
+
+ setTimeout (value, type) {
+ this.timeoutType = type
+ if (value !== this.timeoutValue) {
+ timers.clearTimeout(this.timeout)
+ if (value) {
+ this.timeout = timers.setTimeout(onParserTimeout, value, this)
+ // istanbul ignore else: only for jest
+ if (this.timeout.unref) {
+ this.timeout.unref()
+ }
+ } else {
+ this.timeout = null
+ }
+ this.timeoutValue = value
+ } else if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
+ }
+
+ resume () {
+ if (this.socket.destroyed || !this.paused) {
+ return
+ }
+
+ assert(this.ptr != null)
+ assert(currentParser == null)
+
+ this.llhttp.llhttp_resume(this.ptr)
+
+ assert(this.timeoutType === TIMEOUT_BODY)
+ if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
+
+ this.paused = false
+ this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
+ this.readMore()
+ }
+
+ readMore () {
+ while (!this.paused && this.ptr) {
+ const chunk = this.socket.read()
+ if (chunk === null) {
+ break
+ }
+ this.execute(chunk)
+ }
+ }
+
+ execute (data) {
+ assert(this.ptr != null)
+ assert(currentParser == null)
+ assert(!this.paused)
+
+ const { socket, llhttp } = this
+
+ if (data.length > currentBufferSize) {
+ if (currentBufferPtr) {
+ llhttp.free(currentBufferPtr)
+ }
+ currentBufferSize = Math.ceil(data.length / 4096) * 4096
+ currentBufferPtr = llhttp.malloc(currentBufferSize)
+ }
+
+ new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
+
+ // Call `execute` on the wasm parser.
+ // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
+ // and finally the length of bytes to parse.
+ // The return value is an error code or `constants.ERROR.OK`.
+ try {
+ let ret
+
+ try {
+ currentBufferRef = data
+ currentParser = this
+ ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)
+ /* eslint-disable-next-line no-useless-catch */
+ } catch (err) {
+ /* istanbul ignore next: difficult to make a test case for */
+ throw err
+ } finally {
+ currentParser = null
+ currentBufferRef = null
+ }
+
+ const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
+
+ if (ret === constants.ERROR.PAUSED_UPGRADE) {
+ this.onUpgrade(data.slice(offset))
+ } else if (ret === constants.ERROR.PAUSED) {
+ this.paused = true
+ socket.unshift(data.slice(offset))
+ } else if (ret !== constants.ERROR.OK) {
+ const ptr = llhttp.llhttp_get_error_reason(this.ptr)
+ let message = ''
+ /* istanbul ignore else: difficult to make a test case for */
+ if (ptr) {
+ const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
+ message =
+ 'Response does not match the HTTP/1.1 protocol (' +
+ Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
+ ')'
+ }
+ throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
+ }
+ } catch (err) {
+ util.destroy(socket, err)
+ }
+ }
+
+ destroy () {
+ assert(this.ptr != null)
+ assert(currentParser == null)
+
+ this.llhttp.llhttp_free(this.ptr)
+ this.ptr = null
+
+ timers.clearTimeout(this.timeout)
+ this.timeout = null
+ this.timeoutValue = null
+ this.timeoutType = null
+
+ this.paused = false
+ }
+
+ onStatus (buf) {
+ this.statusText = buf.toString()
+ }
+
+ onMessageBegin () {
+ const { socket, client } = this
+
+ /* istanbul ignore next: difficult to make a test case for */
+ if (socket.destroyed) {
+ return -1
+ }
+
+ const request = client[kQueue][client[kRunningIdx]]
+ if (!request) {
+ return -1
+ }
+ }
+
+ onHeaderField (buf) {
+ const len = this.headers.length
+
+ if ((len & 1) === 0) {
+ this.headers.push(buf)
+ } else {
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ }
+
+ this.trackHeader(buf.length)
+ }
+
+ onHeaderValue (buf) {
+ let len = this.headers.length
+
+ if ((len & 1) === 1) {
+ this.headers.push(buf)
+ len += 1
+ } else {
+ this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ }
+
+ const key = this.headers[len - 2]
+ if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {
+ this.keepAlive += buf.toString()
+ } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {
+ this.connection += buf.toString()
+ } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {
+ this.contentLength += buf.toString()
+ }
+
+ this.trackHeader(buf.length)
+ }
+
+ trackHeader (len) {
+ this.headersSize += len
+ if (this.headersSize >= this.headersMaxSize) {
+ util.destroy(this.socket, new HeadersOverflowError())
+ }
+ }
+
+ onUpgrade (head) {
+ const { upgrade, client, socket, headers, statusCode } = this
+
+ assert(upgrade)
+
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
+
+ assert(!socket.destroyed)
+ assert(socket === client[kSocket])
+ assert(!this.paused)
+ assert(request.upgrade || request.method === 'CONNECT')
+
+ this.statusCode = null
+ this.statusText = ''
+ this.shouldKeepAlive = null
+
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
+
+ socket.unshift(head)
+
+ socket[kParser].destroy()
+ socket[kParser] = null
+
+ socket[kClient] = null
+ socket[kError] = null
+ socket
+ .removeListener('error', onSocketError)
+ .removeListener('readable', onSocketReadable)
+ .removeListener('end', onSocketEnd)
+ .removeListener('close', onSocketClose)
+
+ client[kSocket] = null
+ client[kQueue][client[kRunningIdx]++] = null
+ client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
+
+ try {
+ request.onUpgrade(statusCode, headers, socket)
+ } catch (err) {
+ util.destroy(socket, err)
+ }
+
+ resume(client)
+ }
+
+ onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
+ const { client, socket, headers, statusText } = this
+
+ /* istanbul ignore next: difficult to make a test case for */
+ if (socket.destroyed) {
+ return -1
+ }
+
+ const request = client[kQueue][client[kRunningIdx]]
+
+ /* istanbul ignore next: difficult to make a test case for */
+ if (!request) {
+ return -1
+ }
+
+ assert(!this.upgrade)
+ assert(this.statusCode < 200)
+
+ if (statusCode === 100) {
+ util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
+ return -1
+ }
+
+ /* this can only happen if server is misbehaving */
+ if (upgrade && !request.upgrade) {
+ util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
+ return -1
+ }
+
+ assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)
+
+ this.statusCode = statusCode
+ this.shouldKeepAlive = (
+ shouldKeepAlive ||
+ // Override llhttp value which does not allow keepAlive for HEAD.
+ (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
+ )
+
+ if (this.statusCode >= 200) {
+ const bodyTimeout = request.bodyTimeout != null
+ ? request.bodyTimeout
+ : client[kBodyTimeout]
+ this.setTimeout(bodyTimeout, TIMEOUT_BODY)
+ } else if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
+
+ if (request.method === 'CONNECT') {
+ assert(client[kRunning] === 1)
+ this.upgrade = true
+ return 2
+ }
+
+ if (upgrade) {
+ assert(client[kRunning] === 1)
+ this.upgrade = true
+ return 2
+ }
+
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
+
+ if (this.shouldKeepAlive && client[kPipelining]) {
+ const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
+
+ if (keepAliveTimeout != null) {
+ const timeout = Math.min(
+ keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
+ client[kKeepAliveMaxTimeout]
+ )
+ if (timeout <= 0) {
+ socket[kReset] = true
+ } else {
+ client[kKeepAliveTimeoutValue] = timeout
+ }
+ } else {
+ client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
+ }
+ } else {
+ // Stop more requests from being dispatched.
+ socket[kReset] = true
+ }
+
+ const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
+
+ if (request.aborted) {
+ return -1
+ }
+
+ if (request.method === 'HEAD') {
+ return 1
+ }
+
+ if (statusCode < 200) {
+ return 1
+ }
+
+ if (socket[kBlocking]) {
+ socket[kBlocking] = false
+ resume(client)
+ }
+
+ return pause ? constants.ERROR.PAUSED : 0
+ }
+
+ onBody (buf) {
+ const { client, socket, statusCode, maxResponseSize } = this
+
+ if (socket.destroyed) {
+ return -1
+ }
+
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
+
+ assert.strictEqual(this.timeoutType, TIMEOUT_BODY)
+ if (this.timeout) {
+ // istanbul ignore else: only for jest
+ if (this.timeout.refresh) {
+ this.timeout.refresh()
+ }
+ }
+
+ assert(statusCode >= 200)
+
+ if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
+ util.destroy(socket, new ResponseExceededMaxSizeError())
+ return -1
+ }
+
+ this.bytesRead += buf.length
+
+ if (request.onData(buf) === false) {
+ return constants.ERROR.PAUSED
+ }
+ }
+
+ onMessageComplete () {
+ const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
+
+ if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
+ return -1
+ }
+
+ if (upgrade) {
+ return
+ }
+
+ const request = client[kQueue][client[kRunningIdx]]
+ assert(request)
+
+ assert(statusCode >= 100)
+
+ this.statusCode = null
+ this.statusText = ''
+ this.bytesRead = 0
+ this.contentLength = ''
+ this.keepAlive = ''
+ this.connection = ''
+
+ assert(this.headers.length % 2 === 0)
+ this.headers = []
+ this.headersSize = 0
+
+ if (statusCode < 200) {
+ return
+ }
+
+ /* istanbul ignore next: should be handled by llhttp? */
+ if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
+ util.destroy(socket, new ResponseContentLengthMismatchError())
+ return -1
+ }
+
+ request.onComplete(headers)
+
+ client[kQueue][client[kRunningIdx]++] = null
+
+ if (socket[kWriting]) {
+ assert.strictEqual(client[kRunning], 0)
+ // Response completed before request.
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (!shouldKeepAlive) {
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (socket[kReset] && client[kRunning] === 0) {
+ // Destroy socket once all requests have completed.
+ // The request at the tail of the pipeline is the one
+ // that requested reset and no further requests should
+ // have been queued since then.
+ util.destroy(socket, new InformationalError('reset'))
+ return constants.ERROR.PAUSED
+ } else if (client[kPipelining] === 1) {
+ // We must wait a full event loop cycle to reuse this socket to make sure
+ // that non-spec compliant servers are not closing the connection even if they
+ // said they won't.
+ setImmediate(resume, client)
+ } else {
+ resume(client)
+ }
+ }
+}
+
+function onParserTimeout (parser) {
+ const { socket, timeoutType, client } = parser
+
+ /* istanbul ignore else */
+ if (timeoutType === TIMEOUT_HEADERS) {
+ if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
+ assert(!parser.paused, 'cannot be paused while waiting for headers')
+ util.destroy(socket, new HeadersTimeoutError())
+ }
+ } else if (timeoutType === TIMEOUT_BODY) {
+ if (!parser.paused) {
+ util.destroy(socket, new BodyTimeoutError())
+ }
+ } else if (timeoutType === TIMEOUT_IDLE) {
+ assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
+ util.destroy(socket, new InformationalError('socket idle timeout'))
+ }
+}
+
+function onSocketReadable () {
+ const { [kParser]: parser } = this
+ if (parser) {
+ parser.readMore()
+ }
+}
+
+function onSocketError (err) {
+ const { [kClient]: client, [kParser]: parser } = this
+
+ assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+
+ if (client[kHTTPConnVersion] !== 'h2') {
+ // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
+ // to the user.
+ if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so for as a valid response.
+ parser.onMessageComplete()
+ return
+ }
+ }
+
+ this[kError] = err
+
+ onError(this[kClient], err)
+}
+
+function onError (client, err) {
+ if (
+ client[kRunning] === 0 &&
+ err.code !== 'UND_ERR_INFO' &&
+ err.code !== 'UND_ERR_SOCKET'
+ ) {
+ // Error is not caused by running request and not a recoverable
+ // socket error.
+
+ assert(client[kPendingIdx] === client[kRunningIdx])
+
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(client, request, err)
+ }
+ assert(client[kSize] === 0)
+ }
+}
+
+function onSocketEnd () {
+ const { [kParser]: parser, [kClient]: client } = this
+
+ if (client[kHTTPConnVersion] !== 'h2') {
+ if (parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so far as a valid response.
+ parser.onMessageComplete()
+ return
+ }
+ }
+
+ util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
+}
+
+function onSocketClose () {
+ const { [kClient]: client, [kParser]: parser } = this
+
+ if (client[kHTTPConnVersion] === 'h1' && parser) {
+ if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
+ // We treat all incoming data so far as a valid response.
+ parser.onMessageComplete()
+ }
+
+ this[kParser].destroy()
+ this[kParser] = null
+ }
+
+ const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
+
+ client[kSocket] = null
+
+ if (client.destroyed) {
+ assert(client[kPending] === 0)
+
+ // Fail entire queue.
+ const requests = client[kQueue].splice(client[kRunningIdx])
+ for (let i = 0; i < requests.length; i++) {
+ const request = requests[i]
+ errorRequest(client, request, err)
+ }
+ } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
+ // Fail head of pipeline.
+ const request = client[kQueue][client[kRunningIdx]]
+ client[kQueue][client[kRunningIdx]++] = null
+
+ errorRequest(client, request, err)
+ }
+
+ client[kPendingIdx] = client[kRunningIdx]
+
+ assert(client[kRunning] === 0)
+
+ client.emit('disconnect', client[kUrl], [client], err)
+
+ resume(client)
+}
+
+async function connect (client) {
+ assert(!client[kConnecting])
+ assert(!client[kSocket])
+
+ let { host, hostname, protocol, port } = client[kUrl]
+
+ // Resolve ipv6
+ if (hostname[0] === '[') {
+ const idx = hostname.indexOf(']')
+
+ assert(idx !== -1)
+ const ip = hostname.substring(1, idx)
+
+ assert(net.isIP(ip))
+ hostname = ip
+ }
+
+ client[kConnecting] = true
+
+ if (channels.beforeConnect.hasSubscribers) {
+ channels.beforeConnect.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector]
+ })
+ }
+
+ try {
+ const socket = await new Promise((resolve, reject) => {
+ client[kConnector]({
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ }, (err, socket) => {
+ if (err) {
+ reject(err)
+ } else {
+ resolve(socket)
+ }
+ })
+ })
+
+ if (client.destroyed) {
+ util.destroy(socket.on('error', () => {}), new ClientDestroyedError())
+ return
+ }
+
+ client[kConnecting] = false
+
+ assert(socket)
+
+ const isH2 = socket.alpnProtocol === 'h2'
+ if (isH2) {
+ if (!h2ExperimentalWarned) {
+ h2ExperimentalWarned = true
+ process.emitWarning('H2 support is experimental, expect them to change at any time.', {
+ code: 'UNDICI-H2'
+ })
+ }
+
+ const session = http2.connect(client[kUrl], {
+ createConnection: () => socket,
+ peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams
+ })
+
+ client[kHTTPConnVersion] = 'h2'
+ session[kClient] = client
+ session[kSocket] = socket
+ session.on('error', onHttp2SessionError)
+ session.on('frameError', onHttp2FrameError)
+ session.on('end', onHttp2SessionEnd)
+ session.on('goaway', onHTTP2GoAway)
+ session.on('close', onSocketClose)
+ session.unref()
+
+ client[kHTTP2Session] = session
+ socket[kHTTP2Session] = session
+ } else {
+ if (!llhttpInstance) {
+ llhttpInstance = await llhttpPromise
+ llhttpPromise = null
+ }
+
+ socket[kNoRef] = false
+ socket[kWriting] = false
+ socket[kReset] = false
+ socket[kBlocking] = false
+ socket[kParser] = new Parser(client, socket, llhttpInstance)
+ }
+
+ socket[kCounter] = 0
+ socket[kMaxRequests] = client[kMaxRequests]
+ socket[kClient] = client
+ socket[kError] = null
+
+ socket
+ .on('error', onSocketError)
+ .on('readable', onSocketReadable)
+ .on('end', onSocketEnd)
+ .on('close', onSocketClose)
+
+ client[kSocket] = socket
+
+ if (channels.connected.hasSubscribers) {
+ channels.connected.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ socket
+ })
+ }
+ client.emit('connect', client[kUrl], [client])
+ } catch (err) {
+ if (client.destroyed) {
+ return
+ }
+
+ client[kConnecting] = false
+
+ if (channels.connectError.hasSubscribers) {
+ channels.connectError.publish({
+ connectParams: {
+ host,
+ hostname,
+ protocol,
+ port,
+ servername: client[kServerName],
+ localAddress: client[kLocalAddress]
+ },
+ connector: client[kConnector],
+ error: err
+ })
+ }
+
+ if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
+ assert(client[kRunning] === 0)
+ while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
+ const request = client[kQueue][client[kPendingIdx]++]
+ errorRequest(client, request, err)
+ }
+ } else {
+ onError(client, err)
+ }
+
+ client.emit('connectionError', client[kUrl], [client], err)
+ }
+
+ resume(client)
+}
+
+function emitDrain (client) {
+ client[kNeedDrain] = 0
+ client.emit('drain', client[kUrl], [client])
+}
+
+function resume (client, sync) {
+ if (client[kResuming] === 2) {
+ return
+ }
+
+ client[kResuming] = 2
+
+ _resume(client, sync)
+ client[kResuming] = 0
+
+ if (client[kRunningIdx] > 256) {
+ client[kQueue].splice(0, client[kRunningIdx])
+ client[kPendingIdx] -= client[kRunningIdx]
+ client[kRunningIdx] = 0
+ }
+}
+
+function _resume (client, sync) {
+ while (true) {
+ if (client.destroyed) {
+ assert(client[kPending] === 0)
+ return
+ }
+
+ if (client[kClosedResolve] && !client[kSize]) {
+ client[kClosedResolve]()
+ client[kClosedResolve] = null
+ return
+ }
+
+ const socket = client[kSocket]
+
+ if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {
+ if (client[kSize] === 0) {
+ if (!socket[kNoRef] && socket.unref) {
+ socket.unref()
+ socket[kNoRef] = true
+ }
+ } else if (socket[kNoRef] && socket.ref) {
+ socket.ref()
+ socket[kNoRef] = false
+ }
+
+ if (client[kSize] === 0) {
+ if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
+ socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)
+ }
+ } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
+ if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
+ const request = client[kQueue][client[kRunningIdx]]
+ const headersTimeout = request.headersTimeout != null
+ ? request.headersTimeout
+ : client[kHeadersTimeout]
+ socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
+ }
+ }
+ }
+
+ if (client[kBusy]) {
+ client[kNeedDrain] = 2
+ } else if (client[kNeedDrain] === 2) {
+ if (sync) {
+ client[kNeedDrain] = 1
+ process.nextTick(emitDrain, client)
+ } else {
+ emitDrain(client)
+ }
+ continue
+ }
+
+ if (client[kPending] === 0) {
+ return
+ }
+
+ if (client[kRunning] >= (client[kPipelining] || 1)) {
+ return
+ }
+
+ const request = client[kQueue][client[kPendingIdx]]
+
+ if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
+ if (client[kRunning] > 0) {
+ return
+ }
+
+ client[kServerName] = request.servername
+
+ if (socket && socket.servername !== request.servername) {
+ util.destroy(socket, new InformationalError('servername changed'))
+ return
+ }
+ }
+
+ if (client[kConnecting]) {
+ return
+ }
+
+ if (!socket && !client[kHTTP2Session]) {
+ connect(client)
+ return
+ }
+
+ if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {
+ return
+ }
+
+ if (client[kRunning] > 0 && !request.idempotent) {
+ // Non-idempotent request cannot be retried.
+ // Ensure that no other requests are inflight and
+ // could cause failure.
+ return
+ }
+
+ if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
+ // Don't dispatch an upgrade until all preceding requests have completed.
+ // A misbehaving server might upgrade the connection before all pipelined
+ // request has completed.
+ return
+ }
+
+ if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
+ (util.isStream(request.body) || util.isAsyncIterable(request.body))) {
+ // Request with stream or iterator body can error while other requests
+ // are inflight and indirectly error those as well.
+ // Ensure this doesn't happen by waiting for inflight
+ // to complete before dispatching.
+
+ // Request with stream or iterator body cannot be retried.
+ // Ensure that no other requests are inflight and
+ // could cause failure.
+ return
+ }
+
+ if (!request.aborted && write(client, request)) {
+ client[kPendingIdx]++
+ } else {
+ client[kQueue].splice(client[kPendingIdx], 1)
+ }
+ }
+}
+
+// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
+function shouldSendContentLength (method) {
+ return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
+}
+
+function write (client, request) {
+ if (client[kHTTPConnVersion] === 'h2') {
+ writeH2(client, client[kHTTP2Session], request)
+ return
+ }
+
+ const { body, method, path, host, upgrade, headers, blocking, reset } = request
+
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
+
+ // Sending a payload body on a request that does not
+ // expect it can cause undefined behavior on some
+ // servers and corrupt connection state. Do not
+ // re-use the connection for further requests.
+
+ const expectsPayload = (
+ method === 'PUT' ||
+ method === 'POST' ||
+ method === 'PATCH'
+ )
+
+ if (body && typeof body.read === 'function') {
+ // Try to read EOF in order to get length.
+ body.read(0)
+ }
+
+ const bodyLength = util.bodyLength(body)
+
+ let contentLength = bodyLength
+
+ if (contentLength === null) {
+ contentLength = request.contentLength
+ }
+
+ if (contentLength === 0 && !expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD NOT send a Content-Length header field when
+ // the request message does not contain a payload body and the method
+ // semantics do not anticipate such a body.
+
+ contentLength = null
+ }
+
+ // https://github.com/nodejs/undici/issues/2046
+ // A user agent may send a Content-Length header with 0 value, this should be allowed.
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
+ if (client[kStrictContentLength]) {
+ errorRequest(client, request, new RequestContentLengthMismatchError())
+ return false
+ }
+
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
+
+ const socket = client[kSocket]
+
+ try {
+ request.onConnect((err) => {
+ if (request.aborted || request.completed) {
+ return
+ }
+
+ errorRequest(client, request, err || new RequestAbortedError())
+
+ util.destroy(socket, new InformationalError('aborted'))
+ })
+ } catch (err) {
+ errorRequest(client, request, err)
+ }
+
+ if (request.aborted) {
+ return false
+ }
+
+ if (method === 'HEAD') {
+ // https://github.com/mcollina/undici/issues/258
+ // Close after a HEAD request to interop with misbehaving servers
+ // that may send a body in the response.
+
+ socket[kReset] = true
+ }
+
+ if (upgrade || method === 'CONNECT') {
+ // On CONNECT or upgrade, block pipeline from dispatching further
+ // requests on this connection.
+
+ socket[kReset] = true
+ }
+
+ if (reset != null) {
+ socket[kReset] = reset
+ }
+
+ if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
+ socket[kReset] = true
+ }
+
+ if (blocking) {
+ socket[kBlocking] = true
+ }
+
+ let header = `${method} ${path} HTTP/1.1\r\n`
+
+ if (typeof host === 'string') {
+ header += `host: ${host}\r\n`
+ } else {
+ header += client[kHostHeader]
+ }
+
+ if (upgrade) {
+ header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
+ } else if (client[kPipelining] && !socket[kReset]) {
+ header += 'connection: keep-alive\r\n'
+ } else {
+ header += 'connection: close\r\n'
+ }
+
+ if (headers) {
+ header += headers
+ }
+
+ if (channels.sendHeaders.hasSubscribers) {
+ channels.sendHeaders.publish({ request, headers: header, socket })
+ }
+
+ /* istanbul ignore else: assertion */
+ if (!body || bodyLength === 0) {
+ if (contentLength === 0) {
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
+ } else {
+ assert(contentLength === null, 'no body must not have content length')
+ socket.write(`${header}\r\n`, 'latin1')
+ }
+ request.onRequestSent()
+ } else if (util.isBuffer(body)) {
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
+
+ socket.cork()
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ socket.write(body)
+ socket.uncork()
+ request.onBodySent(body)
+ request.onRequestSent()
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === 'function') {
+ writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })
+ } else {
+ writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })
+ }
+ } else if (util.isStream(body)) {
+ writeStream({ body, client, request, socket, contentLength, header, expectsPayload })
+ } else if (util.isIterable(body)) {
+ writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })
+ } else {
+ assert(false)
+ }
+
+ return true
+}
+
+function writeH2 (client, session, request) {
+ const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
+
+ let headers
+ if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())
+ else headers = reqHeaders
+
+ if (upgrade) {
+ errorRequest(client, request, new Error('Upgrade not supported for H2'))
+ return false
+ }
+
+ try {
+ // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?
+ request.onConnect((err) => {
+ if (request.aborted || request.completed) {
+ return
+ }
+
+ errorRequest(client, request, err || new RequestAbortedError())
+ })
+ } catch (err) {
+ errorRequest(client, request, err)
+ }
+
+ if (request.aborted) {
+ return false
+ }
+
+ /** @type {import('node:http2').ClientHttp2Stream} */
+ let stream
+ const h2State = client[kHTTP2SessionState]
+
+ headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]
+ headers[HTTP2_HEADER_METHOD] = method
+
+ if (method === 'CONNECT') {
+ session.ref()
+ // we are already connected, streams are pending, first request
+ // will create a new stream. We trigger a request to create the stream and wait until
+ // `ready` event is triggered
+ // We disabled endStream to allow the user to write to the stream
+ stream = session.request(headers, { endStream: false, signal })
+
+ if (stream.id && !stream.pending) {
+ request.onUpgrade(null, null, stream)
+ ++h2State.openStreams
+ } else {
+ stream.once('ready', () => {
+ request.onUpgrade(null, null, stream)
+ ++h2State.openStreams
+ })
+ }
+
+ stream.once('close', () => {
+ h2State.openStreams -= 1
+ // TODO(HTTP/2): unref only if current streams count is 0
+ if (h2State.openStreams === 0) session.unref()
+ })
+
+ return true
+ }
+
+ // https://tools.ietf.org/html/rfc7540#section-8.3
+ // :path and :scheme headers must be omited when sending CONNECT
+
+ headers[HTTP2_HEADER_PATH] = path
+ headers[HTTP2_HEADER_SCHEME] = 'https'
+
+ // https://tools.ietf.org/html/rfc7231#section-4.3.1
+ // https://tools.ietf.org/html/rfc7231#section-4.3.2
+ // https://tools.ietf.org/html/rfc7231#section-4.3.5
+
+ // Sending a payload body on a request that does not
+ // expect it can cause undefined behavior on some
+ // servers and corrupt connection state. Do not
+ // re-use the connection for further requests.
+
+ const expectsPayload = (
+ method === 'PUT' ||
+ method === 'POST' ||
+ method === 'PATCH'
+ )
+
+ if (body && typeof body.read === 'function') {
+ // Try to read EOF in order to get length.
+ body.read(0)
+ }
+
+ let contentLength = util.bodyLength(body)
+
+ if (contentLength == null) {
+ contentLength = request.contentLength
+ }
+
+ if (contentLength === 0 || !expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD NOT send a Content-Length header field when
+ // the request message does not contain a payload body and the method
+ // semantics do not anticipate such a body.
+
+ contentLength = null
+ }
+
+ // https://github.com/nodejs/undici/issues/2046
+ // A user agent may send a Content-Length header with 0 value, this should be allowed.
+ if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
+ if (client[kStrictContentLength]) {
+ errorRequest(client, request, new RequestContentLengthMismatchError())
+ return false
+ }
+
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
+
+ if (contentLength != null) {
+ assert(body, 'no body must not have content length')
+ headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
+ }
+
+ session.ref()
+
+ const shouldEndStream = method === 'GET' || method === 'HEAD'
+ if (expectContinue) {
+ headers[HTTP2_HEADER_EXPECT] = '100-continue'
+ stream = session.request(headers, { endStream: shouldEndStream, signal })
+
+ stream.once('continue', writeBodyH2)
+ } else {
+ stream = session.request(headers, {
+ endStream: shouldEndStream,
+ signal
+ })
+ writeBodyH2()
+ }
+
+ // Increment counter as we have new several streams open
+ ++h2State.openStreams
+
+ stream.once('response', headers => {
+ const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
+
+ if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {
+ stream.pause()
+ }
+ })
+
+ stream.once('end', () => {
+ request.onComplete([])
+ })
+
+ stream.on('data', (chunk) => {
+ if (request.onData(chunk) === false) {
+ stream.pause()
+ }
+ })
+
+ stream.once('close', () => {
+ h2State.openStreams -= 1
+ // TODO(HTTP/2): unref only if current streams count is 0
+ if (h2State.openStreams === 0) {
+ session.unref()
+ }
+ })
+
+ stream.once('error', function (err) {
+ if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
+ h2State.streams -= 1
+ util.destroy(stream, err)
+ }
+ })
+
+ stream.once('frameError', (type, code) => {
+ const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
+ errorRequest(client, request, err)
+
+ if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
+ h2State.streams -= 1
+ util.destroy(stream, err)
+ }
+ })
+
+ // stream.on('aborted', () => {
+ // // TODO(HTTP/2): Support aborted
+ // })
+
+ // stream.on('timeout', () => {
+ // // TODO(HTTP/2): Support timeout
+ // })
+
+ // stream.on('push', headers => {
+ // // TODO(HTTP/2): Suppor push
+ // })
+
+ // stream.on('trailers', headers => {
+ // // TODO(HTTP/2): Support trailers
+ // })
+
+ return true
+
+ function writeBodyH2 () {
+ /* istanbul ignore else: assertion */
+ if (!body) {
+ request.onRequestSent()
+ } else if (util.isBuffer(body)) {
+ assert(contentLength === body.byteLength, 'buffer body must have content length')
+ stream.cork()
+ stream.write(body)
+ stream.uncork()
+ stream.end()
+ request.onBodySent(body)
+ request.onRequestSent()
+ } else if (util.isBlobLike(body)) {
+ if (typeof body.stream === 'function') {
+ writeIterable({
+ client,
+ request,
+ contentLength,
+ h2stream: stream,
+ expectsPayload,
+ body: body.stream(),
+ socket: client[kSocket],
+ header: ''
+ })
+ } else {
+ writeBlob({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ h2stream: stream,
+ header: '',
+ socket: client[kSocket]
+ })
+ }
+ } else if (util.isStream(body)) {
+ writeStream({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ socket: client[kSocket],
+ h2stream: stream,
+ header: ''
+ })
+ } else if (util.isIterable(body)) {
+ writeIterable({
+ body,
+ client,
+ request,
+ contentLength,
+ expectsPayload,
+ header: '',
+ h2stream: stream,
+ socket: client[kSocket]
+ })
+ } else {
+ assert(false)
+ }
+ }
+}
+
+function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
+
+ if (client[kHTTPConnVersion] === 'h2') {
+ // For HTTP/2, is enough to pipe the stream
+ const pipe = pipeline(
+ body,
+ h2stream,
+ (err) => {
+ if (err) {
+ util.destroy(body, err)
+ util.destroy(h2stream, err)
+ } else {
+ request.onRequestSent()
+ }
+ }
+ )
+
+ pipe.on('data', onPipeData)
+ pipe.once('end', () => {
+ pipe.removeListener('data', onPipeData)
+ util.destroy(pipe)
+ })
+
+ function onPipeData (chunk) {
+ request.onBodySent(chunk)
+ }
+
+ return
+ }
+
+ let finished = false
+
+ const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
+
+ const onData = function (chunk) {
+ if (finished) {
+ return
+ }
+
+ try {
+ if (!writer.write(chunk) && this.pause) {
+ this.pause()
+ }
+ } catch (err) {
+ util.destroy(this, err)
+ }
+ }
+ const onDrain = function () {
+ if (finished) {
+ return
+ }
+
+ if (body.resume) {
+ body.resume()
+ }
+ }
+ const onAbort = function () {
+ if (finished) {
+ return
+ }
+ const err = new RequestAbortedError()
+ queueMicrotask(() => onFinished(err))
+ }
+ const onFinished = function (err) {
+ if (finished) {
+ return
+ }
+
+ finished = true
+
+ assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
+
+ socket
+ .off('drain', onDrain)
+ .off('error', onFinished)
+
+ body
+ .removeListener('data', onData)
+ .removeListener('end', onFinished)
+ .removeListener('error', onFinished)
+ .removeListener('close', onAbort)
+
+ if (!err) {
+ try {
+ writer.end()
+ } catch (er) {
+ err = er
+ }
+ }
+
+ writer.destroy(err)
+
+ if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
+ util.destroy(body, err)
+ } else {
+ util.destroy(body)
+ }
+ }
+
+ body
+ .on('data', onData)
+ .on('end', onFinished)
+ .on('error', onFinished)
+ .on('close', onAbort)
+
+ if (body.resume) {
+ body.resume()
+ }
+
+ socket
+ .on('drain', onDrain)
+ .on('error', onFinished)
+}
+
+async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength === body.size, 'blob body must have content length')
+
+ const isH2 = client[kHTTPConnVersion] === 'h2'
+ try {
+ if (contentLength != null && contentLength !== body.size) {
+ throw new RequestContentLengthMismatchError()
+ }
+
+ const buffer = Buffer.from(await body.arrayBuffer())
+
+ if (isH2) {
+ h2stream.cork()
+ h2stream.write(buffer)
+ h2stream.uncork()
+ } else {
+ socket.cork()
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ socket.write(buffer)
+ socket.uncork()
+ }
+
+ request.onBodySent(buffer)
+ request.onRequestSent()
+
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
+
+ resume(client)
+ } catch (err) {
+ util.destroy(isH2 ? h2stream : socket, err)
+ }
+}
+
+async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
+ assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
+
+ let callback = null
+ function onDrain () {
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb()
+ }
+ }
+
+ const waitForDrain = () => new Promise((resolve, reject) => {
+ assert(callback === null)
+
+ if (socket[kError]) {
+ reject(socket[kError])
+ } else {
+ callback = resolve
+ }
+ })
+
+ if (client[kHTTPConnVersion] === 'h2') {
+ h2stream
+ .on('close', onDrain)
+ .on('drain', onDrain)
+
+ try {
+ // It's up to the user to somehow abort the async iterable.
+ for await (const chunk of body) {
+ if (socket[kError]) {
+ throw socket[kError]
+ }
+
+ const res = h2stream.write(chunk)
+ request.onBodySent(chunk)
+ if (!res) {
+ await waitForDrain()
+ }
+ }
+ } catch (err) {
+ h2stream.destroy(err)
+ } finally {
+ request.onRequestSent()
+ h2stream.end()
+ h2stream
+ .off('close', onDrain)
+ .off('drain', onDrain)
+ }
+
+ return
+ }
+
+ socket
+ .on('close', onDrain)
+ .on('drain', onDrain)
+
+ const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
+ try {
+ // It's up to the user to somehow abort the async iterable.
+ for await (const chunk of body) {
+ if (socket[kError]) {
+ throw socket[kError]
+ }
+
+ if (!writer.write(chunk)) {
+ await waitForDrain()
+ }
+ }
+
+ writer.end()
+ } catch (err) {
+ writer.destroy(err)
+ } finally {
+ socket
+ .off('close', onDrain)
+ .off('drain', onDrain)
+ }
+}
+
+class AsyncWriter {
+ constructor ({ socket, request, contentLength, client, expectsPayload, header }) {
+ this.socket = socket
+ this.request = request
+ this.contentLength = contentLength
+ this.client = client
+ this.bytesWritten = 0
+ this.expectsPayload = expectsPayload
+ this.header = header
+
+ socket[kWriting] = true
+ }
+
+ write (chunk) {
+ const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
+
+ if (socket[kError]) {
+ throw socket[kError]
+ }
+
+ if (socket.destroyed) {
+ return false
+ }
+
+ const len = Buffer.byteLength(chunk)
+ if (!len) {
+ return true
+ }
+
+ // We should defer writing chunks.
+ if (contentLength !== null && bytesWritten + len > contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError()
+ }
+
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
+
+ socket.cork()
+
+ if (bytesWritten === 0) {
+ if (!expectsPayload) {
+ socket[kReset] = true
+ }
+
+ if (contentLength === null) {
+ socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
+ } else {
+ socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
+ }
+ }
+
+ if (contentLength === null) {
+ socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
+ }
+
+ this.bytesWritten += len
+
+ const ret = socket.write(chunk)
+
+ socket.uncork()
+
+ request.onBodySent(chunk)
+
+ if (!ret) {
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ // istanbul ignore else: only for jest
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh()
+ }
+ }
+ }
+
+ return ret
+ }
+
+ end () {
+ const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
+ request.onRequestSent()
+
+ socket[kWriting] = false
+
+ if (socket[kError]) {
+ throw socket[kError]
+ }
+
+ if (socket.destroyed) {
+ return
+ }
+
+ if (bytesWritten === 0) {
+ if (expectsPayload) {
+ // https://tools.ietf.org/html/rfc7230#section-3.3.2
+ // A user agent SHOULD send a Content-Length in a request message when
+ // no Transfer-Encoding is sent and the request method defines a meaning
+ // for an enclosed payload body.
+
+ socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
+ } else {
+ socket.write(`${header}\r\n`, 'latin1')
+ }
+ } else if (contentLength === null) {
+ socket.write('\r\n0\r\n\r\n', 'latin1')
+ }
+
+ if (contentLength !== null && bytesWritten !== contentLength) {
+ if (client[kStrictContentLength]) {
+ throw new RequestContentLengthMismatchError()
+ } else {
+ process.emitWarning(new RequestContentLengthMismatchError())
+ }
+ }
+
+ if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
+ // istanbul ignore else: only for jest
+ if (socket[kParser].timeout.refresh) {
+ socket[kParser].timeout.refresh()
+ }
+ }
+
+ resume(client)
+ }
+
+ destroy (err) {
+ const { socket, client } = this
+
+ socket[kWriting] = false
+
+ if (err) {
+ assert(client[kRunning] <= 1, 'pipeline should only contain this request')
+ util.destroy(socket, err)
+ }
+ }
+}
+
+function errorRequest (client, request, err) {
+ try {
+ request.onError(err)
+ assert(request.aborted)
+ } catch (err) {
+ client.emit('error', err)
+ }
+}
+
+module.exports = Client
+
+
+/***/ }),
+
+/***/ 90022:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+/* istanbul ignore file: only for Node 12 */
+
+const { kConnected, kSize } = __nccwpck_require__(68031)
+
+class CompatWeakRef {
+ constructor (value) {
+ this.value = value
+ }
+
+ deref () {
+ return this.value[kConnected] === 0 && this.value[kSize] === 0
+ ? undefined
+ : this.value
+ }
+}
+
+class CompatFinalizer {
+ constructor (finalizer) {
+ this.finalizer = finalizer
+ }
+
+ register (dispatcher, key) {
+ if (dispatcher.on) {
+ dispatcher.on('disconnect', () => {
+ if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
+ this.finalizer(key)
+ }
+ })
+ }
+ }
+}
+
+module.exports = function () {
+ // FIXME: remove workaround when the Node bug is fixed
+ // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
+ if (process.env.NODE_V8_COVERAGE) {
+ return {
+ WeakRef: CompatWeakRef,
+ FinalizationRegistry: CompatFinalizer
+ }
+ }
+ return {
+ WeakRef: global.WeakRef || CompatWeakRef,
+ FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
+ }
+}
+
+
+/***/ }),
+
+/***/ 16985:
+/***/ ((module) => {
+
+
+
+// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size
+const maxAttributeValueSize = 1024
+
+// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size
+const maxNameValuePairSize = 4096
+
+module.exports = {
+ maxAttributeValueSize,
+ maxNameValuePairSize
+}
+
+
+/***/ }),
+
+/***/ 64276:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { parseSetCookie } = __nccwpck_require__(16695)
+const { stringify, getHeadersList } = __nccwpck_require__(83126)
+const { webidl } = __nccwpck_require__(94354)
+const { Headers } = __nccwpck_require__(12801)
+
+/**
+ * @typedef {Object} Cookie
+ * @property {string} name
+ * @property {string} value
+ * @property {Date|number|undefined} expires
+ * @property {number|undefined} maxAge
+ * @property {string|undefined} domain
+ * @property {string|undefined} path
+ * @property {boolean|undefined} secure
+ * @property {boolean|undefined} httpOnly
+ * @property {'Strict'|'Lax'|'None'} sameSite
+ * @property {string[]} unparsed
+ */
+
+/**
+ * @param {Headers} headers
+ * @returns {Record}
+ */
+function getCookies (headers) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })
+
+ webidl.brandCheck(headers, Headers, { strict: false })
+
+ const cookie = headers.get('cookie')
+ const out = {}
+
+ if (!cookie) {
+ return out
+ }
+
+ for (const piece of cookie.split(';')) {
+ const [name, ...value] = piece.split('=')
+
+ out[name.trim()] = value.join('=')
+ }
+
+ return out
+}
+
+/**
+ * @param {Headers} headers
+ * @param {string} name
+ * @param {{ path?: string, domain?: string }|undefined} attributes
+ * @returns {void}
+ */
+function deleteCookie (headers, name, attributes) {
+ webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })
+
+ webidl.brandCheck(headers, Headers, { strict: false })
+
+ name = webidl.converters.DOMString(name)
+ attributes = webidl.converters.DeleteCookieAttributes(attributes)
+
+ // Matches behavior of
+ // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
+ setCookie(headers, {
+ name,
+ value: '',
+ expires: new Date(0),
+ ...attributes
+ })
+}
+
+/**
+ * @param {Headers} headers
+ * @returns {Cookie[]}
+ */
+function getSetCookies (headers) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })
+
+ webidl.brandCheck(headers, Headers, { strict: false })
+
+ const cookies = getHeadersList(headers).cookies
+
+ if (!cookies) {
+ return []
+ }
+
+ // In older versions of undici, cookies is a list of name:value.
+ return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair))
+}
+
+/**
+ * @param {Headers} headers
+ * @param {Cookie} cookie
+ * @returns {void}
+ */
+function setCookie (headers, cookie) {
+ webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })
+
+ webidl.brandCheck(headers, Headers, { strict: false })
+
+ cookie = webidl.converters.Cookie(cookie)
+
+ const str = stringify(cookie)
+
+ if (str) {
+ headers.append('Set-Cookie', stringify(cookie))
+ }
+}
+
+webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'path',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'domain',
+ defaultValue: null
+ }
+])
+
+webidl.converters.Cookie = webidl.dictionaryConverter([
+ {
+ converter: webidl.converters.DOMString,
+ key: 'name'
+ },
+ {
+ converter: webidl.converters.DOMString,
+ key: 'value'
+ },
+ {
+ converter: webidl.nullableConverter((value) => {
+ if (typeof value === 'number') {
+ return webidl.converters['unsigned long long'](value)
+ }
+
+ return new Date(value)
+ }),
+ key: 'expires',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters['long long']),
+ key: 'maxAge',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'domain',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.DOMString),
+ key: 'path',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.boolean),
+ key: 'secure',
+ defaultValue: null
+ },
+ {
+ converter: webidl.nullableConverter(webidl.converters.boolean),
+ key: 'httpOnly',
+ defaultValue: null
+ },
+ {
+ converter: webidl.converters.USVString,
+ key: 'sameSite',
+ allowedValues: ['Strict', 'Lax', 'None']
+ },
+ {
+ converter: webidl.sequenceConverter(webidl.converters.DOMString),
+ key: 'unparsed',
+ defaultValue: []
+ }
+])
+
+module.exports = {
+ getCookies,
+ deleteCookie,
+ getSetCookies,
+ setCookie
+}
+
+
+/***/ }),
+
+/***/ 16695:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(16985)
+const { isCTLExcludingHtab } = __nccwpck_require__(83126)
+const { collectASequenceOfCodePointsFast } = __nccwpck_require__(37246)
+const assert = __nccwpck_require__(42613)
+
+/**
+ * @description Parses the field-value attributes of a set-cookie header string.
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
+ * @param {string} header
+ * @returns if the header is invalid, null will be returned
+ */
+function parseSetCookie (header) {
+ // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
+ // character (CTL characters excluding HTAB): Abort these steps and
+ // ignore the set-cookie-string entirely.
+ if (isCTLExcludingHtab(header)) {
+ return null
+ }
+
+ let nameValuePair = ''
+ let unparsedAttributes = ''
+ let name = ''
+ let value = ''
+
+ // 2. If the set-cookie-string contains a %x3B (";") character:
+ if (header.includes(';')) {
+ // 1. The name-value-pair string consists of the characters up to,
+ // but not including, the first %x3B (";"), and the unparsed-
+ // attributes consist of the remainder of the set-cookie-string
+ // (including the %x3B (";") in question).
+ const position = { position: 0 }
+
+ nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
+ unparsedAttributes = header.slice(position.position)
+ } else {
+ // Otherwise:
+
+ // 1. The name-value-pair string consists of all the characters
+ // contained in the set-cookie-string, and the unparsed-
+ // attributes is the empty string.
+ nameValuePair = header
+ }
+
+ // 3. If the name-value-pair string lacks a %x3D ("=") character, then
+ // the name string is empty, and the value string is the value of
+ // name-value-pair.
+ if (!nameValuePair.includes('=')) {
+ value = nameValuePair
+ } else {
+ // Otherwise, the name string consists of the characters up to, but
+ // not including, the first %x3D ("=") character, and the (possibly
+ // empty) value string consists of the characters after the first
+ // %x3D ("=") character.
+ const position = { position: 0 }
+ name = collectASequenceOfCodePointsFast(
+ '=',
+ nameValuePair,
+ position
+ )
+ value = nameValuePair.slice(position.position + 1)
+ }
+
+ // 4. Remove any leading or trailing WSP characters from the name
+ // string and the value string.
+ name = name.trim()
+ value = value.trim()
+
+ // 5. If the sum of the lengths of the name string and the value string
+ // is more than 4096 octets, abort these steps and ignore the set-
+ // cookie-string entirely.
+ if (name.length + value.length > maxNameValuePairSize) {
+ return null
+ }
+
+ // 6. The cookie-name is the name string, and the cookie-value is the
+ // value string.
+ return {
+ name, value, ...parseUnparsedAttributes(unparsedAttributes)
+ }
+}
+
+/**
+ * Parses the remaining attributes of a set-cookie header
+ * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
+ * @param {string} unparsedAttributes
+ * @param {[Object.]={}} cookieAttributeList
+ */
+function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
+ // 1. If the unparsed-attributes string is empty, skip the rest of
+ // these steps.
+ if (unparsedAttributes.length === 0) {
+ return cookieAttributeList
+ }
+
+ // 2. Discard the first character of the unparsed-attributes (which
+ // will be a %x3B (";") character).
+ assert(unparsedAttributes[0] === ';')
+ unparsedAttributes = unparsedAttributes.slice(1)
+
+ let cookieAv = ''
+
+ // 3. If the remaining unparsed-attributes contains a %x3B (";")
+ // character:
+ if (unparsedAttributes.includes(';')) {
+ // 1. Consume the characters of the unparsed-attributes up to, but
+ // not including, the first %x3B (";") character.
+ cookieAv = collectASequenceOfCodePointsFast(
+ ';',
+ unparsedAttributes,
+ { position: 0 }
+ )
+ unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
+ } else {
+ // Otherwise:
+
+ // 1. Consume the remainder of the unparsed-attributes.
+ cookieAv = unparsedAttributes
+ unparsedAttributes = ''
+ }
+
+ // Let the cookie-av string be the characters consumed in this step.
+
+ let attributeName = ''
+ let attributeValue = ''
+
+ // 4. If the cookie-av string contains a %x3D ("=") character:
+ if (cookieAv.includes('=')) {
+ // 1. The (possibly empty) attribute-name string consists of the
+ // characters up to, but not including, the first %x3D ("=")
+ // character, and the (possibly empty) attribute-value string
+ // consists of the characters after the first %x3D ("=")
+ // character.
+ const position = { position: 0 }
+
+ attributeName = collectASequenceOfCodePointsFast(
+ '=',
+ cookieAv,
+ position
+ )
+ attributeValue = cookieAv.slice(position.position + 1)
+ } else {
+ // Otherwise:
+
+ // 1. The attribute-name string consists of the entire cookie-av
+ // string, and the attribute-value string is empty.
+ attributeName = cookieAv
+ }
+
+ // 5. Remove any leading or trailing WSP characters from the attribute-
+ // name string and the attribute-value string.
+ attributeName = attributeName.trim()
+ attributeValue = attributeValue.trim()
+
+ // 6. If the attribute-value is longer than 1024 octets, ignore the
+ // cookie-av string and return to Step 1 of this algorithm.
+ if (attributeValue.length > maxAttributeValueSize) {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ }
+
+ // 7. Process the attribute-name and attribute-value according to the
+ // requirements in the following subsections. (Notice that
+ // attributes with unrecognized attribute-names are ignored.)
+ const attributeNameLowercase = attributeName.toLowerCase()
+
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
+ // If the attribute-name case-insensitively matches the string
+ // "Expires", the user agent MUST process the cookie-av as follows.
+ if (attributeNameLowercase === 'expires') {
+ // 1. Let the expiry-time be the result of parsing the attribute-value
+ // as cookie-date (see Section 5.1.1).
+ const expiryTime = new Date(attributeValue)
+
+ // 2. If the attribute-value failed to parse as a cookie date, ignore
+ // the cookie-av.
+
+ cookieAttributeList.expires = expiryTime
+ } else if (attributeNameLowercase === 'max-age') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
+ // If the attribute-name case-insensitively matches the string "Max-
+ // Age", the user agent MUST process the cookie-av as follows.
+
+ // 1. If the first character of the attribute-value is not a DIGIT or a
+ // "-" character, ignore the cookie-av.
+ const charCode = attributeValue.charCodeAt(0)
+
+ if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
- ];
- const list = appleModelIds.filter((model) => model.key === key);
- if (list.length === 0) {
- return {
- key: key,
- model: 'Apple',
- version: 'Unknown'
- };
+ // 2. If the remainder of attribute-value contains a non-DIGIT
+ // character, ignore the cookie-av.
+ if (!/^\d+$/.test(attributeValue)) {
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ }
+
+ // 3. Let delta-seconds be the attribute-value converted to an integer.
+ const deltaSeconds = Number(attributeValue)
+
+ // 4. Let cookie-age-limit be the maximum age of the cookie (which
+ // SHOULD be 400 days or less, see Section 4.1.2.2).
+
+ // 5. Set delta-seconds to the smaller of its present value and cookie-
+ // age-limit.
+ // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
+
+ // 6. If delta-seconds is less than or equal to zero (0), let expiry-
+ // time be the earliest representable date and time. Otherwise, let
+ // the expiry-time be the current date and time plus delta-seconds
+ // seconds.
+ // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
+
+ // 7. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Max-Age and an attribute-value of expiry-time.
+ cookieAttributeList.maxAge = deltaSeconds
+ } else if (attributeNameLowercase === 'domain') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
+ // If the attribute-name case-insensitively matches the string "Domain",
+ // the user agent MUST process the cookie-av as follows.
+
+ // 1. Let cookie-domain be the attribute-value.
+ let cookieDomain = attributeValue
+
+ // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
+ // cookie-domain without its leading %x2E (".").
+ if (cookieDomain[0] === '.') {
+ cookieDomain = cookieDomain.slice(1)
+ }
+
+ // 3. Convert the cookie-domain to lower case.
+ cookieDomain = cookieDomain.toLowerCase()
+
+ // 4. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Domain and an attribute-value of cookie-domain.
+ cookieAttributeList.domain = cookieDomain
+ } else if (attributeNameLowercase === 'path') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
+ // If the attribute-name case-insensitively matches the string "Path",
+ // the user agent MUST process the cookie-av as follows.
+
+ // 1. If the attribute-value is empty or if the first character of the
+ // attribute-value is not %x2F ("/"):
+ let cookiePath = ''
+ if (attributeValue.length === 0 || attributeValue[0] !== '/') {
+ // 1. Let cookie-path be the default-path.
+ cookiePath = '/'
+ } else {
+ // Otherwise:
+
+ // 1. Let cookie-path be the attribute-value.
+ cookiePath = attributeValue
+ }
+
+ // 2. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of Path and an attribute-value of cookie-path.
+ cookieAttributeList.path = cookiePath
+ } else if (attributeNameLowercase === 'secure') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
+ // If the attribute-name case-insensitively matches the string "Secure",
+ // the user agent MUST append an attribute to the cookie-attribute-list
+ // with an attribute-name of Secure and an empty attribute-value.
+
+ cookieAttributeList.secure = true
+ } else if (attributeNameLowercase === 'httponly') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
+ // If the attribute-name case-insensitively matches the string
+ // "HttpOnly", the user agent MUST append an attribute to the cookie-
+ // attribute-list with an attribute-name of HttpOnly and an empty
+ // attribute-value.
+
+ cookieAttributeList.httpOnly = true
+ } else if (attributeNameLowercase === 'samesite') {
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
+ // If the attribute-name case-insensitively matches the string
+ // "SameSite", the user agent MUST process the cookie-av as follows:
+
+ // 1. Let enforcement be "Default".
+ let enforcement = 'Default'
+
+ const attributeValueLowercase = attributeValue.toLowerCase()
+ // 2. If cookie-av's attribute-value is a case-insensitive match for
+ // "None", set enforcement to "None".
+ if (attributeValueLowercase.includes('none')) {
+ enforcement = 'None'
+ }
+
+ // 3. If cookie-av's attribute-value is a case-insensitive match for
+ // "Strict", set enforcement to "Strict".
+ if (attributeValueLowercase.includes('strict')) {
+ enforcement = 'Strict'
+ }
+
+ // 4. If cookie-av's attribute-value is a case-insensitive match for
+ // "Lax", set enforcement to "Lax".
+ if (attributeValueLowercase.includes('lax')) {
+ enforcement = 'Lax'
+ }
+
+ // 5. Append an attribute to the cookie-attribute-list with an
+ // attribute-name of "SameSite" and an attribute-value of
+ // enforcement.
+ cookieAttributeList.sameSite = enforcement
+ } else {
+ cookieAttributeList.unparsed ??= []
+
+ cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
+ }
+
+ // 8. Return to Step 1 of this algorithm.
+ return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+}
+
+module.exports = {
+ parseSetCookie,
+ parseUnparsedAttributes
+}
+
+
+/***/ }),
+
+/***/ 83126:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const assert = __nccwpck_require__(42613)
+const { kHeadersList } = __nccwpck_require__(68031)
+
+function isCTLExcludingHtab (value) {
+ if (value.length === 0) {
+ return false
+ }
+
+ for (const char of value) {
+ const code = char.charCodeAt(0)
+
+ if (
+ (code >= 0x00 || code <= 0x08) ||
+ (code >= 0x0A || code <= 0x1F) ||
+ code === 0x7F
+ ) {
+ return false
+ }
+ }
+}
+
+/**
+ CHAR =
+ token = 1*
+ separators = "(" | ")" | "<" | ">" | "@"
+ | "," | ";" | ":" | "\" | <">
+ | "/" | "[" | "]" | "?" | "="
+ | "{" | "}" | SP | HT
+ * @param {string} name
+ */
+function validateCookieName (name) {
+ for (const char of name) {
+ const code = char.charCodeAt(0)
+
+ if (
+ (code <= 0x20 || code > 0x7F) ||
+ char === '(' ||
+ char === ')' ||
+ char === '>' ||
+ char === '<' ||
+ char === '@' ||
+ char === ',' ||
+ char === ';' ||
+ char === ':' ||
+ char === '\\' ||
+ char === '"' ||
+ char === '/' ||
+ char === '[' ||
+ char === ']' ||
+ char === '?' ||
+ char === '=' ||
+ char === '{' ||
+ char === '}'
+ ) {
+ throw new Error('Invalid cookie name')
+ }
+ }
+}
+
+/**
+ cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
+ cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
+ ; US-ASCII characters excluding CTLs,
+ ; whitespace DQUOTE, comma, semicolon,
+ ; and backslash
+ * @param {string} value
+ */
+function validateCookieValue (value) {
+ for (const char of value) {
+ const code = char.charCodeAt(0)
+
+ if (
+ code < 0x21 || // exclude CTLs (0-31)
+ code === 0x22 ||
+ code === 0x2C ||
+ code === 0x3B ||
+ code === 0x5C ||
+ code > 0x7E // non-ascii
+ ) {
+ throw new Error('Invalid header value')
+ }
+ }
+}
+
+/**
+ * path-value =
+ * @param {string} path
+ */
+function validateCookiePath (path) {
+ for (const char of path) {
+ const code = char.charCodeAt(0)
+
+ if (code < 0x21 || char === ';') {
+ throw new Error('Invalid cookie path')
+ }
+ }
+}
+
+/**
+ * I have no idea why these values aren't allowed to be honest,
+ * but Deno tests these. - Khafra
+ * @param {string} domain
+ */
+function validateCookieDomain (domain) {
+ if (
+ domain.startsWith('-') ||
+ domain.endsWith('.') ||
+ domain.endsWith('-')
+ ) {
+ throw new Error('Invalid cookie domain')
+ }
+}
+
+/**
+ * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
+ * @param {number|Date} date
+ IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
+ ; fixed length/zone/capitalization subset of the format
+ ; see Section 3.3 of [RFC5322]
+
+ day-name = %x4D.6F.6E ; "Mon", case-sensitive
+ / %x54.75.65 ; "Tue", case-sensitive
+ / %x57.65.64 ; "Wed", case-sensitive
+ / %x54.68.75 ; "Thu", case-sensitive
+ / %x46.72.69 ; "Fri", case-sensitive
+ / %x53.61.74 ; "Sat", case-sensitive
+ / %x53.75.6E ; "Sun", case-sensitive
+ date1 = day SP month SP year
+ ; e.g., 02 Jun 1982
+
+ day = 2DIGIT
+ month = %x4A.61.6E ; "Jan", case-sensitive
+ / %x46.65.62 ; "Feb", case-sensitive
+ / %x4D.61.72 ; "Mar", case-sensitive
+ / %x41.70.72 ; "Apr", case-sensitive
+ / %x4D.61.79 ; "May", case-sensitive
+ / %x4A.75.6E ; "Jun", case-sensitive
+ / %x4A.75.6C ; "Jul", case-sensitive
+ / %x41.75.67 ; "Aug", case-sensitive
+ / %x53.65.70 ; "Sep", case-sensitive
+ / %x4F.63.74 ; "Oct", case-sensitive
+ / %x4E.6F.76 ; "Nov", case-sensitive
+ / %x44.65.63 ; "Dec", case-sensitive
+ year = 4DIGIT
+
+ GMT = %x47.4D.54 ; "GMT", case-sensitive
+
+ time-of-day = hour ":" minute ":" second
+ ; 00:00:00 - 23:59:60 (leap second)
+
+ hour = 2DIGIT
+ minute = 2DIGIT
+ second = 2DIGIT
+ */
+function toIMFDate (date) {
+ if (typeof date === 'number') {
+ date = new Date(date)
+ }
+
+ const days = [
+ 'Sun', 'Mon', 'Tue', 'Wed',
+ 'Thu', 'Fri', 'Sat'
+ ]
+
+ const months = [
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
+ ]
+
+ const dayName = days[date.getUTCDay()]
+ const day = date.getUTCDate().toString().padStart(2, '0')
+ const month = months[date.getUTCMonth()]
+ const year = date.getUTCFullYear()
+ const hour = date.getUTCHours().toString().padStart(2, '0')
+ const minute = date.getUTCMinutes().toString().padStart(2, '0')
+ const second = date.getUTCSeconds().toString().padStart(2, '0')
+
+ return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`
+}
+
+/**
+ max-age-av = "Max-Age=" non-zero-digit *DIGIT
+ ; In practice, both expires-av and max-age-av
+ ; are limited to dates representable by the
+ ; user agent.
+ * @param {number} maxAge
+ */
+function validateCookieMaxAge (maxAge) {
+ if (maxAge < 0) {
+ throw new Error('Invalid cookie max-age')
}
- const features = [];
- if (list[0].size) { features.push(list[0].size); }
- if (list[0].processor) { features.push(list[0].processor); }
- if (list[0].year) { features.push(list[0].year); }
- if (list[0].additional) { features.push(list[0].additional); }
- return {
- key: key,
- model: list[0].name,
- version: list[0].name + ' (' + features.join(', ') + ')'
- };
}
-function checkWebsite(url, timeout = 5000) {
- const http = ((url.startsWith('https:') || url.indexOf(':443/') > 0 || url.indexOf(':8443/') > 0) ? __nccwpck_require__(65692) : __nccwpck_require__(58611));
- const t = Date.now();
- return new Promise((resolve) => {
- const request = http
- .get(url, { rejectUnauthorized: false }, function (res) {
- res.on('data', () => { });
- res.on('end', () => {
- resolve({
- url,
- statusCode: res.statusCode,
- message: res.statusMessage,
- time: Date.now() - t
- });
- });
- })
- .on("error", function (e) {
- resolve({
- url,
- statusCode: 404,
- message: e.message,
- time: Date.now() - t
- });
- })
- .setTimeout(timeout, () => {
- request.close();
- resolve({
- url,
- statusCode: 408,
- message: 'Request Timeout',
- time: Date.now() - t
- });
- });
- });
-};
+/**
+ * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
+ * @param {import('./index').Cookie} cookie
+ */
+function stringify (cookie) {
+ if (cookie.name.length === 0) {
+ return null
+ }
-function noop() { }
+ validateCookieName(cookie.name)
+ validateCookieValue(cookie.value)
-exports.toInt = toInt;
-exports.splitByNumber = splitByNumber;
-exports.execOptsWin = execOptsWin;
-exports.execOptsLinux = execOptsLinux;
-exports.getCodepage = getCodepage;
-exports.execWin = execWin;
-exports.isFunction = isFunction;
-exports.unique = unique;
-exports.sortByKey = sortByKey;
-exports.cores = cores;
-exports.getValue = getValue;
-exports.decodeEscapeSequence = decodeEscapeSequence;
-exports.parseDateTime = parseDateTime;
-exports.parseHead = parseHead;
-exports.findObjectByKey = findObjectByKey;
-exports.getWmic = getWmic;
-exports.wmic = wmic;
-exports.darwinXcodeExists = darwinXcodeExists;
-exports.getVboxmanage = getVboxmanage;
-exports.powerShell = powerShell;
-exports.powerShellStart = powerShellStart;
-exports.powerShellRelease = powerShellRelease;
-exports.execSafe = execSafe;
-exports.nanoSeconds = nanoSeconds;
-exports.countUniqueLines = countUniqueLines;
-exports.countLines = countLines;
-exports.noop = noop;
-exports.isRaspberry = isRaspberry;
-exports.isRaspbian = isRaspbian;
-exports.sanitizeShellString = sanitizeShellString;
-exports.isPrototypePolluted = isPrototypePolluted;
-exports.decodePiCpuinfo = decodePiCpuinfo;
-exports.getRpiGpu = getRpiGpu;
-exports.promiseAll = promiseAll;
-exports.promisify = promisify;
-exports.promisifySave = promisifySave;
-exports.smartMonToolsInstalled = smartMonToolsInstalled;
-exports.linuxVersion = linuxVersion;
-exports.plistParser = plistParser;
-exports.plistReader = plistReader;
-exports.stringObj = stringObj;
-exports.stringReplace = stringReplace;
-exports.stringToLower = stringToLower;
-exports.stringToString = stringToString;
-exports.stringSubstr = stringSubstr;
-exports.stringTrim = stringTrim;
-exports.stringStartWith = stringStartWith;
-exports.mathMin = mathMin;
-exports.WINDIR = WINDIR;
-exports.getFilesInPath = getFilesInPath;
-exports.semverCompare = semverCompare;
-exports.getAppleModel = getAppleModel;
-exports.checkWebsite = checkWebsite;
+ const out = [`${cookie.name}=${cookie.value}`]
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
+ // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
+ if (cookie.name.startsWith('__Secure-')) {
+ cookie.secure = true
+ }
-/***/ }),
+ if (cookie.name.startsWith('__Host-')) {
+ cookie.secure = true
+ cookie.domain = null
+ cookie.path = '/'
+ }
-/***/ 3881:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (cookie.secure) {
+ out.push('Secure')
+ }
+ if (cookie.httpOnly) {
+ out.push('HttpOnly')
+ }
-// @ts-check
-// ==================================================================================
-// virtualbox.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 14. Docker
-// ----------------------------------------------------------------------------------
+ if (typeof cookie.maxAge === 'number') {
+ validateCookieMaxAge(cookie.maxAge)
+ out.push(`Max-Age=${cookie.maxAge}`)
+ }
-const os = __nccwpck_require__(70857);
-const exec = (__nccwpck_require__(35317).exec);
-const util = __nccwpck_require__(33225);
+ if (cookie.domain) {
+ validateCookieDomain(cookie.domain)
+ out.push(`Domain=${cookie.domain}`)
+ }
-function vboxInfo(callback) {
+ if (cookie.path) {
+ validateCookiePath(cookie.path)
+ out.push(`Path=${cookie.path}`)
+ }
- // fallback - if only callback is given
- let result = [];
- return new Promise((resolve) => {
- process.nextTick(() => {
- try {
- exec(util.getVboxmanage() + ' list vms --long', function (error, stdout) {
- let parts = (os.EOL + stdout.toString()).split(os.EOL + 'Name:');
- parts.shift();
- parts.forEach(part => {
- const lines = ('Name:' + part).split(os.EOL);
- const state = util.getValue(lines, 'State');
- const running = state.startsWith('running');
- const runningSinceString = running ? state.replace('running (since ', '').replace(')', '').trim() : '';
- let runningSince = 0;
- try {
- if (running) {
- const sinceDateObj = new Date(runningSinceString);
- const offset = sinceDateObj.getTimezoneOffset();
- runningSince = Math.round((Date.now() - Date.parse(sinceDateObj)) / 1000) + offset * 60;
- }
- } catch (e) {
- util.noop();
- }
- const stoppedSinceString = !running ? state.replace('powered off (since', '').replace(')', '').trim() : '';
- let stoppedSince = 0;
- try {
- if (!running) {
- const sinceDateObj = new Date(stoppedSinceString);
- const offset = sinceDateObj.getTimezoneOffset();
- stoppedSince = Math.round((Date.now() - Date.parse(sinceDateObj)) / 1000) + offset * 60;
- }
- } catch (e) {
- util.noop();
- }
- result.push({
- id: util.getValue(lines, 'UUID'),
- name: util.getValue(lines, 'Name'),
- running,
- started: runningSinceString,
- runningSince,
- stopped: stoppedSinceString,
- stoppedSince,
- guestOS: util.getValue(lines, 'Guest OS'),
- hardwareUUID: util.getValue(lines, 'Hardware UUID'),
- memory: parseInt(util.getValue(lines, 'Memory size', ' '), 10),
- vram: parseInt(util.getValue(lines, 'VRAM size'), 10),
- cpus: parseInt(util.getValue(lines, 'Number of CPUs'), 10),
- cpuExepCap: util.getValue(lines, 'CPU exec cap'),
- cpuProfile: util.getValue(lines, 'CPUProfile'),
- chipset: util.getValue(lines, 'Chipset'),
- firmware: util.getValue(lines, 'Firmware'),
- pageFusion: util.getValue(lines, 'Page Fusion') === 'enabled',
- configFile: util.getValue(lines, 'Config file'),
- snapshotFolder: util.getValue(lines, 'Snapshot folder'),
- logFolder: util.getValue(lines, 'Log folder'),
- hpet: util.getValue(lines, 'HPET') === 'enabled',
- pae: util.getValue(lines, 'PAE') === 'enabled',
- longMode: util.getValue(lines, 'Long Mode') === 'enabled',
- tripleFaultReset: util.getValue(lines, 'Triple Fault Reset') === 'enabled',
- apic: util.getValue(lines, 'APIC') === 'enabled',
- x2Apic: util.getValue(lines, 'X2APIC') === 'enabled',
- acpi: util.getValue(lines, 'ACPI') === 'enabled',
- ioApic: util.getValue(lines, 'IOAPIC') === 'enabled',
- biosApicMode: util.getValue(lines, 'BIOS APIC mode'),
- bootMenuMode: util.getValue(lines, 'Boot menu mode'),
- bootDevice1: util.getValue(lines, 'Boot Device 1'),
- bootDevice2: util.getValue(lines, 'Boot Device 2'),
- bootDevice3: util.getValue(lines, 'Boot Device 3'),
- bootDevice4: util.getValue(lines, 'Boot Device 4'),
- timeOffset: util.getValue(lines, 'Time offset'),
- rtc: util.getValue(lines, 'RTC'),
- });
- });
+ if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
+ out.push(`Expires=${toIMFDate(cookie.expires)}`)
+ }
- if (callback) { callback(result); }
- resolve(result);
- });
- } catch (e) {
- if (callback) { callback(result); }
- resolve(result);
- }
- });
- });
-}
+ if (cookie.sameSite) {
+ out.push(`SameSite=${cookie.sameSite}`)
+ }
-exports.vboxInfo = vboxInfo;
+ for (const part of cookie.unparsed) {
+ if (!part.includes('=')) {
+ throw new Error('Invalid unparsed')
+ }
+ const [key, ...value] = part.split('=')
-/***/ }),
+ out.push(`${key.trim()}=${value.join('=')}`)
+ }
-/***/ 81180:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return out.join('; ')
+}
+let kHeadersListNode
-// @ts-check
-// ==================================================================================
-// wifi.js
-// ----------------------------------------------------------------------------------
-// Description: System Information - library
-// for Node.js
-// Copyright: (c) 2014 - 2024
-// Author: Sebastian Hildebrandt
-// ----------------------------------------------------------------------------------
-// License: MIT
-// ==================================================================================
-// 9. wifi
-// ----------------------------------------------------------------------------------
+function getHeadersList (headers) {
+ if (headers[kHeadersList]) {
+ return headers[kHeadersList]
+ }
-const os = __nccwpck_require__(70857);
-const exec = (__nccwpck_require__(35317).exec);
-const execSync = (__nccwpck_require__(35317).execSync);
-const util = __nccwpck_require__(33225);
+ if (!kHeadersListNode) {
+ kHeadersListNode = Object.getOwnPropertySymbols(headers).find(
+ (symbol) => symbol.description === 'headers list'
+ )
-let _platform = process.platform;
+ assert(kHeadersListNode, 'Headers cannot be parsed')
+ }
-const _linux = (_platform === 'linux' || _platform === 'android');
-const _darwin = (_platform === 'darwin');
-const _windows = (_platform === 'win32');
+ const headersList = headers[kHeadersListNode]
+ assert(headersList)
-function wifiDBFromQuality(quality) {
- const qual = parseFloat(quality);
- if (qual < 0) { return 0; }
- if (qual >= 100) { return -50; }
- return (qual / 2 - 100);
+ return headersList
}
-function wifiQualityFromDB(db) {
- const result = 2 * (parseFloat(db) + 100);
- return result <= 100 ? result : 100;
+module.exports = {
+ isCTLExcludingHtab,
+ stringify,
+ getHeadersList
}
-const _wifi_frequencies = {
- 1: 2412,
- 2: 2417,
- 3: 2422,
- 4: 2427,
- 5: 2432,
- 6: 2437,
- 7: 2442,
- 8: 2447,
- 9: 2452,
- 10: 2457,
- 11: 2462,
- 12: 2467,
- 13: 2472,
- 14: 2484,
- 32: 5160,
- 34: 5170,
- 36: 5180,
- 38: 5190,
- 40: 5200,
- 42: 5210,
- 44: 5220,
- 46: 5230,
- 48: 5240,
- 50: 5250,
- 52: 5260,
- 54: 5270,
- 56: 5280,
- 58: 5290,
- 60: 5300,
- 62: 5310,
- 64: 5320,
- 68: 5340,
- 96: 5480,
- 100: 5500,
- 102: 5510,
- 104: 5520,
- 106: 5530,
- 108: 5540,
- 110: 5550,
- 112: 5560,
- 114: 5570,
- 116: 5580,
- 118: 5590,
- 120: 5600,
- 122: 5610,
- 124: 5620,
- 126: 5630,
- 128: 5640,
- 132: 5660,
- 134: 5670,
- 136: 5680,
- 138: 5690,
- 140: 5700,
- 142: 5710,
- 144: 5720,
- 149: 5745,
- 151: 5755,
- 153: 5765,
- 155: 5775,
- 157: 5785,
- 159: 5795,
- 161: 5805,
- 165: 5825,
- 169: 5845,
- 173: 5865,
- 183: 4915,
- 184: 4920,
- 185: 4925,
- 187: 4935,
- 188: 4940,
- 189: 4945,
- 192: 4960,
- 196: 4980
-};
-function wifiFrequencyFromChannel(channel) {
- return {}.hasOwnProperty.call(_wifi_frequencies, channel) ? _wifi_frequencies[channel] : null;
-}
+/***/ }),
-function wifiChannelFromFrequencs(frequency) {
- let channel = 0;
- for (let key in _wifi_frequencies) {
- if ({}.hasOwnProperty.call(_wifi_frequencies, key)) {
- if (_wifi_frequencies[key] === frequency) { channel = util.toInt(key); }
- }
- }
- return channel;
-}
+/***/ 91332:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-function ifaceListLinux() {
- const result = [];
- const cmd = 'iw dev 2>/dev/null';
- try {
- const all = execSync(cmd, util.execOptsLinux).toString().split('\n').map(line => line.trim()).join('\n');
- const parts = all.split('\nInterface ');
- parts.shift();
- parts.forEach(ifaceDetails => {
- const lines = ifaceDetails.split('\n');
- const iface = lines[0];
- const id = util.toInt(util.getValue(lines, 'ifindex', ' '));
- const mac = util.getValue(lines, 'addr', ' ');
- const channel = util.toInt(util.getValue(lines, 'channel', ' '));
- result.push({
- id,
- iface,
- mac,
- channel
- });
- });
- return result;
- } catch (e) {
- try {
- const all = execSync('nmcli -t -f general,wifi-properties,wired-properties,interface-flags,capabilities,nsp device show 2>/dev/null', util.execOptsLinux).toString();
- const parts = all.split('\n\n');
- let i = 1;
- parts.forEach(ifaceDetails => {
- const lines = ifaceDetails.split('\n');
- const iface = util.getValue(lines, 'GENERAL.DEVICE');
- const type = util.getValue(lines, 'GENERAL.TYPE');
- const id = i++; // // util.getValue(lines, 'GENERAL.PATH');
- const mac = util.getValue(lines, 'GENERAL.HWADDR');
- const channel = '';
- if (type.toLowerCase() === 'wifi') {
- result.push({
- id,
- iface,
- mac,
- channel
- });
+
+
+const net = __nccwpck_require__(69278)
+const assert = __nccwpck_require__(42613)
+const util = __nccwpck_require__(89500)
+const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(53959)
+
+let tls // include tls conditionally since it is not always available
+
+// TODO: session re-use does not wait for the first
+// connection to resolve the session and might therefore
+// resolve the same servername multiple times even when
+// re-use is enabled.
+
+let SessionCache
+// FIXME: remove workaround when the Node bug is fixed
+// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
+if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {
+ SessionCache = class WeakSessionCache {
+ constructor (maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions
+ this._sessionCache = new Map()
+ this._sessionRegistry = new global.FinalizationRegistry((key) => {
+ if (this._sessionCache.size < this._maxCachedSessions) {
+ return
}
- });
- return result;
- } catch (e) {
- return [];
+
+ const ref = this._sessionCache.get(key)
+ if (ref !== undefined && ref.deref() === undefined) {
+ this._sessionCache.delete(key)
+ }
+ })
+ }
+
+ get (sessionKey) {
+ const ref = this._sessionCache.get(sessionKey)
+ return ref ? ref.deref() : null
+ }
+
+ set (sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return
+ }
+
+ this._sessionCache.set(sessionKey, new WeakRef(session))
+ this._sessionRegistry.register(session, sessionKey)
}
}
-}
+} else {
+ SessionCache = class SimpleSessionCache {
+ constructor (maxCachedSessions) {
+ this._maxCachedSessions = maxCachedSessions
+ this._sessionCache = new Map()
+ }
-function nmiDeviceLinux(iface) {
- const cmd = `nmcli -t -f general,wifi-properties,capabilities,ip4,ip6 device show ${iface} 2> /dev/null`;
- try {
- const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- const ssid = util.getValue(lines, 'GENERAL.CONNECTION');
- return {
- iface,
- type: util.getValue(lines, 'GENERAL.TYPE'),
- vendor: util.getValue(lines, 'GENERAL.VENDOR'),
- product: util.getValue(lines, 'GENERAL.PRODUCT'),
- mac: util.getValue(lines, 'GENERAL.HWADDR').toLowerCase(),
- ssid: ssid !== '--' ? ssid : null
- };
- } catch (e) {
- return {};
- }
-}
+ get (sessionKey) {
+ return this._sessionCache.get(sessionKey)
+ }
-function nmiConnectionLinux(ssid) {
- const cmd = `nmcli -t --show-secrets connection show ${ssid} 2>/dev/null`;
- try {
- const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- const bssid = util.getValue(lines, '802-11-wireless.seen-bssids').toLowerCase();
- return {
- ssid: ssid !== '--' ? ssid : null,
- uuid: util.getValue(lines, 'connection.uuid'),
- type: util.getValue(lines, 'connection.type'),
- autoconnect: util.getValue(lines, 'connection.autoconnect') === 'yes',
- security: util.getValue(lines, '802-11-wireless-security.key-mgmt'),
- bssid: bssid !== '--' ? bssid : null
- };
- } catch (e) {
- return {};
- }
-}
+ set (sessionKey, session) {
+ if (this._maxCachedSessions === 0) {
+ return
+ }
-function wpaConnectionLinux(iface) {
- if (!iface) {
- return {};
- }
- const cmd = `wpa_cli -i ${iface} status 2>&1`;
- try {
- const lines = execSync(cmd, util.execOptsLinux).toString().split('\n');
- const freq = util.toInt(util.getValue(lines, 'freq', '='));
- return {
- ssid: util.getValue(lines, 'ssid', '='),
- uuid: util.getValue(lines, 'uuid', '='),
- security: util.getValue(lines, 'key_mgmt', '='),
- freq,
- channel: wifiChannelFromFrequencs(freq),
- bssid: util.getValue(lines, 'bssid', '=').toLowerCase()
- };
- } catch (e) {
- return {};
+ if (this._sessionCache.size >= this._maxCachedSessions) {
+ // remove the oldest session
+ const { value: oldestKey } = this._sessionCache.keys().next()
+ this._sessionCache.delete(oldestKey)
+ }
+
+ this._sessionCache.set(sessionKey, session)
+ }
}
}
-function getWifiNetworkListNmi() {
- const result = [];
- const cmd = 'nmcli -t -m multiline --fields active,ssid,bssid,mode,chan,freq,signal,security,wpa-flags,rsn-flags device wifi list 2>/dev/null';
- try {
- const stdout = execSync(cmd, util.execOptsLinux);
- const parts = stdout.toString().split('ACTIVE:');
- parts.shift();
- parts.forEach(part => {
- part = 'ACTIVE:' + part;
- const lines = part.split(os.EOL);
- const channel = util.getValue(lines, 'CHAN');
- const frequency = util.getValue(lines, 'FREQ').toLowerCase().replace('mhz', '').trim();
- const security = util.getValue(lines, 'SECURITY').replace('(', '').replace(')', '');
- const wpaFlags = util.getValue(lines, 'WPA-FLAGS').replace('(', '').replace(')', '');
- const rsnFlags = util.getValue(lines, 'RSN-FLAGS').replace('(', '').replace(')', '');
- const quality = util.getValue(lines, 'SIGNAL');
- result.push({
- ssid: util.getValue(lines, 'SSID'),
- bssid: util.getValue(lines, 'BSSID').toLowerCase(),
- mode: util.getValue(lines, 'MODE'),
- channel: channel ? parseInt(channel, 10) : null,
- frequency: frequency ? parseInt(frequency, 10) : null,
- signalLevel: wifiDBFromQuality(quality),
- quality: quality ? parseInt(quality, 10) : null,
- security: security && security !== 'none' ? security.split(' ') : [],
- wpaFlags: wpaFlags && wpaFlags !== 'none' ? wpaFlags.split(' ') : [],
- rsnFlags: rsnFlags && rsnFlags !== 'none' ? rsnFlags.split(' ') : []
- });
- });
- return result;
- } catch (e) {
- return [];
+function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {
+ if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
+ throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
}
-}
-function getWifiNetworkListIw(iface) {
- const result = [];
- try {
- let iwlistParts = execSync(`export LC_ALL=C; iwlist ${iface} scan 2>&1; unset LC_ALL`, util.execOptsLinux).toString().split(' Cell ');
- if (iwlistParts[0].indexOf('resource busy') >= 0) { return -1; }
- if (iwlistParts.length > 1) {
- iwlistParts.shift();
- iwlistParts.forEach(element => {
- const lines = element.split('\n');
- const channel = util.getValue(lines, 'channel', ':', true);
- const address = (lines && lines.length && lines[0].indexOf('Address:') >= 0 ? lines[0].split('Address:')[1].trim().toLowerCase() : '');
- const mode = util.getValue(lines, 'mode', ':', true);
- const frequency = util.getValue(lines, 'frequency', ':', true);
- const qualityString = util.getValue(lines, 'Quality', '=', true);
- const dbParts = qualityString.toLowerCase().split('signal level=');
- const db = dbParts.length > 1 ? util.toInt(dbParts[1]) : 0;
- const quality = db ? wifiQualityFromDB(db) : 0;
- const ssid = util.getValue(lines, 'essid', ':', true);
+ const options = { path: socketPath, ...opts }
+ const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
+ timeout = timeout == null ? 10e3 : timeout
+ allowH2 = allowH2 != null ? allowH2 : false
+ return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
+ let socket
+ if (protocol === 'https:') {
+ if (!tls) {
+ tls = __nccwpck_require__(64756)
+ }
+ servername = servername || options.servername || util.getServerName(host) || null
- // security and wpa-flags
- const isWpa = element.indexOf(' WPA ') >= 0;
- const isWpa2 = element.indexOf('WPA2 ') >= 0;
- const security = [];
- if (isWpa) { security.push('WPA'); }
- if (isWpa2) { security.push('WPA2'); }
- const wpaFlags = [];
- let wpaFlag = '';
- lines.forEach(function (line) {
- const l = line.trim().toLowerCase();
- if (l.indexOf('group cipher') >= 0) {
- if (wpaFlag) {
- wpaFlags.push(wpaFlag);
- }
- const parts = l.split(':');
- if (parts.length > 1) {
- wpaFlag = parts[1].trim().toUpperCase();
- }
- }
- if (l.indexOf('pairwise cipher') >= 0) {
- const parts = l.split(':');
- if (parts.length > 1) {
- if (parts[1].indexOf('tkip')) { wpaFlag = (wpaFlag ? 'TKIP/' + wpaFlag : 'TKIP'); }
- else if (parts[1].indexOf('ccmp')) { wpaFlag = (wpaFlag ? 'CCMP/' + wpaFlag : 'CCMP'); }
- else if (parts[1].indexOf('proprietary')) { wpaFlag = (wpaFlag ? 'PROP/' + wpaFlag : 'PROP'); }
- }
- }
- if (l.indexOf('authentication suites') >= 0) {
- const parts = l.split(':');
- if (parts.length > 1) {
- if (parts[1].indexOf('802.1x')) { wpaFlag = (wpaFlag ? '802.1x/' + wpaFlag : '802.1x'); }
- else if (parts[1].indexOf('psk')) { wpaFlag = (wpaFlag ? 'PSK/' + wpaFlag : 'PSK'); }
- }
- }
- });
- if (wpaFlag) {
- wpaFlags.push(wpaFlag);
- }
+ const sessionKey = servername || hostname
+ const session = sessionCache.get(sessionKey) || null
- result.push({
- ssid,
- bssid: address,
- mode,
- channel: channel ? util.toInt(channel) : null,
- frequency: frequency ? util.toInt(frequency.replace('.', '')) : null,
- signalLevel: db,
- quality,
- security,
- wpaFlags,
- rsnFlags: []
- });
- });
+ assert(sessionKey)
+
+ socket = tls.connect({
+ highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
+ ...options,
+ servername,
+ session,
+ localAddress,
+ // TODO(HTTP/2): Add support for h2c
+ ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
+ socket: httpSocket, // upgrade socket connection
+ port: port || 443,
+ host: hostname
+ })
+
+ socket
+ .on('session', function (session) {
+ // TODO (fix): Can a session become invalid once established? Don't think so?
+ sessionCache.set(sessionKey, session)
+ })
+ } else {
+ assert(!httpSocket, 'httpSocket can only be sent on TLS update')
+ socket = net.connect({
+ highWaterMark: 64 * 1024, // Same as nodejs fs streams.
+ ...options,
+ localAddress,
+ port: port || 80,
+ host: hostname
+ })
}
- return result;
- } catch (e) {
- return -1;
- }
-}
-function parseWifiDarwinXX(wifiObj) {
- const result = [];
- if (wifiObj) {
- wifiObj.forEach(function (wifiItem) {
- const signalLevel = wifiItem.RSSI;
- let security = [];
- let wpaFlags = [];
- let ssid = wifiItem.SSID_STR || '';
- if (wifiItem.WPA_IE) {
- security.push('WPA');
- if (wifiItem.WPA_IE.IE_KEY_WPA_UCIPHERS) {
- wifiItem.WPA_IE.IE_KEY_WPA_UCIPHERS.forEach(function (ciphers) {
- if (ciphers === 0 && wpaFlags.indexOf('unknown/TKIP') === -1) { wpaFlags.push('unknown/TKIP'); }
- if (ciphers === 2 && wpaFlags.indexOf('PSK/TKIP') === -1) { wpaFlags.push('PSK/TKIP'); }
- if (ciphers === 4 && wpaFlags.indexOf('PSK/AES') === -1) { wpaFlags.push('PSK/AES'); }
- });
- }
- }
- if (wifiItem.RSN_IE) {
- security.push('WPA2');
- if (wifiItem.RSN_IE.IE_KEY_RSN_UCIPHERS) {
- wifiItem.RSN_IE.IE_KEY_RSN_UCIPHERS.forEach(function (ciphers) {
- if (ciphers === 0 && wpaFlags.indexOf('unknown/TKIP') === -1) { wpaFlags.push('unknown/TKIP'); }
- if (ciphers === 2 && wpaFlags.indexOf('TKIP/TKIP') === -1) { wpaFlags.push('TKIP/TKIP'); }
- if (ciphers === 4 && wpaFlags.indexOf('PSK/AES') === -1) { wpaFlags.push('PSK/AES'); }
- });
+ // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
+ if (options.keepAlive == null || options.keepAlive) {
+ const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
+ socket.setKeepAlive(true, keepAliveInitialDelay)
+ }
+
+ const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)
+
+ socket
+ .setNoDelay(true)
+ .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
+ cancelTimeout()
+
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb(null, this)
}
- }
- if (wifiItem.SSID && ssid === '') {
- try {
- ssid = Buffer.from(wifiItem.SSID, 'base64').toString('utf8');
- } catch (err) {
- util.noop();
+ })
+ .on('error', function (err) {
+ cancelTimeout()
+
+ if (callback) {
+ const cb = callback
+ callback = null
+ cb(err)
}
- }
- result.push({
- ssid,
- bssid: wifiItem.BSSID || '',
- mode: '',
- channel: wifiItem.CHANNEL,
- frequency: wifiFrequencyFromChannel(wifiItem.CHANNEL),
- signalLevel: signalLevel ? parseInt(signalLevel, 10) : null,
- quality: wifiQualityFromDB(signalLevel),
- security,
- wpaFlags,
- rsnFlags: []
- });
- });
+ })
+
+ return socket
}
- return result;
}
-function parseWifiDarwin(wifiStr) {
- const result = [];
- try {
- let wifiObj = JSON.parse(wifiStr);
- wifiObj = wifiObj.SPAirPortDataType[0].spairport_airport_interfaces[0].spairport_airport_other_local_wireless_networks;
- wifiObj.forEach(function (wifiItem) {
+function setupTimeout (onConnectTimeout, timeout) {
+ if (!timeout) {
+ return () => {}
+ }
- let security = [];
- const sm = wifiItem.spairport_security_mode;
- if (sm === 'spairport_security_mode_wep') {
- security.push('WEP');
- } else if (sm === 'spairport_security_mode_wpa2_personal') {
- security.push('WPA2');
- } else if (sm.startsWith('spairport_security_mode_wpa2_enterprise')) {
- security.push('WPA2 EAP');
- } else if (sm.startsWith('pairport_security_mode_wpa3_transition')) {
- security.push('WPA2/WPA3');
- } else if (sm.startsWith('pairport_security_mode_wpa3')) {
- security.push('WPA3');
+ let s1 = null
+ let s2 = null
+ const timeoutId = setTimeout(() => {
+ // setImmediate is added to make sure that we priotorise socket error events over timeouts
+ s1 = setImmediate(() => {
+ if (process.platform === 'win32') {
+ // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
+ s2 = setImmediate(() => onConnectTimeout())
+ } else {
+ onConnectTimeout()
}
- const channel = parseInt(('' + wifiItem.spairport_network_channel).split(' ')[0]) || 0;
- const signalLevel = wifiItem.spairport_signal_noise || null;
-
- result.push({
- ssid: wifiItem._name || '',
- bssid: wifiItem.spairport_network_bssid || null,
- mode: wifiItem.spairport_network_phymode,
- channel,
- frequency: wifiFrequencyFromChannel(channel),
- signalLevel: signalLevel ? parseInt(signalLevel, 10) : null,
- quality: wifiQualityFromDB(signalLevel),
- security,
- wpaFlags: [],
- rsnFlags: []
- });
- });
- return result;
- } catch (e) {
- return result;
+ })
+ }, timeout)
+ return () => {
+ clearTimeout(timeoutId)
+ clearImmediate(s1)
+ clearImmediate(s2)
}
-};
-function wifiNetworks(callback) {
- return new Promise((resolve) => {
- process.nextTick(() => {
- let result = [];
- if (_linux) {
- result = getWifiNetworkListNmi();
- if (result.length === 0) {
- try {
- const iwconfigParts = execSync('export LC_ALL=C; iwconfig 2>/dev/null; unset LC_ALL', util.execOptsLinux).toString().split('\n\n');
- let iface = '';
- iwconfigParts.forEach(element => {
- if (element.indexOf('no wireless') === -1 && element.trim() !== '') {
- iface = element.split(' ')[0];
- }
- });
- if (iface) {
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(iface, true);
- const l = util.mathMin(s.length, 2000);
+}
- for (let i = 0; i <= l; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
+function onConnectTimeout (socket) {
+ util.destroy(socket, new ConnectTimeoutError())
+}
- const res = getWifiNetworkListIw(ifaceSanitized);
- if (res === -1) {
- // try again after 4 secs
- setTimeout(function (iface) {
- const res = getWifiNetworkListIw(iface);
- if (res != -1) { result = res; }
- if (callback) {
- callback(result);
- }
- resolve(result);
- }, 4000);
- } else {
- result = res;
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- } catch (e) {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- } else if (_darwin) {
- let cmd = 'system_profiler SPAirPortDataType -json 2>/dev/null';
- exec(cmd, { maxBuffer: 1024 * 40000 }, function (error, stdout) {
- result = parseWifiDarwin(stdout.toString());
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else if (_windows) {
- let cmd = 'netsh wlan show networks mode=Bssid';
- util.powerShell(cmd).then((stdout) => {
- const ssidParts = stdout.toString('utf8').split(os.EOL + os.EOL + 'SSID ');
- ssidParts.shift();
+module.exports = buildConnector
- ssidParts.forEach(ssidPart => {
- const ssidLines = ssidPart.split(os.EOL);
- if (ssidLines && ssidLines.length >= 8 && ssidLines[0].indexOf(':') >= 0) {
- const bssidsParts = ssidPart.split(' BSSID');
- bssidsParts.shift();
- bssidsParts.forEach((bssidPart) => {
- const bssidLines = bssidPart.split(os.EOL);
- const bssidLine = bssidLines[0].split(':');
- bssidLine.shift();
- const bssid = bssidLine.join(':').trim().toLowerCase();
- const channel = bssidLines[3].split(':').pop().trim();
- const quality = bssidLines[1].split(':').pop().trim();
+/***/ }),
+
+/***/ 42371:
+/***/ ((module) => {
+
+
+
+/** @type {Record} */
+const headerNameLowerCasedRecord = {}
+
+// https://developer.mozilla.org/docs/Web/HTTP/Headers
+const wellknownHeaderNames = [
+ 'Accept',
+ 'Accept-Encoding',
+ 'Accept-Language',
+ 'Accept-Ranges',
+ 'Access-Control-Allow-Credentials',
+ 'Access-Control-Allow-Headers',
+ 'Access-Control-Allow-Methods',
+ 'Access-Control-Allow-Origin',
+ 'Access-Control-Expose-Headers',
+ 'Access-Control-Max-Age',
+ 'Access-Control-Request-Headers',
+ 'Access-Control-Request-Method',
+ 'Age',
+ 'Allow',
+ 'Alt-Svc',
+ 'Alt-Used',
+ 'Authorization',
+ 'Cache-Control',
+ 'Clear-Site-Data',
+ 'Connection',
+ 'Content-Disposition',
+ 'Content-Encoding',
+ 'Content-Language',
+ 'Content-Length',
+ 'Content-Location',
+ 'Content-Range',
+ 'Content-Security-Policy',
+ 'Content-Security-Policy-Report-Only',
+ 'Content-Type',
+ 'Cookie',
+ 'Cross-Origin-Embedder-Policy',
+ 'Cross-Origin-Opener-Policy',
+ 'Cross-Origin-Resource-Policy',
+ 'Date',
+ 'Device-Memory',
+ 'Downlink',
+ 'ECT',
+ 'ETag',
+ 'Expect',
+ 'Expect-CT',
+ 'Expires',
+ 'Forwarded',
+ 'From',
+ 'Host',
+ 'If-Match',
+ 'If-Modified-Since',
+ 'If-None-Match',
+ 'If-Range',
+ 'If-Unmodified-Since',
+ 'Keep-Alive',
+ 'Last-Modified',
+ 'Link',
+ 'Location',
+ 'Max-Forwards',
+ 'Origin',
+ 'Permissions-Policy',
+ 'Pragma',
+ 'Proxy-Authenticate',
+ 'Proxy-Authorization',
+ 'RTT',
+ 'Range',
+ 'Referer',
+ 'Referrer-Policy',
+ 'Refresh',
+ 'Retry-After',
+ 'Sec-WebSocket-Accept',
+ 'Sec-WebSocket-Extensions',
+ 'Sec-WebSocket-Key',
+ 'Sec-WebSocket-Protocol',
+ 'Sec-WebSocket-Version',
+ 'Server',
+ 'Server-Timing',
+ 'Service-Worker-Allowed',
+ 'Service-Worker-Navigation-Preload',
+ 'Set-Cookie',
+ 'SourceMap',
+ 'Strict-Transport-Security',
+ 'Supports-Loading-Mode',
+ 'TE',
+ 'Timing-Allow-Origin',
+ 'Trailer',
+ 'Transfer-Encoding',
+ 'Upgrade',
+ 'Upgrade-Insecure-Requests',
+ 'User-Agent',
+ 'Vary',
+ 'Via',
+ 'WWW-Authenticate',
+ 'X-Content-Type-Options',
+ 'X-DNS-Prefetch-Control',
+ 'X-Frame-Options',
+ 'X-Permitted-Cross-Domain-Policies',
+ 'X-Powered-By',
+ 'X-Requested-With',
+ 'X-XSS-Protection'
+]
+
+for (let i = 0; i < wellknownHeaderNames.length; ++i) {
+ const key = wellknownHeaderNames[i]
+ const lowerCasedKey = key.toLowerCase()
+ headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
+ lowerCasedKey
+}
- result.push({
- ssid: ssidLines[0].split(':').pop().trim(),
- bssid,
- mode: '',
- channel: channel ? parseInt(channel, 10) : null,
- frequency: wifiFrequencyFromChannel(channel),
- signalLevel: wifiDBFromQuality(quality),
- quality: quality ? parseInt(quality, 10) : null,
- security: [ssidLines[2].split(':').pop().trim()],
- wpaFlags: [ssidLines[3].split(':').pop().trim()],
- rsnFlags: []
- });
- });
- }
- });
+// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
+Object.setPrototypeOf(headerNameLowerCasedRecord, null)
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- });
+module.exports = {
+ wellknownHeaderNames,
+ headerNameLowerCasedRecord
}
-exports.wifiNetworks = wifiNetworks;
-function getVendor(model) {
- model = model.toLowerCase();
- let result = '';
- if (model.indexOf('intel') >= 0) { result = 'Intel'; }
- else if (model.indexOf('realtek') >= 0) { result = 'Realtek'; }
- else if (model.indexOf('qualcom') >= 0) { result = 'Qualcom'; }
- else if (model.indexOf('broadcom') >= 0) { result = 'Broadcom'; }
- else if (model.indexOf('cavium') >= 0) { result = 'Cavium'; }
- else if (model.indexOf('cisco') >= 0) { result = 'Cisco'; }
- else if (model.indexOf('marvel') >= 0) { result = 'Marvel'; }
- else if (model.indexOf('zyxel') >= 0) { result = 'Zyxel'; }
- else if (model.indexOf('melanox') >= 0) { result = 'Melanox'; }
- else if (model.indexOf('d-link') >= 0) { result = 'D-Link'; }
- else if (model.indexOf('tp-link') >= 0) { result = 'TP-Link'; }
- else if (model.indexOf('asus') >= 0) { result = 'Asus'; }
- else if (model.indexOf('linksys') >= 0) { result = 'Linksys'; }
- return result;
-}
+/***/ }),
-function formatBssid(s) {
- s = s.replace(//g, '').match(/.{1,2}/g) || [];
- return s.join(':');
+/***/ 53959:
+/***/ ((module) => {
+
+
+
+class UndiciError extends Error {
+ constructor (message) {
+ super(message)
+ this.name = 'UndiciError'
+ this.code = 'UND_ERR'
+ }
}
-function wifiConnections(callback) {
+class ConnectTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ConnectTimeoutError)
+ this.name = 'ConnectTimeoutError'
+ this.message = message || 'Connect Timeout Error'
+ this.code = 'UND_ERR_CONNECT_TIMEOUT'
+ }
+}
- return new Promise((resolve) => {
- process.nextTick(() => {
- const result = [];
+class HeadersTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, HeadersTimeoutError)
+ this.name = 'HeadersTimeoutError'
+ this.message = message || 'Headers Timeout Error'
+ this.code = 'UND_ERR_HEADERS_TIMEOUT'
+ }
+}
- if (_linux) {
- const ifaces = ifaceListLinux();
- const networkList = getWifiNetworkListNmi();
- ifaces.forEach(ifaceDetail => {
- let ifaceSanitized = '';
- const s = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(ifaceDetail.iface, true);
- const ll = util.mathMin(s.length, 2000);
+class HeadersOverflowError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, HeadersOverflowError)
+ this.name = 'HeadersOverflowError'
+ this.message = message || 'Headers Overflow Error'
+ this.code = 'UND_ERR_HEADERS_OVERFLOW'
+ }
+}
- for (let i = 0; i <= ll; i++) {
- if (s[i] !== undefined) {
- ifaceSanitized = ifaceSanitized + s[i];
- }
- }
+class BodyTimeoutError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, BodyTimeoutError)
+ this.name = 'BodyTimeoutError'
+ this.message = message || 'Body Timeout Error'
+ this.code = 'UND_ERR_BODY_TIMEOUT'
+ }
+}
- const nmiDetails = nmiDeviceLinux(ifaceSanitized);
- const wpaDetails = wpaConnectionLinux(ifaceSanitized);
- const ssid = nmiDetails.ssid || wpaDetails.ssid;
- const network = networkList.filter(nw => nw.ssid === ssid);
- let ssidSanitized = '';
- const t = util.isPrototypePolluted() ? '---' : util.sanitizeShellString(ssid, true);
- const l = util.mathMin(t.length, 32);
- for (let i = 0; i <= l; i++) {
- if (t[i] !== undefined) {
- ssidSanitized = ssidSanitized + t[i];
- }
- }
+class ResponseStatusCodeError extends UndiciError {
+ constructor (message, statusCode, headers, body) {
+ super(message)
+ Error.captureStackTrace(this, ResponseStatusCodeError)
+ this.name = 'ResponseStatusCodeError'
+ this.message = message || 'Response Status Code Error'
+ this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
+ this.body = body
+ this.status = statusCode
+ this.statusCode = statusCode
+ this.headers = headers
+ }
+}
- const nmiConnection = nmiConnectionLinux(ssidSanitized);
- const channel = network && network.length && network[0].channel ? network[0].channel : (wpaDetails.channel ? wpaDetails.channel : null);
- const bssid = network && network.length && network[0].bssid ? network[0].bssid : (wpaDetails.bssid ? wpaDetails.bssid : null);
- const signalLevel = network && network.length && network[0].signalLevel ? network[0].signalLevel : null;
- if (ssid && bssid) {
- result.push({
- id: ifaceDetail.id,
- iface: ifaceDetail.iface,
- model: nmiDetails.product,
- ssid,
- bssid: network && network.length && network[0].bssid ? network[0].bssid : (wpaDetails.bssid ? wpaDetails.bssid : null),
- channel,
- frequency: channel ? wifiFrequencyFromChannel(channel) : null,
- type: nmiConnection.type ? nmiConnection.type : '802.11',
- security: nmiConnection.security ? nmiConnection.security : (wpaDetails.security ? wpaDetails.security : null),
- signalLevel,
- quality: wifiQualityFromDB(signalLevel),
- txRate: null
- });
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else if (_darwin) {
- let cmd = 'system_profiler SPNetworkDataType SPAirPortDataType -xml 2>/dev/null; echo "######" ; ioreg -n AppleBCMWLANSkywalkInterface -r 2>/dev/null';
- exec(cmd, function (error, stdout) {
- try {
- const parts = stdout.toString().split('######');
- const profilerObj = util.plistParser(parts[0]);
- const networkObj = profilerObj[0]._SPCommandLineArguments.indexOf('SPNetworkDataType') >= 0 ? profilerObj[0]._items : profilerObj[1]._items;
- const airportObj = profilerObj[0]._SPCommandLineArguments.indexOf('SPAirPortDataType') >= 0 ? profilerObj[0]._items[0].spairport_airport_interfaces : profilerObj[1]._items[0].spairport_airport_interfaces;
+class InvalidArgumentError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InvalidArgumentError)
+ this.name = 'InvalidArgumentError'
+ this.message = message || 'Invalid Argument Error'
+ this.code = 'UND_ERR_INVALID_ARG'
+ }
+}
- // parts[1] : ioreg
- let lines3 = [];
- if (parts[1].indexOf(' | {') > 0 && parts[1].indexOf(' | }') > parts[1].indexOf(' | {')) {
- lines3 = parts[1].split(' | {')[1].split(' | }')[0].replace(/ \| /g, '').replace(/"/g, '').split('\n');
- }
+class InvalidReturnValueError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InvalidReturnValueError)
+ this.name = 'InvalidReturnValueError'
+ this.message = message || 'Invalid Return Value Error'
+ this.code = 'UND_ERR_INVALID_RETURN_VALUE'
+ }
+}
- const networkWifiObj = networkObj.find((item) => { return item._name === 'Wi-Fi'; });
- const airportWifiObj = airportObj[0].spairport_current_network_information;
+class RequestAbortedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, RequestAbortedError)
+ this.name = 'AbortError'
+ this.message = message || 'Request aborted'
+ this.code = 'UND_ERR_ABORTED'
+ }
+}
- const channel = parseInt(('' + airportWifiObj.spairport_network_channel).split(' ')[0]) || 0;
- const signalLevel = airportWifiObj.spairport_signal_noise || null;
+class InformationalError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, InformationalError)
+ this.name = 'InformationalError'
+ this.message = message || 'Request information'
+ this.code = 'UND_ERR_INFO'
+ }
+}
- let security = [];
- const sm = airportWifiObj.spairport_security_mode;
- if (sm === 'spairport_security_mode_wep') {
- security.push('WEP');
- } else if (sm === 'spairport_security_mode_wpa2_personal') {
- security.push('WPA2');
- } else if (sm.startsWith('spairport_security_mode_wpa2_enterprise')) {
- security.push('WPA2 EAP');
- } else if (sm.startsWith('pairport_security_mode_wpa3_transition')) {
- security.push('WPA2/WPA3');
- } else if (sm.startsWith('pairport_security_mode_wpa3')) {
- security.push('WPA3');
- }
+class RequestContentLengthMismatchError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, RequestContentLengthMismatchError)
+ this.name = 'RequestContentLengthMismatchError'
+ this.message = message || 'Request body length does not match content-length header'
+ this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
+ }
+}
- result.push({
- id: networkWifiObj._name || 'Wi-Fi',
- iface: networkWifiObj.interface || '',
- model: networkWifiObj.hardware || '',
- ssid: airportWifiObj._name || '',
- bssid: airportWifiObj.spairport_network_bssid || '',
- channel,
- frequency: channel ? wifiFrequencyFromChannel(channel) : null,
- type: airportWifiObj.spairport_network_phymode || '802.11',
- security,
- signalLevel: signalLevel ? parseInt(signalLevel, 10) : null,
- quality: wifiQualityFromDB(signalLevel),
- txRate: airportWifiObj.spairport_network_rate || null,
- });
+class ResponseContentLengthMismatchError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ResponseContentLengthMismatchError)
+ this.name = 'ResponseContentLengthMismatchError'
+ this.message = message || 'Response body length does not match content-length header'
+ this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
+ }
+}
- } catch (e) {
- util.noop();
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else if (_windows) {
- let cmd = 'netsh wlan show interfaces';
- util.powerShell(cmd).then(function (stdout) {
- const allLines = stdout.toString().split('\r\n');
- for (let i = 0; i < allLines.length; i++) {
- allLines[i] = allLines[i].trim();
- }
- const parts = allLines.join('\r\n').split(':\r\n\r\n');
- parts.shift();
- parts.forEach(part => {
- const lines = part.split('\r\n');
- if (lines.length >= 5) {
- const iface = lines[0].indexOf(':') >= 0 ? lines[0].split(':')[1].trim() : '';
- const model = lines[1].indexOf(':') >= 0 ? lines[1].split(':')[1].trim() : '';
- const id = lines[2].indexOf(':') >= 0 ? lines[2].split(':')[1].trim() : '';
- const ssid = util.getValue(lines, 'SSID', ':', true);
- const bssid = util.getValue(lines, 'BSSID', ':', true) || util.getValue(lines, 'AP BSSID', ':', true);
- const quality = util.getValue(lines, 'Signal', ':', true);
- const signalLevel = wifiDBFromQuality(quality);
- const type = util.getValue(lines, 'Radio type', ':', true) || util.getValue(lines, 'Type de radio', ':', true) || util.getValue(lines, 'Funktyp', ':', true) || null;
- const security = util.getValue(lines, 'authentication', ':', true) || util.getValue(lines, 'Authentification', ':', true) || util.getValue(lines, 'Authentifizierung', ':', true) || null;
- const channel = util.getValue(lines, 'Channel', ':', true) || util.getValue(lines, 'Canal', ':', true) || util.getValue(lines, 'Kanal', ':', true) || null;
- const txRate = util.getValue(lines, 'Transmit rate (mbps)', ':', true) || util.getValue(lines, 'Transmission (mbit/s)', ':', true) || util.getValue(lines, 'Empfangsrate (MBit/s)', ':', true) || null;
- if (model && id && ssid && bssid) {
- result.push({
- id,
- iface,
- model,
- ssid,
- bssid,
- channel: util.toInt(channel),
- frequency: channel ? wifiFrequencyFromChannel(channel) : null,
- type,
- security,
- signalLevel,
- quality: quality ? parseInt(quality, 10) : null,
- txRate: util.toInt(txRate) || null
- });
- }
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- });
+class ClientDestroyedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ClientDestroyedError)
+ this.name = 'ClientDestroyedError'
+ this.message = message || 'The client is destroyed'
+ this.code = 'UND_ERR_DESTROYED'
+ }
}
-exports.wifiConnections = wifiConnections;
+class ClientClosedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ClientClosedError)
+ this.name = 'ClientClosedError'
+ this.message = message || 'The client is closed'
+ this.code = 'UND_ERR_CLOSED'
+ }
+}
-function wifiInterfaces(callback) {
+class SocketError extends UndiciError {
+ constructor (message, socket) {
+ super(message)
+ Error.captureStackTrace(this, SocketError)
+ this.name = 'SocketError'
+ this.message = message || 'Socket error'
+ this.code = 'UND_ERR_SOCKET'
+ this.socket = socket
+ }
+}
- return new Promise((resolve) => {
- process.nextTick(() => {
- const result = [];
+class NotSupportedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, NotSupportedError)
+ this.name = 'NotSupportedError'
+ this.message = message || 'Not supported error'
+ this.code = 'UND_ERR_NOT_SUPPORTED'
+ }
+}
- if (_linux) {
- const ifaces = ifaceListLinux();
- ifaces.forEach(ifaceDetail => {
- const nmiDetails = nmiDeviceLinux(ifaceDetail.iface);
- result.push({
- id: ifaceDetail.id,
- iface: ifaceDetail.iface,
- model: nmiDetails.product ? nmiDetails.product : null,
- vendor: nmiDetails.vendor ? nmiDetails.vendor : null,
- mac: ifaceDetail.mac,
- });
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- } else if (_darwin) {
- let cmd = 'system_profiler SPNetworkDataType';
- exec(cmd, function (error, stdout) {
- const parts1 = stdout.toString().split('\n\n Wi-Fi:\n\n');
- if (parts1.length > 1) {
- const lines = parts1[1].split('\n\n')[0].split('\n');
- const iface = util.getValue(lines, 'BSD Device Name', ':', true);
- const mac = util.getValue(lines, 'MAC Address', ':', true);
- const model = util.getValue(lines, 'hardware', ':', true);
- result.push({
- id: 'Wi-Fi',
- iface,
- model,
- vendor: '',
- mac
- });
- }
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else if (_windows) {
- let cmd = 'netsh wlan show interfaces';
- util.powerShell(cmd).then(function (stdout) {
- const allLines = stdout.toString().split('\r\n');
- for (let i = 0; i < allLines.length; i++) {
- allLines[i] = allLines[i].trim();
- }
- const parts = allLines.join('\r\n').split(':\r\n\r\n');
- parts.shift();
- parts.forEach(part => {
- const lines = part.split('\r\n');
- if (lines.length >= 5) {
- const iface = lines[0].indexOf(':') >= 0 ? lines[0].split(':')[1].trim() : '';
- const model = lines[1].indexOf(':') >= 0 ? lines[1].split(':')[1].trim() : '';
- const id = lines[2].indexOf(':') >= 0 ? lines[2].split(':')[1].trim() : '';
- const macParts = lines[3].indexOf(':') >= 0 ? lines[3].split(':') : [];
- macParts.shift();
- const mac = macParts.join(':').trim();
- const vendor = getVendor(model);
- if (iface && model && id && mac) {
- result.push({
- id,
- iface,
- model,
- vendor,
- mac,
- });
- }
- }
- });
- if (callback) {
- callback(result);
- }
- resolve(result);
- });
- } else {
- if (callback) {
- callback(result);
- }
- resolve(result);
- }
- });
- });
+class BalancedPoolMissingUpstreamError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, NotSupportedError)
+ this.name = 'MissingUpstreamError'
+ this.message = message || 'No upstream has been added to the BalancedPool'
+ this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
+ }
}
-exports.wifiInterfaces = wifiInterfaces;
+class HTTPParserError extends Error {
+ constructor (message, code, data) {
+ super(message)
+ Error.captureStackTrace(this, HTTPParserError)
+ this.name = 'HTTPParserError'
+ this.code = code ? `HPE_${code}` : undefined
+ this.data = data ? data.toString() : undefined
+ }
+}
+
+class ResponseExceededMaxSizeError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, ResponseExceededMaxSizeError)
+ this.name = 'ResponseExceededMaxSizeError'
+ this.message = message || 'Response content exceeded max size'
+ this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
+ }
+}
+
+class RequestRetryError extends UndiciError {
+ constructor (message, code, { headers, data }) {
+ super(message)
+ Error.captureStackTrace(this, RequestRetryError)
+ this.name = 'RequestRetryError'
+ this.message = message || 'Request retry error'
+ this.code = 'UND_ERR_REQ_RETRY'
+ this.statusCode = code
+ this.data = data
+ this.headers = headers
+ }
+}
+
+module.exports = {
+ HTTPParserError,
+ UndiciError,
+ HeadersTimeoutError,
+ HeadersOverflowError,
+ BodyTimeoutError,
+ RequestContentLengthMismatchError,
+ ConnectTimeoutError,
+ ResponseStatusCodeError,
+ InvalidArgumentError,
+ InvalidReturnValueError,
+ RequestAbortedError,
+ ClientDestroyedError,
+ ClientClosedError,
+ InformationalError,
+ SocketError,
+ NotSupportedError,
+ ResponseContentLengthMismatchError,
+ BalancedPoolMissingUpstreamError,
+ ResponseExceededMaxSizeError,
+ RequestRetryError
+}
/***/ }),
-/***/ 94176:
-/***/ ((module) => {
+/***/ 69691:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-/******************************************************************************
-Copyright (c) Microsoft Corporation.
-Permission to use, copy, modify, and/or distribute this software for any
-purpose with or without fee is hereby granted.
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
-OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-PERFORMANCE OF THIS SOFTWARE.
-***************************************************************************** */
-/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */
-var __extends;
-var __assign;
-var __rest;
-var __decorate;
-var __param;
-var __esDecorate;
-var __runInitializers;
-var __propKey;
-var __setFunctionName;
-var __metadata;
-var __awaiter;
-var __generator;
-var __exportStar;
-var __values;
-var __read;
-var __spread;
-var __spreadArrays;
-var __spreadArray;
-var __await;
-var __asyncGenerator;
-var __asyncDelegator;
-var __asyncValues;
-var __makeTemplateObject;
-var __importStar;
-var __importDefault;
-var __classPrivateFieldGet;
-var __classPrivateFieldSet;
-var __classPrivateFieldIn;
-var __createBinding;
-var __addDisposableResource;
-var __disposeResources;
-var __rewriteRelativeImportExtension;
-(function (factory) {
- var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
- if (typeof define === "function" && define.amd) {
- define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
+const {
+ InvalidArgumentError,
+ NotSupportedError
+} = __nccwpck_require__(53959)
+const assert = __nccwpck_require__(42613)
+const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(68031)
+const util = __nccwpck_require__(89500)
+
+// tokenRegExp and headerCharRegex have been lifted from
+// https://github.com/nodejs/node/blob/main/lib/_http_common.js
+
+/**
+ * Verifies that the given val is a valid HTTP token
+ * per the rules defined in RFC 7230
+ * See https://tools.ietf.org/html/rfc7230#section-3.2.6
+ */
+const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/
+
+/**
+ * Matches if val contains an invalid field-vchar
+ * field-value = *( field-content / obs-fold )
+ * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
+ * field-vchar = VCHAR / obs-text
+ */
+const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
+
+// Verifies that a given path is valid does not contain control chars \x00 to \x20
+const invalidPathRegex = /[^\u0021-\u00ff]/
+
+const kHandler = Symbol('handler')
+
+const channels = {}
+
+let extractBody
+
+try {
+ const diagnosticsChannel = __nccwpck_require__(31637)
+ channels.create = diagnosticsChannel.channel('undici:request:create')
+ channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')
+ channels.headers = diagnosticsChannel.channel('undici:request:headers')
+ channels.trailers = diagnosticsChannel.channel('undici:request:trailers')
+ channels.error = diagnosticsChannel.channel('undici:request:error')
+} catch {
+ channels.create = { hasSubscribers: false }
+ channels.bodySent = { hasSubscribers: false }
+ channels.headers = { hasSubscribers: false }
+ channels.trailers = { hasSubscribers: false }
+ channels.error = { hasSubscribers: false }
+}
+
+class Request {
+ constructor (origin, {
+ path,
+ method,
+ body,
+ headers,
+ query,
+ idempotent,
+ blocking,
+ upgrade,
+ headersTimeout,
+ bodyTimeout,
+ reset,
+ throwOnError,
+ expectContinue
+ }, handler) {
+ if (typeof path !== 'string') {
+ throw new InvalidArgumentError('path must be a string')
+ } else if (
+ path[0] !== '/' &&
+ !(path.startsWith('http://') || path.startsWith('https://')) &&
+ method !== 'CONNECT'
+ ) {
+ throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
+ } else if (invalidPathRegex.exec(path) !== null) {
+ throw new InvalidArgumentError('invalid request path')
}
- else if ( true && typeof module.exports === "object") {
- factory(createExporter(root, createExporter(module.exports)));
+
+ if (typeof method !== 'string') {
+ throw new InvalidArgumentError('method must be a string')
+ } else if (tokenRegExp.exec(method) === null) {
+ throw new InvalidArgumentError('invalid request method')
}
- else {
- factory(createExporter(root));
+
+ if (upgrade && typeof upgrade !== 'string') {
+ throw new InvalidArgumentError('upgrade must be a string')
}
- function createExporter(exports, previous) {
- if (exports !== root) {
- if (typeof Object.create === "function") {
- Object.defineProperty(exports, "__esModule", { value: true });
- }
- else {
- exports.__esModule = true;
- }
- }
- return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
+
+ if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
+ throw new InvalidArgumentError('invalid headersTimeout')
}
-})
-(function (exporter) {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
- __extends = function (d, b) {
- if (typeof b !== "function" && b !== null)
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
+ if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
+ throw new InvalidArgumentError('invalid bodyTimeout')
+ }
- __assign = Object.assign || function (t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
- }
- return t;
- };
+ if (reset != null && typeof reset !== 'boolean') {
+ throw new InvalidArgumentError('invalid reset')
+ }
- __rest = function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
- };
+ if (expectContinue != null && typeof expectContinue !== 'boolean') {
+ throw new InvalidArgumentError('invalid expectContinue')
+ }
- __decorate = function (decorators, target, key, desc) {
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
- return c > 3 && r && Object.defineProperty(target, key, r), r;
- };
+ this.headersTimeout = headersTimeout
- __param = function (paramIndex, decorator) {
- return function (target, key) { decorator(target, key, paramIndex); }
- };
+ this.bodyTimeout = bodyTimeout
- __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
- function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
- var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
- var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
- var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
- var _, done = false;
- for (var i = decorators.length - 1; i >= 0; i--) {
- var context = {};
- for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
- for (var p in contextIn.access) context.access[p] = contextIn.access[p];
- context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
- var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
- if (kind === "accessor") {
- if (result === void 0) continue;
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
- if (_ = accept(result.get)) descriptor.get = _;
- if (_ = accept(result.set)) descriptor.set = _;
- if (_ = accept(result.init)) initializers.unshift(_);
- }
- else if (_ = accept(result)) {
- if (kind === "field") initializers.unshift(_);
- else descriptor[key] = _;
- }
+ this.throwOnError = throwOnError === true
+
+ this.method = method
+
+ this.abort = null
+
+ if (body == null) {
+ this.body = null
+ } else if (util.isStream(body)) {
+ this.body = body
+
+ const rState = this.body._readableState
+ if (!rState || !rState.autoDestroy) {
+ this.endHandler = function autoDestroy () {
+ util.destroy(this)
}
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
- done = true;
- };
+ this.body.on('end', this.endHandler)
+ }
- __runInitializers = function (thisArg, initializers, value) {
- var useValue = arguments.length > 2;
- for (var i = 0; i < initializers.length; i++) {
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
+ this.errorHandler = err => {
+ if (this.abort) {
+ this.abort(err)
+ } else {
+ this.error = err
}
- return useValue ? value : void 0;
- };
+ }
+ this.body.on('error', this.errorHandler)
+ } else if (util.isBuffer(body)) {
+ this.body = body.byteLength ? body : null
+ } else if (ArrayBuffer.isView(body)) {
+ this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
+ } else if (body instanceof ArrayBuffer) {
+ this.body = body.byteLength ? Buffer.from(body) : null
+ } else if (typeof body === 'string') {
+ this.body = body.length ? Buffer.from(body) : null
+ } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {
+ this.body = body
+ } else {
+ throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
+ }
- __propKey = function (x) {
- return typeof x === "symbol" ? x : "".concat(x);
- };
+ this.completed = false
- __setFunctionName = function (f, name, prefix) {
- if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
- return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
- };
+ this.aborted = false
- __metadata = function (metadataKey, metadataValue) {
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
- };
+ this.upgrade = upgrade || null
- __awaiter = function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
- };
+ this.path = query ? util.buildURL(path, query) : path
- __generator = function (thisArg, body) {
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
- function verb(n) { return function (v) { return step([n, v]); }; }
- function step(op) {
- if (f) throw new TypeError("Generator is already executing.");
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
- if (y = 0, t) op = [op[0] & 2, t.value];
- switch (op[0]) {
- case 0: case 1: t = op; break;
- case 4: _.label++; return { value: op[1], done: false };
- case 5: _.label++; y = op[1]; op = [0]; continue;
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
- default:
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
- if (t[2]) _.ops.pop();
- _.trys.pop(); continue;
- }
- op = body.call(thisArg, _);
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
- }
- };
+ this.origin = origin
- __exportStar = function(m, o) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
- };
+ this.idempotent = idempotent == null
+ ? method === 'HEAD' || method === 'GET'
+ : idempotent
- __createBinding = Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- });
+ this.blocking = blocking == null ? false : blocking
- __values = function (o) {
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
- if (m) return m.call(o);
- if (o && typeof o.length === "number") return {
- next: function () {
- if (o && i >= o.length) o = void 0;
- return { value: o && o[i++], done: !o };
- }
- };
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
- };
+ this.reset = reset == null ? null : reset
- __read = function (o, n) {
- var m = typeof Symbol === "function" && o[Symbol.iterator];
- if (!m) return o;
- var i = m.call(o), r, ar = [], e;
- try {
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
- }
- catch (error) { e = { error: error }; }
- finally {
- try {
- if (r && !r.done && (m = i["return"])) m.call(i);
- }
- finally { if (e) throw e.error; }
- }
- return ar;
- };
+ this.host = null
- /** @deprecated */
- __spread = function () {
- for (var ar = [], i = 0; i < arguments.length; i++)
- ar = ar.concat(__read(arguments[i]));
- return ar;
- };
+ this.contentLength = null
- /** @deprecated */
- __spreadArrays = function () {
- for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
- for (var r = Array(s), k = 0, i = 0; i < il; i++)
- for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
- r[k] = a[j];
- return r;
- };
+ this.contentType = null
- __spreadArray = function (to, from, pack) {
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
- if (ar || !(i in from)) {
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
- ar[i] = from[i];
- }
- }
- return to.concat(ar || Array.prototype.slice.call(from));
- };
+ this.headers = ''
+
+ // Only for H2
+ this.expectContinue = expectContinue != null ? expectContinue : false
+
+ if (Array.isArray(headers)) {
+ if (headers.length % 2 !== 0) {
+ throw new InvalidArgumentError('headers array must be even')
+ }
+ for (let i = 0; i < headers.length; i += 2) {
+ processHeader(this, headers[i], headers[i + 1])
+ }
+ } else if (headers && typeof headers === 'object') {
+ const keys = Object.keys(headers)
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i]
+ processHeader(this, key, headers[key])
+ }
+ } else if (headers != null) {
+ throw new InvalidArgumentError('headers must be an object or an array')
+ }
+
+ if (util.isFormDataLike(this.body)) {
+ if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {
+ throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')
+ }
+
+ if (!extractBody) {
+ extractBody = (__nccwpck_require__(37791).extractBody)
+ }
+
+ const [bodyStream, contentType] = extractBody(body)
+ if (this.contentType == null) {
+ this.contentType = contentType
+ this.headers += `content-type: ${contentType}\r\n`
+ }
+ this.body = bodyStream.stream
+ this.contentLength = bodyStream.length
+ } else if (util.isBlobLike(body) && this.contentType == null && body.type) {
+ this.contentType = body.type
+ this.headers += `content-type: ${body.type}\r\n`
+ }
+
+ util.validateHandler(handler, method, upgrade)
+
+ this.servername = util.getServerName(this.host)
+
+ this[kHandler] = handler
+
+ if (channels.create.hasSubscribers) {
+ channels.create.publish({ request: this })
+ }
+ }
+
+ onBodySent (chunk) {
+ if (this[kHandler].onBodySent) {
+ try {
+ return this[kHandler].onBodySent(chunk)
+ } catch (err) {
+ this.abort(err)
+ }
+ }
+ }
- __await = function (v) {
- return this instanceof __await ? (this.v = v, this) : new __await(v);
- };
+ onRequestSent () {
+ if (channels.bodySent.hasSubscribers) {
+ channels.bodySent.publish({ request: this })
+ }
- __asyncGenerator = function (thisArg, _arguments, generator) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
- return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
- function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
- function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
- function fulfill(value) { resume("next", value); }
- function reject(value) { resume("throw", value); }
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
- };
+ if (this[kHandler].onRequestSent) {
+ try {
+ return this[kHandler].onRequestSent()
+ } catch (err) {
+ this.abort(err)
+ }
+ }
+ }
- __asyncDelegator = function (o) {
- var i, p;
- return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
- function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
- };
+ onConnect (abort) {
+ assert(!this.aborted)
+ assert(!this.completed)
- __asyncValues = function (o) {
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
- var m = o[Symbol.asyncIterator], i;
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
- };
+ if (this.error) {
+ abort(this.error)
+ } else {
+ this.abort = abort
+ return this[kHandler].onConnect(abort)
+ }
+ }
- __makeTemplateObject = function (cooked, raw) {
- if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
- return cooked;
- };
+ onHeaders (statusCode, headers, resume, statusText) {
+ assert(!this.aborted)
+ assert(!this.completed)
- var __setModuleDefault = Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- };
+ if (channels.headers.hasSubscribers) {
+ channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
+ }
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
+ try {
+ return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
+ } catch (err) {
+ this.abort(err)
+ }
+ }
- __importStar = function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
+ onData (chunk) {
+ assert(!this.aborted)
+ assert(!this.completed)
- __importDefault = function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
- };
+ try {
+ return this[kHandler].onData(chunk)
+ } catch (err) {
+ this.abort(err)
+ return false
+ }
+ }
- __classPrivateFieldGet = function (receiver, state, kind, f) {
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
- };
+ onUpgrade (statusCode, headers, socket) {
+ assert(!this.aborted)
+ assert(!this.completed)
- __classPrivateFieldSet = function (receiver, state, value, kind, f) {
- if (kind === "m") throw new TypeError("Private method is not writable");
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
- };
+ return this[kHandler].onUpgrade(statusCode, headers, socket)
+ }
- __classPrivateFieldIn = function (state, receiver) {
- if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
- return typeof state === "function" ? receiver === state : state.has(receiver);
- };
+ onComplete (trailers) {
+ this.onFinally()
- __addDisposableResource = function (env, value, async) {
- if (value !== null && value !== void 0) {
- if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
- var dispose, inner;
- if (async) {
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
- dispose = value[Symbol.asyncDispose];
- }
- if (dispose === void 0) {
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
- dispose = value[Symbol.dispose];
- if (async) inner = dispose;
- }
- if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
- if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
- env.stack.push({ value: value, dispose: dispose, async: async });
- }
- else if (async) {
- env.stack.push({ async: true });
- }
- return value;
- };
+ assert(!this.aborted)
- var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
- var e = new Error(message);
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
- };
+ this.completed = true
+ if (channels.trailers.hasSubscribers) {
+ channels.trailers.publish({ request: this, trailers })
+ }
- __disposeResources = function (env) {
- function fail(e) {
- env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
- env.hasError = true;
- }
- var r, s = 0;
- function next() {
- while (r = env.stack.pop()) {
- try {
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
- if (r.dispose) {
- var result = r.dispose.call(r.value);
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
- }
- else s |= 1;
- }
- catch (e) {
- fail(e);
- }
- }
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
- if (env.hasError) throw env.error;
- }
- return next();
- };
+ try {
+ return this[kHandler].onComplete(trailers)
+ } catch (err) {
+ // TODO (fix): This might be a bad idea?
+ this.onError(err)
+ }
+ }
- __rewriteRelativeImportExtension = function (path, preserveJsx) {
- if (typeof path === "string" && /^\.\.?\//.test(path)) {
- return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
- return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
- });
- }
- return path;
- };
+ onError (error) {
+ this.onFinally()
- exporter("__extends", __extends);
- exporter("__assign", __assign);
- exporter("__rest", __rest);
- exporter("__decorate", __decorate);
- exporter("__param", __param);
- exporter("__esDecorate", __esDecorate);
- exporter("__runInitializers", __runInitializers);
- exporter("__propKey", __propKey);
- exporter("__setFunctionName", __setFunctionName);
- exporter("__metadata", __metadata);
- exporter("__awaiter", __awaiter);
- exporter("__generator", __generator);
- exporter("__exportStar", __exportStar);
- exporter("__createBinding", __createBinding);
- exporter("__values", __values);
- exporter("__read", __read);
- exporter("__spread", __spread);
- exporter("__spreadArrays", __spreadArrays);
- exporter("__spreadArray", __spreadArray);
- exporter("__await", __await);
- exporter("__asyncGenerator", __asyncGenerator);
- exporter("__asyncDelegator", __asyncDelegator);
- exporter("__asyncValues", __asyncValues);
- exporter("__makeTemplateObject", __makeTemplateObject);
- exporter("__importStar", __importStar);
- exporter("__importDefault", __importDefault);
- exporter("__classPrivateFieldGet", __classPrivateFieldGet);
- exporter("__classPrivateFieldSet", __classPrivateFieldSet);
- exporter("__classPrivateFieldIn", __classPrivateFieldIn);
- exporter("__addDisposableResource", __addDisposableResource);
- exporter("__disposeResources", __disposeResources);
- exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension);
-});
+ if (channels.error.hasSubscribers) {
+ channels.error.publish({ request: this, error })
+ }
-0 && (0);
+ if (this.aborted) {
+ return
+ }
+ this.aborted = true
+ return this[kHandler].onError(error)
+ }
-/***/ }),
+ onFinally () {
+ if (this.errorHandler) {
+ this.body.off('error', this.errorHandler)
+ this.errorHandler = null
+ }
-/***/ 5070:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (this.endHandler) {
+ this.body.off('end', this.endHandler)
+ this.endHandler = null
+ }
+ }
-module.exports = __nccwpck_require__(35862);
+ // TODO: adjust to support H2
+ addHeader (key, value) {
+ processHeader(this, key, value)
+ return this
+ }
+ static [kHTTP1BuildRequest] (origin, opts, handler) {
+ // TODO: Migrate header parsing here, to make Requests
+ // HTTP agnostic
+ return new Request(origin, opts, handler)
+ }
-/***/ }),
+ static [kHTTP2BuildRequest] (origin, opts, handler) {
+ const headers = opts.headers
+ opts = { ...opts, headers: null }
-/***/ 35862:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ const request = new Request(origin, opts, handler)
+ request.headers = {}
+ if (Array.isArray(headers)) {
+ if (headers.length % 2 !== 0) {
+ throw new InvalidArgumentError('headers array must be even')
+ }
+ for (let i = 0; i < headers.length; i += 2) {
+ processHeader(request, headers[i], headers[i + 1], true)
+ }
+ } else if (headers && typeof headers === 'object') {
+ const keys = Object.keys(headers)
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i]
+ processHeader(request, key, headers[key], true)
+ }
+ } else if (headers != null) {
+ throw new InvalidArgumentError('headers must be an object or an array')
+ }
-var net = __nccwpck_require__(69278);
-var tls = __nccwpck_require__(64756);
-var http = __nccwpck_require__(58611);
-var https = __nccwpck_require__(65692);
-var events = __nccwpck_require__(24434);
-var assert = __nccwpck_require__(42613);
-var util = __nccwpck_require__(39023);
+ return request
+ }
+ static [kHTTP2CopyHeaders] (raw) {
+ const rawHeaders = raw.split('\r\n')
+ const headers = {}
-exports.httpOverHttp = httpOverHttp;
-exports.httpsOverHttp = httpsOverHttp;
-exports.httpOverHttps = httpOverHttps;
-exports.httpsOverHttps = httpsOverHttps;
+ for (const header of rawHeaders) {
+ const [key, value] = header.split(': ')
+ if (value == null || value.length === 0) continue
-function httpOverHttp(options) {
- var agent = new TunnelingAgent(options);
- agent.request = http.request;
- return agent;
-}
+ if (headers[key]) headers[key] += `,${value}`
+ else headers[key] = value
+ }
-function httpsOverHttp(options) {
- var agent = new TunnelingAgent(options);
- agent.request = http.request;
- agent.createSocket = createSecureSocket;
- agent.defaultPort = 443;
- return agent;
+ return headers
+ }
}
-function httpOverHttps(options) {
- var agent = new TunnelingAgent(options);
- agent.request = https.request;
- return agent;
-}
+function processHeaderValue (key, val, skipAppend) {
+ if (val && typeof val === 'object') {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ }
-function httpsOverHttps(options) {
- var agent = new TunnelingAgent(options);
- agent.request = https.request;
- agent.createSocket = createSecureSocket;
- agent.defaultPort = 443;
- return agent;
-}
+ val = val != null ? `${val}` : ''
+ if (headerCharRegex.exec(val) !== null) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ }
-function TunnelingAgent(options) {
- var self = this;
- self.options = options || {};
- self.proxyOptions = self.options.proxy || {};
- self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets;
- self.requests = [];
- self.sockets = [];
+ return skipAppend ? val : `${key}: ${val}\r\n`
+}
- self.on('free', function onFree(socket, host, port, localAddress) {
- var options = toOptions(host, port, localAddress);
- for (var i = 0, len = self.requests.length; i < len; ++i) {
- var pending = self.requests[i];
- if (pending.host === options.host && pending.port === options.port) {
- // Detect the request to connect same origin server,
- // reuse the connection.
- self.requests.splice(i, 1);
- pending.request.onSocket(socket);
- return;
+function processHeader (request, key, val, skipAppend = false) {
+ if (val && (typeof val === 'object' && !Array.isArray(val))) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ } else if (val === undefined) {
+ return
+ }
+
+ if (
+ request.host === null &&
+ key.length === 4 &&
+ key.toLowerCase() === 'host'
+ ) {
+ if (headerCharRegex.exec(val) !== null) {
+ throw new InvalidArgumentError(`invalid ${key} header`)
+ }
+ // Consumed by Client
+ request.host = val
+ } else if (
+ request.contentLength === null &&
+ key.length === 14 &&
+ key.toLowerCase() === 'content-length'
+ ) {
+ request.contentLength = parseInt(val, 10)
+ if (!Number.isFinite(request.contentLength)) {
+ throw new InvalidArgumentError('invalid content-length header')
+ }
+ } else if (
+ request.contentType === null &&
+ key.length === 12 &&
+ key.toLowerCase() === 'content-type'
+ ) {
+ request.contentType = val
+ if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
+ else request.headers += processHeaderValue(key, val)
+ } else if (
+ key.length === 17 &&
+ key.toLowerCase() === 'transfer-encoding'
+ ) {
+ throw new InvalidArgumentError('invalid transfer-encoding header')
+ } else if (
+ key.length === 10 &&
+ key.toLowerCase() === 'connection'
+ ) {
+ const value = typeof val === 'string' ? val.toLowerCase() : null
+ if (value !== 'close' && value !== 'keep-alive') {
+ throw new InvalidArgumentError('invalid connection header')
+ } else if (value === 'close') {
+ request.reset = true
+ }
+ } else if (
+ key.length === 10 &&
+ key.toLowerCase() === 'keep-alive'
+ ) {
+ throw new InvalidArgumentError('invalid keep-alive header')
+ } else if (
+ key.length === 7 &&
+ key.toLowerCase() === 'upgrade'
+ ) {
+ throw new InvalidArgumentError('invalid upgrade header')
+ } else if (
+ key.length === 6 &&
+ key.toLowerCase() === 'expect'
+ ) {
+ throw new NotSupportedError('expect header not supported')
+ } else if (tokenRegExp.exec(key) === null) {
+ throw new InvalidArgumentError('invalid header key')
+ } else {
+ if (Array.isArray(val)) {
+ for (let i = 0; i < val.length; i++) {
+ if (skipAppend) {
+ if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`
+ else request.headers[key] = processHeaderValue(key, val[i], skipAppend)
+ } else {
+ request.headers += processHeaderValue(key, val[i])
+ }
}
+ } else {
+ if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
+ else request.headers += processHeaderValue(key, val)
}
- socket.destroy();
- self.removeSocket(socket);
- });
+ }
}
-util.inherits(TunnelingAgent, events.EventEmitter);
-TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) {
- var self = this;
- var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress));
+module.exports = Request
- if (self.sockets.length >= this.maxSockets) {
- // We are over limit so we'll add it to the queue.
- self.requests.push(options);
- return;
- }
- // If we are under maxSockets create a new one.
- self.createSocket(options, function(socket) {
- socket.on('free', onFree);
- socket.on('close', onCloseOrRemove);
- socket.on('agentRemove', onCloseOrRemove);
- req.onSocket(socket);
+/***/ }),
+
+/***/ 68031:
+/***/ ((module) => {
+
+module.exports = {
+ kClose: Symbol('close'),
+ kDestroy: Symbol('destroy'),
+ kDispatch: Symbol('dispatch'),
+ kUrl: Symbol('url'),
+ kWriting: Symbol('writing'),
+ kResuming: Symbol('resuming'),
+ kQueue: Symbol('queue'),
+ kConnect: Symbol('connect'),
+ kConnecting: Symbol('connecting'),
+ kHeadersList: Symbol('headers list'),
+ kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
+ kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
+ kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
+ kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
+ kKeepAlive: Symbol('keep alive'),
+ kHeadersTimeout: Symbol('headers timeout'),
+ kBodyTimeout: Symbol('body timeout'),
+ kServerName: Symbol('server name'),
+ kLocalAddress: Symbol('local address'),
+ kHost: Symbol('host'),
+ kNoRef: Symbol('no ref'),
+ kBodyUsed: Symbol('used'),
+ kRunning: Symbol('running'),
+ kBlocking: Symbol('blocking'),
+ kPending: Symbol('pending'),
+ kSize: Symbol('size'),
+ kBusy: Symbol('busy'),
+ kQueued: Symbol('queued'),
+ kFree: Symbol('free'),
+ kConnected: Symbol('connected'),
+ kClosed: Symbol('closed'),
+ kNeedDrain: Symbol('need drain'),
+ kReset: Symbol('reset'),
+ kDestroyed: Symbol.for('nodejs.stream.destroyed'),
+ kMaxHeadersSize: Symbol('max headers size'),
+ kRunningIdx: Symbol('running index'),
+ kPendingIdx: Symbol('pending index'),
+ kError: Symbol('error'),
+ kClients: Symbol('clients'),
+ kClient: Symbol('client'),
+ kParser: Symbol('parser'),
+ kOnDestroyed: Symbol('destroy callbacks'),
+ kPipelining: Symbol('pipelining'),
+ kSocket: Symbol('socket'),
+ kHostHeader: Symbol('host header'),
+ kConnector: Symbol('connector'),
+ kStrictContentLength: Symbol('strict content length'),
+ kMaxRedirections: Symbol('maxRedirections'),
+ kMaxRequests: Symbol('maxRequestsPerClient'),
+ kProxy: Symbol('proxy agent options'),
+ kCounter: Symbol('socket request counter'),
+ kInterceptors: Symbol('dispatch interceptors'),
+ kMaxResponseSize: Symbol('max response size'),
+ kHTTP2Session: Symbol('http2Session'),
+ kHTTP2SessionState: Symbol('http2Session state'),
+ kHTTP2BuildRequest: Symbol('http2 build request'),
+ kHTTP1BuildRequest: Symbol('http1 build request'),
+ kHTTP2CopyHeaders: Symbol('http2 copy headers'),
+ kHTTPConnVersion: Symbol('http connection version'),
+ kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
+ kConstruct: Symbol('constructable')
+}
- function onFree() {
- self.emit('free', socket, options);
- }
- function onCloseOrRemove(err) {
- self.removeSocket(socket);
- socket.removeListener('free', onFree);
- socket.removeListener('close', onCloseOrRemove);
- socket.removeListener('agentRemove', onCloseOrRemove);
- }
- });
-};
+/***/ }),
-TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
- var self = this;
- var placeholder = {};
- self.sockets.push(placeholder);
+/***/ 89500:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- var connectOptions = mergeOptions({}, self.proxyOptions, {
- method: 'CONNECT',
- path: options.host + ':' + options.port,
- agent: false,
- headers: {
- host: options.host + ':' + options.port
- }
- });
- if (options.localAddress) {
- connectOptions.localAddress = options.localAddress;
- }
- if (connectOptions.proxyAuth) {
- connectOptions.headers = connectOptions.headers || {};
- connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
- new Buffer(connectOptions.proxyAuth).toString('base64');
- }
- debug('making CONNECT request');
- var connectReq = self.request(connectOptions);
- connectReq.useChunkedEncodingByDefault = false; // for v0.6
- connectReq.once('response', onResponse); // for v0.6
- connectReq.once('upgrade', onUpgrade); // for v0.6
- connectReq.once('connect', onConnect); // for v0.7 or later
- connectReq.once('error', onError);
- connectReq.end();
- function onResponse(res) {
- // Very hacky. This is necessary to avoid http-parser leaks.
- res.upgrade = true;
- }
+const assert = __nccwpck_require__(42613)
+const { kDestroyed, kBodyUsed } = __nccwpck_require__(68031)
+const { IncomingMessage } = __nccwpck_require__(58611)
+const stream = __nccwpck_require__(2203)
+const net = __nccwpck_require__(69278)
+const { InvalidArgumentError } = __nccwpck_require__(53959)
+const { Blob } = __nccwpck_require__(20181)
+const nodeUtil = __nccwpck_require__(39023)
+const { stringify } = __nccwpck_require__(83480)
+const { headerNameLowerCasedRecord } = __nccwpck_require__(42371)
- function onUpgrade(res, socket, head) {
- // Hacky.
- process.nextTick(function() {
- onConnect(res, socket, head);
- });
- }
+const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
- function onConnect(res, socket, head) {
- connectReq.removeAllListeners();
- socket.removeAllListeners();
+function nop () {}
- if (res.statusCode !== 200) {
- debug('tunneling socket could not be established, statusCode=%d',
- res.statusCode);
- socket.destroy();
- var error = new Error('tunneling socket could not be established, ' +
- 'statusCode=' + res.statusCode);
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
- return;
- }
- if (head.length > 0) {
- debug('got illegal response body from proxy');
- socket.destroy();
- var error = new Error('got illegal response body from proxy');
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
- return;
- }
- debug('tunneling connection has established');
- self.sockets[self.sockets.indexOf(placeholder)] = socket;
- return cb(socket);
- }
+function isStream (obj) {
+ return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
+}
- function onError(cause) {
- connectReq.removeAllListeners();
+// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
+function isBlobLike (object) {
+ return (Blob && object instanceof Blob) || (
+ object &&
+ typeof object === 'object' &&
+ (typeof object.stream === 'function' ||
+ typeof object.arrayBuffer === 'function') &&
+ /^(Blob|File)$/.test(object[Symbol.toStringTag])
+ )
+}
- debug('tunneling socket could not be established, cause=%s\n',
- cause.message, cause.stack);
- var error = new Error('tunneling socket could not be established, ' +
- 'cause=' + cause.message);
- error.code = 'ECONNRESET';
- options.request.emit('error', error);
- self.removeSocket(placeholder);
+function buildURL (url, queryParams) {
+ if (url.includes('?') || url.includes('#')) {
+ throw new Error('Query params cannot be passed when url already contains "?" or "#".')
}
-};
-TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
- var pos = this.sockets.indexOf(socket)
- if (pos === -1) {
- return;
- }
- this.sockets.splice(pos, 1);
+ const stringified = stringify(queryParams)
- var pending = this.requests.shift();
- if (pending) {
- // If we have pending requests and a socket gets closed a new one
- // needs to be created to take over in the pool for the one that closed.
- this.createSocket(pending, function(socket) {
- pending.request.onSocket(socket);
- });
+ if (stringified) {
+ url += '?' + stringified
}
-};
-
-function createSecureSocket(options, cb) {
- var self = this;
- TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
- var hostHeader = options.request.getHeader('host');
- var tlsOptions = mergeOptions({}, self.options, {
- socket: socket,
- servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host
- });
- // 0 is dummy port for v0.6
- var secureSocket = tls.connect(0, tlsOptions);
- self.sockets[self.sockets.indexOf(socket)] = secureSocket;
- cb(secureSocket);
- });
+ return url
}
+function parseURL (url) {
+ if (typeof url === 'string') {
+ url = new URL(url)
-function toOptions(host, port, localAddress) {
- if (typeof host === 'string') { // since v0.10
- return {
- host: host,
- port: port,
- localAddress: localAddress
- };
- }
- return host; // for v0.11 or later
-}
-
-function mergeOptions(target) {
- for (var i = 1, len = arguments.length; i < len; ++i) {
- var overrides = arguments[i];
- if (typeof overrides === 'object') {
- var keys = Object.keys(overrides);
- for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
- var k = keys[j];
- if (overrides[k] !== undefined) {
- target[k] = overrides[k];
- }
- }
+ if (!/^https?:/.test(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
}
- }
- return target;
-}
-
-var debug;
-if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
- debug = function() {
- var args = Array.prototype.slice.call(arguments);
- if (typeof args[0] === 'string') {
- args[0] = 'TUNNEL: ' + args[0];
- } else {
- args.unshift('TUNNEL:');
- }
- console.error.apply(console, args);
+ return url
}
-} else {
- debug = function() {};
-}
-exports.debug = debug; // for test
-
-/***/ }),
+ if (!url || typeof url !== 'object') {
+ throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
+ }
-/***/ 99069:
-/***/ ((__unused_webpack_module, exports) => {
+ if (!/^https?:/.test(url.origin || url.protocol)) {
+ throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
+ }
+ if (!(url instanceof URL)) {
+ if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {
+ throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
+ }
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+ if (url.path != null && typeof url.path !== 'string') {
+ throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
+ }
+ if (url.pathname != null && typeof url.pathname !== 'string') {
+ throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
+ }
-/***/ }),
+ if (url.hostname != null && typeof url.hostname !== 'string') {
+ throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
+ }
-/***/ 28775:
-/***/ ((__unused_webpack_module, exports) => {
+ if (url.origin != null && typeof url.origin !== 'string') {
+ throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
+ }
+ const port = url.port != null
+ ? url.port
+ : (url.protocol === 'https:' ? 443 : 80)
+ let origin = url.origin != null
+ ? url.origin
+ : `${url.protocol}//${url.hostname}:${port}`
+ let path = url.path != null
+ ? url.path
+ : `${url.pathname || ''}${url.search || ''}`
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isValidErrorCode = exports.httpStatusFromErrorCode = exports.TwirpErrorCode = exports.BadRouteError = exports.InternalServerErrorWith = exports.InternalServerError = exports.RequiredArgumentError = exports.InvalidArgumentError = exports.NotFoundError = exports.TwirpError = void 0;
-/**
- * Represents a twirp error
- */
-class TwirpError extends Error {
- constructor(code, msg) {
- super(msg);
- this.code = TwirpErrorCode.Internal;
- this.meta = {};
- this.code = code;
- this.msg = msg;
- Object.setPrototypeOf(this, TwirpError.prototype);
- }
- /**
- * Adds a metadata kv to the error
- * @param key
- * @param value
- */
- withMeta(key, value) {
- this.meta[key] = value;
- return this;
- }
- /**
- * Returns a single metadata value
- * return "" if not found
- * @param key
- */
- getMeta(key) {
- return this.meta[key] || "";
- }
- /**
- * Add the original error cause
- * @param err
- * @param addMeta
- */
- withCause(err, addMeta = false) {
- this._originalCause = err;
- if (addMeta) {
- this.withMeta("cause", err.message);
- }
- return this;
- }
- cause() {
- return this._originalCause;
- }
- /**
- * Returns the error representation to JSON
- */
- toJSON() {
- try {
- return JSON.stringify({
- code: this.code,
- msg: this.msg,
- meta: this.meta,
- });
- }
- catch (e) {
- return `{"code": "internal", "msg": "There was an error but it could not be serialized into JSON"}`;
- }
- }
- /**
- * Create a twirp error from an object
- * @param obj
- */
- static fromObject(obj) {
- const code = obj["code"] || TwirpErrorCode.Unknown;
- const msg = obj["msg"] || "unknown";
- const error = new TwirpError(code, msg);
- if (obj["meta"]) {
- Object.keys(obj["meta"]).forEach((key) => {
- error.withMeta(key, obj["meta"][key]);
- });
- }
- return error;
- }
-}
-exports.TwirpError = TwirpError;
-/**
- * NotFoundError constructor for the common NotFound error.
- */
-class NotFoundError extends TwirpError {
- constructor(msg) {
- super(TwirpErrorCode.NotFound, msg);
- }
-}
-exports.NotFoundError = NotFoundError;
-/**
- * InvalidArgumentError constructor for the common InvalidArgument error. Can be
- * used when an argument has invalid format, is a number out of range, is a bad
- * option, etc).
- */
-class InvalidArgumentError extends TwirpError {
- constructor(argument, validationMsg) {
- super(TwirpErrorCode.InvalidArgument, argument + " " + validationMsg);
- this.withMeta("argument", argument);
- }
-}
-exports.InvalidArgumentError = InvalidArgumentError;
-/**
- * RequiredArgumentError is a more specific constructor for InvalidArgument
- * error. Should be used when the argument is required (expected to have a
- * non-zero value).
- */
-class RequiredArgumentError extends InvalidArgumentError {
- constructor(argument) {
- super(argument, "is required");
- }
-}
-exports.RequiredArgumentError = RequiredArgumentError;
-/**
- * InternalError constructor for the common Internal error. Should be used to
- * specify that something bad or unexpected happened.
- */
-class InternalServerError extends TwirpError {
- constructor(msg) {
- super(TwirpErrorCode.Internal, msg);
- }
-}
-exports.InternalServerError = InternalServerError;
-/**
- * InternalErrorWith makes an internal error, wrapping the original error and using it
- * for the error message, and with metadata "cause" with the original error type.
- * This function is used by Twirp services to wrap non-Twirp errors as internal errors.
- * The wrapped error can be extracted later with err.cause()
- */
-class InternalServerErrorWith extends InternalServerError {
- constructor(err) {
- super(err.message);
- this.withMeta("cause", err.name);
- this.withCause(err);
- }
-}
-exports.InternalServerErrorWith = InternalServerErrorWith;
-/**
- * A standard BadRoute Error
- */
-class BadRouteError extends TwirpError {
- constructor(msg, method, url) {
- super(TwirpErrorCode.BadRoute, msg);
- this.withMeta("twirp_invalid_route", method + " " + url);
- }
-}
-exports.BadRouteError = BadRouteError;
-var TwirpErrorCode;
-(function (TwirpErrorCode) {
- // Canceled indicates the operation was cancelled (typically by the caller).
- TwirpErrorCode["Canceled"] = "canceled";
- // Unknown error. For example when handling errors raised by APIs that do not
- // return enough error information.
- TwirpErrorCode["Unknown"] = "unknown";
- // InvalidArgument indicates client specified an invalid argument. It
- // indicates arguments that are problematic regardless of the state of the
- // system (i.e. a malformed file name, required argument, number out of range,
- // etc.).
- TwirpErrorCode["InvalidArgument"] = "invalid_argument";
- // Malformed indicates an error occurred while decoding the client's request.
- // This may mean that the message was encoded improperly, or that there is a
- // disagreement in message format between the client and server.
- TwirpErrorCode["Malformed"] = "malformed";
- // DeadlineExceeded means operation expired before completion. For operations
- // that change the state of the system, this error may be returned even if the
- // operation has completed successfully (timeout).
- TwirpErrorCode["DeadlineExceeded"] = "deadline_exceeded";
- // NotFound means some requested entity was not found.
- TwirpErrorCode["NotFound"] = "not_found";
- // BadRoute means that the requested URL path wasn't routable to a Twirp
- // service and method. This is returned by the generated server, and usually
- // shouldn't be returned by applications. Instead, applications should use
- // NotFound or Unimplemented.
- TwirpErrorCode["BadRoute"] = "bad_route";
- // AlreadyExists means an attempt to create an entity failed because one
- // already exists.
- TwirpErrorCode["AlreadyExists"] = "already_exists";
- // PermissionDenied indicates the caller does not have permission to execute
- // the specified operation. It must not be used if the caller cannot be
- // identified (Unauthenticated).
- TwirpErrorCode["PermissionDenied"] = "permission_denied";
- // Unauthenticated indicates the request does not have valid authentication
- // credentials for the operation.
- TwirpErrorCode["Unauthenticated"] = "unauthenticated";
- // ResourceExhausted indicates some resource has been exhausted, perhaps a
- // per-user quota, or perhaps the entire file system is out of space.
- TwirpErrorCode["ResourceExhausted"] = "resource_exhausted";
- // FailedPrecondition indicates operation was rejected because the system is
- // not in a state required for the operation's execution. For example, doing
- // an rmdir operation on a directory that is non-empty, or on a non-directory
- // object, or when having conflicting read-modify-write on the same resource.
- TwirpErrorCode["FailedPrecondition"] = "failed_precondition";
- // Aborted indicates the operation was aborted, typically due to a concurrency
- // issue like sequencer check failures, transaction aborts, etc.
- TwirpErrorCode["Aborted"] = "aborted";
- // OutOfRange means operation was attempted past the valid range. For example,
- // seeking or reading past end of a paginated collection.
- //
- // Unlike InvalidArgument, this error indicates a problem that may be fixed if
- // the system state changes (i.e. adding more items to the collection).
- //
- // There is a fair bit of overlap between FailedPrecondition and OutOfRange.
- // We recommend using OutOfRange (the more specific error) when it applies so
- // that callers who are iterating through a space can easily look for an
- // OutOfRange error to detect when they are done.
- TwirpErrorCode["OutOfRange"] = "out_of_range";
- // Unimplemented indicates operation is not implemented or not
- // supported/enabled in this service.
- TwirpErrorCode["Unimplemented"] = "unimplemented";
- // Internal errors. When some invariants expected by the underlying system
- // have been broken. In other words, something bad happened in the library or
- // backend service. Do not confuse with HTTP Internal Server Error; an
- // Internal error could also happen on the client code, i.e. when parsing a
- // server response.
- TwirpErrorCode["Internal"] = "internal";
- // Unavailable indicates the service is currently unavailable. This is a most
- // likely a transient condition and may be corrected by retrying with a
- // backoff.
- TwirpErrorCode["Unavailable"] = "unavailable";
- // DataLoss indicates unrecoverable data loss or corruption.
- TwirpErrorCode["DataLoss"] = "data_loss";
-})(TwirpErrorCode = exports.TwirpErrorCode || (exports.TwirpErrorCode = {}));
-// ServerHTTPStatusFromErrorCode maps a Twirp error type into a similar HTTP
-// response status. It is used by the Twirp server handler to set the HTTP
-// response status code. Returns 0 if the ErrorCode is invalid.
-function httpStatusFromErrorCode(code) {
- switch (code) {
- case TwirpErrorCode.Canceled:
- return 408; // RequestTimeout
- case TwirpErrorCode.Unknown:
- return 500; // Internal Server Error
- case TwirpErrorCode.InvalidArgument:
- return 400; // BadRequest
- case TwirpErrorCode.Malformed:
- return 400; // BadRequest
- case TwirpErrorCode.DeadlineExceeded:
- return 408; // RequestTimeout
- case TwirpErrorCode.NotFound:
- return 404; // Not Found
- case TwirpErrorCode.BadRoute:
- return 404; // Not Found
- case TwirpErrorCode.AlreadyExists:
- return 409; // Conflict
- case TwirpErrorCode.PermissionDenied:
- return 403; // Forbidden
- case TwirpErrorCode.Unauthenticated:
- return 401; // Unauthorized
- case TwirpErrorCode.ResourceExhausted:
- return 429; // Too Many Requests
- case TwirpErrorCode.FailedPrecondition:
- return 412; // Precondition Failed
- case TwirpErrorCode.Aborted:
- return 409; // Conflict
- case TwirpErrorCode.OutOfRange:
- return 400; // Bad Request
- case TwirpErrorCode.Unimplemented:
- return 501; // Not Implemented
- case TwirpErrorCode.Internal:
- return 500; // Internal Server Error
- case TwirpErrorCode.Unavailable:
- return 503; // Service Unavailable
- case TwirpErrorCode.DataLoss:
- return 500; // Internal Server Error
- default:
- return 0; // Invalid!
+ if (origin.endsWith('/')) {
+ origin = origin.substring(0, origin.length - 1)
+ }
+
+ if (path && !path.startsWith('/')) {
+ path = `/${path}`
}
+ // new URL(path, origin) is unsafe when `path` contains an absolute URL
+ // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
+ // If first parameter is a relative URL, second param is required, and will be used as the base URL.
+ // If first parameter is an absolute URL, a given second param will be ignored.
+ url = new URL(origin + path)
+ }
+
+ return url
}
-exports.httpStatusFromErrorCode = httpStatusFromErrorCode;
-// IsValidErrorCode returns true if is one of the valid predefined constants.
-function isValidErrorCode(code) {
- return httpStatusFromErrorCode(code) != 0;
+
+function parseOrigin (url) {
+ url = parseURL(url)
+
+ if (url.pathname !== '/' || url.search || url.hash) {
+ throw new InvalidArgumentError('invalid url')
+ }
+
+ return url
}
-exports.isValidErrorCode = isValidErrorCode;
+function getHostname (host) {
+ if (host[0] === '[') {
+ const idx = host.indexOf(']')
-/***/ }),
+ assert(idx !== -1)
+ return host.substring(1, idx)
+ }
-/***/ 70048:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ const idx = host.indexOf(':')
+ if (idx === -1) return host
+ return host.substring(0, idx)
+}
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-var __rest = (this && this.__rest) || function (s, e) {
- var t = {};
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
- t[p] = s[p];
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
- t[p[i]] = s[p[i]];
- }
- return t;
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Gateway = exports.Pattern = void 0;
-const querystring_1 = __nccwpck_require__(83480);
-const dotObject = __importStar(__nccwpck_require__(98749));
-const request_1 = __nccwpck_require__(21179);
-const errors_1 = __nccwpck_require__(28775);
-const http_client_1 = __nccwpck_require__(52503);
-const server_1 = __nccwpck_require__(1991);
-var Pattern;
-(function (Pattern) {
- Pattern["POST"] = "post";
- Pattern["GET"] = "get";
- Pattern["PATCH"] = "patch";
- Pattern["PUT"] = "put";
- Pattern["DELETE"] = "delete";
-})(Pattern = exports.Pattern || (exports.Pattern = {}));
-/**
- * The Gateway proxies http requests to Twirp Compliant
- * handlers
- */
-class Gateway {
- constructor(routes) {
- this.routes = routes;
- }
- /**
- * Middleware that rewrite the current request
- * to a Twirp compliant request
- */
- twirpRewrite(prefix = "/twirp") {
- return (req, resp, next) => {
- this.rewrite(req, resp, prefix)
- .then(() => next())
- .catch((e) => {
- if (e instanceof errors_1.TwirpError) {
- if (e.code !== errors_1.TwirpErrorCode.NotFound) {
- server_1.writeError(resp, e);
- }
- else {
- next();
- }
- }
- });
- };
- }
- /**
- * Rewrite an incoming request to a Twirp compliant request
- * @param req
- * @param resp
- * @param prefix
- */
- rewrite(req, resp, prefix = "/twirp") {
- return __awaiter(this, void 0, void 0, function* () {
- const [match, route] = this.matchRoute(req);
- const body = yield this.prepareTwirpBody(req, match, route);
- const twirpUrl = `${prefix}/${route.packageName}.${route.serviceName}/${route.methodName}`;
- req.url = twirpUrl;
- req.originalUrl = twirpUrl;
- req.method = "POST";
- req.headers["content-type"] = "application/json";
- req.rawBody = Buffer.from(JSON.stringify(body));
- if (route.responseBodyKey) {
- const endFn = resp.end.bind(resp);
- resp.end = function (chunk) {
- if (resp.statusCode === 200) {
- endFn(`{ "${route.responseBodyKey}": ${chunk} }`);
- }
- else {
- endFn(chunk);
- }
- };
- }
- });
- }
- /**
- * Create a reverse proxy handler to
- * proxy http requests to Twirp Compliant handlers
- * @param httpClientOption
- */
- reverseProxy(httpClientOption) {
- const client = http_client_1.NodeHttpRPC(httpClientOption);
- return (req, res) => __awaiter(this, void 0, void 0, function* () {
- try {
- const [match, route] = this.matchRoute(req);
- const body = yield this.prepareTwirpBody(req, match, route);
- const response = yield client.request(`${route.packageName}.${route.serviceName}`, route.methodName, "application/json", body);
- res.statusCode = 200;
- res.setHeader("content-type", "application/json");
- let jsonResponse;
- if (route.responseBodyKey) {
- jsonResponse = JSON.stringify({ [route.responseBodyKey]: response });
- }
- else {
- jsonResponse = JSON.stringify(response);
- }
- res.end(jsonResponse);
- }
- catch (e) {
- server_1.writeError(res, e);
- }
- });
- }
- /**
- * Prepares twirp body requests using http.google.annotions
- * compliant spec
- *
- * @param req
- * @param match
- * @param route
- * @protected
- */
- prepareTwirpBody(req, match, route) {
- return __awaiter(this, void 0, void 0, function* () {
- const _a = match.params, { query_string } = _a, params = __rest(_a, ["query_string"]);
- let requestBody = Object.assign({}, params);
- if (query_string && route.bodyKey !== "*") {
- const queryParams = this.parseQueryString(query_string);
- requestBody = Object.assign(Object.assign({}, queryParams), requestBody);
- }
- let body = {};
- if (route.bodyKey) {
- const data = yield request_1.getRequestData(req);
- try {
- const jsonBody = JSON.parse(data.toString() || "{}");
- if (route.bodyKey === "*") {
- body = jsonBody;
- }
- else {
- body[route.bodyKey] = jsonBody;
- }
- }
- catch (e) {
- const msg = "the json request could not be decoded";
- throw new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, msg).withCause(e, true);
- }
- }
- return Object.assign(Object.assign({}, body), requestBody);
- });
- }
- /**
- * Matches a route
- * @param req
- */
- matchRoute(req) {
- var _a;
- const httpMethod = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toLowerCase();
- if (!httpMethod) {
- throw new errors_1.BadRouteError(`method not allowed`, req.method || "", req.url || "");
- }
- const routes = this.routes[httpMethod];
- for (const route of routes) {
- const match = route.matcher(req.url || "/");
- if (match) {
- return [match, route];
- }
- }
- throw new errors_1.NotFoundError(`url ${req.url} not found`);
- }
- /**
- * Parse query string
- * @param queryString
- */
- parseQueryString(queryString) {
- const queryParams = querystring_1.parse(queryString.replace("?", ""));
- return dotObject.object(queryParams);
- }
+// IP addresses are not valid server names per RFC6066
+// > Currently, the only server names supported are DNS hostnames
+function getServerName (host) {
+ if (!host) {
+ return null
+ }
+
+ assert.strictEqual(typeof host, 'string')
+
+ const servername = getHostname(host)
+ if (net.isIP(servername)) {
+ return ''
+ }
+
+ return servername
}
-exports.Gateway = Gateway;
+function deepClone (obj) {
+ return JSON.parse(JSON.stringify(obj))
+}
-/***/ }),
+function isAsyncIterable (obj) {
+ return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
+}
-/***/ 99462:
-/***/ (function(__unused_webpack_module, exports) {
+function isIterable (obj) {
+ return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
+}
+function bodyLength (body) {
+ if (body == null) {
+ return 0
+ } else if (isStream(body)) {
+ const state = body._readableState
+ return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
+ ? state.length
+ : null
+ } else if (isBlobLike(body)) {
+ return body.size != null ? body.size : null
+ } else if (isBuffer(body)) {
+ return body.byteLength
+ }
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isHook = exports.chainHooks = void 0;
-// ChainHooks creates a new ServerHook which chains the callbacks in
-// each of the constituent hooks passed in. Each hook function will be
-// called in the order of the ServerHooks values passed in.
-//
-// For the erroring hooks, RequestReceived and RequestRouted, any returned
-// errors prevent processing by later hooks.
-function chainHooks(...hooks) {
- if (hooks.length === 0) {
- return null;
- }
- if (hooks.length === 1) {
- return hooks[0];
- }
- const serverHook = {
- requestReceived(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestReceived) {
- continue;
- }
- yield hook.requestReceived(ctx);
- }
- });
- },
- requestPrepared(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestPrepared) {
- continue;
- }
- console.warn("hook requestPrepared is deprecated and will be removed in the next release. " +
- "Please use responsePrepared instead.");
- yield hook.requestPrepared(ctx);
- }
- });
- },
- responsePrepared(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.responsePrepared) {
- continue;
- }
- yield hook.responsePrepared(ctx);
- }
- });
- },
- requestSent(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestSent) {
- continue;
- }
- console.warn("hook requestSent is deprecated and will be removed in the next release. " +
- "Please use responseSent instead.");
- yield hook.requestSent(ctx);
- }
- });
- },
- responseSent(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.responseSent) {
- continue;
- }
- yield hook.responseSent(ctx);
- }
- });
- },
- requestRouted(ctx) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.requestRouted) {
- continue;
- }
- yield hook.requestRouted(ctx);
- }
- });
- },
- error(ctx, err) {
- return __awaiter(this, void 0, void 0, function* () {
- for (const hook of hooks) {
- if (!hook.error) {
- continue;
- }
- yield hook.error(ctx, err);
- }
- });
- },
- };
- return serverHook;
+ return null
}
-exports.chainHooks = chainHooks;
-function isHook(object) {
- return ("requestReceived" in object ||
- "requestPrepared" in object ||
- "requestSent" in object ||
- "requestRouted" in object ||
- "responsePrepared" in object ||
- "responseSent" in object ||
- "error" in object);
+
+function isDestroyed (stream) {
+ return !stream || !!(stream.destroyed || stream[kDestroyed])
}
-exports.isHook = isHook;
+function isReadableAborted (stream) {
+ const state = stream && stream._readableState
+ return isDestroyed(stream) && state && !state.endEmitted
+}
-/***/ }),
+function destroy (stream, err) {
+ if (stream == null || !isStream(stream) || isDestroyed(stream)) {
+ return
+ }
-/***/ 52503:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ if (typeof stream.destroy === 'function') {
+ if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
+ // See: https://github.com/nodejs/node/pull/38505/files
+ stream.socket = null
+ }
+ stream.destroy(err)
+ } else if (err) {
+ process.nextTick((stream, err) => {
+ stream.emit('error', err)
+ }, stream, err)
+ }
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
-}) : function(o, v) {
- o["default"] = v;
-});
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
- __setModuleDefault(result, mod);
- return result;
-};
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.FetchRPC = exports.wrapErrorResponseToTwirpError = exports.NodeHttpRPC = void 0;
-const http = __importStar(__nccwpck_require__(58611));
-const https = __importStar(__nccwpck_require__(65692));
-const url_1 = __nccwpck_require__(87016);
-const errors_1 = __nccwpck_require__(28775);
-/**
- * a node HTTP RPC implementation
- * @param options
- * @constructor
- */
-const NodeHttpRPC = (options) => ({
- request(service, method, contentType, data) {
- let client;
- return new Promise((resolve, rejected) => {
- const responseChunks = [];
- const requestData = contentType === "application/protobuf"
- ? Buffer.from(data)
- : JSON.stringify(data);
- const url = new url_1.URL(options.baseUrl);
- const isHttps = url.protocol === "https:";
- if (isHttps) {
- client = https;
- }
- else {
- client = http;
- }
- const prefix = url.pathname !== "/" ? url.pathname : "";
- const req = client
- .request(Object.assign(Object.assign({}, (options ? options : {})), { method: "POST", protocol: url.protocol, host: url.hostname, port: url.port ? url.port : isHttps ? 443 : 80, path: `${prefix}/${service}/${method}`, headers: Object.assign(Object.assign({}, (options.headers ? options.headers : {})), { "Content-Type": contentType, "Content-Length": contentType === "application/protobuf"
- ? Buffer.byteLength(requestData)
- : Buffer.from(requestData).byteLength }) }), (res) => {
- res.on("data", (chunk) => responseChunks.push(chunk));
- res.on("end", () => {
- const data = Buffer.concat(responseChunks);
- if (res.statusCode != 200) {
- rejected(wrapErrorResponseToTwirpError(data.toString()));
- }
- else {
- if (contentType === "application/json") {
- resolve(JSON.parse(data.toString()));
- }
- else {
- resolve(data);
- }
- }
- });
- res.on("error", (err) => {
- rejected(err);
- });
- })
- .on("error", (err) => {
- rejected(err);
- });
- req.end(requestData);
- });
- },
-});
-exports.NodeHttpRPC = NodeHttpRPC;
-function wrapErrorResponseToTwirpError(errorResponse) {
- return errors_1.TwirpError.fromObject(JSON.parse(errorResponse));
+ if (stream.destroyed !== true) {
+ stream[kDestroyed] = true
+ }
}
-exports.wrapErrorResponseToTwirpError = wrapErrorResponseToTwirpError;
+
+const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
+function parseKeepAliveTimeout (val) {
+ const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
+ return m ? parseInt(m[1], 10) * 1000 : null
+}
+
/**
- * a browser fetch RPC implementation
+ * Retrieves a header name and returns its lowercase value.
+ * @param {string | Buffer} value Header name
+ * @returns {string}
*/
-const FetchRPC = (options) => ({
- request(service, method, contentType, data) {
- return __awaiter(this, void 0, void 0, function* () {
- const headers = new Headers(options.headers);
- headers.set("content-type", contentType);
- const response = yield fetch(`${options.baseUrl}/${service}/${method}`, Object.assign(Object.assign({}, options), { method: "POST", headers, body: data instanceof Uint8Array ? data : JSON.stringify(data) }));
- if (response.status === 200) {
- if (contentType === "application/json") {
- return yield response.json();
- }
- return new Uint8Array(yield response.arrayBuffer());
- }
- throw errors_1.TwirpError.fromObject(yield response.json());
- });
- },
-});
-exports.FetchRPC = FetchRPC;
+function headerNameToString (value) {
+ return headerNameLowerCasedRecord[value] || value.toLowerCase()
+}
+function parseHeaders (headers, obj = {}) {
+ // For H2 support
+ if (!Array.isArray(headers)) return headers
-/***/ }),
+ for (let i = 0; i < headers.length; i += 2) {
+ const key = headers[i].toString().toLowerCase()
+ let val = obj[key]
-/***/ 33874:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ if (!val) {
+ if (Array.isArray(headers[i + 1])) {
+ obj[key] = headers[i + 1].map(x => x.toString('utf8'))
+ } else {
+ obj[key] = headers[i + 1].toString('utf8')
+ }
+ } else {
+ if (!Array.isArray(val)) {
+ val = [val]
+ obj[key] = val
+ }
+ val.push(headers[i + 1].toString('utf8'))
+ }
+ }
+ // See https://github.com/nodejs/node/pull/46528
+ if ('content-length' in obj && 'content-disposition' in obj) {
+ obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
+ }
-var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
-}) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
-}));
-var __exportStar = (this && this.__exportStar) || function(m, exports) {
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.TwirpContentType = void 0;
-__exportStar(__nccwpck_require__(99069), exports);
-__exportStar(__nccwpck_require__(1991), exports);
-__exportStar(__nccwpck_require__(51816), exports);
-__exportStar(__nccwpck_require__(99462), exports);
-__exportStar(__nccwpck_require__(28775), exports);
-__exportStar(__nccwpck_require__(70048), exports);
-__exportStar(__nccwpck_require__(52503), exports);
-var request_1 = __nccwpck_require__(21179);
-Object.defineProperty(exports, "TwirpContentType", ({ enumerable: true, get: function () { return request_1.TwirpContentType; } }));
+ return obj
+}
+function parseRawHeaders (headers) {
+ const ret = []
+ let hasContentLength = false
+ let contentDispositionIdx = -1
-/***/ }),
+ for (let n = 0; n < headers.length; n += 2) {
+ const key = headers[n + 0].toString()
+ const val = headers[n + 1].toString('utf8')
-/***/ 51816:
-/***/ (function(__unused_webpack_module, exports) {
+ if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
+ ret.push(key, val)
+ hasContentLength = true
+ } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
+ contentDispositionIdx = ret.push(key, val) - 1
+ } else {
+ ret.push(key, val)
+ }
+ }
+ // See https://github.com/nodejs/node/pull/46528
+ if (hasContentLength && contentDispositionIdx !== -1) {
+ ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
+ }
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.chainInterceptors = void 0;
-// chains multiple Interceptors into a single Interceptor.
-// The first interceptor wraps the second one, and so on.
-// Returns null if interceptors is empty.
-function chainInterceptors(...interceptors) {
- if (interceptors.length === 0) {
- return;
- }
- if (interceptors.length === 1) {
- return interceptors[0];
- }
- const first = interceptors[0];
- return (ctx, request, handler) => __awaiter(this, void 0, void 0, function* () {
- let next = handler;
- for (let i = interceptors.length - 1; i > 0; i--) {
- next = ((next) => (ctx, typedRequest) => {
- return interceptors[i](ctx, typedRequest, next);
- })(next);
- }
- return first(ctx, request, next);
- });
+ return ret
}
-exports.chainInterceptors = chainInterceptors;
+function isBuffer (buffer) {
+ // See, https://github.com/mcollina/undici/pull/319
+ return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
+}
-/***/ }),
+function validateHandler (handler, method, upgrade) {
+ if (!handler || typeof handler !== 'object') {
+ throw new InvalidArgumentError('handler must be an object')
+ }
-/***/ 21179:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ if (typeof handler.onConnect !== 'function') {
+ throw new InvalidArgumentError('invalid onConnect method')
+ }
+ if (typeof handler.onError !== 'function') {
+ throw new InvalidArgumentError('invalid onError method')
+ }
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.parseTwirpPath = exports.getRequestData = exports.validateRequest = exports.getContentType = exports.TwirpContentType = void 0;
-const errors_1 = __nccwpck_require__(28775);
-/**
- * Supported Twirp Content-Type
- */
-var TwirpContentType;
-(function (TwirpContentType) {
- TwirpContentType[TwirpContentType["Protobuf"] = 0] = "Protobuf";
- TwirpContentType[TwirpContentType["JSON"] = 1] = "JSON";
- TwirpContentType[TwirpContentType["Unknown"] = 2] = "Unknown";
-})(TwirpContentType = exports.TwirpContentType || (exports.TwirpContentType = {}));
-/**
- * Get supported content-type
- * @param mimeType
- */
-function getContentType(mimeType) {
- switch (mimeType) {
- case "application/protobuf":
- return TwirpContentType.Protobuf;
- case "application/json":
- return TwirpContentType.JSON;
- default:
- return TwirpContentType.Unknown;
- }
-}
-exports.getContentType = getContentType;
-/**
- * Validate a twirp request
- * @param ctx
- * @param request
- * @param pathPrefix
- */
-function validateRequest(ctx, request, pathPrefix) {
- if (request.method !== "POST") {
- const msg = `unsupported method ${request.method} (only POST is allowed)`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
+ throw new InvalidArgumentError('invalid onBodySent method')
+ }
+
+ if (upgrade || method === 'CONNECT') {
+ if (typeof handler.onUpgrade !== 'function') {
+ throw new InvalidArgumentError('invalid onUpgrade method')
}
- const path = parseTwirpPath(request.url || "");
- if (path.pkgService !==
- (ctx.packageName ? ctx.packageName + "." : "") + ctx.serviceName) {
- const msg = `no handler for path ${request.url}`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+ } else {
+ if (typeof handler.onHeaders !== 'function') {
+ throw new InvalidArgumentError('invalid onHeaders method')
}
- if (path.prefix !== pathPrefix) {
- const msg = `invalid path prefix ${path.prefix}, expected ${pathPrefix}, on path ${request.url}`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+
+ if (typeof handler.onData !== 'function') {
+ throw new InvalidArgumentError('invalid onData method')
}
- const mimeContentType = request.headers["content-type"] || "";
- if (ctx.contentType === TwirpContentType.Unknown) {
- const msg = `unexpected Content-Type: ${request.headers["content-type"]}`;
- throw new errors_1.BadRouteError(msg, request.method || "", request.url || "");
+
+ if (typeof handler.onComplete !== 'function') {
+ throw new InvalidArgumentError('invalid onComplete method')
}
- return Object.assign(Object.assign({}, path), { mimeContentType, contentType: ctx.contentType });
+ }
}
-exports.validateRequest = validateRequest;
-/**
- * Get request data from the body
- * @param req
- */
-function getRequestData(req) {
- return new Promise((resolve, reject) => {
- const reqWithRawBody = req;
- if (reqWithRawBody.rawBody instanceof Buffer) {
- resolve(reqWithRawBody.rawBody);
- return;
+
+// A body is disturbed if it has been read from and it cannot
+// be re-used without losing state or data.
+function isDisturbed (body) {
+ return !!(body && (
+ stream.isDisturbed
+ ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?
+ : body[kBodyUsed] ||
+ body.readableDidRead ||
+ (body._readableState && body._readableState.dataEmitted) ||
+ isReadableAborted(body)
+ ))
+}
+
+function isErrored (body) {
+ return !!(body && (
+ stream.isErrored
+ ? stream.isErrored(body)
+ : /state: 'errored'/.test(nodeUtil.inspect(body)
+ )))
+}
+
+function isReadable (body) {
+ return !!(body && (
+ stream.isReadable
+ ? stream.isReadable(body)
+ : /state: 'readable'/.test(nodeUtil.inspect(body)
+ )))
+}
+
+function getSocketInfo (socket) {
+ return {
+ localAddress: socket.localAddress,
+ localPort: socket.localPort,
+ remoteAddress: socket.remoteAddress,
+ remotePort: socket.remotePort,
+ remoteFamily: socket.remoteFamily,
+ timeout: socket.timeout,
+ bytesWritten: socket.bytesWritten,
+ bytesRead: socket.bytesRead
+ }
+}
+
+async function * convertIterableToBuffer (iterable) {
+ for await (const chunk of iterable) {
+ yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+ }
+}
+
+let ReadableStream
+function ReadableStreamFrom (iterable) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
+
+ if (ReadableStream.from) {
+ return ReadableStream.from(convertIterableToBuffer(iterable))
+ }
+
+ let iterator
+ return new ReadableStream(
+ {
+ async start () {
+ iterator = iterable[Symbol.asyncIterator]()
+ },
+ async pull (controller) {
+ const { done, value } = await iterator.next()
+ if (done) {
+ queueMicrotask(() => {
+ controller.close()
+ })
+ } else {
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
+ controller.enqueue(new Uint8Array(buf))
}
- const chunks = [];
- req.on("data", (chunk) => chunks.push(chunk));
- req.on("end", () => __awaiter(this, void 0, void 0, function* () {
- const data = Buffer.concat(chunks);
- resolve(data);
- }));
- req.on("error", (err) => {
- if (req.aborted) {
- reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.DeadlineExceeded, "failed to read request: deadline exceeded"));
- }
- else {
- reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Malformed, err.message).withCause(err));
- }
- });
- req.on("close", () => {
- reject(new errors_1.TwirpError(errors_1.TwirpErrorCode.Canceled, "failed to read request: context canceled"));
- });
- });
+ return controller.desiredSize > 0
+ },
+ async cancel (reason) {
+ await iterator.return()
+ }
+ },
+ 0
+ )
}
-exports.getRequestData = getRequestData;
+
+// The chunk should be a FormData instance and contains
+// all the required methods.
+function isFormDataLike (object) {
+ return (
+ object &&
+ typeof object === 'object' &&
+ typeof object.append === 'function' &&
+ typeof object.delete === 'function' &&
+ typeof object.get === 'function' &&
+ typeof object.getAll === 'function' &&
+ typeof object.has === 'function' &&
+ typeof object.set === 'function' &&
+ object[Symbol.toStringTag] === 'FormData'
+ )
+}
+
+function throwIfAborted (signal) {
+ if (!signal) { return }
+ if (typeof signal.throwIfAborted === 'function') {
+ signal.throwIfAborted()
+ } else {
+ if (signal.aborted) {
+ // DOMException not available < v17.0.0
+ const err = new Error('The operation was aborted')
+ err.name = 'AbortError'
+ throw err
+ }
+ }
+}
+
+function addAbortListener (signal, listener) {
+ if ('addEventListener' in signal) {
+ signal.addEventListener('abort', listener, { once: true })
+ return () => signal.removeEventListener('abort', listener)
+ }
+ signal.addListener('abort', listener)
+ return () => signal.removeListener('abort', listener)
+}
+
+const hasToWellFormed = !!String.prototype.toWellFormed
+
/**
- * Parses twirp url path
- * @param path
+ * @param {string} val
*/
-function parseTwirpPath(path) {
- const parts = path.split("/");
- if (parts.length < 2) {
- return {
- pkgService: "",
- method: "",
- prefix: "",
- };
+function toUSVString (val) {
+ if (hasToWellFormed) {
+ return `${val}`.toWellFormed()
+ } else if (nodeUtil.toUSVString) {
+ return nodeUtil.toUSVString(val)
+ }
+
+ return `${val}`
+}
+
+// Parsed accordingly to RFC 9110
+// https://www.rfc-editor.org/rfc/rfc9110#field.content-range
+function parseRangeHeader (range) {
+ if (range == null || range === '') return { start: 0, end: null, size: null }
+
+ const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
+ return m
+ ? {
+ start: parseInt(m[1]),
+ end: m[2] ? parseInt(m[2]) : null,
+ size: m[3] ? parseInt(m[3]) : null
+ }
+ : null
+}
+
+const kEnumerableProperty = Object.create(null)
+kEnumerableProperty.enumerable = true
+
+module.exports = {
+ kEnumerableProperty,
+ nop,
+ isDisturbed,
+ isErrored,
+ isReadable,
+ toUSVString,
+ isReadableAborted,
+ isBlobLike,
+ parseOrigin,
+ parseURL,
+ getServerName,
+ isStream,
+ isIterable,
+ isAsyncIterable,
+ isDestroyed,
+ headerNameToString,
+ parseRawHeaders,
+ parseHeaders,
+ parseKeepAliveTimeout,
+ destroy,
+ bodyLength,
+ deepClone,
+ ReadableStreamFrom,
+ isBuffer,
+ validateHandler,
+ getSocketInfo,
+ isFormDataLike,
+ buildURL,
+ throwIfAborted,
+ addAbortListener,
+ parseRangeHeader,
+ nodeMajor,
+ nodeMinor,
+ nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),
+ safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']
+}
+
+
+/***/ }),
+
+/***/ 52421:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const Dispatcher = __nccwpck_require__(20303)
+const {
+ ClientDestroyedError,
+ ClientClosedError,
+ InvalidArgumentError
+} = __nccwpck_require__(53959)
+const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(68031)
+
+const kDestroyed = Symbol('destroyed')
+const kClosed = Symbol('closed')
+const kOnDestroyed = Symbol('onDestroyed')
+const kOnClosed = Symbol('onClosed')
+const kInterceptedDispatch = Symbol('Intercepted Dispatch')
+
+class DispatcherBase extends Dispatcher {
+ constructor () {
+ super()
+
+ this[kDestroyed] = false
+ this[kOnDestroyed] = null
+ this[kClosed] = false
+ this[kOnClosed] = []
+ }
+
+ get destroyed () {
+ return this[kDestroyed]
+ }
+
+ get closed () {
+ return this[kClosed]
+ }
+
+ get interceptors () {
+ return this[kInterceptors]
+ }
+
+ set interceptors (newInterceptors) {
+ if (newInterceptors) {
+ for (let i = newInterceptors.length - 1; i >= 0; i--) {
+ const interceptor = this[kInterceptors][i]
+ if (typeof interceptor !== 'function') {
+ throw new InvalidArgumentError('interceptor must be an function')
+ }
+ }
}
- return {
- method: parts[parts.length - 1],
- pkgService: parts[parts.length - 2],
- prefix: parts.slice(0, parts.length - 2).join("/"),
- };
-}
-exports.parseTwirpPath = parseTwirpPath;
+ this[kInterceptors] = newInterceptors
+ }
-/***/ }),
+ close (callback) {
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ this.close((err, data) => {
+ return err ? reject(err) : resolve(data)
+ })
+ })
+ }
-/***/ 1991:
-/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
+ }
+ if (this[kDestroyed]) {
+ queueMicrotask(() => callback(new ClientDestroyedError(), null))
+ return
+ }
-var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
- return new (P || (P = Promise))(function (resolve, reject) {
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
- step((generator = generator.apply(thisArg, _arguments || [])).next());
- });
-};
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.writeError = exports.TwirpServer = void 0;
-const hooks_1 = __nccwpck_require__(99462);
-const request_1 = __nccwpck_require__(21179);
-const errors_1 = __nccwpck_require__(28775);
-/**
- * Runtime server implementation of a TwirpServer
- */
-class TwirpServer {
- constructor(options) {
- this.pathPrefix = "/twirp";
- this.hooks = [];
- this.interceptors = [];
- this.packageName = options.packageName;
- this.serviceName = options.serviceName;
- this.methodList = options.methodList;
- this.matchRoute = options.matchRoute;
- this.service = options.service;
+ if (this[kClosed]) {
+ if (this[kOnClosed]) {
+ this[kOnClosed].push(callback)
+ } else {
+ queueMicrotask(() => callback(null, null))
+ }
+ return
}
- /**
- * Returns the prefix for this server
- */
- get prefix() {
- return this.pathPrefix;
+
+ this[kClosed] = true
+ this[kOnClosed].push(callback)
+
+ const onClosed = () => {
+ const callbacks = this[kOnClosed]
+ this[kOnClosed] = null
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null)
+ }
}
- /**
- * The http handler for twirp complaint endpoints
- * @param options
- */
- httpHandler(options) {
- return (req, resp) => {
- // setup prefix
- if ((options === null || options === void 0 ? void 0 : options.prefix) !== undefined) {
- this.withPrefix(options.prefix);
- }
- return this._httpHandler(req, resp);
- };
+
+ // Should not error.
+ this[kClose]()
+ .then(() => this.destroy())
+ .then(() => {
+ queueMicrotask(onClosed)
+ })
+ }
+
+ destroy (err, callback) {
+ if (typeof err === 'function') {
+ callback = err
+ err = null
}
- /**
- * Adds interceptors or hooks to the request stack
- * @param middlewares
- */
- use(...middlewares) {
- middlewares.forEach((middleware) => {
- if (hooks_1.isHook(middleware)) {
- this.hooks.push(middleware);
- return this;
- }
- this.interceptors.push(middleware);
- });
- return this;
+
+ if (callback === undefined) {
+ return new Promise((resolve, reject) => {
+ this.destroy(err, (err, data) => {
+ return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
+ })
+ })
}
- /**
- * Adds a prefix to the service url path
- * @param prefix
- */
- withPrefix(prefix) {
- if (prefix === false) {
- this.pathPrefix = "";
- }
- else {
- this.pathPrefix = prefix;
- }
- return this;
+
+ if (typeof callback !== 'function') {
+ throw new InvalidArgumentError('invalid callback')
}
- /**
- * Returns the regex matching path for this twirp server
- */
- matchingPath() {
- const baseRegex = this.baseURI().replace(/\./g, "\\.");
- return new RegExp(`${baseRegex}\/(${this.methodList.join("|")})`);
+
+ if (this[kDestroyed]) {
+ if (this[kOnDestroyed]) {
+ this[kOnDestroyed].push(callback)
+ } else {
+ queueMicrotask(() => callback(null, null))
+ }
+ return
}
- /**
- * Returns the base URI for this twirp server
- */
- baseURI() {
- return `${this.pathPrefix}/${this.packageName ? this.packageName + "." : ""}${this.serviceName}`;
+
+ if (!err) {
+ err = new ClientDestroyedError()
}
- /**
- * Create a twirp context
- * @param req
- * @param res
- * @private
- */
- createContext(req, res) {
- return {
- packageName: this.packageName,
- serviceName: this.serviceName,
- methodName: "",
- contentType: request_1.getContentType(req.headers["content-type"]),
- req: req,
- res: res,
- };
+
+ this[kDestroyed] = true
+ this[kOnDestroyed] = this[kOnDestroyed] || []
+ this[kOnDestroyed].push(callback)
+
+ const onDestroyed = () => {
+ const callbacks = this[kOnDestroyed]
+ this[kOnDestroyed] = null
+ for (let i = 0; i < callbacks.length; i++) {
+ callbacks[i](null, null)
+ }
}
- /**
- * Twrip server http handler implementation
- * @param req
- * @param resp
- * @private
- */
- _httpHandler(req, resp) {
- return __awaiter(this, void 0, void 0, function* () {
- const ctx = this.createContext(req, resp);
- try {
- yield this.invokeHook("requestReceived", ctx);
- const { method, mimeContentType } = request_1.validateRequest(ctx, req, this.pathPrefix || "");
- const handler = this.matchRoute(method, {
- onMatch: (ctx) => {
- return this.invokeHook("requestRouted", ctx);
- },
- onNotFound: () => {
- const msg = `no handler for path ${req.url}`;
- throw new errors_1.BadRouteError(msg, req.method || "", req.url || "");
- },
- });
- const body = yield request_1.getRequestData(req);
- const response = yield handler(ctx, this.service, body, this.interceptors);
- yield Promise.all([
- this.invokeHook("responsePrepared", ctx),
- // keep backwards compatibility till next release
- this.invokeHook("requestPrepared", ctx),
- ]);
- resp.statusCode = 200;
- resp.setHeader("Content-Type", mimeContentType);
- resp.end(response);
- }
- catch (e) {
- yield this.invokeHook("error", ctx, mustBeTwirpError(e));
- if (!resp.headersSent) {
- writeError(resp, e);
- }
- }
- finally {
- yield Promise.all([
- this.invokeHook("responseSent", ctx),
- // keep backwards compatibility till next release
- this.invokeHook("requestSent", ctx),
- ]);
- }
- });
+
+ // Should not error.
+ this[kDestroy](err).then(() => {
+ queueMicrotask(onDestroyed)
+ })
+ }
+
+ [kInterceptedDispatch] (opts, handler) {
+ if (!this[kInterceptors] || this[kInterceptors].length === 0) {
+ this[kInterceptedDispatch] = this[kDispatch]
+ return this[kDispatch](opts, handler)
}
- /**
- * Invoke a hook
- * @param hookName
- * @param ctx
- * @param err
- * @protected
- */
- invokeHook(hookName, ctx, err) {
- return __awaiter(this, void 0, void 0, function* () {
- if (this.hooks.length === 0) {
- return;
- }
- const chainedHooks = hooks_1.chainHooks(...this.hooks);
- const hook = chainedHooks === null || chainedHooks === void 0 ? void 0 : chainedHooks[hookName];
- if (hook) {
- yield hook(ctx, err || new errors_1.InternalServerError("internal server error"));
- }
- });
+
+ let dispatch = this[kDispatch].bind(this)
+ for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
+ dispatch = this[kInterceptors][i](dispatch)
}
-}
-exports.TwirpServer = TwirpServer;
-/**
- * Write http error response
- * @param res
- * @param error
- */
-function writeError(res, error) {
- const twirpError = mustBeTwirpError(error);
- res.setHeader("Content-Type", "application/json");
- res.statusCode = errors_1.httpStatusFromErrorCode(twirpError.code);
- res.end(twirpError.toJSON());
-}
-exports.writeError = writeError;
-/**
- * Make sure that the error passed is a TwirpError
- * otherwise it will wrap it into an InternalError
- * @param err
- */
-function mustBeTwirpError(err) {
- if (err instanceof errors_1.TwirpError) {
- return err;
+ this[kInterceptedDispatch] = dispatch
+ return dispatch(opts, handler)
+ }
+
+ dispatch (opts, handler) {
+ if (!handler || typeof handler !== 'object') {
+ throw new InvalidArgumentError('handler must be an object')
}
- return new errors_1.InternalServerErrorWith(err);
+
+ try {
+ if (!opts || typeof opts !== 'object') {
+ throw new InvalidArgumentError('opts must be an object.')
+ }
+
+ if (this[kDestroyed] || this[kOnDestroyed]) {
+ throw new ClientDestroyedError()
+ }
+
+ if (this[kClosed]) {
+ throw new ClientClosedError()
+ }
+
+ return this[kInterceptedDispatch](opts, handler)
+ } catch (err) {
+ if (typeof handler.onError !== 'function') {
+ throw new InvalidArgumentError('invalid onError method')
+ }
+
+ handler.onError(err)
+
+ return false
+ }
+ }
}
+module.exports = DispatcherBase
+
/***/ }),
-/***/ 61684:
+/***/ 20303:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const Client = __nccwpck_require__(45513)
-const Dispatcher = __nccwpck_require__(20303)
-const errors = __nccwpck_require__(53959)
-const Pool = __nccwpck_require__(44288)
-const BalancedPool = __nccwpck_require__(95377)
-const Agent = __nccwpck_require__(92121)
-const util = __nccwpck_require__(89500)
-const { InvalidArgumentError } = errors
-const api = __nccwpck_require__(82531)
-const buildConnector = __nccwpck_require__(91332)
-const MockClient = __nccwpck_require__(72361)
-const MockAgent = __nccwpck_require__(77017)
-const MockPool = __nccwpck_require__(36480)
-const mockErrors = __nccwpck_require__(12673)
-const ProxyAgent = __nccwpck_require__(79276)
-const RetryHandler = __nccwpck_require__(49569)
-const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(61481)
-const DecoratorHandler = __nccwpck_require__(41468)
-const RedirectHandler = __nccwpck_require__(8591)
-const createRedirectInterceptor = __nccwpck_require__(99299)
+const EventEmitter = __nccwpck_require__(24434)
-let hasCrypto
-try {
- __nccwpck_require__(76982)
- hasCrypto = true
-} catch {
- hasCrypto = false
+class Dispatcher extends EventEmitter {
+ dispatch () {
+ throw new Error('not implemented')
+ }
+
+ close () {
+ throw new Error('not implemented')
+ }
+
+ destroy () {
+ throw new Error('not implemented')
+ }
}
-Object.assign(Dispatcher.prototype, api)
+module.exports = Dispatcher
-module.exports.Dispatcher = Dispatcher
-module.exports.Client = Client
-module.exports.Pool = Pool
-module.exports.BalancedPool = BalancedPool
-module.exports.Agent = Agent
-module.exports.ProxyAgent = ProxyAgent
-module.exports.RetryHandler = RetryHandler
-module.exports.DecoratorHandler = DecoratorHandler
-module.exports.RedirectHandler = RedirectHandler
-module.exports.createRedirectInterceptor = createRedirectInterceptor
+/***/ }),
-module.exports.buildConnector = buildConnector
-module.exports.errors = errors
+/***/ 37791:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-function makeDispatcher (fn) {
- return (url, opts, handler) => {
- if (typeof opts === 'function') {
- handler = opts
- opts = null
- }
- if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) {
- throw new InvalidArgumentError('invalid url')
+
+const Busboy = __nccwpck_require__(75249)
+const util = __nccwpck_require__(89500)
+const {
+ ReadableStreamFrom,
+ isBlobLike,
+ isReadableStreamLike,
+ readableStreamClose,
+ createDeferredPromise,
+ fullyReadBody
+} = __nccwpck_require__(72847)
+const { FormData } = __nccwpck_require__(47453)
+const { kState } = __nccwpck_require__(63730)
+const { webidl } = __nccwpck_require__(94354)
+const { DOMException, structuredClone } = __nccwpck_require__(21234)
+const { Blob, File: NativeFile } = __nccwpck_require__(20181)
+const { kBodyUsed } = __nccwpck_require__(68031)
+const assert = __nccwpck_require__(42613)
+const { isErrored } = __nccwpck_require__(89500)
+const { isUint8Array, isArrayBuffer } = __nccwpck_require__(98253)
+const { File: UndiciFile } = __nccwpck_require__(17005)
+const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
+
+let ReadableStream = globalThis.ReadableStream
+
+/** @type {globalThis['File']} */
+const File = NativeFile ?? UndiciFile
+const textEncoder = new TextEncoder()
+const textDecoder = new TextDecoder()
+
+// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
+function extractBody (object, keepalive = false) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
+
+ // 1. Let stream be null.
+ let stream = null
+
+ // 2. If object is a ReadableStream object, then set stream to object.
+ if (object instanceof ReadableStream) {
+ stream = object
+ } else if (isBlobLike(object)) {
+ // 3. Otherwise, if object is a Blob object, set stream to the
+ // result of running object’s get stream.
+ stream = object.stream()
+ } else {
+ // 4. Otherwise, set stream to a new ReadableStream object, and set
+ // up stream.
+ stream = new ReadableStream({
+ async pull (controller) {
+ controller.enqueue(
+ typeof source === 'string' ? textEncoder.encode(source) : source
+ )
+ queueMicrotask(() => readableStreamClose(controller))
+ },
+ start () {},
+ type: undefined
+ })
+ }
+
+ // 5. Assert: stream is a ReadableStream object.
+ assert(isReadableStreamLike(stream))
+
+ // 6. Let action be null.
+ let action = null
+
+ // 7. Let source be null.
+ let source = null
+
+ // 8. Let length be null.
+ let length = null
+
+ // 9. Let type be null.
+ let type = null
+
+ // 10. Switch on object:
+ if (typeof object === 'string') {
+ // Set source to the UTF-8 encoding of object.
+ // Note: setting source to a Uint8Array here breaks some mocking assumptions.
+ source = object
+
+ // Set type to `text/plain;charset=UTF-8`.
+ type = 'text/plain;charset=UTF-8'
+ } else if (object instanceof URLSearchParams) {
+ // URLSearchParams
+
+ // spec says to run application/x-www-form-urlencoded on body.list
+ // this is implemented in Node.js as apart of an URLSearchParams instance toString method
+ // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
+ // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
+
+ // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
+ source = object.toString()
+
+ // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
+ type = 'application/x-www-form-urlencoded;charset=UTF-8'
+ } else if (isArrayBuffer(object)) {
+ // BufferSource/ArrayBuffer
+
+ // Set source to a copy of the bytes held by object.
+ source = new Uint8Array(object.slice())
+ } else if (ArrayBuffer.isView(object)) {
+ // BufferSource/ArrayBufferView
+
+ // Set source to a copy of the bytes held by object.
+ source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
+ } else if (util.isFormDataLike(object)) {
+ const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`
+ const prefix = `--${boundary}\r\nContent-Disposition: form-data`
+
+ /*! formdata-polyfill. MIT License. Jimmy Wärting */
+ const escape = (str) =>
+ str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
+ const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
+
+ // Set action to this step: run the multipart/form-data
+ // encoding algorithm, with object’s entry list and UTF-8.
+ // - This ensures that the body is immutable and can't be changed afterwords
+ // - That the content-length is calculated in advance.
+ // - And that all parts are pre-encoded and ready to be sent.
+
+ const blobParts = []
+ const rn = new Uint8Array([13, 10]) // '\r\n'
+ length = 0
+ let hasUnknownSizeValue = false
+
+ for (const [name, value] of object) {
+ if (typeof value === 'string') {
+ const chunk = textEncoder.encode(prefix +
+ `; name="${escape(normalizeLinefeeds(name))}"` +
+ `\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
+ blobParts.push(chunk)
+ length += chunk.byteLength
+ } else {
+ const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
+ (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
+ `Content-Type: ${
+ value.type || 'application/octet-stream'
+ }\r\n\r\n`)
+ blobParts.push(chunk, value, rn)
+ if (typeof value.size === 'number') {
+ length += chunk.byteLength + value.size + rn.byteLength
+ } else {
+ hasUnknownSizeValue = true
+ }
+ }
}
- if (opts != null && typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+ const chunk = textEncoder.encode(`--${boundary}--`)
+ blobParts.push(chunk)
+ length += chunk.byteLength
+ if (hasUnknownSizeValue) {
+ length = null
}
- if (opts && opts.path != null) {
- if (typeof opts.path !== 'string') {
- throw new InvalidArgumentError('invalid opts.path')
- }
+ // Set source to object.
+ source = object
- let path = opts.path
- if (!opts.path.startsWith('/')) {
- path = `/${path}`
+ action = async function * () {
+ for (const part of blobParts) {
+ if (part.stream) {
+ yield * part.stream()
+ } else {
+ yield part
+ }
}
+ }
- url = new URL(util.parseOrigin(url).origin + path)
- } else {
- if (!opts) {
- opts = typeof url === 'object' ? url : {}
- }
+ // Set type to `multipart/form-data; boundary=`,
+ // followed by the multipart/form-data boundary string generated
+ // by the multipart/form-data encoding algorithm.
+ type = 'multipart/form-data; boundary=' + boundary
+ } else if (isBlobLike(object)) {
+ // Blob
- url = util.parseURL(url)
- }
+ // Set source to object.
+ source = object
- const { agent, dispatcher = getGlobalDispatcher() } = opts
+ // Set length to object’s size.
+ length = object.size
- if (agent) {
- throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?')
+ // If object’s type attribute is not the empty byte sequence, set
+ // type to its value.
+ if (object.type) {
+ type = object.type
+ }
+ } else if (typeof object[Symbol.asyncIterator] === 'function') {
+ // If keepalive is true, then throw a TypeError.
+ if (keepalive) {
+ throw new TypeError('keepalive')
}
- return fn.call(dispatcher, {
- ...opts,
- origin: url.origin,
- path: url.search ? `${url.pathname}${url.search}` : url.pathname,
- method: opts.method || (opts.body ? 'PUT' : 'GET')
- }, handler)
+ // If object is disturbed or locked, then throw a TypeError.
+ if (util.isDisturbed(object) || object.locked) {
+ throw new TypeError(
+ 'Response body object should not be disturbed or locked'
+ )
+ }
+
+ stream =
+ object instanceof ReadableStream ? object : ReadableStreamFrom(object)
}
-}
-module.exports.setGlobalDispatcher = setGlobalDispatcher
-module.exports.getGlobalDispatcher = getGlobalDispatcher
+ // 11. If source is a byte sequence, then set action to a
+ // step that returns source and length to source’s length.
+ if (typeof source === 'string' || util.isBuffer(source)) {
+ length = Buffer.byteLength(source)
+ }
-if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) {
- let fetchImpl = null
- module.exports.fetch = async function fetch (resource) {
- if (!fetchImpl) {
- fetchImpl = (__nccwpck_require__(11503).fetch)
- }
+ // 12. If action is non-null, then run these steps in in parallel:
+ if (action != null) {
+ // Run action.
+ let iterator
+ stream = new ReadableStream({
+ async start () {
+ iterator = action(object)[Symbol.asyncIterator]()
+ },
+ async pull (controller) {
+ const { value, done } = await iterator.next()
+ if (done) {
+ // When running action is done, close stream.
+ queueMicrotask(() => {
+ controller.close()
+ })
+ } else {
+ // Whenever one or more bytes are available and stream is not errored,
+ // enqueue a Uint8Array wrapping an ArrayBuffer containing the available
+ // bytes into stream.
+ if (!isErrored(stream)) {
+ controller.enqueue(new Uint8Array(value))
+ }
+ }
+ return controller.desiredSize > 0
+ },
+ async cancel (reason) {
+ await iterator.return()
+ },
+ type: undefined
+ })
+ }
- try {
- return await fetchImpl(...arguments)
- } catch (err) {
- if (typeof err === 'object') {
- Error.captureStackTrace(err, this)
- }
+ // 13. Let body be a body whose stream is stream, source is source,
+ // and length is length.
+ const body = { stream, source, length }
- throw err
- }
- }
- module.exports.Headers = __nccwpck_require__(12801).Headers
- module.exports.Response = __nccwpck_require__(89928).Response
- module.exports.Request = __nccwpck_require__(2630).Request
- module.exports.FormData = __nccwpck_require__(47453).FormData
- module.exports.File = __nccwpck_require__(17005).File
- module.exports.FileReader = __nccwpck_require__(30052).FileReader
+ // 14. Return (body, type).
+ return [body, type]
+}
- const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(62896)
+// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
+function safelyExtractBody (object, keepalive = false) {
+ if (!ReadableStream) {
+ // istanbul ignore next
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
- module.exports.setGlobalOrigin = setGlobalOrigin
- module.exports.getGlobalOrigin = getGlobalOrigin
+ // To safely extract a body and a `Content-Type` value from
+ // a byte sequence or BodyInit object object, run these steps:
- const { CacheStorage } = __nccwpck_require__(66446)
- const { kConstruct } = __nccwpck_require__(68652)
+ // 1. If object is a ReadableStream object, then:
+ if (object instanceof ReadableStream) {
+ // Assert: object is neither disturbed nor locked.
+ // istanbul ignore next
+ assert(!util.isDisturbed(object), 'The body has already been consumed.')
+ // istanbul ignore next
+ assert(!object.locked, 'The stream is locked.')
+ }
- // Cache & CacheStorage are tightly coupled with fetch. Even if it may run
- // in an older version of Node, it doesn't have any use without fetch.
- module.exports.caches = new CacheStorage(kConstruct)
+ // 2. Return the results of extracting object.
+ return extractBody(object, keepalive)
}
-if (util.nodeMajor >= 16) {
- const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(64276)
+function cloneBody (body) {
+ // To clone a body body, run these steps:
- module.exports.deleteCookie = deleteCookie
- module.exports.getCookies = getCookies
- module.exports.getSetCookies = getSetCookies
- module.exports.setCookie = setCookie
+ // https://fetch.spec.whatwg.org/#concept-body-clone
- const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
+ // 1. Let « out1, out2 » be the result of teeing body’s stream.
+ const [out1, out2] = body.stream.tee()
+ const out2Clone = structuredClone(out2, { transfer: [out2] })
+ // This, for whatever reasons, unrefs out2Clone which allows
+ // the process to exit by itself.
+ const [, finalClone] = out2Clone.tee()
- module.exports.parseMIMEType = parseMIMEType
- module.exports.serializeAMimeType = serializeAMimeType
+ // 2. Set body’s stream to out1.
+ body.stream = out1
+
+ // 3. Return a body whose stream is out2 and other members are copied from body.
+ return {
+ stream: finalClone,
+ length: body.length,
+ source: body.source
+ }
}
-if (util.nodeMajor >= 18 && hasCrypto) {
- const { WebSocket } = __nccwpck_require__(90551)
+async function * consumeBody (body) {
+ if (body) {
+ if (isUint8Array(body)) {
+ yield body
+ } else {
+ const stream = body.stream
- module.exports.WebSocket = WebSocket
-}
+ if (util.isDisturbed(stream)) {
+ throw new TypeError('The body has already been consumed.')
+ }
-module.exports.request = makeDispatcher(api.request)
-module.exports.stream = makeDispatcher(api.stream)
-module.exports.pipeline = makeDispatcher(api.pipeline)
-module.exports.connect = makeDispatcher(api.connect)
-module.exports.upgrade = makeDispatcher(api.upgrade)
+ if (stream.locked) {
+ throw new TypeError('The stream is locked.')
+ }
-module.exports.MockClient = MockClient
-module.exports.MockPool = MockPool
-module.exports.MockAgent = MockAgent
-module.exports.mockErrors = mockErrors
+ // Compat.
+ stream[kBodyUsed] = true
+ yield * stream
+ }
+ }
+}
-/***/ }),
+function throwIfAborted (state) {
+ if (state.aborted) {
+ throw new DOMException('The operation was aborted.', 'AbortError')
+ }
+}
-/***/ 92121:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+function bodyMixinMethods (instance) {
+ const methods = {
+ blob () {
+ // The blob() method steps are to return the result of
+ // running consume body with this and the following step
+ // given a byte sequence bytes: return a Blob whose
+ // contents are bytes and whose type attribute is this’s
+ // MIME type.
+ return specConsumeBody(this, (bytes) => {
+ let mimeType = bodyMimeType(this)
+ if (mimeType === 'failure') {
+ mimeType = ''
+ } else if (mimeType) {
+ mimeType = serializeAMimeType(mimeType)
+ }
+ // Return a Blob whose contents are bytes and type attribute
+ // is mimeType.
+ return new Blob([bytes], { type: mimeType })
+ }, instance)
+ },
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(68031)
-const DispatcherBase = __nccwpck_require__(52421)
-const Pool = __nccwpck_require__(44288)
-const Client = __nccwpck_require__(45513)
-const util = __nccwpck_require__(89500)
-const createRedirectInterceptor = __nccwpck_require__(99299)
-const { WeakRef, FinalizationRegistry } = __nccwpck_require__(90022)()
+ arrayBuffer () {
+ // The arrayBuffer() method steps are to return the result
+ // of running consume body with this and the following step
+ // given a byte sequence bytes: return a new ArrayBuffer
+ // whose contents are bytes.
+ return specConsumeBody(this, (bytes) => {
+ return new Uint8Array(bytes).buffer
+ }, instance)
+ },
-const kOnConnect = Symbol('onConnect')
-const kOnDisconnect = Symbol('onDisconnect')
-const kOnConnectionError = Symbol('onConnectionError')
-const kMaxRedirections = Symbol('maxRedirections')
-const kOnDrain = Symbol('onDrain')
-const kFactory = Symbol('factory')
-const kFinalizer = Symbol('finalizer')
-const kOptions = Symbol('options')
+ text () {
+ // The text() method steps are to return the result of running
+ // consume body with this and UTF-8 decode.
+ return specConsumeBody(this, utf8DecodeBytes, instance)
+ },
-function defaultFactory (origin, opts) {
- return opts && opts.connections === 1
- ? new Client(origin, opts)
- : new Pool(origin, opts)
-}
+ json () {
+ // The json() method steps are to return the result of running
+ // consume body with this and parse JSON from bytes.
+ return specConsumeBody(this, parseJSONFromBytes, instance)
+ },
-class Agent extends DispatcherBase {
- constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) {
- super()
+ async formData () {
+ webidl.brandCheck(this, instance)
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
+ throwIfAborted(this[kState])
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
- }
+ const contentType = this.headers.get('Content-Type')
- if (!Number.isInteger(maxRedirections) || maxRedirections < 0) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
+ // If mimeType’s essence is "multipart/form-data", then:
+ if (/multipart\/form-data/.test(contentType)) {
+ const headers = {}
+ for (const [key, value] of this.headers) headers[key.toLowerCase()] = value
- if (connect && typeof connect !== 'function') {
- connect = { ...connect }
- }
+ const responseFormData = new FormData()
- this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent)
- ? options.interceptors.Agent
- : [createRedirectInterceptor({ maxRedirections })]
+ let busboy
- this[kOptions] = { ...util.deepClone(options), connect }
- this[kOptions].interceptors = options.interceptors
- ? { ...options.interceptors }
- : undefined
- this[kMaxRedirections] = maxRedirections
- this[kFactory] = factory
- this[kClients] = new Map()
- this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => {
- const ref = this[kClients].get(key)
- if (ref !== undefined && ref.deref() === undefined) {
- this[kClients].delete(key)
- }
- })
+ try {
+ busboy = new Busboy({
+ headers,
+ preservePath: true
+ })
+ } catch (err) {
+ throw new DOMException(`${err}`, 'AbortError')
+ }
- const agent = this
+ busboy.on('field', (name, value) => {
+ responseFormData.append(name, value)
+ })
+ busboy.on('file', (name, value, filename, encoding, mimeType) => {
+ const chunks = []
- this[kOnDrain] = (origin, targets) => {
- agent.emit('drain', origin, [agent, ...targets])
- }
+ if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {
+ let base64chunk = ''
- this[kOnConnect] = (origin, targets) => {
- agent.emit('connect', origin, [agent, ...targets])
- }
+ value.on('data', (chunk) => {
+ base64chunk += chunk.toString().replace(/[\r\n]/gm, '')
- this[kOnDisconnect] = (origin, targets, err) => {
- agent.emit('disconnect', origin, [agent, ...targets], err)
- }
+ const end = base64chunk.length - base64chunk.length % 4
+ chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))
- this[kOnConnectionError] = (origin, targets, err) => {
- agent.emit('connectionError', origin, [agent, ...targets], err)
- }
- }
+ base64chunk = base64chunk.slice(end)
+ })
+ value.on('end', () => {
+ chunks.push(Buffer.from(base64chunk, 'base64'))
+ responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
+ })
+ } else {
+ value.on('data', (chunk) => {
+ chunks.push(chunk)
+ })
+ value.on('end', () => {
+ responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
+ })
+ }
+ })
- get [kRunning] () {
- let ret = 0
- for (const ref of this[kClients].values()) {
- const client = ref.deref()
- /* istanbul ignore next: gc is undeterministic */
- if (client) {
- ret += client[kRunning]
- }
- }
- return ret
- }
+ const busboyResolve = new Promise((resolve, reject) => {
+ busboy.on('finish', resolve)
+ busboy.on('error', (err) => reject(new TypeError(err)))
+ })
- [kDispatch] (opts, handler) {
- let key
- if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) {
- key = String(opts.origin)
- } else {
- throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.')
- }
+ if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)
+ busboy.end()
+ await busboyResolve
- const ref = this[kClients].get(key)
+ return responseFormData
+ } else if (/application\/x-www-form-urlencoded/.test(contentType)) {
+ // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then:
- let dispatcher = ref ? ref.deref() : null
- if (!dispatcher) {
- dispatcher = this[kFactory](opts.origin, this[kOptions])
- .on('drain', this[kOnDrain])
- .on('connect', this[kOnConnect])
- .on('disconnect', this[kOnDisconnect])
- .on('connectionError', this[kOnConnectionError])
+ // 1. Let entries be the result of parsing bytes.
+ let entries
+ try {
+ let text = ''
+ // application/x-www-form-urlencoded parser will keep the BOM.
+ // https://url.spec.whatwg.org/#concept-urlencoded-parser
+ // Note that streaming decoder is stateful and cannot be reused
+ const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
- this[kClients].set(key, new WeakRef(dispatcher))
- this[kFinalizer].register(dispatcher, key)
- }
+ for await (const chunk of consumeBody(this[kState].body)) {
+ if (!isUint8Array(chunk)) {
+ throw new TypeError('Expected Uint8Array chunk')
+ }
+ text += streamingDecoder.decode(chunk, { stream: true })
+ }
+ text += streamingDecoder.decode()
+ entries = new URLSearchParams(text)
+ } catch (err) {
+ // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.
+ // 2. If entries is failure, then throw a TypeError.
+ throw Object.assign(new TypeError(), { cause: err })
+ }
- return dispatcher.dispatch(opts, handler)
- }
+ // 3. Return a new FormData object whose entries are entries.
+ const formData = new FormData()
+ for (const [name, value] of entries) {
+ formData.append(name, value)
+ }
+ return formData
+ } else {
+ // Wait a tick before checking if the request has been aborted.
+ // Otherwise, a TypeError can be thrown when an AbortError should.
+ await Promise.resolve()
- async [kClose] () {
- const closePromises = []
- for (const ref of this[kClients].values()) {
- const client = ref.deref()
- /* istanbul ignore else: gc is undeterministic */
- if (client) {
- closePromises.push(client.close())
+ throwIfAborted(this[kState])
+
+ // Otherwise, throw a TypeError.
+ throw webidl.errors.exception({
+ header: `${instance.name}.formData`,
+ message: 'Could not parse content as FormData.'
+ })
}
}
-
- await Promise.all(closePromises)
}
- async [kDestroy] (err) {
- const destroyPromises = []
- for (const ref of this[kClients].values()) {
- const client = ref.deref()
- /* istanbul ignore else: gc is undeterministic */
- if (client) {
- destroyPromises.push(client.destroy(err))
- }
- }
+ return methods
+}
- await Promise.all(destroyPromises)
- }
+function mixinBody (prototype) {
+ Object.assign(prototype.prototype, bodyMixinMethods(prototype))
}
-module.exports = Agent
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
+ * @param {Response|Request} object
+ * @param {(value: unknown) => unknown} convertBytesToJSValue
+ * @param {Response|Request} instance
+ */
+async function specConsumeBody (object, convertBytesToJSValue, instance) {
+ webidl.brandCheck(object, instance)
+ throwIfAborted(object[kState])
-/***/ }),
+ // 1. If object is unusable, then return a promise rejected
+ // with a TypeError.
+ if (bodyUnusable(object[kState].body)) {
+ throw new TypeError('Body is unusable')
+ }
-/***/ 52730:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Let promise be a new promise.
+ const promise = createDeferredPromise()
-const { addAbortListener } = __nccwpck_require__(89500)
-const { RequestAbortedError } = __nccwpck_require__(53959)
+ // 3. Let errorSteps given error be to reject promise with error.
+ const errorSteps = (error) => promise.reject(error)
-const kListener = Symbol('kListener')
-const kSignal = Symbol('kSignal')
+ // 4. Let successSteps given a byte sequence data be to resolve
+ // promise with the result of running convertBytesToJSValue
+ // with data. If that threw an exception, then run errorSteps
+ // with that exception.
+ const successSteps = (data) => {
+ try {
+ promise.resolve(convertBytesToJSValue(data))
+ } catch (e) {
+ errorSteps(e)
+ }
+ }
-function abort (self) {
- if (self.abort) {
- self.abort()
- } else {
- self.onError(new RequestAbortedError())
+ // 5. If object’s body is null, then run successSteps with an
+ // empty byte sequence.
+ if (object[kState].body == null) {
+ successSteps(new Uint8Array())
+ return promise.promise
}
+
+ // 6. Otherwise, fully read object’s body given successSteps,
+ // errorSteps, and object’s relevant global object.
+ await fullyReadBody(object[kState].body, successSteps, errorSteps)
+
+ // 7. Return promise.
+ return promise.promise
}
-function addSignal (self, signal) {
- self[kSignal] = null
- self[kListener] = null
+// https://fetch.spec.whatwg.org/#body-unusable
+function bodyUnusable (body) {
+ // An object including the Body interface mixin is
+ // said to be unusable if its body is non-null and
+ // its body’s stream is disturbed or locked.
+ return body != null && (body.stream.locked || util.isDisturbed(body.stream))
+}
- if (!signal) {
- return
+/**
+ * @see https://encoding.spec.whatwg.org/#utf-8-decode
+ * @param {Buffer} buffer
+ */
+function utf8DecodeBytes (buffer) {
+ if (buffer.length === 0) {
+ return ''
}
- if (signal.aborted) {
- abort(self)
- return
- }
+ // 1. Let buffer be the result of peeking three bytes from
+ // ioQueue, converted to a byte sequence.
- self[kSignal] = signal
- self[kListener] = () => {
- abort(self)
+ // 2. If buffer is 0xEF 0xBB 0xBF, then read three
+ // bytes from ioQueue. (Do nothing with those bytes.)
+ if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
+ buffer = buffer.subarray(3)
}
- addAbortListener(self[kSignal], self[kListener])
+ // 3. Process a queue with an instance of UTF-8’s
+ // decoder, ioQueue, output, and "replacement".
+ const output = textDecoder.decode(buffer)
+
+ // 4. Return output.
+ return output
}
-function removeSignal (self) {
- if (!self[kSignal]) {
- return
- }
+/**
+ * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
+ * @param {Uint8Array} bytes
+ */
+function parseJSONFromBytes (bytes) {
+ return JSON.parse(utf8DecodeBytes(bytes))
+}
- if ('removeEventListener' in self[kSignal]) {
- self[kSignal].removeEventListener('abort', self[kListener])
- } else {
- self[kSignal].removeListener('abort', self[kListener])
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
+ * @param {import('./response').Response|import('./request').Request} object
+ */
+function bodyMimeType (object) {
+ const { headersList } = object[kState]
+ const contentType = headersList.get('content-type')
+
+ if (contentType === null) {
+ return 'failure'
}
- self[kSignal] = null
- self[kListener] = null
+ return parseMIMEType(contentType)
}
module.exports = {
- addSignal,
- removeSignal
+ extractBody,
+ safelyExtractBody,
+ cloneBody,
+ mixinBody
}
/***/ }),
-/***/ 73192:
+/***/ 21234:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { AsyncResource } = __nccwpck_require__(90290)
-const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { addSignal, removeSignal } = __nccwpck_require__(52730)
+const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(28167)
-class ConnectHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+const corsSafeListedMethods = ['GET', 'HEAD', 'POST']
+const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+const nullBodyStatus = [101, 204, 205, 304]
- const { signal, opaque, responseHeaders } = opts
+const redirectStatus = [301, 302, 303, 307, 308]
+const redirectStatusSet = new Set(redirectStatus)
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+// https://fetch.spec.whatwg.org/#block-bad-port
+const badPorts = [
+ '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',
+ '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',
+ '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',
+ '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',
+ '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',
+ '10080'
+]
- super('UNDICI_CONNECT')
+const badPortsSet = new Set(badPorts)
- this.opaque = opaque || null
- this.responseHeaders = responseHeaders || null
- this.callback = callback
- this.abort = null
+// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
+const referrerPolicy = [
+ '',
+ 'no-referrer',
+ 'no-referrer-when-downgrade',
+ 'same-origin',
+ 'origin',
+ 'strict-origin',
+ 'origin-when-cross-origin',
+ 'strict-origin-when-cross-origin',
+ 'unsafe-url'
+]
+const referrerPolicySet = new Set(referrerPolicy)
- addSignal(this, signal)
- }
+const requestRedirect = ['follow', 'manual', 'error']
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
- }
+const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
+const safeMethodsSet = new Set(safeMethods)
- this.abort = abort
- this.context = context
- }
+const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']
- onHeaders () {
- throw new SocketError('bad connect', null)
- }
+const requestCredentials = ['omit', 'same-origin', 'include']
- onUpgrade (statusCode, rawHeaders, socket) {
- const { callback, opaque, context } = this
+const requestCache = [
+ 'default',
+ 'no-store',
+ 'reload',
+ 'no-cache',
+ 'force-cache',
+ 'only-if-cached'
+]
- removeSignal(this)
+// https://fetch.spec.whatwg.org/#request-body-header-name
+const requestBodyHeader = [
+ 'content-encoding',
+ 'content-language',
+ 'content-location',
+ 'content-type',
+ // See https://github.com/nodejs/undici/issues/2021
+ // 'Content-Length' is a forbidden header name, which is typically
+ // removed in the Headers implementation. However, undici doesn't
+ // filter out headers, so we add it here.
+ 'content-length'
+]
- this.callback = null
+// https://fetch.spec.whatwg.org/#enumdef-requestduplex
+const requestDuplex = [
+ 'half'
+]
- let headers = rawHeaders
- // Indicates is an HTTP2Session
- if (headers != null) {
- headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- }
+// http://fetch.spec.whatwg.org/#forbidden-method
+const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']
+const forbiddenMethodsSet = new Set(forbiddenMethods)
- this.runInAsyncScope(callback, null, null, {
- statusCode,
- headers,
- socket,
- opaque,
- context
- })
- }
+const subresource = [
+ 'audio',
+ 'audioworklet',
+ 'font',
+ 'image',
+ 'manifest',
+ 'paintworklet',
+ 'script',
+ 'style',
+ 'track',
+ 'video',
+ 'xslt',
+ ''
+]
+const subresourceSet = new Set(subresource)
- onError (err) {
- const { callback, opaque } = this
+/** @type {globalThis['DOMException']} */
+const DOMException = globalThis.DOMException ?? (() => {
+ // DOMException was only made a global in Node v17.0.0,
+ // but fetch supports >= v16.8.
+ try {
+ atob('~')
+ } catch (err) {
+ return Object.getPrototypeOf(err).constructor
+ }
+})()
- removeSignal(this)
+let channel
- if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
+/** @type {globalThis['structuredClone']} */
+const structuredClone =
+ globalThis.structuredClone ??
+ // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js
+ // structuredClone was added in v17.0.0, but fetch supports v16.8
+ function structuredClone (value, options = undefined) {
+ if (arguments.length === 0) {
+ throw new TypeError('missing argument')
}
- }
-}
-
-function connect (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- connect.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
- try {
- const connectHandler = new ConnectHandler(opts, callback)
- this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler)
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
+ if (!channel) {
+ channel = new MessageChannel()
}
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
+ channel.port1.unref()
+ channel.port2.unref()
+ channel.port1.postMessage(value, options?.transfer)
+ return receiveMessageOnPort(channel.port2).message
}
-}
-module.exports = connect
+module.exports = {
+ DOMException,
+ structuredClone,
+ subresource,
+ forbiddenMethods,
+ requestBodyHeader,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ redirectStatus,
+ corsSafeListedMethods,
+ nullBodyStatus,
+ safeMethods,
+ badPorts,
+ requestDuplex,
+ subresourceSet,
+ badPortsSet,
+ redirectStatusSet,
+ corsSafeListedMethodsSet,
+ safeMethodsSet,
+ forbiddenMethodsSet,
+ referrerPolicySet
+}
/***/ }),
-/***/ 62466:
+/***/ 37246:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+const assert = __nccwpck_require__(42613)
+const { atob } = __nccwpck_require__(20181)
+const { isomorphicDecode } = __nccwpck_require__(72847)
+const encoder = new TextEncoder()
-const {
- Readable,
- Duplex,
- PassThrough
-} = __nccwpck_require__(2203)
-const {
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError
-} = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { AsyncResource } = __nccwpck_require__(90290)
-const { addSignal, removeSignal } = __nccwpck_require__(52730)
-const assert = __nccwpck_require__(42613)
+/**
+ * @see https://mimesniff.spec.whatwg.org/#http-token-code-point
+ */
+const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/
+const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line
+/**
+ * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
+ */
+const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line
-const kResume = Symbol('resume')
+// https://fetch.spec.whatwg.org/#data-url-processor
+/** @param {URL} dataURL */
+function dataURLProcessor (dataURL) {
+ // 1. Assert: dataURL’s scheme is "data".
+ assert(dataURL.protocol === 'data:')
-class PipelineRequest extends Readable {
- constructor () {
- super({ autoDestroy: true })
+ // 2. Let input be the result of running the URL
+ // serializer on dataURL with exclude fragment
+ // set to true.
+ let input = URLSerializer(dataURL, true)
- this[kResume] = null
+ // 3. Remove the leading "data:" string from input.
+ input = input.slice(5)
+
+ // 4. Let position point at the start of input.
+ const position = { position: 0 }
+
+ // 5. Let mimeType be the result of collecting a
+ // sequence of code points that are not equal
+ // to U+002C (,), given position.
+ let mimeType = collectASequenceOfCodePointsFast(
+ ',',
+ input,
+ position
+ )
+
+ // 6. Strip leading and trailing ASCII whitespace
+ // from mimeType.
+ // Undici implementation note: we need to store the
+ // length because if the mimetype has spaces removed,
+ // the wrong amount will be sliced from the input in
+ // step #9
+ const mimeTypeLength = mimeType.length
+ mimeType = removeASCIIWhitespace(mimeType, true, true)
+
+ // 7. If position is past the end of input, then
+ // return failure
+ if (position.position >= input.length) {
+ return 'failure'
}
- _read () {
- const { [kResume]: resume } = this
+ // 8. Advance position by 1.
+ position.position++
- if (resume) {
- this[kResume] = null
- resume()
+ // 9. Let encodedBody be the remainder of input.
+ const encodedBody = input.slice(mimeTypeLength + 1)
+
+ // 10. Let body be the percent-decoding of encodedBody.
+ let body = stringPercentDecode(encodedBody)
+
+ // 11. If mimeType ends with U+003B (;), followed by
+ // zero or more U+0020 SPACE, followed by an ASCII
+ // case-insensitive match for "base64", then:
+ if (/;(\u0020){0,}base64$/i.test(mimeType)) {
+ // 1. Let stringBody be the isomorphic decode of body.
+ const stringBody = isomorphicDecode(body)
+
+ // 2. Set body to the forgiving-base64 decode of
+ // stringBody.
+ body = forgivingBase64(stringBody)
+
+ // 3. If body is failure, then return failure.
+ if (body === 'failure') {
+ return 'failure'
}
+
+ // 4. Remove the last 6 code points from mimeType.
+ mimeType = mimeType.slice(0, -6)
+
+ // 5. Remove trailing U+0020 SPACE code points from mimeType,
+ // if any.
+ mimeType = mimeType.replace(/(\u0020)+$/, '')
+
+ // 6. Remove the last U+003B (;) code point from mimeType.
+ mimeType = mimeType.slice(0, -1)
}
- _destroy (err, callback) {
- this._read()
+ // 12. If mimeType starts with U+003B (;), then prepend
+ // "text/plain" to mimeType.
+ if (mimeType.startsWith(';')) {
+ mimeType = 'text/plain' + mimeType
+ }
- callback(err)
+ // 13. Let mimeTypeRecord be the result of parsing
+ // mimeType.
+ let mimeTypeRecord = parseMIMEType(mimeType)
+
+ // 14. If mimeTypeRecord is failure, then set
+ // mimeTypeRecord to text/plain;charset=US-ASCII.
+ if (mimeTypeRecord === 'failure') {
+ mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
}
+
+ // 15. Return a new data: URL struct whose MIME
+ // type is mimeTypeRecord and body is body.
+ // https://fetch.spec.whatwg.org/#data-url-struct
+ return { mimeType: mimeTypeRecord, body }
}
-class PipelineResponse extends Readable {
- constructor (resume) {
- super({ autoDestroy: true })
- this[kResume] = resume
+// https://url.spec.whatwg.org/#concept-url-serializer
+/**
+ * @param {URL} url
+ * @param {boolean} excludeFragment
+ */
+function URLSerializer (url, excludeFragment = false) {
+ if (!excludeFragment) {
+ return url.href
}
- _read () {
- this[kResume]()
+ const href = url.href
+ const hashLength = url.hash.length
+
+ return hashLength === 0 ? href : href.substring(0, href.length - hashLength)
+}
+
+// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
+/**
+ * @param {(char: string) => boolean} condition
+ * @param {string} input
+ * @param {{ position: number }} position
+ */
+function collectASequenceOfCodePoints (condition, input, position) {
+ // 1. Let result be the empty string.
+ let result = ''
+
+ // 2. While position doesn’t point past the end of input and the
+ // code point at position within input meets the condition condition:
+ while (position.position < input.length && condition(input[position.position])) {
+ // 1. Append that code point to the end of result.
+ result += input[position.position]
+
+ // 2. Advance position by 1.
+ position.position++
}
- _destroy (err, callback) {
- if (!err && !this._readableState.endEmitted) {
- err = new RequestAbortedError()
- }
+ // 3. Return result.
+ return result
+}
- callback(err)
+/**
+ * A faster collectASequenceOfCodePoints that only works when comparing a single character.
+ * @param {string} char
+ * @param {string} input
+ * @param {{ position: number }} position
+ */
+function collectASequenceOfCodePointsFast (char, input, position) {
+ const idx = input.indexOf(char, position.position)
+ const start = position.position
+
+ if (idx === -1) {
+ position.position = input.length
+ return input.slice(start)
}
-}
-class PipelineHandler extends AsyncResource {
- constructor (opts, handler) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+ position.position = idx
+ return input.slice(start, position.position)
+}
- if (typeof handler !== 'function') {
- throw new InvalidArgumentError('invalid handler')
- }
+// https://url.spec.whatwg.org/#string-percent-decode
+/** @param {string} input */
+function stringPercentDecode (input) {
+ // 1. Let bytes be the UTF-8 encoding of input.
+ const bytes = encoder.encode(input)
- const { signal, method, opaque, onInfo, responseHeaders } = opts
+ // 2. Return the percent-decoding of bytes.
+ return percentDecode(bytes)
+}
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+// https://url.spec.whatwg.org/#percent-decode
+/** @param {Uint8Array} input */
+function percentDecode (input) {
+ // 1. Let output be an empty byte sequence.
+ /** @type {number[]} */
+ const output = []
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
+ // 2. For each byte byte in input:
+ for (let i = 0; i < input.length; i++) {
+ const byte = input[i]
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
+ // 1. If byte is not 0x25 (%), then append byte to output.
+ if (byte !== 0x25) {
+ output.push(byte)
- super('UNDICI_PIPELINE')
+ // 2. Otherwise, if byte is 0x25 (%) and the next two bytes
+ // after byte in input are not in the ranges
+ // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),
+ // and 0x61 (a) to 0x66 (f), all inclusive, append byte
+ // to output.
+ } else if (
+ byte === 0x25 &&
+ !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))
+ ) {
+ output.push(0x25)
- this.opaque = opaque || null
- this.responseHeaders = responseHeaders || null
- this.handler = handler
- this.abort = null
- this.context = null
- this.onInfo = onInfo || null
+ // 3. Otherwise:
+ } else {
+ // 1. Let bytePoint be the two bytes after byte in input,
+ // decoded, and then interpreted as hexadecimal number.
+ const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])
+ const bytePoint = Number.parseInt(nextTwoBytes, 16)
- this.req = new PipelineRequest().on('error', util.nop)
+ // 2. Append a byte whose value is bytePoint to output.
+ output.push(bytePoint)
- this.ret = new Duplex({
- readableObjectMode: opts.objectMode,
- autoDestroy: true,
- read: () => {
- const { body } = this
+ // 3. Skip the next two bytes in input.
+ i += 2
+ }
+ }
- if (body && body.resume) {
- body.resume()
- }
- },
- write: (chunk, encoding, callback) => {
- const { req } = this
+ // 3. Return output.
+ return Uint8Array.from(output)
+}
- if (req.push(chunk, encoding) || req._readableState.destroyed) {
- callback()
- } else {
- req[kResume] = callback
- }
- },
- destroy: (err, callback) => {
- const { body, req, res, ret, abort } = this
+// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
+/** @param {string} input */
+function parseMIMEType (input) {
+ // 1. Remove any leading and trailing HTTP whitespace
+ // from input.
+ input = removeHTTPWhitespace(input, true, true)
- if (!err && !ret._readableState.endEmitted) {
- err = new RequestAbortedError()
- }
+ // 2. Let position be a position variable for input,
+ // initially pointing at the start of input.
+ const position = { position: 0 }
- if (abort && err) {
- abort()
- }
+ // 3. Let type be the result of collecting a sequence
+ // of code points that are not U+002F (/) from
+ // input, given position.
+ const type = collectASequenceOfCodePointsFast(
+ '/',
+ input,
+ position
+ )
- util.destroy(body, err)
- util.destroy(req, err)
- util.destroy(res, err)
+ // 4. If type is the empty string or does not solely
+ // contain HTTP token code points, then return failure.
+ // https://mimesniff.spec.whatwg.org/#http-token-code-point
+ if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
+ return 'failure'
+ }
- removeSignal(this)
+ // 5. If position is past the end of input, then return
+ // failure
+ if (position.position > input.length) {
+ return 'failure'
+ }
- callback(err)
- }
- }).on('prefinish', () => {
- const { req } = this
+ // 6. Advance position by 1. (This skips past U+002F (/).)
+ position.position++
- // Node < 15 does not call _final in same tick.
- req.push(null)
- })
+ // 7. Let subtype be the result of collecting a sequence of
+ // code points that are not U+003B (;) from input, given
+ // position.
+ let subtype = collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
- this.res = null
+ // 8. Remove any trailing HTTP whitespace from subtype.
+ subtype = removeHTTPWhitespace(subtype, false, true)
- addSignal(this, signal)
+ // 9. If subtype is the empty string or does not solely
+ // contain HTTP token code points, then return failure.
+ if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
+ return 'failure'
}
- onConnect (abort, context) {
- const { ret, res } = this
+ const typeLowercase = type.toLowerCase()
+ const subtypeLowercase = subtype.toLowerCase()
- assert(!res, 'pipeline cannot be retried')
+ // 10. Let mimeType be a new MIME type record whose type
+ // is type, in ASCII lowercase, and subtype is subtype,
+ // in ASCII lowercase.
+ // https://mimesniff.spec.whatwg.org/#mime-type
+ const mimeType = {
+ type: typeLowercase,
+ subtype: subtypeLowercase,
+ /** @type {Map} */
+ parameters: new Map(),
+ // https://mimesniff.spec.whatwg.org/#mime-type-essence
+ essence: `${typeLowercase}/${subtypeLowercase}`
+ }
- if (ret.destroyed) {
- throw new RequestAbortedError()
- }
+ // 11. While position is not past the end of input:
+ while (position.position < input.length) {
+ // 1. Advance position by 1. (This skips past U+003B (;).)
+ position.position++
- this.abort = abort
- this.context = context
- }
+ // 2. Collect a sequence of code points that are HTTP
+ // whitespace from input given position.
+ collectASequenceOfCodePoints(
+ // https://fetch.spec.whatwg.org/#http-whitespace
+ char => HTTP_WHITESPACE_REGEX.test(char),
+ input,
+ position
+ )
- onHeaders (statusCode, rawHeaders, resume) {
- const { opaque, handler, context } = this
+ // 3. Let parameterName be the result of collecting a
+ // sequence of code points that are not U+003B (;)
+ // or U+003D (=) from input, given position.
+ let parameterName = collectASequenceOfCodePoints(
+ (char) => char !== ';' && char !== '=',
+ input,
+ position
+ )
- if (statusCode < 200) {
- if (this.onInfo) {
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- this.onInfo({ statusCode, headers })
- }
- return
- }
+ // 4. Set parameterName to parameterName, in ASCII
+ // lowercase.
+ parameterName = parameterName.toLowerCase()
- this.res = new PipelineResponse(resume)
+ // 5. If position is not past the end of input, then:
+ if (position.position < input.length) {
+ // 1. If the code point at position within input is
+ // U+003B (;), then continue.
+ if (input[position.position] === ';') {
+ continue
+ }
- let body
- try {
- this.handler = null
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- body = this.runInAsyncScope(handler, null, {
- statusCode,
- headers,
- opaque,
- body: this.res,
- context
- })
- } catch (err) {
- this.res.on('error', util.nop)
- throw err
+ // 2. Advance position by 1. (This skips past U+003D (=).)
+ position.position++
}
- if (!body || typeof body.on !== 'function') {
- throw new InvalidReturnValueError('expected Readable')
+ // 6. If position is past the end of input, then break.
+ if (position.position > input.length) {
+ break
}
- body
- .on('data', (chunk) => {
- const { ret, body } = this
+ // 7. Let parameterValue be null.
+ let parameterValue = null
- if (!ret.push(chunk) && body.pause) {
- body.pause()
- }
- })
- .on('error', (err) => {
- const { ret } = this
+ // 8. If the code point at position within input is
+ // U+0022 ("), then:
+ if (input[position.position] === '"') {
+ // 1. Set parameterValue to the result of collecting
+ // an HTTP quoted string from input, given position
+ // and the extract-value flag.
+ parameterValue = collectAnHTTPQuotedString(input, position, true)
- util.destroy(ret, err)
- })
- .on('end', () => {
- const { ret } = this
+ // 2. Collect a sequence of code points that are not
+ // U+003B (;) from input, given position.
+ collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
- ret.push(null)
- })
- .on('close', () => {
- const { ret } = this
+ // 9. Otherwise:
+ } else {
+ // 1. Set parameterValue to the result of collecting
+ // a sequence of code points that are not U+003B (;)
+ // from input, given position.
+ parameterValue = collectASequenceOfCodePointsFast(
+ ';',
+ input,
+ position
+ )
- if (!ret._readableState.ended) {
- util.destroy(ret, new RequestAbortedError())
- }
- })
+ // 2. Remove any trailing HTTP whitespace from parameterValue.
+ parameterValue = removeHTTPWhitespace(parameterValue, false, true)
- this.body = body
- }
+ // 3. If parameterValue is the empty string, then continue.
+ if (parameterValue.length === 0) {
+ continue
+ }
+ }
- onData (chunk) {
- const { res } = this
- return res.push(chunk)
+ // 10. If all of the following are true
+ // - parameterName is not the empty string
+ // - parameterName solely contains HTTP token code points
+ // - parameterValue solely contains HTTP quoted-string token code points
+ // - mimeType’s parameters[parameterName] does not exist
+ // then set mimeType’s parameters[parameterName] to parameterValue.
+ if (
+ parameterName.length !== 0 &&
+ HTTP_TOKEN_CODEPOINTS.test(parameterName) &&
+ (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&
+ !mimeType.parameters.has(parameterName)
+ ) {
+ mimeType.parameters.set(parameterName, parameterValue)
+ }
}
- onComplete (trailers) {
- const { res } = this
- res.push(null)
+ // 12. Return mimeType.
+ return mimeType
+}
+
+// https://infra.spec.whatwg.org/#forgiving-base64-decode
+/** @param {string} data */
+function forgivingBase64 (data) {
+ // 1. Remove all ASCII whitespace from data.
+ data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line
+
+ // 2. If data’s code point length divides by 4 leaving
+ // no remainder, then:
+ if (data.length % 4 === 0) {
+ // 1. If data ends with one or two U+003D (=) code points,
+ // then remove them from data.
+ data = data.replace(/=?=$/, '')
}
- onError (err) {
- const { ret } = this
- this.handler = null
- util.destroy(ret, err)
+ // 3. If data’s code point length divides by 4 leaving
+ // a remainder of 1, then return failure.
+ if (data.length % 4 === 1) {
+ return 'failure'
}
-}
-function pipeline (opts, handler) {
- try {
- const pipelineHandler = new PipelineHandler(opts, handler)
- this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
- return pipelineHandler.ret
- } catch (err) {
- return new PassThrough().destroy(err)
+ // 4. If data contains a code point that is not one of
+ // U+002B (+)
+ // U+002F (/)
+ // ASCII alphanumeric
+ // then return failure.
+ if (/[^+/0-9A-Za-z]/.test(data)) {
+ return 'failure'
}
-}
-module.exports = pipeline
+ const binary = atob(data)
+ const bytes = new Uint8Array(binary.length)
+ for (let byte = 0; byte < binary.length; byte++) {
+ bytes[byte] = binary.charCodeAt(byte)
+ }
-/***/ }),
+ return bytes
+}
-/***/ 50887:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
+// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string
+/**
+ * @param {string} input
+ * @param {{ position: number }} position
+ * @param {boolean?} extractValue
+ */
+function collectAnHTTPQuotedString (input, position, extractValue) {
+ // 1. Let positionStart be position.
+ const positionStart = position.position
+ // 2. Let value be the empty string.
+ let value = ''
+
+ // 3. Assert: the code point at position within input
+ // is U+0022 (").
+ assert(input[position.position] === '"')
+ // 4. Advance position by 1.
+ position.position++
-const Readable = __nccwpck_require__(38947)
-const {
- InvalidArgumentError,
- RequestAbortedError
-} = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { getResolveErrorBodyCallback } = __nccwpck_require__(80363)
-const { AsyncResource } = __nccwpck_require__(90290)
-const { addSignal, removeSignal } = __nccwpck_require__(52730)
+ // 5. While true:
+ while (true) {
+ // 1. Append the result of collecting a sequence of code points
+ // that are not U+0022 (") or U+005C (\) from input, given
+ // position, to value.
+ value += collectASequenceOfCodePoints(
+ (char) => char !== '"' && char !== '\\',
+ input,
+ position
+ )
-class RequestHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
+ // 2. If position is past the end of input, then break.
+ if (position.position >= input.length) {
+ break
}
- const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts
+ // 3. Let quoteOrBackslash be the code point at position within
+ // input.
+ const quoteOrBackslash = input[position.position]
- try {
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ // 4. Advance position by 1.
+ position.position++
- if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) {
- throw new InvalidArgumentError('invalid highWaterMark')
+ // 5. If quoteOrBackslash is U+005C (\), then:
+ if (quoteOrBackslash === '\\') {
+ // 1. If position is past the end of input, then append
+ // U+005C (\) to value and break.
+ if (position.position >= input.length) {
+ value += '\\'
+ break
}
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+ // 2. Append the code point at position within input to value.
+ value += input[position.position]
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
+ // 3. Advance position by 1.
+ position.position++
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
+ // 6. Otherwise:
+ } else {
+ // 1. Assert: quoteOrBackslash is U+0022 (").
+ assert(quoteOrBackslash === '"')
- super('UNDICI_REQUEST')
- } catch (err) {
- if (util.isStream(body)) {
- util.destroy(body.on('error', util.nop), err)
- }
- throw err
+ // 2. Break.
+ break
}
+ }
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.callback = callback
- this.res = null
- this.abort = null
- this.body = body
- this.trailers = {}
- this.context = null
- this.onInfo = onInfo || null
- this.throwOnError = throwOnError
- this.highWaterMark = highWaterMark
+ // 6. If the extract-value flag is set, then return value.
+ if (extractValue) {
+ return value
+ }
- if (util.isStream(body)) {
- body.on('error', (err) => {
- this.onError(err)
- })
- }
+ // 7. Return the code points from positionStart to position,
+ // inclusive, within input.
+ return input.slice(positionStart, position.position)
+}
- addSignal(this, signal)
- }
+/**
+ * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
+ */
+function serializeAMimeType (mimeType) {
+ assert(mimeType !== 'failure')
+ const { parameters, essence } = mimeType
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
- }
+ // 1. Let serialization be the concatenation of mimeType’s
+ // type, U+002F (/), and mimeType’s subtype.
+ let serialization = essence
- this.abort = abort
- this.context = context
- }
+ // 2. For each name → value of mimeType’s parameters:
+ for (let [name, value] of parameters.entries()) {
+ // 1. Append U+003B (;) to serialization.
+ serialization += ';'
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this
+ // 2. Append name to serialization.
+ serialization += name
- const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ // 3. Append U+003D (=) to serialization.
+ serialization += '='
- if (statusCode < 200) {
- if (this.onInfo) {
- this.onInfo({ statusCode, headers })
- }
- return
- }
+ // 4. If value does not solely contain HTTP token code
+ // points or value is the empty string, then:
+ if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
+ // 1. Precede each occurence of U+0022 (") or
+ // U+005C (\) in value with U+005C (\).
+ value = value.replace(/(\\|")/g, '\\$1')
- const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
- const contentType = parsedHeaders['content-type']
- const body = new Readable({ resume, abort, contentType, highWaterMark })
+ // 2. Prepend U+0022 (") to value.
+ value = '"' + value
- this.callback = null
- this.res = body
- if (callback !== null) {
- if (this.throwOnError && statusCode >= 400) {
- this.runInAsyncScope(getResolveErrorBodyCallback, null,
- { callback, body, contentType, statusCode, statusMessage, headers }
- )
- } else {
- this.runInAsyncScope(callback, null, null, {
- statusCode,
- headers,
- trailers: this.trailers,
- opaque,
- body,
- context
- })
- }
+ // 3. Append U+0022 (") to value.
+ value += '"'
}
- }
- onData (chunk) {
- const { res } = this
- return res.push(chunk)
+ // 5. Append value to serialization.
+ serialization += value
}
- onComplete (trailers) {
- const { res } = this
+ // 3. Return serialization.
+ return serialization
+}
- removeSignal(this)
+/**
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
+ * @param {string} char
+ */
+function isHTTPWhiteSpace (char) {
+ return char === '\r' || char === '\n' || char === '\t' || char === ' '
+}
- util.parseHeaders(trailers, this.trailers)
+/**
+ * @see https://fetch.spec.whatwg.org/#http-whitespace
+ * @param {string} str
+ */
+function removeHTTPWhitespace (str, leading = true, trailing = true) {
+ let lead = 0
+ let trail = str.length - 1
- res.push(null)
+ if (leading) {
+ for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);
}
- onError (err) {
- const { res, callback, body, opaque } = this
+ if (trailing) {
+ for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);
+ }
- removeSignal(this)
+ return str.slice(lead, trail + 1)
+}
- if (callback) {
- // TODO: Does this need queueMicrotask?
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
+/**
+ * @see https://infra.spec.whatwg.org/#ascii-whitespace
+ * @param {string} char
+ */
+function isASCIIWhitespace (char) {
+ return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' '
+}
- if (res) {
- this.res = null
- // Ensure all queued handlers are invoked before destroying res.
- queueMicrotask(() => {
- util.destroy(res, err)
- })
- }
+/**
+ * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
+ */
+function removeASCIIWhitespace (str, leading = true, trailing = true) {
+ let lead = 0
+ let trail = str.length - 1
- if (body) {
- this.body = null
- util.destroy(body, err)
- }
+ if (leading) {
+ for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);
}
-}
-function request (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- request.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
+ if (trailing) {
+ for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);
}
- try {
- this.dispatch(opts, new RequestHandler(opts, callback))
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
+ return str.slice(lead, trail + 1)
}
-module.exports = request
-module.exports.RequestHandler = RequestHandler
+module.exports = {
+ dataURLProcessor,
+ URLSerializer,
+ collectASequenceOfCodePoints,
+ collectASequenceOfCodePointsFast,
+ stringPercentDecode,
+ parseMIMEType,
+ collectAnHTTPQuotedString,
+ serializeAMimeType
+}
/***/ }),
-/***/ 44388:
+/***/ 17005:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { finished, PassThrough } = __nccwpck_require__(2203)
-const {
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError
-} = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { getResolveErrorBodyCallback } = __nccwpck_require__(80363)
-const { AsyncResource } = __nccwpck_require__(90290)
-const { addSignal, removeSignal } = __nccwpck_require__(52730)
+const { Blob, File: NativeFile } = __nccwpck_require__(20181)
+const { types } = __nccwpck_require__(39023)
+const { kState } = __nccwpck_require__(63730)
+const { isBlobLike } = __nccwpck_require__(72847)
+const { webidl } = __nccwpck_require__(94354)
+const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
+const { kEnumerableProperty } = __nccwpck_require__(89500)
+const encoder = new TextEncoder()
-class StreamHandler extends AsyncResource {
- constructor (opts, factory, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+class File extends Blob {
+ constructor (fileBits, fileName, options = {}) {
+ // The File constructor is invoked with two or three parameters, depending
+ // on whether the optional dictionary parameter is used. When the File()
+ // constructor is invoked, user agents must run the following steps:
+ webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })
- const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts
+ fileBits = webidl.converters['sequence'](fileBits)
+ fileName = webidl.converters.USVString(fileName)
+ options = webidl.converters.FilePropertyBag(options)
- try {
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ // 1. Let bytes be the result of processing blob parts given fileBits and
+ // options.
+ // Note: Blob handles this for us
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('invalid factory')
- }
+ // 2. Let n be the fileName argument to the constructor.
+ const n = fileName
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
- }
+ // 3. Process FilePropertyBag dictionary argument by running the following
+ // substeps:
- if (method === 'CONNECT') {
- throw new InvalidArgumentError('invalid method')
- }
+ // 1. If the type member is provided and is not the empty string, let t
+ // be set to the type dictionary member. If t contains any characters
+ // outside the range U+0020 to U+007E, then set t to the empty string
+ // and return from these substeps.
+ // 2. Convert every character in t to ASCII lowercase.
+ let t = options.type
+ let d
- if (onInfo && typeof onInfo !== 'function') {
- throw new InvalidArgumentError('invalid onInfo callback')
- }
+ // eslint-disable-next-line no-labels
+ substep: {
+ if (t) {
+ t = parseMIMEType(t)
- super('UNDICI_STREAM')
- } catch (err) {
- if (util.isStream(body)) {
- util.destroy(body.on('error', util.nop), err)
+ if (t === 'failure') {
+ t = ''
+ // eslint-disable-next-line no-labels
+ break substep
+ }
+
+ t = serializeAMimeType(t).toLowerCase()
}
- throw err
+
+ // 3. If the lastModified member is provided, let d be set to the
+ // lastModified dictionary member. If it is not provided, set d to the
+ // current date and time represented as the number of milliseconds since
+ // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
+ d = options.lastModified
}
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.factory = factory
- this.callback = callback
- this.res = null
- this.abort = null
- this.context = null
- this.trailers = null
- this.body = body
- this.onInfo = onInfo || null
- this.throwOnError = throwOnError || false
+ // 4. Return a new File object F such that:
+ // F refers to the bytes byte sequence.
+ // F.size is set to the number of total bytes in bytes.
+ // F.name is set to n.
+ // F.type is set to t.
+ // F.lastModified is set to d.
- if (util.isStream(body)) {
- body.on('error', (err) => {
- this.onError(err)
- })
+ super(processBlobParts(fileBits, options), { type: t })
+ this[kState] = {
+ name: n,
+ lastModified: d,
+ type: t
}
-
- addSignal(this, signal)
}
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
- }
+ get name () {
+ webidl.brandCheck(this, File)
- this.abort = abort
- this.context = context
+ return this[kState].name
}
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const { factory, opaque, context, callback, responseHeaders } = this
+ get lastModified () {
+ webidl.brandCheck(this, File)
- const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
+ return this[kState].lastModified
+ }
- if (statusCode < 200) {
- if (this.onInfo) {
- this.onInfo({ statusCode, headers })
- }
- return
- }
+ get type () {
+ webidl.brandCheck(this, File)
- this.factory = null
+ return this[kState].type
+ }
+}
- let res
+class FileLike {
+ constructor (blobLike, fileName, options = {}) {
+ // TODO: argument idl type check
- if (this.throwOnError && statusCode >= 400) {
- const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers
- const contentType = parsedHeaders['content-type']
- res = new PassThrough()
+ // The File constructor is invoked with two or three parameters, depending
+ // on whether the optional dictionary parameter is used. When the File()
+ // constructor is invoked, user agents must run the following steps:
- this.callback = null
- this.runInAsyncScope(getResolveErrorBodyCallback, null,
- { callback, body: res, contentType, statusCode, statusMessage, headers }
- )
- } else {
- if (factory === null) {
- return
- }
+ // 1. Let bytes be the result of processing blob parts given fileBits and
+ // options.
- res = this.runInAsyncScope(factory, null, {
- statusCode,
- headers,
- opaque,
- context
- })
+ // 2. Let n be the fileName argument to the constructor.
+ const n = fileName
- if (
- !res ||
- typeof res.write !== 'function' ||
- typeof res.end !== 'function' ||
- typeof res.on !== 'function'
- ) {
- throw new InvalidReturnValueError('expected Writable')
- }
+ // 3. Process FilePropertyBag dictionary argument by running the following
+ // substeps:
- // TODO: Avoid finished. It registers an unnecessary amount of listeners.
- finished(res, { readable: false }, (err) => {
- const { callback, res, opaque, trailers, abort } = this
+ // 1. If the type member is provided and is not the empty string, let t
+ // be set to the type dictionary member. If t contains any characters
+ // outside the range U+0020 to U+007E, then set t to the empty string
+ // and return from these substeps.
+ // TODO
+ const t = options.type
- this.res = null
- if (err || !res.readable) {
- util.destroy(res, err)
- }
+ // 2. Convert every character in t to ASCII lowercase.
+ // TODO
- this.callback = null
- this.runInAsyncScope(callback, null, err || null, { opaque, trailers })
+ // 3. If the lastModified member is provided, let d be set to the
+ // lastModified dictionary member. If it is not provided, set d to the
+ // current date and time represented as the number of milliseconds since
+ // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
+ const d = options.lastModified ?? Date.now()
- if (err) {
- abort()
- }
- })
+ // 4. Return a new File object F such that:
+ // F refers to the bytes byte sequence.
+ // F.size is set to the number of total bytes in bytes.
+ // F.name is set to n.
+ // F.type is set to t.
+ // F.lastModified is set to d.
+
+ this[kState] = {
+ blobLike,
+ name: n,
+ type: t,
+ lastModified: d
}
+ }
- res.on('drain', resume)
+ stream (...args) {
+ webidl.brandCheck(this, FileLike)
- this.res = res
+ return this[kState].blobLike.stream(...args)
+ }
- const needDrain = res.writableNeedDrain !== undefined
- ? res.writableNeedDrain
- : res._writableState && res._writableState.needDrain
+ arrayBuffer (...args) {
+ webidl.brandCheck(this, FileLike)
- return needDrain !== true
+ return this[kState].blobLike.arrayBuffer(...args)
}
- onData (chunk) {
- const { res } = this
+ slice (...args) {
+ webidl.brandCheck(this, FileLike)
- return res ? res.write(chunk) : true
+ return this[kState].blobLike.slice(...args)
}
- onComplete (trailers) {
- const { res } = this
-
- removeSignal(this)
+ text (...args) {
+ webidl.brandCheck(this, FileLike)
- if (!res) {
- return
- }
+ return this[kState].blobLike.text(...args)
+ }
- this.trailers = util.parseHeaders(trailers)
+ get size () {
+ webidl.brandCheck(this, FileLike)
- res.end()
+ return this[kState].blobLike.size
}
- onError (err) {
- const { res, callback, opaque, body } = this
-
- removeSignal(this)
+ get type () {
+ webidl.brandCheck(this, FileLike)
- this.factory = null
+ return this[kState].blobLike.type
+ }
- if (res) {
- this.res = null
- util.destroy(res, err)
- } else if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
+ get name () {
+ webidl.brandCheck(this, FileLike)
- if (body) {
- this.body = null
- util.destroy(body, err)
- }
+ return this[kState].name
}
-}
-function stream (opts, factory, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- stream.call(this, opts, factory, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
+ get lastModified () {
+ webidl.brandCheck(this, FileLike)
+
+ return this[kState].lastModified
}
- try {
- this.dispatch(opts, new StreamHandler(opts, factory, callback))
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
+ get [Symbol.toStringTag] () {
+ return 'File'
}
}
-module.exports = stream
-
-
-/***/ }),
-
-/***/ 56342:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(53959)
-const { AsyncResource } = __nccwpck_require__(90290)
-const util = __nccwpck_require__(89500)
-const { addSignal, removeSignal } = __nccwpck_require__(52730)
-const assert = __nccwpck_require__(42613)
+Object.defineProperties(File.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'File',
+ configurable: true
+ },
+ name: kEnumerableProperty,
+ lastModified: kEnumerableProperty
+})
-class UpgradeHandler extends AsyncResource {
- constructor (opts, callback) {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('invalid opts')
- }
+webidl.converters.Blob = webidl.interfaceConverter(Blob)
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
+webidl.converters.BlobPart = function (V, opts) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
}
- const { signal, opaque, responseHeaders } = opts
-
- if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
- throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
+ if (
+ ArrayBuffer.isView(V) ||
+ types.isAnyArrayBuffer(V)
+ ) {
+ return webidl.converters.BufferSource(V, opts)
}
+ }
- super('UNDICI_UPGRADE')
-
- this.responseHeaders = responseHeaders || null
- this.opaque = opaque || null
- this.callback = callback
- this.abort = null
- this.context = null
+ return webidl.converters.USVString(V, opts)
+}
- addSignal(this, signal)
- }
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.BlobPart
+)
- onConnect (abort, context) {
- if (!this.callback) {
- throw new RequestAbortedError()
+// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag
+webidl.converters.FilePropertyBag = webidl.dictionaryConverter([
+ {
+ key: 'lastModified',
+ converter: webidl.converters['long long'],
+ get defaultValue () {
+ return Date.now()
}
+ },
+ {
+ key: 'type',
+ converter: webidl.converters.DOMString,
+ defaultValue: ''
+ },
+ {
+ key: 'endings',
+ converter: (value) => {
+ value = webidl.converters.DOMString(value)
+ value = value.toLowerCase()
- this.abort = abort
- this.context = null
- }
+ if (value !== 'native') {
+ value = 'transparent'
+ }
- onHeaders () {
- throw new SocketError('bad upgrade', null)
+ return value
+ },
+ defaultValue: 'transparent'
}
+])
- onUpgrade (statusCode, rawHeaders, socket) {
- const { callback, opaque, context } = this
+/**
+ * @see https://www.w3.org/TR/FileAPI/#process-blob-parts
+ * @param {(NodeJS.TypedArray|Blob|string)[]} parts
+ * @param {{ type: string, endings: string }} options
+ */
+function processBlobParts (parts, options) {
+ // 1. Let bytes be an empty sequence of bytes.
+ /** @type {NodeJS.TypedArray[]} */
+ const bytes = []
- assert.strictEqual(statusCode, 101)
+ // 2. For each element in parts:
+ for (const element of parts) {
+ // 1. If element is a USVString, run the following substeps:
+ if (typeof element === 'string') {
+ // 1. Let s be element.
+ let s = element
- removeSignal(this)
+ // 2. If the endings member of options is "native", set s
+ // to the result of converting line endings to native
+ // of element.
+ if (options.endings === 'native') {
+ s = convertLineEndingsNative(s)
+ }
- this.callback = null
- const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
- this.runInAsyncScope(callback, null, null, {
- headers,
- socket,
- opaque,
- context
- })
+ // 3. Append the result of UTF-8 encoding s to bytes.
+ bytes.push(encoder.encode(s))
+ } else if (
+ types.isAnyArrayBuffer(element) ||
+ types.isTypedArray(element)
+ ) {
+ // 2. If element is a BufferSource, get a copy of the
+ // bytes held by the buffer source, and append those
+ // bytes to bytes.
+ if (!element.buffer) { // ArrayBuffer
+ bytes.push(new Uint8Array(element))
+ } else {
+ bytes.push(
+ new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
+ )
+ }
+ } else if (isBlobLike(element)) {
+ // 3. If element is a Blob, append the bytes it represents
+ // to bytes.
+ bytes.push(element)
+ }
}
- onError (err) {
- const { callback, opaque } = this
+ // 3. Return bytes.
+ return bytes
+}
- removeSignal(this)
+/**
+ * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native
+ * @param {string} s
+ */
+function convertLineEndingsNative (s) {
+ // 1. Let native line ending be be the code point U+000A LF.
+ let nativeLineEnding = '\n'
- if (callback) {
- this.callback = null
- queueMicrotask(() => {
- this.runInAsyncScope(callback, null, err, { opaque })
- })
- }
+ // 2. If the underlying platform’s conventions are to
+ // represent newlines as a carriage return and line feed
+ // sequence, set native line ending to the code point
+ // U+000D CR followed by the code point U+000A LF.
+ if (process.platform === 'win32') {
+ nativeLineEnding = '\r\n'
}
-}
-function upgrade (opts, callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- upgrade.call(this, opts, (err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
+ return s.replace(/\r?\n/g, nativeLineEnding)
+}
- try {
- const upgradeHandler = new UpgradeHandler(opts, callback)
- this.dispatch({
- ...opts,
- method: opts.method || 'GET',
- upgrade: opts.protocol || 'Websocket'
- }, upgradeHandler)
- } catch (err) {
- if (typeof callback !== 'function') {
- throw err
- }
- const opaque = opts && opts.opaque
- queueMicrotask(() => callback(err, { opaque }))
- }
+// If this function is moved to ./util.js, some tools (such as
+// rollup) will warn about circular dependencies. See:
+// https://github.com/nodejs/undici/issues/1629
+function isFileLike (object) {
+ return (
+ (NativeFile && object instanceof NativeFile) ||
+ object instanceof File || (
+ object &&
+ (typeof object.stream === 'function' ||
+ typeof object.arrayBuffer === 'function') &&
+ object[Symbol.toStringTag] === 'File'
+ )
+ )
}
-module.exports = upgrade
+module.exports = { File, FileLike, isFileLike }
/***/ }),
-/***/ 82531:
+/***/ 47453:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-module.exports.request = __nccwpck_require__(50887)
-module.exports.stream = __nccwpck_require__(44388)
-module.exports.pipeline = __nccwpck_require__(62466)
-module.exports.upgrade = __nccwpck_require__(56342)
-module.exports.connect = __nccwpck_require__(73192)
+const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(72847)
+const { kState } = __nccwpck_require__(63730)
+const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(17005)
+const { webidl } = __nccwpck_require__(94354)
+const { Blob, File: NativeFile } = __nccwpck_require__(20181)
+/** @type {globalThis['File']} */
+const File = NativeFile ?? UndiciFile
-/***/ }),
+// https://xhr.spec.whatwg.org/#formdata
+class FormData {
+ constructor (form) {
+ if (form !== undefined) {
+ throw webidl.errors.conversionFailed({
+ prefix: 'FormData constructor',
+ argument: 'Argument 1',
+ types: ['undefined']
+ })
+ }
-/***/ 38947:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ this[kState] = []
+ }
-// Ported from https://github.com/nodejs/undici/pull/907
+ append (name, value, filename = undefined) {
+ webidl.brandCheck(this, FormData)
+ webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })
+ if (arguments.length === 3 && !isBlobLike(value)) {
+ throw new TypeError(
+ "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
+ )
+ }
-const assert = __nccwpck_require__(42613)
-const { Readable } = __nccwpck_require__(2203)
-const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(89500)
+ // 1. Let value be value if given; otherwise blobValue.
-let Blob
+ name = webidl.converters.USVString(name)
+ value = isBlobLike(value)
+ ? webidl.converters.Blob(value, { strict: false })
+ : webidl.converters.USVString(value)
+ filename = arguments.length === 3
+ ? webidl.converters.USVString(filename)
+ : undefined
-const kConsume = Symbol('kConsume')
-const kReading = Symbol('kReading')
-const kBody = Symbol('kBody')
-const kAbort = Symbol('abort')
-const kContentType = Symbol('kContentType')
+ // 2. Let entry be the result of creating an entry with
+ // name, value, and filename if given.
+ const entry = makeEntry(name, value, filename)
-const noop = () => {}
+ // 3. Append entry to this’s entry list.
+ this[kState].push(entry)
+ }
-module.exports = class BodyReadable extends Readable {
- constructor ({
- resume,
- abort,
- contentType = '',
- highWaterMark = 64 * 1024 // Same as nodejs fs streams.
- }) {
- super({
- autoDestroy: true,
- read: resume,
- highWaterMark
- })
+ delete (name) {
+ webidl.brandCheck(this, FormData)
- this._readableState.dataEmitted = false
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })
- this[kAbort] = abort
- this[kConsume] = null
- this[kBody] = null
- this[kContentType] = contentType
+ name = webidl.converters.USVString(name)
- // Is stream being consumed through Readable API?
- // This is an optimization so that we avoid checking
- // for 'data' and 'readable' listeners in the hot path
- // inside push().
- this[kReading] = false
+ // The delete(name) method steps are to remove all entries whose name
+ // is name from this’s entry list.
+ this[kState] = this[kState].filter(entry => entry.name !== name)
}
- destroy (err) {
- if (this.destroyed) {
- // Node < 16
- return this
- }
+ get (name) {
+ webidl.brandCheck(this, FormData)
- if (!err && !this._readableState.endEmitted) {
- err = new RequestAbortedError()
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })
- if (err) {
- this[kAbort]()
+ name = webidl.converters.USVString(name)
+
+ // 1. If there is no entry whose name is name in this’s entry list,
+ // then return null.
+ const idx = this[kState].findIndex((entry) => entry.name === name)
+ if (idx === -1) {
+ return null
}
- return super.destroy(err)
+ // 2. Return the value of the first entry whose name is name from
+ // this’s entry list.
+ return this[kState][idx].value
}
- emit (ev, ...args) {
- if (ev === 'data') {
- // Node < 16.7
- this._readableState.dataEmitted = true
- } else if (ev === 'error') {
- // Node < 16
- this._readableState.errorEmitted = true
- }
- return super.emit(ev, ...args)
- }
+ getAll (name) {
+ webidl.brandCheck(this, FormData)
- on (ev, ...args) {
- if (ev === 'data' || ev === 'readable') {
- this[kReading] = true
- }
- return super.on(ev, ...args)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })
+
+ name = webidl.converters.USVString(name)
+
+ // 1. If there is no entry whose name is name in this’s entry list,
+ // then return the empty list.
+ // 2. Return the values of all entries whose name is name, in order,
+ // from this’s entry list.
+ return this[kState]
+ .filter((entry) => entry.name === name)
+ .map((entry) => entry.value)
}
- addListener (ev, ...args) {
- return this.on(ev, ...args)
+ has (name) {
+ webidl.brandCheck(this, FormData)
+
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })
+
+ name = webidl.converters.USVString(name)
+
+ // The has(name) method steps are to return true if there is an entry
+ // whose name is name in this’s entry list; otherwise false.
+ return this[kState].findIndex((entry) => entry.name === name) !== -1
}
- off (ev, ...args) {
- const ret = super.off(ev, ...args)
- if (ev === 'data' || ev === 'readable') {
- this[kReading] = (
- this.listenerCount('data') > 0 ||
- this.listenerCount('readable') > 0
+ set (name, value, filename = undefined) {
+ webidl.brandCheck(this, FormData)
+
+ webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })
+
+ if (arguments.length === 3 && !isBlobLike(value)) {
+ throw new TypeError(
+ "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
)
}
- return ret
- }
- removeListener (ev, ...args) {
- return this.off(ev, ...args)
- }
+ // The set(name, value) and set(name, blobValue, filename) method steps
+ // are:
- push (chunk) {
- if (this[kConsume] && chunk !== null && this.readableLength === 0) {
- consumePush(this[kConsume], chunk)
- return this[kReading] ? super.push(chunk) : true
+ // 1. Let value be value if given; otherwise blobValue.
+
+ name = webidl.converters.USVString(name)
+ value = isBlobLike(value)
+ ? webidl.converters.Blob(value, { strict: false })
+ : webidl.converters.USVString(value)
+ filename = arguments.length === 3
+ ? toUSVString(filename)
+ : undefined
+
+ // 2. Let entry be the result of creating an entry with name, value, and
+ // filename if given.
+ const entry = makeEntry(name, value, filename)
+
+ // 3. If there are entries in this’s entry list whose name is name, then
+ // replace the first such entry with entry and remove the others.
+ const idx = this[kState].findIndex((entry) => entry.name === name)
+ if (idx !== -1) {
+ this[kState] = [
+ ...this[kState].slice(0, idx),
+ entry,
+ ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
+ ]
+ } else {
+ // 4. Otherwise, append entry to this’s entry list.
+ this[kState].push(entry)
}
- return super.push(chunk)
}
- // https://fetch.spec.whatwg.org/#dom-body-text
- async text () {
- return consume(this, 'text')
- }
+ entries () {
+ webidl.brandCheck(this, FormData)
- // https://fetch.spec.whatwg.org/#dom-body-json
- async json () {
- return consume(this, 'json')
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'key+value'
+ )
}
- // https://fetch.spec.whatwg.org/#dom-body-blob
- async blob () {
- return consume(this, 'blob')
- }
+ keys () {
+ webidl.brandCheck(this, FormData)
- // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
- async arrayBuffer () {
- return consume(this, 'arrayBuffer')
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'key'
+ )
}
- // https://fetch.spec.whatwg.org/#dom-body-formdata
- async formData () {
- // TODO: Implement.
- throw new NotSupportedError()
- }
+ values () {
+ webidl.brandCheck(this, FormData)
- // https://fetch.spec.whatwg.org/#dom-body-bodyused
- get bodyUsed () {
- return util.isDisturbed(this)
+ return makeIterator(
+ () => this[kState].map(pair => [pair.name, pair.value]),
+ 'FormData',
+ 'value'
+ )
}
- // https://fetch.spec.whatwg.org/#dom-body-body
- get body () {
- if (!this[kBody]) {
- this[kBody] = ReadableStreamFrom(this)
- if (this[kConsume]) {
- // TODO: Is this the best way to force a lock?
- this[kBody].getReader() // Ensure stream is locked.
- assert(this[kBody].locked)
- }
- }
- return this[kBody]
- }
+ /**
+ * @param {(value: string, key: string, self: FormData) => void} callbackFn
+ * @param {unknown} thisArg
+ */
+ forEach (callbackFn, thisArg = globalThis) {
+ webidl.brandCheck(this, FormData)
- dump (opts) {
- let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144
- const signal = opts && opts.signal
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })
- if (signal) {
- try {
- if (typeof signal !== 'object' || !('aborted' in signal)) {
- throw new InvalidArgumentError('signal must be an AbortSignal')
- }
- util.throwIfAborted(signal)
- } catch (err) {
- return Promise.reject(err)
- }
+ if (typeof callbackFn !== 'function') {
+ throw new TypeError(
+ "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."
+ )
}
- if (this.closed) {
- return Promise.resolve(null)
+ for (const [key, value] of this) {
+ callbackFn.apply(thisArg, [value, key, this])
}
-
- return new Promise((resolve, reject) => {
- const signalListenerCleanup = signal
- ? util.addAbortListener(signal, () => {
- this.destroy()
- })
- : noop
-
- this
- .on('close', function () {
- signalListenerCleanup()
- if (signal && signal.aborted) {
- reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }))
- } else {
- resolve(null)
- }
- })
- .on('error', noop)
- .on('data', function (chunk) {
- limit -= chunk.length
- if (limit <= 0) {
- this.destroy()
- }
- })
- .resume()
- })
}
}
-// https://streams.spec.whatwg.org/#readablestream-locked
-function isLocked (self) {
- // Consume is an implicit lock.
- return (self[kBody] && self[kBody].locked === true) || self[kConsume]
-}
-
-// https://fetch.spec.whatwg.org/#body-unusable
-function isUnusable (self) {
- return util.isDisturbed(self) || isLocked(self)
-}
+FormData.prototype[Symbol.iterator] = FormData.prototype.entries
-async function consume (stream, type) {
- if (isUnusable(stream)) {
- throw new TypeError('unusable')
+Object.defineProperties(FormData.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'FormData',
+ configurable: true
}
+})
- assert(!stream[kConsume])
+/**
+ * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
+ * @param {string} name
+ * @param {string|Blob} value
+ * @param {?string} filename
+ * @returns
+ */
+function makeEntry (name, value, filename) {
+ // 1. Set name to the result of converting name into a scalar value string.
+ // "To convert a string into a scalar value string, replace any surrogates
+ // with U+FFFD."
+ // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end
+ name = Buffer.from(name).toString('utf8')
- return new Promise((resolve, reject) => {
- stream[kConsume] = {
- type,
- stream,
- resolve,
- reject,
- length: 0,
- body: []
+ // 2. If value is a string, then set value to the result of converting
+ // value into a scalar value string.
+ if (typeof value === 'string') {
+ value = Buffer.from(value).toString('utf8')
+ } else {
+ // 3. Otherwise:
+
+ // 1. If value is not a File object, then set value to a new File object,
+ // representing the same bytes, whose name attribute value is "blob"
+ if (!isFileLike(value)) {
+ value = value instanceof Blob
+ ? new File([value], 'blob', { type: value.type })
+ : new FileLike(value, 'blob', { type: value.type })
}
- stream
- .on('error', function (err) {
- consumeFinish(this[kConsume], err)
- })
- .on('close', function () {
- if (this[kConsume].body !== null) {
- consumeFinish(this[kConsume], new RequestAbortedError())
- }
- })
-
- process.nextTick(consumeStart, stream[kConsume])
- })
-}
+ // 2. If filename is given, then set value to a new File object,
+ // representing the same bytes, whose name attribute is filename.
+ if (filename !== undefined) {
+ /** @type {FilePropertyBag} */
+ const options = {
+ type: value.type,
+ lastModified: value.lastModified
+ }
-function consumeStart (consume) {
- if (consume.body === null) {
- return
+ value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile
+ ? new File([value], filename, options)
+ : new FileLike(value, filename, options)
+ }
}
- const { _readableState: state } = consume.stream
-
- for (const chunk of state.buffer) {
- consumePush(consume, chunk)
- }
+ // 4. Return an entry whose name is name and whose value is value.
+ return { name, value }
+}
- if (state.endEmitted) {
- consumeEnd(this[kConsume])
- } else {
- consume.stream.on('end', function () {
- consumeEnd(this[kConsume])
- })
- }
+module.exports = { FormData }
- consume.stream.resume()
- while (consume.stream.read() != null) {
- // Loop
- }
-}
+/***/ }),
-function consumeEnd (consume) {
- const { type, body, resolve, stream, length } = consume
+/***/ 62896:
+/***/ ((module) => {
- try {
- if (type === 'text') {
- resolve(toUSVString(Buffer.concat(body)))
- } else if (type === 'json') {
- resolve(JSON.parse(Buffer.concat(body)))
- } else if (type === 'arrayBuffer') {
- const dst = new Uint8Array(length)
- let pos = 0
- for (const buf of body) {
- dst.set(buf, pos)
- pos += buf.byteLength
- }
- resolve(dst.buffer)
- } else if (type === 'blob') {
- if (!Blob) {
- Blob = (__nccwpck_require__(20181).Blob)
- }
- resolve(new Blob(body, { type: stream[kContentType] }))
- }
+// In case of breaking changes, increase the version
+// number to avoid conflicts.
+const globalOrigin = Symbol.for('undici.globalOrigin.1')
- consumeFinish(consume)
- } catch (err) {
- stream.destroy(err)
- }
+function getGlobalOrigin () {
+ return globalThis[globalOrigin]
}
-function consumePush (consume, chunk) {
- consume.length += chunk.length
- consume.body.push(chunk)
-}
+function setGlobalOrigin (newOrigin) {
+ if (newOrigin === undefined) {
+ Object.defineProperty(globalThis, globalOrigin, {
+ value: undefined,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
-function consumeFinish (consume, err) {
- if (consume.body === null) {
return
}
- if (err) {
- consume.reject(err)
- } else {
- consume.resolve()
+ const parsedURL = new URL(newOrigin)
+
+ if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
+ throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
}
- consume.type = null
- consume.stream = null
- consume.resolve = null
- consume.reject = null
- consume.length = 0
- consume.body = null
+ Object.defineProperty(globalThis, globalOrigin, {
+ value: parsedURL,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
+}
+
+module.exports = {
+ getGlobalOrigin,
+ setGlobalOrigin
}
/***/ }),
-/***/ 80363:
+/***/ 12801:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const assert = __nccwpck_require__(42613)
+// https://github.com/Ethan-Arrowood/undici-fetch
+
+
+
+const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
+const { kGuard } = __nccwpck_require__(63730)
+const { kEnumerableProperty } = __nccwpck_require__(89500)
const {
- ResponseStatusCodeError
-} = __nccwpck_require__(53959)
-const { toUSVString } = __nccwpck_require__(89500)
+ makeIterator,
+ isValidHeaderName,
+ isValidHeaderValue
+} = __nccwpck_require__(72847)
+const { webidl } = __nccwpck_require__(94354)
+const assert = __nccwpck_require__(42613)
-async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) {
- assert(body)
+const kHeadersMap = Symbol('headers map')
+const kHeadersSortedMap = Symbol('headers map sorted')
- let chunks = []
- let limit = 0
+/**
+ * @param {number} code
+ */
+function isHTTPWhiteSpaceCharCode (code) {
+ return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
+}
- for await (const chunk of body) {
- chunks.push(chunk)
- limit += chunk.length
- if (limit > 128 * 1024) {
- chunks = null
- break
- }
- }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
+ * @param {string} potentialValue
+ */
+function headerValueNormalize (potentialValue) {
+ // To normalize a byte sequence potentialValue, remove
+ // any leading and trailing HTTP whitespace bytes from
+ // potentialValue.
+ let i = 0; let j = potentialValue.length
- if (statusCode === 204 || !contentType || !chunks) {
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
- return
- }
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j
+ while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i
- try {
- if (contentType.startsWith('application/json')) {
- const payload = JSON.parse(toUSVString(Buffer.concat(chunks)))
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
- return
+ return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)
+}
+
+function fill (headers, object) {
+ // To fill a Headers object headers with a given object object, run these steps:
+
+ // 1. If object is a sequence, then for each header in object:
+ // Note: webidl conversion to array has already been done.
+ if (Array.isArray(object)) {
+ for (let i = 0; i < object.length; ++i) {
+ const header = object[i]
+ // 1. If header does not contain exactly two items, then throw a TypeError.
+ if (header.length !== 2) {
+ throw webidl.errors.exception({
+ header: 'Headers constructor',
+ message: `expected name/value pair to be length 2, found ${header.length}.`
+ })
+ }
+
+ // 2. Append (header’s first item, header’s second item) to headers.
+ appendHeader(headers, header[0], header[1])
}
+ } else if (typeof object === 'object' && object !== null) {
+ // Note: null should throw
- if (contentType.startsWith('text/')) {
- const payload = toUSVString(Buffer.concat(chunks))
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload))
- return
+ // 2. Otherwise, object is a record, then for each key → value in object,
+ // append (key, value) to headers
+ const keys = Object.keys(object)
+ for (let i = 0; i < keys.length; ++i) {
+ appendHeader(headers, keys[i], object[keys[i]])
}
- } catch (err) {
- // Process in a fallback if error
+ } else {
+ throw webidl.errors.conversionFailed({
+ prefix: 'Headers constructor',
+ argument: 'Argument 1',
+ types: ['sequence>', 'record']
+ })
}
-
- process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers))
}
-module.exports = { getResolveErrorBodyCallback }
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-headers-append
+ */
+function appendHeader (headers, name, value) {
+ // 1. Normalize value.
+ value = headerValueNormalize(value)
+ // 2. If name is not a header name or value is not a
+ // header value, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.append',
+ value: name,
+ type: 'header name'
+ })
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.append',
+ value,
+ type: 'header value'
+ })
+ }
-/***/ }),
+ // 3. If headers’s guard is "immutable", then throw a TypeError.
+ // 4. Otherwise, if headers’s guard is "request" and name is a
+ // forbidden header name, return.
+ // Note: undici does not implement forbidden header names
+ if (headers[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (headers[kGuard] === 'request-no-cors') {
+ // 5. Otherwise, if headers’s guard is "request-no-cors":
+ // TODO
+ }
-/***/ 95377:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 6. Otherwise, if headers’s guard is "response" and name is a
+ // forbidden response-header name, return.
+ // 7. Append (name, value) to headers’s header list.
+ return headers[kHeadersList].append(name, value)
+ // 8. If headers’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from headers
+}
-const {
- BalancedPoolMissingUpstreamError,
- InvalidArgumentError
-} = __nccwpck_require__(53959)
-const {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kGetDispatcher
-} = __nccwpck_require__(18804)
-const Pool = __nccwpck_require__(44288)
-const { kUrl, kInterceptors } = __nccwpck_require__(68031)
-const { parseOrigin } = __nccwpck_require__(89500)
-const kFactory = Symbol('factory')
+class HeadersList {
+ /** @type {[string, string][]|null} */
+ cookies = null
-const kOptions = Symbol('options')
-const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor')
-const kCurrentWeight = Symbol('kCurrentWeight')
-const kIndex = Symbol('kIndex')
-const kWeight = Symbol('kWeight')
-const kMaxWeightPerServer = Symbol('kMaxWeightPerServer')
-const kErrorPenalty = Symbol('kErrorPenalty')
+ constructor (init) {
+ if (init instanceof HeadersList) {
+ this[kHeadersMap] = new Map(init[kHeadersMap])
+ this[kHeadersSortedMap] = init[kHeadersSortedMap]
+ this.cookies = init.cookies === null ? null : [...init.cookies]
+ } else {
+ this[kHeadersMap] = new Map(init)
+ this[kHeadersSortedMap] = null
+ }
+ }
-function getGreatestCommonDivisor (a, b) {
- if (b === 0) return a
- return getGreatestCommonDivisor(b, a % b)
-}
+ // https://fetch.spec.whatwg.org/#header-list-contains
+ contains (name) {
+ // A header list list contains a header name name if list
+ // contains a header whose name is a byte-case-insensitive
+ // match for name.
+ name = name.toLowerCase()
-function defaultFactory (origin, opts) {
- return new Pool(origin, opts)
-}
+ return this[kHeadersMap].has(name)
+ }
-class BalancedPool extends PoolBase {
- constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) {
- super()
+ clear () {
+ this[kHeadersMap].clear()
+ this[kHeadersSortedMap] = null
+ this.cookies = null
+ }
- this[kOptions] = opts
- this[kIndex] = -1
- this[kCurrentWeight] = 0
+ // https://fetch.spec.whatwg.org/#concept-header-list-append
+ append (name, value) {
+ this[kHeadersSortedMap] = null
- this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100
- this[kErrorPenalty] = this[kOptions].errorPenalty || 15
+ // 1. If list contains name, then set name to the first such
+ // header’s name.
+ const lowercaseName = name.toLowerCase()
+ const exists = this[kHeadersMap].get(lowercaseName)
- if (!Array.isArray(upstreams)) {
- upstreams = [upstreams]
+ // 2. Append (name, value) to list.
+ if (exists) {
+ const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
+ this[kHeadersMap].set(lowercaseName, {
+ name: exists.name,
+ value: `${exists.value}${delimiter}${value}`
+ })
+ } else {
+ this[kHeadersMap].set(lowercaseName, { name, value })
}
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
+ if (lowercaseName === 'set-cookie') {
+ this.cookies ??= []
+ this.cookies.push(value)
}
+ }
- this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool)
- ? opts.interceptors.BalancedPool
- : []
- this[kFactory] = factory
+ // https://fetch.spec.whatwg.org/#concept-header-list-set
+ set (name, value) {
+ this[kHeadersSortedMap] = null
+ const lowercaseName = name.toLowerCase()
- for (const upstream of upstreams) {
- this.addUpstream(upstream)
+ if (lowercaseName === 'set-cookie') {
+ this.cookies = [value]
}
- this._updateBalancedPoolStats()
+
+ // 1. If list contains name, then set the value of
+ // the first such header to value and remove the
+ // others.
+ // 2. Otherwise, append header (name, value) to list.
+ this[kHeadersMap].set(lowercaseName, { name, value })
}
- addUpstream (upstream) {
- const upstreamOrigin = parseOrigin(upstream).origin
+ // https://fetch.spec.whatwg.org/#concept-header-list-delete
+ delete (name) {
+ this[kHeadersSortedMap] = null
- if (this[kClients].find((pool) => (
- pool[kUrl].origin === upstreamOrigin &&
- pool.closed !== true &&
- pool.destroyed !== true
- ))) {
- return this
+ name = name.toLowerCase()
+
+ if (name === 'set-cookie') {
+ this.cookies = null
}
- const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions]))
- this[kAddClient](pool)
- pool.on('connect', () => {
- pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty])
- })
+ this[kHeadersMap].delete(name)
+ }
- pool.on('connectionError', () => {
- pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
- this._updateBalancedPoolStats()
- })
+ // https://fetch.spec.whatwg.org/#concept-header-list-get
+ get (name) {
+ const value = this[kHeadersMap].get(name.toLowerCase())
- pool.on('disconnect', (...args) => {
- const err = args[2]
- if (err && err.code === 'UND_ERR_SOCKET') {
- // decrease the weight of the pool.
- pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty])
- this._updateBalancedPoolStats()
- }
- })
+ // 1. If list does not contain name, then return null.
+ // 2. Return the values of all headers in list whose name
+ // is a byte-case-insensitive match for name,
+ // separated from each other by 0x2C 0x20, in order.
+ return value === undefined ? null : value.value
+ }
- for (const client of this[kClients]) {
- client[kWeight] = this[kMaxWeightPerServer]
+ * [Symbol.iterator] () {
+ // use the lowercased name
+ for (const [name, { value }] of this[kHeadersMap]) {
+ yield [name, value]
}
+ }
- this._updateBalancedPoolStats()
+ get entries () {
+ const headers = {}
- return this
- }
+ if (this[kHeadersMap].size) {
+ for (const { name, value } of this[kHeadersMap].values()) {
+ headers[name] = value
+ }
+ }
- _updateBalancedPoolStats () {
- this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0)
+ return headers
}
+}
- removeUpstream (upstream) {
- const upstreamOrigin = parseOrigin(upstream).origin
+// https://fetch.spec.whatwg.org/#headers-class
+class Headers {
+ constructor (init = undefined) {
+ if (init === kConstruct) {
+ return
+ }
+ this[kHeadersList] = new HeadersList()
- const pool = this[kClients].find((pool) => (
- pool[kUrl].origin === upstreamOrigin &&
- pool.closed !== true &&
- pool.destroyed !== true
- ))
+ // The new Headers(init) constructor steps are:
- if (pool) {
- this[kRemoveClient](pool)
- }
+ // 1. Set this’s guard to "none".
+ this[kGuard] = 'none'
- return this
+ // 2. If init is given, then fill this with init.
+ if (init !== undefined) {
+ init = webidl.converters.HeadersInit(init)
+ fill(this, init)
+ }
}
- get upstreams () {
- return this[kClients]
- .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true)
- .map((p) => p[kUrl].origin)
+ // https://fetch.spec.whatwg.org/#dom-headers-append
+ append (name, value) {
+ webidl.brandCheck(this, Headers)
+
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })
+
+ name = webidl.converters.ByteString(name)
+ value = webidl.converters.ByteString(value)
+
+ return appendHeader(this, name, value)
}
- [kGetDispatcher] () {
- // We validate that pools is greater than 0,
- // otherwise we would have to wait until an upstream
- // is added, which might never happen.
- if (this[kClients].length === 0) {
- throw new BalancedPoolMissingUpstreamError()
- }
+ // https://fetch.spec.whatwg.org/#dom-headers-delete
+ delete (name) {
+ webidl.brandCheck(this, Headers)
- const dispatcher = this[kClients].find(dispatcher => (
- !dispatcher[kNeedDrain] &&
- dispatcher.closed !== true &&
- dispatcher.destroyed !== true
- ))
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })
- if (!dispatcher) {
- return
+ name = webidl.converters.ByteString(name)
+
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.delete',
+ value: name,
+ type: 'header name'
+ })
+ }
+
+ // 2. If this’s guard is "immutable", then throw a TypeError.
+ // 3. Otherwise, if this’s guard is "request" and name is a
+ // forbidden header name, return.
+ // 4. Otherwise, if this’s guard is "request-no-cors", name
+ // is not a no-CORS-safelisted request-header name, and
+ // name is not a privileged no-CORS request-header name,
+ // return.
+ // 5. Otherwise, if this’s guard is "response" and name is
+ // a forbidden response-header name, return.
+ // Note: undici does not implement forbidden header names
+ if (this[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (this[kGuard] === 'request-no-cors') {
+ // TODO
}
- const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true)
-
- if (allClientsBusy) {
+ // 6. If this’s header list does not contain name, then
+ // return.
+ if (!this[kHeadersList].contains(name)) {
return
}
- let counter = 0
-
- let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain])
+ // 7. Delete name from this’s header list.
+ // 8. If this’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from this.
+ this[kHeadersList].delete(name)
+ }
- while (counter++ < this[kClients].length) {
- this[kIndex] = (this[kIndex] + 1) % this[kClients].length
- const pool = this[kClients][this[kIndex]]
+ // https://fetch.spec.whatwg.org/#dom-headers-get
+ get (name) {
+ webidl.brandCheck(this, Headers)
- // find pool index with the largest weight
- if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) {
- maxWeightIndex = this[kIndex]
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })
- // decrease the current weight every `this[kClients].length`.
- if (this[kIndex] === 0) {
- // Set the current weight to the next lower weight.
- this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]
+ name = webidl.converters.ByteString(name)
- if (this[kCurrentWeight] <= 0) {
- this[kCurrentWeight] = this[kMaxWeightPerServer]
- }
- }
- if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) {
- return pool
- }
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.get',
+ value: name,
+ type: 'header name'
+ })
}
- this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight]
- this[kIndex] = maxWeightIndex
- return this[kClients][maxWeightIndex]
+ // 2. Return the result of getting name from this’s header
+ // list.
+ return this[kHeadersList].get(name)
}
-}
-module.exports = BalancedPool
+ // https://fetch.spec.whatwg.org/#dom-headers-has
+ has (name) {
+ webidl.brandCheck(this, Headers)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })
-/***/ }),
+ name = webidl.converters.ByteString(name)
-/***/ 40611:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 1. If name is not a header name, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.has',
+ value: name,
+ type: 'header name'
+ })
+ }
+ // 2. Return true if this’s header list contains name;
+ // otherwise false.
+ return this[kHeadersList].contains(name)
+ }
+ // https://fetch.spec.whatwg.org/#dom-headers-set
+ set (name, value) {
+ webidl.brandCheck(this, Headers)
-const { kConstruct } = __nccwpck_require__(68652)
-const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(71173)
-const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(89500)
-const { kHeadersList } = __nccwpck_require__(68031)
-const { webidl } = __nccwpck_require__(94354)
-const { Response, cloneResponse } = __nccwpck_require__(89928)
-const { Request } = __nccwpck_require__(2630)
-const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
-const { fetching } = __nccwpck_require__(11503)
-const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(72847)
-const assert = __nccwpck_require__(42613)
-const { getGlobalDispatcher } = __nccwpck_require__(61481)
+ webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })
-/**
- * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation
- * @typedef {Object} CacheBatchOperation
- * @property {'delete' | 'put'} type
- * @property {any} request
- * @property {any} response
- * @property {import('../../types/cache').CacheQueryOptions} options
- */
+ name = webidl.converters.ByteString(name)
+ value = webidl.converters.ByteString(value)
-/**
- * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list
- * @typedef {[any, any][]} requestResponseList
- */
+ // 1. Normalize value.
+ value = headerValueNormalize(value)
-class Cache {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list
- * @type {requestResponseList}
- */
- #relevantRequestResponseList
+ // 2. If name is not a header name or value is not a
+ // header value, then throw a TypeError.
+ if (!isValidHeaderName(name)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.set',
+ value: name,
+ type: 'header name'
+ })
+ } else if (!isValidHeaderValue(value)) {
+ throw webidl.errors.invalidArgument({
+ prefix: 'Headers.set',
+ value,
+ type: 'header value'
+ })
+ }
- constructor () {
- if (arguments[0] !== kConstruct) {
- webidl.illegalConstructor()
+ // 3. If this’s guard is "immutable", then throw a TypeError.
+ // 4. Otherwise, if this’s guard is "request" and name is a
+ // forbidden header name, return.
+ // 5. Otherwise, if this’s guard is "request-no-cors" and
+ // name/value is not a no-CORS-safelisted request-header,
+ // return.
+ // 6. Otherwise, if this’s guard is "response" and name is a
+ // forbidden response-header name, return.
+ // Note: undici does not implement forbidden header names
+ if (this[kGuard] === 'immutable') {
+ throw new TypeError('immutable')
+ } else if (this[kGuard] === 'request-no-cors') {
+ // TODO
}
- this.#relevantRequestResponseList = arguments[1]
+ // 7. Set (name, value) in this’s header list.
+ // 8. If this’s guard is "request-no-cors", then remove
+ // privileged no-CORS request headers from this
+ this[kHeadersList].set(name, value)
}
- async match (request, options = {}) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' })
+ // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
+ getSetCookie () {
+ webidl.brandCheck(this, Headers)
- request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+ // 1. If this’s header list does not contain `Set-Cookie`, then return « ».
+ // 2. Return the values of all headers in this’s header list whose name is
+ // a byte-case-insensitive match for `Set-Cookie`, in order.
- const p = await this.matchAll(request, options)
+ const list = this[kHeadersList].cookies
- if (p.length === 0) {
- return
+ if (list) {
+ return [...list]
}
- return p[0]
+ return []
}
- async matchAll (request = undefined, options = {}) {
- webidl.brandCheck(this, Cache)
+ // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
+ get [kHeadersSortedMap] () {
+ if (this[kHeadersList][kHeadersSortedMap]) {
+ return this[kHeadersList][kHeadersSortedMap]
+ }
- if (request !== undefined) request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+ // 1. Let headers be an empty list of headers with the key being the name
+ // and value the value.
+ const headers = []
- // 1.
- let r = null
+ // 2. Let names be the result of convert header names to a sorted-lowercase
+ // set with all the names of the headers in list.
+ const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)
+ const cookies = this[kHeadersList].cookies
- // 2.
- if (request !== undefined) {
- if (request instanceof Request) {
- // 2.1.1
- r = request[kState]
+ // 3. For each name of names:
+ for (let i = 0; i < names.length; ++i) {
+ const [name, value] = names[i]
+ // 1. If name is `set-cookie`, then:
+ if (name === 'set-cookie') {
+ // 1. Let values be a list of all values of headers in list whose name
+ // is a byte-case-insensitive match for name, in order.
- // 2.1.2
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return []
+ // 2. For each value of values:
+ // 1. Append (name, value) to headers.
+ for (let j = 0; j < cookies.length; ++j) {
+ headers.push([name, cookies[j]])
}
- } else if (typeof request === 'string') {
- // 2.2.1
- r = new Request(request)[kState]
- }
- }
+ } else {
+ // 2. Otherwise:
- // 5.
- // 5.1
- const responses = []
+ // 1. Let value be the result of getting name from list.
- // 5.2
- if (request === undefined) {
- // 5.2.1
- for (const requestResponse of this.#relevantRequestResponseList) {
- responses.push(requestResponse[1])
- }
- } else { // 5.3
- // 5.3.1
- const requestResponses = this.#queryCache(r, options)
+ // 2. Assert: value is non-null.
+ assert(value !== null)
- // 5.3.2
- for (const requestResponse of requestResponses) {
- responses.push(requestResponse[1])
+ // 3. Append (name, value) to headers.
+ headers.push([name, value])
}
}
- // 5.4
- // We don't implement CORs so we don't need to loop over the responses, yay!
+ this[kHeadersList][kHeadersSortedMap] = headers
- // 5.5.1
- const responseList = []
+ // 4. Return headers.
+ return headers
+ }
- // 5.5.2
- for (const response of responses) {
- // 5.5.2.1
- const responseObject = new Response(response.body?.source ?? null)
- const body = responseObject[kState].body
- responseObject[kState] = response
- responseObject[kState].body = body
- responseObject[kHeaders][kHeadersList] = response.headersList
- responseObject[kHeaders][kGuard] = 'immutable'
+ keys () {
+ webidl.brandCheck(this, Headers)
- responseList.push(responseObject)
+ if (this[kGuard] === 'immutable') {
+ const value = this[kHeadersSortedMap]
+ return makeIterator(() => value, 'Headers',
+ 'key')
}
- // 6.
- return Object.freeze(responseList)
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'key'
+ )
}
- async add (request) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' })
-
- request = webidl.converters.RequestInfo(request)
-
- // 1.
- const requests = [request]
+ values () {
+ webidl.brandCheck(this, Headers)
- // 2.
- const responseArrayPromise = this.addAll(requests)
+ if (this[kGuard] === 'immutable') {
+ const value = this[kHeadersSortedMap]
+ return makeIterator(() => value, 'Headers',
+ 'value')
+ }
- // 3.
- return await responseArrayPromise
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'value'
+ )
}
- async addAll (requests) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' })
+ entries () {
+ webidl.brandCheck(this, Headers)
- requests = webidl.converters['sequence'](requests)
+ if (this[kGuard] === 'immutable') {
+ const value = this[kHeadersSortedMap]
+ return makeIterator(() => value, 'Headers',
+ 'key+value')
+ }
- // 1.
- const responsePromises = []
+ return makeIterator(
+ () => [...this[kHeadersSortedMap].values()],
+ 'Headers',
+ 'key+value'
+ )
+ }
- // 2.
- const requestList = []
+ /**
+ * @param {(value: string, key: string, self: Headers) => void} callbackFn
+ * @param {unknown} thisArg
+ */
+ forEach (callbackFn, thisArg = globalThis) {
+ webidl.brandCheck(this, Headers)
- // 3.
- for (const request of requests) {
- if (typeof request === 'string') {
- continue
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })
- // 3.1
- const r = request[kState]
+ if (typeof callbackFn !== 'function') {
+ throw new TypeError(
+ "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
+ )
+ }
- // 3.2
- if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'Expected http/s scheme when method is not GET.'
- })
- }
+ for (const [key, value] of this) {
+ callbackFn.apply(thisArg, [value, key, this])
}
+ }
- // 4.
- /** @type {ReturnType[]} */
- const fetchControllers = []
+ [Symbol.for('nodejs.util.inspect.custom')] () {
+ webidl.brandCheck(this, Headers)
- // 5.
- for (const request of requests) {
- // 5.1
- const r = new Request(request)[kState]
+ return this[kHeadersList]
+ }
+}
- // 5.2
- if (!urlIsHttpHttpsScheme(r.url)) {
- throw webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'Expected http/s scheme.'
- })
- }
+Headers.prototype[Symbol.iterator] = Headers.prototype.entries
- // 5.4
- r.initiator = 'fetch'
- r.destination = 'subresource'
+Object.defineProperties(Headers.prototype, {
+ append: kEnumerableProperty,
+ delete: kEnumerableProperty,
+ get: kEnumerableProperty,
+ has: kEnumerableProperty,
+ set: kEnumerableProperty,
+ getSetCookie: kEnumerableProperty,
+ keys: kEnumerableProperty,
+ values: kEnumerableProperty,
+ entries: kEnumerableProperty,
+ forEach: kEnumerableProperty,
+ [Symbol.iterator]: { enumerable: false },
+ [Symbol.toStringTag]: {
+ value: 'Headers',
+ configurable: true
+ }
+})
- // 5.5
- requestList.push(r)
+webidl.converters.HeadersInit = function (V) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (V[Symbol.iterator]) {
+ return webidl.converters['sequence>'](V)
+ }
- // 5.6
- const responsePromise = createDeferredPromise()
+ return webidl.converters['record'](V)
+ }
- // 5.7
- fetchControllers.push(fetching({
- request: r,
- dispatcher: getGlobalDispatcher(),
- processResponse (response) {
- // 1.
- if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) {
- responsePromise.reject(webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'Received an invalid status code or the request failed.'
- }))
- } else if (response.headersList.contains('vary')) { // 2.
- // 2.1
- const fieldValues = getFieldValues(response.headersList.get('vary'))
+ throw webidl.errors.conversionFailed({
+ prefix: 'Headers constructor',
+ argument: 'Argument 1',
+ types: ['sequence>', 'record']
+ })
+}
- // 2.2
- for (const fieldValue of fieldValues) {
- // 2.2.1
- if (fieldValue === '*') {
- responsePromise.reject(webidl.errors.exception({
- header: 'Cache.addAll',
- message: 'invalid vary field value'
- }))
+module.exports = {
+ fill,
+ Headers,
+ HeadersList
+}
- for (const controller of fetchControllers) {
- controller.abort()
- }
- return
- }
- }
- }
- },
- processResponseEndOfBody (response) {
- // 1.
- if (response.aborted) {
- responsePromise.reject(new DOMException('aborted', 'AbortError'))
- return
- }
+/***/ }),
- // 2.
- responsePromise.resolve(response)
- }
- }))
+/***/ 11503:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 5.8
- responsePromises.push(responsePromise.promise)
- }
+// https://github.com/Ethan-Arrowood/undici-fetch
- // 6.
- const p = Promise.all(responsePromises)
- // 7.
- const responses = await p
- // 7.1
- const operations = []
+const {
+ Response,
+ makeNetworkError,
+ makeAppropriateNetworkError,
+ filterResponse,
+ makeResponse
+} = __nccwpck_require__(89928)
+const { Headers } = __nccwpck_require__(12801)
+const { Request, makeRequest } = __nccwpck_require__(2630)
+const zlib = __nccwpck_require__(43106)
+const {
+ bytesMatch,
+ makePolicyContainer,
+ clonePolicyContainer,
+ requestBadPort,
+ TAOCheck,
+ appendRequestOriginHeader,
+ responseLocationURL,
+ requestCurrentURL,
+ setRequestReferrerPolicyOnRedirect,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ createOpaqueTimingInfo,
+ appendFetchMetadata,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ determineRequestsReferrer,
+ coarsenedSharedCurrentTime,
+ createDeferredPromise,
+ isBlobLike,
+ sameOrigin,
+ isCancelled,
+ isAborted,
+ isErrorLike,
+ fullyReadBody,
+ readableStreamClose,
+ isomorphicEncode,
+ urlIsLocal,
+ urlIsHttpHttpsScheme,
+ urlHasHttpsScheme
+} = __nccwpck_require__(72847)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
+const assert = __nccwpck_require__(42613)
+const { safelyExtractBody } = __nccwpck_require__(37791)
+const {
+ redirectStatusSet,
+ nullBodyStatus,
+ safeMethodsSet,
+ requestBodyHeader,
+ subresourceSet,
+ DOMException
+} = __nccwpck_require__(21234)
+const { kHeadersList } = __nccwpck_require__(68031)
+const EE = __nccwpck_require__(24434)
+const { Readable, pipeline } = __nccwpck_require__(2203)
+const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(89500)
+const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(37246)
+const { TransformStream } = __nccwpck_require__(63774)
+const { getGlobalDispatcher } = __nccwpck_require__(61481)
+const { webidl } = __nccwpck_require__(94354)
+const { STATUS_CODES } = __nccwpck_require__(58611)
+const GET_OR_HEAD = ['GET', 'HEAD']
+
+/** @type {import('buffer').resolveObjectURL} */
+let resolveObjectURL
+let ReadableStream = globalThis.ReadableStream
+
+class Fetch extends EE {
+ constructor (dispatcher) {
+ super()
- // 7.2
- let index = 0
+ this.dispatcher = dispatcher
+ this.connection = null
+ this.dump = false
+ this.state = 'ongoing'
+ // 2 terminated listeners get added per request,
+ // but only 1 gets removed. If there are 20 redirects,
+ // 21 listeners will be added.
+ // See https://github.com/nodejs/undici/issues/1711
+ // TODO (fix): Find and fix root cause for leaked listener.
+ this.setMaxListeners(21)
+ }
- // 7.3
- for (const response of responses) {
- // 7.3.1
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'put', // 7.3.2
- request: requestList[index], // 7.3.3
- response // 7.3.4
- }
+ terminate (reason) {
+ if (this.state !== 'ongoing') {
+ return
+ }
- operations.push(operation) // 7.3.5
+ this.state = 'terminated'
+ this.connection?.destroy(reason)
+ this.emit('terminated', reason)
+ }
- index++ // 7.3.6
+ // https://fetch.spec.whatwg.org/#fetch-controller-abort
+ abort (error) {
+ if (this.state !== 'ongoing') {
+ return
}
- // 7.5
- const cacheJobPromise = createDeferredPromise()
-
- // 7.6.1
- let errorData = null
+ // 1. Set controller’s state to "aborted".
+ this.state = 'aborted'
- // 7.6.2
- try {
- this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
+ // 2. Let fallbackError be an "AbortError" DOMException.
+ // 3. Set error to fallbackError if it is not given.
+ if (!error) {
+ error = new DOMException('The operation was aborted.', 'AbortError')
}
- // 7.6.3
- queueMicrotask(() => {
- // 7.6.3.1
- if (errorData === null) {
- cacheJobPromise.resolve(undefined)
- } else {
- // 7.6.3.2
- cacheJobPromise.reject(errorData)
- }
- })
+ // 4. Let serializedError be StructuredSerialize(error).
+ // If that threw an exception, catch it, and let
+ // serializedError be StructuredSerialize(fallbackError).
- // 7.7
- return cacheJobPromise.promise
+ // 5. Set controller’s serialized abort reason to serializedError.
+ this.serializedAbortReason = error
+
+ this.connection?.destroy(error)
+ this.emit('terminated', error)
}
+}
- async put (request, response) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' })
+// https://fetch.spec.whatwg.org/#fetch-method
+function fetch (input, init = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
- request = webidl.converters.RequestInfo(request)
- response = webidl.converters.Response(response)
+ // 1. Let p be a new promise.
+ const p = createDeferredPromise()
- // 1.
- let innerRequest = null
+ // 2. Let requestObject be the result of invoking the initial value of
+ // Request as constructor with input and init as arguments. If this throws
+ // an exception, reject p with it and return p.
+ let requestObject
- // 2.
- if (request instanceof Request) {
- innerRequest = request[kState]
- } else { // 3.
- innerRequest = new Request(request)[kState]
- }
+ try {
+ requestObject = new Request(input, init)
+ } catch (e) {
+ p.reject(e)
+ return p.promise
+ }
- // 4.
- if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Expected an http/s scheme when method is not GET'
- })
- }
+ // 3. Let request be requestObject’s request.
+ const request = requestObject[kState]
- // 5.
- const innerResponse = response[kState]
+ // 4. If requestObject’s signal’s aborted flag is set, then:
+ if (requestObject.signal.aborted) {
+ // 1. Abort the fetch() call with p, request, null, and
+ // requestObject’s signal’s abort reason.
+ abortFetch(p, request, null, requestObject.signal.reason)
- // 6.
- if (innerResponse.status === 206) {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Got 206 status'
- })
- }
+ // 2. Return p.
+ return p.promise
+ }
- // 7.
- if (innerResponse.headersList.contains('vary')) {
- // 7.1.
- const fieldValues = getFieldValues(innerResponse.headersList.get('vary'))
+ // 5. Let globalObject be request’s client’s global object.
+ const globalObject = request.client.globalObject
- // 7.2.
- for (const fieldValue of fieldValues) {
- // 7.2.1
- if (fieldValue === '*') {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Got * vary field value'
- })
- }
- }
- }
+ // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
+ // request’s service-workers mode to "none".
+ if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
+ request.serviceWorkers = 'none'
+ }
- // 8.
- if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) {
- throw webidl.errors.exception({
- header: 'Cache.put',
- message: 'Response body is locked or disturbed'
- })
- }
+ // 7. Let responseObject be null.
+ let responseObject = null
- // 9.
- const clonedResponse = cloneResponse(innerResponse)
+ // 8. Let relevantRealm be this’s relevant Realm.
+ const relevantRealm = null
- // 10.
- const bodyReadPromise = createDeferredPromise()
+ // 9. Let locallyAborted be false.
+ let locallyAborted = false
- // 11.
- if (innerResponse.body != null) {
- // 11.1
- const stream = innerResponse.body.stream
+ // 10. Let controller be null.
+ let controller = null
- // 11.2
- const reader = stream.getReader()
+ // 11. Add the following abort steps to requestObject’s signal:
+ addAbortListener(
+ requestObject.signal,
+ () => {
+ // 1. Set locallyAborted to true.
+ locallyAborted = true
- // 11.3
- readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject)
- } else {
- bodyReadPromise.resolve(undefined)
- }
+ // 2. Assert: controller is non-null.
+ assert(controller != null)
- // 12.
- /** @type {CacheBatchOperation[]} */
- const operations = []
+ // 3. Abort controller with requestObject’s signal’s abort reason.
+ controller.abort(requestObject.signal.reason)
- // 13.
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'put', // 14.
- request: innerRequest, // 15.
- response: clonedResponse // 16.
+ // 4. Abort the fetch() call with p, request, responseObject,
+ // and requestObject’s signal’s abort reason.
+ abortFetch(p, request, responseObject, requestObject.signal.reason)
}
+ )
- // 17.
- operations.push(operation)
+ // 12. Let handleFetchDone given response response be to finalize and
+ // report timing with response, globalObject, and "fetch".
+ const handleFetchDone = (response) =>
+ finalizeAndReportTiming(response, 'fetch')
- // 19.
- const bytes = await bodyReadPromise.promise
+ // 13. Set controller to the result of calling fetch given request,
+ // with processResponseEndOfBody set to handleFetchDone, and processResponse
+ // given response being these substeps:
- if (clonedResponse.body != null) {
- clonedResponse.body.source = bytes
+ const processResponse = (response) => {
+ // 1. If locallyAborted is true, terminate these substeps.
+ if (locallyAborted) {
+ return Promise.resolve()
}
- // 19.1
- const cacheJobPromise = createDeferredPromise()
+ // 2. If response’s aborted flag is set, then:
+ if (response.aborted) {
+ // 1. Let deserializedError be the result of deserialize a serialized
+ // abort reason given controller’s serialized abort reason and
+ // relevantRealm.
- // 19.2.1
- let errorData = null
+ // 2. Abort the fetch() call with p, request, responseObject, and
+ // deserializedError.
- // 19.2.2
- try {
- this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
+ abortFetch(p, request, responseObject, controller.serializedAbortReason)
+ return Promise.resolve()
}
- // 19.2.3
- queueMicrotask(() => {
- // 19.2.3.1
- if (errorData === null) {
- cacheJobPromise.resolve()
- } else { // 19.2.3.2
- cacheJobPromise.reject(errorData)
- }
- })
-
- return cacheJobPromise.promise
- }
-
- async delete (request, options = {}) {
- webidl.brandCheck(this, Cache)
- webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' })
+ // 3. If response is a network error, then reject p with a TypeError
+ // and terminate these substeps.
+ if (response.type === 'error') {
+ p.reject(
+ Object.assign(new TypeError('fetch failed'), { cause: response.error })
+ )
+ return Promise.resolve()
+ }
- request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
+ // 4. Set responseObject to the result of creating a Response object,
+ // given response, "immutable", and relevantRealm.
+ responseObject = new Response()
+ responseObject[kState] = response
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kHeadersList] = response.headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
- /**
- * @type {Request}
- */
- let r = null
+ // 5. Resolve p with responseObject.
+ p.resolve(responseObject)
+ }
- if (request instanceof Request) {
- r = request[kState]
+ controller = fetching({
+ request,
+ processResponseEndOfBody: handleFetchDone,
+ processResponse,
+ dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
+ })
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return false
- }
- } else {
- assert(typeof request === 'string')
+ // 14. Return p.
+ return p.promise
+}
- r = new Request(request)[kState]
- }
+// https://fetch.spec.whatwg.org/#finalize-and-report-timing
+function finalizeAndReportTiming (response, initiatorType = 'other') {
+ // 1. If response is an aborted network error, then return.
+ if (response.type === 'error' && response.aborted) {
+ return
+ }
- /** @type {CacheBatchOperation[]} */
- const operations = []
+ // 2. If response’s URL list is null or empty, then return.
+ if (!response.urlList?.length) {
+ return
+ }
- /** @type {CacheBatchOperation} */
- const operation = {
- type: 'delete',
- request: r,
- options
- }
+ // 3. Let originalURL be response’s URL list[0].
+ const originalURL = response.urlList[0]
- operations.push(operation)
+ // 4. Let timingInfo be response’s timing info.
+ let timingInfo = response.timingInfo
- const cacheJobPromise = createDeferredPromise()
+ // 5. Let cacheState be response’s cache state.
+ let cacheState = response.cacheState
- let errorData = null
- let requestResponses
+ // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
+ if (!urlIsHttpHttpsScheme(originalURL)) {
+ return
+ }
- try {
- requestResponses = this.#batchCacheOperations(operations)
- } catch (e) {
- errorData = e
- }
+ // 7. If timingInfo is null, then return.
+ if (timingInfo === null) {
+ return
+ }
- queueMicrotask(() => {
- if (errorData === null) {
- cacheJobPromise.resolve(!!requestResponses?.length)
- } else {
- cacheJobPromise.reject(errorData)
- }
+ // 8. If response’s timing allow passed flag is not set, then:
+ if (!response.timingAllowPassed) {
+ // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
+ timingInfo = createOpaqueTimingInfo({
+ startTime: timingInfo.startTime
})
- return cacheJobPromise.promise
+ // 2. Set cacheState to the empty string.
+ cacheState = ''
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys
- * @param {any} request
- * @param {import('../../types/cache').CacheQueryOptions} options
- * @returns {readonly Request[]}
- */
- async keys (request = undefined, options = {}) {
- webidl.brandCheck(this, Cache)
-
- if (request !== undefined) request = webidl.converters.RequestInfo(request)
- options = webidl.converters.CacheQueryOptions(options)
-
- // 1.
- let r = null
+ // 9. Set timingInfo’s end time to the coarsened shared current time
+ // given global’s relevant settings object’s cross-origin isolated
+ // capability.
+ // TODO: given global’s relevant settings object’s cross-origin isolated
+ // capability?
+ timingInfo.endTime = coarsenedSharedCurrentTime()
- // 2.
- if (request !== undefined) {
- // 2.1
- if (request instanceof Request) {
- // 2.1.1
- r = request[kState]
+ // 10. Set response’s timing info to timingInfo.
+ response.timingInfo = timingInfo
- // 2.1.2
- if (r.method !== 'GET' && !options.ignoreMethod) {
- return []
- }
- } else if (typeof request === 'string') { // 2.2
- r = new Request(request)[kState]
- }
- }
+ // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
+ // global, and cacheState.
+ markResourceTiming(
+ timingInfo,
+ originalURL,
+ initiatorType,
+ globalThis,
+ cacheState
+ )
+}
- // 4.
- const promise = createDeferredPromise()
+// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
+function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {
+ if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {
+ performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)
+ }
+}
- // 5.
- // 5.1
- const requests = []
+// https://fetch.spec.whatwg.org/#abort-fetch
+function abortFetch (p, request, responseObject, error) {
+ // Note: AbortSignal.reason was added in node v17.2.0
+ // which would give us an undefined error to reject with.
+ // Remove this once node v16 is no longer supported.
+ if (!error) {
+ error = new DOMException('The operation was aborted.', 'AbortError')
+ }
- // 5.2
- if (request === undefined) {
- // 5.2.1
- for (const requestResponse of this.#relevantRequestResponseList) {
- // 5.2.1.1
- requests.push(requestResponse[0])
- }
- } else { // 5.3
- // 5.3.1
- const requestResponses = this.#queryCache(r, options)
+ // 1. Reject promise with error.
+ p.reject(error)
- // 5.3.2
- for (const requestResponse of requestResponses) {
- // 5.3.2.1
- requests.push(requestResponse[0])
+ // 2. If request’s body is not null and is readable, then cancel request’s
+ // body with error.
+ if (request.body != null && isReadable(request.body?.stream)) {
+ request.body.stream.cancel(error).catch((err) => {
+ if (err.code === 'ERR_INVALID_STATE') {
+ // Node bug?
+ return
}
- }
+ throw err
+ })
+ }
- // 5.4
- queueMicrotask(() => {
- // 5.4.1
- const requestList = []
+ // 3. If responseObject is null, then return.
+ if (responseObject == null) {
+ return
+ }
- // 5.4.2
- for (const request of requests) {
- const requestObject = new Request('https://a')
- requestObject[kState] = request
- requestObject[kHeaders][kHeadersList] = request.headersList
- requestObject[kHeaders][kGuard] = 'immutable'
- requestObject[kRealm] = request.client
+ // 4. Let response be responseObject’s response.
+ const response = responseObject[kState]
- // 5.4.2.1
- requestList.push(requestObject)
+ // 5. If response’s body is not null and is readable, then error response’s
+ // body with error.
+ if (response.body != null && isReadable(response.body?.stream)) {
+ response.body.stream.cancel(error).catch((err) => {
+ if (err.code === 'ERR_INVALID_STATE') {
+ // Node bug?
+ return
}
-
- // 5.4.3
- promise.resolve(Object.freeze(requestList))
+ throw err
})
-
- return promise.promise
}
+}
- /**
- * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm
- * @param {CacheBatchOperation[]} operations
- * @returns {requestResponseList}
- */
- #batchCacheOperations (operations) {
- // 1.
- const cache = this.#relevantRequestResponseList
-
- // 2.
- const backupCache = [...cache]
-
- // 3.
- const addedItems = []
+// https://fetch.spec.whatwg.org/#fetching
+function fetching ({
+ request,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseEndOfBody,
+ processResponseConsumeBody,
+ useParallelQueue = false,
+ dispatcher // undici
+}) {
+ // 1. Let taskDestination be null.
+ let taskDestination = null
- // 4.1
- const resultList = []
+ // 2. Let crossOriginIsolatedCapability be false.
+ let crossOriginIsolatedCapability = false
- try {
- // 4.2
- for (const operation of operations) {
- // 4.2.1
- if (operation.type !== 'delete' && operation.type !== 'put') {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'operation type does not match "delete" or "put"'
- })
- }
+ // 3. If request’s client is non-null, then:
+ if (request.client != null) {
+ // 1. Set taskDestination to request’s client’s global object.
+ taskDestination = request.client.globalObject
- // 4.2.2
- if (operation.type === 'delete' && operation.response != null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'delete operation should not have an associated response'
- })
- }
+ // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
+ // isolated capability.
+ crossOriginIsolatedCapability =
+ request.client.crossOriginIsolatedCapability
+ }
- // 4.2.3
- if (this.#queryCache(operation.request, operation.options, addedItems).length) {
- throw new DOMException('???', 'InvalidStateError')
- }
+ // 4. If useParallelQueue is true, then set taskDestination to the result of
+ // starting a new parallel queue.
+ // TODO
- // 4.2.4
- let requestResponses
+ // 5. Let timingInfo be a new fetch timing info whose start time and
+ // post-redirect start time are the coarsened shared current time given
+ // crossOriginIsolatedCapability.
+ const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
+ const timingInfo = createOpaqueTimingInfo({
+ startTime: currenTime
+ })
- // 4.2.5
- if (operation.type === 'delete') {
- // 4.2.5.1
- requestResponses = this.#queryCache(operation.request, operation.options)
+ // 6. Let fetchParams be a new fetch params whose
+ // request is request,
+ // timing info is timingInfo,
+ // process request body chunk length is processRequestBodyChunkLength,
+ // process request end-of-body is processRequestEndOfBody,
+ // process response is processResponse,
+ // process response consume body is processResponseConsumeBody,
+ // process response end-of-body is processResponseEndOfBody,
+ // task destination is taskDestination,
+ // and cross-origin isolated capability is crossOriginIsolatedCapability.
+ const fetchParams = {
+ controller: new Fetch(dispatcher),
+ request,
+ timingInfo,
+ processRequestBodyChunkLength,
+ processRequestEndOfBody,
+ processResponse,
+ processResponseConsumeBody,
+ processResponseEndOfBody,
+ taskDestination,
+ crossOriginIsolatedCapability
+ }
- // TODO: the spec is wrong, this is needed to pass WPTs
- if (requestResponses.length === 0) {
- return []
- }
+ // 7. If request’s body is a byte sequence, then set request’s body to
+ // request’s body as a body.
+ // NOTE: Since fetching is only called from fetch, body should already be
+ // extracted.
+ assert(!request.body || request.body.stream)
- // 4.2.5.2
- for (const requestResponse of requestResponses) {
- const idx = cache.indexOf(requestResponse)
- assert(idx !== -1)
+ // 8. If request’s window is "client", then set request’s window to request’s
+ // client, if request’s client’s global object is a Window object; otherwise
+ // "no-window".
+ if (request.window === 'client') {
+ // TODO: What if request.client is null?
+ request.window =
+ request.client?.globalObject?.constructor?.name === 'Window'
+ ? request.client
+ : 'no-window'
+ }
- // 4.2.5.2.1
- cache.splice(idx, 1)
- }
- } else if (operation.type === 'put') { // 4.2.6
- // 4.2.6.1
- if (operation.response == null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'put operation should have an associated response'
- })
- }
+ // 9. If request’s origin is "client", then set request’s origin to request’s
+ // client’s origin.
+ if (request.origin === 'client') {
+ // TODO: What if request.client is null?
+ request.origin = request.client?.origin
+ }
- // 4.2.6.2
- const r = operation.request
+ // 10. If all of the following conditions are true:
+ // TODO
- // 4.2.6.3
- if (!urlIsHttpHttpsScheme(r.url)) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'expected http or https scheme'
- })
- }
+ // 11. If request’s policy container is "client", then:
+ if (request.policyContainer === 'client') {
+ // 1. If request’s client is non-null, then set request’s policy
+ // container to a clone of request’s client’s policy container. [HTML]
+ if (request.client != null) {
+ request.policyContainer = clonePolicyContainer(
+ request.client.policyContainer
+ )
+ } else {
+ // 2. Otherwise, set request’s policy container to a new policy
+ // container.
+ request.policyContainer = makePolicyContainer()
+ }
+ }
- // 4.2.6.4
- if (r.method !== 'GET') {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'not get method'
- })
- }
+ // 12. If request’s header list does not contain `Accept`, then:
+ if (!request.headersList.contains('accept')) {
+ // 1. Let value be `*/*`.
+ const value = '*/*'
- // 4.2.6.5
- if (operation.options != null) {
- throw webidl.errors.exception({
- header: 'Cache.#batchCacheOperations',
- message: 'options must not be defined'
- })
- }
+ // 2. A user agent should set value to the first matching statement, if
+ // any, switching on request’s destination:
+ // "document"
+ // "frame"
+ // "iframe"
+ // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
+ // "image"
+ // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
+ // "style"
+ // `text/css,*/*;q=0.1`
+ // TODO
- // 4.2.6.6
- requestResponses = this.#queryCache(operation.request)
+ // 3. Append `Accept`/value to request’s header list.
+ request.headersList.append('accept', value)
+ }
- // 4.2.6.7
- for (const requestResponse of requestResponses) {
- const idx = cache.indexOf(requestResponse)
- assert(idx !== -1)
+ // 13. If request’s header list does not contain `Accept-Language`, then
+ // user agents should append `Accept-Language`/an appropriate value to
+ // request’s header list.
+ if (!request.headersList.contains('accept-language')) {
+ request.headersList.append('accept-language', '*')
+ }
- // 4.2.6.7.1
- cache.splice(idx, 1)
- }
+ // 14. If request’s priority is null, then use request’s initiator and
+ // destination appropriately in setting request’s priority to a
+ // user-agent-defined object.
+ if (request.priority === null) {
+ // TODO
+ }
- // 4.2.6.8
- cache.push([operation.request, operation.response])
+ // 15. If request is a subresource request, then:
+ if (subresourceSet.has(request.destination)) {
+ // TODO
+ }
- // 4.2.6.10
- addedItems.push([operation.request, operation.response])
- }
+ // 16. Run main fetch given fetchParams.
+ mainFetch(fetchParams)
+ .catch(err => {
+ fetchParams.controller.terminate(err)
+ })
- // 4.2.7
- resultList.push([operation.request, operation.response])
- }
+ // 17. Return fetchParam's controller
+ return fetchParams.controller
+}
- // 4.3
- return resultList
- } catch (e) { // 5.
- // 5.1
- this.#relevantRequestResponseList.length = 0
+// https://fetch.spec.whatwg.org/#concept-main-fetch
+async function mainFetch (fetchParams, recursive = false) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- // 5.2
- this.#relevantRequestResponseList = backupCache
+ // 2. Let response be null.
+ let response = null
- // 5.3
- throw e
- }
+ // 3. If request’s local-URLs-only flag is set and request’s current URL is
+ // not local, then set response to a network error.
+ if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
+ response = makeNetworkError('local URLs only')
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#query-cache
- * @param {any} requestQuery
- * @param {import('../../types/cache').CacheQueryOptions} options
- * @param {requestResponseList} targetStorage
- * @returns {requestResponseList}
- */
- #queryCache (requestQuery, options, targetStorage) {
- /** @type {requestResponseList} */
- const resultList = []
+ // 4. Run report Content Security Policy violations for request.
+ // TODO
- const storage = targetStorage ?? this.#relevantRequestResponseList
+ // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
+ tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
- for (const requestResponse of storage) {
- const [cachedRequest, cachedResponse] = requestResponse
- if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) {
- resultList.push(requestResponse)
- }
- }
+ // 6. If should request be blocked due to a bad port, should fetching request
+ // be blocked as mixed content, or should request be blocked by Content
+ // Security Policy returns blocked, then set response to a network error.
+ if (requestBadPort(request) === 'blocked') {
+ response = makeNetworkError('bad port')
+ }
+ // TODO: should fetching request be blocked as mixed content?
+ // TODO: should request be blocked by Content Security Policy?
- return resultList
+ // 7. If request’s referrer policy is the empty string, then set request’s
+ // referrer policy to request’s policy container’s referrer policy.
+ if (request.referrerPolicy === '') {
+ request.referrerPolicy = request.policyContainer.referrerPolicy
}
- /**
- * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm
- * @param {any} requestQuery
- * @param {any} request
- * @param {any | null} response
- * @param {import('../../types/cache').CacheQueryOptions | undefined} options
- * @returns {boolean}
- */
- #requestMatchesCachedItem (requestQuery, request, response = null, options) {
- // if (options?.ignoreMethod === false && request.method === 'GET') {
- // return false
- // }
+ // 8. If request’s referrer is not "no-referrer", then set request’s
+ // referrer to the result of invoking determine request’s referrer.
+ if (request.referrer !== 'no-referrer') {
+ request.referrer = determineRequestsReferrer(request)
+ }
- const queryURL = new URL(requestQuery.url)
+ // 9. Set request’s current URL’s scheme to "https" if all of the following
+ // conditions are true:
+ // - request’s current URL’s scheme is "http"
+ // - request’s current URL’s host is a domain
+ // - Matching request’s current URL’s host per Known HSTS Host Domain Name
+ // Matching results in either a superdomain match with an asserted
+ // includeSubDomains directive or a congruent match (with or without an
+ // asserted includeSubDomains directive). [HSTS]
+ // TODO
- const cachedURL = new URL(request.url)
+ // 10. If recursive is false, then run the remaining steps in parallel.
+ // TODO
- if (options?.ignoreSearch) {
- cachedURL.search = ''
+ // 11. If response is null, then set response to the result of running
+ // the steps corresponding to the first matching statement:
+ if (response === null) {
+ response = await (async () => {
+ const currentURL = requestCurrentURL(request)
- queryURL.search = ''
- }
+ if (
+ // - request’s current URL’s origin is same origin with request’s origin,
+ // and request’s response tainting is "basic"
+ (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
+ // request’s current URL’s scheme is "data"
+ (currentURL.protocol === 'data:') ||
+ // - request’s mode is "navigate" or "websocket"
+ (request.mode === 'navigate' || request.mode === 'websocket')
+ ) {
+ // 1. Set request’s response tainting to "basic".
+ request.responseTainting = 'basic'
- if (!urlEquals(queryURL, cachedURL, true)) {
- return false
- }
+ // 2. Return the result of running scheme fetch given fetchParams.
+ return await schemeFetch(fetchParams)
+ }
- if (
- response == null ||
- options?.ignoreVary ||
- !response.headersList.contains('vary')
- ) {
- return true
- }
+ // request’s mode is "same-origin"
+ if (request.mode === 'same-origin') {
+ // 1. Return a network error.
+ return makeNetworkError('request mode cannot be "same-origin"')
+ }
- const fieldValues = getFieldValues(response.headersList.get('vary'))
+ // request’s mode is "no-cors"
+ if (request.mode === 'no-cors') {
+ // 1. If request’s redirect mode is not "follow", then return a network
+ // error.
+ if (request.redirect !== 'follow') {
+ return makeNetworkError(
+ 'redirect mode cannot be "follow" for "no-cors" request'
+ )
+ }
- for (const fieldValue of fieldValues) {
- if (fieldValue === '*') {
- return false
- }
+ // 2. Set request’s response tainting to "opaque".
+ request.responseTainting = 'opaque'
- const requestValue = request.headersList.get(fieldValue)
- const queryValue = requestQuery.headersList.get(fieldValue)
+ // 3. Return the result of running scheme fetch given fetchParams.
+ return await schemeFetch(fetchParams)
+ }
- // If one has the header and the other doesn't, or one has
- // a different value than the other, return false
- if (requestValue !== queryValue) {
- return false
+ // request’s current URL’s scheme is not an HTTP(S) scheme
+ if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
+ // Return a network error.
+ return makeNetworkError('URL scheme must be a HTTP(S) scheme')
}
- }
- return true
- }
-}
+ // - request’s use-CORS-preflight flag is set
+ // - request’s unsafe-request flag is set and either request’s method is
+ // not a CORS-safelisted method or CORS-unsafe request-header names with
+ // request’s header list is not empty
+ // 1. Set request’s response tainting to "cors".
+ // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
+ // given fetchParams and true.
+ // 3. If corsWithPreflightResponse is a network error, then clear cache
+ // entries using request.
+ // 4. Return corsWithPreflightResponse.
+ // TODO
-Object.defineProperties(Cache.prototype, {
- [Symbol.toStringTag]: {
- value: 'Cache',
- configurable: true
- },
- match: kEnumerableProperty,
- matchAll: kEnumerableProperty,
- add: kEnumerableProperty,
- addAll: kEnumerableProperty,
- put: kEnumerableProperty,
- delete: kEnumerableProperty,
- keys: kEnumerableProperty
-})
+ // Otherwise
+ // 1. Set request’s response tainting to "cors".
+ request.responseTainting = 'cors'
-const cacheQueryOptionConverters = [
- {
- key: 'ignoreSearch',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'ignoreMethod',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'ignoreVary',
- converter: webidl.converters.boolean,
- defaultValue: false
+ // 2. Return the result of running HTTP fetch given fetchParams.
+ return await httpFetch(fetchParams)
+ })()
}
-]
-
-webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters)
-webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([
- ...cacheQueryOptionConverters,
- {
- key: 'cacheName',
- converter: webidl.converters.DOMString
+ // 12. If recursive is true, then return response.
+ if (recursive) {
+ return response
}
-])
-
-webidl.converters.Response = webidl.interfaceConverter(Response)
-
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.RequestInfo
-)
-
-module.exports = {
- Cache
-}
-
-/***/ }),
+ // 13. If response is not a network error and response is not a filtered
+ // response, then:
+ if (response.status !== 0 && !response.internalResponse) {
+ // If request’s response tainting is "cors", then:
+ if (request.responseTainting === 'cors') {
+ // 1. Let headerNames be the result of extracting header list values
+ // given `Access-Control-Expose-Headers` and response’s header list.
+ // TODO
+ // 2. If request’s credentials mode is not "include" and headerNames
+ // contains `*`, then set response’s CORS-exposed header-name list to
+ // all unique header names in response’s header list.
+ // TODO
+ // 3. Otherwise, if headerNames is not null or failure, then set
+ // response’s CORS-exposed header-name list to headerNames.
+ // TODO
+ }
-/***/ 66446:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // Set response to the following filtered response with response as its
+ // internal response, depending on request’s response tainting:
+ if (request.responseTainting === 'basic') {
+ response = filterResponse(response, 'basic')
+ } else if (request.responseTainting === 'cors') {
+ response = filterResponse(response, 'cors')
+ } else if (request.responseTainting === 'opaque') {
+ response = filterResponse(response, 'opaque')
+ } else {
+ assert(false)
+ }
+ }
+ // 14. Let internalResponse be response, if response is a network error,
+ // and response’s internal response otherwise.
+ let internalResponse =
+ response.status === 0 ? response : response.internalResponse
+ // 15. If internalResponse’s URL list is empty, then set it to a clone of
+ // request’s URL list.
+ if (internalResponse.urlList.length === 0) {
+ internalResponse.urlList.push(...request.urlList)
+ }
-const { kConstruct } = __nccwpck_require__(68652)
-const { Cache } = __nccwpck_require__(40611)
-const { webidl } = __nccwpck_require__(94354)
-const { kEnumerableProperty } = __nccwpck_require__(89500)
+ // 16. If request’s timing allow failed flag is unset, then set
+ // internalResponse’s timing allow passed flag.
+ if (!request.timingAllowFailed) {
+ response.timingAllowPassed = true
+ }
-class CacheStorage {
- /**
- * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map
- * @type {Map
+ fetchFinale(fetchParams, makeNetworkError(reason))
- // 1.
- if (options.cacheName != null) {
- // 1.1.1.1
- if (this.#caches.has(options.cacheName)) {
- // 1.1.1.1.1
- const cacheList = this.#caches.get(options.cacheName)
- const cache = new Cache(kConstruct, cacheList)
+ // 2. If request’s response tainting is "opaque", or response’s body is null,
+ // then run processBodyError and abort these steps.
+ if (request.responseTainting === 'opaque' || response.body == null) {
+ processBodyError(response.error)
+ return
+ }
- return await cache.match(request, options)
+ // 3. Let processBody given bytes be these steps:
+ const processBody = (bytes) => {
+ // 1. If bytes do not match request’s integrity metadata,
+ // then run processBodyError and abort these steps. [SRI]
+ if (!bytesMatch(bytes, request.integrity)) {
+ processBodyError('integrity mismatch')
+ return
}
- } else { // 2.
- // 2.2
- for (const cacheList of this.#caches.values()) {
- const cache = new Cache(kConstruct, cacheList)
- // 2.2.1.2
- const response = await cache.match(request, options)
+ // 2. Set response’s body to bytes as a body.
+ response.body = safelyExtractBody(bytes)[0]
- if (response !== undefined) {
- return response
- }
- }
+ // 3. Run fetch finale given fetchParams and response.
+ fetchFinale(fetchParams, response)
}
- }
-
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-has
- * @param {string} cacheName
- * @returns {Promise}
- */
- async has (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' })
-
- cacheName = webidl.converters.DOMString(cacheName)
- // 2.1.1
- // 2.2
- return this.#caches.has(cacheName)
+ // 4. Fully read response’s body given processBody and processBodyError.
+ await fullyReadBody(response.body, processBody, processBodyError)
+ } else {
+ // 21. Otherwise, run fetch finale given fetchParams and response.
+ fetchFinale(fetchParams, response)
}
+}
- /**
- * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open
- * @param {string} cacheName
- * @returns {Promise}
- */
- async open (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' })
+// https://fetch.spec.whatwg.org/#concept-scheme-fetch
+// given a fetch params fetchParams
+function schemeFetch (fetchParams) {
+ // Note: since the connection is destroyed on redirect, which sets fetchParams to a
+ // cancelled state, we do not want this condition to trigger *unless* there have been
+ // no redirects. See https://github.com/nodejs/undici/issues/1776
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
+ return Promise.resolve(makeAppropriateNetworkError(fetchParams))
+ }
- cacheName = webidl.converters.DOMString(cacheName)
+ // 2. Let request be fetchParams’s request.
+ const { request } = fetchParams
- // 2.1
- if (this.#caches.has(cacheName)) {
- // await caches.open('v1') !== await caches.open('v1')
+ const { protocol: scheme } = requestCurrentURL(request)
- // 2.1.1
- const cache = this.#caches.get(cacheName)
+ // 3. Switch on request’s current URL’s scheme and run the associated steps:
+ switch (scheme) {
+ case 'about:': {
+ // If request’s current URL’s path is the string "blank", then return a new response
+ // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
+ // and body is the empty byte sequence as a body.
- // 2.1.1.1
- return new Cache(kConstruct, cache)
+ // Otherwise, return a network error.
+ return Promise.resolve(makeNetworkError('about scheme is not supported'))
}
+ case 'blob:': {
+ if (!resolveObjectURL) {
+ resolveObjectURL = (__nccwpck_require__(20181).resolveObjectURL)
+ }
- // 2.2
- const cache = []
+ // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
+ const blobURLEntry = requestCurrentURL(request)
- // 2.3
- this.#caches.set(cacheName, cache)
+ // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
+ // Buffer.resolveObjectURL does not ignore URL queries.
+ if (blobURLEntry.search.length !== 0) {
+ return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
+ }
- // 2.4
- return new Cache(kConstruct, cache)
- }
+ const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete
- * @param {string} cacheName
- * @returns {Promise}
- */
- async delete (cacheName) {
- webidl.brandCheck(this, CacheStorage)
- webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' })
+ // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
+ // object is not a Blob object, then return a network error.
+ if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {
+ return Promise.resolve(makeNetworkError('invalid method'))
+ }
- cacheName = webidl.converters.DOMString(cacheName)
+ // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.
+ const bodyWithType = safelyExtractBody(blobURLEntryObject)
- return this.#caches.delete(cacheName)
- }
+ // 4. Let body be bodyWithType’s body.
+ const body = bodyWithType[0]
- /**
- * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys
- * @returns {string[]}
- */
- async keys () {
- webidl.brandCheck(this, CacheStorage)
+ // 5. Let length be body’s length, serialized and isomorphic encoded.
+ const length = isomorphicEncode(`${body.length}`)
- // 2.1
- const keys = this.#caches.keys()
+ // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.
+ const type = bodyWithType[1] ?? ''
- // 2.2
- return [...keys]
- }
-}
+ // 7. Return a new response whose status message is `OK`, header list is
+ // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.
+ const response = makeResponse({
+ statusText: 'OK',
+ headersList: [
+ ['content-length', { name: 'Content-Length', value: length }],
+ ['content-type', { name: 'Content-Type', value: type }]
+ ]
+ })
-Object.defineProperties(CacheStorage.prototype, {
- [Symbol.toStringTag]: {
- value: 'CacheStorage',
- configurable: true
- },
- match: kEnumerableProperty,
- has: kEnumerableProperty,
- open: kEnumerableProperty,
- delete: kEnumerableProperty,
- keys: kEnumerableProperty
-})
+ response.body = body
-module.exports = {
- CacheStorage
-}
+ return Promise.resolve(response)
+ }
+ case 'data:': {
+ // 1. Let dataURLStruct be the result of running the
+ // data: URL processor on request’s current URL.
+ const currentURL = requestCurrentURL(request)
+ const dataURLStruct = dataURLProcessor(currentURL)
+ // 2. If dataURLStruct is failure, then return a
+ // network error.
+ if (dataURLStruct === 'failure') {
+ return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
+ }
-/***/ }),
+ // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
+ const mimeType = serializeAMimeType(dataURLStruct.mimeType)
-/***/ 68652:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 4. Return a response whose status message is `OK`,
+ // header list is « (`Content-Type`, mimeType) »,
+ // and body is dataURLStruct’s body as a body.
+ return Promise.resolve(makeResponse({
+ statusText: 'OK',
+ headersList: [
+ ['content-type', { name: 'Content-Type', value: mimeType }]
+ ],
+ body: safelyExtractBody(dataURLStruct.body)[0]
+ }))
+ }
+ case 'file:': {
+ // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
+ // When in doubt, return a network error.
+ return Promise.resolve(makeNetworkError('not implemented... yet...'))
+ }
+ case 'http:':
+ case 'https:': {
+ // Return the result of running HTTP fetch given fetchParams.
+ return httpFetch(fetchParams)
+ .catch((err) => makeNetworkError(err))
+ }
+ default: {
+ return Promise.resolve(makeNetworkError('unknown scheme'))
+ }
+ }
+}
+// https://fetch.spec.whatwg.org/#finalize-response
+function finalizeResponse (fetchParams, response) {
+ // 1. Set fetchParams’s request’s done flag.
+ fetchParams.request.done = true
-module.exports = {
- kConstruct: (__nccwpck_require__(68031).kConstruct)
+ // 2, If fetchParams’s process response done is not null, then queue a fetch
+ // task to run fetchParams’s process response done given response, with
+ // fetchParams’s task destination.
+ if (fetchParams.processResponseDone != null) {
+ queueMicrotask(() => fetchParams.processResponseDone(response))
+ }
}
+// https://fetch.spec.whatwg.org/#fetch-finale
+function fetchFinale (fetchParams, response) {
+ // 1. If response is a network error, then:
+ if (response.type === 'error') {
+ // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».
+ response.urlList = [fetchParams.request.urlList[0]]
-/***/ }),
+ // 2. Set response’s timing info to the result of creating an opaque timing
+ // info for fetchParams’s timing info.
+ response.timingInfo = createOpaqueTimingInfo({
+ startTime: fetchParams.timingInfo.startTime
+ })
+ }
-/***/ 71173:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Let processResponseEndOfBody be the following steps:
+ const processResponseEndOfBody = () => {
+ // 1. Set fetchParams’s request’s done flag.
+ fetchParams.request.done = true
+ // If fetchParams’s process response end-of-body is not null,
+ // then queue a fetch task to run fetchParams’s process response
+ // end-of-body given response with fetchParams’s task destination.
+ if (fetchParams.processResponseEndOfBody != null) {
+ queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
+ }
+ }
+ // 3. If fetchParams’s process response is non-null, then queue a fetch task
+ // to run fetchParams’s process response given response, with fetchParams’s
+ // task destination.
+ if (fetchParams.processResponse != null) {
+ queueMicrotask(() => fetchParams.processResponse(response))
+ }
-const assert = __nccwpck_require__(42613)
-const { URLSerializer } = __nccwpck_require__(37246)
-const { isValidHeaderName } = __nccwpck_require__(72847)
+ // 4. If response’s body is null, then run processResponseEndOfBody.
+ if (response.body == null) {
+ processResponseEndOfBody()
+ } else {
+ // 5. Otherwise:
-/**
- * @see https://url.spec.whatwg.org/#concept-url-equals
- * @param {URL} A
- * @param {URL} B
- * @param {boolean | undefined} excludeFragment
- * @returns {boolean}
- */
-function urlEquals (A, B, excludeFragment = false) {
- const serializedA = URLSerializer(A, excludeFragment)
+ // 1. Let transformStream be a new a TransformStream.
- const serializedB = URLSerializer(B, excludeFragment)
+ // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,
+ // enqueues chunk in transformStream.
+ const identityTransformAlgorithm = (chunk, controller) => {
+ controller.enqueue(chunk)
+ }
- return serializedA === serializedB
-}
+ // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm
+ // and flushAlgorithm set to processResponseEndOfBody.
+ const transformStream = new TransformStream({
+ start () {},
+ transform: identityTransformAlgorithm,
+ flush: processResponseEndOfBody
+ }, {
+ size () {
+ return 1
+ }
+ }, {
+ size () {
+ return 1
+ }
+ })
-/**
- * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262
- * @param {string} header
- */
-function fieldValues (header) {
- assert(header !== null)
+ // 4. Set response’s body to the result of piping response’s body through transformStream.
+ response.body = { stream: response.body.stream.pipeThrough(transformStream) }
+ }
- const values = []
+ // 6. If fetchParams’s process response consume body is non-null, then:
+ if (fetchParams.processResponseConsumeBody != null) {
+ // 1. Let processBody given nullOrBytes be this step: run fetchParams’s
+ // process response consume body given response and nullOrBytes.
+ const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)
- for (let value of header.split(',')) {
- value = value.trim()
+ // 2. Let processBodyError be this step: run fetchParams’s process
+ // response consume body given response and failure.
+ const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)
- if (!value.length) {
- continue
- } else if (!isValidHeaderName(value)) {
- continue
+ // 3. If response’s body is null, then queue a fetch task to run processBody
+ // given null, with fetchParams’s task destination.
+ if (response.body == null) {
+ queueMicrotask(() => processBody(null))
+ } else {
+ // 4. Otherwise, fully read response’s body given processBody, processBodyError,
+ // and fetchParams’s task destination.
+ return fullyReadBody(response.body, processBody, processBodyError)
}
-
- values.push(value)
+ return Promise.resolve()
}
-
- return values
}
-module.exports = {
- urlEquals,
- fieldValues
-}
+// https://fetch.spec.whatwg.org/#http-fetch
+async function httpFetch (fetchParams) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
+ // 2. Let response be null.
+ let response = null
-/***/ }),
+ // 3. Let actualResponse be null.
+ let actualResponse = null
-/***/ 45513:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 4. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
-// @ts-check
+ // 5. If request’s service-workers mode is "all", then:
+ if (request.serviceWorkers === 'all') {
+ // TODO
+ }
+ // 6. If response is null, then:
+ if (response === null) {
+ // 1. If makeCORSPreflight is true and one of these conditions is true:
+ // TODO
+ // 2. If request’s redirect mode is "follow", then set request’s
+ // service-workers mode to "none".
+ if (request.redirect === 'follow') {
+ request.serviceWorkers = 'none'
+ }
-/* global WebAssembly */
+ // 3. Set response and actualResponse to the result of running
+ // HTTP-network-or-cache fetch given fetchParams.
+ actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
-const assert = __nccwpck_require__(42613)
-const net = __nccwpck_require__(69278)
-const http = __nccwpck_require__(58611)
-const { pipeline } = __nccwpck_require__(2203)
-const util = __nccwpck_require__(89500)
-const timers = __nccwpck_require__(82576)
-const Request = __nccwpck_require__(69691)
-const DispatcherBase = __nccwpck_require__(52421)
-const {
- RequestContentLengthMismatchError,
- ResponseContentLengthMismatchError,
- InvalidArgumentError,
- RequestAbortedError,
- HeadersTimeoutError,
- HeadersOverflowError,
- SocketError,
- InformationalError,
- BodyTimeoutError,
- HTTPParserError,
- ResponseExceededMaxSizeError,
- ClientDestroyedError
-} = __nccwpck_require__(53959)
-const buildConnector = __nccwpck_require__(91332)
-const {
- kUrl,
- kReset,
- kServerName,
- kClient,
- kBusy,
- kParser,
- kConnect,
- kBlocking,
- kResuming,
- kRunning,
- kPending,
- kSize,
- kWriting,
- kQueue,
- kConnected,
- kConnecting,
- kNeedDrain,
- kNoRef,
- kKeepAliveDefaultTimeout,
- kHostHeader,
- kPendingIdx,
- kRunningIdx,
- kError,
- kPipelining,
- kSocket,
- kKeepAliveTimeoutValue,
- kMaxHeadersSize,
- kKeepAliveMaxTimeout,
- kKeepAliveTimeoutThreshold,
- kHeadersTimeout,
- kBodyTimeout,
- kStrictContentLength,
- kConnector,
- kMaxRedirections,
- kMaxRequests,
- kCounter,
- kClose,
- kDestroy,
- kDispatch,
- kInterceptors,
- kLocalAddress,
- kMaxResponseSize,
- kHTTPConnVersion,
- // HTTP2
- kHost,
- kHTTP2Session,
- kHTTP2SessionState,
- kHTTP2BuildRequest,
- kHTTP2CopyHeaders,
- kHTTP1BuildRequest
-} = __nccwpck_require__(68031)
+ // 4. If request’s response tainting is "cors" and a CORS check
+ // for request and response returns failure, then return a network error.
+ if (
+ request.responseTainting === 'cors' &&
+ corsCheck(request, response) === 'failure'
+ ) {
+ return makeNetworkError('cors failure')
+ }
-/** @type {import('http2')} */
-let http2
-try {
- http2 = __nccwpck_require__(85675)
-} catch {
- // @ts-ignore
- http2 = { constants: {} }
-}
+ // 5. If the TAO check for request and response returns failure, then set
+ // request’s timing allow failed flag.
+ if (TAOCheck(request, response) === 'failure') {
+ request.timingAllowFailed = true
+ }
+ }
+
+ // 7. If either request’s response tainting or response’s type
+ // is "opaque", and the cross-origin resource policy check with
+ // request’s origin, request’s client, request’s destination,
+ // and actualResponse returns blocked, then return a network error.
+ if (
+ (request.responseTainting === 'opaque' || response.type === 'opaque') &&
+ crossOriginResourcePolicyCheck(
+ request.origin,
+ request.client,
+ request.destination,
+ actualResponse
+ ) === 'blocked'
+ ) {
+ return makeNetworkError('blocked')
+ }
+
+ // 8. If actualResponse’s status is a redirect status, then:
+ if (redirectStatusSet.has(actualResponse.status)) {
+ // 1. If actualResponse’s status is not 303, request’s body is not null,
+ // and the connection uses HTTP/2, then user agents may, and are even
+ // encouraged to, transmit an RST_STREAM frame.
+ // See, https://github.com/whatwg/fetch/issues/1288
+ if (request.redirect !== 'manual') {
+ fetchParams.controller.connection.destroy()
+ }
-const {
- constants: {
- HTTP2_HEADER_AUTHORITY,
- HTTP2_HEADER_METHOD,
- HTTP2_HEADER_PATH,
- HTTP2_HEADER_SCHEME,
- HTTP2_HEADER_CONTENT_LENGTH,
- HTTP2_HEADER_EXPECT,
- HTTP2_HEADER_STATUS
+ // 2. Switch on request’s redirect mode:
+ if (request.redirect === 'error') {
+ // Set response to a network error.
+ response = makeNetworkError('unexpected redirect')
+ } else if (request.redirect === 'manual') {
+ // Set response to an opaque-redirect filtered response whose internal
+ // response is actualResponse.
+ // NOTE(spec): On the web this would return an `opaqueredirect` response,
+ // but that doesn't make sense server side.
+ // See https://github.com/nodejs/undici/issues/1193.
+ response = actualResponse
+ } else if (request.redirect === 'follow') {
+ // Set response to the result of running HTTP-redirect fetch given
+ // fetchParams and response.
+ response = await httpRedirectFetch(fetchParams, response)
+ } else {
+ assert(false)
+ }
}
-} = http2
-// Experimental
-let h2ExperimentalWarned = false
+ // 9. Set response’s timing info to timingInfo.
+ response.timingInfo = timingInfo
-const FastBuffer = Buffer[Symbol.species]
+ // 10. Return response.
+ return response
+}
-const kClosedResolve = Symbol('kClosedResolve')
+// https://fetch.spec.whatwg.org/#http-redirect-fetch
+function httpRedirectFetch (fetchParams, response) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
-const channels = {}
+ // 2. Let actualResponse be response, if response is not a filtered response,
+ // and response’s internal response otherwise.
+ const actualResponse = response.internalResponse
+ ? response.internalResponse
+ : response
-try {
- const diagnosticsChannel = __nccwpck_require__(31637)
- channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders')
- channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect')
- channels.connectError = diagnosticsChannel.channel('undici:client:connectError')
- channels.connected = diagnosticsChannel.channel('undici:client:connected')
-} catch {
- channels.sendHeaders = { hasSubscribers: false }
- channels.beforeConnect = { hasSubscribers: false }
- channels.connectError = { hasSubscribers: false }
- channels.connected = { hasSubscribers: false }
-}
+ // 3. Let locationURL be actualResponse’s location URL given request’s current
+ // URL’s fragment.
+ let locationURL
-/**
- * @type {import('../types/client').default}
- */
-class Client extends DispatcherBase {
- /**
- *
- * @param {string|URL} url
- * @param {import('../types/client').Client.Options} options
- */
- constructor (url, {
- interceptors,
- maxHeaderSize,
- headersTimeout,
- socketTimeout,
- requestTimeout,
- connectTimeout,
- bodyTimeout,
- idleTimeout,
- keepAlive,
- keepAliveTimeout,
- maxKeepAliveTimeout,
- keepAliveMaxTimeout,
- keepAliveTimeoutThreshold,
- socketPath,
- pipelining,
- tls,
- strictContentLength,
- maxCachedSessions,
- maxRedirections,
- connect,
- maxRequestsPerClient,
- localAddress,
- maxResponseSize,
- autoSelectFamily,
- autoSelectFamilyAttemptTimeout,
- // h2
- allowH2,
- maxConcurrentStreams
- } = {}) {
- super()
+ try {
+ locationURL = responseLocationURL(
+ actualResponse,
+ requestCurrentURL(request).hash
+ )
- if (keepAlive !== undefined) {
- throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead')
+ // 4. If locationURL is null, then return response.
+ if (locationURL == null) {
+ return response
}
+ } catch (err) {
+ // 5. If locationURL is failure, then return a network error.
+ return Promise.resolve(makeNetworkError(err))
+ }
- if (socketTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead')
- }
+ // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
+ // error.
+ if (!urlIsHttpHttpsScheme(locationURL)) {
+ return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
+ }
- if (requestTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead')
- }
+ // 7. If request’s redirect count is 20, then return a network error.
+ if (request.redirectCount === 20) {
+ return Promise.resolve(makeNetworkError('redirect count exceeded'))
+ }
- if (idleTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead')
- }
+ // 8. Increase request’s redirect count by 1.
+ request.redirectCount += 1
- if (maxKeepAliveTimeout !== undefined) {
- throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead')
- }
+ // 9. If request’s mode is "cors", locationURL includes credentials, and
+ // request’s origin is not same origin with locationURL’s origin, then return
+ // a network error.
+ if (
+ request.mode === 'cors' &&
+ (locationURL.username || locationURL.password) &&
+ !sameOrigin(request, locationURL)
+ ) {
+ return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
+ }
- if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) {
- throw new InvalidArgumentError('invalid maxHeaderSize')
- }
+ // 10. If request’s response tainting is "cors" and locationURL includes
+ // credentials, then return a network error.
+ if (
+ request.responseTainting === 'cors' &&
+ (locationURL.username || locationURL.password)
+ ) {
+ return Promise.resolve(makeNetworkError(
+ 'URL cannot contain credentials for request mode "cors"'
+ ))
+ }
- if (socketPath != null && typeof socketPath !== 'string') {
- throw new InvalidArgumentError('invalid socketPath')
- }
+ // 11. If actualResponse’s status is not 303, request’s body is non-null,
+ // and request’s body’s source is null, then return a network error.
+ if (
+ actualResponse.status !== 303 &&
+ request.body != null &&
+ request.body.source == null
+ ) {
+ return Promise.resolve(makeNetworkError())
+ }
- if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) {
- throw new InvalidArgumentError('invalid connectTimeout')
- }
+ // 12. If one of the following is true
+ // - actualResponse’s status is 301 or 302 and request’s method is `POST`
+ // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
+ if (
+ ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
+ (actualResponse.status === 303 &&
+ !GET_OR_HEAD.includes(request.method))
+ ) {
+ // then:
+ // 1. Set request’s method to `GET` and request’s body to null.
+ request.method = 'GET'
+ request.body = null
- if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) {
- throw new InvalidArgumentError('invalid keepAliveTimeout')
+ // 2. For each headerName of request-body-header name, delete headerName from
+ // request’s header list.
+ for (const headerName of requestBodyHeader) {
+ request.headersList.delete(headerName)
}
+ }
- if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) {
- throw new InvalidArgumentError('invalid keepAliveMaxTimeout')
- }
+ // 13. If request’s current URL’s origin is not same origin with locationURL’s
+ // origin, then for each headerName of CORS non-wildcard request-header name,
+ // delete headerName from request’s header list.
+ if (!sameOrigin(requestCurrentURL(request), locationURL)) {
+ // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
+ request.headersList.delete('authorization')
- if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) {
- throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold')
- }
+ // https://fetch.spec.whatwg.org/#authentication-entries
+ request.headersList.delete('proxy-authorization', true)
- if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError('headersTimeout must be a positive integer or zero')
- }
+ // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
+ request.headersList.delete('cookie')
+ request.headersList.delete('host')
+ }
- if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero')
- }
+ // 14. If request’s body is non-null, then set request’s body to the first return
+ // value of safely extracting request’s body’s source.
+ if (request.body != null) {
+ assert(request.body.source != null)
+ request.body = safelyExtractBody(request.body.source)[0]
+ }
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
- }
+ // 15. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
- if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
- }
+ // 16. Set timingInfo’s redirect end time and post-redirect start time to the
+ // coarsened shared current time given fetchParams’s cross-origin isolated
+ // capability.
+ timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
+ coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
- if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
- throw new InvalidArgumentError('maxRequestsPerClient must be a positive number')
- }
+ // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
+ // redirect start time to timingInfo’s start time.
+ if (timingInfo.redirectStartTime === 0) {
+ timingInfo.redirectStartTime = timingInfo.startTime
+ }
- if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) {
- throw new InvalidArgumentError('localAddress must be valid string IP address')
- }
+ // 18. Append locationURL to request’s URL list.
+ request.urlList.push(locationURL)
- if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
- throw new InvalidArgumentError('maxResponseSize must be a positive number')
- }
+ // 19. Invoke set request’s referrer policy on redirect on request and
+ // actualResponse.
+ setRequestReferrerPolicyOnRedirect(request, actualResponse)
- if (
- autoSelectFamilyAttemptTimeout != null &&
- (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1)
- ) {
- throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number')
- }
+ // 20. Return the result of running main fetch given fetchParams and true.
+ return mainFetch(fetchParams, true)
+}
- // h2
- if (allowH2 != null && typeof allowH2 !== 'boolean') {
- throw new InvalidArgumentError('allowH2 must be a valid boolean value')
- }
+// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
+async function httpNetworkOrCacheFetch (
+ fetchParams,
+ isAuthenticationFetch = false,
+ isNewConnectionFetch = false
+) {
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
- if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) {
- throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0')
- }
+ // 2. Let httpFetchParams be null.
+ let httpFetchParams = null
- if (typeof connect !== 'function') {
- connect = buildConnector({
- ...tls,
- maxCachedSessions,
- allowH2,
- socketPath,
- timeout: connectTimeout,
- ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
- ...connect
- })
- }
+ // 3. Let httpRequest be null.
+ let httpRequest = null
- this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client)
- ? interceptors.Client
- : [createRedirectInterceptor({ maxRedirections })]
- this[kUrl] = util.parseOrigin(url)
- this[kConnector] = connect
- this[kSocket] = null
- this[kPipelining] = pipelining != null ? pipelining : 1
- this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize
- this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout
- this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout
- this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold
- this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]
- this[kServerName] = null
- this[kLocalAddress] = localAddress != null ? localAddress : null
- this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming
- this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming
- this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n`
- this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3
- this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3
- this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength
- this[kMaxRedirections] = maxRedirections
- this[kMaxRequests] = maxRequestsPerClient
- this[kClosedResolve] = null
- this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1
- this[kHTTPConnVersion] = 'h1'
+ // 4. Let response be null.
+ let response = null
- // HTTP/2
- this[kHTTP2Session] = null
- this[kHTTP2SessionState] = !allowH2
- ? null
- : {
- // streams: null, // Fixed queue of streams - For future support of `push`
- openStreams: 0, // Keep track of them to decide wether or not unref the session
- maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server
- }
- this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}`
+ // 5. Let storedResponse be null.
+ // TODO: cache
- // kQueue is built up of 3 sections separated by
- // the kRunningIdx and kPendingIdx indices.
- // | complete | running | pending |
- // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length
- // kRunningIdx points to the first running element.
- // kPendingIdx points to the first pending element.
- // This implements a fast queue with an amortized
- // time of O(1).
+ // 6. Let httpCache be null.
+ const httpCache = null
- this[kQueue] = []
- this[kRunningIdx] = 0
- this[kPendingIdx] = 0
+ // 7. Let the revalidatingFlag be unset.
+ const revalidatingFlag = false
+
+ // 8. Run these steps, but abort when the ongoing fetch is terminated:
+
+ // 1. If request’s window is "no-window" and request’s redirect mode is
+ // "error", then set httpFetchParams to fetchParams and httpRequest to
+ // request.
+ if (request.window === 'no-window' && request.redirect === 'error') {
+ httpFetchParams = fetchParams
+ httpRequest = request
+ } else {
+ // Otherwise:
+
+ // 1. Set httpRequest to a clone of request.
+ httpRequest = makeRequest(request)
+
+ // 2. Set httpFetchParams to a copy of fetchParams.
+ httpFetchParams = { ...fetchParams }
+
+ // 3. Set httpFetchParams’s request to httpRequest.
+ httpFetchParams.request = httpRequest
}
- get pipelining () {
- return this[kPipelining]
+ // 3. Let includeCredentials be true if one of
+ const includeCredentials =
+ request.credentials === 'include' ||
+ (request.credentials === 'same-origin' &&
+ request.responseTainting === 'basic')
+
+ // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
+ // body is non-null; otherwise null.
+ const contentLength = httpRequest.body ? httpRequest.body.length : null
+
+ // 5. Let contentLengthHeaderValue be null.
+ let contentLengthHeaderValue = null
+
+ // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
+ // `PUT`, then set contentLengthHeaderValue to `0`.
+ if (
+ httpRequest.body == null &&
+ ['POST', 'PUT'].includes(httpRequest.method)
+ ) {
+ contentLengthHeaderValue = '0'
}
- set pipelining (value) {
- this[kPipelining] = value
- resume(this, true)
+ // 7. If contentLength is non-null, then set contentLengthHeaderValue to
+ // contentLength, serialized and isomorphic encoded.
+ if (contentLength != null) {
+ contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
}
- get [kPending] () {
- return this[kQueue].length - this[kPendingIdx]
+ // 8. If contentLengthHeaderValue is non-null, then append
+ // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
+ // list.
+ if (contentLengthHeaderValue != null) {
+ httpRequest.headersList.append('content-length', contentLengthHeaderValue)
}
- get [kRunning] () {
- return this[kPendingIdx] - this[kRunningIdx]
+ // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
+ // contentLengthHeaderValue) to httpRequest’s header list.
+
+ // 10. If contentLength is non-null and httpRequest’s keepalive is true,
+ // then:
+ if (contentLength != null && httpRequest.keepalive) {
+ // NOTE: keepalive is a noop outside of browser context.
}
- get [kSize] () {
- return this[kQueue].length - this[kRunningIdx]
+ // 11. If httpRequest’s referrer is a URL, then append
+ // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
+ // to httpRequest’s header list.
+ if (httpRequest.referrer instanceof URL) {
+ httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))
}
- get [kConnected] () {
- return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed
+ // 12. Append a request `Origin` header for httpRequest.
+ appendRequestOriginHeader(httpRequest)
+
+ // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
+ appendFetchMetadata(httpRequest)
+
+ // 14. If httpRequest’s header list does not contain `User-Agent`, then
+ // user agents should append `User-Agent`/default `User-Agent` value to
+ // httpRequest’s header list.
+ if (!httpRequest.headersList.contains('user-agent')) {
+ httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')
}
- get [kBusy] () {
- const socket = this[kSocket]
- return (
- (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) ||
- (this[kSize] >= (this[kPipelining] || 1)) ||
- this[kPending] > 0
- )
+ // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
+ // list contains `If-Modified-Since`, `If-None-Match`,
+ // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
+ // httpRequest’s cache mode to "no-store".
+ if (
+ httpRequest.cache === 'default' &&
+ (httpRequest.headersList.contains('if-modified-since') ||
+ httpRequest.headersList.contains('if-none-match') ||
+ httpRequest.headersList.contains('if-unmodified-since') ||
+ httpRequest.headersList.contains('if-match') ||
+ httpRequest.headersList.contains('if-range'))
+ ) {
+ httpRequest.cache = 'no-store'
}
- /* istanbul ignore: only used for test */
- [kConnect] (cb) {
- connect(this)
- this.once('connect', cb)
+ // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
+ // no-cache cache-control header modification flag is unset, and
+ // httpRequest’s header list does not contain `Cache-Control`, then append
+ // `Cache-Control`/`max-age=0` to httpRequest’s header list.
+ if (
+ httpRequest.cache === 'no-cache' &&
+ !httpRequest.preventNoCacheCacheControlHeaderModification &&
+ !httpRequest.headersList.contains('cache-control')
+ ) {
+ httpRequest.headersList.append('cache-control', 'max-age=0')
}
- [kDispatch] (opts, handler) {
- const origin = opts.origin || this[kUrl].origin
+ // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
+ if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
+ // 1. If httpRequest’s header list does not contain `Pragma`, then append
+ // `Pragma`/`no-cache` to httpRequest’s header list.
+ if (!httpRequest.headersList.contains('pragma')) {
+ httpRequest.headersList.append('pragma', 'no-cache')
+ }
- const request = this[kHTTPConnVersion] === 'h2'
- ? Request[kHTTP2BuildRequest](origin, opts, handler)
- : Request[kHTTP1BuildRequest](origin, opts, handler)
+ // 2. If httpRequest’s header list does not contain `Cache-Control`,
+ // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
+ if (!httpRequest.headersList.contains('cache-control')) {
+ httpRequest.headersList.append('cache-control', 'no-cache')
+ }
+ }
- this[kQueue].push(request)
- if (this[kResuming]) {
- // Do nothing.
- } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) {
- // Wait a tick in case stream/iterator is ended in the same tick.
- this[kResuming] = 1
- process.nextTick(resume, this)
+ // 18. If httpRequest’s header list contains `Range`, then append
+ // `Accept-Encoding`/`identity` to httpRequest’s header list.
+ if (httpRequest.headersList.contains('range')) {
+ httpRequest.headersList.append('accept-encoding', 'identity')
+ }
+
+ // 19. Modify httpRequest’s header list per HTTP. Do not append a given
+ // header if httpRequest’s header list contains that header’s name.
+ // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
+ if (!httpRequest.headersList.contains('accept-encoding')) {
+ if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
+ httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')
} else {
- resume(this, true)
+ httpRequest.headersList.append('accept-encoding', 'gzip, deflate')
}
+ }
- if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) {
- this[kNeedDrain] = 2
- }
+ httpRequest.headersList.delete('host')
- return this[kNeedDrain] < 2
+ // 20. If includeCredentials is true, then:
+ if (includeCredentials) {
+ // 1. If the user agent is not configured to block cookies for httpRequest
+ // (see section 7 of [COOKIES]), then:
+ // TODO: credentials
+ // 2. If httpRequest’s header list does not contain `Authorization`, then:
+ // TODO: credentials
}
- async [kClose] () {
- // TODO: for H2 we need to gracefully flush the remaining enqueued
- // request and close each stream.
- return new Promise((resolve) => {
- if (!this[kSize]) {
- resolve(null)
- } else {
- this[kClosedResolve] = resolve
- }
- })
- }
+ // 21. If there’s a proxy-authentication entry, use it as appropriate.
+ // TODO: proxy-authentication
- async [kDestroy] (err) {
- return new Promise((resolve) => {
- const requests = this[kQueue].splice(this[kPendingIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- errorRequest(this, request, err)
- }
+ // 22. Set httpCache to the result of determining the HTTP cache
+ // partition, given httpRequest.
+ // TODO: cache
- const callback = () => {
- if (this[kClosedResolve]) {
- // TODO (fix): Should we error here with ClientDestroyedError?
- this[kClosedResolve]()
- this[kClosedResolve] = null
- }
- resolve()
- }
+ // 23. If httpCache is null, then set httpRequest’s cache mode to
+ // "no-store".
+ if (httpCache == null) {
+ httpRequest.cache = 'no-store'
+ }
- if (this[kHTTP2Session] != null) {
- util.destroy(this[kHTTP2Session], err)
- this[kHTTP2Session] = null
- this[kHTTP2SessionState] = null
- }
+ // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
+ // then:
+ if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {
+ // TODO: cache
+ }
- if (!this[kSocket]) {
- queueMicrotask(callback)
- } else {
- util.destroy(this[kSocket].on('close', callback), err)
- }
+ // 9. If aborted, then return the appropriate network error for fetchParams.
+ // TODO
- resume(this)
- })
- }
-}
+ // 10. If response is null, then:
+ if (response == null) {
+ // 1. If httpRequest’s cache mode is "only-if-cached", then return a
+ // network error.
+ if (httpRequest.mode === 'only-if-cached') {
+ return makeNetworkError('only if cached')
+ }
-function onHttp2SessionError (err) {
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+ // 2. Let forwardResponse be the result of running HTTP-network fetch
+ // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
+ const forwardResponse = await httpNetworkFetch(
+ httpFetchParams,
+ includeCredentials,
+ isNewConnectionFetch
+ )
- this[kSocket][kError] = err
+ // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
+ // in the range 200 to 399, inclusive, invalidate appropriate stored
+ // responses in httpCache, as per the "Invalidation" chapter of HTTP
+ // Caching, and set storedResponse to null. [HTTP-CACHING]
+ if (
+ !safeMethodsSet.has(httpRequest.method) &&
+ forwardResponse.status >= 200 &&
+ forwardResponse.status <= 399
+ ) {
+ // TODO: cache
+ }
- onError(this[kClient], err)
-}
+ // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
+ // then:
+ if (revalidatingFlag && forwardResponse.status === 304) {
+ // TODO: cache
+ }
-function onHttp2FrameError (type, code, id) {
- const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
+ // 5. If response is null, then:
+ if (response == null) {
+ // 1. Set response to forwardResponse.
+ response = forwardResponse
- if (id === 0) {
- this[kSocket][kError] = err
- onError(this[kClient], err)
+ // 2. Store httpRequest and forwardResponse in httpCache, as per the
+ // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
+ // TODO: cache
+ }
}
-}
-function onHttp2SessionEnd () {
- util.destroy(this, new SocketError('other side closed'))
- util.destroy(this[kSocket], new SocketError('other side closed'))
-}
+ // 11. Set response’s URL list to a clone of httpRequest’s URL list.
+ response.urlList = [...httpRequest.urlList]
-function onHTTP2GoAway (code) {
- const client = this[kClient]
- const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`)
- client[kSocket] = null
- client[kHTTP2Session] = null
+ // 12. If httpRequest’s header list contains `Range`, then set response’s
+ // range-requested flag.
+ if (httpRequest.headersList.contains('range')) {
+ response.rangeRequested = true
+ }
- if (client.destroyed) {
- assert(this[kPending] === 0)
+ // 13. Set response’s request-includes-credentials to includeCredentials.
+ response.requestIncludesCredentials = includeCredentials
- // Fail entire queue.
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- errorRequest(this, request, err)
+ // 14. If response’s status is 401, httpRequest’s response tainting is not
+ // "cors", includeCredentials is true, and request’s window is an environment
+ // settings object, then:
+ // TODO
+
+ // 15. If response’s status is 407, then:
+ if (response.status === 407) {
+ // 1. If request’s window is "no-window", then return a network error.
+ if (request.window === 'no-window') {
+ return makeNetworkError()
}
- } else if (client[kRunning] > 0) {
- // Fail head of pipeline.
- const request = client[kQueue][client[kRunningIdx]]
- client[kQueue][client[kRunningIdx]++] = null
- errorRequest(client, request, err)
- }
+ // 2. ???
- client[kPendingIdx] = client[kRunningIdx]
+ // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams)
+ }
- assert(client[kRunning] === 0)
+ // 4. Prompt the end user as appropriate in request’s window and store
+ // the result as a proxy-authentication entry. [HTTP-AUTH]
+ // TODO: Invoke some kind of callback?
- client.emit('disconnect',
- client[kUrl],
- [client],
- err
- )
+ // 5. Set response to the result of running HTTP-network-or-cache fetch given
+ // fetchParams.
+ // TODO
+ return makeNetworkError('proxy authentication required')
+ }
- resume(client)
-}
+ // 16. If all of the following are true
+ if (
+ // response’s status is 421
+ response.status === 421 &&
+ // isNewConnectionFetch is false
+ !isNewConnectionFetch &&
+ // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
+ (request.body == null || request.body.source != null)
+ ) {
+ // then:
-const constants = __nccwpck_require__(40748)
-const createRedirectInterceptor = __nccwpck_require__(99299)
-const EMPTY_BUF = Buffer.alloc(0)
+ // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
+ if (isCancelled(fetchParams)) {
+ return makeAppropriateNetworkError(fetchParams)
+ }
-async function lazyllhttp () {
- const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(63922) : undefined
+ // 2. Set response to the result of running HTTP-network-or-cache
+ // fetch given fetchParams, isAuthenticationFetch, and true.
- let mod
- try {
- mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(53742), 'base64'))
- } catch (e) {
- /* istanbul ignore next */
+ // TODO (spec): The spec doesn't specify this but we need to cancel
+ // the active response before we can start a new one.
+ // https://github.com/whatwg/fetch/issues/1293
+ fetchParams.controller.connection.destroy()
- // We could check if the error was caused by the simd option not
- // being enabled, but the occurring of this other error
- // * https://github.com/emscripten-core/emscripten/issues/11495
- // got me to remove that check to avoid breaking Node 12.
- mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(63922), 'base64'))
+ response = await httpNetworkOrCacheFetch(
+ fetchParams,
+ isAuthenticationFetch,
+ true
+ )
}
- return await WebAssembly.instantiate(mod, {
- env: {
- /* eslint-disable camelcase */
-
- wasm_on_url: (p, at, len) => {
- /* istanbul ignore next */
- return 0
- },
- wasm_on_status: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_message_begin: (p) => {
- assert.strictEqual(currentParser.ptr, p)
- return currentParser.onMessageBegin() || 0
- },
- wasm_on_header_field: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_header_value: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
- assert.strictEqual(currentParser.ptr, p)
- return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0
- },
- wasm_on_body: (p, at, len) => {
- assert.strictEqual(currentParser.ptr, p)
- const start = at - currentBufferPtr + currentBufferRef.byteOffset
- return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0
- },
- wasm_on_message_complete: (p) => {
- assert.strictEqual(currentParser.ptr, p)
- return currentParser.onMessageComplete() || 0
- }
+ // 17. If isAuthenticationFetch is true, then create an authentication entry
+ if (isAuthenticationFetch) {
+ // TODO
+ }
- /* eslint-enable camelcase */
- }
- })
+ // 18. Return response.
+ return response
}
-let llhttpInstance = null
-let llhttpPromise = lazyllhttp()
-llhttpPromise.catch()
+// https://fetch.spec.whatwg.org/#http-network-fetch
+async function httpNetworkFetch (
+ fetchParams,
+ includeCredentials = false,
+ forceNewConnection = false
+) {
+ assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
-let currentParser = null
-let currentBufferRef = null
-let currentBufferSize = 0
-let currentBufferPtr = null
+ fetchParams.controller.connection = {
+ abort: null,
+ destroyed: false,
+ destroy (err) {
+ if (!this.destroyed) {
+ this.destroyed = true
+ this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
+ }
+ }
+ }
-const TIMEOUT_HEADERS = 1
-const TIMEOUT_BODY = 2
-const TIMEOUT_IDLE = 3
+ // 1. Let request be fetchParams’s request.
+ const request = fetchParams.request
-class Parser {
- constructor (client, socket, { exports }) {
- assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0)
+ // 2. Let response be null.
+ let response = null
- this.llhttp = exports
- this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE)
- this.client = client
- this.socket = socket
- this.timeout = null
- this.timeoutValue = null
- this.timeoutType = null
- this.statusCode = null
- this.statusText = ''
- this.upgrade = false
- this.headers = []
- this.headersSize = 0
- this.headersMaxSize = client[kMaxHeadersSize]
- this.shouldKeepAlive = false
- this.paused = false
- this.resume = this.resume.bind(this)
+ // 3. Let timingInfo be fetchParams’s timing info.
+ const timingInfo = fetchParams.timingInfo
- this.bytesRead = 0
+ // 4. Let httpCache be the result of determining the HTTP cache partition,
+ // given request.
+ // TODO: cache
+ const httpCache = null
- this.keepAlive = ''
- this.contentLength = ''
- this.connection = ''
- this.maxResponseSize = client[kMaxResponseSize]
+ // 5. If httpCache is null, then set request’s cache mode to "no-store".
+ if (httpCache == null) {
+ request.cache = 'no-store'
}
- setTimeout (value, type) {
- this.timeoutType = type
- if (value !== this.timeoutValue) {
- timers.clearTimeout(this.timeout)
- if (value) {
- this.timeout = timers.setTimeout(onParserTimeout, value, this)
- // istanbul ignore else: only for jest
- if (this.timeout.unref) {
- this.timeout.unref()
- }
- } else {
- this.timeout = null
- }
- this.timeoutValue = value
- } else if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
- }
+ // 6. Let networkPartitionKey be the result of determining the network
+ // partition key given request.
+ // TODO
- resume () {
- if (this.socket.destroyed || !this.paused) {
- return
- }
+ // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
+ // "no".
+ const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
- assert(this.ptr != null)
- assert(currentParser == null)
+ // 8. Switch on request’s mode:
+ if (request.mode === 'websocket') {
+ // Let connection be the result of obtaining a WebSocket connection,
+ // given request’s current URL.
+ // TODO
+ } else {
+ // Let connection be the result of obtaining a connection, given
+ // networkPartitionKey, request’s current URL’s origin,
+ // includeCredentials, and forceNewConnection.
+ // TODO
+ }
- this.llhttp.llhttp_resume(this.ptr)
+ // 9. Run these steps, but abort when the ongoing fetch is terminated:
- assert(this.timeoutType === TIMEOUT_BODY)
- if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
+ // 1. If connection is failure, then return a network error.
- this.paused = false
- this.execute(this.socket.read() || EMPTY_BUF) // Flush parser.
- this.readMore()
- }
+ // 2. Set timingInfo’s final connection timing info to the result of
+ // calling clamp and coarsen connection timing info with connection’s
+ // timing info, timingInfo’s post-redirect start time, and fetchParams’s
+ // cross-origin isolated capability.
- readMore () {
- while (!this.paused && this.ptr) {
- const chunk = this.socket.read()
- if (chunk === null) {
- break
- }
- this.execute(chunk)
- }
- }
+ // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
+ // and request’s body’s source is null, then append (`Transfer-Encoding`,
+ // `chunked`) to request’s header list.
- execute (data) {
- assert(this.ptr != null)
- assert(currentParser == null)
- assert(!this.paused)
+ // 4. Set timingInfo’s final network-request start time to the coarsened
+ // shared current time given fetchParams’s cross-origin isolated
+ // capability.
- const { socket, llhttp } = this
+ // 5. Set response to the result of making an HTTP request over connection
+ // using request with the following caveats:
- if (data.length > currentBufferSize) {
- if (currentBufferPtr) {
- llhttp.free(currentBufferPtr)
- }
- currentBufferSize = Math.ceil(data.length / 4096) * 4096
- currentBufferPtr = llhttp.malloc(currentBufferSize)
- }
+ // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
+ // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
- new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data)
+ // - If request’s body is non-null, and request’s body’s source is null,
+ // then the user agent may have a buffer of up to 64 kibibytes and store
+ // a part of request’s body in that buffer. If the user agent reads from
+ // request’s body beyond that buffer’s size and the user agent needs to
+ // resend request, then instead return a network error.
- // Call `execute` on the wasm parser.
- // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data,
- // and finally the length of bytes to parse.
- // The return value is an error code or `constants.ERROR.OK`.
- try {
- let ret
+ // - Set timingInfo’s final network-response start time to the coarsened
+ // shared current time given fetchParams’s cross-origin isolated capability,
+ // immediately after the user agent’s HTTP parser receives the first byte
+ // of the response (e.g., frame header bytes for HTTP/2 or response status
+ // line for HTTP/1.x).
- try {
- currentBufferRef = data
- currentParser = this
- ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length)
- /* eslint-disable-next-line no-useless-catch */
- } catch (err) {
- /* istanbul ignore next: difficult to make a test case for */
- throw err
- } finally {
- currentParser = null
- currentBufferRef = null
- }
+ // - Wait until all the headers are transmitted.
- const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr
+ // - Any responses whose status is in the range 100 to 199, inclusive,
+ // and is not 101, are to be ignored, except for the purposes of setting
+ // timingInfo’s final network-response start time above.
- if (ret === constants.ERROR.PAUSED_UPGRADE) {
- this.onUpgrade(data.slice(offset))
- } else if (ret === constants.ERROR.PAUSED) {
- this.paused = true
- socket.unshift(data.slice(offset))
- } else if (ret !== constants.ERROR.OK) {
- const ptr = llhttp.llhttp_get_error_reason(this.ptr)
- let message = ''
- /* istanbul ignore else: difficult to make a test case for */
- if (ptr) {
- const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0)
- message =
- 'Response does not match the HTTP/1.1 protocol (' +
- Buffer.from(llhttp.memory.buffer, ptr, len).toString() +
- ')'
- }
- throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset))
- }
- } catch (err) {
- util.destroy(socket, err)
- }
- }
+ // - If request’s header list contains `Transfer-Encoding`/`chunked` and
+ // response is transferred via HTTP/1.0 or older, then return a network
+ // error.
- destroy () {
- assert(this.ptr != null)
- assert(currentParser == null)
+ // - If the HTTP request results in a TLS client certificate dialog, then:
- this.llhttp.llhttp_free(this.ptr)
- this.ptr = null
+ // 1. If request’s window is an environment settings object, make the
+ // dialog available in request’s window.
- timers.clearTimeout(this.timeout)
- this.timeout = null
- this.timeoutValue = null
- this.timeoutType = null
+ // 2. Otherwise, return a network error.
- this.paused = false
- }
+ // To transmit request’s body body, run these steps:
+ let requestBody = null
+ // 1. If body is null and fetchParams’s process request end-of-body is
+ // non-null, then queue a fetch task given fetchParams’s process request
+ // end-of-body and fetchParams’s task destination.
+ if (request.body == null && fetchParams.processRequestEndOfBody) {
+ queueMicrotask(() => fetchParams.processRequestEndOfBody())
+ } else if (request.body != null) {
+ // 2. Otherwise, if body is non-null:
- onStatus (buf) {
- this.statusText = buf.toString()
- }
+ // 1. Let processBodyChunk given bytes be these steps:
+ const processBodyChunk = async function * (bytes) {
+ // 1. If the ongoing fetch is terminated, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
- onMessageBegin () {
- const { socket, client } = this
+ // 2. Run this step in parallel: transmit bytes.
+ yield bytes
- /* istanbul ignore next: difficult to make a test case for */
- if (socket.destroyed) {
- return -1
+ // 3. If fetchParams’s process request body is non-null, then run
+ // fetchParams’s process request body given bytes’s length.
+ fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
}
- const request = client[kQueue][client[kRunningIdx]]
- if (!request) {
- return -1
+ // 2. Let processEndOfBody be these steps:
+ const processEndOfBody = () => {
+ // 1. If fetchParams is canceled, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
+
+ // 2. If fetchParams’s process request end-of-body is non-null,
+ // then run fetchParams’s process request end-of-body.
+ if (fetchParams.processRequestEndOfBody) {
+ fetchParams.processRequestEndOfBody()
+ }
}
- }
- onHeaderField (buf) {
- const len = this.headers.length
+ // 3. Let processBodyError given e be these steps:
+ const processBodyError = (e) => {
+ // 1. If fetchParams is canceled, then abort these steps.
+ if (isCancelled(fetchParams)) {
+ return
+ }
- if ((len & 1) === 0) {
- this.headers.push(buf)
- } else {
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
+ if (e.name === 'AbortError') {
+ fetchParams.controller.abort()
+ } else {
+ fetchParams.controller.terminate(e)
+ }
}
- this.trackHeader(buf.length)
+ // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
+ // processBodyError, and fetchParams’s task destination.
+ requestBody = (async function * () {
+ try {
+ for await (const bytes of request.body.stream) {
+ yield * processBodyChunk(bytes)
+ }
+ processEndOfBody()
+ } catch (err) {
+ processBodyError(err)
+ }
+ })()
}
- onHeaderValue (buf) {
- let len = this.headers.length
+ try {
+ // socket is only provided for websockets
+ const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
- if ((len & 1) === 1) {
- this.headers.push(buf)
- len += 1
+ if (socket) {
+ response = makeResponse({ status, statusText, headersList, socket })
} else {
- this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf])
+ const iterator = body[Symbol.asyncIterator]()
+ fetchParams.controller.next = () => iterator.next()
+
+ response = makeResponse({ status, statusText, headersList })
}
+ } catch (err) {
+ // 10. If aborted, then:
+ if (err.name === 'AbortError') {
+ // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
+ fetchParams.controller.connection.destroy()
- const key = this.headers[len - 2]
- if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') {
- this.keepAlive += buf.toString()
- } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') {
- this.connection += buf.toString()
- } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') {
- this.contentLength += buf.toString()
+ // 2. Return the appropriate network error for fetchParams.
+ return makeAppropriateNetworkError(fetchParams, err)
}
- this.trackHeader(buf.length)
+ return makeNetworkError(err)
}
- trackHeader (len) {
- this.headersSize += len
- if (this.headersSize >= this.headersMaxSize) {
- util.destroy(this.socket, new HeadersOverflowError())
- }
+ // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
+ // if it is suspended.
+ const pullAlgorithm = () => {
+ fetchParams.controller.resume()
}
- onUpgrade (head) {
- const { upgrade, client, socket, headers, statusCode } = this
-
- assert(upgrade)
-
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
-
- assert(!socket.destroyed)
- assert(socket === client[kSocket])
- assert(!this.paused)
- assert(request.upgrade || request.method === 'CONNECT')
-
- this.statusCode = null
- this.statusText = ''
- this.shouldKeepAlive = null
-
- assert(this.headers.length % 2 === 0)
- this.headers = []
- this.headersSize = 0
-
- socket.unshift(head)
+ // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
+ // controller with reason, given reason.
+ const cancelAlgorithm = (reason) => {
+ fetchParams.controller.abort(reason)
+ }
- socket[kParser].destroy()
- socket[kParser] = null
+ // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
+ // the user agent.
+ // TODO
- socket[kClient] = null
- socket[kError] = null
- socket
- .removeListener('error', onSocketError)
- .removeListener('readable', onSocketReadable)
- .removeListener('end', onSocketEnd)
- .removeListener('close', onSocketClose)
+ // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
+ // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
+ // TODO
- client[kSocket] = null
- client[kQueue][client[kRunningIdx]++] = null
- client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade'))
+ // 15. Let stream be a new ReadableStream.
+ // 16. Set up stream with pullAlgorithm set to pullAlgorithm,
+ // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to
+ // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
- try {
- request.onUpgrade(statusCode, headers, socket)
- } catch (err) {
- util.destroy(socket, err)
+ const stream = new ReadableStream(
+ {
+ async start (controller) {
+ fetchParams.controller.controller = controller
+ },
+ async pull (controller) {
+ await pullAlgorithm(controller)
+ },
+ async cancel (reason) {
+ await cancelAlgorithm(reason)
+ }
+ },
+ {
+ highWaterMark: 0,
+ size () {
+ return 1
+ }
}
+ )
- resume(client)
- }
+ // 17. Run these steps, but abort when the ongoing fetch is terminated:
- onHeadersComplete (statusCode, upgrade, shouldKeepAlive) {
- const { client, socket, headers, statusText } = this
+ // 1. Set response’s body to a new body whose stream is stream.
+ response.body = { stream }
- /* istanbul ignore next: difficult to make a test case for */
- if (socket.destroyed) {
- return -1
- }
+ // 2. If response is not a network error and request’s cache mode is
+ // not "no-store", then update response in httpCache for request.
+ // TODO
- const request = client[kQueue][client[kRunningIdx]]
+ // 3. If includeCredentials is true and the user agent is not configured
+ // to block cookies for request (see section 7 of [COOKIES]), then run the
+ // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
+ // the value of each header whose name is a byte-case-insensitive match for
+ // `Set-Cookie` in response’s header list, if any, and request’s current URL.
+ // TODO
- /* istanbul ignore next: difficult to make a test case for */
- if (!request) {
- return -1
- }
+ // 18. If aborted, then:
+ // TODO
- assert(!this.upgrade)
- assert(this.statusCode < 200)
+ // 19. Run these steps in parallel:
- if (statusCode === 100) {
- util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket)))
- return -1
- }
+ // 1. Run these steps, but abort when fetchParams is canceled:
+ fetchParams.controller.on('terminated', onAborted)
+ fetchParams.controller.resume = async () => {
+ // 1. While true
+ while (true) {
+ // 1-3. See onData...
- /* this can only happen if server is misbehaving */
- if (upgrade && !request.upgrade) {
- util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket)))
- return -1
- }
+ // 4. Set bytes to the result of handling content codings given
+ // codings and bytes.
+ let bytes
+ let isFailure
+ try {
+ const { done, value } = await fetchParams.controller.next()
- assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS)
+ if (isAborted(fetchParams)) {
+ break
+ }
- this.statusCode = statusCode
- this.shouldKeepAlive = (
- shouldKeepAlive ||
- // Override llhttp value which does not allow keepAlive for HEAD.
- (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive')
- )
+ bytes = done ? undefined : value
+ } catch (err) {
+ if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
+ // zlib doesn't like empty streams.
+ bytes = undefined
+ } else {
+ bytes = err
- if (this.statusCode >= 200) {
- const bodyTimeout = request.bodyTimeout != null
- ? request.bodyTimeout
- : client[kBodyTimeout]
- this.setTimeout(bodyTimeout, TIMEOUT_BODY)
- } else if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
+ // err may be propagated from the result of calling readablestream.cancel,
+ // which might not be an error. https://github.com/nodejs/undici/issues/2009
+ isFailure = true
+ }
}
- }
- if (request.method === 'CONNECT') {
- assert(client[kRunning] === 1)
- this.upgrade = true
- return 2
- }
+ if (bytes === undefined) {
+ // 2. Otherwise, if the bytes transmission for response’s message
+ // body is done normally and stream is readable, then close
+ // stream, finalize response for fetchParams and response, and
+ // abort these in-parallel steps.
+ readableStreamClose(fetchParams.controller.controller)
- if (upgrade) {
- assert(client[kRunning] === 1)
- this.upgrade = true
- return 2
- }
+ finalizeResponse(fetchParams, response)
- assert(this.headers.length % 2 === 0)
- this.headers = []
- this.headersSize = 0
+ return
+ }
- if (this.shouldKeepAlive && client[kPipelining]) {
- const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null
+ // 5. Increase timingInfo’s decoded body size by bytes’s length.
+ timingInfo.decodedBodySize += bytes?.byteLength ?? 0
- if (keepAliveTimeout != null) {
- const timeout = Math.min(
- keepAliveTimeout - client[kKeepAliveTimeoutThreshold],
- client[kKeepAliveMaxTimeout]
- )
- if (timeout <= 0) {
- socket[kReset] = true
- } else {
- client[kKeepAliveTimeoutValue] = timeout
- }
- } else {
- client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]
+ // 6. If bytes is failure, then terminate fetchParams’s controller.
+ if (isFailure) {
+ fetchParams.controller.terminate(bytes)
+ return
}
- } else {
- // Stop more requests from being dispatched.
- socket[kReset] = true
- }
- const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false
+ // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
+ // into stream.
+ fetchParams.controller.controller.enqueue(new Uint8Array(bytes))
- if (request.aborted) {
- return -1
- }
+ // 8. If stream is errored, then terminate the ongoing fetch.
+ if (isErrored(stream)) {
+ fetchParams.controller.terminate()
+ return
+ }
- if (request.method === 'HEAD') {
- return 1
+ // 9. If stream doesn’t need more data ask the user agent to suspend
+ // the ongoing fetch.
+ if (!fetchParams.controller.controller.desiredSize) {
+ return
+ }
}
+ }
- if (statusCode < 200) {
- return 1
- }
+ // 2. If aborted, then:
+ function onAborted (reason) {
+ // 2. If fetchParams is aborted, then:
+ if (isAborted(fetchParams)) {
+ // 1. Set response’s aborted flag.
+ response.aborted = true
- if (socket[kBlocking]) {
- socket[kBlocking] = false
- resume(client)
+ // 2. If stream is readable, then error stream with the result of
+ // deserialize a serialized abort reason given fetchParams’s
+ // controller’s serialized abort reason and an
+ // implementation-defined realm.
+ if (isReadable(stream)) {
+ fetchParams.controller.controller.error(
+ fetchParams.controller.serializedAbortReason
+ )
+ }
+ } else {
+ // 3. Otherwise, if stream is readable, error stream with a TypeError.
+ if (isReadable(stream)) {
+ fetchParams.controller.controller.error(new TypeError('terminated', {
+ cause: isErrorLike(reason) ? reason : undefined
+ }))
+ }
}
- return pause ? constants.ERROR.PAUSED : 0
+ // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
+ // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
+ fetchParams.controller.connection.destroy()
}
- onBody (buf) {
- const { client, socket, statusCode, maxResponseSize } = this
+ // 20. Return response.
+ return response
- if (socket.destroyed) {
- return -1
- }
+ async function dispatch ({ body }) {
+ const url = requestCurrentURL(request)
+ /** @type {import('../..').Agent} */
+ const agent = fetchParams.controller.dispatcher
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
+ return new Promise((resolve, reject) => agent.dispatch(
+ {
+ path: url.pathname + url.search,
+ origin: url.origin,
+ method: request.method,
+ body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
+ headers: request.headersList.entries,
+ maxRedirections: 0,
+ upgrade: request.mode === 'websocket' ? 'websocket' : undefined
+ },
+ {
+ body: null,
+ abort: null,
- assert.strictEqual(this.timeoutType, TIMEOUT_BODY)
- if (this.timeout) {
- // istanbul ignore else: only for jest
- if (this.timeout.refresh) {
- this.timeout.refresh()
- }
- }
+ onConnect (abort) {
+ // TODO (fix): Do we need connection here?
+ const { connection } = fetchParams.controller
- assert(statusCode >= 200)
+ if (connection.destroyed) {
+ abort(new DOMException('The operation was aborted.', 'AbortError'))
+ } else {
+ fetchParams.controller.on('terminated', abort)
+ this.abort = connection.abort = abort
+ }
+ },
- if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) {
- util.destroy(socket, new ResponseExceededMaxSizeError())
- return -1
- }
+ onHeaders (status, headersList, resume, statusText) {
+ if (status < 200) {
+ return
+ }
- this.bytesRead += buf.length
+ let codings = []
+ let location = ''
- if (request.onData(buf) === false) {
- return constants.ERROR.PAUSED
- }
- }
+ const headers = new Headers()
- onMessageComplete () {
- const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this
+ // For H2, the headers are a plain JS object
+ // We distinguish between them and iterate accordingly
+ if (Array.isArray(headersList)) {
+ for (let n = 0; n < headersList.length; n += 2) {
+ const key = headersList[n + 0].toString('latin1')
+ const val = headersList[n + 1].toString('latin1')
+ if (key.toLowerCase() === 'content-encoding') {
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
+ // "All content-coding values are case-insensitive..."
+ codings = val.toLowerCase().split(',').map((x) => x.trim())
+ } else if (key.toLowerCase() === 'location') {
+ location = val
+ }
- if (socket.destroyed && (!statusCode || shouldKeepAlive)) {
- return -1
- }
+ headers[kHeadersList].append(key, val)
+ }
+ } else {
+ const keys = Object.keys(headersList)
+ for (const key of keys) {
+ const val = headersList[key]
+ if (key.toLowerCase() === 'content-encoding') {
+ // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
+ // "All content-coding values are case-insensitive..."
+ codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()
+ } else if (key.toLowerCase() === 'location') {
+ location = val
+ }
- if (upgrade) {
- return
- }
+ headers[kHeadersList].append(key, val)
+ }
+ }
- const request = client[kQueue][client[kRunningIdx]]
- assert(request)
+ this.body = new Readable({ read: resume })
- assert(statusCode >= 100)
+ const decoders = []
- this.statusCode = null
- this.statusText = ''
- this.bytesRead = 0
- this.contentLength = ''
- this.keepAlive = ''
- this.connection = ''
+ const willFollow = request.redirect === 'follow' &&
+ location &&
+ redirectStatusSet.has(status)
- assert(this.headers.length % 2 === 0)
- this.headers = []
- this.headersSize = 0
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
+ if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
+ for (const coding of codings) {
+ // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
+ if (coding === 'x-gzip' || coding === 'gzip') {
+ decoders.push(zlib.createGunzip({
+ // Be less strict when decoding compressed responses, since sometimes
+ // servers send slightly invalid responses that are still accepted
+ // by common browsers.
+ // Always using Z_SYNC_FLUSH is what cURL does.
+ flush: zlib.constants.Z_SYNC_FLUSH,
+ finishFlush: zlib.constants.Z_SYNC_FLUSH
+ }))
+ } else if (coding === 'deflate') {
+ decoders.push(zlib.createInflate())
+ } else if (coding === 'br') {
+ decoders.push(zlib.createBrotliDecompress())
+ } else {
+ decoders.length = 0
+ break
+ }
+ }
+ }
- if (statusCode < 200) {
- return
- }
+ resolve({
+ status,
+ statusText,
+ headersList: headers[kHeadersList],
+ body: decoders.length
+ ? pipeline(this.body, ...decoders, () => { })
+ : this.body.on('error', () => {})
+ })
- /* istanbul ignore next: should be handled by llhttp? */
- if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) {
- util.destroy(socket, new ResponseContentLengthMismatchError())
- return -1
- }
+ return true
+ },
- request.onComplete(headers)
+ onData (chunk) {
+ if (fetchParams.controller.dump) {
+ return
+ }
- client[kQueue][client[kRunningIdx]++] = null
+ // 1. If one or more bytes have been transmitted from response’s
+ // message body, then:
- if (socket[kWriting]) {
- assert.strictEqual(client[kRunning], 0)
- // Response completed before request.
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (!shouldKeepAlive) {
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (socket[kReset] && client[kRunning] === 0) {
- // Destroy socket once all requests have completed.
- // The request at the tail of the pipeline is the one
- // that requested reset and no further requests should
- // have been queued since then.
- util.destroy(socket, new InformationalError('reset'))
- return constants.ERROR.PAUSED
- } else if (client[kPipelining] === 1) {
- // We must wait a full event loop cycle to reuse this socket to make sure
- // that non-spec compliant servers are not closing the connection even if they
- // said they won't.
- setImmediate(resume, client)
- } else {
- resume(client)
- }
- }
-}
+ // 1. Let bytes be the transmitted bytes.
+ const bytes = chunk
-function onParserTimeout (parser) {
- const { socket, timeoutType, client } = parser
+ // 2. Let codings be the result of extracting header list values
+ // given `Content-Encoding` and response’s header list.
+ // See pullAlgorithm.
- /* istanbul ignore else */
- if (timeoutType === TIMEOUT_HEADERS) {
- if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) {
- assert(!parser.paused, 'cannot be paused while waiting for headers')
- util.destroy(socket, new HeadersTimeoutError())
- }
- } else if (timeoutType === TIMEOUT_BODY) {
- if (!parser.paused) {
- util.destroy(socket, new BodyTimeoutError())
- }
- } else if (timeoutType === TIMEOUT_IDLE) {
- assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue])
- util.destroy(socket, new InformationalError('socket idle timeout'))
- }
-}
+ // 3. Increase timingInfo’s encoded body size by bytes’s length.
+ timingInfo.encodedBodySize += bytes.byteLength
-function onSocketReadable () {
- const { [kParser]: parser } = this
- if (parser) {
- parser.readMore()
- }
-}
+ // 4. See pullAlgorithm...
-function onSocketError (err) {
- const { [kClient]: client, [kParser]: parser } = this
+ return this.body.push(bytes)
+ },
- assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID')
+ onComplete () {
+ if (this.abort) {
+ fetchParams.controller.off('terminated', this.abort)
+ }
- if (client[kHTTPConnVersion] !== 'h2') {
- // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded
- // to the user.
- if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so for as a valid response.
- parser.onMessageComplete()
- return
- }
- }
+ fetchParams.controller.ended = true
- this[kError] = err
+ this.body.push(null)
+ },
- onError(this[kClient], err)
-}
+ onError (error) {
+ if (this.abort) {
+ fetchParams.controller.off('terminated', this.abort)
+ }
-function onError (client, err) {
- if (
- client[kRunning] === 0 &&
- err.code !== 'UND_ERR_INFO' &&
- err.code !== 'UND_ERR_SOCKET'
- ) {
- // Error is not caused by running request and not a recoverable
- // socket error.
+ this.body?.destroy(error)
- assert(client[kPendingIdx] === client[kRunningIdx])
+ fetchParams.controller.terminate(error)
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- errorRequest(client, request, err)
- }
- assert(client[kSize] === 0)
- }
-}
+ reject(error)
+ },
-function onSocketEnd () {
- const { [kParser]: parser, [kClient]: client } = this
+ onUpgrade (status, headersList, socket) {
+ if (status !== 101) {
+ return
+ }
- if (client[kHTTPConnVersion] !== 'h2') {
- if (parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so far as a valid response.
- parser.onMessageComplete()
- return
- }
- }
+ const headers = new Headers()
- util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this)))
-}
+ for (let n = 0; n < headersList.length; n += 2) {
+ const key = headersList[n + 0].toString('latin1')
+ const val = headersList[n + 1].toString('latin1')
-function onSocketClose () {
- const { [kClient]: client, [kParser]: parser } = this
+ headers[kHeadersList].append(key, val)
+ }
- if (client[kHTTPConnVersion] === 'h1' && parser) {
- if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) {
- // We treat all incoming data so far as a valid response.
- parser.onMessageComplete()
- }
+ resolve({
+ status,
+ statusText: STATUS_CODES[status],
+ headersList: headers[kHeadersList],
+ socket
+ })
- this[kParser].destroy()
- this[kParser] = null
+ return true
+ }
+ }
+ ))
}
+}
- const err = this[kError] || new SocketError('closed', util.getSocketInfo(this))
-
- client[kSocket] = null
+module.exports = {
+ fetch,
+ Fetch,
+ fetching,
+ finalizeAndReportTiming
+}
- if (client.destroyed) {
- assert(client[kPending] === 0)
- // Fail entire queue.
- const requests = client[kQueue].splice(client[kRunningIdx])
- for (let i = 0; i < requests.length; i++) {
- const request = requests[i]
- errorRequest(client, request, err)
- }
- } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') {
- // Fail head of pipeline.
- const request = client[kQueue][client[kRunningIdx]]
- client[kQueue][client[kRunningIdx]++] = null
+/***/ }),
- errorRequest(client, request, err)
- }
+/***/ 2630:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- client[kPendingIdx] = client[kRunningIdx]
+/* globals AbortController */
- assert(client[kRunning] === 0)
- client.emit('disconnect', client[kUrl], [client], err)
- resume(client)
-}
+const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(37791)
+const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(12801)
+const { FinalizationRegistry } = __nccwpck_require__(90022)()
+const util = __nccwpck_require__(89500)
+const {
+ isValidHTTPToken,
+ sameOrigin,
+ normalizeMethod,
+ makePolicyContainer,
+ normalizeMethodRecord
+} = __nccwpck_require__(72847)
+const {
+ forbiddenMethodsSet,
+ corsSafeListedMethodsSet,
+ referrerPolicy,
+ requestRedirect,
+ requestMode,
+ requestCredentials,
+ requestCache,
+ requestDuplex
+} = __nccwpck_require__(21234)
+const { kEnumerableProperty } = util
+const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(63730)
+const { webidl } = __nccwpck_require__(94354)
+const { getGlobalOrigin } = __nccwpck_require__(62896)
+const { URLSerializer } = __nccwpck_require__(37246)
+const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
+const assert = __nccwpck_require__(42613)
+const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(24434)
-async function connect (client) {
- assert(!client[kConnecting])
- assert(!client[kSocket])
+let TransformStream = globalThis.TransformStream
- let { host, hostname, protocol, port } = client[kUrl]
+const kAbortController = Symbol('abortController')
- // Resolve ipv6
- if (hostname[0] === '[') {
- const idx = hostname.indexOf(']')
+const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
+ signal.removeEventListener('abort', abort)
+})
- assert(idx !== -1)
- const ip = hostname.substring(1, idx)
+// https://fetch.spec.whatwg.org/#request-class
+class Request {
+ // https://fetch.spec.whatwg.org/#dom-request
+ constructor (input, init = {}) {
+ if (input === kConstruct) {
+ return
+ }
- assert(net.isIP(ip))
- hostname = ip
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })
- client[kConnecting] = true
+ input = webidl.converters.RequestInfo(input)
+ init = webidl.converters.RequestInit(init)
- if (channels.beforeConnect.hasSubscribers) {
- channels.beforeConnect.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector]
- })
- }
+ // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
+ this[kRealm] = {
+ settingsObject: {
+ baseUrl: getGlobalOrigin(),
+ get origin () {
+ return this.baseUrl?.origin
+ },
+ policyContainer: makePolicyContainer()
+ }
+ }
- try {
- const socket = await new Promise((resolve, reject) => {
- client[kConnector]({
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- }, (err, socket) => {
- if (err) {
- reject(err)
- } else {
- resolve(socket)
- }
- })
- })
+ // 1. Let request be null.
+ let request = null
- if (client.destroyed) {
- util.destroy(socket.on('error', () => {}), new ClientDestroyedError())
- return
- }
+ // 2. Let fallbackMode be null.
+ let fallbackMode = null
- client[kConnecting] = false
+ // 3. Let baseURL be this’s relevant settings object’s API base URL.
+ const baseUrl = this[kRealm].settingsObject.baseUrl
- assert(socket)
+ // 4. Let signal be null.
+ let signal = null
- const isH2 = socket.alpnProtocol === 'h2'
- if (isH2) {
- if (!h2ExperimentalWarned) {
- h2ExperimentalWarned = true
- process.emitWarning('H2 support is experimental, expect them to change at any time.', {
- code: 'UNDICI-H2'
- })
+ // 5. If input is a string, then:
+ if (typeof input === 'string') {
+ // 1. Let parsedURL be the result of parsing input with baseURL.
+ // 2. If parsedURL is failure, then throw a TypeError.
+ let parsedURL
+ try {
+ parsedURL = new URL(input, baseUrl)
+ } catch (err) {
+ throw new TypeError('Failed to parse URL from ' + input, { cause: err })
}
- const session = http2.connect(client[kUrl], {
- createConnection: () => socket,
- peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams
- })
+ // 3. If parsedURL includes credentials, then throw a TypeError.
+ if (parsedURL.username || parsedURL.password) {
+ throw new TypeError(
+ 'Request cannot be constructed from a URL that includes credentials: ' +
+ input
+ )
+ }
- client[kHTTPConnVersion] = 'h2'
- session[kClient] = client
- session[kSocket] = socket
- session.on('error', onHttp2SessionError)
- session.on('frameError', onHttp2FrameError)
- session.on('end', onHttp2SessionEnd)
- session.on('goaway', onHTTP2GoAway)
- session.on('close', onSocketClose)
- session.unref()
+ // 4. Set request to a new request whose URL is parsedURL.
+ request = makeRequest({ urlList: [parsedURL] })
- client[kHTTP2Session] = session
- socket[kHTTP2Session] = session
+ // 5. Set fallbackMode to "cors".
+ fallbackMode = 'cors'
} else {
- if (!llhttpInstance) {
- llhttpInstance = await llhttpPromise
- llhttpPromise = null
- }
+ // 6. Otherwise:
- socket[kNoRef] = false
- socket[kWriting] = false
- socket[kReset] = false
- socket[kBlocking] = false
- socket[kParser] = new Parser(client, socket, llhttpInstance)
- }
+ // 7. Assert: input is a Request object.
+ assert(input instanceof Request)
- socket[kCounter] = 0
- socket[kMaxRequests] = client[kMaxRequests]
- socket[kClient] = client
- socket[kError] = null
+ // 8. Set request to input’s request.
+ request = input[kState]
- socket
- .on('error', onSocketError)
- .on('readable', onSocketReadable)
- .on('end', onSocketEnd)
- .on('close', onSocketClose)
+ // 9. Set signal to input’s signal.
+ signal = input[kSignal]
+ }
- client[kSocket] = socket
+ // 7. Let origin be this’s relevant settings object’s origin.
+ const origin = this[kRealm].settingsObject.origin
- if (channels.connected.hasSubscribers) {
- channels.connected.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector],
- socket
- })
- }
- client.emit('connect', client[kUrl], [client])
- } catch (err) {
- if (client.destroyed) {
- return
- }
+ // 8. Let window be "client".
+ let window = 'client'
- client[kConnecting] = false
+ // 9. If request’s window is an environment settings object and its origin
+ // is same origin with origin, then set window to request’s window.
+ if (
+ request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
+ sameOrigin(request.window, origin)
+ ) {
+ window = request.window
+ }
- if (channels.connectError.hasSubscribers) {
- channels.connectError.publish({
- connectParams: {
- host,
- hostname,
- protocol,
- port,
- servername: client[kServerName],
- localAddress: client[kLocalAddress]
- },
- connector: client[kConnector],
- error: err
- })
+ // 10. If init["window"] exists and is non-null, then throw a TypeError.
+ if (init.window != null) {
+ throw new TypeError(`'window' option '${window}' must be null`)
}
- if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') {
- assert(client[kRunning] === 0)
- while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) {
- const request = client[kQueue][client[kPendingIdx]++]
- errorRequest(client, request, err)
- }
- } else {
- onError(client, err)
+ // 11. If init["window"] exists, then set window to "no-window".
+ if ('window' in init) {
+ window = 'no-window'
}
- client.emit('connectionError', client[kUrl], [client], err)
- }
+ // 12. Set request to a new request with the following properties:
+ request = makeRequest({
+ // URL request’s URL.
+ // undici implementation note: this is set as the first item in request's urlList in makeRequest
+ // method request’s method.
+ method: request.method,
+ // header list A copy of request’s header list.
+ // undici implementation note: headersList is cloned in makeRequest
+ headersList: request.headersList,
+ // unsafe-request flag Set.
+ unsafeRequest: request.unsafeRequest,
+ // client This’s relevant settings object.
+ client: this[kRealm].settingsObject,
+ // window window.
+ window,
+ // priority request’s priority.
+ priority: request.priority,
+ // origin request’s origin. The propagation of the origin is only significant for navigation requests
+ // being handled by a service worker. In this scenario a request can have an origin that is different
+ // from the current client.
+ origin: request.origin,
+ // referrer request’s referrer.
+ referrer: request.referrer,
+ // referrer policy request’s referrer policy.
+ referrerPolicy: request.referrerPolicy,
+ // mode request’s mode.
+ mode: request.mode,
+ // credentials mode request’s credentials mode.
+ credentials: request.credentials,
+ // cache mode request’s cache mode.
+ cache: request.cache,
+ // redirect mode request’s redirect mode.
+ redirect: request.redirect,
+ // integrity metadata request’s integrity metadata.
+ integrity: request.integrity,
+ // keepalive request’s keepalive.
+ keepalive: request.keepalive,
+ // reload-navigation flag request’s reload-navigation flag.
+ reloadNavigation: request.reloadNavigation,
+ // history-navigation flag request’s history-navigation flag.
+ historyNavigation: request.historyNavigation,
+ // URL list A clone of request’s URL list.
+ urlList: [...request.urlList]
+ })
- resume(client)
-}
+ const initHasKey = Object.keys(init).length !== 0
-function emitDrain (client) {
- client[kNeedDrain] = 0
- client.emit('drain', client[kUrl], [client])
-}
+ // 13. If init is not empty, then:
+ if (initHasKey) {
+ // 1. If request’s mode is "navigate", then set it to "same-origin".
+ if (request.mode === 'navigate') {
+ request.mode = 'same-origin'
+ }
-function resume (client, sync) {
- if (client[kResuming] === 2) {
- return
- }
+ // 2. Unset request’s reload-navigation flag.
+ request.reloadNavigation = false
- client[kResuming] = 2
+ // 3. Unset request’s history-navigation flag.
+ request.historyNavigation = false
- _resume(client, sync)
- client[kResuming] = 0
+ // 4. Set request’s origin to "client".
+ request.origin = 'client'
- if (client[kRunningIdx] > 256) {
- client[kQueue].splice(0, client[kRunningIdx])
- client[kPendingIdx] -= client[kRunningIdx]
- client[kRunningIdx] = 0
- }
-}
+ // 5. Set request’s referrer to "client"
+ request.referrer = 'client'
-function _resume (client, sync) {
- while (true) {
- if (client.destroyed) {
- assert(client[kPending] === 0)
- return
- }
+ // 6. Set request’s referrer policy to the empty string.
+ request.referrerPolicy = ''
- if (client[kClosedResolve] && !client[kSize]) {
- client[kClosedResolve]()
- client[kClosedResolve] = null
- return
+ // 7. Set request’s URL to request’s current URL.
+ request.url = request.urlList[request.urlList.length - 1]
+
+ // 8. Set request’s URL list to « request’s URL ».
+ request.urlList = [request.url]
}
- const socket = client[kSocket]
+ // 14. If init["referrer"] exists, then:
+ if (init.referrer !== undefined) {
+ // 1. Let referrer be init["referrer"].
+ const referrer = init.referrer
- if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') {
- if (client[kSize] === 0) {
- if (!socket[kNoRef] && socket.unref) {
- socket.unref()
- socket[kNoRef] = true
+ // 2. If referrer is the empty string, then set request’s referrer to "no-referrer".
+ if (referrer === '') {
+ request.referrer = 'no-referrer'
+ } else {
+ // 1. Let parsedReferrer be the result of parsing referrer with
+ // baseURL.
+ // 2. If parsedReferrer is failure, then throw a TypeError.
+ let parsedReferrer
+ try {
+ parsedReferrer = new URL(referrer, baseUrl)
+ } catch (err) {
+ throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
}
- } else if (socket[kNoRef] && socket.ref) {
- socket.ref()
- socket[kNoRef] = false
- }
- if (client[kSize] === 0) {
- if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
- socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE)
- }
- } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) {
- if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) {
- const request = client[kQueue][client[kRunningIdx]]
- const headersTimeout = request.headersTimeout != null
- ? request.headersTimeout
- : client[kHeadersTimeout]
- socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS)
+ // 3. If one of the following is true
+ // - parsedReferrer’s scheme is "about" and path is the string "client"
+ // - parsedReferrer’s origin is not same origin with origin
+ // then set request’s referrer to "client".
+ if (
+ (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||
+ (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl))
+ ) {
+ request.referrer = 'client'
+ } else {
+ // 4. Otherwise, set request’s referrer to parsedReferrer.
+ request.referrer = parsedReferrer
}
}
}
- if (client[kBusy]) {
- client[kNeedDrain] = 2
- } else if (client[kNeedDrain] === 2) {
- if (sync) {
- client[kNeedDrain] = 1
- process.nextTick(emitDrain, client)
- } else {
- emitDrain(client)
- }
- continue
+ // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
+ // to it.
+ if (init.referrerPolicy !== undefined) {
+ request.referrerPolicy = init.referrerPolicy
}
- if (client[kPending] === 0) {
- return
+ // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
+ let mode
+ if (init.mode !== undefined) {
+ mode = init.mode
+ } else {
+ mode = fallbackMode
}
- if (client[kRunning] >= (client[kPipelining] || 1)) {
- return
+ // 17. If mode is "navigate", then throw a TypeError.
+ if (mode === 'navigate') {
+ throw webidl.errors.exception({
+ header: 'Request constructor',
+ message: 'invalid request mode navigate.'
+ })
}
- const request = client[kQueue][client[kPendingIdx]]
-
- if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) {
- if (client[kRunning] > 0) {
- return
- }
-
- client[kServerName] = request.servername
+ // 18. If mode is non-null, set request’s mode to mode.
+ if (mode != null) {
+ request.mode = mode
+ }
- if (socket && socket.servername !== request.servername) {
- util.destroy(socket, new InformationalError('servername changed'))
- return
- }
+ // 19. If init["credentials"] exists, then set request’s credentials mode
+ // to it.
+ if (init.credentials !== undefined) {
+ request.credentials = init.credentials
}
- if (client[kConnecting]) {
- return
+ // 18. If init["cache"] exists, then set request’s cache mode to it.
+ if (init.cache !== undefined) {
+ request.cache = init.cache
}
- if (!socket && !client[kHTTP2Session]) {
- connect(client)
- return
+ // 21. If request’s cache mode is "only-if-cached" and request’s mode is
+ // not "same-origin", then throw a TypeError.
+ if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
+ throw new TypeError(
+ "'only-if-cached' can be set only with 'same-origin' mode"
+ )
}
- if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) {
- return
+ // 22. If init["redirect"] exists, then set request’s redirect mode to it.
+ if (init.redirect !== undefined) {
+ request.redirect = init.redirect
}
- if (client[kRunning] > 0 && !request.idempotent) {
- // Non-idempotent request cannot be retried.
- // Ensure that no other requests are inflight and
- // could cause failure.
- return
+ // 23. If init["integrity"] exists, then set request’s integrity metadata to it.
+ if (init.integrity != null) {
+ request.integrity = String(init.integrity)
}
- if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) {
- // Don't dispatch an upgrade until all preceding requests have completed.
- // A misbehaving server might upgrade the connection before all pipelined
- // request has completed.
- return
+ // 24. If init["keepalive"] exists, then set request’s keepalive to it.
+ if (init.keepalive !== undefined) {
+ request.keepalive = Boolean(init.keepalive)
}
- if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 &&
- (util.isStream(request.body) || util.isAsyncIterable(request.body))) {
- // Request with stream or iterator body can error while other requests
- // are inflight and indirectly error those as well.
- // Ensure this doesn't happen by waiting for inflight
- // to complete before dispatching.
+ // 25. If init["method"] exists, then:
+ if (init.method !== undefined) {
+ // 1. Let method be init["method"].
+ let method = init.method
- // Request with stream or iterator body cannot be retried.
- // Ensure that no other requests are inflight and
- // could cause failure.
- return
+ // 2. If method is not a method or method is a forbidden method, then
+ // throw a TypeError.
+ if (!isValidHTTPToken(method)) {
+ throw new TypeError(`'${method}' is not a valid HTTP method.`)
+ }
+
+ if (forbiddenMethodsSet.has(method.toUpperCase())) {
+ throw new TypeError(`'${method}' HTTP method is unsupported.`)
+ }
+
+ // 3. Normalize method.
+ method = normalizeMethodRecord[method] ?? normalizeMethod(method)
+
+ // 4. Set request’s method to method.
+ request.method = method
}
- if (!request.aborted && write(client, request)) {
- client[kPendingIdx]++
- } else {
- client[kQueue].splice(client[kPendingIdx], 1)
+ // 26. If init["signal"] exists, then set signal to it.
+ if (init.signal !== undefined) {
+ signal = init.signal
}
- }
-}
-// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2
-function shouldSendContentLength (method) {
- return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT'
-}
+ // 27. Set this’s request to request.
+ this[kState] = request
-function write (client, request) {
- if (client[kHTTPConnVersion] === 'h2') {
- writeH2(client, client[kHTTP2Session], request)
- return
- }
+ // 28. Set this’s signal to a new AbortSignal object with this’s relevant
+ // Realm.
+ // TODO: could this be simplified with AbortSignal.any
+ // (https://dom.spec.whatwg.org/#dom-abortsignal-any)
+ const ac = new AbortController()
+ this[kSignal] = ac.signal
+ this[kSignal][kRealm] = this[kRealm]
- const { body, method, path, host, upgrade, headers, blocking, reset } = request
+ // 29. If signal is not null, then make this’s signal follow signal.
+ if (signal != null) {
+ if (
+ !signal ||
+ typeof signal.aborted !== 'boolean' ||
+ typeof signal.addEventListener !== 'function'
+ ) {
+ throw new TypeError(
+ "Failed to construct 'Request': member signal is not of type AbortSignal."
+ )
+ }
- // https://tools.ietf.org/html/rfc7231#section-4.3.1
- // https://tools.ietf.org/html/rfc7231#section-4.3.2
- // https://tools.ietf.org/html/rfc7231#section-4.3.5
+ if (signal.aborted) {
+ ac.abort(signal.reason)
+ } else {
+ // Keep a strong ref to ac while request object
+ // is alive. This is needed to prevent AbortController
+ // from being prematurely garbage collected.
+ // See, https://github.com/nodejs/undici/issues/1926.
+ this[kAbortController] = ac
- // Sending a payload body on a request that does not
- // expect it can cause undefined behavior on some
- // servers and corrupt connection state. Do not
- // re-use the connection for further requests.
+ const acRef = new WeakRef(ac)
+ const abort = function () {
+ const ac = acRef.deref()
+ if (ac !== undefined) {
+ ac.abort(this.reason)
+ }
+ }
- const expectsPayload = (
- method === 'PUT' ||
- method === 'POST' ||
- method === 'PATCH'
- )
+ // Third-party AbortControllers may not work with these.
+ // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
+ try {
+ // If the max amount of listeners is equal to the default, increase it
+ // This is only available in node >= v19.9.0
+ if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
+ setMaxListeners(100, signal)
+ } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
+ setMaxListeners(100, signal)
+ }
+ } catch {}
- if (body && typeof body.read === 'function') {
- // Try to read EOF in order to get length.
- body.read(0)
- }
+ util.addAbortListener(signal, abort)
+ requestFinalizer.register(ac, { signal, abort })
+ }
+ }
- const bodyLength = util.bodyLength(body)
+ // 30. Set this’s headers to a new Headers object with this’s relevant
+ // Realm, whose header list is request’s header list and guard is
+ // "request".
+ this[kHeaders] = new Headers(kConstruct)
+ this[kHeaders][kHeadersList] = request.headersList
+ this[kHeaders][kGuard] = 'request'
+ this[kHeaders][kRealm] = this[kRealm]
- let contentLength = bodyLength
+ // 31. If this’s request’s mode is "no-cors", then:
+ if (mode === 'no-cors') {
+ // 1. If this’s request’s method is not a CORS-safelisted method,
+ // then throw a TypeError.
+ if (!corsSafeListedMethodsSet.has(request.method)) {
+ throw new TypeError(
+ `'${request.method} is unsupported in no-cors mode.`
+ )
+ }
- if (contentLength === null) {
- contentLength = request.contentLength
- }
+ // 2. Set this’s headers’s guard to "request-no-cors".
+ this[kHeaders][kGuard] = 'request-no-cors'
+ }
- if (contentLength === 0 && !expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD NOT send a Content-Length header field when
- // the request message does not contain a payload body and the method
- // semantics do not anticipate such a body.
+ // 32. If init is not empty, then:
+ if (initHasKey) {
+ /** @type {HeadersList} */
+ const headersList = this[kHeaders][kHeadersList]
+ // 1. Let headers be a copy of this’s headers and its associated header
+ // list.
+ // 2. If init["headers"] exists, then set headers to init["headers"].
+ const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)
- contentLength = null
- }
+ // 3. Empty this’s headers’s header list.
+ headersList.clear()
- // https://github.com/nodejs/undici/issues/2046
- // A user agent may send a Content-Length header with 0 value, this should be allowed.
- if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) {
- if (client[kStrictContentLength]) {
- errorRequest(client, request, new RequestContentLengthMismatchError())
- return false
+ // 4. If headers is a Headers object, then for each header in its header
+ // list, append header’s name/header’s value to this’s headers.
+ if (headers instanceof HeadersList) {
+ for (const [key, val] of headers) {
+ headersList.append(key, val)
+ }
+ // Note: Copy the `set-cookie` meta-data.
+ headersList.cookies = headers.cookies
+ } else {
+ // 5. Otherwise, fill this’s headers with headers.
+ fillHeaders(this[kHeaders], headers)
+ }
}
- process.emitWarning(new RequestContentLengthMismatchError())
- }
+ // 33. Let inputBody be input’s request’s body if input is a Request
+ // object; otherwise null.
+ const inputBody = input instanceof Request ? input[kState].body : null
- const socket = client[kSocket]
+ // 34. If either init["body"] exists and is non-null or inputBody is
+ // non-null, and request’s method is `GET` or `HEAD`, then throw a
+ // TypeError.
+ if (
+ (init.body != null || inputBody != null) &&
+ (request.method === 'GET' || request.method === 'HEAD')
+ ) {
+ throw new TypeError('Request with GET/HEAD method cannot have body.')
+ }
- try {
- request.onConnect((err) => {
- if (request.aborted || request.completed) {
- return
+ // 35. Let initBody be null.
+ let initBody = null
+
+ // 36. If init["body"] exists and is non-null, then:
+ if (init.body != null) {
+ // 1. Let Content-Type be null.
+ // 2. Set initBody and Content-Type to the result of extracting
+ // init["body"], with keepalive set to request’s keepalive.
+ const [extractedBody, contentType] = extractBody(
+ init.body,
+ request.keepalive
+ )
+ initBody = extractedBody
+
+ // 3, If Content-Type is non-null and this’s headers’s header list does
+ // not contain `Content-Type`, then append `Content-Type`/Content-Type to
+ // this’s headers.
+ if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) {
+ this[kHeaders].append('content-type', contentType)
}
+ }
- errorRequest(client, request, err || new RequestAbortedError())
+ // 37. Let inputOrInitBody be initBody if it is non-null; otherwise
+ // inputBody.
+ const inputOrInitBody = initBody ?? inputBody
- util.destroy(socket, new InformationalError('aborted'))
- })
- } catch (err) {
- errorRequest(client, request, err)
- }
+ // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is
+ // null, then:
+ if (inputOrInitBody != null && inputOrInitBody.source == null) {
+ // 1. If initBody is non-null and init["duplex"] does not exist,
+ // then throw a TypeError.
+ if (initBody != null && init.duplex == null) {
+ throw new TypeError('RequestInit: duplex option is required when sending a body.')
+ }
- if (request.aborted) {
- return false
- }
+ // 2. If this’s request’s mode is neither "same-origin" nor "cors",
+ // then throw a TypeError.
+ if (request.mode !== 'same-origin' && request.mode !== 'cors') {
+ throw new TypeError(
+ 'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
+ )
+ }
- if (method === 'HEAD') {
- // https://github.com/mcollina/undici/issues/258
- // Close after a HEAD request to interop with misbehaving servers
- // that may send a body in the response.
+ // 3. Set this’s request’s use-CORS-preflight flag.
+ request.useCORSPreflightFlag = true
+ }
- socket[kReset] = true
- }
+ // 39. Let finalBody be inputOrInitBody.
+ let finalBody = inputOrInitBody
- if (upgrade || method === 'CONNECT') {
- // On CONNECT or upgrade, block pipeline from dispatching further
- // requests on this connection.
+ // 40. If initBody is null and inputBody is non-null, then:
+ if (initBody == null && inputBody != null) {
+ // 1. If input is unusable, then throw a TypeError.
+ if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {
+ throw new TypeError(
+ 'Cannot construct a Request with a Request object that has already been used.'
+ )
+ }
- socket[kReset] = true
- }
+ // 2. Set finalBody to the result of creating a proxy for inputBody.
+ if (!TransformStream) {
+ TransformStream = (__nccwpck_require__(63774).TransformStream)
+ }
- if (reset != null) {
- socket[kReset] = reset
- }
+ // https://streams.spec.whatwg.org/#readablestream-create-a-proxy
+ const identityTransform = new TransformStream()
+ inputBody.stream.pipeThrough(identityTransform)
+ finalBody = {
+ source: inputBody.source,
+ length: inputBody.length,
+ stream: identityTransform.readable
+ }
+ }
- if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) {
- socket[kReset] = true
+ // 41. Set this’s request’s body to finalBody.
+ this[kState].body = finalBody
}
- if (blocking) {
- socket[kBlocking] = true
+ // Returns request’s HTTP method, which is "GET" by default.
+ get method () {
+ webidl.brandCheck(this, Request)
+
+ // The method getter steps are to return this’s request’s method.
+ return this[kState].method
}
- let header = `${method} ${path} HTTP/1.1\r\n`
+ // Returns the URL of request as a string.
+ get url () {
+ webidl.brandCheck(this, Request)
- if (typeof host === 'string') {
- header += `host: ${host}\r\n`
- } else {
- header += client[kHostHeader]
+ // The url getter steps are to return this’s request’s URL, serialized.
+ return URLSerializer(this[kState].url)
}
- if (upgrade) {
- header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`
- } else if (client[kPipelining] && !socket[kReset]) {
- header += 'connection: keep-alive\r\n'
- } else {
- header += 'connection: close\r\n'
- }
+ // Returns a Headers object consisting of the headers associated with request.
+ // Note that headers added in the network layer by the user agent will not
+ // be accounted for in this object, e.g., the "Host" header.
+ get headers () {
+ webidl.brandCheck(this, Request)
- if (headers) {
- header += headers
+ // The headers getter steps are to return this’s headers.
+ return this[kHeaders]
}
- if (channels.sendHeaders.hasSubscribers) {
- channels.sendHeaders.publish({ request, headers: header, socket })
- }
+ // Returns the kind of resource requested by request, e.g., "document"
+ // or "script".
+ get destination () {
+ webidl.brandCheck(this, Request)
- /* istanbul ignore else: assertion */
- if (!body || bodyLength === 0) {
- if (contentLength === 0) {
- socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
- } else {
- assert(contentLength === null, 'no body must not have content length')
- socket.write(`${header}\r\n`, 'latin1')
- }
- request.onRequestSent()
- } else if (util.isBuffer(body)) {
- assert(contentLength === body.byteLength, 'buffer body must have content length')
+ // The destination getter are to return this’s request’s destination.
+ return this[kState].destination
+ }
- socket.cork()
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- socket.write(body)
- socket.uncork()
- request.onBodySent(body)
- request.onRequestSent()
- if (!expectsPayload) {
- socket[kReset] = true
- }
- } else if (util.isBlobLike(body)) {
- if (typeof body.stream === 'function') {
- writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload })
- } else {
- writeBlob({ body, client, request, socket, contentLength, header, expectsPayload })
+ // Returns the referrer of request. Its value can be a same-origin URL if
+ // explicitly set in init, the empty string to indicate no referrer, and
+ // "about:client" when defaulting to the global’s default. This is used
+ // during fetching to determine the value of the `Referer` header of the
+ // request being made.
+ get referrer () {
+ webidl.brandCheck(this, Request)
+
+ // 1. If this’s request’s referrer is "no-referrer", then return the
+ // empty string.
+ if (this[kState].referrer === 'no-referrer') {
+ return ''
}
- } else if (util.isStream(body)) {
- writeStream({ body, client, request, socket, contentLength, header, expectsPayload })
- } else if (util.isIterable(body)) {
- writeIterable({ body, client, request, socket, contentLength, header, expectsPayload })
- } else {
- assert(false)
- }
- return true
-}
+ // 2. If this’s request’s referrer is "client", then return
+ // "about:client".
+ if (this[kState].referrer === 'client') {
+ return 'about:client'
+ }
-function writeH2 (client, session, request) {
- const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request
+ // Return this’s request’s referrer, serialized.
+ return this[kState].referrer.toString()
+ }
- let headers
- if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim())
- else headers = reqHeaders
+ // Returns the referrer policy associated with request.
+ // This is used during fetching to compute the value of the request’s
+ // referrer.
+ get referrerPolicy () {
+ webidl.brandCheck(this, Request)
- if (upgrade) {
- errorRequest(client, request, new Error('Upgrade not supported for H2'))
- return false
+ // The referrerPolicy getter steps are to return this’s request’s referrer policy.
+ return this[kState].referrerPolicy
}
- try {
- // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event?
- request.onConnect((err) => {
- if (request.aborted || request.completed) {
- return
- }
+ // Returns the mode associated with request, which is a string indicating
+ // whether the request will use CORS, or will be restricted to same-origin
+ // URLs.
+ get mode () {
+ webidl.brandCheck(this, Request)
- errorRequest(client, request, err || new RequestAbortedError())
- })
- } catch (err) {
- errorRequest(client, request, err)
+ // The mode getter steps are to return this’s request’s mode.
+ return this[kState].mode
}
- if (request.aborted) {
- return false
+ // Returns the credentials mode associated with request,
+ // which is a string indicating whether credentials will be sent with the
+ // request always, never, or only when sent to a same-origin URL.
+ get credentials () {
+ // The credentials getter steps are to return this’s request’s credentials mode.
+ return this[kState].credentials
}
- /** @type {import('node:http2').ClientHttp2Stream} */
- let stream
- const h2State = client[kHTTP2SessionState]
+ // Returns the cache mode associated with request,
+ // which is a string indicating how the request will
+ // interact with the browser’s cache when fetching.
+ get cache () {
+ webidl.brandCheck(this, Request)
- headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]
- headers[HTTP2_HEADER_METHOD] = method
+ // The cache getter steps are to return this’s request’s cache mode.
+ return this[kState].cache
+ }
- if (method === 'CONNECT') {
- session.ref()
- // we are already connected, streams are pending, first request
- // will create a new stream. We trigger a request to create the stream and wait until
- // `ready` event is triggered
- // We disabled endStream to allow the user to write to the stream
- stream = session.request(headers, { endStream: false, signal })
+ // Returns the redirect mode associated with request,
+ // which is a string indicating how redirects for the
+ // request will be handled during fetching. A request
+ // will follow redirects by default.
+ get redirect () {
+ webidl.brandCheck(this, Request)
- if (stream.id && !stream.pending) {
- request.onUpgrade(null, null, stream)
- ++h2State.openStreams
- } else {
- stream.once('ready', () => {
- request.onUpgrade(null, null, stream)
- ++h2State.openStreams
- })
- }
+ // The redirect getter steps are to return this’s request’s redirect mode.
+ return this[kState].redirect
+ }
- stream.once('close', () => {
- h2State.openStreams -= 1
- // TODO(HTTP/2): unref only if current streams count is 0
- if (h2State.openStreams === 0) session.unref()
- })
+ // Returns request’s subresource integrity metadata, which is a
+ // cryptographic hash of the resource being fetched. Its value
+ // consists of multiple hashes separated by whitespace. [SRI]
+ get integrity () {
+ webidl.brandCheck(this, Request)
- return true
+ // The integrity getter steps are to return this’s request’s integrity
+ // metadata.
+ return this[kState].integrity
}
- // https://tools.ietf.org/html/rfc7540#section-8.3
- // :path and :scheme headers must be omited when sending CONNECT
+ // Returns a boolean indicating whether or not request can outlive the
+ // global in which it was created.
+ get keepalive () {
+ webidl.brandCheck(this, Request)
- headers[HTTP2_HEADER_PATH] = path
- headers[HTTP2_HEADER_SCHEME] = 'https'
+ // The keepalive getter steps are to return this’s request’s keepalive.
+ return this[kState].keepalive
+ }
- // https://tools.ietf.org/html/rfc7231#section-4.3.1
- // https://tools.ietf.org/html/rfc7231#section-4.3.2
- // https://tools.ietf.org/html/rfc7231#section-4.3.5
+ // Returns a boolean indicating whether or not request is for a reload
+ // navigation.
+ get isReloadNavigation () {
+ webidl.brandCheck(this, Request)
- // Sending a payload body on a request that does not
- // expect it can cause undefined behavior on some
- // servers and corrupt connection state. Do not
- // re-use the connection for further requests.
+ // The isReloadNavigation getter steps are to return true if this’s
+ // request’s reload-navigation flag is set; otherwise false.
+ return this[kState].reloadNavigation
+ }
- const expectsPayload = (
- method === 'PUT' ||
- method === 'POST' ||
- method === 'PATCH'
- )
+ // Returns a boolean indicating whether or not request is for a history
+ // navigation (a.k.a. back-foward navigation).
+ get isHistoryNavigation () {
+ webidl.brandCheck(this, Request)
- if (body && typeof body.read === 'function') {
- // Try to read EOF in order to get length.
- body.read(0)
+ // The isHistoryNavigation getter steps are to return true if this’s request’s
+ // history-navigation flag is set; otherwise false.
+ return this[kState].historyNavigation
}
- let contentLength = util.bodyLength(body)
+ // Returns the signal associated with request, which is an AbortSignal
+ // object indicating whether or not request has been aborted, and its
+ // abort event handler.
+ get signal () {
+ webidl.brandCheck(this, Request)
- if (contentLength == null) {
- contentLength = request.contentLength
+ // The signal getter steps are to return this’s signal.
+ return this[kSignal]
}
- if (contentLength === 0 || !expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD NOT send a Content-Length header field when
- // the request message does not contain a payload body and the method
- // semantics do not anticipate such a body.
+ get body () {
+ webidl.brandCheck(this, Request)
- contentLength = null
+ return this[kState].body ? this[kState].body.stream : null
}
- // https://github.com/nodejs/undici/issues/2046
- // A user agent may send a Content-Length header with 0 value, this should be allowed.
- if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) {
- if (client[kStrictContentLength]) {
- errorRequest(client, request, new RequestContentLengthMismatchError())
- return false
- }
+ get bodyUsed () {
+ webidl.brandCheck(this, Request)
- process.emitWarning(new RequestContentLengthMismatchError())
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
}
- if (contentLength != null) {
- assert(body, 'no body must not have content length')
- headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`
- }
+ get duplex () {
+ webidl.brandCheck(this, Request)
- session.ref()
+ return 'half'
+ }
- const shouldEndStream = method === 'GET' || method === 'HEAD'
- if (expectContinue) {
- headers[HTTP2_HEADER_EXPECT] = '100-continue'
- stream = session.request(headers, { endStream: shouldEndStream, signal })
+ // Returns a clone of request.
+ clone () {
+ webidl.brandCheck(this, Request)
- stream.once('continue', writeBodyH2)
- } else {
- stream = session.request(headers, {
- endStream: shouldEndStream,
- signal
- })
- writeBodyH2()
- }
+ // 1. If this is unusable, then throw a TypeError.
+ if (this.bodyUsed || this.body?.locked) {
+ throw new TypeError('unusable')
+ }
- // Increment counter as we have new several streams open
- ++h2State.openStreams
+ // 2. Let clonedRequest be the result of cloning this’s request.
+ const clonedRequest = cloneRequest(this[kState])
- stream.once('response', headers => {
- const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers
+ // 3. Let clonedRequestObject be the result of creating a Request object,
+ // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
+ const clonedRequestObject = new Request(kConstruct)
+ clonedRequestObject[kState] = clonedRequest
+ clonedRequestObject[kRealm] = this[kRealm]
+ clonedRequestObject[kHeaders] = new Headers(kConstruct)
+ clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList
+ clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]
+ clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]
- if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) {
- stream.pause()
+ // 4. Make clonedRequestObject’s signal follow this’s signal.
+ const ac = new AbortController()
+ if (this.signal.aborted) {
+ ac.abort(this.signal.reason)
+ } else {
+ util.addAbortListener(
+ this.signal,
+ () => {
+ ac.abort(this.signal.reason)
+ }
+ )
}
- })
+ clonedRequestObject[kSignal] = ac.signal
- stream.once('end', () => {
- request.onComplete([])
- })
+ // 4. Return clonedRequestObject.
+ return clonedRequestObject
+ }
+}
- stream.on('data', (chunk) => {
- if (request.onData(chunk) === false) {
- stream.pause()
- }
- })
+mixinBody(Request)
- stream.once('close', () => {
- h2State.openStreams -= 1
- // TODO(HTTP/2): unref only if current streams count is 0
- if (h2State.openStreams === 0) {
- session.unref()
- }
- })
+function makeRequest (init) {
+ // https://fetch.spec.whatwg.org/#requests
+ const request = {
+ method: 'GET',
+ localURLsOnly: false,
+ unsafeRequest: false,
+ body: null,
+ client: null,
+ reservedClient: null,
+ replacesClientId: '',
+ window: 'client',
+ keepalive: false,
+ serviceWorkers: 'all',
+ initiator: '',
+ destination: '',
+ priority: null,
+ origin: 'client',
+ policyContainer: 'client',
+ referrer: 'client',
+ referrerPolicy: '',
+ mode: 'no-cors',
+ useCORSPreflightFlag: false,
+ credentials: 'same-origin',
+ useCredentials: false,
+ cache: 'default',
+ redirect: 'follow',
+ integrity: '',
+ cryptoGraphicsNonceMetadata: '',
+ parserMetadata: '',
+ reloadNavigation: false,
+ historyNavigation: false,
+ userActivation: false,
+ taintedOrigin: false,
+ redirectCount: 0,
+ responseTainting: 'basic',
+ preventNoCacheCacheControlHeaderModification: false,
+ done: false,
+ timingAllowFailed: false,
+ ...init,
+ headersList: init.headersList
+ ? new HeadersList(init.headersList)
+ : new HeadersList()
+ }
+ request.url = request.urlList[0]
+ return request
+}
- stream.once('error', function (err) {
- if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
- h2State.streams -= 1
- util.destroy(stream, err)
- }
- })
+// https://fetch.spec.whatwg.org/#concept-request-clone
+function cloneRequest (request) {
+ // To clone a request request, run these steps:
- stream.once('frameError', (type, code) => {
- const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`)
- errorRequest(client, request, err)
+ // 1. Let newRequest be a copy of request, except for its body.
+ const newRequest = makeRequest({ ...request, body: null })
- if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) {
- h2State.streams -= 1
- util.destroy(stream, err)
- }
- })
+ // 2. If request’s body is non-null, set newRequest’s body to the
+ // result of cloning request’s body.
+ if (request.body != null) {
+ newRequest.body = cloneBody(request.body)
+ }
- // stream.on('aborted', () => {
- // // TODO(HTTP/2): Support aborted
- // })
+ // 3. Return newRequest.
+ return newRequest
+}
- // stream.on('timeout', () => {
- // // TODO(HTTP/2): Support timeout
- // })
+Object.defineProperties(Request.prototype, {
+ method: kEnumerableProperty,
+ url: kEnumerableProperty,
+ headers: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ clone: kEnumerableProperty,
+ signal: kEnumerableProperty,
+ duplex: kEnumerableProperty,
+ destination: kEnumerableProperty,
+ body: kEnumerableProperty,
+ bodyUsed: kEnumerableProperty,
+ isHistoryNavigation: kEnumerableProperty,
+ isReloadNavigation: kEnumerableProperty,
+ keepalive: kEnumerableProperty,
+ integrity: kEnumerableProperty,
+ cache: kEnumerableProperty,
+ credentials: kEnumerableProperty,
+ attribute: kEnumerableProperty,
+ referrerPolicy: kEnumerableProperty,
+ referrer: kEnumerableProperty,
+ mode: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'Request',
+ configurable: true
+ }
+})
- // stream.on('push', headers => {
- // // TODO(HTTP/2): Suppor push
- // })
+webidl.converters.Request = webidl.interfaceConverter(
+ Request
+)
- // stream.on('trailers', headers => {
- // // TODO(HTTP/2): Support trailers
- // })
+// https://fetch.spec.whatwg.org/#requestinfo
+webidl.converters.RequestInfo = function (V) {
+ if (typeof V === 'string') {
+ return webidl.converters.USVString(V)
+ }
- return true
+ if (V instanceof Request) {
+ return webidl.converters.Request(V)
+ }
- function writeBodyH2 () {
- /* istanbul ignore else: assertion */
- if (!body) {
- request.onRequestSent()
- } else if (util.isBuffer(body)) {
- assert(contentLength === body.byteLength, 'buffer body must have content length')
- stream.cork()
- stream.write(body)
- stream.uncork()
- stream.end()
- request.onBodySent(body)
- request.onRequestSent()
- } else if (util.isBlobLike(body)) {
- if (typeof body.stream === 'function') {
- writeIterable({
- client,
- request,
- contentLength,
- h2stream: stream,
- expectsPayload,
- body: body.stream(),
- socket: client[kSocket],
- header: ''
- })
- } else {
- writeBlob({
- body,
- client,
- request,
- contentLength,
- expectsPayload,
- h2stream: stream,
- header: '',
- socket: client[kSocket]
- })
- }
- } else if (util.isStream(body)) {
- writeStream({
- body,
- client,
- request,
- contentLength,
- expectsPayload,
- socket: client[kSocket],
- h2stream: stream,
- header: ''
- })
- } else if (util.isIterable(body)) {
- writeIterable({
- body,
- client,
- request,
- contentLength,
- expectsPayload,
- header: '',
- h2stream: stream,
- socket: client[kSocket]
- })
- } else {
- assert(false)
- }
+ return webidl.converters.USVString(V)
+}
+
+webidl.converters.AbortSignal = webidl.interfaceConverter(
+ AbortSignal
+)
+
+// https://fetch.spec.whatwg.org/#requestinit
+webidl.converters.RequestInit = webidl.dictionaryConverter([
+ {
+ key: 'method',
+ converter: webidl.converters.ByteString
+ },
+ {
+ key: 'headers',
+ converter: webidl.converters.HeadersInit
+ },
+ {
+ key: 'body',
+ converter: webidl.nullableConverter(
+ webidl.converters.BodyInit
+ )
+ },
+ {
+ key: 'referrer',
+ converter: webidl.converters.USVString
+ },
+ {
+ key: 'referrerPolicy',
+ converter: webidl.converters.DOMString,
+ // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
+ allowedValues: referrerPolicy
+ },
+ {
+ key: 'mode',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#concept-request-mode
+ allowedValues: requestMode
+ },
+ {
+ key: 'credentials',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestcredentials
+ allowedValues: requestCredentials
+ },
+ {
+ key: 'cache',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestcache
+ allowedValues: requestCache
+ },
+ {
+ key: 'redirect',
+ converter: webidl.converters.DOMString,
+ // https://fetch.spec.whatwg.org/#requestredirect
+ allowedValues: requestRedirect
+ },
+ {
+ key: 'integrity',
+ converter: webidl.converters.DOMString
+ },
+ {
+ key: 'keepalive',
+ converter: webidl.converters.boolean
+ },
+ {
+ key: 'signal',
+ converter: webidl.nullableConverter(
+ (signal) => webidl.converters.AbortSignal(
+ signal,
+ { strict: false }
+ )
+ )
+ },
+ {
+ key: 'window',
+ converter: webidl.converters.any
+ },
+ {
+ key: 'duplex',
+ converter: webidl.converters.DOMString,
+ allowedValues: requestDuplex
}
-}
+])
-function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined')
+module.exports = { Request, makeRequest }
- if (client[kHTTPConnVersion] === 'h2') {
- // For HTTP/2, is enough to pipe the stream
- const pipe = pipeline(
- body,
- h2stream,
- (err) => {
- if (err) {
- util.destroy(body, err)
- util.destroy(h2stream, err)
- } else {
- request.onRequestSent()
- }
- }
- )
- pipe.on('data', onPipeData)
- pipe.once('end', () => {
- pipe.removeListener('data', onPipeData)
- util.destroy(pipe)
- })
+/***/ }),
- function onPipeData (chunk) {
- request.onBodySent(chunk)
- }
+/***/ 89928:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return
- }
- let finished = false
- const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
+const { Headers, HeadersList, fill } = __nccwpck_require__(12801)
+const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(37791)
+const util = __nccwpck_require__(89500)
+const { kEnumerableProperty } = util
+const {
+ isValidReasonPhrase,
+ isCancelled,
+ isAborted,
+ isBlobLike,
+ serializeJavascriptValueToJSONString,
+ isErrorLike,
+ isomorphicEncode
+} = __nccwpck_require__(72847)
+const {
+ redirectStatusSet,
+ nullBodyStatus,
+ DOMException
+} = __nccwpck_require__(21234)
+const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
+const { webidl } = __nccwpck_require__(94354)
+const { FormData } = __nccwpck_require__(47453)
+const { getGlobalOrigin } = __nccwpck_require__(62896)
+const { URLSerializer } = __nccwpck_require__(37246)
+const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
+const assert = __nccwpck_require__(42613)
+const { types } = __nccwpck_require__(39023)
- const onData = function (chunk) {
- if (finished) {
- return
- }
+const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(63774).ReadableStream)
+const textEncoder = new TextEncoder('utf-8')
- try {
- if (!writer.write(chunk) && this.pause) {
- this.pause()
- }
- } catch (err) {
- util.destroy(this, err)
- }
- }
- const onDrain = function () {
- if (finished) {
- return
- }
+// https://fetch.spec.whatwg.org/#response-class
+class Response {
+ // Creates network error Response.
+ static error () {
+ // TODO
+ const relevantRealm = { settingsObject: {} }
- if (body.resume) {
- body.resume()
- }
- }
- const onAbort = function () {
- if (finished) {
- return
- }
- const err = new RequestAbortedError()
- queueMicrotask(() => onFinished(err))
+ // The static error() method steps are to return the result of creating a
+ // Response object, given a new network error, "immutable", and this’s
+ // relevant Realm.
+ const responseObject = new Response()
+ responseObject[kState] = makeNetworkError()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
+ return responseObject
}
- const onFinished = function (err) {
- if (finished) {
- return
- }
- finished = true
+ // https://fetch.spec.whatwg.org/#dom-response-json
+ static json (data, init = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })
- assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1))
+ if (init !== null) {
+ init = webidl.converters.ResponseInit(init)
+ }
- socket
- .off('drain', onDrain)
- .off('error', onFinished)
+ // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
+ const bytes = textEncoder.encode(
+ serializeJavascriptValueToJSONString(data)
+ )
- body
- .removeListener('data', onData)
- .removeListener('end', onFinished)
- .removeListener('error', onFinished)
- .removeListener('close', onAbort)
+ // 2. Let body be the result of extracting bytes.
+ const body = extractBody(bytes)
- if (!err) {
- try {
- writer.end()
- } catch (er) {
- err = er
- }
- }
+ // 3. Let responseObject be the result of creating a Response object, given a new response,
+ // "response", and this’s relevant Realm.
+ const relevantRealm = { settingsObject: {} }
+ const responseObject = new Response()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kGuard] = 'response'
+ responseObject[kHeaders][kRealm] = relevantRealm
- writer.destroy(err)
+ // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
+ initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
- if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) {
- util.destroy(body, err)
- } else {
- util.destroy(body)
- }
+ // 5. Return responseObject.
+ return responseObject
}
- body
- .on('data', onData)
- .on('end', onFinished)
- .on('error', onFinished)
- .on('close', onAbort)
-
- if (body.resume) {
- body.resume()
- }
+ // Creates a redirect Response that redirects to url with status status.
+ static redirect (url, status = 302) {
+ const relevantRealm = { settingsObject: {} }
- socket
- .on('drain', onDrain)
- .on('error', onFinished)
-}
+ webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })
-async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
- assert(contentLength === body.size, 'blob body must have content length')
+ url = webidl.converters.USVString(url)
+ status = webidl.converters['unsigned short'](status)
- const isH2 = client[kHTTPConnVersion] === 'h2'
- try {
- if (contentLength != null && contentLength !== body.size) {
- throw new RequestContentLengthMismatchError()
+ // 1. Let parsedURL be the result of parsing url with current settings
+ // object’s API base URL.
+ // 2. If parsedURL is failure, then throw a TypeError.
+ // TODO: base-URL?
+ let parsedURL
+ try {
+ parsedURL = new URL(url, getGlobalOrigin())
+ } catch (err) {
+ throw Object.assign(new TypeError('Failed to parse URL from ' + url), {
+ cause: err
+ })
}
- const buffer = Buffer.from(await body.arrayBuffer())
-
- if (isH2) {
- h2stream.cork()
- h2stream.write(buffer)
- h2stream.uncork()
- } else {
- socket.cork()
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- socket.write(buffer)
- socket.uncork()
+ // 3. If status is not a redirect status, then throw a RangeError.
+ if (!redirectStatusSet.has(status)) {
+ throw new RangeError('Invalid status code ' + status)
}
- request.onBodySent(buffer)
- request.onRequestSent()
+ // 4. Let responseObject be the result of creating a Response object,
+ // given a new response, "immutable", and this’s relevant Realm.
+ const responseObject = new Response()
+ responseObject[kRealm] = relevantRealm
+ responseObject[kHeaders][kGuard] = 'immutable'
+ responseObject[kHeaders][kRealm] = relevantRealm
- if (!expectsPayload) {
- socket[kReset] = true
- }
+ // 5. Set responseObject’s response’s status to status.
+ responseObject[kState].status = status
- resume(client)
- } catch (err) {
- util.destroy(isH2 ? h2stream : socket, err)
- }
-}
+ // 6. Let value be parsedURL, serialized and isomorphic encoded.
+ const value = isomorphicEncode(URLSerializer(parsedURL))
-async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) {
- assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined')
+ // 7. Append `Location`/value to responseObject’s response’s header list.
+ responseObject[kState].headersList.append('location', value)
- let callback = null
- function onDrain () {
- if (callback) {
- const cb = callback
- callback = null
- cb()
- }
+ // 8. Return responseObject.
+ return responseObject
}
- const waitForDrain = () => new Promise((resolve, reject) => {
- assert(callback === null)
-
- if (socket[kError]) {
- reject(socket[kError])
- } else {
- callback = resolve
+ // https://fetch.spec.whatwg.org/#dom-response
+ constructor (body = null, init = {}) {
+ if (body !== null) {
+ body = webidl.converters.BodyInit(body)
}
- })
-
- if (client[kHTTPConnVersion] === 'h2') {
- h2stream
- .on('close', onDrain)
- .on('drain', onDrain)
- try {
- // It's up to the user to somehow abort the async iterable.
- for await (const chunk of body) {
- if (socket[kError]) {
- throw socket[kError]
- }
+ init = webidl.converters.ResponseInit(init)
- const res = h2stream.write(chunk)
- request.onBodySent(chunk)
- if (!res) {
- await waitForDrain()
- }
- }
- } catch (err) {
- h2stream.destroy(err)
- } finally {
- request.onRequestSent()
- h2stream.end()
- h2stream
- .off('close', onDrain)
- .off('drain', onDrain)
- }
+ // TODO
+ this[kRealm] = { settingsObject: {} }
- return
- }
+ // 1. Set this’s response to a new response.
+ this[kState] = makeResponse({})
- socket
- .on('close', onDrain)
- .on('drain', onDrain)
+ // 2. Set this’s headers to a new Headers object with this’s relevant
+ // Realm, whose header list is this’s response’s header list and guard
+ // is "response".
+ this[kHeaders] = new Headers(kConstruct)
+ this[kHeaders][kGuard] = 'response'
+ this[kHeaders][kHeadersList] = this[kState].headersList
+ this[kHeaders][kRealm] = this[kRealm]
- const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header })
- try {
- // It's up to the user to somehow abort the async iterable.
- for await (const chunk of body) {
- if (socket[kError]) {
- throw socket[kError]
- }
+ // 3. Let bodyWithType be null.
+ let bodyWithType = null
- if (!writer.write(chunk)) {
- await waitForDrain()
- }
+ // 4. If body is non-null, then set bodyWithType to the result of extracting body.
+ if (body != null) {
+ const [extractedBody, type] = extractBody(body)
+ bodyWithType = { body: extractedBody, type }
}
- writer.end()
- } catch (err) {
- writer.destroy(err)
- } finally {
- socket
- .off('close', onDrain)
- .off('drain', onDrain)
+ // 5. Perform initialize a response given this, init, and bodyWithType.
+ initializeResponse(this, init, bodyWithType)
}
-}
-class AsyncWriter {
- constructor ({ socket, request, contentLength, client, expectsPayload, header }) {
- this.socket = socket
- this.request = request
- this.contentLength = contentLength
- this.client = client
- this.bytesWritten = 0
- this.expectsPayload = expectsPayload
- this.header = header
+ // Returns response’s type, e.g., "cors".
+ get type () {
+ webidl.brandCheck(this, Response)
- socket[kWriting] = true
+ // The type getter steps are to return this’s response’s type.
+ return this[kState].type
}
- write (chunk) {
- const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this
+ // Returns response’s URL, if it has one; otherwise the empty string.
+ get url () {
+ webidl.brandCheck(this, Response)
- if (socket[kError]) {
- throw socket[kError]
- }
+ const urlList = this[kState].urlList
- if (socket.destroyed) {
- return false
- }
+ // The url getter steps are to return the empty string if this’s
+ // response’s URL is null; otherwise this’s response’s URL,
+ // serialized with exclude fragment set to true.
+ const url = urlList[urlList.length - 1] ?? null
- const len = Buffer.byteLength(chunk)
- if (!len) {
- return true
+ if (url === null) {
+ return ''
}
- // We should defer writing chunks.
- if (contentLength !== null && bytesWritten + len > contentLength) {
- if (client[kStrictContentLength]) {
- throw new RequestContentLengthMismatchError()
- }
+ return URLSerializer(url, true)
+ }
- process.emitWarning(new RequestContentLengthMismatchError())
- }
+ // Returns whether response was obtained through a redirect.
+ get redirected () {
+ webidl.brandCheck(this, Response)
- socket.cork()
+ // The redirected getter steps are to return true if this’s response’s URL
+ // list has more than one item; otherwise false.
+ return this[kState].urlList.length > 1
+ }
- if (bytesWritten === 0) {
- if (!expectsPayload) {
- socket[kReset] = true
- }
+ // Returns response’s status.
+ get status () {
+ webidl.brandCheck(this, Response)
- if (contentLength === null) {
- socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1')
- } else {
- socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1')
- }
- }
+ // The status getter steps are to return this’s response’s status.
+ return this[kState].status
+ }
- if (contentLength === null) {
- socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1')
- }
+ // Returns whether response’s status is an ok status.
+ get ok () {
+ webidl.brandCheck(this, Response)
- this.bytesWritten += len
+ // The ok getter steps are to return true if this’s response’s status is an
+ // ok status; otherwise false.
+ return this[kState].status >= 200 && this[kState].status <= 299
+ }
- const ret = socket.write(chunk)
+ // Returns response’s status message.
+ get statusText () {
+ webidl.brandCheck(this, Response)
- socket.uncork()
+ // The statusText getter steps are to return this’s response’s status
+ // message.
+ return this[kState].statusText
+ }
- request.onBodySent(chunk)
+ // Returns response’s headers as Headers.
+ get headers () {
+ webidl.brandCheck(this, Response)
- if (!ret) {
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
- // istanbul ignore else: only for jest
- if (socket[kParser].timeout.refresh) {
- socket[kParser].timeout.refresh()
- }
- }
- }
+ // The headers getter steps are to return this’s headers.
+ return this[kHeaders]
+ }
- return ret
+ get body () {
+ webidl.brandCheck(this, Response)
+
+ return this[kState].body ? this[kState].body.stream : null
}
- end () {
- const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this
- request.onRequestSent()
+ get bodyUsed () {
+ webidl.brandCheck(this, Response)
- socket[kWriting] = false
+ return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
+ }
- if (socket[kError]) {
- throw socket[kError]
- }
+ // Returns a clone of response.
+ clone () {
+ webidl.brandCheck(this, Response)
- if (socket.destroyed) {
- return
+ // 1. If this is unusable, then throw a TypeError.
+ if (this.bodyUsed || (this.body && this.body.locked)) {
+ throw webidl.errors.exception({
+ header: 'Response.clone',
+ message: 'Body has already been consumed.'
+ })
}
- if (bytesWritten === 0) {
- if (expectsPayload) {
- // https://tools.ietf.org/html/rfc7230#section-3.3.2
- // A user agent SHOULD send a Content-Length in a request message when
- // no Transfer-Encoding is sent and the request method defines a meaning
- // for an enclosed payload body.
+ // 2. Let clonedResponse be the result of cloning this’s response.
+ const clonedResponse = cloneResponse(this[kState])
- socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1')
- } else {
- socket.write(`${header}\r\n`, 'latin1')
- }
- } else if (contentLength === null) {
- socket.write('\r\n0\r\n\r\n', 'latin1')
- }
+ // 3. Return the result of creating a Response object, given
+ // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
+ const clonedResponseObject = new Response()
+ clonedResponseObject[kState] = clonedResponse
+ clonedResponseObject[kRealm] = this[kRealm]
+ clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList
+ clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]
+ clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]
+
+ return clonedResponseObject
+ }
+}
+
+mixinBody(Response)
+
+Object.defineProperties(Response.prototype, {
+ type: kEnumerableProperty,
+ url: kEnumerableProperty,
+ status: kEnumerableProperty,
+ ok: kEnumerableProperty,
+ redirected: kEnumerableProperty,
+ statusText: kEnumerableProperty,
+ headers: kEnumerableProperty,
+ clone: kEnumerableProperty,
+ body: kEnumerableProperty,
+ bodyUsed: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'Response',
+ configurable: true
+ }
+})
- if (contentLength !== null && bytesWritten !== contentLength) {
- if (client[kStrictContentLength]) {
- throw new RequestContentLengthMismatchError()
- } else {
- process.emitWarning(new RequestContentLengthMismatchError())
- }
- }
+Object.defineProperties(Response, {
+ json: kEnumerableProperty,
+ redirect: kEnumerableProperty,
+ error: kEnumerableProperty
+})
- if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) {
- // istanbul ignore else: only for jest
- if (socket[kParser].timeout.refresh) {
- socket[kParser].timeout.refresh()
- }
- }
+// https://fetch.spec.whatwg.org/#concept-response-clone
+function cloneResponse (response) {
+ // To clone a response response, run these steps:
- resume(client)
+ // 1. If response is a filtered response, then return a new identical
+ // filtered response whose internal response is a clone of response’s
+ // internal response.
+ if (response.internalResponse) {
+ return filterResponse(
+ cloneResponse(response.internalResponse),
+ response.type
+ )
}
- destroy (err) {
- const { socket, client } = this
-
- socket[kWriting] = false
+ // 2. Let newResponse be a copy of response, except for its body.
+ const newResponse = makeResponse({ ...response, body: null })
- if (err) {
- assert(client[kRunning] <= 1, 'pipeline should only contain this request')
- util.destroy(socket, err)
- }
+ // 3. If response’s body is non-null, then set newResponse’s body to the
+ // result of cloning response’s body.
+ if (response.body != null) {
+ newResponse.body = cloneBody(response.body)
}
+
+ // 4. Return newResponse.
+ return newResponse
}
-function errorRequest (client, request, err) {
- try {
- request.onError(err)
- assert(request.aborted)
- } catch (err) {
- client.emit('error', err)
+function makeResponse (init) {
+ return {
+ aborted: false,
+ rangeRequested: false,
+ timingAllowPassed: false,
+ requestIncludesCredentials: false,
+ type: 'default',
+ status: 200,
+ timingInfo: null,
+ cacheState: '',
+ statusText: '',
+ ...init,
+ headersList: init.headersList
+ ? new HeadersList(init.headersList)
+ : new HeadersList(),
+ urlList: init.urlList ? [...init.urlList] : []
}
}
-module.exports = Client
-
+function makeNetworkError (reason) {
+ const isError = isErrorLike(reason)
+ return makeResponse({
+ type: 'error',
+ status: 0,
+ error: isError
+ ? reason
+ : new Error(reason ? String(reason) : reason),
+ aborted: reason && reason.name === 'AbortError'
+ })
+}
-/***/ }),
+function makeFilteredResponse (response, state) {
+ state = {
+ internalResponse: response,
+ ...state
+ }
-/***/ 90022:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ return new Proxy(response, {
+ get (target, p) {
+ return p in state ? state[p] : target[p]
+ },
+ set (target, p, value) {
+ assert(!(p in state))
+ target[p] = value
+ return true
+ }
+ })
+}
+// https://fetch.spec.whatwg.org/#concept-filtered-response
+function filterResponse (response, type) {
+ // Set response to the following filtered response with response as its
+ // internal response, depending on request’s response tainting:
+ if (type === 'basic') {
+ // A basic filtered response is a filtered response whose type is "basic"
+ // and header list excludes any headers in internal response’s header list
+ // whose name is a forbidden response-header name.
+ // Note: undici does not implement forbidden response-header names
+ return makeFilteredResponse(response, {
+ type: 'basic',
+ headersList: response.headersList
+ })
+ } else if (type === 'cors') {
+ // A CORS filtered response is a filtered response whose type is "cors"
+ // and header list excludes any headers in internal response’s header
+ // list whose name is not a CORS-safelisted response-header name, given
+ // internal response’s CORS-exposed header-name list.
-/* istanbul ignore file: only for Node 12 */
+ // Note: undici does not implement CORS-safelisted response-header names
+ return makeFilteredResponse(response, {
+ type: 'cors',
+ headersList: response.headersList
+ })
+ } else if (type === 'opaque') {
+ // An opaque filtered response is a filtered response whose type is
+ // "opaque", URL list is the empty list, status is 0, status message
+ // is the empty byte sequence, header list is empty, and body is null.
-const { kConnected, kSize } = __nccwpck_require__(68031)
+ return makeFilteredResponse(response, {
+ type: 'opaque',
+ urlList: Object.freeze([]),
+ status: 0,
+ statusText: '',
+ body: null
+ })
+ } else if (type === 'opaqueredirect') {
+ // An opaque-redirect filtered response is a filtered response whose type
+ // is "opaqueredirect", status is 0, status message is the empty byte
+ // sequence, header list is empty, and body is null.
-class CompatWeakRef {
- constructor (value) {
- this.value = value
+ return makeFilteredResponse(response, {
+ type: 'opaqueredirect',
+ status: 0,
+ statusText: '',
+ headersList: [],
+ body: null
+ })
+ } else {
+ assert(false)
}
+}
- deref () {
- return this.value[kConnected] === 0 && this.value[kSize] === 0
- ? undefined
- : this.value
- }
+// https://fetch.spec.whatwg.org/#appropriate-network-error
+function makeAppropriateNetworkError (fetchParams, err = null) {
+ // 1. Assert: fetchParams is canceled.
+ assert(isCancelled(fetchParams))
+
+ // 2. Return an aborted network error if fetchParams is aborted;
+ // otherwise return a network error.
+ return isAborted(fetchParams)
+ ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))
+ : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))
}
-class CompatFinalizer {
- constructor (finalizer) {
- this.finalizer = finalizer
+// https://whatpr.org/fetch/1392.html#initialize-a-response
+function initializeResponse (response, init, body) {
+ // 1. If init["status"] is not in the range 200 to 599, inclusive, then
+ // throw a RangeError.
+ if (init.status !== null && (init.status < 200 || init.status > 599)) {
+ throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')
}
- register (dispatcher, key) {
- if (dispatcher.on) {
- dispatcher.on('disconnect', () => {
- if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) {
- this.finalizer(key)
- }
- })
+ // 2. If init["statusText"] does not match the reason-phrase token production,
+ // then throw a TypeError.
+ if ('statusText' in init && init.statusText != null) {
+ // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:
+ // reason-phrase = *( HTAB / SP / VCHAR / obs-text )
+ if (!isValidReasonPhrase(String(init.statusText))) {
+ throw new TypeError('Invalid statusText')
}
}
-}
-module.exports = function () {
- // FIXME: remove workaround when the Node bug is fixed
- // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
- if (process.env.NODE_V8_COVERAGE) {
- return {
- WeakRef: CompatWeakRef,
- FinalizationRegistry: CompatFinalizer
- }
- }
- return {
- WeakRef: global.WeakRef || CompatWeakRef,
- FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer
+ // 3. Set response’s response’s status to init["status"].
+ if ('status' in init && init.status != null) {
+ response[kState].status = init.status
}
-}
-
-
-/***/ }),
-
-/***/ 16985:
-/***/ ((module) => {
+ // 4. Set response’s response’s status message to init["statusText"].
+ if ('statusText' in init && init.statusText != null) {
+ response[kState].statusText = init.statusText
+ }
+ // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
+ if ('headers' in init && init.headers != null) {
+ fill(response[kHeaders], init.headers)
+ }
-// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size
-const maxAttributeValueSize = 1024
+ // 6. If body was given, then:
+ if (body) {
+ // 1. If response's status is a null body status, then throw a TypeError.
+ if (nullBodyStatus.includes(response.status)) {
+ throw webidl.errors.exception({
+ header: 'Response constructor',
+ message: 'Invalid response status code ' + response.status
+ })
+ }
-// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size
-const maxNameValuePairSize = 4096
+ // 2. Set response's body to body's body.
+ response[kState].body = body.body
-module.exports = {
- maxAttributeValueSize,
- maxNameValuePairSize
+ // 3. If body's type is non-null and response's header list does not contain
+ // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.
+ if (body.type != null && !response[kState].headersList.contains('Content-Type')) {
+ response[kState].headersList.append('content-type', body.type)
+ }
+ }
}
+webidl.converters.ReadableStream = webidl.interfaceConverter(
+ ReadableStream
+)
-/***/ }),
+webidl.converters.FormData = webidl.interfaceConverter(
+ FormData
+)
-/***/ 64276:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+webidl.converters.URLSearchParams = webidl.interfaceConverter(
+ URLSearchParams
+)
+// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
+webidl.converters.XMLHttpRequestBodyInit = function (V) {
+ if (typeof V === 'string') {
+ return webidl.converters.USVString(V)
+ }
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
+ }
-const { parseSetCookie } = __nccwpck_require__(16695)
-const { stringify, getHeadersList } = __nccwpck_require__(83126)
-const { webidl } = __nccwpck_require__(94354)
-const { Headers } = __nccwpck_require__(12801)
+ if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {
+ return webidl.converters.BufferSource(V)
+ }
-/**
- * @typedef {Object} Cookie
- * @property {string} name
- * @property {string} value
- * @property {Date|number|undefined} expires
- * @property {number|undefined} maxAge
- * @property {string|undefined} domain
- * @property {string|undefined} path
- * @property {boolean|undefined} secure
- * @property {boolean|undefined} httpOnly
- * @property {'Strict'|'Lax'|'None'} sameSite
- * @property {string[]} unparsed
- */
+ if (util.isFormDataLike(V)) {
+ return webidl.converters.FormData(V, { strict: false })
+ }
-/**
- * @param {Headers} headers
- * @returns {Record}
- */
-function getCookies (headers) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' })
+ if (V instanceof URLSearchParams) {
+ return webidl.converters.URLSearchParams(V)
+ }
- webidl.brandCheck(headers, Headers, { strict: false })
+ return webidl.converters.DOMString(V)
+}
- const cookie = headers.get('cookie')
- const out = {}
+// https://fetch.spec.whatwg.org/#bodyinit
+webidl.converters.BodyInit = function (V) {
+ if (V instanceof ReadableStream) {
+ return webidl.converters.ReadableStream(V)
+ }
- if (!cookie) {
- return out
+ // Note: the spec doesn't include async iterables,
+ // this is an undici extension.
+ if (V?.[Symbol.asyncIterator]) {
+ return V
}
- for (const piece of cookie.split(';')) {
- const [name, ...value] = piece.split('=')
+ return webidl.converters.XMLHttpRequestBodyInit(V)
+}
- out[name.trim()] = value.join('=')
+webidl.converters.ResponseInit = webidl.dictionaryConverter([
+ {
+ key: 'status',
+ converter: webidl.converters['unsigned short'],
+ defaultValue: 200
+ },
+ {
+ key: 'statusText',
+ converter: webidl.converters.ByteString,
+ defaultValue: ''
+ },
+ {
+ key: 'headers',
+ converter: webidl.converters.HeadersInit
}
+])
- return out
+module.exports = {
+ makeNetworkError,
+ makeResponse,
+ makeAppropriateNetworkError,
+ filterResponse,
+ Response,
+ cloneResponse
}
-/**
- * @param {Headers} headers
- * @param {string} name
- * @param {{ path?: string, domain?: string }|undefined} attributes
- * @returns {void}
- */
-function deleteCookie (headers, name, attributes) {
- webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' })
- webidl.brandCheck(headers, Headers, { strict: false })
+/***/ }),
- name = webidl.converters.DOMString(name)
- attributes = webidl.converters.DeleteCookieAttributes(attributes)
+/***/ 63730:
+/***/ ((module) => {
- // Matches behavior of
- // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278
- setCookie(headers, {
- name,
- value: '',
- expires: new Date(0),
- ...attributes
- })
+
+
+module.exports = {
+ kUrl: Symbol('url'),
+ kHeaders: Symbol('headers'),
+ kSignal: Symbol('signal'),
+ kState: Symbol('state'),
+ kGuard: Symbol('guard'),
+ kRealm: Symbol('realm')
}
-/**
- * @param {Headers} headers
- * @returns {Cookie[]}
- */
-function getSetCookies (headers) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' })
- webidl.brandCheck(headers, Headers, { strict: false })
+/***/ }),
- const cookies = getHeadersList(headers).cookies
+/***/ 72847:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (!cookies) {
- return []
- }
- // In older versions of undici, cookies is a list of name:value.
- return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair))
-}
-/**
- * @param {Headers} headers
- * @param {Cookie} cookie
- * @returns {void}
- */
-function setCookie (headers, cookie) {
- webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' })
+const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(21234)
+const { getGlobalOrigin } = __nccwpck_require__(62896)
+const { performance } = __nccwpck_require__(82987)
+const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(89500)
+const assert = __nccwpck_require__(42613)
+const { isUint8Array } = __nccwpck_require__(98253)
- webidl.brandCheck(headers, Headers, { strict: false })
+let supportedHashes = []
- cookie = webidl.converters.Cookie(cookie)
+// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
+/** @type {import('crypto')|undefined} */
+let crypto
- const str = stringify(cookie)
+try {
+ crypto = __nccwpck_require__(76982)
+ const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
+ supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
+/* c8 ignore next 3 */
+} catch {
+}
- if (str) {
- headers.append('Set-Cookie', stringify(cookie))
- }
+function responseURL (response) {
+ // https://fetch.spec.whatwg.org/#responses
+ // A response has an associated URL. It is a pointer to the last URL
+ // in response’s URL list and null if response’s URL list is empty.
+ const urlList = response.urlList
+ const length = urlList.length
+ return length === 0 ? null : urlList[length - 1].toString()
}
-webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'path',
- defaultValue: null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'domain',
- defaultValue: null
+// https://fetch.spec.whatwg.org/#concept-response-location-url
+function responseLocationURL (response, requestFragment) {
+ // 1. If response’s status is not a redirect status, then return null.
+ if (!redirectStatusSet.has(response.status)) {
+ return null
}
-])
-webidl.converters.Cookie = webidl.dictionaryConverter([
- {
- converter: webidl.converters.DOMString,
- key: 'name'
- },
- {
- converter: webidl.converters.DOMString,
- key: 'value'
- },
- {
- converter: webidl.nullableConverter((value) => {
- if (typeof value === 'number') {
- return webidl.converters['unsigned long long'](value)
- }
+ // 2. Let location be the result of extracting header list values given
+ // `Location` and response’s header list.
+ let location = response.headersList.get('location')
- return new Date(value)
- }),
- key: 'expires',
- defaultValue: null
- },
- {
- converter: webidl.nullableConverter(webidl.converters['long long']),
- key: 'maxAge',
- defaultValue: null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'domain',
- defaultValue: null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.DOMString),
- key: 'path',
- defaultValue: null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.boolean),
- key: 'secure',
- defaultValue: null
- },
- {
- converter: webidl.nullableConverter(webidl.converters.boolean),
- key: 'httpOnly',
- defaultValue: null
- },
- {
- converter: webidl.converters.USVString,
- key: 'sameSite',
- allowedValues: ['Strict', 'Lax', 'None']
- },
- {
- converter: webidl.sequenceConverter(webidl.converters.DOMString),
- key: 'unparsed',
- defaultValue: []
+ // 3. If location is a header value, then set location to the result of
+ // parsing location with response’s URL.
+ if (location !== null && isValidHeaderValue(location)) {
+ location = new URL(location, responseURL(response))
}
-])
-module.exports = {
- getCookies,
- deleteCookie,
- getSetCookies,
- setCookie
+ // 4. If location is a URL whose fragment is null, then set location’s
+ // fragment to requestFragment.
+ if (location && !location.hash) {
+ location.hash = requestFragment
+ }
+
+ // 5. Return location.
+ return location
}
+/** @returns {URL} */
+function requestCurrentURL (request) {
+ return request.urlList[request.urlList.length - 1]
+}
-/***/ }),
+function requestBadPort (request) {
+ // 1. Let url be request’s current URL.
+ const url = requestCurrentURL(request)
-/***/ 16695:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,
+ // then return blocked.
+ if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
+ return 'blocked'
+ }
+ // 3. Return allowed.
+ return 'allowed'
+}
+function isErrorLike (object) {
+ return object instanceof Error || (
+ object?.constructor?.name === 'Error' ||
+ object?.constructor?.name === 'DOMException'
+ )
+}
-const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(16985)
-const { isCTLExcludingHtab } = __nccwpck_require__(83126)
-const { collectASequenceOfCodePointsFast } = __nccwpck_require__(37246)
-const assert = __nccwpck_require__(42613)
+// Check whether |statusText| is a ByteString and
+// matches the Reason-Phrase token production.
+// RFC 2616: https://tools.ietf.org/html/rfc2616
+// RFC 7230: https://tools.ietf.org/html/rfc7230
+// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )"
+// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116
+function isValidReasonPhrase (statusText) {
+ for (let i = 0; i < statusText.length; ++i) {
+ const c = statusText.charCodeAt(i)
+ if (
+ !(
+ (
+ c === 0x09 || // HTAB
+ (c >= 0x20 && c <= 0x7e) || // SP / VCHAR
+ (c >= 0x80 && c <= 0xff)
+ ) // obs-text
+ )
+ ) {
+ return false
+ }
+ }
+ return true
+}
/**
- * @description Parses the field-value attributes of a set-cookie header string.
- * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
- * @param {string} header
- * @returns if the header is invalid, null will be returned
+ * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
+ * @param {number} c
*/
-function parseSetCookie (header) {
- // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F
- // character (CTL characters excluding HTAB): Abort these steps and
- // ignore the set-cookie-string entirely.
- if (isCTLExcludingHtab(header)) {
- return null
+function isTokenCharCode (c) {
+ switch (c) {
+ case 0x22:
+ case 0x28:
+ case 0x29:
+ case 0x2c:
+ case 0x2f:
+ case 0x3a:
+ case 0x3b:
+ case 0x3c:
+ case 0x3d:
+ case 0x3e:
+ case 0x3f:
+ case 0x40:
+ case 0x5b:
+ case 0x5c:
+ case 0x5d:
+ case 0x7b:
+ case 0x7d:
+ // DQUOTE and "(),/:;<=>?@[\]{}"
+ return false
+ default:
+ // VCHAR %x21-7E
+ return c >= 0x21 && c <= 0x7e
}
+}
- let nameValuePair = ''
- let unparsedAttributes = ''
- let name = ''
- let value = ''
-
- // 2. If the set-cookie-string contains a %x3B (";") character:
- if (header.includes(';')) {
- // 1. The name-value-pair string consists of the characters up to,
- // but not including, the first %x3B (";"), and the unparsed-
- // attributes consist of the remainder of the set-cookie-string
- // (including the %x3B (";") in question).
- const position = { position: 0 }
-
- nameValuePair = collectASequenceOfCodePointsFast(';', header, position)
- unparsedAttributes = header.slice(position.position)
- } else {
- // Otherwise:
-
- // 1. The name-value-pair string consists of all the characters
- // contained in the set-cookie-string, and the unparsed-
- // attributes is the empty string.
- nameValuePair = header
+/**
+ * @param {string} characters
+ */
+function isValidHTTPToken (characters) {
+ if (characters.length === 0) {
+ return false
}
-
- // 3. If the name-value-pair string lacks a %x3D ("=") character, then
- // the name string is empty, and the value string is the value of
- // name-value-pair.
- if (!nameValuePair.includes('=')) {
- value = nameValuePair
- } else {
- // Otherwise, the name string consists of the characters up to, but
- // not including, the first %x3D ("=") character, and the (possibly
- // empty) value string consists of the characters after the first
- // %x3D ("=") character.
- const position = { position: 0 }
- name = collectASequenceOfCodePointsFast(
- '=',
- nameValuePair,
- position
- )
- value = nameValuePair.slice(position.position + 1)
+ for (let i = 0; i < characters.length; ++i) {
+ if (!isTokenCharCode(characters.charCodeAt(i))) {
+ return false
+ }
}
+ return true
+}
- // 4. Remove any leading or trailing WSP characters from the name
- // string and the value string.
- name = name.trim()
- value = value.trim()
+/**
+ * @see https://fetch.spec.whatwg.org/#header-name
+ * @param {string} potentialValue
+ */
+function isValidHeaderName (potentialValue) {
+ return isValidHTTPToken(potentialValue)
+}
- // 5. If the sum of the lengths of the name string and the value string
- // is more than 4096 octets, abort these steps and ignore the set-
- // cookie-string entirely.
- if (name.length + value.length > maxNameValuePairSize) {
- return null
+/**
+ * @see https://fetch.spec.whatwg.org/#header-value
+ * @param {string} potentialValue
+ */
+function isValidHeaderValue (potentialValue) {
+ // - Has no leading or trailing HTTP tab or space bytes.
+ // - Contains no 0x00 (NUL) or HTTP newline bytes.
+ if (
+ potentialValue.startsWith('\t') ||
+ potentialValue.startsWith(' ') ||
+ potentialValue.endsWith('\t') ||
+ potentialValue.endsWith(' ')
+ ) {
+ return false
}
- // 6. The cookie-name is the name string, and the cookie-value is the
- // value string.
- return {
- name, value, ...parseUnparsedAttributes(unparsedAttributes)
+ if (
+ potentialValue.includes('\0') ||
+ potentialValue.includes('\r') ||
+ potentialValue.includes('\n')
+ ) {
+ return false
}
+
+ return true
}
-/**
- * Parses the remaining attributes of a set-cookie header
- * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4
- * @param {string} unparsedAttributes
- * @param {[Object.]={}} cookieAttributeList
- */
-function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) {
- // 1. If the unparsed-attributes string is empty, skip the rest of
- // these steps.
- if (unparsedAttributes.length === 0) {
- return cookieAttributeList
- }
+// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
+function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
+ // Given a request request and a response actualResponse, this algorithm
+ // updates request’s referrer policy according to the Referrer-Policy
+ // header (if any) in actualResponse.
- // 2. Discard the first character of the unparsed-attributes (which
- // will be a %x3B (";") character).
- assert(unparsedAttributes[0] === ';')
- unparsedAttributes = unparsedAttributes.slice(1)
+ // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
+ // from a Referrer-Policy header on actualResponse.
- let cookieAv = ''
+ // 8.1 Parse a referrer policy from a Referrer-Policy header
+ // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
+ const { headersList } = actualResponse
+ // 2. Let policy be the empty string.
+ // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.
+ // 4. Return policy.
+ const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')
- // 3. If the remaining unparsed-attributes contains a %x3B (";")
- // character:
- if (unparsedAttributes.includes(';')) {
- // 1. Consume the characters of the unparsed-attributes up to, but
- // not including, the first %x3B (";") character.
- cookieAv = collectASequenceOfCodePointsFast(
- ';',
- unparsedAttributes,
- { position: 0 }
- )
- unparsedAttributes = unparsedAttributes.slice(cookieAv.length)
- } else {
- // Otherwise:
+ // Note: As the referrer-policy can contain multiple policies
+ // separated by comma, we need to loop through all of them
+ // and pick the first valid one.
+ // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy
+ let policy = ''
+ if (policyHeader.length > 0) {
+ // The right-most policy takes precedence.
+ // The left-most policy is the fallback.
+ for (let i = policyHeader.length; i !== 0; i--) {
+ const token = policyHeader[i - 1].trim()
+ if (referrerPolicyTokens.has(token)) {
+ policy = token
+ break
+ }
+ }
+ }
- // 1. Consume the remainder of the unparsed-attributes.
- cookieAv = unparsedAttributes
- unparsedAttributes = ''
+ // 2. If policy is not the empty string, then set request’s referrer policy to policy.
+ if (policy !== '') {
+ request.referrerPolicy = policy
}
+}
- // Let the cookie-av string be the characters consumed in this step.
+// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
+function crossOriginResourcePolicyCheck () {
+ // TODO
+ return 'allowed'
+}
- let attributeName = ''
- let attributeValue = ''
+// https://fetch.spec.whatwg.org/#concept-cors-check
+function corsCheck () {
+ // TODO
+ return 'success'
+}
- // 4. If the cookie-av string contains a %x3D ("=") character:
- if (cookieAv.includes('=')) {
- // 1. The (possibly empty) attribute-name string consists of the
- // characters up to, but not including, the first %x3D ("=")
- // character, and the (possibly empty) attribute-value string
- // consists of the characters after the first %x3D ("=")
- // character.
- const position = { position: 0 }
+// https://fetch.spec.whatwg.org/#concept-tao-check
+function TAOCheck () {
+ // TODO
+ return 'success'
+}
- attributeName = collectASequenceOfCodePointsFast(
- '=',
- cookieAv,
- position
- )
- attributeValue = cookieAv.slice(position.position + 1)
- } else {
- // Otherwise:
+function appendFetchMetadata (httpRequest) {
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
+ // TODO
- // 1. The attribute-name string consists of the entire cookie-av
- // string, and the attribute-value string is empty.
- attributeName = cookieAv
- }
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
- // 5. Remove any leading or trailing WSP characters from the attribute-
- // name string and the attribute-value string.
- attributeName = attributeName.trim()
- attributeValue = attributeValue.trim()
+ // 1. Assert: r’s url is a potentially trustworthy URL.
+ // TODO
- // 6. If the attribute-value is longer than 1024 octets, ignore the
- // cookie-av string and return to Step 1 of this algorithm.
- if (attributeValue.length > maxAttributeValueSize) {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
- }
+ // 2. Let header be a Structured Header whose value is a token.
+ let header = null
- // 7. Process the attribute-name and attribute-value according to the
- // requirements in the following subsections. (Notice that
- // attributes with unrecognized attribute-names are ignored.)
- const attributeNameLowercase = attributeName.toLowerCase()
+ // 3. Set header’s value to r’s mode.
+ header = httpRequest.mode
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1
- // If the attribute-name case-insensitively matches the string
- // "Expires", the user agent MUST process the cookie-av as follows.
- if (attributeNameLowercase === 'expires') {
- // 1. Let the expiry-time be the result of parsing the attribute-value
- // as cookie-date (see Section 5.1.1).
- const expiryTime = new Date(attributeValue)
+ // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
+ httpRequest.headersList.set('sec-fetch-mode', header)
- // 2. If the attribute-value failed to parse as a cookie date, ignore
- // the cookie-av.
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
+ // TODO
- cookieAttributeList.expires = expiryTime
- } else if (attributeNameLowercase === 'max-age') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2
- // If the attribute-name case-insensitively matches the string "Max-
- // Age", the user agent MUST process the cookie-av as follows.
+ // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
+ // TODO
+}
- // 1. If the first character of the attribute-value is not a DIGIT or a
- // "-" character, ignore the cookie-av.
- const charCode = attributeValue.charCodeAt(0)
+// https://fetch.spec.whatwg.org/#append-a-request-origin-header
+function appendRequestOriginHeader (request) {
+ // 1. Let serializedOrigin be the result of byte-serializing a request origin with request.
+ let serializedOrigin = request.origin
- if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list.
+ if (request.responseTainting === 'cors' || request.mode === 'websocket') {
+ if (serializedOrigin) {
+ request.headersList.append('origin', serializedOrigin)
}
- // 2. If the remainder of attribute-value contains a non-DIGIT
- // character, ignore the cookie-av.
- if (!/^\d+$/.test(attributeValue)) {
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
+ // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
+ } else if (request.method !== 'GET' && request.method !== 'HEAD') {
+ // 1. Switch on request’s referrer policy:
+ switch (request.referrerPolicy) {
+ case 'no-referrer':
+ // Set serializedOrigin to `null`.
+ serializedOrigin = null
+ break
+ case 'no-referrer-when-downgrade':
+ case 'strict-origin':
+ case 'strict-origin-when-cross-origin':
+ // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`.
+ if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
+ serializedOrigin = null
+ }
+ break
+ case 'same-origin':
+ // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`.
+ if (!sameOrigin(request, requestCurrentURL(request))) {
+ serializedOrigin = null
+ }
+ break
+ default:
+ // Do nothing.
}
- // 3. Let delta-seconds be the attribute-value converted to an integer.
- const deltaSeconds = Number(attributeValue)
+ if (serializedOrigin) {
+ // 2. Append (`Origin`, serializedOrigin) to request’s header list.
+ request.headersList.append('origin', serializedOrigin)
+ }
+ }
+}
- // 4. Let cookie-age-limit be the maximum age of the cookie (which
- // SHOULD be 400 days or less, see Section 4.1.2.2).
+function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
+ // TODO
+ return performance.now()
+}
- // 5. Set delta-seconds to the smaller of its present value and cookie-
- // age-limit.
- // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs)
+// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
+function createOpaqueTimingInfo (timingInfo) {
+ return {
+ startTime: timingInfo.startTime ?? 0,
+ redirectStartTime: 0,
+ redirectEndTime: 0,
+ postRedirectStartTime: timingInfo.startTime ?? 0,
+ finalServiceWorkerStartTime: 0,
+ finalNetworkResponseStartTime: 0,
+ finalNetworkRequestStartTime: 0,
+ endTime: 0,
+ encodedBodySize: 0,
+ decodedBodySize: 0,
+ finalConnectionTimingInfo: null
+ }
+}
- // 6. If delta-seconds is less than or equal to zero (0), let expiry-
- // time be the earliest representable date and time. Otherwise, let
- // the expiry-time be the current date and time plus delta-seconds
- // seconds.
- // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds
+// https://html.spec.whatwg.org/multipage/origin.html#policy-container
+function makePolicyContainer () {
+ // Note: the fetch spec doesn't make use of embedder policy or CSP list
+ return {
+ referrerPolicy: 'strict-origin-when-cross-origin'
+ }
+}
- // 7. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Max-Age and an attribute-value of expiry-time.
- cookieAttributeList.maxAge = deltaSeconds
- } else if (attributeNameLowercase === 'domain') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3
- // If the attribute-name case-insensitively matches the string "Domain",
- // the user agent MUST process the cookie-av as follows.
+// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
+function clonePolicyContainer (policyContainer) {
+ return {
+ referrerPolicy: policyContainer.referrerPolicy
+ }
+}
- // 1. Let cookie-domain be the attribute-value.
- let cookieDomain = attributeValue
+// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
+function determineRequestsReferrer (request) {
+ // 1. Let policy be request's referrer policy.
+ const policy = request.referrerPolicy
- // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be
- // cookie-domain without its leading %x2E (".").
- if (cookieDomain[0] === '.') {
- cookieDomain = cookieDomain.slice(1)
- }
+ // Note: policy cannot (shouldn't) be null or an empty string.
+ assert(policy)
- // 3. Convert the cookie-domain to lower case.
- cookieDomain = cookieDomain.toLowerCase()
+ // 2. Let environment be request’s client.
- // 4. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Domain and an attribute-value of cookie-domain.
- cookieAttributeList.domain = cookieDomain
- } else if (attributeNameLowercase === 'path') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4
- // If the attribute-name case-insensitively matches the string "Path",
- // the user agent MUST process the cookie-av as follows.
+ let referrerSource = null
- // 1. If the attribute-value is empty or if the first character of the
- // attribute-value is not %x2F ("/"):
- let cookiePath = ''
- if (attributeValue.length === 0 || attributeValue[0] !== '/') {
- // 1. Let cookie-path be the default-path.
- cookiePath = '/'
- } else {
- // Otherwise:
+ // 3. Switch on request’s referrer:
+ if (request.referrer === 'client') {
+ // Note: node isn't a browser and doesn't implement document/iframes,
+ // so we bypass this step and replace it with our own.
- // 1. Let cookie-path be the attribute-value.
- cookiePath = attributeValue
+ const globalOrigin = getGlobalOrigin()
+
+ if (!globalOrigin || globalOrigin.origin === 'null') {
+ return 'no-referrer'
}
- // 2. Append an attribute to the cookie-attribute-list with an
- // attribute-name of Path and an attribute-value of cookie-path.
- cookieAttributeList.path = cookiePath
- } else if (attributeNameLowercase === 'secure') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5
- // If the attribute-name case-insensitively matches the string "Secure",
- // the user agent MUST append an attribute to the cookie-attribute-list
- // with an attribute-name of Secure and an empty attribute-value.
+ // note: we need to clone it as it's mutated
+ referrerSource = new URL(globalOrigin)
+ } else if (request.referrer instanceof URL) {
+ // Let referrerSource be request’s referrer.
+ referrerSource = request.referrer
+ }
- cookieAttributeList.secure = true
- } else if (attributeNameLowercase === 'httponly') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6
- // If the attribute-name case-insensitively matches the string
- // "HttpOnly", the user agent MUST append an attribute to the cookie-
- // attribute-list with an attribute-name of HttpOnly and an empty
- // attribute-value.
+ // 4. Let request’s referrerURL be the result of stripping referrerSource for
+ // use as a referrer.
+ let referrerURL = stripURLForReferrer(referrerSource)
+
+ // 5. Let referrerOrigin be the result of stripping referrerSource for use as
+ // a referrer, with the origin-only flag set to true.
+ const referrerOrigin = stripURLForReferrer(referrerSource, true)
+
+ // 6. If the result of serializing referrerURL is a string whose length is
+ // greater than 4096, set referrerURL to referrerOrigin.
+ if (referrerURL.toString().length > 4096) {
+ referrerURL = referrerOrigin
+ }
- cookieAttributeList.httpOnly = true
- } else if (attributeNameLowercase === 'samesite') {
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7
- // If the attribute-name case-insensitively matches the string
- // "SameSite", the user agent MUST process the cookie-av as follows:
+ const areSameOrigin = sameOrigin(request, referrerURL)
+ const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
+ !isURLPotentiallyTrustworthy(request.url)
- // 1. Let enforcement be "Default".
- let enforcement = 'Default'
+ // 8. Execute the switch statements corresponding to the value of policy:
+ switch (policy) {
+ case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
+ case 'unsafe-url': return referrerURL
+ case 'same-origin':
+ return areSameOrigin ? referrerOrigin : 'no-referrer'
+ case 'origin-when-cross-origin':
+ return areSameOrigin ? referrerURL : referrerOrigin
+ case 'strict-origin-when-cross-origin': {
+ const currentURL = requestCurrentURL(request)
- const attributeValueLowercase = attributeValue.toLowerCase()
- // 2. If cookie-av's attribute-value is a case-insensitive match for
- // "None", set enforcement to "None".
- if (attributeValueLowercase.includes('none')) {
- enforcement = 'None'
- }
+ // 1. If the origin of referrerURL and the origin of request’s current
+ // URL are the same, then return referrerURL.
+ if (sameOrigin(referrerURL, currentURL)) {
+ return referrerURL
+ }
- // 3. If cookie-av's attribute-value is a case-insensitive match for
- // "Strict", set enforcement to "Strict".
- if (attributeValueLowercase.includes('strict')) {
- enforcement = 'Strict'
- }
+ // 2. If referrerURL is a potentially trustworthy URL and request’s
+ // current URL is not a potentially trustworthy URL, then return no
+ // referrer.
+ if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
+ return 'no-referrer'
+ }
- // 4. If cookie-av's attribute-value is a case-insensitive match for
- // "Lax", set enforcement to "Lax".
- if (attributeValueLowercase.includes('lax')) {
- enforcement = 'Lax'
+ // 3. Return referrerOrigin.
+ return referrerOrigin
}
+ case 'strict-origin': // eslint-disable-line
+ /**
+ * 1. If referrerURL is a potentially trustworthy URL and
+ * request’s current URL is not a potentially trustworthy URL,
+ * then return no referrer.
+ * 2. Return referrerOrigin
+ */
+ case 'no-referrer-when-downgrade': // eslint-disable-line
+ /**
+ * 1. If referrerURL is a potentially trustworthy URL and
+ * request’s current URL is not a potentially trustworthy URL,
+ * then return no referrer.
+ * 2. Return referrerOrigin
+ */
- // 5. Append an attribute to the cookie-attribute-list with an
- // attribute-name of "SameSite" and an attribute-value of
- // enforcement.
- cookieAttributeList.sameSite = enforcement
- } else {
- cookieAttributeList.unparsed ??= []
-
- cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`)
+ default: // eslint-disable-line
+ return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
}
-
- // 8. Return to Step 1 of this algorithm.
- return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList)
}
-module.exports = {
- parseSetCookie,
- parseUnparsedAttributes
-}
+/**
+ * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
+ * @param {URL} url
+ * @param {boolean|undefined} originOnly
+ */
+function stripURLForReferrer (url, originOnly) {
+ // 1. Assert: url is a URL.
+ assert(url instanceof URL)
+ // 2. If url’s scheme is a local scheme, then return no referrer.
+ if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
+ return 'no-referrer'
+ }
-/***/ }),
+ // 3. Set url’s username to the empty string.
+ url.username = ''
-/***/ 83126:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 4. Set url’s password to the empty string.
+ url.password = ''
+ // 5. Set url’s fragment to null.
+ url.hash = ''
+ // 6. If the origin-only flag is true, then:
+ if (originOnly) {
+ // 1. Set url’s path to « the empty string ».
+ url.pathname = ''
-const assert = __nccwpck_require__(42613)
-const { kHeadersList } = __nccwpck_require__(68031)
+ // 2. Set url’s query to null.
+ url.search = ''
+ }
-function isCTLExcludingHtab (value) {
- if (value.length === 0) {
+ // 7. Return url.
+ return url
+}
+
+function isURLPotentiallyTrustworthy (url) {
+ if (!(url instanceof URL)) {
return false
}
- for (const char of value) {
- const code = char.charCodeAt(0)
-
- if (
- (code >= 0x00 || code <= 0x08) ||
- (code >= 0x0A || code <= 0x1F) ||
- code === 0x7F
- ) {
- return false
- }
+ // If child of about, return true
+ if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
+ return true
}
-}
-/**
- CHAR =
- token = 1*
- separators = "(" | ")" | "<" | ">" | "@"
- | "," | ";" | ":" | "\" | <">
- | "/" | "[" | "]" | "?" | "="
- | "{" | "}" | SP | HT
- * @param {string} name
- */
-function validateCookieName (name) {
- for (const char of name) {
- const code = char.charCodeAt(0)
+ // If scheme is data, return true
+ if (url.protocol === 'data:') return true
- if (
- (code <= 0x20 || code > 0x7F) ||
- char === '(' ||
- char === ')' ||
- char === '>' ||
- char === '<' ||
- char === '@' ||
- char === ',' ||
- char === ';' ||
- char === ':' ||
- char === '\\' ||
- char === '"' ||
- char === '/' ||
- char === '[' ||
- char === ']' ||
- char === '?' ||
- char === '=' ||
- char === '{' ||
- char === '}'
- ) {
- throw new Error('Invalid cookie name')
- }
- }
-}
+ // If file, return true
+ if (url.protocol === 'file:') return true
-/**
- cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
- cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
- ; US-ASCII characters excluding CTLs,
- ; whitespace DQUOTE, comma, semicolon,
- ; and backslash
- * @param {string} value
- */
-function validateCookieValue (value) {
- for (const char of value) {
- const code = char.charCodeAt(0)
+ return isOriginPotentiallyTrustworthy(url.origin)
- if (
- code < 0x21 || // exclude CTLs (0-31)
- code === 0x22 ||
- code === 0x2C ||
- code === 0x3B ||
- code === 0x5C ||
- code > 0x7E // non-ascii
- ) {
- throw new Error('Invalid header value')
- }
- }
-}
+ function isOriginPotentiallyTrustworthy (origin) {
+ // If origin is explicitly null, return false
+ if (origin == null || origin === 'null') return false
-/**
- * path-value =
- * @param {string} path
- */
-function validateCookiePath (path) {
- for (const char of path) {
- const code = char.charCodeAt(0)
+ const originAsURL = new URL(origin)
- if (code < 0x21 || char === ';') {
- throw new Error('Invalid cookie path')
+ // If secure, return true
+ if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
+ return true
+ }
+
+ // If localhost or variants, return true
+ if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
+ (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
+ (originAsURL.hostname.endsWith('.localhost'))) {
+ return true
}
+
+ // If any other, return false
+ return false
}
}
/**
- * I have no idea why these values aren't allowed to be honest,
- * but Deno tests these. - Khafra
- * @param {string} domain
+ * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
+ * @param {Uint8Array} bytes
+ * @param {string} metadataList
*/
-function validateCookieDomain (domain) {
- if (
- domain.startsWith('-') ||
- domain.endsWith('.') ||
- domain.endsWith('-')
- ) {
- throw new Error('Invalid cookie domain')
+function bytesMatch (bytes, metadataList) {
+ // If node is not built with OpenSSL support, we cannot check
+ // a request's integrity, so allow it by default (the spec will
+ // allow requests if an invalid hash is given, as precedence).
+ /* istanbul ignore if: only if node is built with --without-ssl */
+ if (crypto === undefined) {
+ return true
}
-}
-/**
- * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1
- * @param {number|Date} date
- IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
- ; fixed length/zone/capitalization subset of the format
- ; see Section 3.3 of [RFC5322]
+ // 1. Let parsedMetadata be the result of parsing metadataList.
+ const parsedMetadata = parseMetadata(metadataList)
- day-name = %x4D.6F.6E ; "Mon", case-sensitive
- / %x54.75.65 ; "Tue", case-sensitive
- / %x57.65.64 ; "Wed", case-sensitive
- / %x54.68.75 ; "Thu", case-sensitive
- / %x46.72.69 ; "Fri", case-sensitive
- / %x53.61.74 ; "Sat", case-sensitive
- / %x53.75.6E ; "Sun", case-sensitive
- date1 = day SP month SP year
- ; e.g., 02 Jun 1982
+ // 2. If parsedMetadata is no metadata, return true.
+ if (parsedMetadata === 'no metadata') {
+ return true
+ }
- day = 2DIGIT
- month = %x4A.61.6E ; "Jan", case-sensitive
- / %x46.65.62 ; "Feb", case-sensitive
- / %x4D.61.72 ; "Mar", case-sensitive
- / %x41.70.72 ; "Apr", case-sensitive
- / %x4D.61.79 ; "May", case-sensitive
- / %x4A.75.6E ; "Jun", case-sensitive
- / %x4A.75.6C ; "Jul", case-sensitive
- / %x41.75.67 ; "Aug", case-sensitive
- / %x53.65.70 ; "Sep", case-sensitive
- / %x4F.63.74 ; "Oct", case-sensitive
- / %x4E.6F.76 ; "Nov", case-sensitive
- / %x44.65.63 ; "Dec", case-sensitive
- year = 4DIGIT
+ // 3. If response is not eligible for integrity validation, return false.
+ // TODO
- GMT = %x47.4D.54 ; "GMT", case-sensitive
+ // 4. If parsedMetadata is the empty set, return true.
+ if (parsedMetadata.length === 0) {
+ return true
+ }
- time-of-day = hour ":" minute ":" second
- ; 00:00:00 - 23:59:60 (leap second)
+ // 5. Let metadata be the result of getting the strongest
+ // metadata from parsedMetadata.
+ const strongest = getStrongestMetadata(parsedMetadata)
+ const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)
- hour = 2DIGIT
- minute = 2DIGIT
- second = 2DIGIT
- */
-function toIMFDate (date) {
- if (typeof date === 'number') {
- date = new Date(date)
- }
+ // 6. For each item in metadata:
+ for (const item of metadata) {
+ // 1. Let algorithm be the alg component of item.
+ const algorithm = item.algo
- const days = [
- 'Sun', 'Mon', 'Tue', 'Wed',
- 'Thu', 'Fri', 'Sat'
- ]
+ // 2. Let expectedValue be the val component of item.
+ const expectedValue = item.hash
- const months = [
- 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
- 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
- ]
+ // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e
+ // "be liberal with padding". This is annoying, and it's not even in the spec.
- const dayName = days[date.getUTCDay()]
- const day = date.getUTCDate().toString().padStart(2, '0')
- const month = months[date.getUTCMonth()]
- const year = date.getUTCFullYear()
- const hour = date.getUTCHours().toString().padStart(2, '0')
- const minute = date.getUTCMinutes().toString().padStart(2, '0')
- const second = date.getUTCSeconds().toString().padStart(2, '0')
+ // 3. Let actualValue be the result of applying algorithm to bytes.
+ let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
- return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT`
-}
+ if (actualValue[actualValue.length - 1] === '=') {
+ if (actualValue[actualValue.length - 2] === '=') {
+ actualValue = actualValue.slice(0, -2)
+ } else {
+ actualValue = actualValue.slice(0, -1)
+ }
+ }
-/**
- max-age-av = "Max-Age=" non-zero-digit *DIGIT
- ; In practice, both expires-av and max-age-av
- ; are limited to dates representable by the
- ; user agent.
- * @param {number} maxAge
- */
-function validateCookieMaxAge (maxAge) {
- if (maxAge < 0) {
- throw new Error('Invalid cookie max-age')
+ // 4. If actualValue is a case-sensitive match for expectedValue,
+ // return true.
+ if (compareBase64Mixed(actualValue, expectedValue)) {
+ return true
+ }
}
+
+ // 7. Return false.
+ return false
}
+// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options
+// https://www.w3.org/TR/CSP2/#source-list-syntax
+// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1
+const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i
+
/**
- * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1
- * @param {import('./index').Cookie} cookie
+ * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
+ * @param {string} metadata
*/
-function stringify (cookie) {
- if (cookie.name.length === 0) {
- return null
- }
+function parseMetadata (metadata) {
+ // 1. Let result be the empty set.
+ /** @type {{ algo: string, hash: string }[]} */
+ const result = []
- validateCookieName(cookie.name)
- validateCookieValue(cookie.value)
+ // 2. Let empty be equal to true.
+ let empty = true
- const out = [`${cookie.name}=${cookie.value}`]
+ // 3. For each token returned by splitting metadata on spaces:
+ for (const token of metadata.split(' ')) {
+ // 1. Set empty to false.
+ empty = false
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1
- // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2
- if (cookie.name.startsWith('__Secure-')) {
- cookie.secure = true
- }
+ // 2. Parse token as a hash-with-options.
+ const parsedToken = parseHashWithOptions.exec(token)
- if (cookie.name.startsWith('__Host-')) {
- cookie.secure = true
- cookie.domain = null
- cookie.path = '/'
- }
+ // 3. If token does not parse, continue to the next token.
+ if (
+ parsedToken === null ||
+ parsedToken.groups === undefined ||
+ parsedToken.groups.algo === undefined
+ ) {
+ // Note: Chromium blocks the request at this point, but Firefox
+ // gives a warning that an invalid integrity was given. The
+ // correct behavior is to ignore these, and subsequently not
+ // check the integrity of the resource.
+ continue
+ }
- if (cookie.secure) {
- out.push('Secure')
- }
+ // 4. Let algorithm be the hash-algo component of token.
+ const algorithm = parsedToken.groups.algo.toLowerCase()
- if (cookie.httpOnly) {
- out.push('HttpOnly')
+ // 5. If algorithm is a hash function recognized by the user
+ // agent, add the parsed token to result.
+ if (supportedHashes.includes(algorithm)) {
+ result.push(parsedToken.groups)
+ }
}
- if (typeof cookie.maxAge === 'number') {
- validateCookieMaxAge(cookie.maxAge)
- out.push(`Max-Age=${cookie.maxAge}`)
+ // 4. Return no metadata if empty is true, otherwise return result.
+ if (empty === true) {
+ return 'no metadata'
}
- if (cookie.domain) {
- validateCookieDomain(cookie.domain)
- out.push(`Domain=${cookie.domain}`)
+ return result
+}
+
+/**
+ * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList
+ */
+function getStrongestMetadata (metadataList) {
+ // Let algorithm be the algo component of the first item in metadataList.
+ // Can be sha256
+ let algorithm = metadataList[0].algo
+ // If the algorithm is sha512, then it is the strongest
+ // and we can return immediately
+ if (algorithm[3] === '5') {
+ return algorithm
}
- if (cookie.path) {
- validateCookiePath(cookie.path)
- out.push(`Path=${cookie.path}`)
+ for (let i = 1; i < metadataList.length; ++i) {
+ const metadata = metadataList[i]
+ // If the algorithm is sha512, then it is the strongest
+ // and we can break the loop immediately
+ if (metadata.algo[3] === '5') {
+ algorithm = 'sha512'
+ break
+ // If the algorithm is sha384, then a potential sha256 or sha384 is ignored
+ } else if (algorithm[3] === '3') {
+ continue
+ // algorithm is sha256, check if algorithm is sha384 and if so, set it as
+ // the strongest
+ } else if (metadata.algo[3] === '3') {
+ algorithm = 'sha384'
+ }
}
+ return algorithm
+}
- if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') {
- out.push(`Expires=${toIMFDate(cookie.expires)}`)
+function filterMetadataListByAlgorithm (metadataList, algorithm) {
+ if (metadataList.length === 1) {
+ return metadataList
}
- if (cookie.sameSite) {
- out.push(`SameSite=${cookie.sameSite}`)
+ let pos = 0
+ for (let i = 0; i < metadataList.length; ++i) {
+ if (metadataList[i].algo === algorithm) {
+ metadataList[pos++] = metadataList[i]
+ }
}
- for (const part of cookie.unparsed) {
- if (!part.includes('=')) {
- throw new Error('Invalid unparsed')
+ metadataList.length = pos
+
+ return metadataList
+}
+
+/**
+ * Compares two base64 strings, allowing for base64url
+ * in the second string.
+ *
+* @param {string} actualValue always base64
+ * @param {string} expectedValue base64 or base64url
+ * @returns {boolean}
+ */
+function compareBase64Mixed (actualValue, expectedValue) {
+ if (actualValue.length !== expectedValue.length) {
+ return false
+ }
+ for (let i = 0; i < actualValue.length; ++i) {
+ if (actualValue[i] !== expectedValue[i]) {
+ if (
+ (actualValue[i] === '+' && expectedValue[i] === '-') ||
+ (actualValue[i] === '/' && expectedValue[i] === '_')
+ ) {
+ continue
+ }
+ return false
}
+ }
- const [key, ...value] = part.split('=')
+ return true
+}
+
+// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
+function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
+ // TODO
+}
+
+/**
+ * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
+ * @param {URL} A
+ * @param {URL} B
+ */
+function sameOrigin (A, B) {
+ // 1. If A and B are the same opaque origin, then return true.
+ if (A.origin === B.origin && A.origin === 'null') {
+ return true
+ }
- out.push(`${key.trim()}=${value.join('=')}`)
+ // 2. If A and B are both tuple origins and their schemes,
+ // hosts, and port are identical, then return true.
+ if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
+ return true
}
- return out.join('; ')
+ // 3. Return false.
+ return false
}
-let kHeadersListNode
-
-function getHeadersList (headers) {
- if (headers[kHeadersList]) {
- return headers[kHeadersList]
- }
-
- if (!kHeadersListNode) {
- kHeadersListNode = Object.getOwnPropertySymbols(headers).find(
- (symbol) => symbol.description === 'headers list'
- )
+function createDeferredPromise () {
+ let res
+ let rej
+ const promise = new Promise((resolve, reject) => {
+ res = resolve
+ rej = reject
+ })
- assert(kHeadersListNode, 'Headers cannot be parsed')
- }
+ return { promise, resolve: res, reject: rej }
+}
- const headersList = headers[kHeadersListNode]
- assert(headersList)
+function isAborted (fetchParams) {
+ return fetchParams.controller.state === 'aborted'
+}
- return headersList
+function isCancelled (fetchParams) {
+ return fetchParams.controller.state === 'aborted' ||
+ fetchParams.controller.state === 'terminated'
}
-module.exports = {
- isCTLExcludingHtab,
- stringify,
- getHeadersList
+const normalizeMethodRecord = {
+ delete: 'DELETE',
+ DELETE: 'DELETE',
+ get: 'GET',
+ GET: 'GET',
+ head: 'HEAD',
+ HEAD: 'HEAD',
+ options: 'OPTIONS',
+ OPTIONS: 'OPTIONS',
+ post: 'POST',
+ POST: 'POST',
+ put: 'PUT',
+ PUT: 'PUT'
}
+// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
+Object.setPrototypeOf(normalizeMethodRecord, null)
-/***/ }),
+/**
+ * @see https://fetch.spec.whatwg.org/#concept-method-normalize
+ * @param {string} method
+ */
+function normalizeMethod (method) {
+ return normalizeMethodRecord[method.toLowerCase()] ?? method
+}
-/***/ 91332:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
+function serializeJavascriptValueToJSONString (value) {
+ // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
+ const result = JSON.stringify(value)
+ // 2. If result is undefined, then throw a TypeError.
+ if (result === undefined) {
+ throw new TypeError('Value is not JSON serializable')
+ }
+ // 3. Assert: result is a string.
+ assert(typeof result === 'string')
-const net = __nccwpck_require__(69278)
-const assert = __nccwpck_require__(42613)
-const util = __nccwpck_require__(89500)
-const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(53959)
+ // 4. Return result.
+ return result
+}
-let tls // include tls conditionally since it is not always available
+// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
+const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
-// TODO: session re-use does not wait for the first
-// connection to resolve the session and might therefore
-// resolve the same servername multiple times even when
-// re-use is enabled.
+/**
+ * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
+ * @param {() => unknown[]} iterator
+ * @param {string} name name of the instance
+ * @param {'key'|'value'|'key+value'} kind
+ */
+function makeIterator (iterator, name, kind) {
+ const object = {
+ index: 0,
+ kind,
+ target: iterator
+ }
-let SessionCache
-// FIXME: remove workaround when the Node bug is fixed
-// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308
-if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) {
- SessionCache = class WeakSessionCache {
- constructor (maxCachedSessions) {
- this._maxCachedSessions = maxCachedSessions
- this._sessionCache = new Map()
- this._sessionRegistry = new global.FinalizationRegistry((key) => {
- if (this._sessionCache.size < this._maxCachedSessions) {
- return
- }
+ const i = {
+ next () {
+ // 1. Let interface be the interface for which the iterator prototype object exists.
- const ref = this._sessionCache.get(key)
- if (ref !== undefined && ref.deref() === undefined) {
- this._sessionCache.delete(key)
- }
- })
- }
+ // 2. Let thisValue be the this value.
- get (sessionKey) {
- const ref = this._sessionCache.get(sessionKey)
- return ref ? ref.deref() : null
- }
+ // 3. Let object be ? ToObject(thisValue).
- set (sessionKey, session) {
- if (this._maxCachedSessions === 0) {
- return
+ // 4. If object is a platform object, then perform a security
+ // check, passing:
+
+ // 5. If object is not a default iterator object for interface,
+ // then throw a TypeError.
+ if (Object.getPrototypeOf(this) !== i) {
+ throw new TypeError(
+ `'next' called on an object that does not implement interface ${name} Iterator.`
+ )
}
- this._sessionCache.set(sessionKey, new WeakRef(session))
- this._sessionRegistry.register(session, sessionKey)
- }
- }
-} else {
- SessionCache = class SimpleSessionCache {
- constructor (maxCachedSessions) {
- this._maxCachedSessions = maxCachedSessions
- this._sessionCache = new Map()
- }
+ // 6. Let index be object’s index.
+ // 7. Let kind be object’s kind.
+ // 8. Let values be object’s target's value pairs to iterate over.
+ const { index, kind, target } = object
+ const values = target()
- get (sessionKey) {
- return this._sessionCache.get(sessionKey)
- }
+ // 9. Let len be the length of values.
+ const len = values.length
- set (sessionKey, session) {
- if (this._maxCachedSessions === 0) {
- return
+ // 10. If index is greater than or equal to len, then return
+ // CreateIterResultObject(undefined, true).
+ if (index >= len) {
+ return { value: undefined, done: true }
}
- if (this._sessionCache.size >= this._maxCachedSessions) {
- // remove the oldest session
- const { value: oldestKey } = this._sessionCache.keys().next()
- this._sessionCache.delete(oldestKey)
- }
+ // 11. Let pair be the entry in values at index index.
+ const pair = values[index]
- this._sessionCache.set(sessionKey, session)
- }
- }
-}
+ // 12. Set object’s index to index + 1.
+ object.index = index + 1
-function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) {
- if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) {
- throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero')
+ // 13. Return the iterator result for pair and kind.
+ return iteratorResult(pair, kind)
+ },
+ // The class string of an iterator prototype object for a given interface is the
+ // result of concatenating the identifier of the interface and the string " Iterator".
+ [Symbol.toStringTag]: `${name} Iterator`
}
- const options = { path: socketPath, ...opts }
- const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions)
- timeout = timeout == null ? 10e3 : timeout
- allowH2 = allowH2 != null ? allowH2 : false
- return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) {
- let socket
- if (protocol === 'https:') {
- if (!tls) {
- tls = __nccwpck_require__(64756)
- }
- servername = servername || options.servername || util.getServerName(host) || null
-
- const sessionKey = servername || hostname
- const session = sessionCache.get(sessionKey) || null
-
- assert(sessionKey)
+ // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.
+ Object.setPrototypeOf(i, esIteratorPrototype)
+ // esIteratorPrototype needs to be the prototype of i
+ // which is the prototype of an empty object. Yes, it's confusing.
+ return Object.setPrototypeOf({}, i)
+}
- socket = tls.connect({
- highWaterMark: 16384, // TLS in node can't have bigger HWM anyway...
- ...options,
- servername,
- session,
- localAddress,
- // TODO(HTTP/2): Add support for h2c
- ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'],
- socket: httpSocket, // upgrade socket connection
- port: port || 443,
- host: hostname
- })
+// https://webidl.spec.whatwg.org/#iterator-result
+function iteratorResult (pair, kind) {
+ let result
- socket
- .on('session', function (session) {
- // TODO (fix): Can a session become invalid once established? Don't think so?
- sessionCache.set(sessionKey, session)
- })
- } else {
- assert(!httpSocket, 'httpSocket can only be sent on TLS update')
- socket = net.connect({
- highWaterMark: 64 * 1024, // Same as nodejs fs streams.
- ...options,
- localAddress,
- port: port || 80,
- host: hostname
- })
+ // 1. Let result be a value determined by the value of kind:
+ switch (kind) {
+ case 'key': {
+ // 1. Let idlKey be pair’s key.
+ // 2. Let key be the result of converting idlKey to an
+ // ECMAScript value.
+ // 3. result is key.
+ result = pair[0]
+ break
}
-
- // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket
- if (options.keepAlive == null || options.keepAlive) {
- const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay
- socket.setKeepAlive(true, keepAliveInitialDelay)
+ case 'value': {
+ // 1. Let idlValue be pair’s value.
+ // 2. Let value be the result of converting idlValue to
+ // an ECMAScript value.
+ // 3. result is value.
+ result = pair[1]
+ break
+ }
+ case 'key+value': {
+ // 1. Let idlKey be pair’s key.
+ // 2. Let idlValue be pair’s value.
+ // 3. Let key be the result of converting idlKey to an
+ // ECMAScript value.
+ // 4. Let value be the result of converting idlValue to
+ // an ECMAScript value.
+ // 5. Let array be ! ArrayCreate(2).
+ // 6. Call ! CreateDataProperty(array, "0", key).
+ // 7. Call ! CreateDataProperty(array, "1", value).
+ // 8. result is array.
+ result = pair
+ break
}
+ }
- const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout)
+ // 2. Return CreateIterResultObject(result, false).
+ return { value: result, done: false }
+}
- socket
- .setNoDelay(true)
- .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () {
- cancelTimeout()
+/**
+ * @see https://fetch.spec.whatwg.org/#body-fully-read
+ */
+async function fullyReadBody (body, processBody, processBodyError) {
+ // 1. If taskDestination is null, then set taskDestination to
+ // the result of starting a new parallel queue.
- if (callback) {
- const cb = callback
- callback = null
- cb(null, this)
- }
- })
- .on('error', function (err) {
- cancelTimeout()
+ // 2. Let successSteps given a byte sequence bytes be to queue a
+ // fetch task to run processBody given bytes, with taskDestination.
+ const successSteps = processBody
- if (callback) {
- const cb = callback
- callback = null
- cb(err)
- }
- })
+ // 3. Let errorSteps be to queue a fetch task to run processBodyError,
+ // with taskDestination.
+ const errorSteps = processBodyError
- return socket
- }
-}
+ // 4. Let reader be the result of getting a reader for body’s stream.
+ // If that threw an exception, then run errorSteps with that
+ // exception and return.
+ let reader
-function setupTimeout (onConnectTimeout, timeout) {
- if (!timeout) {
- return () => {}
+ try {
+ reader = body.stream.getReader()
+ } catch (e) {
+ errorSteps(e)
+ return
}
- let s1 = null
- let s2 = null
- const timeoutId = setTimeout(() => {
- // setImmediate is added to make sure that we priotorise socket error events over timeouts
- s1 = setImmediate(() => {
- if (process.platform === 'win32') {
- // Windows needs an extra setImmediate probably due to implementation differences in the socket logic
- s2 = setImmediate(() => onConnectTimeout())
- } else {
- onConnectTimeout()
- }
- })
- }, timeout)
- return () => {
- clearTimeout(timeoutId)
- clearImmediate(s1)
- clearImmediate(s2)
+ // 5. Read all bytes from reader, given successSteps and errorSteps.
+ try {
+ const result = await readAllBytes(reader)
+ successSteps(result)
+ } catch (e) {
+ errorSteps(e)
}
}
-function onConnectTimeout (socket) {
- util.destroy(socket, new ConnectTimeoutError())
-}
-
-module.exports = buildConnector
-
+/** @type {ReadableStream} */
+let ReadableStream = globalThis.ReadableStream
-/***/ }),
+function isReadableStreamLike (stream) {
+ if (!ReadableStream) {
+ ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ }
-/***/ 42371:
-/***/ ((module) => {
+ return stream instanceof ReadableStream || (
+ stream[Symbol.toStringTag] === 'ReadableStream' &&
+ typeof stream.tee === 'function'
+ )
+}
+const MAXIMUM_ARGUMENT_LENGTH = 65535
+/**
+ * @see https://infra.spec.whatwg.org/#isomorphic-decode
+ * @param {number[]|Uint8Array} input
+ */
+function isomorphicDecode (input) {
+ // 1. To isomorphic decode a byte sequence input, return a string whose code point
+ // length is equal to input’s length and whose code points have the same values
+ // as the values of input’s bytes, in the same order.
-/** @type {Record} */
-const headerNameLowerCasedRecord = {}
+ if (input.length < MAXIMUM_ARGUMENT_LENGTH) {
+ return String.fromCharCode(...input)
+ }
-// https://developer.mozilla.org/docs/Web/HTTP/Headers
-const wellknownHeaderNames = [
- 'Accept',
- 'Accept-Encoding',
- 'Accept-Language',
- 'Accept-Ranges',
- 'Access-Control-Allow-Credentials',
- 'Access-Control-Allow-Headers',
- 'Access-Control-Allow-Methods',
- 'Access-Control-Allow-Origin',
- 'Access-Control-Expose-Headers',
- 'Access-Control-Max-Age',
- 'Access-Control-Request-Headers',
- 'Access-Control-Request-Method',
- 'Age',
- 'Allow',
- 'Alt-Svc',
- 'Alt-Used',
- 'Authorization',
- 'Cache-Control',
- 'Clear-Site-Data',
- 'Connection',
- 'Content-Disposition',
- 'Content-Encoding',
- 'Content-Language',
- 'Content-Length',
- 'Content-Location',
- 'Content-Range',
- 'Content-Security-Policy',
- 'Content-Security-Policy-Report-Only',
- 'Content-Type',
- 'Cookie',
- 'Cross-Origin-Embedder-Policy',
- 'Cross-Origin-Opener-Policy',
- 'Cross-Origin-Resource-Policy',
- 'Date',
- 'Device-Memory',
- 'Downlink',
- 'ECT',
- 'ETag',
- 'Expect',
- 'Expect-CT',
- 'Expires',
- 'Forwarded',
- 'From',
- 'Host',
- 'If-Match',
- 'If-Modified-Since',
- 'If-None-Match',
- 'If-Range',
- 'If-Unmodified-Since',
- 'Keep-Alive',
- 'Last-Modified',
- 'Link',
- 'Location',
- 'Max-Forwards',
- 'Origin',
- 'Permissions-Policy',
- 'Pragma',
- 'Proxy-Authenticate',
- 'Proxy-Authorization',
- 'RTT',
- 'Range',
- 'Referer',
- 'Referrer-Policy',
- 'Refresh',
- 'Retry-After',
- 'Sec-WebSocket-Accept',
- 'Sec-WebSocket-Extensions',
- 'Sec-WebSocket-Key',
- 'Sec-WebSocket-Protocol',
- 'Sec-WebSocket-Version',
- 'Server',
- 'Server-Timing',
- 'Service-Worker-Allowed',
- 'Service-Worker-Navigation-Preload',
- 'Set-Cookie',
- 'SourceMap',
- 'Strict-Transport-Security',
- 'Supports-Loading-Mode',
- 'TE',
- 'Timing-Allow-Origin',
- 'Trailer',
- 'Transfer-Encoding',
- 'Upgrade',
- 'Upgrade-Insecure-Requests',
- 'User-Agent',
- 'Vary',
- 'Via',
- 'WWW-Authenticate',
- 'X-Content-Type-Options',
- 'X-DNS-Prefetch-Control',
- 'X-Frame-Options',
- 'X-Permitted-Cross-Domain-Policies',
- 'X-Powered-By',
- 'X-Requested-With',
- 'X-XSS-Protection'
-]
+ return input.reduce((previous, current) => previous + String.fromCharCode(current), '')
+}
-for (let i = 0; i < wellknownHeaderNames.length; ++i) {
- const key = wellknownHeaderNames[i]
- const lowerCasedKey = key.toLowerCase()
- headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] =
- lowerCasedKey
+/**
+ * @param {ReadableStreamController} controller
+ */
+function readableStreamClose (controller) {
+ try {
+ controller.close()
+ } catch (err) {
+ // TODO: add comment explaining why this error occurs.
+ if (!err.message.includes('Controller is already closed')) {
+ throw err
+ }
+ }
}
-// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
-Object.setPrototypeOf(headerNameLowerCasedRecord, null)
+/**
+ * @see https://infra.spec.whatwg.org/#isomorphic-encode
+ * @param {string} input
+ */
+function isomorphicEncode (input) {
+ // 1. Assert: input contains no code points greater than U+00FF.
+ for (let i = 0; i < input.length; i++) {
+ assert(input.charCodeAt(i) <= 0xFF)
+ }
-module.exports = {
- wellknownHeaderNames,
- headerNameLowerCasedRecord
+ // 2. Return a byte sequence whose length is equal to input’s code
+ // point length and whose bytes have the same values as the
+ // values of input’s code points, in the same order
+ return input
}
+/**
+ * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
+ * @see https://streams.spec.whatwg.org/#read-loop
+ * @param {ReadableStreamDefaultReader} reader
+ */
+async function readAllBytes (reader) {
+ const bytes = []
+ let byteLength = 0
-/***/ }),
+ while (true) {
+ const { done, value: chunk } = await reader.read()
-/***/ 53959:
-/***/ ((module) => {
+ if (done) {
+ // 1. Call successSteps with bytes.
+ return Buffer.concat(bytes, byteLength)
+ }
+ // 1. If chunk is not a Uint8Array object, call failureSteps
+ // with a TypeError and abort these steps.
+ if (!isUint8Array(chunk)) {
+ throw new TypeError('Received non-Uint8Array chunk')
+ }
+ // 2. Append the bytes represented by chunk to bytes.
+ bytes.push(chunk)
+ byteLength += chunk.length
-class UndiciError extends Error {
- constructor (message) {
- super(message)
- this.name = 'UndiciError'
- this.code = 'UND_ERR'
+ // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
}
}
-class ConnectTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ConnectTimeoutError)
- this.name = 'ConnectTimeoutError'
- this.message = message || 'Connect Timeout Error'
- this.code = 'UND_ERR_CONNECT_TIMEOUT'
- }
-}
+/**
+ * @see https://fetch.spec.whatwg.org/#is-local
+ * @param {URL} url
+ */
+function urlIsLocal (url) {
+ assert('protocol' in url) // ensure it's a url object
-class HeadersTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, HeadersTimeoutError)
- this.name = 'HeadersTimeoutError'
- this.message = message || 'Headers Timeout Error'
- this.code = 'UND_ERR_HEADERS_TIMEOUT'
- }
-}
+ const protocol = url.protocol
-class HeadersOverflowError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, HeadersOverflowError)
- this.name = 'HeadersOverflowError'
- this.message = message || 'Headers Overflow Error'
- this.code = 'UND_ERR_HEADERS_OVERFLOW'
- }
+ return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
}
-class BodyTimeoutError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, BodyTimeoutError)
- this.name = 'BodyTimeoutError'
- this.message = message || 'Body Timeout Error'
- this.code = 'UND_ERR_BODY_TIMEOUT'
+/**
+ * @param {string|URL} url
+ */
+function urlHasHttpsScheme (url) {
+ if (typeof url === 'string') {
+ return url.startsWith('https:')
}
-}
-class ResponseStatusCodeError extends UndiciError {
- constructor (message, statusCode, headers, body) {
- super(message)
- Error.captureStackTrace(this, ResponseStatusCodeError)
- this.name = 'ResponseStatusCodeError'
- this.message = message || 'Response Status Code Error'
- this.code = 'UND_ERR_RESPONSE_STATUS_CODE'
- this.body = body
- this.status = statusCode
- this.statusCode = statusCode
- this.headers = headers
- }
+ return url.protocol === 'https:'
}
-class InvalidArgumentError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, InvalidArgumentError)
- this.name = 'InvalidArgumentError'
- this.message = message || 'Invalid Argument Error'
- this.code = 'UND_ERR_INVALID_ARG'
- }
-}
+/**
+ * @see https://fetch.spec.whatwg.org/#http-scheme
+ * @param {URL} url
+ */
+function urlIsHttpHttpsScheme (url) {
+ assert('protocol' in url) // ensure it's a url object
-class InvalidReturnValueError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, InvalidReturnValueError)
- this.name = 'InvalidReturnValueError'
- this.message = message || 'Invalid Return Value Error'
- this.code = 'UND_ERR_INVALID_RETURN_VALUE'
- }
-}
+ const protocol = url.protocol
-class RequestAbortedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, RequestAbortedError)
- this.name = 'AbortError'
- this.message = message || 'Request aborted'
- this.code = 'UND_ERR_ABORTED'
- }
+ return protocol === 'http:' || protocol === 'https:'
}
-class InformationalError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, InformationalError)
- this.name = 'InformationalError'
- this.message = message || 'Request information'
- this.code = 'UND_ERR_INFO'
- }
-}
+/**
+ * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.
+ */
+const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))
-class RequestContentLengthMismatchError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, RequestContentLengthMismatchError)
- this.name = 'RequestContentLengthMismatchError'
- this.message = message || 'Request body length does not match content-length header'
- this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
- }
+module.exports = {
+ isAborted,
+ isCancelled,
+ createDeferredPromise,
+ ReadableStreamFrom,
+ toUSVString,
+ tryUpgradeRequestToAPotentiallyTrustworthyURL,
+ coarsenedSharedCurrentTime,
+ determineRequestsReferrer,
+ makePolicyContainer,
+ clonePolicyContainer,
+ appendFetchMetadata,
+ appendRequestOriginHeader,
+ TAOCheck,
+ corsCheck,
+ crossOriginResourcePolicyCheck,
+ createOpaqueTimingInfo,
+ setRequestReferrerPolicyOnRedirect,
+ isValidHTTPToken,
+ requestBadPort,
+ requestCurrentURL,
+ responseURL,
+ responseLocationURL,
+ isBlobLike,
+ isURLPotentiallyTrustworthy,
+ isValidReasonPhrase,
+ sameOrigin,
+ normalizeMethod,
+ serializeJavascriptValueToJSONString,
+ makeIterator,
+ isValidHeaderName,
+ isValidHeaderValue,
+ hasOwn,
+ isErrorLike,
+ fullyReadBody,
+ bytesMatch,
+ isReadableStreamLike,
+ readableStreamClose,
+ isomorphicEncode,
+ isomorphicDecode,
+ urlIsLocal,
+ urlHasHttpsScheme,
+ urlIsHttpHttpsScheme,
+ readAllBytes,
+ normalizeMethodRecord,
+ parseMetadata
}
-class ResponseContentLengthMismatchError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ResponseContentLengthMismatchError)
- this.name = 'ResponseContentLengthMismatchError'
- this.message = message || 'Response body length does not match content-length header'
- this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'
- }
-}
-class ClientDestroyedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ClientDestroyedError)
- this.name = 'ClientDestroyedError'
- this.message = message || 'The client is destroyed'
- this.code = 'UND_ERR_DESTROYED'
- }
-}
+/***/ }),
-class ClientClosedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ClientClosedError)
- this.name = 'ClientClosedError'
- this.message = message || 'The client is closed'
- this.code = 'UND_ERR_CLOSED'
- }
-}
+/***/ 94354:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-class SocketError extends UndiciError {
- constructor (message, socket) {
- super(message)
- Error.captureStackTrace(this, SocketError)
- this.name = 'SocketError'
- this.message = message || 'Socket error'
- this.code = 'UND_ERR_SOCKET'
- this.socket = socket
- }
+
+
+const { types } = __nccwpck_require__(39023)
+const { hasOwn, toUSVString } = __nccwpck_require__(72847)
+
+/** @type {import('../../types/webidl').Webidl} */
+const webidl = {}
+webidl.converters = {}
+webidl.util = {}
+webidl.errors = {}
+
+webidl.errors.exception = function (message) {
+ return new TypeError(`${message.header}: ${message.message}`)
}
-class NotSupportedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, NotSupportedError)
- this.name = 'NotSupportedError'
- this.message = message || 'Not supported error'
- this.code = 'UND_ERR_NOT_SUPPORTED'
- }
+webidl.errors.conversionFailed = function (context) {
+ const plural = context.types.length === 1 ? '' : ' one of'
+ const message =
+ `${context.argument} could not be converted to` +
+ `${plural}: ${context.types.join(', ')}.`
+
+ return webidl.errors.exception({
+ header: context.prefix,
+ message
+ })
}
-class BalancedPoolMissingUpstreamError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, NotSupportedError)
- this.name = 'MissingUpstreamError'
- this.message = message || 'No upstream has been added to the BalancedPool'
- this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'
- }
+webidl.errors.invalidArgument = function (context) {
+ return webidl.errors.exception({
+ header: context.prefix,
+ message: `"${context.value}" is an invalid ${context.type}.`
+ })
}
-class HTTPParserError extends Error {
- constructor (message, code, data) {
- super(message)
- Error.captureStackTrace(this, HTTPParserError)
- this.name = 'HTTPParserError'
- this.code = code ? `HPE_${code}` : undefined
- this.data = data ? data.toString() : undefined
+// https://webidl.spec.whatwg.org/#implements
+webidl.brandCheck = function (V, I, opts = undefined) {
+ if (opts?.strict !== false && !(V instanceof I)) {
+ throw new TypeError('Illegal invocation')
+ } else {
+ return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]
}
}
-class ResponseExceededMaxSizeError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, ResponseExceededMaxSizeError)
- this.name = 'ResponseExceededMaxSizeError'
- this.message = message || 'Response content exceeded max size'
- this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'
+webidl.argumentLengthCheck = function ({ length }, min, ctx) {
+ if (length < min) {
+ throw webidl.errors.exception({
+ message: `${min} argument${min !== 1 ? 's' : ''} required, ` +
+ `but${length ? ' only' : ''} ${length} found.`,
+ ...ctx
+ })
}
}
-class RequestRetryError extends UndiciError {
- constructor (message, code, { headers, data }) {
- super(message)
- Error.captureStackTrace(this, RequestRetryError)
- this.name = 'RequestRetryError'
- this.message = message || 'Request retry error'
- this.code = 'UND_ERR_REQ_RETRY'
- this.statusCode = code
- this.data = data
- this.headers = headers
- }
+webidl.illegalConstructor = function () {
+ throw webidl.errors.exception({
+ header: 'TypeError',
+ message: 'Illegal constructor'
+ })
}
-module.exports = {
- HTTPParserError,
- UndiciError,
- HeadersTimeoutError,
- HeadersOverflowError,
- BodyTimeoutError,
- RequestContentLengthMismatchError,
- ConnectTimeoutError,
- ResponseStatusCodeError,
- InvalidArgumentError,
- InvalidReturnValueError,
- RequestAbortedError,
- ClientDestroyedError,
- ClientClosedError,
- InformationalError,
- SocketError,
- NotSupportedError,
- ResponseContentLengthMismatchError,
- BalancedPoolMissingUpstreamError,
- ResponseExceededMaxSizeError,
- RequestRetryError
+// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
+webidl.util.Type = function (V) {
+ switch (typeof V) {
+ case 'undefined': return 'Undefined'
+ case 'boolean': return 'Boolean'
+ case 'string': return 'String'
+ case 'symbol': return 'Symbol'
+ case 'number': return 'Number'
+ case 'bigint': return 'BigInt'
+ case 'function':
+ case 'object': {
+ if (V === null) {
+ return 'Null'
+ }
+
+ return 'Object'
+ }
+ }
}
+// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
+webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {
+ let upperBound
+ let lowerBound
-/***/ }),
+ // 1. If bitLength is 64, then:
+ if (bitLength === 64) {
+ // 1. Let upperBound be 2^53 − 1.
+ upperBound = Math.pow(2, 53) - 1
-/***/ 69691:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. If signedness is "unsigned", then let lowerBound be 0.
+ if (signedness === 'unsigned') {
+ lowerBound = 0
+ } else {
+ // 3. Otherwise let lowerBound be −2^53 + 1.
+ lowerBound = Math.pow(-2, 53) + 1
+ }
+ } else if (signedness === 'unsigned') {
+ // 2. Otherwise, if signedness is "unsigned", then:
+ // 1. Let lowerBound be 0.
+ lowerBound = 0
+ // 2. Let upperBound be 2^bitLength − 1.
+ upperBound = Math.pow(2, bitLength) - 1
+ } else {
+ // 3. Otherwise:
-const {
- InvalidArgumentError,
- NotSupportedError
-} = __nccwpck_require__(53959)
-const assert = __nccwpck_require__(42613)
-const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(68031)
-const util = __nccwpck_require__(89500)
+ // 1. Let lowerBound be -2^bitLength − 1.
+ lowerBound = Math.pow(-2, bitLength) - 1
-// tokenRegExp and headerCharRegex have been lifted from
-// https://github.com/nodejs/node/blob/main/lib/_http_common.js
+ // 2. Let upperBound be 2^bitLength − 1 − 1.
+ upperBound = Math.pow(2, bitLength - 1) - 1
+ }
-/**
- * Verifies that the given val is a valid HTTP token
- * per the rules defined in RFC 7230
- * See https://tools.ietf.org/html/rfc7230#section-3.2.6
- */
-const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/
+ // 4. Let x be ? ToNumber(V).
+ let x = Number(V)
-/**
- * Matches if val contains an invalid field-vchar
- * field-value = *( field-content / obs-fold )
- * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
- * field-vchar = VCHAR / obs-text
- */
-const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/
+ // 5. If x is −0, then set x to +0.
+ if (x === 0) {
+ x = 0
+ }
-// Verifies that a given path is valid does not contain control chars \x00 to \x20
-const invalidPathRegex = /[^\u0021-\u00ff]/
+ // 6. If the conversion is to an IDL type associated
+ // with the [EnforceRange] extended attribute, then:
+ if (opts.enforceRange === true) {
+ // 1. If x is NaN, +∞, or −∞, then throw a TypeError.
+ if (
+ Number.isNaN(x) ||
+ x === Number.POSITIVE_INFINITY ||
+ x === Number.NEGATIVE_INFINITY
+ ) {
+ throw webidl.errors.exception({
+ header: 'Integer conversion',
+ message: `Could not convert ${V} to an integer.`
+ })
+ }
-const kHandler = Symbol('handler')
+ // 2. Set x to IntegerPart(x).
+ x = webidl.util.IntegerPart(x)
-const channels = {}
+ // 3. If x < lowerBound or x > upperBound, then
+ // throw a TypeError.
+ if (x < lowerBound || x > upperBound) {
+ throw webidl.errors.exception({
+ header: 'Integer conversion',
+ message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
+ })
+ }
-let extractBody
+ // 4. Return x.
+ return x
+ }
-try {
- const diagnosticsChannel = __nccwpck_require__(31637)
- channels.create = diagnosticsChannel.channel('undici:request:create')
- channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent')
- channels.headers = diagnosticsChannel.channel('undici:request:headers')
- channels.trailers = diagnosticsChannel.channel('undici:request:trailers')
- channels.error = diagnosticsChannel.channel('undici:request:error')
-} catch {
- channels.create = { hasSubscribers: false }
- channels.bodySent = { hasSubscribers: false }
- channels.headers = { hasSubscribers: false }
- channels.trailers = { hasSubscribers: false }
- channels.error = { hasSubscribers: false }
-}
+ // 7. If x is not NaN and the conversion is to an IDL
+ // type associated with the [Clamp] extended
+ // attribute, then:
+ if (!Number.isNaN(x) && opts.clamp === true) {
+ // 1. Set x to min(max(x, lowerBound), upperBound).
+ x = Math.min(Math.max(x, lowerBound), upperBound)
-class Request {
- constructor (origin, {
- path,
- method,
- body,
- headers,
- query,
- idempotent,
- blocking,
- upgrade,
- headersTimeout,
- bodyTimeout,
- reset,
- throwOnError,
- expectContinue
- }, handler) {
- if (typeof path !== 'string') {
- throw new InvalidArgumentError('path must be a string')
- } else if (
- path[0] !== '/' &&
- !(path.startsWith('http://') || path.startsWith('https://')) &&
- method !== 'CONNECT'
- ) {
- throw new InvalidArgumentError('path must be an absolute URL or start with a slash')
- } else if (invalidPathRegex.exec(path) !== null) {
- throw new InvalidArgumentError('invalid request path')
+ // 2. Round x to the nearest integer, choosing the
+ // even integer if it lies halfway between two,
+ // and choosing +0 rather than −0.
+ if (Math.floor(x) % 2 === 0) {
+ x = Math.floor(x)
+ } else {
+ x = Math.ceil(x)
}
- if (typeof method !== 'string') {
- throw new InvalidArgumentError('method must be a string')
- } else if (tokenRegExp.exec(method) === null) {
- throw new InvalidArgumentError('invalid request method')
- }
+ // 3. Return x.
+ return x
+ }
- if (upgrade && typeof upgrade !== 'string') {
- throw new InvalidArgumentError('upgrade must be a string')
- }
+ // 8. If x is NaN, +0, +∞, or −∞, then return +0.
+ if (
+ Number.isNaN(x) ||
+ (x === 0 && Object.is(0, x)) ||
+ x === Number.POSITIVE_INFINITY ||
+ x === Number.NEGATIVE_INFINITY
+ ) {
+ return 0
+ }
- if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) {
- throw new InvalidArgumentError('invalid headersTimeout')
- }
+ // 9. Set x to IntegerPart(x).
+ x = webidl.util.IntegerPart(x)
- if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) {
- throw new InvalidArgumentError('invalid bodyTimeout')
- }
+ // 10. Set x to x modulo 2^bitLength.
+ x = x % Math.pow(2, bitLength)
- if (reset != null && typeof reset !== 'boolean') {
- throw new InvalidArgumentError('invalid reset')
- }
+ // 11. If signedness is "signed" and x ≥ 2^bitLength − 1,
+ // then return x − 2^bitLength.
+ if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
+ return x - Math.pow(2, bitLength)
+ }
- if (expectContinue != null && typeof expectContinue !== 'boolean') {
- throw new InvalidArgumentError('invalid expectContinue')
- }
+ // 12. Otherwise, return x.
+ return x
+}
- this.headersTimeout = headersTimeout
+// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
+webidl.util.IntegerPart = function (n) {
+ // 1. Let r be floor(abs(n)).
+ const r = Math.floor(Math.abs(n))
- this.bodyTimeout = bodyTimeout
+ // 2. If n < 0, then return -1 × r.
+ if (n < 0) {
+ return -1 * r
+ }
- this.throwOnError = throwOnError === true
+ // 3. Otherwise, return r.
+ return r
+}
- this.method = method
+// https://webidl.spec.whatwg.org/#es-sequence
+webidl.sequenceConverter = function (converter) {
+ return (V) => {
+ // 1. If Type(V) is not Object, throw a TypeError.
+ if (webidl.util.Type(V) !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Sequence',
+ message: `Value of type ${webidl.util.Type(V)} is not an Object.`
+ })
+ }
- this.abort = null
+ // 2. Let method be ? GetMethod(V, @@iterator).
+ /** @type {Generator} */
+ const method = V?.[Symbol.iterator]?.()
+ const seq = []
- if (body == null) {
- this.body = null
- } else if (util.isStream(body)) {
- this.body = body
+ // 3. If method is undefined, throw a TypeError.
+ if (
+ method === undefined ||
+ typeof method.next !== 'function'
+ ) {
+ throw webidl.errors.exception({
+ header: 'Sequence',
+ message: 'Object is not an iterator.'
+ })
+ }
- const rState = this.body._readableState
- if (!rState || !rState.autoDestroy) {
- this.endHandler = function autoDestroy () {
- util.destroy(this)
- }
- this.body.on('end', this.endHandler)
- }
+ // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
+ while (true) {
+ const { done, value } = method.next()
- this.errorHandler = err => {
- if (this.abort) {
- this.abort(err)
- } else {
- this.error = err
- }
+ if (done) {
+ break
}
- this.body.on('error', this.errorHandler)
- } else if (util.isBuffer(body)) {
- this.body = body.byteLength ? body : null
- } else if (ArrayBuffer.isView(body)) {
- this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null
- } else if (body instanceof ArrayBuffer) {
- this.body = body.byteLength ? Buffer.from(body) : null
- } else if (typeof body === 'string') {
- this.body = body.length ? Buffer.from(body) : null
- } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) {
- this.body = body
- } else {
- throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable')
- }
- this.completed = false
+ seq.push(converter(value))
+ }
- this.aborted = false
+ return seq
+ }
+}
- this.upgrade = upgrade || null
+// https://webidl.spec.whatwg.org/#es-to-record
+webidl.recordConverter = function (keyConverter, valueConverter) {
+ return (O) => {
+ // 1. If Type(O) is not Object, throw a TypeError.
+ if (webidl.util.Type(O) !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Record',
+ message: `Value of type ${webidl.util.Type(O)} is not an Object.`
+ })
+ }
- this.path = query ? util.buildURL(path, query) : path
+ // 2. Let result be a new empty instance of record.
+ const result = {}
- this.origin = origin
+ if (!types.isProxy(O)) {
+ // Object.keys only returns enumerable properties
+ const keys = Object.keys(O)
- this.idempotent = idempotent == null
- ? method === 'HEAD' || method === 'GET'
- : idempotent
+ for (const key of keys) {
+ // 1. Let typedKey be key converted to an IDL value of type K.
+ const typedKey = keyConverter(key)
- this.blocking = blocking == null ? false : blocking
+ // 2. Let value be ? Get(O, key).
+ // 3. Let typedValue be value converted to an IDL value of type V.
+ const typedValue = valueConverter(O[key])
- this.reset = reset == null ? null : reset
+ // 4. Set result[typedKey] to typedValue.
+ result[typedKey] = typedValue
+ }
- this.host = null
+ // 5. Return result.
+ return result
+ }
- this.contentLength = null
+ // 3. Let keys be ? O.[[OwnPropertyKeys]]().
+ const keys = Reflect.ownKeys(O)
- this.contentType = null
+ // 4. For each key of keys.
+ for (const key of keys) {
+ // 1. Let desc be ? O.[[GetOwnProperty]](key).
+ const desc = Reflect.getOwnPropertyDescriptor(O, key)
- this.headers = ''
+ // 2. If desc is not undefined and desc.[[Enumerable]] is true:
+ if (desc?.enumerable) {
+ // 1. Let typedKey be key converted to an IDL value of type K.
+ const typedKey = keyConverter(key)
- // Only for H2
- this.expectContinue = expectContinue != null ? expectContinue : false
+ // 2. Let value be ? Get(O, key).
+ // 3. Let typedValue be value converted to an IDL value of type V.
+ const typedValue = valueConverter(O[key])
- if (Array.isArray(headers)) {
- if (headers.length % 2 !== 0) {
- throw new InvalidArgumentError('headers array must be even')
- }
- for (let i = 0; i < headers.length; i += 2) {
- processHeader(this, headers[i], headers[i + 1])
- }
- } else if (headers && typeof headers === 'object') {
- const keys = Object.keys(headers)
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i]
- processHeader(this, key, headers[key])
+ // 4. Set result[typedKey] to typedValue.
+ result[typedKey] = typedValue
}
- } else if (headers != null) {
- throw new InvalidArgumentError('headers must be an object or an array')
}
- if (util.isFormDataLike(this.body)) {
- if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) {
- throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.')
- }
+ // 5. Return result.
+ return result
+ }
+}
- if (!extractBody) {
- extractBody = (__nccwpck_require__(37791).extractBody)
- }
+webidl.interfaceConverter = function (i) {
+ return (V, opts = {}) => {
+ if (opts.strict !== false && !(V instanceof i)) {
+ throw webidl.errors.exception({
+ header: i.name,
+ message: `Expected ${V} to be an instance of ${i.name}.`
+ })
+ }
- const [bodyStream, contentType] = extractBody(body)
- if (this.contentType == null) {
- this.contentType = contentType
- this.headers += `content-type: ${contentType}\r\n`
- }
- this.body = bodyStream.stream
- this.contentLength = bodyStream.length
- } else if (util.isBlobLike(body) && this.contentType == null && body.type) {
- this.contentType = body.type
- this.headers += `content-type: ${body.type}\r\n`
+ return V
+ }
+}
+
+webidl.dictionaryConverter = function (converters) {
+ return (dictionary) => {
+ const type = webidl.util.Type(dictionary)
+ const dict = {}
+
+ if (type === 'Null' || type === 'Undefined') {
+ return dict
+ } else if (type !== 'Object') {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
+ })
}
- util.validateHandler(handler, method, upgrade)
+ for (const options of converters) {
+ const { key, defaultValue, required, converter } = options
- this.servername = util.getServerName(this.host)
+ if (required === true) {
+ if (!hasOwn(dictionary, key)) {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `Missing required key "${key}".`
+ })
+ }
+ }
- this[kHandler] = handler
+ let value = dictionary[key]
+ const hasDefault = hasOwn(options, 'defaultValue')
- if (channels.create.hasSubscribers) {
- channels.create.publish({ request: this })
- }
- }
+ // Only use defaultValue if value is undefined and
+ // a defaultValue options was provided.
+ if (hasDefault && value !== null) {
+ value = value ?? defaultValue
+ }
- onBodySent (chunk) {
- if (this[kHandler].onBodySent) {
- try {
- return this[kHandler].onBodySent(chunk)
- } catch (err) {
- this.abort(err)
+ // A key can be optional and have no default value.
+ // When this happens, do not perform a conversion,
+ // and do not assign the key a value.
+ if (required || hasDefault || value !== undefined) {
+ value = converter(value)
+
+ if (
+ options.allowedValues &&
+ !options.allowedValues.includes(value)
+ ) {
+ throw webidl.errors.exception({
+ header: 'Dictionary',
+ message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
+ })
+ }
+
+ dict[key] = value
}
}
+
+ return dict
}
+}
- onRequestSent () {
- if (channels.bodySent.hasSubscribers) {
- channels.bodySent.publish({ request: this })
+webidl.nullableConverter = function (converter) {
+ return (V) => {
+ if (V === null) {
+ return V
}
- if (this[kHandler].onRequestSent) {
- try {
- return this[kHandler].onRequestSent()
- } catch (err) {
- this.abort(err)
- }
- }
+ return converter(V)
}
+}
- onConnect (abort) {
- assert(!this.aborted)
- assert(!this.completed)
+// https://webidl.spec.whatwg.org/#es-DOMString
+webidl.converters.DOMString = function (V, opts = {}) {
+ // 1. If V is null and the conversion is to an IDL type
+ // associated with the [LegacyNullToEmptyString]
+ // extended attribute, then return the DOMString value
+ // that represents the empty string.
+ if (V === null && opts.legacyNullToEmptyString) {
+ return ''
+ }
- if (this.error) {
- abort(this.error)
- } else {
- this.abort = abort
- return this[kHandler].onConnect(abort)
- }
+ // 2. Let x be ? ToString(V).
+ if (typeof V === 'symbol') {
+ throw new TypeError('Could not convert argument of type symbol to string.')
}
- onHeaders (statusCode, headers, resume, statusText) {
- assert(!this.aborted)
- assert(!this.completed)
+ // 3. Return the IDL DOMString value that represents the
+ // same sequence of code units as the one the
+ // ECMAScript String value x represents.
+ return String(V)
+}
- if (channels.headers.hasSubscribers) {
- channels.headers.publish({ request: this, response: { statusCode, headers, statusText } })
- }
+// https://webidl.spec.whatwg.org/#es-ByteString
+webidl.converters.ByteString = function (V) {
+ // 1. Let x be ? ToString(V).
+ // Note: DOMString converter perform ? ToString(V)
+ const x = webidl.converters.DOMString(V)
- try {
- return this[kHandler].onHeaders(statusCode, headers, resume, statusText)
- } catch (err) {
- this.abort(err)
+ // 2. If the value of any element of x is greater than
+ // 255, then throw a TypeError.
+ for (let index = 0; index < x.length; index++) {
+ if (x.charCodeAt(index) > 255) {
+ throw new TypeError(
+ 'Cannot convert argument to a ByteString because the character at ' +
+ `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
+ )
}
}
- onData (chunk) {
- assert(!this.aborted)
- assert(!this.completed)
+ // 3. Return an IDL ByteString value whose length is the
+ // length of x, and where the value of each element is
+ // the value of the corresponding element of x.
+ return x
+}
- try {
- return this[kHandler].onData(chunk)
- } catch (err) {
- this.abort(err)
- return false
- }
- }
+// https://webidl.spec.whatwg.org/#es-USVString
+webidl.converters.USVString = toUSVString
- onUpgrade (statusCode, headers, socket) {
- assert(!this.aborted)
- assert(!this.completed)
+// https://webidl.spec.whatwg.org/#es-boolean
+webidl.converters.boolean = function (V) {
+ // 1. Let x be the result of computing ToBoolean(V).
+ const x = Boolean(V)
- return this[kHandler].onUpgrade(statusCode, headers, socket)
- }
+ // 2. Return the IDL boolean value that is the one that represents
+ // the same truth value as the ECMAScript Boolean value x.
+ return x
+}
- onComplete (trailers) {
- this.onFinally()
+// https://webidl.spec.whatwg.org/#es-any
+webidl.converters.any = function (V) {
+ return V
+}
- assert(!this.aborted)
+// https://webidl.spec.whatwg.org/#es-long-long
+webidl.converters['long long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 64, "signed").
+ const x = webidl.util.ConvertToInt(V, 64, 'signed')
- this.completed = true
- if (channels.trailers.hasSubscribers) {
- channels.trailers.publish({ request: this, trailers })
- }
+ // 2. Return the IDL long long value that represents
+ // the same numeric value as x.
+ return x
+}
- try {
- return this[kHandler].onComplete(trailers)
- } catch (err) {
- // TODO (fix): This might be a bad idea?
- this.onError(err)
- }
- }
+// https://webidl.spec.whatwg.org/#es-unsigned-long-long
+webidl.converters['unsigned long long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 64, 'unsigned')
- onError (error) {
- this.onFinally()
+ // 2. Return the IDL unsigned long long value that
+ // represents the same numeric value as x.
+ return x
+}
- if (channels.error.hasSubscribers) {
- channels.error.publish({ request: this, error })
- }
+// https://webidl.spec.whatwg.org/#es-unsigned-long
+webidl.converters['unsigned long'] = function (V) {
+ // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 32, 'unsigned')
- if (this.aborted) {
- return
- }
- this.aborted = true
+ // 2. Return the IDL unsigned long value that
+ // represents the same numeric value as x.
+ return x
+}
- return this[kHandler].onError(error)
- }
+// https://webidl.spec.whatwg.org/#es-unsigned-short
+webidl.converters['unsigned short'] = function (V, opts) {
+ // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
+ const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)
- onFinally () {
- if (this.errorHandler) {
- this.body.off('error', this.errorHandler)
- this.errorHandler = null
- }
+ // 2. Return the IDL unsigned short value that represents
+ // the same numeric value as x.
+ return x
+}
- if (this.endHandler) {
- this.body.off('end', this.endHandler)
- this.endHandler = null
- }
+// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
+webidl.converters.ArrayBuffer = function (V, opts = {}) {
+ // 1. If Type(V) is not Object, or V does not have an
+ // [[ArrayBufferData]] internal slot, then throw a
+ // TypeError.
+ // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
+ // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances
+ if (
+ webidl.util.Type(V) !== 'Object' ||
+ !types.isAnyArrayBuffer(V)
+ ) {
+ throw webidl.errors.conversionFailed({
+ prefix: `${V}`,
+ argument: `${V}`,
+ types: ['ArrayBuffer']
+ })
}
- // TODO: adjust to support H2
- addHeader (key, value) {
- processHeader(this, key, value)
- return this
+ // 2. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V) is true, then throw a
+ // TypeError.
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
+ }
+
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V) is true, then throw a
+ // TypeError.
+ // Note: resizable ArrayBuffers are currently a proposal.
+
+ // 4. Return the IDL ArrayBuffer value that is a
+ // reference to the same object as V.
+ return V
+}
+
+webidl.converters.TypedArray = function (V, T, opts = {}) {
+ // 1. Let T be the IDL type V is being converted to.
+
+ // 2. If Type(V) is not Object, or V does not have a
+ // [[TypedArrayName]] internal slot with a value
+ // equal to T’s name, then throw a TypeError.
+ if (
+ webidl.util.Type(V) !== 'Object' ||
+ !types.isTypedArray(V) ||
+ V.constructor.name !== T.name
+ ) {
+ throw webidl.errors.conversionFailed({
+ prefix: `${T.name}`,
+ argument: `${V}`,
+ types: [T.name]
+ })
}
- static [kHTTP1BuildRequest] (origin, opts, handler) {
- // TODO: Migrate header parsing here, to make Requests
- // HTTP agnostic
- return new Request(origin, opts, handler)
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
}
- static [kHTTP2BuildRequest] (origin, opts, handler) {
- const headers = opts.headers
- opts = { ...opts, headers: null }
-
- const request = new Request(origin, opts, handler)
-
- request.headers = {}
+ // 4. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ // Note: resizable array buffers are currently a proposal
- if (Array.isArray(headers)) {
- if (headers.length % 2 !== 0) {
- throw new InvalidArgumentError('headers array must be even')
- }
- for (let i = 0; i < headers.length; i += 2) {
- processHeader(request, headers[i], headers[i + 1], true)
- }
- } else if (headers && typeof headers === 'object') {
- const keys = Object.keys(headers)
- for (let i = 0; i < keys.length; i++) {
- const key = keys[i]
- processHeader(request, key, headers[key], true)
- }
- } else if (headers != null) {
- throw new InvalidArgumentError('headers must be an object or an array')
- }
+ // 5. Return the IDL value of type T that is a reference
+ // to the same object as V.
+ return V
+}
- return request
+webidl.converters.DataView = function (V, opts = {}) {
+ // 1. If Type(V) is not Object, or V does not have a
+ // [[DataView]] internal slot, then throw a TypeError.
+ if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {
+ throw webidl.errors.exception({
+ header: 'DataView',
+ message: 'Object is not a DataView.'
+ })
}
- static [kHTTP2CopyHeaders] (raw) {
- const rawHeaders = raw.split('\r\n')
- const headers = {}
-
- for (const header of rawHeaders) {
- const [key, value] = header.split(': ')
-
- if (value == null || value.length === 0) continue
+ // 2. If the conversion is not to an IDL type associated
+ // with the [AllowShared] extended attribute, and
+ // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,
+ // then throw a TypeError.
+ if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
+ throw webidl.errors.exception({
+ header: 'ArrayBuffer',
+ message: 'SharedArrayBuffer is not allowed.'
+ })
+ }
- if (headers[key]) headers[key] += `,${value}`
- else headers[key] = value
- }
+ // 3. If the conversion is not to an IDL type associated
+ // with the [AllowResizable] extended attribute, and
+ // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
+ // true, then throw a TypeError.
+ // Note: resizable ArrayBuffers are currently a proposal
- return headers
- }
+ // 4. Return the IDL DataView value that is a reference
+ // to the same object as V.
+ return V
}
-function processHeaderValue (key, val, skipAppend) {
- if (val && typeof val === 'object') {
- throw new InvalidArgumentError(`invalid ${key} header`)
+// https://webidl.spec.whatwg.org/#BufferSource
+webidl.converters.BufferSource = function (V, opts = {}) {
+ if (types.isAnyArrayBuffer(V)) {
+ return webidl.converters.ArrayBuffer(V, opts)
}
- val = val != null ? `${val}` : ''
+ if (types.isTypedArray(V)) {
+ return webidl.converters.TypedArray(V, V.constructor)
+ }
- if (headerCharRegex.exec(val) !== null) {
- throw new InvalidArgumentError(`invalid ${key} header`)
+ if (types.isDataView(V)) {
+ return webidl.converters.DataView(V, opts)
}
- return skipAppend ? val : `${key}: ${val}\r\n`
+ throw new TypeError(`Could not convert ${V} to a BufferSource.`)
}
-function processHeader (request, key, val, skipAppend = false) {
- if (val && (typeof val === 'object' && !Array.isArray(val))) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- } else if (val === undefined) {
- return
- }
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.ByteString
+)
- if (
- request.host === null &&
- key.length === 4 &&
- key.toLowerCase() === 'host'
- ) {
- if (headerCharRegex.exec(val) !== null) {
- throw new InvalidArgumentError(`invalid ${key} header`)
- }
- // Consumed by Client
- request.host = val
- } else if (
- request.contentLength === null &&
- key.length === 14 &&
- key.toLowerCase() === 'content-length'
- ) {
- request.contentLength = parseInt(val, 10)
- if (!Number.isFinite(request.contentLength)) {
- throw new InvalidArgumentError('invalid content-length header')
- }
- } else if (
- request.contentType === null &&
- key.length === 12 &&
- key.toLowerCase() === 'content-type'
- ) {
- request.contentType = val
- if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
- else request.headers += processHeaderValue(key, val)
- } else if (
- key.length === 17 &&
- key.toLowerCase() === 'transfer-encoding'
- ) {
- throw new InvalidArgumentError('invalid transfer-encoding header')
- } else if (
- key.length === 10 &&
- key.toLowerCase() === 'connection'
- ) {
- const value = typeof val === 'string' ? val.toLowerCase() : null
- if (value !== 'close' && value !== 'keep-alive') {
- throw new InvalidArgumentError('invalid connection header')
- } else if (value === 'close') {
- request.reset = true
- }
- } else if (
- key.length === 10 &&
- key.toLowerCase() === 'keep-alive'
- ) {
- throw new InvalidArgumentError('invalid keep-alive header')
- } else if (
- key.length === 7 &&
- key.toLowerCase() === 'upgrade'
- ) {
- throw new InvalidArgumentError('invalid upgrade header')
- } else if (
- key.length === 6 &&
- key.toLowerCase() === 'expect'
- ) {
- throw new NotSupportedError('expect header not supported')
- } else if (tokenRegExp.exec(key) === null) {
- throw new InvalidArgumentError('invalid header key')
- } else {
- if (Array.isArray(val)) {
- for (let i = 0; i < val.length; i++) {
- if (skipAppend) {
- if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`
- else request.headers[key] = processHeaderValue(key, val[i], skipAppend)
- } else {
- request.headers += processHeaderValue(key, val[i])
- }
- }
- } else {
- if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend)
- else request.headers += processHeaderValue(key, val)
- }
- }
-}
+webidl.converters['sequence>'] = webidl.sequenceConverter(
+ webidl.converters['sequence']
+)
-module.exports = Request
+webidl.converters['record'] = webidl.recordConverter(
+ webidl.converters.ByteString,
+ webidl.converters.ByteString
+)
+
+module.exports = {
+ webidl
+}
/***/ }),
-/***/ 68031:
+/***/ 68064:
/***/ ((module) => {
-module.exports = {
- kClose: Symbol('close'),
- kDestroy: Symbol('destroy'),
- kDispatch: Symbol('dispatch'),
- kUrl: Symbol('url'),
- kWriting: Symbol('writing'),
- kResuming: Symbol('resuming'),
- kQueue: Symbol('queue'),
- kConnect: Symbol('connect'),
- kConnecting: Symbol('connecting'),
- kHeadersList: Symbol('headers list'),
- kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'),
- kKeepAliveMaxTimeout: Symbol('max keep alive timeout'),
- kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'),
- kKeepAliveTimeoutValue: Symbol('keep alive timeout'),
- kKeepAlive: Symbol('keep alive'),
- kHeadersTimeout: Symbol('headers timeout'),
- kBodyTimeout: Symbol('body timeout'),
- kServerName: Symbol('server name'),
- kLocalAddress: Symbol('local address'),
- kHost: Symbol('host'),
- kNoRef: Symbol('no ref'),
- kBodyUsed: Symbol('used'),
- kRunning: Symbol('running'),
- kBlocking: Symbol('blocking'),
- kPending: Symbol('pending'),
- kSize: Symbol('size'),
- kBusy: Symbol('busy'),
- kQueued: Symbol('queued'),
- kFree: Symbol('free'),
- kConnected: Symbol('connected'),
- kClosed: Symbol('closed'),
- kNeedDrain: Symbol('need drain'),
- kReset: Symbol('reset'),
- kDestroyed: Symbol.for('nodejs.stream.destroyed'),
- kMaxHeadersSize: Symbol('max headers size'),
- kRunningIdx: Symbol('running index'),
- kPendingIdx: Symbol('pending index'),
- kError: Symbol('error'),
- kClients: Symbol('clients'),
- kClient: Symbol('client'),
- kParser: Symbol('parser'),
- kOnDestroyed: Symbol('destroy callbacks'),
- kPipelining: Symbol('pipelining'),
- kSocket: Symbol('socket'),
- kHostHeader: Symbol('host header'),
- kConnector: Symbol('connector'),
- kStrictContentLength: Symbol('strict content length'),
- kMaxRedirections: Symbol('maxRedirections'),
- kMaxRequests: Symbol('maxRequestsPerClient'),
- kProxy: Symbol('proxy agent options'),
- kCounter: Symbol('socket request counter'),
- kInterceptors: Symbol('dispatch interceptors'),
- kMaxResponseSize: Symbol('max response size'),
- kHTTP2Session: Symbol('http2Session'),
- kHTTP2SessionState: Symbol('http2Session state'),
- kHTTP2BuildRequest: Symbol('http2 build request'),
- kHTTP1BuildRequest: Symbol('http1 build request'),
- kHTTP2CopyHeaders: Symbol('http2 copy headers'),
- kHTTPConnVersion: Symbol('http connection version'),
- kRetryHandlerDefaultRetry: Symbol('retry agent default retry'),
- kConstruct: Symbol('constructable')
+
+
+/**
+ * @see https://encoding.spec.whatwg.org/#concept-encoding-get
+ * @param {string|undefined} label
+ */
+function getEncoding (label) {
+ if (!label) {
+ return 'failure'
+ }
+
+ // 1. Remove any leading and trailing ASCII whitespace from label.
+ // 2. If label is an ASCII case-insensitive match for any of the
+ // labels listed in the table below, then return the
+ // corresponding encoding; otherwise return failure.
+ switch (label.trim().toLowerCase()) {
+ case 'unicode-1-1-utf-8':
+ case 'unicode11utf8':
+ case 'unicode20utf8':
+ case 'utf-8':
+ case 'utf8':
+ case 'x-unicode20utf8':
+ return 'UTF-8'
+ case '866':
+ case 'cp866':
+ case 'csibm866':
+ case 'ibm866':
+ return 'IBM866'
+ case 'csisolatin2':
+ case 'iso-8859-2':
+ case 'iso-ir-101':
+ case 'iso8859-2':
+ case 'iso88592':
+ case 'iso_8859-2':
+ case 'iso_8859-2:1987':
+ case 'l2':
+ case 'latin2':
+ return 'ISO-8859-2'
+ case 'csisolatin3':
+ case 'iso-8859-3':
+ case 'iso-ir-109':
+ case 'iso8859-3':
+ case 'iso88593':
+ case 'iso_8859-3':
+ case 'iso_8859-3:1988':
+ case 'l3':
+ case 'latin3':
+ return 'ISO-8859-3'
+ case 'csisolatin4':
+ case 'iso-8859-4':
+ case 'iso-ir-110':
+ case 'iso8859-4':
+ case 'iso88594':
+ case 'iso_8859-4':
+ case 'iso_8859-4:1988':
+ case 'l4':
+ case 'latin4':
+ return 'ISO-8859-4'
+ case 'csisolatincyrillic':
+ case 'cyrillic':
+ case 'iso-8859-5':
+ case 'iso-ir-144':
+ case 'iso8859-5':
+ case 'iso88595':
+ case 'iso_8859-5':
+ case 'iso_8859-5:1988':
+ return 'ISO-8859-5'
+ case 'arabic':
+ case 'asmo-708':
+ case 'csiso88596e':
+ case 'csiso88596i':
+ case 'csisolatinarabic':
+ case 'ecma-114':
+ case 'iso-8859-6':
+ case 'iso-8859-6-e':
+ case 'iso-8859-6-i':
+ case 'iso-ir-127':
+ case 'iso8859-6':
+ case 'iso88596':
+ case 'iso_8859-6':
+ case 'iso_8859-6:1987':
+ return 'ISO-8859-6'
+ case 'csisolatingreek':
+ case 'ecma-118':
+ case 'elot_928':
+ case 'greek':
+ case 'greek8':
+ case 'iso-8859-7':
+ case 'iso-ir-126':
+ case 'iso8859-7':
+ case 'iso88597':
+ case 'iso_8859-7':
+ case 'iso_8859-7:1987':
+ case 'sun_eu_greek':
+ return 'ISO-8859-7'
+ case 'csiso88598e':
+ case 'csisolatinhebrew':
+ case 'hebrew':
+ case 'iso-8859-8':
+ case 'iso-8859-8-e':
+ case 'iso-ir-138':
+ case 'iso8859-8':
+ case 'iso88598':
+ case 'iso_8859-8':
+ case 'iso_8859-8:1988':
+ case 'visual':
+ return 'ISO-8859-8'
+ case 'csiso88598i':
+ case 'iso-8859-8-i':
+ case 'logical':
+ return 'ISO-8859-8-I'
+ case 'csisolatin6':
+ case 'iso-8859-10':
+ case 'iso-ir-157':
+ case 'iso8859-10':
+ case 'iso885910':
+ case 'l6':
+ case 'latin6':
+ return 'ISO-8859-10'
+ case 'iso-8859-13':
+ case 'iso8859-13':
+ case 'iso885913':
+ return 'ISO-8859-13'
+ case 'iso-8859-14':
+ case 'iso8859-14':
+ case 'iso885914':
+ return 'ISO-8859-14'
+ case 'csisolatin9':
+ case 'iso-8859-15':
+ case 'iso8859-15':
+ case 'iso885915':
+ case 'iso_8859-15':
+ case 'l9':
+ return 'ISO-8859-15'
+ case 'iso-8859-16':
+ return 'ISO-8859-16'
+ case 'cskoi8r':
+ case 'koi':
+ case 'koi8':
+ case 'koi8-r':
+ case 'koi8_r':
+ return 'KOI8-R'
+ case 'koi8-ru':
+ case 'koi8-u':
+ return 'KOI8-U'
+ case 'csmacintosh':
+ case 'mac':
+ case 'macintosh':
+ case 'x-mac-roman':
+ return 'macintosh'
+ case 'iso-8859-11':
+ case 'iso8859-11':
+ case 'iso885911':
+ case 'tis-620':
+ case 'windows-874':
+ return 'windows-874'
+ case 'cp1250':
+ case 'windows-1250':
+ case 'x-cp1250':
+ return 'windows-1250'
+ case 'cp1251':
+ case 'windows-1251':
+ case 'x-cp1251':
+ return 'windows-1251'
+ case 'ansi_x3.4-1968':
+ case 'ascii':
+ case 'cp1252':
+ case 'cp819':
+ case 'csisolatin1':
+ case 'ibm819':
+ case 'iso-8859-1':
+ case 'iso-ir-100':
+ case 'iso8859-1':
+ case 'iso88591':
+ case 'iso_8859-1':
+ case 'iso_8859-1:1987':
+ case 'l1':
+ case 'latin1':
+ case 'us-ascii':
+ case 'windows-1252':
+ case 'x-cp1252':
+ return 'windows-1252'
+ case 'cp1253':
+ case 'windows-1253':
+ case 'x-cp1253':
+ return 'windows-1253'
+ case 'cp1254':
+ case 'csisolatin5':
+ case 'iso-8859-9':
+ case 'iso-ir-148':
+ case 'iso8859-9':
+ case 'iso88599':
+ case 'iso_8859-9':
+ case 'iso_8859-9:1989':
+ case 'l5':
+ case 'latin5':
+ case 'windows-1254':
+ case 'x-cp1254':
+ return 'windows-1254'
+ case 'cp1255':
+ case 'windows-1255':
+ case 'x-cp1255':
+ return 'windows-1255'
+ case 'cp1256':
+ case 'windows-1256':
+ case 'x-cp1256':
+ return 'windows-1256'
+ case 'cp1257':
+ case 'windows-1257':
+ case 'x-cp1257':
+ return 'windows-1257'
+ case 'cp1258':
+ case 'windows-1258':
+ case 'x-cp1258':
+ return 'windows-1258'
+ case 'x-mac-cyrillic':
+ case 'x-mac-ukrainian':
+ return 'x-mac-cyrillic'
+ case 'chinese':
+ case 'csgb2312':
+ case 'csiso58gb231280':
+ case 'gb2312':
+ case 'gb_2312':
+ case 'gb_2312-80':
+ case 'gbk':
+ case 'iso-ir-58':
+ case 'x-gbk':
+ return 'GBK'
+ case 'gb18030':
+ return 'gb18030'
+ case 'big5':
+ case 'big5-hkscs':
+ case 'cn-big5':
+ case 'csbig5':
+ case 'x-x-big5':
+ return 'Big5'
+ case 'cseucpkdfmtjapanese':
+ case 'euc-jp':
+ case 'x-euc-jp':
+ return 'EUC-JP'
+ case 'csiso2022jp':
+ case 'iso-2022-jp':
+ return 'ISO-2022-JP'
+ case 'csshiftjis':
+ case 'ms932':
+ case 'ms_kanji':
+ case 'shift-jis':
+ case 'shift_jis':
+ case 'sjis':
+ case 'windows-31j':
+ case 'x-sjis':
+ return 'Shift_JIS'
+ case 'cseuckr':
+ case 'csksc56011987':
+ case 'euc-kr':
+ case 'iso-ir-149':
+ case 'korean':
+ case 'ks_c_5601-1987':
+ case 'ks_c_5601-1989':
+ case 'ksc5601':
+ case 'ksc_5601':
+ case 'windows-949':
+ return 'EUC-KR'
+ case 'csiso2022kr':
+ case 'hz-gb-2312':
+ case 'iso-2022-cn':
+ case 'iso-2022-cn-ext':
+ case 'iso-2022-kr':
+ case 'replacement':
+ return 'replacement'
+ case 'unicodefffe':
+ case 'utf-16be':
+ return 'UTF-16BE'
+ case 'csunicode':
+ case 'iso-10646-ucs-2':
+ case 'ucs-2':
+ case 'unicode':
+ case 'unicodefeff':
+ case 'utf-16':
+ case 'utf-16le':
+ return 'UTF-16LE'
+ case 'x-user-defined':
+ return 'x-user-defined'
+ default: return 'failure'
+ }
+}
+
+module.exports = {
+ getEncoding
}
/***/ }),
-/***/ 89500:
+/***/ 30052:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const assert = __nccwpck_require__(42613)
-const { kDestroyed, kBodyUsed } = __nccwpck_require__(68031)
-const { IncomingMessage } = __nccwpck_require__(58611)
-const stream = __nccwpck_require__(2203)
-const net = __nccwpck_require__(69278)
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-const { Blob } = __nccwpck_require__(20181)
-const nodeUtil = __nccwpck_require__(39023)
-const { stringify } = __nccwpck_require__(83480)
-const { headerNameLowerCasedRecord } = __nccwpck_require__(42371)
-
-const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v))
-
-function nop () {}
-
-function isStream (obj) {
- return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function'
-}
-
-// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License)
-function isBlobLike (object) {
- return (Blob && object instanceof Blob) || (
- object &&
- typeof object === 'object' &&
- (typeof object.stream === 'function' ||
- typeof object.arrayBuffer === 'function') &&
- /^(Blob|File)$/.test(object[Symbol.toStringTag])
- )
-}
-
-function buildURL (url, queryParams) {
- if (url.includes('?') || url.includes('#')) {
- throw new Error('Query params cannot be passed when url already contains "?" or "#".')
- }
+const {
+ staticPropertyDescriptors,
+ readOperation,
+ fireAProgressEvent
+} = __nccwpck_require__(94273)
+const {
+ kState,
+ kError,
+ kResult,
+ kEvents,
+ kAborted
+} = __nccwpck_require__(52736)
+const { webidl } = __nccwpck_require__(94354)
+const { kEnumerableProperty } = __nccwpck_require__(89500)
- const stringified = stringify(queryParams)
+class FileReader extends EventTarget {
+ constructor () {
+ super()
- if (stringified) {
- url += '?' + stringified
+ this[kState] = 'empty'
+ this[kResult] = null
+ this[kError] = null
+ this[kEvents] = {
+ loadend: null,
+ error: null,
+ abort: null,
+ load: null,
+ progress: null,
+ loadstart: null
+ }
}
- return url
-}
-
-function parseURL (url) {
- if (typeof url === 'string') {
- url = new URL(url)
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
+ * @param {import('buffer').Blob} blob
+ */
+ readAsArrayBuffer (blob) {
+ webidl.brandCheck(this, FileReader)
- if (!/^https?:/.test(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })
- return url
- }
+ blob = webidl.converters.Blob(blob, { strict: false })
- if (!url || typeof url !== 'object') {
- throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.')
+ // The readAsArrayBuffer(blob) method, when invoked,
+ // must initiate a read operation for blob with ArrayBuffer.
+ readOperation(this, blob, 'ArrayBuffer')
}
- if (!/^https?:/.test(url.origin || url.protocol)) {
- throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.')
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#readAsBinaryString
+ * @param {import('buffer').Blob} blob
+ */
+ readAsBinaryString (blob) {
+ webidl.brandCheck(this, FileReader)
- if (!(url instanceof URL)) {
- if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) {
- throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.')
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })
- if (url.path != null && typeof url.path !== 'string') {
- throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.')
- }
+ blob = webidl.converters.Blob(blob, { strict: false })
- if (url.pathname != null && typeof url.pathname !== 'string') {
- throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.')
- }
+ // The readAsBinaryString(blob) method, when invoked,
+ // must initiate a read operation for blob with BinaryString.
+ readOperation(this, blob, 'BinaryString')
+ }
- if (url.hostname != null && typeof url.hostname !== 'string') {
- throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.')
- }
+ /**
+ * @see https://w3c.github.io/FileAPI/#readAsDataText
+ * @param {import('buffer').Blob} blob
+ * @param {string?} encoding
+ */
+ readAsText (blob, encoding = undefined) {
+ webidl.brandCheck(this, FileReader)
- if (url.origin != null && typeof url.origin !== 'string') {
- throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.')
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })
- const port = url.port != null
- ? url.port
- : (url.protocol === 'https:' ? 443 : 80)
- let origin = url.origin != null
- ? url.origin
- : `${url.protocol}//${url.hostname}:${port}`
- let path = url.path != null
- ? url.path
- : `${url.pathname || ''}${url.search || ''}`
+ blob = webidl.converters.Blob(blob, { strict: false })
- if (origin.endsWith('/')) {
- origin = origin.substring(0, origin.length - 1)
+ if (encoding !== undefined) {
+ encoding = webidl.converters.DOMString(encoding)
}
- if (path && !path.startsWith('/')) {
- path = `/${path}`
- }
- // new URL(path, origin) is unsafe when `path` contains an absolute URL
- // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL:
- // If first parameter is a relative URL, second param is required, and will be used as the base URL.
- // If first parameter is an absolute URL, a given second param will be ignored.
- url = new URL(origin + path)
+ // The readAsText(blob, encoding) method, when invoked,
+ // must initiate a read operation for blob with Text and encoding.
+ readOperation(this, blob, 'Text', encoding)
}
- return url
-}
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
+ * @param {import('buffer').Blob} blob
+ */
+ readAsDataURL (blob) {
+ webidl.brandCheck(this, FileReader)
-function parseOrigin (url) {
- url = parseURL(url)
+ webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })
- if (url.pathname !== '/' || url.search || url.hash) {
- throw new InvalidArgumentError('invalid url')
+ blob = webidl.converters.Blob(blob, { strict: false })
+
+ // The readAsDataURL(blob) method, when invoked, must
+ // initiate a read operation for blob with DataURL.
+ readOperation(this, blob, 'DataURL')
}
- return url
-}
+ /**
+ * @see https://w3c.github.io/FileAPI/#dfn-abort
+ */
+ abort () {
+ // 1. If this's state is "empty" or if this's state is
+ // "done" set this's result to null and terminate
+ // this algorithm.
+ if (this[kState] === 'empty' || this[kState] === 'done') {
+ this[kResult] = null
+ return
+ }
-function getHostname (host) {
- if (host[0] === '[') {
- const idx = host.indexOf(']')
+ // 2. If this's state is "loading" set this's state to
+ // "done" and set this's result to null.
+ if (this[kState] === 'loading') {
+ this[kState] = 'done'
+ this[kResult] = null
+ }
- assert(idx !== -1)
- return host.substring(1, idx)
- }
+ // 3. If there are any tasks from this on the file reading
+ // task source in an affiliated task queue, then remove
+ // those tasks from that task queue.
+ this[kAborted] = true
- const idx = host.indexOf(':')
- if (idx === -1) return host
+ // 4. Terminate the algorithm for the read method being processed.
+ // TODO
- return host.substring(0, idx)
-}
+ // 5. Fire a progress event called abort at this.
+ fireAProgressEvent('abort', this)
-// IP addresses are not valid server names per RFC6066
-// > Currently, the only server names supported are DNS hostnames
-function getServerName (host) {
- if (!host) {
- return null
+ // 6. If this's state is not "loading", fire a progress
+ // event called loadend at this.
+ if (this[kState] !== 'loading') {
+ fireAProgressEvent('loadend', this)
+ }
}
- assert.strictEqual(typeof host, 'string')
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
+ */
+ get readyState () {
+ webidl.brandCheck(this, FileReader)
- const servername = getHostname(host)
- if (net.isIP(servername)) {
- return ''
+ switch (this[kState]) {
+ case 'empty': return this.EMPTY
+ case 'loading': return this.LOADING
+ case 'done': return this.DONE
+ }
}
- return servername
-}
-
-function deepClone (obj) {
- return JSON.parse(JSON.stringify(obj))
-}
-
-function isAsyncIterable (obj) {
- return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function')
-}
-
-function isIterable (obj) {
- return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function'))
-}
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-result
+ */
+ get result () {
+ webidl.brandCheck(this, FileReader)
-function bodyLength (body) {
- if (body == null) {
- return 0
- } else if (isStream(body)) {
- const state = body._readableState
- return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length)
- ? state.length
- : null
- } else if (isBlobLike(body)) {
- return body.size != null ? body.size : null
- } else if (isBuffer(body)) {
- return body.byteLength
+ // The result attribute’s getter, when invoked, must return
+ // this's result.
+ return this[kResult]
}
- return null
-}
-
-function isDestroyed (stream) {
- return !stream || !!(stream.destroyed || stream[kDestroyed])
-}
-
-function isReadableAborted (stream) {
- const state = stream && stream._readableState
- return isDestroyed(stream) && state && !state.endEmitted
-}
+ /**
+ * @see https://w3c.github.io/FileAPI/#dom-filereader-error
+ */
+ get error () {
+ webidl.brandCheck(this, FileReader)
-function destroy (stream, err) {
- if (stream == null || !isStream(stream) || isDestroyed(stream)) {
- return
+ // The error attribute’s getter, when invoked, must return
+ // this's error.
+ return this[kError]
}
- if (typeof stream.destroy === 'function') {
- if (Object.getPrototypeOf(stream).constructor === IncomingMessage) {
- // See: https://github.com/nodejs/node/pull/38505/files
- stream.socket = null
- }
-
- stream.destroy(err)
- } else if (err) {
- process.nextTick((stream, err) => {
- stream.emit('error', err)
- }, stream, err)
- }
+ get onloadend () {
+ webidl.brandCheck(this, FileReader)
- if (stream.destroyed !== true) {
- stream[kDestroyed] = true
+ return this[kEvents].loadend
}
-}
-const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/
-function parseKeepAliveTimeout (val) {
- const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR)
- return m ? parseInt(m[1], 10) * 1000 : null
-}
-
-/**
- * Retrieves a header name and returns its lowercase value.
- * @param {string | Buffer} value Header name
- * @returns {string}
- */
-function headerNameToString (value) {
- return headerNameLowerCasedRecord[value] || value.toLowerCase()
-}
-
-function parseHeaders (headers, obj = {}) {
- // For H2 support
- if (!Array.isArray(headers)) return headers
-
- for (let i = 0; i < headers.length; i += 2) {
- const key = headers[i].toString().toLowerCase()
- let val = obj[key]
+ set onloadend (fn) {
+ webidl.brandCheck(this, FileReader)
- if (!val) {
- if (Array.isArray(headers[i + 1])) {
- obj[key] = headers[i + 1].map(x => x.toString('utf8'))
- } else {
- obj[key] = headers[i + 1].toString('utf8')
- }
- } else {
- if (!Array.isArray(val)) {
- val = [val]
- obj[key] = val
- }
- val.push(headers[i + 1].toString('utf8'))
+ if (this[kEvents].loadend) {
+ this.removeEventListener('loadend', this[kEvents].loadend)
}
- }
-
- // See https://github.com/nodejs/node/pull/46528
- if ('content-length' in obj && 'content-disposition' in obj) {
- obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1')
- }
-
- return obj
-}
-
-function parseRawHeaders (headers) {
- const ret = []
- let hasContentLength = false
- let contentDispositionIdx = -1
-
- for (let n = 0; n < headers.length; n += 2) {
- const key = headers[n + 0].toString()
- const val = headers[n + 1].toString('utf8')
- if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) {
- ret.push(key, val)
- hasContentLength = true
- } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) {
- contentDispositionIdx = ret.push(key, val) - 1
+ if (typeof fn === 'function') {
+ this[kEvents].loadend = fn
+ this.addEventListener('loadend', fn)
} else {
- ret.push(key, val)
+ this[kEvents].loadend = null
}
}
- // See https://github.com/nodejs/node/pull/46528
- if (hasContentLength && contentDispositionIdx !== -1) {
- ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1')
- }
-
- return ret
-}
-
-function isBuffer (buffer) {
- // See, https://github.com/mcollina/undici/pull/319
- return buffer instanceof Uint8Array || Buffer.isBuffer(buffer)
-}
-
-function validateHandler (handler, method, upgrade) {
- if (!handler || typeof handler !== 'object') {
- throw new InvalidArgumentError('handler must be an object')
- }
-
- if (typeof handler.onConnect !== 'function') {
- throw new InvalidArgumentError('invalid onConnect method')
- }
-
- if (typeof handler.onError !== 'function') {
- throw new InvalidArgumentError('invalid onError method')
- }
+ get onerror () {
+ webidl.brandCheck(this, FileReader)
- if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) {
- throw new InvalidArgumentError('invalid onBodySent method')
+ return this[kEvents].error
}
- if (upgrade || method === 'CONNECT') {
- if (typeof handler.onUpgrade !== 'function') {
- throw new InvalidArgumentError('invalid onUpgrade method')
- }
- } else {
- if (typeof handler.onHeaders !== 'function') {
- throw new InvalidArgumentError('invalid onHeaders method')
- }
+ set onerror (fn) {
+ webidl.brandCheck(this, FileReader)
- if (typeof handler.onData !== 'function') {
- throw new InvalidArgumentError('invalid onData method')
+ if (this[kEvents].error) {
+ this.removeEventListener('error', this[kEvents].error)
}
- if (typeof handler.onComplete !== 'function') {
- throw new InvalidArgumentError('invalid onComplete method')
+ if (typeof fn === 'function') {
+ this[kEvents].error = fn
+ this.addEventListener('error', fn)
+ } else {
+ this[kEvents].error = null
}
}
-}
-
-// A body is disturbed if it has been read from and it cannot
-// be re-used without losing state or data.
-function isDisturbed (body) {
- return !!(body && (
- stream.isDisturbed
- ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed?
- : body[kBodyUsed] ||
- body.readableDidRead ||
- (body._readableState && body._readableState.dataEmitted) ||
- isReadableAborted(body)
- ))
-}
-function isErrored (body) {
- return !!(body && (
- stream.isErrored
- ? stream.isErrored(body)
- : /state: 'errored'/.test(nodeUtil.inspect(body)
- )))
-}
+ get onloadstart () {
+ webidl.brandCheck(this, FileReader)
-function isReadable (body) {
- return !!(body && (
- stream.isReadable
- ? stream.isReadable(body)
- : /state: 'readable'/.test(nodeUtil.inspect(body)
- )))
-}
+ return this[kEvents].loadstart
+ }
-function getSocketInfo (socket) {
- return {
- localAddress: socket.localAddress,
- localPort: socket.localPort,
- remoteAddress: socket.remoteAddress,
- remotePort: socket.remotePort,
- remoteFamily: socket.remoteFamily,
- timeout: socket.timeout,
- bytesWritten: socket.bytesWritten,
- bytesRead: socket.bytesRead
+ set onloadstart (fn) {
+ webidl.brandCheck(this, FileReader)
+
+ if (this[kEvents].loadstart) {
+ this.removeEventListener('loadstart', this[kEvents].loadstart)
+ }
+
+ if (typeof fn === 'function') {
+ this[kEvents].loadstart = fn
+ this.addEventListener('loadstart', fn)
+ } else {
+ this[kEvents].loadstart = null
+ }
}
-}
-async function * convertIterableToBuffer (iterable) {
- for await (const chunk of iterable) {
- yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
+ get onprogress () {
+ webidl.brandCheck(this, FileReader)
+
+ return this[kEvents].progress
}
-}
-let ReadableStream
-function ReadableStreamFrom (iterable) {
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(63774).ReadableStream)
+ set onprogress (fn) {
+ webidl.brandCheck(this, FileReader)
+
+ if (this[kEvents].progress) {
+ this.removeEventListener('progress', this[kEvents].progress)
+ }
+
+ if (typeof fn === 'function') {
+ this[kEvents].progress = fn
+ this.addEventListener('progress', fn)
+ } else {
+ this[kEvents].progress = null
+ }
}
- if (ReadableStream.from) {
- return ReadableStream.from(convertIterableToBuffer(iterable))
+ get onload () {
+ webidl.brandCheck(this, FileReader)
+
+ return this[kEvents].load
}
- let iterator
- return new ReadableStream(
- {
- async start () {
- iterator = iterable[Symbol.asyncIterator]()
- },
- async pull (controller) {
- const { done, value } = await iterator.next()
- if (done) {
- queueMicrotask(() => {
- controller.close()
- })
- } else {
- const buf = Buffer.isBuffer(value) ? value : Buffer.from(value)
- controller.enqueue(new Uint8Array(buf))
- }
- return controller.desiredSize > 0
- },
- async cancel (reason) {
- await iterator.return()
- }
- },
- 0
- )
-}
+ set onload (fn) {
+ webidl.brandCheck(this, FileReader)
-// The chunk should be a FormData instance and contains
-// all the required methods.
-function isFormDataLike (object) {
- return (
- object &&
- typeof object === 'object' &&
- typeof object.append === 'function' &&
- typeof object.delete === 'function' &&
- typeof object.get === 'function' &&
- typeof object.getAll === 'function' &&
- typeof object.has === 'function' &&
- typeof object.set === 'function' &&
- object[Symbol.toStringTag] === 'FormData'
- )
-}
+ if (this[kEvents].load) {
+ this.removeEventListener('load', this[kEvents].load)
+ }
-function throwIfAborted (signal) {
- if (!signal) { return }
- if (typeof signal.throwIfAborted === 'function') {
- signal.throwIfAborted()
- } else {
- if (signal.aborted) {
- // DOMException not available < v17.0.0
- const err = new Error('The operation was aborted')
- err.name = 'AbortError'
- throw err
+ if (typeof fn === 'function') {
+ this[kEvents].load = fn
+ this.addEventListener('load', fn)
+ } else {
+ this[kEvents].load = null
}
}
-}
-function addAbortListener (signal, listener) {
- if ('addEventListener' in signal) {
- signal.addEventListener('abort', listener, { once: true })
- return () => signal.removeEventListener('abort', listener)
+ get onabort () {
+ webidl.brandCheck(this, FileReader)
+
+ return this[kEvents].abort
}
- signal.addListener('abort', listener)
- return () => signal.removeListener('abort', listener)
-}
-const hasToWellFormed = !!String.prototype.toWellFormed
+ set onabort (fn) {
+ webidl.brandCheck(this, FileReader)
-/**
- * @param {string} val
- */
-function toUSVString (val) {
- if (hasToWellFormed) {
- return `${val}`.toWellFormed()
- } else if (nodeUtil.toUSVString) {
- return nodeUtil.toUSVString(val)
- }
+ if (this[kEvents].abort) {
+ this.removeEventListener('abort', this[kEvents].abort)
+ }
- return `${val}`
+ if (typeof fn === 'function') {
+ this[kEvents].abort = fn
+ this.addEventListener('abort', fn)
+ } else {
+ this[kEvents].abort = null
+ }
+ }
}
-// Parsed accordingly to RFC 9110
-// https://www.rfc-editor.org/rfc/rfc9110#field.content-range
-function parseRangeHeader (range) {
- if (range == null || range === '') return { start: 0, end: null, size: null }
+// https://w3c.github.io/FileAPI/#dom-filereader-empty
+FileReader.EMPTY = FileReader.prototype.EMPTY = 0
+// https://w3c.github.io/FileAPI/#dom-filereader-loading
+FileReader.LOADING = FileReader.prototype.LOADING = 1
+// https://w3c.github.io/FileAPI/#dom-filereader-done
+FileReader.DONE = FileReader.prototype.DONE = 2
- const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null
- return m
- ? {
- start: parseInt(m[1]),
- end: m[2] ? parseInt(m[2]) : null,
- size: m[3] ? parseInt(m[3]) : null
- }
- : null
-}
+Object.defineProperties(FileReader.prototype, {
+ EMPTY: staticPropertyDescriptors,
+ LOADING: staticPropertyDescriptors,
+ DONE: staticPropertyDescriptors,
+ readAsArrayBuffer: kEnumerableProperty,
+ readAsBinaryString: kEnumerableProperty,
+ readAsText: kEnumerableProperty,
+ readAsDataURL: kEnumerableProperty,
+ abort: kEnumerableProperty,
+ readyState: kEnumerableProperty,
+ result: kEnumerableProperty,
+ error: kEnumerableProperty,
+ onloadstart: kEnumerableProperty,
+ onprogress: kEnumerableProperty,
+ onload: kEnumerableProperty,
+ onabort: kEnumerableProperty,
+ onerror: kEnumerableProperty,
+ onloadend: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'FileReader',
+ writable: false,
+ enumerable: false,
+ configurable: true
+ }
+})
-const kEnumerableProperty = Object.create(null)
-kEnumerableProperty.enumerable = true
+Object.defineProperties(FileReader, {
+ EMPTY: staticPropertyDescriptors,
+ LOADING: staticPropertyDescriptors,
+ DONE: staticPropertyDescriptors
+})
module.exports = {
- kEnumerableProperty,
- nop,
- isDisturbed,
- isErrored,
- isReadable,
- toUSVString,
- isReadableAborted,
- isBlobLike,
- parseOrigin,
- parseURL,
- getServerName,
- isStream,
- isIterable,
- isAsyncIterable,
- isDestroyed,
- headerNameToString,
- parseRawHeaders,
- parseHeaders,
- parseKeepAliveTimeout,
- destroy,
- bodyLength,
- deepClone,
- ReadableStreamFrom,
- isBuffer,
- validateHandler,
- getSocketInfo,
- isFormDataLike,
- buildURL,
- throwIfAborted,
- addAbortListener,
- parseRangeHeader,
- nodeMajor,
- nodeMinor,
- nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13),
- safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE']
+ FileReader
}
/***/ }),
-/***/ 52421:
+/***/ 92804:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const Dispatcher = __nccwpck_require__(20303)
-const {
- ClientDestroyedError,
- ClientClosedError,
- InvalidArgumentError
-} = __nccwpck_require__(53959)
-const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(68031)
+const { webidl } = __nccwpck_require__(94354)
-const kDestroyed = Symbol('destroyed')
-const kClosed = Symbol('closed')
-const kOnDestroyed = Symbol('onDestroyed')
-const kOnClosed = Symbol('onClosed')
-const kInterceptedDispatch = Symbol('Intercepted Dispatch')
+const kState = Symbol('ProgressEvent state')
-class DispatcherBase extends Dispatcher {
- constructor () {
- super()
+/**
+ * @see https://xhr.spec.whatwg.org/#progressevent
+ */
+class ProgressEvent extends Event {
+ constructor (type, eventInitDict = {}) {
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
- this[kDestroyed] = false
- this[kOnDestroyed] = null
- this[kClosed] = false
- this[kOnClosed] = []
- }
+ super(type, eventInitDict)
- get destroyed () {
- return this[kDestroyed]
+ this[kState] = {
+ lengthComputable: eventInitDict.lengthComputable,
+ loaded: eventInitDict.loaded,
+ total: eventInitDict.total
+ }
}
- get closed () {
- return this[kClosed]
- }
+ get lengthComputable () {
+ webidl.brandCheck(this, ProgressEvent)
- get interceptors () {
- return this[kInterceptors]
+ return this[kState].lengthComputable
}
- set interceptors (newInterceptors) {
- if (newInterceptors) {
- for (let i = newInterceptors.length - 1; i >= 0; i--) {
- const interceptor = this[kInterceptors][i]
- if (typeof interceptor !== 'function') {
- throw new InvalidArgumentError('interceptor must be an function')
- }
- }
- }
+ get loaded () {
+ webidl.brandCheck(this, ProgressEvent)
- this[kInterceptors] = newInterceptors
+ return this[kState].loaded
}
- close (callback) {
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- this.close((err, data) => {
- return err ? reject(err) : resolve(data)
- })
- })
- }
+ get total () {
+ webidl.brandCheck(this, ProgressEvent)
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+ return this[kState].total
+ }
+}
- if (this[kDestroyed]) {
- queueMicrotask(() => callback(new ClientDestroyedError(), null))
- return
- }
+webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
+ {
+ key: 'lengthComputable',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'loaded',
+ converter: webidl.converters['unsigned long long'],
+ defaultValue: 0
+ },
+ {
+ key: 'total',
+ converter: webidl.converters['unsigned long long'],
+ defaultValue: 0
+ },
+ {
+ key: 'bubbles',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'cancelable',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'composed',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ }
+])
- if (this[kClosed]) {
- if (this[kOnClosed]) {
- this[kOnClosed].push(callback)
- } else {
- queueMicrotask(() => callback(null, null))
- }
- return
- }
+module.exports = {
+ ProgressEvent
+}
- this[kClosed] = true
- this[kOnClosed].push(callback)
- const onClosed = () => {
- const callbacks = this[kOnClosed]
- this[kOnClosed] = null
- for (let i = 0; i < callbacks.length; i++) {
- callbacks[i](null, null)
- }
- }
+/***/ }),
- // Should not error.
- this[kClose]()
- .then(() => this.destroy())
- .then(() => {
- queueMicrotask(onClosed)
- })
- }
+/***/ 52736:
+/***/ ((module) => {
- destroy (err, callback) {
- if (typeof err === 'function') {
- callback = err
- err = null
- }
- if (callback === undefined) {
- return new Promise((resolve, reject) => {
- this.destroy(err, (err, data) => {
- return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data)
- })
- })
- }
- if (typeof callback !== 'function') {
- throw new InvalidArgumentError('invalid callback')
- }
+module.exports = {
+ kState: Symbol('FileReader state'),
+ kResult: Symbol('FileReader result'),
+ kError: Symbol('FileReader error'),
+ kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
+ kEvents: Symbol('FileReader events'),
+ kAborted: Symbol('FileReader aborted')
+}
- if (this[kDestroyed]) {
- if (this[kOnDestroyed]) {
- this[kOnDestroyed].push(callback)
- } else {
- queueMicrotask(() => callback(null, null))
- }
- return
- }
- if (!err) {
- err = new ClientDestroyedError()
- }
+/***/ }),
- this[kDestroyed] = true
- this[kOnDestroyed] = this[kOnDestroyed] || []
- this[kOnDestroyed].push(callback)
+/***/ 94273:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- const onDestroyed = () => {
- const callbacks = this[kOnDestroyed]
- this[kOnDestroyed] = null
- for (let i = 0; i < callbacks.length; i++) {
- callbacks[i](null, null)
- }
- }
- // Should not error.
- this[kDestroy](err).then(() => {
- queueMicrotask(onDestroyed)
- })
- }
- [kInterceptedDispatch] (opts, handler) {
- if (!this[kInterceptors] || this[kInterceptors].length === 0) {
- this[kInterceptedDispatch] = this[kDispatch]
- return this[kDispatch](opts, handler)
- }
+const {
+ kState,
+ kError,
+ kResult,
+ kAborted,
+ kLastProgressEventFired
+} = __nccwpck_require__(52736)
+const { ProgressEvent } = __nccwpck_require__(92804)
+const { getEncoding } = __nccwpck_require__(68064)
+const { DOMException } = __nccwpck_require__(21234)
+const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(37246)
+const { types } = __nccwpck_require__(39023)
+const { StringDecoder } = __nccwpck_require__(13193)
+const { btoa } = __nccwpck_require__(20181)
- let dispatch = this[kDispatch].bind(this)
- for (let i = this[kInterceptors].length - 1; i >= 0; i--) {
- dispatch = this[kInterceptors][i](dispatch)
- }
- this[kInterceptedDispatch] = dispatch
- return dispatch(opts, handler)
- }
+/** @type {PropertyDescriptor} */
+const staticPropertyDescriptors = {
+ enumerable: true,
+ writable: false,
+ configurable: false
+}
- dispatch (opts, handler) {
- if (!handler || typeof handler !== 'object') {
- throw new InvalidArgumentError('handler must be an object')
- }
+/**
+ * @see https://w3c.github.io/FileAPI/#readOperation
+ * @param {import('./filereader').FileReader} fr
+ * @param {import('buffer').Blob} blob
+ * @param {string} type
+ * @param {string?} encodingName
+ */
+function readOperation (fr, blob, type, encodingName) {
+ // 1. If fr’s state is "loading", throw an InvalidStateError
+ // DOMException.
+ if (fr[kState] === 'loading') {
+ throw new DOMException('Invalid state', 'InvalidStateError')
+ }
- try {
- if (!opts || typeof opts !== 'object') {
- throw new InvalidArgumentError('opts must be an object.')
- }
+ // 2. Set fr’s state to "loading".
+ fr[kState] = 'loading'
- if (this[kDestroyed] || this[kOnDestroyed]) {
- throw new ClientDestroyedError()
- }
+ // 3. Set fr’s result to null.
+ fr[kResult] = null
- if (this[kClosed]) {
- throw new ClientClosedError()
- }
+ // 4. Set fr’s error to null.
+ fr[kError] = null
- return this[kInterceptedDispatch](opts, handler)
- } catch (err) {
- if (typeof handler.onError !== 'function') {
- throw new InvalidArgumentError('invalid onError method')
- }
+ // 5. Let stream be the result of calling get stream on blob.
+ /** @type {import('stream/web').ReadableStream} */
+ const stream = blob.stream()
- handler.onError(err)
+ // 6. Let reader be the result of getting a reader from stream.
+ const reader = stream.getReader()
- return false
- }
- }
-}
+ // 7. Let bytes be an empty byte sequence.
+ /** @type {Uint8Array[]} */
+ const bytes = []
-module.exports = DispatcherBase
+ // 8. Let chunkPromise be the result of reading a chunk from
+ // stream with reader.
+ let chunkPromise = reader.read()
+ // 9. Let isFirstChunk be true.
+ let isFirstChunk = true
-/***/ }),
+ // 10. In parallel, while true:
+ // Note: "In parallel" just means non-blocking
+ // Note 2: readOperation itself cannot be async as double
+ // reading the body would then reject the promise, instead
+ // of throwing an error.
+ ;(async () => {
+ while (!fr[kAborted]) {
+ // 1. Wait for chunkPromise to be fulfilled or rejected.
+ try {
+ const { done, value } = await chunkPromise
-/***/ 20303:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. If chunkPromise is fulfilled, and isFirstChunk is
+ // true, queue a task to fire a progress event called
+ // loadstart at fr.
+ if (isFirstChunk && !fr[kAborted]) {
+ queueMicrotask(() => {
+ fireAProgressEvent('loadstart', fr)
+ })
+ }
+ // 3. Set isFirstChunk to false.
+ isFirstChunk = false
+ // 4. If chunkPromise is fulfilled with an object whose
+ // done property is false and whose value property is
+ // a Uint8Array object, run these steps:
+ if (!done && types.isUint8Array(value)) {
+ // 1. Let bs be the byte sequence represented by the
+ // Uint8Array object.
-const EventEmitter = __nccwpck_require__(24434)
+ // 2. Append bs to bytes.
+ bytes.push(value)
-class Dispatcher extends EventEmitter {
- dispatch () {
- throw new Error('not implemented')
- }
+ // 3. If roughly 50ms have passed since these steps
+ // were last invoked, queue a task to fire a
+ // progress event called progress at fr.
+ if (
+ (
+ fr[kLastProgressEventFired] === undefined ||
+ Date.now() - fr[kLastProgressEventFired] >= 50
+ ) &&
+ !fr[kAborted]
+ ) {
+ fr[kLastProgressEventFired] = Date.now()
+ queueMicrotask(() => {
+ fireAProgressEvent('progress', fr)
+ })
+ }
- close () {
- throw new Error('not implemented')
- }
+ // 4. Set chunkPromise to the result of reading a
+ // chunk from stream with reader.
+ chunkPromise = reader.read()
+ } else if (done) {
+ // 5. Otherwise, if chunkPromise is fulfilled with an
+ // object whose done property is true, queue a task
+ // to run the following steps and abort this algorithm:
+ queueMicrotask(() => {
+ // 1. Set fr’s state to "done".
+ fr[kState] = 'done'
- destroy () {
- throw new Error('not implemented')
- }
-}
+ // 2. Let result be the result of package data given
+ // bytes, type, blob’s type, and encodingName.
+ try {
+ const result = packageData(bytes, type, blob.type, encodingName)
-module.exports = Dispatcher
+ // 4. Else:
+ if (fr[kAborted]) {
+ return
+ }
-/***/ }),
+ // 1. Set fr’s result to result.
+ fr[kResult] = result
-/***/ 37791:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // 2. Fire a progress event called load at the fr.
+ fireAProgressEvent('load', fr)
+ } catch (error) {
+ // 3. If package data threw an exception error:
+ // 1. Set fr’s error to error.
+ fr[kError] = error
+ // 2. Fire a progress event called error at fr.
+ fireAProgressEvent('error', fr)
+ }
-const Busboy = __nccwpck_require__(75249)
-const util = __nccwpck_require__(89500)
-const {
- ReadableStreamFrom,
- isBlobLike,
- isReadableStreamLike,
- readableStreamClose,
- createDeferredPromise,
- fullyReadBody
-} = __nccwpck_require__(72847)
-const { FormData } = __nccwpck_require__(47453)
-const { kState } = __nccwpck_require__(63730)
-const { webidl } = __nccwpck_require__(94354)
-const { DOMException, structuredClone } = __nccwpck_require__(21234)
-const { Blob, File: NativeFile } = __nccwpck_require__(20181)
-const { kBodyUsed } = __nccwpck_require__(68031)
-const assert = __nccwpck_require__(42613)
-const { isErrored } = __nccwpck_require__(89500)
-const { isUint8Array, isArrayBuffer } = __nccwpck_require__(98253)
-const { File: UndiciFile } = __nccwpck_require__(17005)
-const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
+ // 5. If fr’s state is not "loading", fire a progress
+ // event called loadend at the fr.
+ if (fr[kState] !== 'loading') {
+ fireAProgressEvent('loadend', fr)
+ }
+ })
-let ReadableStream = globalThis.ReadableStream
+ break
+ }
+ } catch (error) {
+ if (fr[kAborted]) {
+ return
+ }
-/** @type {globalThis['File']} */
-const File = NativeFile ?? UndiciFile
-const textEncoder = new TextEncoder()
-const textDecoder = new TextDecoder()
+ // 6. Otherwise, if chunkPromise is rejected with an
+ // error error, queue a task to run the following
+ // steps and abort this algorithm:
+ queueMicrotask(() => {
+ // 1. Set fr’s state to "done".
+ fr[kState] = 'done'
-// https://fetch.spec.whatwg.org/#concept-bodyinit-extract
-function extractBody (object, keepalive = false) {
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(63774).ReadableStream)
- }
+ // 2. Set fr’s error to error.
+ fr[kError] = error
- // 1. Let stream be null.
- let stream = null
+ // 3. Fire a progress event called error at fr.
+ fireAProgressEvent('error', fr)
- // 2. If object is a ReadableStream object, then set stream to object.
- if (object instanceof ReadableStream) {
- stream = object
- } else if (isBlobLike(object)) {
- // 3. Otherwise, if object is a Blob object, set stream to the
- // result of running object’s get stream.
- stream = object.stream()
- } else {
- // 4. Otherwise, set stream to a new ReadableStream object, and set
- // up stream.
- stream = new ReadableStream({
- async pull (controller) {
- controller.enqueue(
- typeof source === 'string' ? textEncoder.encode(source) : source
- )
- queueMicrotask(() => readableStreamClose(controller))
- },
- start () {},
- type: undefined
- })
- }
+ // 4. If fr’s state is not "loading", fire a progress
+ // event called loadend at fr.
+ if (fr[kState] !== 'loading') {
+ fireAProgressEvent('loadend', fr)
+ }
+ })
- // 5. Assert: stream is a ReadableStream object.
- assert(isReadableStreamLike(stream))
+ break
+ }
+ }
+ })()
+}
- // 6. Let action be null.
- let action = null
+/**
+ * @see https://w3c.github.io/FileAPI/#fire-a-progress-event
+ * @see https://dom.spec.whatwg.org/#concept-event-fire
+ * @param {string} e The name of the event
+ * @param {import('./filereader').FileReader} reader
+ */
+function fireAProgressEvent (e, reader) {
+ // The progress event e does not bubble. e.bubbles must be false
+ // The progress event e is NOT cancelable. e.cancelable must be false
+ const event = new ProgressEvent(e, {
+ bubbles: false,
+ cancelable: false
+ })
- // 7. Let source be null.
- let source = null
+ reader.dispatchEvent(event)
+}
- // 8. Let length be null.
- let length = null
+/**
+ * @see https://w3c.github.io/FileAPI/#blob-package-data
+ * @param {Uint8Array[]} bytes
+ * @param {string} type
+ * @param {string?} mimeType
+ * @param {string?} encodingName
+ */
+function packageData (bytes, type, mimeType, encodingName) {
+ // 1. A Blob has an associated package data algorithm, given
+ // bytes, a type, a optional mimeType, and a optional
+ // encodingName, which switches on type and runs the
+ // associated steps:
- // 9. Let type be null.
- let type = null
+ switch (type) {
+ case 'DataURL': {
+ // 1. Return bytes as a DataURL [RFC2397] subject to
+ // the considerations below:
+ // * Use mimeType as part of the Data URL if it is
+ // available in keeping with the Data URL
+ // specification [RFC2397].
+ // * If mimeType is not available return a Data URL
+ // without a media-type. [RFC2397].
- // 10. Switch on object:
- if (typeof object === 'string') {
- // Set source to the UTF-8 encoding of object.
- // Note: setting source to a Uint8Array here breaks some mocking assumptions.
- source = object
+ // https://datatracker.ietf.org/doc/html/rfc2397#section-3
+ // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
+ // mediatype := [ type "/" subtype ] *( ";" parameter )
+ // data := *urlchar
+ // parameter := attribute "=" value
+ let dataURL = 'data:'
- // Set type to `text/plain;charset=UTF-8`.
- type = 'text/plain;charset=UTF-8'
- } else if (object instanceof URLSearchParams) {
- // URLSearchParams
+ const parsed = parseMIMEType(mimeType || 'application/octet-stream')
- // spec says to run application/x-www-form-urlencoded on body.list
- // this is implemented in Node.js as apart of an URLSearchParams instance toString method
- // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490
- // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100
+ if (parsed !== 'failure') {
+ dataURL += serializeAMimeType(parsed)
+ }
- // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list.
- source = object.toString()
+ dataURL += ';base64,'
- // Set type to `application/x-www-form-urlencoded;charset=UTF-8`.
- type = 'application/x-www-form-urlencoded;charset=UTF-8'
- } else if (isArrayBuffer(object)) {
- // BufferSource/ArrayBuffer
+ const decoder = new StringDecoder('latin1')
- // Set source to a copy of the bytes held by object.
- source = new Uint8Array(object.slice())
- } else if (ArrayBuffer.isView(object)) {
- // BufferSource/ArrayBufferView
+ for (const chunk of bytes) {
+ dataURL += btoa(decoder.write(chunk))
+ }
- // Set source to a copy of the bytes held by object.
- source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength))
- } else if (util.isFormDataLike(object)) {
- const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`
- const prefix = `--${boundary}\r\nContent-Disposition: form-data`
+ dataURL += btoa(decoder.end())
- /*! formdata-polyfill. MIT License. Jimmy Wärting */
- const escape = (str) =>
- str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
- const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
+ return dataURL
+ }
+ case 'Text': {
+ // 1. Let encoding be failure
+ let encoding = 'failure'
- // Set action to this step: run the multipart/form-data
- // encoding algorithm, with object’s entry list and UTF-8.
- // - This ensures that the body is immutable and can't be changed afterwords
- // - That the content-length is calculated in advance.
- // - And that all parts are pre-encoded and ready to be sent.
+ // 2. If the encodingName is present, set encoding to the
+ // result of getting an encoding from encodingName.
+ if (encodingName) {
+ encoding = getEncoding(encodingName)
+ }
- const blobParts = []
- const rn = new Uint8Array([13, 10]) // '\r\n'
- length = 0
- let hasUnknownSizeValue = false
+ // 3. If encoding is failure, and mimeType is present:
+ if (encoding === 'failure' && mimeType) {
+ // 1. Let type be the result of parse a MIME type
+ // given mimeType.
+ const type = parseMIMEType(mimeType)
- for (const [name, value] of object) {
- if (typeof value === 'string') {
- const chunk = textEncoder.encode(prefix +
- `; name="${escape(normalizeLinefeeds(name))}"` +
- `\r\n\r\n${normalizeLinefeeds(value)}\r\n`)
- blobParts.push(chunk)
- length += chunk.byteLength
- } else {
- const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` +
- (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' +
- `Content-Type: ${
- value.type || 'application/octet-stream'
- }\r\n\r\n`)
- blobParts.push(chunk, value, rn)
- if (typeof value.size === 'number') {
- length += chunk.byteLength + value.size + rn.byteLength
- } else {
- hasUnknownSizeValue = true
+ // 2. If type is not failure, set encoding to the result
+ // of getting an encoding from type’s parameters["charset"].
+ if (type !== 'failure') {
+ encoding = getEncoding(type.parameters.get('charset'))
}
}
+
+ // 4. If encoding is failure, then set encoding to UTF-8.
+ if (encoding === 'failure') {
+ encoding = 'UTF-8'
+ }
+
+ // 5. Decode bytes using fallback encoding encoding, and
+ // return the result.
+ return decode(bytes, encoding)
}
+ case 'ArrayBuffer': {
+ // Return a new ArrayBuffer whose contents are bytes.
+ const sequence = combineByteSequences(bytes)
- const chunk = textEncoder.encode(`--${boundary}--`)
- blobParts.push(chunk)
- length += chunk.byteLength
- if (hasUnknownSizeValue) {
- length = null
+ return sequence.buffer
}
+ case 'BinaryString': {
+ // Return bytes as a binary string, in which every byte
+ // is represented by a code unit of equal value [0..255].
+ let binaryString = ''
- // Set source to object.
- source = object
+ const decoder = new StringDecoder('latin1')
- action = async function * () {
- for (const part of blobParts) {
- if (part.stream) {
- yield * part.stream()
- } else {
- yield part
- }
+ for (const chunk of bytes) {
+ binaryString += decoder.write(chunk)
}
- }
- // Set type to `multipart/form-data; boundary=`,
- // followed by the multipart/form-data boundary string generated
- // by the multipart/form-data encoding algorithm.
- type = 'multipart/form-data; boundary=' + boundary
- } else if (isBlobLike(object)) {
- // Blob
+ binaryString += decoder.end()
- // Set source to object.
- source = object
+ return binaryString
+ }
+ }
+}
- // Set length to object’s size.
- length = object.size
+/**
+ * @see https://encoding.spec.whatwg.org/#decode
+ * @param {Uint8Array[]} ioQueue
+ * @param {string} encoding
+ */
+function decode (ioQueue, encoding) {
+ const bytes = combineByteSequences(ioQueue)
- // If object’s type attribute is not the empty byte sequence, set
- // type to its value.
- if (object.type) {
- type = object.type
- }
- } else if (typeof object[Symbol.asyncIterator] === 'function') {
- // If keepalive is true, then throw a TypeError.
- if (keepalive) {
- throw new TypeError('keepalive')
- }
+ // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
+ const BOMEncoding = BOMSniffing(bytes)
- // If object is disturbed or locked, then throw a TypeError.
- if (util.isDisturbed(object) || object.locked) {
- throw new TypeError(
- 'Response body object should not be disturbed or locked'
- )
- }
+ let slice = 0
- stream =
- object instanceof ReadableStream ? object : ReadableStreamFrom(object)
- }
+ // 2. If BOMEncoding is non-null:
+ if (BOMEncoding !== null) {
+ // 1. Set encoding to BOMEncoding.
+ encoding = BOMEncoding
- // 11. If source is a byte sequence, then set action to a
- // step that returns source and length to source’s length.
- if (typeof source === 'string' || util.isBuffer(source)) {
- length = Buffer.byteLength(source)
+ // 2. Read three bytes from ioQueue, if BOMEncoding is
+ // UTF-8; otherwise read two bytes.
+ // (Do nothing with those bytes.)
+ slice = BOMEncoding === 'UTF-8' ? 3 : 2
}
- // 12. If action is non-null, then run these steps in in parallel:
- if (action != null) {
- // Run action.
- let iterator
- stream = new ReadableStream({
- async start () {
- iterator = action(object)[Symbol.asyncIterator]()
- },
- async pull (controller) {
- const { value, done } = await iterator.next()
- if (done) {
- // When running action is done, close stream.
- queueMicrotask(() => {
- controller.close()
- })
- } else {
- // Whenever one or more bytes are available and stream is not errored,
- // enqueue a Uint8Array wrapping an ArrayBuffer containing the available
- // bytes into stream.
- if (!isErrored(stream)) {
- controller.enqueue(new Uint8Array(value))
- }
- }
- return controller.desiredSize > 0
- },
- async cancel (reason) {
- await iterator.return()
- },
- type: undefined
- })
- }
+ // 3. Process a queue with an instance of encoding’s
+ // decoder, ioQueue, output, and "replacement".
- // 13. Let body be a body whose stream is stream, source is source,
- // and length is length.
- const body = { stream, source, length }
+ // 4. Return output.
- // 14. Return (body, type).
- return [body, type]
+ const sliced = bytes.slice(slice)
+ return new TextDecoder(encoding).decode(sliced)
}
-// https://fetch.spec.whatwg.org/#bodyinit-safely-extract
-function safelyExtractBody (object, keepalive = false) {
- if (!ReadableStream) {
- // istanbul ignore next
- ReadableStream = (__nccwpck_require__(63774).ReadableStream)
- }
-
- // To safely extract a body and a `Content-Type` value from
- // a byte sequence or BodyInit object object, run these steps:
+/**
+ * @see https://encoding.spec.whatwg.org/#bom-sniff
+ * @param {Uint8Array} ioQueue
+ */
+function BOMSniffing (ioQueue) {
+ // 1. Let BOM be the result of peeking 3 bytes from ioQueue,
+ // converted to a byte sequence.
+ const [a, b, c] = ioQueue
- // 1. If object is a ReadableStream object, then:
- if (object instanceof ReadableStream) {
- // Assert: object is neither disturbed nor locked.
- // istanbul ignore next
- assert(!util.isDisturbed(object), 'The body has already been consumed.')
- // istanbul ignore next
- assert(!object.locked, 'The stream is locked.')
+ // 2. For each of the rows in the table below, starting with
+ // the first one and going down, if BOM starts with the
+ // bytes given in the first column, then return the
+ // encoding given in the cell in the second column of that
+ // row. Otherwise, return null.
+ if (a === 0xEF && b === 0xBB && c === 0xBF) {
+ return 'UTF-8'
+ } else if (a === 0xFE && b === 0xFF) {
+ return 'UTF-16BE'
+ } else if (a === 0xFF && b === 0xFE) {
+ return 'UTF-16LE'
}
- // 2. Return the results of extracting object.
- return extractBody(object, keepalive)
+ return null
}
-function cloneBody (body) {
- // To clone a body body, run these steps:
+/**
+ * @param {Uint8Array[]} sequences
+ */
+function combineByteSequences (sequences) {
+ const size = sequences.reduce((a, b) => {
+ return a + b.byteLength
+ }, 0)
- // https://fetch.spec.whatwg.org/#concept-body-clone
+ let offset = 0
- // 1. Let « out1, out2 » be the result of teeing body’s stream.
- const [out1, out2] = body.stream.tee()
- const out2Clone = structuredClone(out2, { transfer: [out2] })
- // This, for whatever reasons, unrefs out2Clone which allows
- // the process to exit by itself.
- const [, finalClone] = out2Clone.tee()
+ return sequences.reduce((a, b) => {
+ a.set(b, offset)
+ offset += b.byteLength
+ return a
+ }, new Uint8Array(size))
+}
+
+module.exports = {
+ staticPropertyDescriptors,
+ readOperation,
+ fireAProgressEvent
+}
- // 2. Set body’s stream to out1.
- body.stream = out1
- // 3. Return a body whose stream is out2 and other members are copied from body.
- return {
- stream: finalClone,
- length: body.length,
- source: body.source
- }
-}
+/***/ }),
-async function * consumeBody (body) {
- if (body) {
- if (isUint8Array(body)) {
- yield body
- } else {
- const stream = body.stream
+/***/ 61481:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (util.isDisturbed(stream)) {
- throw new TypeError('The body has already been consumed.')
- }
- if (stream.locked) {
- throw new TypeError('The stream is locked.')
- }
- // Compat.
- stream[kBodyUsed] = true
+// We include a version number for the Dispatcher API. In case of breaking changes,
+// this version number must be increased to avoid conflicts.
+const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
+const { InvalidArgumentError } = __nccwpck_require__(53959)
+const Agent = __nccwpck_require__(92121)
- yield * stream
- }
- }
+if (getGlobalDispatcher() === undefined) {
+ setGlobalDispatcher(new Agent())
}
-function throwIfAborted (state) {
- if (state.aborted) {
- throw new DOMException('The operation was aborted.', 'AbortError')
+function setGlobalDispatcher (agent) {
+ if (!agent || typeof agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument agent must implement Agent')
}
+ Object.defineProperty(globalThis, globalDispatcher, {
+ value: agent,
+ writable: true,
+ enumerable: false,
+ configurable: false
+ })
}
-function bodyMixinMethods (instance) {
- const methods = {
- blob () {
- // The blob() method steps are to return the result of
- // running consume body with this and the following step
- // given a byte sequence bytes: return a Blob whose
- // contents are bytes and whose type attribute is this’s
- // MIME type.
- return specConsumeBody(this, (bytes) => {
- let mimeType = bodyMimeType(this)
-
- if (mimeType === 'failure') {
- mimeType = ''
- } else if (mimeType) {
- mimeType = serializeAMimeType(mimeType)
- }
-
- // Return a Blob whose contents are bytes and type attribute
- // is mimeType.
- return new Blob([bytes], { type: mimeType })
- }, instance)
- },
+function getGlobalDispatcher () {
+ return globalThis[globalDispatcher]
+}
- arrayBuffer () {
- // The arrayBuffer() method steps are to return the result
- // of running consume body with this and the following step
- // given a byte sequence bytes: return a new ArrayBuffer
- // whose contents are bytes.
- return specConsumeBody(this, (bytes) => {
- return new Uint8Array(bytes).buffer
- }, instance)
- },
+module.exports = {
+ setGlobalDispatcher,
+ getGlobalDispatcher
+}
- text () {
- // The text() method steps are to return the result of running
- // consume body with this and UTF-8 decode.
- return specConsumeBody(this, utf8DecodeBytes, instance)
- },
- json () {
- // The json() method steps are to return the result of running
- // consume body with this and parse JSON from bytes.
- return specConsumeBody(this, parseJSONFromBytes, instance)
- },
+/***/ }),
- async formData () {
- webidl.brandCheck(this, instance)
+/***/ 41468:
+/***/ ((module) => {
- throwIfAborted(this[kState])
- const contentType = this.headers.get('Content-Type')
- // If mimeType’s essence is "multipart/form-data", then:
- if (/multipart\/form-data/.test(contentType)) {
- const headers = {}
- for (const [key, value] of this.headers) headers[key.toLowerCase()] = value
+module.exports = class DecoratorHandler {
+ constructor (handler) {
+ this.handler = handler
+ }
- const responseFormData = new FormData()
+ onConnect (...args) {
+ return this.handler.onConnect(...args)
+ }
- let busboy
+ onError (...args) {
+ return this.handler.onError(...args)
+ }
- try {
- busboy = new Busboy({
- headers,
- preservePath: true
- })
- } catch (err) {
- throw new DOMException(`${err}`, 'AbortError')
- }
+ onUpgrade (...args) {
+ return this.handler.onUpgrade(...args)
+ }
- busboy.on('field', (name, value) => {
- responseFormData.append(name, value)
- })
- busboy.on('file', (name, value, filename, encoding, mimeType) => {
- const chunks = []
+ onHeaders (...args) {
+ return this.handler.onHeaders(...args)
+ }
- if (encoding === 'base64' || encoding.toLowerCase() === 'base64') {
- let base64chunk = ''
+ onData (...args) {
+ return this.handler.onData(...args)
+ }
- value.on('data', (chunk) => {
- base64chunk += chunk.toString().replace(/[\r\n]/gm, '')
+ onComplete (...args) {
+ return this.handler.onComplete(...args)
+ }
- const end = base64chunk.length - base64chunk.length % 4
- chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64'))
+ onBodySent (...args) {
+ return this.handler.onBodySent(...args)
+ }
+}
- base64chunk = base64chunk.slice(end)
- })
- value.on('end', () => {
- chunks.push(Buffer.from(base64chunk, 'base64'))
- responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
- })
- } else {
- value.on('data', (chunk) => {
- chunks.push(chunk)
- })
- value.on('end', () => {
- responseFormData.append(name, new File(chunks, filename, { type: mimeType }))
- })
- }
- })
- const busboyResolve = new Promise((resolve, reject) => {
- busboy.on('finish', resolve)
- busboy.on('error', (err) => reject(new TypeError(err)))
- })
+/***/ }),
- if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk)
- busboy.end()
- await busboyResolve
+/***/ 8591:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- return responseFormData
- } else if (/application\/x-www-form-urlencoded/.test(contentType)) {
- // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then:
- // 1. Let entries be the result of parsing bytes.
- let entries
- try {
- let text = ''
- // application/x-www-form-urlencoded parser will keep the BOM.
- // https://url.spec.whatwg.org/#concept-urlencoded-parser
- // Note that streaming decoder is stateful and cannot be reused
- const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true })
- for await (const chunk of consumeBody(this[kState].body)) {
- if (!isUint8Array(chunk)) {
- throw new TypeError('Expected Uint8Array chunk')
- }
- text += streamingDecoder.decode(chunk, { stream: true })
- }
- text += streamingDecoder.decode()
- entries = new URLSearchParams(text)
- } catch (err) {
- // istanbul ignore next: Unclear when new URLSearchParams can fail on a string.
- // 2. If entries is failure, then throw a TypeError.
- throw Object.assign(new TypeError(), { cause: err })
- }
+const util = __nccwpck_require__(89500)
+const { kBodyUsed } = __nccwpck_require__(68031)
+const assert = __nccwpck_require__(42613)
+const { InvalidArgumentError } = __nccwpck_require__(53959)
+const EE = __nccwpck_require__(24434)
- // 3. Return a new FormData object whose entries are entries.
- const formData = new FormData()
- for (const [name, value] of entries) {
- formData.append(name, value)
- }
- return formData
- } else {
- // Wait a tick before checking if the request has been aborted.
- // Otherwise, a TypeError can be thrown when an AbortError should.
- await Promise.resolve()
+const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
- throwIfAborted(this[kState])
+const kBody = Symbol('body')
- // Otherwise, throw a TypeError.
- throw webidl.errors.exception({
- header: `${instance.name}.formData`,
- message: 'Could not parse content as FormData.'
- })
- }
- }
+class BodyAsyncIterable {
+ constructor (body) {
+ this[kBody] = body
+ this[kBodyUsed] = false
}
- return methods
+ async * [Symbol.asyncIterator] () {
+ assert(!this[kBodyUsed], 'disturbed')
+ this[kBodyUsed] = true
+ yield * this[kBody]
+ }
}
-function mixinBody (prototype) {
- Object.assign(prototype.prototype, bodyMixinMethods(prototype))
-}
+class RedirectHandler {
+ constructor (dispatch, maxRedirections, opts, handler) {
+ if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
+ throw new InvalidArgumentError('maxRedirections must be a positive number')
+ }
-/**
- * @see https://fetch.spec.whatwg.org/#concept-body-consume-body
- * @param {Response|Request} object
- * @param {(value: unknown) => unknown} convertBytesToJSValue
- * @param {Response|Request} instance
- */
-async function specConsumeBody (object, convertBytesToJSValue, instance) {
- webidl.brandCheck(object, instance)
+ util.validateHandler(handler, opts.method, opts.upgrade)
- throwIfAborted(object[kState])
+ this.dispatch = dispatch
+ this.location = null
+ this.abort = null
+ this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy
+ this.maxRedirections = maxRedirections
+ this.handler = handler
+ this.history = []
- // 1. If object is unusable, then return a promise rejected
- // with a TypeError.
- if (bodyUnusable(object[kState].body)) {
- throw new TypeError('Body is unusable')
- }
+ if (util.isStream(this.opts.body)) {
+ // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
+ // so that it can be dispatched again?
+ // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
+ if (util.bodyLength(this.opts.body) === 0) {
+ this.opts.body
+ .on('data', function () {
+ assert(false)
+ })
+ }
- // 2. Let promise be a new promise.
- const promise = createDeferredPromise()
+ if (typeof this.opts.body.readableDidRead !== 'boolean') {
+ this.opts.body[kBodyUsed] = false
+ EE.prototype.on.call(this.opts.body, 'data', function () {
+ this[kBodyUsed] = true
+ })
+ }
+ } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {
+ // TODO (fix): We can't access ReadableStream internal state
+ // to determine whether or not it has been disturbed. This is just
+ // a workaround.
+ this.opts.body = new BodyAsyncIterable(this.opts.body)
+ } else if (
+ this.opts.body &&
+ typeof this.opts.body !== 'string' &&
+ !ArrayBuffer.isView(this.opts.body) &&
+ util.isIterable(this.opts.body)
+ ) {
+ // TODO: Should we allow re-using iterable if !this.opts.idempotent
+ // or through some other flag?
+ this.opts.body = new BodyAsyncIterable(this.opts.body)
+ }
+ }
- // 3. Let errorSteps given error be to reject promise with error.
- const errorSteps = (error) => promise.reject(error)
+ onConnect (abort) {
+ this.abort = abort
+ this.handler.onConnect(abort, { history: this.history })
+ }
- // 4. Let successSteps given a byte sequence data be to resolve
- // promise with the result of running convertBytesToJSValue
- // with data. If that threw an exception, then run errorSteps
- // with that exception.
- const successSteps = (data) => {
- try {
- promise.resolve(convertBytesToJSValue(data))
- } catch (e) {
- errorSteps(e)
- }
+ onUpgrade (statusCode, headers, socket) {
+ this.handler.onUpgrade(statusCode, headers, socket)
}
- // 5. If object’s body is null, then run successSteps with an
- // empty byte sequence.
- if (object[kState].body == null) {
- successSteps(new Uint8Array())
- return promise.promise
+ onError (error) {
+ this.handler.onError(error)
}
- // 6. Otherwise, fully read object’s body given successSteps,
- // errorSteps, and object’s relevant global object.
- await fullyReadBody(object[kState].body, successSteps, errorSteps)
+ onHeaders (statusCode, headers, resume, statusText) {
+ this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)
+ ? null
+ : parseLocation(statusCode, headers)
- // 7. Return promise.
- return promise.promise
-}
+ if (this.opts.origin) {
+ this.history.push(new URL(this.opts.path, this.opts.origin))
+ }
-// https://fetch.spec.whatwg.org/#body-unusable
-function bodyUnusable (body) {
- // An object including the Body interface mixin is
- // said to be unusable if its body is non-null and
- // its body’s stream is disturbed or locked.
- return body != null && (body.stream.locked || util.isDisturbed(body.stream))
-}
+ if (!this.location) {
+ return this.handler.onHeaders(statusCode, headers, resume, statusText)
+ }
-/**
- * @see https://encoding.spec.whatwg.org/#utf-8-decode
- * @param {Buffer} buffer
- */
-function utf8DecodeBytes (buffer) {
- if (buffer.length === 0) {
- return ''
- }
+ const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))
+ const path = search ? `${pathname}${search}` : pathname
- // 1. Let buffer be the result of peeking three bytes from
- // ioQueue, converted to a byte sequence.
+ // Remove headers referring to the original URL.
+ // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.
+ // https://tools.ietf.org/html/rfc7231#section-6.4
+ this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)
+ this.opts.path = path
+ this.opts.origin = origin
+ this.opts.maxRedirections = 0
+ this.opts.query = null
- // 2. If buffer is 0xEF 0xBB 0xBF, then read three
- // bytes from ioQueue. (Do nothing with those bytes.)
- if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
- buffer = buffer.subarray(3)
+ // https://tools.ietf.org/html/rfc7231#section-6.4.4
+ // In case of HTTP 303, always replace method to be either HEAD or GET
+ if (statusCode === 303 && this.opts.method !== 'HEAD') {
+ this.opts.method = 'GET'
+ this.opts.body = null
+ }
}
- // 3. Process a queue with an instance of UTF-8’s
- // decoder, ioQueue, output, and "replacement".
- const output = textDecoder.decode(buffer)
+ onData (chunk) {
+ if (this.location) {
+ /*
+ https://tools.ietf.org/html/rfc7231#section-6.4
- // 4. Return output.
- return output
-}
+ TLDR: undici always ignores 3xx response bodies.
-/**
- * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
- * @param {Uint8Array} bytes
- */
-function parseJSONFromBytes (bytes) {
- return JSON.parse(utf8DecodeBytes(bytes))
-}
+ Redirection is used to serve the requested resource from another URL, so it is assumes that
+ no body is generated (and thus can be ignored). Even though generating a body is not prohibited.
-/**
- * @see https://fetch.spec.whatwg.org/#concept-body-mime-type
- * @param {import('./response').Response|import('./request').Request} object
- */
-function bodyMimeType (object) {
- const { headersList } = object[kState]
- const contentType = headersList.get('content-type')
+ For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually
+ (which means it's optional and not mandated) contain just an hyperlink to the value of
+ the Location response header, so the body can be ignored safely.
- if (contentType === null) {
- return 'failure'
+ For status 300, which is "Multiple Choices", the spec mentions both generating a Location
+ response header AND a response body with the other possible location to follow.
+ Since the spec explicitily chooses not to specify a format for such body and leave it to
+ servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.
+ */
+ } else {
+ return this.handler.onData(chunk)
+ }
}
- return parseMIMEType(contentType)
-}
-
-module.exports = {
- extractBody,
- safelyExtractBody,
- cloneBody,
- mixinBody
-}
-
+ onComplete (trailers) {
+ if (this.location) {
+ /*
+ https://tools.ietf.org/html/rfc7231#section-6.4
-/***/ }),
+ TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections
+ and neither are useful if present.
-/***/ 21234:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ See comment on onData method above for more detailed informations.
+ */
+ this.location = null
+ this.abort = null
+ this.dispatch(this.opts, this)
+ } else {
+ this.handler.onComplete(trailers)
+ }
+ }
-const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(28167)
+ onBodySent (chunk) {
+ if (this.handler.onBodySent) {
+ this.handler.onBodySent(chunk)
+ }
+ }
+}
-const corsSafeListedMethods = ['GET', 'HEAD', 'POST']
-const corsSafeListedMethodsSet = new Set(corsSafeListedMethods)
+function parseLocation (statusCode, headers) {
+ if (redirectableStatusCodes.indexOf(statusCode) === -1) {
+ return null
+ }
-const nullBodyStatus = [101, 204, 205, 304]
+ for (let i = 0; i < headers.length; i += 2) {
+ if (headers[i].toString().toLowerCase() === 'location') {
+ return headers[i + 1]
+ }
+ }
+}
-const redirectStatus = [301, 302, 303, 307, 308]
-const redirectStatusSet = new Set(redirectStatus)
+// https://tools.ietf.org/html/rfc7231#section-6.4.4
+function shouldRemoveHeader (header, removeContent, unknownOrigin) {
+ if (header.length === 4) {
+ return util.headerNameToString(header) === 'host'
+ }
+ if (removeContent && util.headerNameToString(header).startsWith('content-')) {
+ return true
+ }
+ if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
+ const name = util.headerNameToString(header)
+ return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'
+ }
+ return false
+}
-// https://fetch.spec.whatwg.org/#block-bad-port
-const badPorts = [
- '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79',
- '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137',
- '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532',
- '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723',
- '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697',
- '10080'
-]
+// https://tools.ietf.org/html/rfc7231#section-6.4
+function cleanRequestHeaders (headers, removeContent, unknownOrigin) {
+ const ret = []
+ if (Array.isArray(headers)) {
+ for (let i = 0; i < headers.length; i += 2) {
+ if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
+ ret.push(headers[i], headers[i + 1])
+ }
+ }
+ } else if (headers && typeof headers === 'object') {
+ for (const key of Object.keys(headers)) {
+ if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
+ ret.push(key, headers[key])
+ }
+ }
+ } else {
+ assert(headers == null, 'headers must be an object or an array')
+ }
+ return ret
+}
-const badPortsSet = new Set(badPorts)
+module.exports = RedirectHandler
-// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies
-const referrerPolicy = [
- '',
- 'no-referrer',
- 'no-referrer-when-downgrade',
- 'same-origin',
- 'origin',
- 'strict-origin',
- 'origin-when-cross-origin',
- 'strict-origin-when-cross-origin',
- 'unsafe-url'
-]
-const referrerPolicySet = new Set(referrerPolicy)
-const requestRedirect = ['follow', 'manual', 'error']
+/***/ }),
-const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
-const safeMethodsSet = new Set(safeMethods)
+/***/ 49569:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']
+const assert = __nccwpck_require__(42613)
-const requestCredentials = ['omit', 'same-origin', 'include']
+const { kRetryHandlerDefaultRetry } = __nccwpck_require__(68031)
+const { RequestRetryError } = __nccwpck_require__(53959)
+const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(89500)
-const requestCache = [
- 'default',
- 'no-store',
- 'reload',
- 'no-cache',
- 'force-cache',
- 'only-if-cached'
-]
+function calculateRetryAfterHeader (retryAfter) {
+ const current = Date.now()
+ const diff = new Date(retryAfter).getTime() - current
-// https://fetch.spec.whatwg.org/#request-body-header-name
-const requestBodyHeader = [
- 'content-encoding',
- 'content-language',
- 'content-location',
- 'content-type',
- // See https://github.com/nodejs/undici/issues/2021
- // 'Content-Length' is a forbidden header name, which is typically
- // removed in the Headers implementation. However, undici doesn't
- // filter out headers, so we add it here.
- 'content-length'
-]
+ return diff
+}
-// https://fetch.spec.whatwg.org/#enumdef-requestduplex
-const requestDuplex = [
- 'half'
-]
+class RetryHandler {
+ constructor (opts, handlers) {
+ const { retryOptions, ...dispatchOpts } = opts
+ const {
+ // Retry scoped
+ retry: retryFn,
+ maxRetries,
+ maxTimeout,
+ minTimeout,
+ timeoutFactor,
+ // Response scoped
+ methods,
+ errorCodes,
+ retryAfter,
+ statusCodes
+ } = retryOptions ?? {}
-// http://fetch.spec.whatwg.org/#forbidden-method
-const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']
-const forbiddenMethodsSet = new Set(forbiddenMethods)
+ this.dispatch = handlers.dispatch
+ this.handler = handlers.handler
+ this.opts = dispatchOpts
+ this.abort = null
+ this.aborted = false
+ this.retryOpts = {
+ retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],
+ retryAfter: retryAfter ?? true,
+ maxTimeout: maxTimeout ?? 30 * 1000, // 30s,
+ timeout: minTimeout ?? 500, // .5s
+ timeoutFactor: timeoutFactor ?? 2,
+ maxRetries: maxRetries ?? 5,
+ // What errors we should retry
+ methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],
+ // Indicates which errors to retry
+ statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
+ // List of errors to retry
+ errorCodes: errorCodes ?? [
+ 'ECONNRESET',
+ 'ECONNREFUSED',
+ 'ENOTFOUND',
+ 'ENETDOWN',
+ 'ENETUNREACH',
+ 'EHOSTDOWN',
+ 'EHOSTUNREACH',
+ 'EPIPE'
+ ]
+ }
-const subresource = [
- 'audio',
- 'audioworklet',
- 'font',
- 'image',
- 'manifest',
- 'paintworklet',
- 'script',
- 'style',
- 'track',
- 'video',
- 'xslt',
- ''
-]
-const subresourceSet = new Set(subresource)
+ this.retryCount = 0
+ this.start = 0
+ this.end = null
+ this.etag = null
+ this.resume = null
-/** @type {globalThis['DOMException']} */
-const DOMException = globalThis.DOMException ?? (() => {
- // DOMException was only made a global in Node v17.0.0,
- // but fetch supports >= v16.8.
- try {
- atob('~')
- } catch (err) {
- return Object.getPrototypeOf(err).constructor
+ // Handle possible onConnect duplication
+ this.handler.onConnect(reason => {
+ this.aborted = true
+ if (this.abort) {
+ this.abort(reason)
+ } else {
+ this.reason = reason
+ }
+ })
}
-})()
-let channel
+ onRequestSent () {
+ if (this.handler.onRequestSent) {
+ this.handler.onRequestSent()
+ }
+ }
-/** @type {globalThis['structuredClone']} */
-const structuredClone =
- globalThis.structuredClone ??
- // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js
- // structuredClone was added in v17.0.0, but fetch supports v16.8
- function structuredClone (value, options = undefined) {
- if (arguments.length === 0) {
- throw new TypeError('missing argument')
+ onUpgrade (statusCode, headers, socket) {
+ if (this.handler.onUpgrade) {
+ this.handler.onUpgrade(statusCode, headers, socket)
}
+ }
- if (!channel) {
- channel = new MessageChannel()
+ onConnect (abort) {
+ if (this.aborted) {
+ abort(this.reason)
+ } else {
+ this.abort = abort
}
- channel.port1.unref()
- channel.port2.unref()
- channel.port1.postMessage(value, options?.transfer)
- return receiveMessageOnPort(channel.port2).message
}
-module.exports = {
- DOMException,
- structuredClone,
- subresource,
- forbiddenMethods,
- requestBodyHeader,
- referrerPolicy,
- requestRedirect,
- requestMode,
- requestCredentials,
- requestCache,
- redirectStatus,
- corsSafeListedMethods,
- nullBodyStatus,
- safeMethods,
- badPorts,
- requestDuplex,
- subresourceSet,
- badPortsSet,
- redirectStatusSet,
- corsSafeListedMethodsSet,
- safeMethodsSet,
- forbiddenMethodsSet,
- referrerPolicySet
-}
+ onBodySent (chunk) {
+ if (this.handler.onBodySent) return this.handler.onBodySent(chunk)
+ }
+ static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
+ const { statusCode, code, headers } = err
+ const { method, retryOptions } = opts
+ const {
+ maxRetries,
+ timeout,
+ maxTimeout,
+ timeoutFactor,
+ statusCodes,
+ errorCodes,
+ methods
+ } = retryOptions
+ let { counter, currentTimeout } = state
-/***/ }),
+ currentTimeout =
+ currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout
-/***/ 37246:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ // Any code that is not a Undici's originated and allowed to retry
+ if (
+ code &&
+ code !== 'UND_ERR_REQ_RETRY' &&
+ code !== 'UND_ERR_SOCKET' &&
+ !errorCodes.includes(code)
+ ) {
+ cb(err)
+ return
+ }
-const assert = __nccwpck_require__(42613)
-const { atob } = __nccwpck_require__(20181)
-const { isomorphicDecode } = __nccwpck_require__(72847)
+ // If a set of method are provided and the current method is not in the list
+ if (Array.isArray(methods) && !methods.includes(method)) {
+ cb(err)
+ return
+ }
-const encoder = new TextEncoder()
+ // If a set of status code are provided and the current status code is not in the list
+ if (
+ statusCode != null &&
+ Array.isArray(statusCodes) &&
+ !statusCodes.includes(statusCode)
+ ) {
+ cb(err)
+ return
+ }
-/**
- * @see https://mimesniff.spec.whatwg.org/#http-token-code-point
- */
-const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/
-const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line
-/**
- * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point
- */
-const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line
+ // If we reached the max number of retries
+ if (counter > maxRetries) {
+ cb(err)
+ return
+ }
-// https://fetch.spec.whatwg.org/#data-url-processor
-/** @param {URL} dataURL */
-function dataURLProcessor (dataURL) {
- // 1. Assert: dataURL’s scheme is "data".
- assert(dataURL.protocol === 'data:')
+ let retryAfterHeader = headers != null && headers['retry-after']
+ if (retryAfterHeader) {
+ retryAfterHeader = Number(retryAfterHeader)
+ retryAfterHeader = isNaN(retryAfterHeader)
+ ? calculateRetryAfterHeader(retryAfterHeader)
+ : retryAfterHeader * 1e3 // Retry-After is in seconds
+ }
- // 2. Let input be the result of running the URL
- // serializer on dataURL with exclude fragment
- // set to true.
- let input = URLSerializer(dataURL, true)
+ const retryTimeout =
+ retryAfterHeader > 0
+ ? Math.min(retryAfterHeader, maxTimeout)
+ : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout)
- // 3. Remove the leading "data:" string from input.
- input = input.slice(5)
+ state.currentTimeout = retryTimeout
- // 4. Let position point at the start of input.
- const position = { position: 0 }
+ setTimeout(() => cb(null), retryTimeout)
+ }
- // 5. Let mimeType be the result of collecting a
- // sequence of code points that are not equal
- // to U+002C (,), given position.
- let mimeType = collectASequenceOfCodePointsFast(
- ',',
- input,
- position
- )
+ onHeaders (statusCode, rawHeaders, resume, statusMessage) {
+ const headers = parseHeaders(rawHeaders)
- // 6. Strip leading and trailing ASCII whitespace
- // from mimeType.
- // Undici implementation note: we need to store the
- // length because if the mimetype has spaces removed,
- // the wrong amount will be sliced from the input in
- // step #9
- const mimeTypeLength = mimeType.length
- mimeType = removeASCIIWhitespace(mimeType, true, true)
+ this.retryCount += 1
- // 7. If position is past the end of input, then
- // return failure
- if (position.position >= input.length) {
- return 'failure'
- }
+ if (statusCode >= 300) {
+ this.abort(
+ new RequestRetryError('Request failed', statusCode, {
+ headers,
+ count: this.retryCount
+ })
+ )
+ return false
+ }
- // 8. Advance position by 1.
- position.position++
+ // Checkpoint for resume from where we left it
+ if (this.resume != null) {
+ this.resume = null
- // 9. Let encodedBody be the remainder of input.
- const encodedBody = input.slice(mimeTypeLength + 1)
+ if (statusCode !== 206) {
+ return true
+ }
- // 10. Let body be the percent-decoding of encodedBody.
- let body = stringPercentDecode(encodedBody)
+ const contentRange = parseRangeHeader(headers['content-range'])
+ // If no content range
+ if (!contentRange) {
+ this.abort(
+ new RequestRetryError('Content-Range mismatch', statusCode, {
+ headers,
+ count: this.retryCount
+ })
+ )
+ return false
+ }
- // 11. If mimeType ends with U+003B (;), followed by
- // zero or more U+0020 SPACE, followed by an ASCII
- // case-insensitive match for "base64", then:
- if (/;(\u0020){0,}base64$/i.test(mimeType)) {
- // 1. Let stringBody be the isomorphic decode of body.
- const stringBody = isomorphicDecode(body)
+ // Let's start with a weak etag check
+ if (this.etag != null && this.etag !== headers.etag) {
+ this.abort(
+ new RequestRetryError('ETag mismatch', statusCode, {
+ headers,
+ count: this.retryCount
+ })
+ )
+ return false
+ }
- // 2. Set body to the forgiving-base64 decode of
- // stringBody.
- body = forgivingBase64(stringBody)
+ const { start, size, end = size } = contentRange
- // 3. If body is failure, then return failure.
- if (body === 'failure') {
- return 'failure'
+ assert(this.start === start, 'content-range mismatch')
+ assert(this.end == null || this.end === end, 'content-range mismatch')
+
+ this.resume = resume
+ return true
}
- // 4. Remove the last 6 code points from mimeType.
- mimeType = mimeType.slice(0, -6)
+ if (this.end == null) {
+ if (statusCode === 206) {
+ // First time we receive 206
+ const range = parseRangeHeader(headers['content-range'])
- // 5. Remove trailing U+0020 SPACE code points from mimeType,
- // if any.
- mimeType = mimeType.replace(/(\u0020)+$/, '')
+ if (range == null) {
+ return this.handler.onHeaders(
+ statusCode,
+ rawHeaders,
+ resume,
+ statusMessage
+ )
+ }
- // 6. Remove the last U+003B (;) code point from mimeType.
- mimeType = mimeType.slice(0, -1)
- }
+ const { start, size, end = size } = range
- // 12. If mimeType starts with U+003B (;), then prepend
- // "text/plain" to mimeType.
- if (mimeType.startsWith(';')) {
- mimeType = 'text/plain' + mimeType
- }
+ assert(
+ start != null && Number.isFinite(start) && this.start !== start,
+ 'content-range mismatch'
+ )
+ assert(Number.isFinite(start))
+ assert(
+ end != null && Number.isFinite(end) && this.end !== end,
+ 'invalid content-length'
+ )
- // 13. Let mimeTypeRecord be the result of parsing
- // mimeType.
- let mimeTypeRecord = parseMIMEType(mimeType)
+ this.start = start
+ this.end = end
+ }
- // 14. If mimeTypeRecord is failure, then set
- // mimeTypeRecord to text/plain;charset=US-ASCII.
- if (mimeTypeRecord === 'failure') {
- mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII')
+ // We make our best to checkpoint the body for further range headers
+ if (this.end == null) {
+ const contentLength = headers['content-length']
+ this.end = contentLength != null ? Number(contentLength) : null
+ }
+
+ assert(Number.isFinite(this.start))
+ assert(
+ this.end == null || Number.isFinite(this.end),
+ 'invalid content-length'
+ )
+
+ this.resume = resume
+ this.etag = headers.etag != null ? headers.etag : null
+
+ return this.handler.onHeaders(
+ statusCode,
+ rawHeaders,
+ resume,
+ statusMessage
+ )
+ }
+
+ const err = new RequestRetryError('Request failed', statusCode, {
+ headers,
+ count: this.retryCount
+ })
+
+ this.abort(err)
+
+ return false
}
- // 15. Return a new data: URL struct whose MIME
- // type is mimeTypeRecord and body is body.
- // https://fetch.spec.whatwg.org/#data-url-struct
- return { mimeType: mimeTypeRecord, body }
-}
+ onData (chunk) {
+ this.start += chunk.length
-// https://url.spec.whatwg.org/#concept-url-serializer
-/**
- * @param {URL} url
- * @param {boolean} excludeFragment
- */
-function URLSerializer (url, excludeFragment = false) {
- if (!excludeFragment) {
- return url.href
+ return this.handler.onData(chunk)
}
- const href = url.href
- const hashLength = url.hash.length
+ onComplete (rawTrailers) {
+ this.retryCount = 0
+ return this.handler.onComplete(rawTrailers)
+ }
- return hashLength === 0 ? href : href.substring(0, href.length - hashLength)
-}
+ onError (err) {
+ if (this.aborted || isDisturbed(this.opts.body)) {
+ return this.handler.onError(err)
+ }
-// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points
-/**
- * @param {(char: string) => boolean} condition
- * @param {string} input
- * @param {{ position: number }} position
- */
-function collectASequenceOfCodePoints (condition, input, position) {
- // 1. Let result be the empty string.
- let result = ''
+ this.retryOpts.retry(
+ err,
+ {
+ state: { counter: this.retryCount++, currentTimeout: this.retryAfter },
+ opts: { retryOptions: this.retryOpts, ...this.opts }
+ },
+ onRetry.bind(this)
+ )
- // 2. While position doesn’t point past the end of input and the
- // code point at position within input meets the condition condition:
- while (position.position < input.length && condition(input[position.position])) {
- // 1. Append that code point to the end of result.
- result += input[position.position]
+ function onRetry (err) {
+ if (err != null || this.aborted || isDisturbed(this.opts.body)) {
+ return this.handler.onError(err)
+ }
+
+ if (this.start !== 0) {
+ this.opts = {
+ ...this.opts,
+ headers: {
+ ...this.opts.headers,
+ range: `bytes=${this.start}-${this.end ?? ''}`
+ }
+ }
+ }
- // 2. Advance position by 1.
- position.position++
+ try {
+ this.dispatch(this.opts, this)
+ } catch (err) {
+ this.handler.onError(err)
+ }
+ }
}
-
- // 3. Return result.
- return result
}
-/**
- * A faster collectASequenceOfCodePoints that only works when comparing a single character.
- * @param {string} char
- * @param {string} input
- * @param {{ position: number }} position
- */
-function collectASequenceOfCodePointsFast (char, input, position) {
- const idx = input.indexOf(char, position.position)
- const start = position.position
-
- if (idx === -1) {
- position.position = input.length
- return input.slice(start)
- }
-
- position.position = idx
- return input.slice(start, position.position)
-}
+module.exports = RetryHandler
-// https://url.spec.whatwg.org/#string-percent-decode
-/** @param {string} input */
-function stringPercentDecode (input) {
- // 1. Let bytes be the UTF-8 encoding of input.
- const bytes = encoder.encode(input)
- // 2. Return the percent-decoding of bytes.
- return percentDecode(bytes)
-}
+/***/ }),
-// https://url.spec.whatwg.org/#percent-decode
-/** @param {Uint8Array} input */
-function percentDecode (input) {
- // 1. Let output be an empty byte sequence.
- /** @type {number[]} */
- const output = []
+/***/ 99299:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. For each byte byte in input:
- for (let i = 0; i < input.length; i++) {
- const byte = input[i]
- // 1. If byte is not 0x25 (%), then append byte to output.
- if (byte !== 0x25) {
- output.push(byte)
- // 2. Otherwise, if byte is 0x25 (%) and the next two bytes
- // after byte in input are not in the ranges
- // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F),
- // and 0x61 (a) to 0x66 (f), all inclusive, append byte
- // to output.
- } else if (
- byte === 0x25 &&
- !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2]))
- ) {
- output.push(0x25)
+const RedirectHandler = __nccwpck_require__(8591)
- // 3. Otherwise:
- } else {
- // 1. Let bytePoint be the two bytes after byte in input,
- // decoded, and then interpreted as hexadecimal number.
- const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2])
- const bytePoint = Number.parseInt(nextTwoBytes, 16)
+function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {
+ return (dispatch) => {
+ return function Intercept (opts, handler) {
+ const { maxRedirections = defaultMaxRedirections } = opts
- // 2. Append a byte whose value is bytePoint to output.
- output.push(bytePoint)
+ if (!maxRedirections) {
+ return dispatch(opts, handler)
+ }
- // 3. Skip the next two bytes in input.
- i += 2
+ const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
+ opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
+ return dispatch(opts, redirectHandler)
}
}
-
- // 3. Return output.
- return Uint8Array.from(output)
}
-// https://mimesniff.spec.whatwg.org/#parse-a-mime-type
-/** @param {string} input */
-function parseMIMEType (input) {
- // 1. Remove any leading and trailing HTTP whitespace
- // from input.
- input = removeHTTPWhitespace(input, true, true)
+module.exports = createRedirectInterceptor
- // 2. Let position be a position variable for input,
- // initially pointing at the start of input.
- const position = { position: 0 }
- // 3. Let type be the result of collecting a sequence
- // of code points that are not U+002F (/) from
- // input, given position.
- const type = collectASequenceOfCodePointsFast(
- '/',
- input,
- position
- )
+/***/ }),
- // 4. If type is the empty string or does not solely
- // contain HTTP token code points, then return failure.
- // https://mimesniff.spec.whatwg.org/#http-token-code-point
- if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) {
- return 'failure'
- }
+/***/ 40748:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5. If position is past the end of input, then return
- // failure
- if (position.position > input.length) {
- return 'failure'
- }
- // 6. Advance position by 1. (This skips past U+002F (/).)
- position.position++
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
+const utils_1 = __nccwpck_require__(34608);
+// C headers
+var ERROR;
+(function (ERROR) {
+ ERROR[ERROR["OK"] = 0] = "OK";
+ ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL";
+ ERROR[ERROR["STRICT"] = 2] = "STRICT";
+ ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED";
+ ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
+ ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
+ ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD";
+ ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL";
+ ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
+ ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION";
+ ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
+ ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
+ ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
+ ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS";
+ ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
+ ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
+ ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
+ ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
+ ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
+ ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
+ ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
+ ERROR[ERROR["PAUSED"] = 21] = "PAUSED";
+ ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
+ ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
+ ERROR[ERROR["USER"] = 24] = "USER";
+})(ERROR = exports.ERROR || (exports.ERROR = {}));
+var TYPE;
+(function (TYPE) {
+ TYPE[TYPE["BOTH"] = 0] = "BOTH";
+ TYPE[TYPE["REQUEST"] = 1] = "REQUEST";
+ TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE";
+})(TYPE = exports.TYPE || (exports.TYPE = {}));
+var FLAGS;
+(function (FLAGS) {
+ FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
+ FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
+ FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
+ FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED";
+ FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE";
+ FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
+ FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY";
+ FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING";
+ // 1 << 8 is unused
+ FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
+})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
+var LENIENT_FLAGS;
+(function (LENIENT_FLAGS) {
+ LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS";
+ LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
+ LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
+})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
+var METHODS;
+(function (METHODS) {
+ METHODS[METHODS["DELETE"] = 0] = "DELETE";
+ METHODS[METHODS["GET"] = 1] = "GET";
+ METHODS[METHODS["HEAD"] = 2] = "HEAD";
+ METHODS[METHODS["POST"] = 3] = "POST";
+ METHODS[METHODS["PUT"] = 4] = "PUT";
+ /* pathological */
+ METHODS[METHODS["CONNECT"] = 5] = "CONNECT";
+ METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS";
+ METHODS[METHODS["TRACE"] = 7] = "TRACE";
+ /* WebDAV */
+ METHODS[METHODS["COPY"] = 8] = "COPY";
+ METHODS[METHODS["LOCK"] = 9] = "LOCK";
+ METHODS[METHODS["MKCOL"] = 10] = "MKCOL";
+ METHODS[METHODS["MOVE"] = 11] = "MOVE";
+ METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND";
+ METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH";
+ METHODS[METHODS["SEARCH"] = 14] = "SEARCH";
+ METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK";
+ METHODS[METHODS["BIND"] = 16] = "BIND";
+ METHODS[METHODS["REBIND"] = 17] = "REBIND";
+ METHODS[METHODS["UNBIND"] = 18] = "UNBIND";
+ METHODS[METHODS["ACL"] = 19] = "ACL";
+ /* subversion */
+ METHODS[METHODS["REPORT"] = 20] = "REPORT";
+ METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY";
+ METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT";
+ METHODS[METHODS["MERGE"] = 23] = "MERGE";
+ /* upnp */
+ METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH";
+ METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY";
+ METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE";
+ METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
+ /* RFC-5789 */
+ METHODS[METHODS["PATCH"] = 28] = "PATCH";
+ METHODS[METHODS["PURGE"] = 29] = "PURGE";
+ /* CalDAV */
+ METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR";
+ /* RFC-2068, section 19.6.1.2 */
+ METHODS[METHODS["LINK"] = 31] = "LINK";
+ METHODS[METHODS["UNLINK"] = 32] = "UNLINK";
+ /* icecast */
+ METHODS[METHODS["SOURCE"] = 33] = "SOURCE";
+ /* RFC-7540, section 11.6 */
+ METHODS[METHODS["PRI"] = 34] = "PRI";
+ /* RFC-2326 RTSP */
+ METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE";
+ METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE";
+ METHODS[METHODS["SETUP"] = 37] = "SETUP";
+ METHODS[METHODS["PLAY"] = 38] = "PLAY";
+ METHODS[METHODS["PAUSE"] = 39] = "PAUSE";
+ METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN";
+ METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER";
+ METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER";
+ METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT";
+ METHODS[METHODS["RECORD"] = 44] = "RECORD";
+ /* RAOP */
+ METHODS[METHODS["FLUSH"] = 45] = "FLUSH";
+})(METHODS = exports.METHODS || (exports.METHODS = {}));
+exports.METHODS_HTTP = [
+ METHODS.DELETE,
+ METHODS.GET,
+ METHODS.HEAD,
+ METHODS.POST,
+ METHODS.PUT,
+ METHODS.CONNECT,
+ METHODS.OPTIONS,
+ METHODS.TRACE,
+ METHODS.COPY,
+ METHODS.LOCK,
+ METHODS.MKCOL,
+ METHODS.MOVE,
+ METHODS.PROPFIND,
+ METHODS.PROPPATCH,
+ METHODS.SEARCH,
+ METHODS.UNLOCK,
+ METHODS.BIND,
+ METHODS.REBIND,
+ METHODS.UNBIND,
+ METHODS.ACL,
+ METHODS.REPORT,
+ METHODS.MKACTIVITY,
+ METHODS.CHECKOUT,
+ METHODS.MERGE,
+ METHODS['M-SEARCH'],
+ METHODS.NOTIFY,
+ METHODS.SUBSCRIBE,
+ METHODS.UNSUBSCRIBE,
+ METHODS.PATCH,
+ METHODS.PURGE,
+ METHODS.MKCALENDAR,
+ METHODS.LINK,
+ METHODS.UNLINK,
+ METHODS.PRI,
+ // TODO(indutny): should we allow it with HTTP?
+ METHODS.SOURCE,
+];
+exports.METHODS_ICE = [
+ METHODS.SOURCE,
+];
+exports.METHODS_RTSP = [
+ METHODS.OPTIONS,
+ METHODS.DESCRIBE,
+ METHODS.ANNOUNCE,
+ METHODS.SETUP,
+ METHODS.PLAY,
+ METHODS.PAUSE,
+ METHODS.TEARDOWN,
+ METHODS.GET_PARAMETER,
+ METHODS.SET_PARAMETER,
+ METHODS.REDIRECT,
+ METHODS.RECORD,
+ METHODS.FLUSH,
+ // For AirPlay
+ METHODS.GET,
+ METHODS.POST,
+];
+exports.METHOD_MAP = utils_1.enumToMap(METHODS);
+exports.H_METHOD_MAP = {};
+Object.keys(exports.METHOD_MAP).forEach((key) => {
+ if (/^H/.test(key)) {
+ exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
+ }
+});
+var FINISH;
+(function (FINISH) {
+ FINISH[FINISH["SAFE"] = 0] = "SAFE";
+ FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
+ FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE";
+})(FINISH = exports.FINISH || (exports.FINISH = {}));
+exports.ALPHA = [];
+for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
+ // Upper case
+ exports.ALPHA.push(String.fromCharCode(i));
+ // Lower case
+ exports.ALPHA.push(String.fromCharCode(i + 0x20));
+}
+exports.NUM_MAP = {
+ 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
+ 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
+};
+exports.HEX_MAP = {
+ 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
+ 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
+ A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,
+ a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,
+};
+exports.NUM = [
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+];
+exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
+exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')'];
+exports.USERINFO_CHARS = exports.ALPHANUM
+ .concat(exports.MARK)
+ .concat(['%', ';', ':', '&', '=', '+', '$', ',']);
+// TODO(indutny): use RFC
+exports.STRICT_URL_CHAR = [
+ '!', '"', '$', '%', '&', '\'',
+ '(', ')', '*', '+', ',', '-', '.', '/',
+ ':', ';', '<', '=', '>',
+ '@', '[', '\\', ']', '^', '_',
+ '`',
+ '{', '|', '}', '~',
+].concat(exports.ALPHANUM);
+exports.URL_CHAR = exports.STRICT_URL_CHAR
+ .concat(['\t', '\f']);
+// All characters with 0x80 bit set to 1
+for (let i = 0x80; i <= 0xff; i++) {
+ exports.URL_CHAR.push(i);
+}
+exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);
+/* Tokens as defined by rfc 2616. Also lowercases them.
+ * token = 1*
+ * separators = "(" | ")" | "<" | ">" | "@"
+ * | "," | ";" | ":" | "\" | <">
+ * | "/" | "[" | "]" | "?" | "="
+ * | "{" | "}" | SP | HT
+ */
+exports.STRICT_TOKEN = [
+ '!', '#', '$', '%', '&', '\'',
+ '*', '+', '-', '.',
+ '^', '_', '`',
+ '|', '~',
+].concat(exports.ALPHANUM);
+exports.TOKEN = exports.STRICT_TOKEN.concat([' ']);
+/*
+ * Verify that a char is a valid visible (printable) US-ASCII
+ * character or %x80-FF
+ */
+exports.HEADER_CHARS = ['\t'];
+for (let i = 32; i <= 255; i++) {
+ if (i !== 127) {
+ exports.HEADER_CHARS.push(i);
+ }
+}
+// ',' = \x44
+exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
+exports.MAJOR = exports.NUM_MAP;
+exports.MINOR = exports.MAJOR;
+var HEADER_STATE;
+(function (HEADER_STATE) {
+ HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL";
+ HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION";
+ HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
+ HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
+ HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
+ HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
+ HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
+})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
+exports.SPECIAL_HEADERS = {
+ 'connection': HEADER_STATE.CONNECTION,
+ 'content-length': HEADER_STATE.CONTENT_LENGTH,
+ 'proxy-connection': HEADER_STATE.CONNECTION,
+ 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,
+ 'upgrade': HEADER_STATE.UPGRADE,
+};
+//# sourceMappingURL=constants.js.map
- // 7. Let subtype be the result of collecting a sequence of
- // code points that are not U+003B (;) from input, given
- // position.
- let subtype = collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
+/***/ }),
- // 8. Remove any trailing HTTP whitespace from subtype.
- subtype = removeHTTPWhitespace(subtype, false, true)
+/***/ 63922:
+/***/ ((module) => {
- // 9. If subtype is the empty string or does not solely
- // contain HTTP token code points, then return failure.
- if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) {
- return 'failure'
- }
+module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5A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CC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0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EQDCcLQZ4BIRAMJgtBnwEhEAwlC0GgASEQDCQLQaEBIRAMIwtBogEhEAwiC0GjASEQDCELQaQBIRAMIAtBpQEhEAwfC0GmASEQDB4LQacBIRAMHQtBqAEhEAwcC0GpASEQDBsLQaoBIRAMGgtBqwEhEAwZC0GsASEQDBgLQa0BIRAMFwtBrgEhEAwWC0EBIRAMFQtBrwEhEAwUC0GwASEQDBMLQbEBIRAMEgtBswEhEAwRC0GyASEQDBALQbQBIRAMDwtBtQEhEAwOC0G2ASEQDA0LQbcBIRAMDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQA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SQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2Ahw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VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8='
- const typeLowercase = type.toLowerCase()
- const subtypeLowercase = subtype.toLowerCase()
- // 10. Let mimeType be a new MIME type record whose type
- // is type, in ASCII lowercase, and subtype is subtype,
- // in ASCII lowercase.
- // https://mimesniff.spec.whatwg.org/#mime-type
- const mimeType = {
- type: typeLowercase,
- subtype: subtypeLowercase,
- /** @type {Map} */
- parameters: new Map(),
- // https://mimesniff.spec.whatwg.org/#mime-type-essence
- essence: `${typeLowercase}/${subtypeLowercase}`
- }
+/***/ }),
- // 11. While position is not past the end of input:
- while (position.position < input.length) {
- // 1. Advance position by 1. (This skips past U+003B (;).)
- position.position++
+/***/ 53742:
+/***/ ((module) => {
- // 2. Collect a sequence of code points that are HTTP
- // whitespace from input given position.
- collectASequenceOfCodePoints(
- // https://fetch.spec.whatwg.org/#http-whitespace
- char => HTTP_WHITESPACE_REGEX.test(char),
- input,
- position
- )
+module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUB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qRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC0kBAXsgAEEQav0MAAAAAAAAAAAAAAAAAAAAACIB/QsDACAAIAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQ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pC0GcASEQDCgLQZ0BIRAMJwtBngEhEAwmC0GfASEQDCULQaABIRAMJAtBoQEhEAwjC0GiASEQDCILQaMBIRAMIQtBpAEhEAwgC0GlASEQDB8LQaYBIRAMHgtBpwEhEAwdC0GoASEQDBwLQakBIRAMGwtBqgEhEAwaC0GrASEQDBkLQawBIRAMGAtBrQEhEAwXC0GuASEQDBYLQQEhEAwVC0GvASEQDBQLQbABIRAMEwtBsQEhEAwSC0GzASEQDBELQbIBIRAMEAtBtAEhEAwPC0G1ASEQDA4LQbYBIRAMDQtBtwEhEAwMC0G4ASEQDAsLQbkBIRAMCgtBugEhEAwJC0G7ASEQDAgLQcYBIRAMBwtBvAEhEAwGC0G9ASEQDAULQb4BIRAMBAtBvwEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAA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HDYYBQe8AIRAM/AMLIAEiASACRw1/QeoAIRAM+wMLIAEiASACRw17QegAIRAM+gMLIAEiASACRw14QeYAIRAM+QMLIAEiASACRw0aQRghEAz4AwsgASIBIAJHDRRBEiEQDPcDCyABIgEgAkcNWUHFACEQDPYDCyABIgEgAkcNSkE/IRAM9QMLIAEiASACRw1IQTwhEAz0AwsgASIBIAJHDUFBMSEQDPMDCyAALQAuQQFGDesDDIcCCyAAIAEiASACEMCAgIAAQQFHDeYBIABCADcDIAznAQsgACABIgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAE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XFBCk8NACAAIBA6ACogAUEBaiEBQc8AIRAMogELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKcBCyAAQd4ANgIcIAAgATYCFCAAIAQ2AgxBACEQDLoBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKUEjTw0AIAEhAQxZCyAAQQA2AhwgACABNgIUIABB04mAgAA2AhAgAEEINgIMQQAhEAy5AQsgAEEANgIAC0EAIRAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkA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MRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='
- // 3. Let parameterName be the result of collecting a
- // sequence of code points that are not U+003B (;)
- // or U+003D (=) from input, given position.
- let parameterName = collectASequenceOfCodePoints(
- (char) => char !== ';' && char !== '=',
- input,
- position
- )
- // 4. Set parameterName to parameterName, in ASCII
- // lowercase.
- parameterName = parameterName.toLowerCase()
+/***/ }),
- // 5. If position is not past the end of input, then:
- if (position.position < input.length) {
- // 1. If the code point at position within input is
- // U+003B (;), then continue.
- if (input[position.position] === ';') {
- continue
- }
+/***/ 34608:
+/***/ ((__unused_webpack_module, exports) => {
- // 2. Advance position by 1. (This skips past U+003D (=).)
- position.position++
- }
- // 6. If position is past the end of input, then break.
- if (position.position > input.length) {
- break
- }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.enumToMap = void 0;
+function enumToMap(obj) {
+ const res = {};
+ Object.keys(obj).forEach((key) => {
+ const value = obj[key];
+ if (typeof value === 'number') {
+ res[key] = value;
+ }
+ });
+ return res;
+}
+exports.enumToMap = enumToMap;
+//# sourceMappingURL=utils.js.map
- // 7. Let parameterValue be null.
- let parameterValue = null
+/***/ }),
+
+/***/ 77017:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+
+
+
+const { kClients } = __nccwpck_require__(68031)
+const Agent = __nccwpck_require__(92121)
+const {
+ kAgent,
+ kMockAgentSet,
+ kMockAgentGet,
+ kDispatches,
+ kIsMockActive,
+ kNetConnect,
+ kGetNetConnect,
+ kOptions,
+ kFactory
+} = __nccwpck_require__(52305)
+const MockClient = __nccwpck_require__(72361)
+const MockPool = __nccwpck_require__(36480)
+const { matchValue, buildMockOptions } = __nccwpck_require__(73193)
+const { InvalidArgumentError, UndiciError } = __nccwpck_require__(53959)
+const Dispatcher = __nccwpck_require__(20303)
+const Pluralizer = __nccwpck_require__(35773)
+const PendingInterceptorsFormatter = __nccwpck_require__(85738)
- // 8. If the code point at position within input is
- // U+0022 ("), then:
- if (input[position.position] === '"') {
- // 1. Set parameterValue to the result of collecting
- // an HTTP quoted string from input, given position
- // and the extract-value flag.
- parameterValue = collectAnHTTPQuotedString(input, position, true)
+class FakeWeakRef {
+ constructor (value) {
+ this.value = value
+ }
- // 2. Collect a sequence of code points that are not
- // U+003B (;) from input, given position.
- collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
+ deref () {
+ return this.value
+ }
+}
- // 9. Otherwise:
- } else {
- // 1. Set parameterValue to the result of collecting
- // a sequence of code points that are not U+003B (;)
- // from input, given position.
- parameterValue = collectASequenceOfCodePointsFast(
- ';',
- input,
- position
- )
+class MockAgent extends Dispatcher {
+ constructor (opts) {
+ super(opts)
- // 2. Remove any trailing HTTP whitespace from parameterValue.
- parameterValue = removeHTTPWhitespace(parameterValue, false, true)
+ this[kNetConnect] = true
+ this[kIsMockActive] = true
- // 3. If parameterValue is the empty string, then continue.
- if (parameterValue.length === 0) {
- continue
- }
+ // Instantiate Agent and encapsulate
+ if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
}
+ const agent = opts && opts.agent ? opts.agent : new Agent(opts)
+ this[kAgent] = agent
- // 10. If all of the following are true
- // - parameterName is not the empty string
- // - parameterName solely contains HTTP token code points
- // - parameterValue solely contains HTTP quoted-string token code points
- // - mimeType’s parameters[parameterName] does not exist
- // then set mimeType’s parameters[parameterName] to parameterValue.
- if (
- parameterName.length !== 0 &&
- HTTP_TOKEN_CODEPOINTS.test(parameterName) &&
- (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) &&
- !mimeType.parameters.has(parameterName)
- ) {
- mimeType.parameters.set(parameterName, parameterValue)
- }
+ this[kClients] = agent[kClients]
+ this[kOptions] = buildMockOptions(opts)
}
- // 12. Return mimeType.
- return mimeType
-}
+ get (origin) {
+ let dispatcher = this[kMockAgentGet](origin)
-// https://infra.spec.whatwg.org/#forgiving-base64-decode
-/** @param {string} data */
-function forgivingBase64 (data) {
- // 1. Remove all ASCII whitespace from data.
- data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line
+ if (!dispatcher) {
+ dispatcher = this[kFactory](origin)
+ this[kMockAgentSet](origin, dispatcher)
+ }
+ return dispatcher
+ }
- // 2. If data’s code point length divides by 4 leaving
- // no remainder, then:
- if (data.length % 4 === 0) {
- // 1. If data ends with one or two U+003D (=) code points,
- // then remove them from data.
- data = data.replace(/=?=$/, '')
+ dispatch (opts, handler) {
+ // Call MockAgent.get to perform additional setup before dispatching as normal
+ this.get(opts.origin)
+ return this[kAgent].dispatch(opts, handler)
}
- // 3. If data’s code point length divides by 4 leaving
- // a remainder of 1, then return failure.
- if (data.length % 4 === 1) {
- return 'failure'
+ async close () {
+ await this[kAgent].close()
+ this[kClients].clear()
}
- // 4. If data contains a code point that is not one of
- // U+002B (+)
- // U+002F (/)
- // ASCII alphanumeric
- // then return failure.
- if (/[^+/0-9A-Za-z]/.test(data)) {
- return 'failure'
+ deactivate () {
+ this[kIsMockActive] = false
}
- const binary = atob(data)
- const bytes = new Uint8Array(binary.length)
+ activate () {
+ this[kIsMockActive] = true
+ }
- for (let byte = 0; byte < binary.length; byte++) {
- bytes[byte] = binary.charCodeAt(byte)
+ enableNetConnect (matcher) {
+ if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {
+ if (Array.isArray(this[kNetConnect])) {
+ this[kNetConnect].push(matcher)
+ } else {
+ this[kNetConnect] = [matcher]
+ }
+ } else if (typeof matcher === 'undefined') {
+ this[kNetConnect] = true
+ } else {
+ throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')
+ }
}
- return bytes
-}
+ disableNetConnect () {
+ this[kNetConnect] = false
+ }
-// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string
-// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string
-/**
- * @param {string} input
- * @param {{ position: number }} position
- * @param {boolean?} extractValue
- */
-function collectAnHTTPQuotedString (input, position, extractValue) {
- // 1. Let positionStart be position.
- const positionStart = position.position
+ // This is required to bypass issues caused by using global symbols - see:
+ // https://github.com/nodejs/undici/issues/1447
+ get isMockActive () {
+ return this[kIsMockActive]
+ }
- // 2. Let value be the empty string.
- let value = ''
+ [kMockAgentSet] (origin, dispatcher) {
+ this[kClients].set(origin, new FakeWeakRef(dispatcher))
+ }
- // 3. Assert: the code point at position within input
- // is U+0022 (").
- assert(input[position.position] === '"')
+ [kFactory] (origin) {
+ const mockOptions = Object.assign({ agent: this }, this[kOptions])
+ return this[kOptions] && this[kOptions].connections === 1
+ ? new MockClient(origin, mockOptions)
+ : new MockPool(origin, mockOptions)
+ }
- // 4. Advance position by 1.
- position.position++
+ [kMockAgentGet] (origin) {
+ // First check if we can immediately find it
+ const ref = this[kClients].get(origin)
+ if (ref) {
+ return ref.deref()
+ }
- // 5. While true:
- while (true) {
- // 1. Append the result of collecting a sequence of code points
- // that are not U+0022 (") or U+005C (\) from input, given
- // position, to value.
- value += collectASequenceOfCodePoints(
- (char) => char !== '"' && char !== '\\',
- input,
- position
- )
+ // If the origin is not a string create a dummy parent pool and return to user
+ if (typeof origin !== 'string') {
+ const dispatcher = this[kFactory]('http://localhost:9999')
+ this[kMockAgentSet](origin, dispatcher)
+ return dispatcher
+ }
- // 2. If position is past the end of input, then break.
- if (position.position >= input.length) {
- break
+ // If we match, create a pool and assign the same dispatches
+ for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {
+ const nonExplicitDispatcher = nonExplicitRef.deref()
+ if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
+ const dispatcher = this[kFactory](origin)
+ this[kMockAgentSet](origin, dispatcher)
+ dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
+ return dispatcher
+ }
}
+ }
- // 3. Let quoteOrBackslash be the code point at position within
- // input.
- const quoteOrBackslash = input[position.position]
+ [kGetNetConnect] () {
+ return this[kNetConnect]
+ }
- // 4. Advance position by 1.
- position.position++
+ pendingInterceptors () {
+ const mockAgentClients = this[kClients]
- // 5. If quoteOrBackslash is U+005C (\), then:
- if (quoteOrBackslash === '\\') {
- // 1. If position is past the end of input, then append
- // U+005C (\) to value and break.
- if (position.position >= input.length) {
- value += '\\'
- break
- }
+ return Array.from(mockAgentClients.entries())
+ .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin })))
+ .filter(({ pending }) => pending)
+ }
- // 2. Append the code point at position within input to value.
- value += input[position.position]
+ assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
+ const pending = this.pendingInterceptors()
- // 3. Advance position by 1.
- position.position++
+ if (pending.length === 0) {
+ return
+ }
- // 6. Otherwise:
- } else {
- // 1. Assert: quoteOrBackslash is U+0022 (").
- assert(quoteOrBackslash === '"')
+ const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)
- // 2. Break.
- break
- }
- }
+ throw new UndiciError(`
+${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
- // 6. If the extract-value flag is set, then return value.
- if (extractValue) {
- return value
+${pendingInterceptorsFormatter.format(pending)}
+`.trim())
}
-
- // 7. Return the code points from positionStart to position,
- // inclusive, within input.
- return input.slice(positionStart, position.position)
}
-/**
- * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type
- */
-function serializeAMimeType (mimeType) {
- assert(mimeType !== 'failure')
- const { parameters, essence } = mimeType
+module.exports = MockAgent
- // 1. Let serialization be the concatenation of mimeType’s
- // type, U+002F (/), and mimeType’s subtype.
- let serialization = essence
- // 2. For each name → value of mimeType’s parameters:
- for (let [name, value] of parameters.entries()) {
- // 1. Append U+003B (;) to serialization.
- serialization += ';'
+/***/ }),
- // 2. Append name to serialization.
- serialization += name
+/***/ 72361:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 3. Append U+003D (=) to serialization.
- serialization += '='
- // 4. If value does not solely contain HTTP token code
- // points or value is the empty string, then:
- if (!HTTP_TOKEN_CODEPOINTS.test(value)) {
- // 1. Precede each occurence of U+0022 (") or
- // U+005C (\) in value with U+005C (\).
- value = value.replace(/(\\|")/g, '\\$1')
- // 2. Prepend U+0022 (") to value.
- value = '"' + value
+const { promisify } = __nccwpck_require__(39023)
+const Client = __nccwpck_require__(45513)
+const { buildMockDispatch } = __nccwpck_require__(73193)
+const {
+ kDispatches,
+ kMockAgent,
+ kClose,
+ kOriginalClose,
+ kOrigin,
+ kOriginalDispatch,
+ kConnected
+} = __nccwpck_require__(52305)
+const { MockInterceptor } = __nccwpck_require__(5843)
+const Symbols = __nccwpck_require__(68031)
+const { InvalidArgumentError } = __nccwpck_require__(53959)
- // 3. Append U+0022 (") to value.
- value += '"'
+/**
+ * MockClient provides an API that extends the Client to influence the mockDispatches.
+ */
+class MockClient extends Client {
+ constructor (origin, opts) {
+ super(origin, opts)
+
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
}
- // 5. Append value to serialization.
- serialization += value
+ this[kMockAgent] = opts.agent
+ this[kOrigin] = origin
+ this[kDispatches] = []
+ this[kConnected] = 1
+ this[kOriginalDispatch] = this.dispatch
+ this[kOriginalClose] = this.close.bind(this)
+
+ this.dispatch = buildMockDispatch.call(this)
+ this.close = this[kClose]
}
- // 3. Return serialization.
- return serialization
-}
+ get [Symbols.kConnected] () {
+ return this[kConnected]
+ }
-/**
- * @see https://fetch.spec.whatwg.org/#http-whitespace
- * @param {string} char
- */
-function isHTTPWhiteSpace (char) {
- return char === '\r' || char === '\n' || char === '\t' || char === ' '
+ /**
+ * Sets up the base interceptor for mocking replies from undici.
+ */
+ intercept (opts) {
+ return new MockInterceptor(opts, this[kDispatches])
+ }
+
+ async [kClose] () {
+ await promisify(this[kOriginalClose])()
+ this[kConnected] = 0
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
+ }
}
-/**
- * @see https://fetch.spec.whatwg.org/#http-whitespace
- * @param {string} str
- */
-function removeHTTPWhitespace (str, leading = true, trailing = true) {
- let lead = 0
- let trail = str.length - 1
+module.exports = MockClient
- if (leading) {
- for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++);
- }
- if (trailing) {
- for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--);
- }
+/***/ }),
- return str.slice(lead, trail + 1)
-}
+/***/ 12673:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-/**
- * @see https://infra.spec.whatwg.org/#ascii-whitespace
- * @param {string} char
- */
-function isASCIIWhitespace (char) {
- return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' '
-}
-/**
- * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
- */
-function removeASCIIWhitespace (str, leading = true, trailing = true) {
- let lead = 0
- let trail = str.length - 1
- if (leading) {
- for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++);
- }
+const { UndiciError } = __nccwpck_require__(53959)
- if (trailing) {
- for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--);
+class MockNotMatchedError extends UndiciError {
+ constructor (message) {
+ super(message)
+ Error.captureStackTrace(this, MockNotMatchedError)
+ this.name = 'MockNotMatchedError'
+ this.message = message || 'The request does not match any registered mock dispatches'
+ this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
}
-
- return str.slice(lead, trail + 1)
}
module.exports = {
- dataURLProcessor,
- URLSerializer,
- collectASequenceOfCodePoints,
- collectASequenceOfCodePointsFast,
- stringPercentDecode,
- parseMIMEType,
- collectAnHTTPQuotedString,
- serializeAMimeType
+ MockNotMatchedError
}
/***/ }),
-/***/ 17005:
+/***/ 5843:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { Blob, File: NativeFile } = __nccwpck_require__(20181)
-const { types } = __nccwpck_require__(39023)
-const { kState } = __nccwpck_require__(63730)
-const { isBlobLike } = __nccwpck_require__(72847)
-const { webidl } = __nccwpck_require__(94354)
-const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(37246)
-const { kEnumerableProperty } = __nccwpck_require__(89500)
-const encoder = new TextEncoder()
+const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(73193)
+const {
+ kDispatches,
+ kDispatchKey,
+ kDefaultHeaders,
+ kDefaultTrailers,
+ kContentLength,
+ kMockDispatch
+} = __nccwpck_require__(52305)
+const { InvalidArgumentError } = __nccwpck_require__(53959)
+const { buildURL } = __nccwpck_require__(89500)
-class File extends Blob {
- constructor (fileBits, fileName, options = {}) {
- // The File constructor is invoked with two or three parameters, depending
- // on whether the optional dictionary parameter is used. When the File()
- // constructor is invoked, user agents must run the following steps:
- webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' })
+/**
+ * Defines the scope API for an interceptor reply
+ */
+class MockScope {
+ constructor (mockDispatch) {
+ this[kMockDispatch] = mockDispatch
+ }
- fileBits = webidl.converters['sequence'](fileBits)
- fileName = webidl.converters.USVString(fileName)
- options = webidl.converters.FilePropertyBag(options)
+ /**
+ * Delay a reply by a set amount in ms.
+ */
+ delay (waitInMs) {
+ if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {
+ throw new InvalidArgumentError('waitInMs must be a valid integer > 0')
+ }
- // 1. Let bytes be the result of processing blob parts given fileBits and
- // options.
- // Note: Blob handles this for us
+ this[kMockDispatch].delay = waitInMs
+ return this
+ }
- // 2. Let n be the fileName argument to the constructor.
- const n = fileName
+ /**
+ * For a defined reply, never mark as consumed.
+ */
+ persist () {
+ this[kMockDispatch].persist = true
+ return this
+ }
+
+ /**
+ * Allow one to define a reply for a set amount of matching requests.
+ */
+ times (repeatTimes) {
+ if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
+ throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')
+ }
+
+ this[kMockDispatch].times = repeatTimes
+ return this
+ }
+}
+
+/**
+ * Defines an interceptor for a Mock
+ */
+class MockInterceptor {
+ constructor (opts, mockDispatches) {
+ if (typeof opts !== 'object') {
+ throw new InvalidArgumentError('opts must be an object')
+ }
+ if (typeof opts.path === 'undefined') {
+ throw new InvalidArgumentError('opts.path must be defined')
+ }
+ if (typeof opts.method === 'undefined') {
+ opts.method = 'GET'
+ }
+ // See https://github.com/nodejs/undici/issues/1245
+ // As per RFC 3986, clients are not supposed to send URI
+ // fragments to servers when they retrieve a document,
+ if (typeof opts.path === 'string') {
+ if (opts.query) {
+ opts.path = buildURL(opts.path, opts.query)
+ } else {
+ // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811
+ const parsedURL = new URL(opts.path, 'data://')
+ opts.path = parsedURL.pathname + parsedURL.search
+ }
+ }
+ if (typeof opts.method === 'string') {
+ opts.method = opts.method.toUpperCase()
+ }
+
+ this[kDispatchKey] = buildKey(opts)
+ this[kDispatches] = mockDispatches
+ this[kDefaultHeaders] = {}
+ this[kDefaultTrailers] = {}
+ this[kContentLength] = false
+ }
+
+ createMockScopeDispatchData (statusCode, data, responseOptions = {}) {
+ const responseData = getResponseData(data)
+ const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}
+ const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }
+ const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }
- // 3. Process FilePropertyBag dictionary argument by running the following
- // substeps:
+ return { statusCode, data, headers, trailers }
+ }
- // 1. If the type member is provided and is not the empty string, let t
- // be set to the type dictionary member. If t contains any characters
- // outside the range U+0020 to U+007E, then set t to the empty string
- // and return from these substeps.
- // 2. Convert every character in t to ASCII lowercase.
- let t = options.type
- let d
+ validateReplyParameters (statusCode, data, responseOptions) {
+ if (typeof statusCode === 'undefined') {
+ throw new InvalidArgumentError('statusCode must be defined')
+ }
+ if (typeof data === 'undefined') {
+ throw new InvalidArgumentError('data must be defined')
+ }
+ if (typeof responseOptions !== 'object') {
+ throw new InvalidArgumentError('responseOptions must be an object')
+ }
+ }
- // eslint-disable-next-line no-labels
- substep: {
- if (t) {
- t = parseMIMEType(t)
+ /**
+ * Mock an undici request with a defined reply.
+ */
+ reply (replyData) {
+ // Values of reply aren't available right now as they
+ // can only be available when the reply callback is invoked.
+ if (typeof replyData === 'function') {
+ // We'll first wrap the provided callback in another function,
+ // this function will properly resolve the data from the callback
+ // when invoked.
+ const wrappedDefaultsCallback = (opts) => {
+ // Our reply options callback contains the parameter for statusCode, data and options.
+ const resolvedData = replyData(opts)
- if (t === 'failure') {
- t = ''
- // eslint-disable-next-line no-labels
- break substep
+ // Check if it is in the right format
+ if (typeof resolvedData !== 'object') {
+ throw new InvalidArgumentError('reply options callback must return an object')
}
- t = serializeAMimeType(t).toLowerCase()
+ const { statusCode, data = '', responseOptions = {} } = resolvedData
+ this.validateReplyParameters(statusCode, data, responseOptions)
+ // Since the values can be obtained immediately we return them
+ // from this higher order function that will be resolved later.
+ return {
+ ...this.createMockScopeDispatchData(statusCode, data, responseOptions)
+ }
}
- // 3. If the lastModified member is provided, let d be set to the
- // lastModified dictionary member. If it is not provided, set d to the
- // current date and time represented as the number of milliseconds since
- // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
- d = options.lastModified
+ // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)
+ return new MockScope(newMockDispatch)
}
- // 4. Return a new File object F such that:
- // F refers to the bytes byte sequence.
- // F.size is set to the number of total bytes in bytes.
- // F.name is set to n.
- // F.type is set to t.
- // F.lastModified is set to d.
+ // We can have either one or three parameters, if we get here,
+ // we should have 1-3 parameters. So we spread the arguments of
+ // this function to obtain the parameters, since replyData will always
+ // just be the statusCode.
+ const [statusCode, data = '', responseOptions = {}] = [...arguments]
+ this.validateReplyParameters(statusCode, data, responseOptions)
- super(processBlobParts(fileBits, options), { type: t })
- this[kState] = {
- name: n,
- lastModified: d,
- type: t
- }
+ // Send in-already provided data like usual
+ const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions)
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)
+ return new MockScope(newMockDispatch)
}
- get name () {
- webidl.brandCheck(this, File)
+ /**
+ * Mock an undici request with a defined error.
+ */
+ replyWithError (error) {
+ if (typeof error === 'undefined') {
+ throw new InvalidArgumentError('error must be defined')
+ }
- return this[kState].name
+ const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })
+ return new MockScope(newMockDispatch)
}
- get lastModified () {
- webidl.brandCheck(this, File)
+ /**
+ * Set default reply headers on the interceptor for subsequent replies
+ */
+ defaultReplyHeaders (headers) {
+ if (typeof headers === 'undefined') {
+ throw new InvalidArgumentError('headers must be defined')
+ }
- return this[kState].lastModified
+ this[kDefaultHeaders] = headers
+ return this
}
- get type () {
- webidl.brandCheck(this, File)
+ /**
+ * Set default reply trailers on the interceptor for subsequent replies
+ */
+ defaultReplyTrailers (trailers) {
+ if (typeof trailers === 'undefined') {
+ throw new InvalidArgumentError('trailers must be defined')
+ }
- return this[kState].type
+ this[kDefaultTrailers] = trailers
+ return this
}
-}
-class FileLike {
- constructor (blobLike, fileName, options = {}) {
- // TODO: argument idl type check
+ /**
+ * Set reply content length header for replies on the interceptor
+ */
+ replyContentLength () {
+ this[kContentLength] = true
+ return this
+ }
+}
- // The File constructor is invoked with two or three parameters, depending
- // on whether the optional dictionary parameter is used. When the File()
- // constructor is invoked, user agents must run the following steps:
+module.exports.MockInterceptor = MockInterceptor
+module.exports.MockScope = MockScope
- // 1. Let bytes be the result of processing blob parts given fileBits and
- // options.
- // 2. Let n be the fileName argument to the constructor.
- const n = fileName
+/***/ }),
- // 3. Process FilePropertyBag dictionary argument by running the following
- // substeps:
+/***/ 36480:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 1. If the type member is provided and is not the empty string, let t
- // be set to the type dictionary member. If t contains any characters
- // outside the range U+0020 to U+007E, then set t to the empty string
- // and return from these substeps.
- // TODO
- const t = options.type
- // 2. Convert every character in t to ASCII lowercase.
- // TODO
- // 3. If the lastModified member is provided, let d be set to the
- // lastModified dictionary member. If it is not provided, set d to the
- // current date and time represented as the number of milliseconds since
- // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]).
- const d = options.lastModified ?? Date.now()
+const { promisify } = __nccwpck_require__(39023)
+const Pool = __nccwpck_require__(44288)
+const { buildMockDispatch } = __nccwpck_require__(73193)
+const {
+ kDispatches,
+ kMockAgent,
+ kClose,
+ kOriginalClose,
+ kOrigin,
+ kOriginalDispatch,
+ kConnected
+} = __nccwpck_require__(52305)
+const { MockInterceptor } = __nccwpck_require__(5843)
+const Symbols = __nccwpck_require__(68031)
+const { InvalidArgumentError } = __nccwpck_require__(53959)
- // 4. Return a new File object F such that:
- // F refers to the bytes byte sequence.
- // F.size is set to the number of total bytes in bytes.
- // F.name is set to n.
- // F.type is set to t.
- // F.lastModified is set to d.
+/**
+ * MockPool provides an API that extends the Pool to influence the mockDispatches.
+ */
+class MockPool extends Pool {
+ constructor (origin, opts) {
+ super(origin, opts)
- this[kState] = {
- blobLike,
- name: n,
- type: t,
- lastModified: d
+ if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
+ throw new InvalidArgumentError('Argument opts.agent must implement Agent')
}
- }
- stream (...args) {
- webidl.brandCheck(this, FileLike)
+ this[kMockAgent] = opts.agent
+ this[kOrigin] = origin
+ this[kDispatches] = []
+ this[kConnected] = 1
+ this[kOriginalDispatch] = this.dispatch
+ this[kOriginalClose] = this.close.bind(this)
- return this[kState].blobLike.stream(...args)
+ this.dispatch = buildMockDispatch.call(this)
+ this.close = this[kClose]
}
- arrayBuffer (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.arrayBuffer(...args)
+ get [Symbols.kConnected] () {
+ return this[kConnected]
}
- slice (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.slice(...args)
+ /**
+ * Sets up the base interceptor for mocking replies from undici.
+ */
+ intercept (opts) {
+ return new MockInterceptor(opts, this[kDispatches])
}
- text (...args) {
- webidl.brandCheck(this, FileLike)
-
- return this[kState].blobLike.text(...args)
+ async [kClose] () {
+ await promisify(this[kOriginalClose])()
+ this[kConnected] = 0
+ this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
}
+}
- get size () {
- webidl.brandCheck(this, FileLike)
+module.exports = MockPool
- return this[kState].blobLike.size
- }
- get type () {
- webidl.brandCheck(this, FileLike)
+/***/ }),
- return this[kState].blobLike.type
- }
+/***/ 52305:
+/***/ ((module) => {
- get name () {
- webidl.brandCheck(this, FileLike)
- return this[kState].name
- }
- get lastModified () {
- webidl.brandCheck(this, FileLike)
+module.exports = {
+ kAgent: Symbol('agent'),
+ kOptions: Symbol('options'),
+ kFactory: Symbol('factory'),
+ kDispatches: Symbol('dispatches'),
+ kDispatchKey: Symbol('dispatch key'),
+ kDefaultHeaders: Symbol('default headers'),
+ kDefaultTrailers: Symbol('default trailers'),
+ kContentLength: Symbol('content length'),
+ kMockAgent: Symbol('mock agent'),
+ kMockAgentSet: Symbol('mock agent set'),
+ kMockAgentGet: Symbol('mock agent get'),
+ kMockDispatch: Symbol('mock dispatch'),
+ kClose: Symbol('close'),
+ kOriginalClose: Symbol('original agent close'),
+ kOrigin: Symbol('origin'),
+ kIsMockActive: Symbol('is mock active'),
+ kNetConnect: Symbol('net connect'),
+ kGetNetConnect: Symbol('get net connect'),
+ kConnected: Symbol('connected')
+}
- return this[kState].lastModified
- }
- get [Symbol.toStringTag] () {
- return 'File'
- }
-}
+/***/ }),
-Object.defineProperties(File.prototype, {
- [Symbol.toStringTag]: {
- value: 'File',
- configurable: true
- },
- name: kEnumerableProperty,
- lastModified: kEnumerableProperty
-})
+/***/ 73193:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-webidl.converters.Blob = webidl.interfaceConverter(Blob)
-webidl.converters.BlobPart = function (V, opts) {
- if (webidl.util.Type(V) === 'Object') {
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
- }
- if (
- ArrayBuffer.isView(V) ||
- types.isAnyArrayBuffer(V)
- ) {
- return webidl.converters.BufferSource(V, opts)
- }
+const { MockNotMatchedError } = __nccwpck_require__(12673)
+const {
+ kDispatches,
+ kMockAgent,
+ kOriginalDispatch,
+ kOrigin,
+ kGetNetConnect
+} = __nccwpck_require__(52305)
+const { buildURL, nop } = __nccwpck_require__(89500)
+const { STATUS_CODES } = __nccwpck_require__(58611)
+const {
+ types: {
+ isPromise
}
+} = __nccwpck_require__(39023)
- return webidl.converters.USVString(V, opts)
+function matchValue (match, value) {
+ if (typeof match === 'string') {
+ return match === value
+ }
+ if (match instanceof RegExp) {
+ return match.test(value)
+ }
+ if (typeof match === 'function') {
+ return match(value) === true
+ }
+ return false
}
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.BlobPart
-)
-
-// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag
-webidl.converters.FilePropertyBag = webidl.dictionaryConverter([
- {
- key: 'lastModified',
- converter: webidl.converters['long long'],
- get defaultValue () {
- return Date.now()
- }
- },
- {
- key: 'type',
- converter: webidl.converters.DOMString,
- defaultValue: ''
- },
- {
- key: 'endings',
- converter: (value) => {
- value = webidl.converters.DOMString(value)
- value = value.toLowerCase()
+function lowerCaseEntries (headers) {
+ return Object.fromEntries(
+ Object.entries(headers).map(([headerName, headerValue]) => {
+ return [headerName.toLocaleLowerCase(), headerValue]
+ })
+ )
+}
- if (value !== 'native') {
- value = 'transparent'
+/**
+ * @param {import('../../index').Headers|string[]|Record} headers
+ * @param {string} key
+ */
+function getHeaderByName (headers, key) {
+ if (Array.isArray(headers)) {
+ for (let i = 0; i < headers.length; i += 2) {
+ if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
+ return headers[i + 1]
}
+ }
- return value
- },
- defaultValue: 'transparent'
+ return undefined
+ } else if (typeof headers.get === 'function') {
+ return headers.get(key)
+ } else {
+ return lowerCaseEntries(headers)[key.toLocaleLowerCase()]
}
-])
+}
-/**
- * @see https://www.w3.org/TR/FileAPI/#process-blob-parts
- * @param {(NodeJS.TypedArray|Blob|string)[]} parts
- * @param {{ type: string, endings: string }} options
- */
-function processBlobParts (parts, options) {
- // 1. Let bytes be an empty sequence of bytes.
- /** @type {NodeJS.TypedArray[]} */
- const bytes = []
+/** @param {string[]} headers */
+function buildHeadersFromArray (headers) { // fetch HeadersList
+ const clone = headers.slice()
+ const entries = []
+ for (let index = 0; index < clone.length; index += 2) {
+ entries.push([clone[index], clone[index + 1]])
+ }
+ return Object.fromEntries(entries)
+}
- // 2. For each element in parts:
- for (const element of parts) {
- // 1. If element is a USVString, run the following substeps:
- if (typeof element === 'string') {
- // 1. Let s be element.
- let s = element
+function matchHeaders (mockDispatch, headers) {
+ if (typeof mockDispatch.headers === 'function') {
+ if (Array.isArray(headers)) { // fetch HeadersList
+ headers = buildHeadersFromArray(headers)
+ }
+ return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
+ }
+ if (typeof mockDispatch.headers === 'undefined') {
+ return true
+ }
+ if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {
+ return false
+ }
- // 2. If the endings member of options is "native", set s
- // to the result of converting line endings to native
- // of element.
- if (options.endings === 'native') {
- s = convertLineEndingsNative(s)
- }
+ for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {
+ const headerValue = getHeaderByName(headers, matchHeaderName)
- // 3. Append the result of UTF-8 encoding s to bytes.
- bytes.push(encoder.encode(s))
- } else if (
- types.isAnyArrayBuffer(element) ||
- types.isTypedArray(element)
- ) {
- // 2. If element is a BufferSource, get a copy of the
- // bytes held by the buffer source, and append those
- // bytes to bytes.
- if (!element.buffer) { // ArrayBuffer
- bytes.push(new Uint8Array(element))
- } else {
- bytes.push(
- new Uint8Array(element.buffer, element.byteOffset, element.byteLength)
- )
- }
- } else if (isBlobLike(element)) {
- // 3. If element is a Blob, append the bytes it represents
- // to bytes.
- bytes.push(element)
+ if (!matchValue(matchHeaderValue, headerValue)) {
+ return false
}
}
-
- // 3. Return bytes.
- return bytes
+ return true
}
-/**
- * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native
- * @param {string} s
- */
-function convertLineEndingsNative (s) {
- // 1. Let native line ending be be the code point U+000A LF.
- let nativeLineEnding = '\n'
+function safeUrl (path) {
+ if (typeof path !== 'string') {
+ return path
+ }
- // 2. If the underlying platform’s conventions are to
- // represent newlines as a carriage return and line feed
- // sequence, set native line ending to the code point
- // U+000D CR followed by the code point U+000A LF.
- if (process.platform === 'win32') {
- nativeLineEnding = '\r\n'
+ const pathSegments = path.split('?')
+
+ if (pathSegments.length !== 2) {
+ return path
}
- return s.replace(/\r?\n/g, nativeLineEnding)
+ const qp = new URLSearchParams(pathSegments.pop())
+ qp.sort()
+ return [...pathSegments, qp.toString()].join('?')
}
-// If this function is moved to ./util.js, some tools (such as
-// rollup) will warn about circular dependencies. See:
-// https://github.com/nodejs/undici/issues/1629
-function isFileLike (object) {
- return (
- (NativeFile && object instanceof NativeFile) ||
- object instanceof File || (
- object &&
- (typeof object.stream === 'function' ||
- typeof object.arrayBuffer === 'function') &&
- object[Symbol.toStringTag] === 'File'
- )
- )
+function matchKey (mockDispatch, { path, method, body, headers }) {
+ const pathMatch = matchValue(mockDispatch.path, path)
+ const methodMatch = matchValue(mockDispatch.method, method)
+ const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true
+ const headersMatch = matchHeaders(mockDispatch, headers)
+ return pathMatch && methodMatch && bodyMatch && headersMatch
}
-module.exports = { File, FileLike, isFileLike }
-
-
-/***/ }),
-
-/***/ 47453:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+function getResponseData (data) {
+ if (Buffer.isBuffer(data)) {
+ return data
+ } else if (typeof data === 'object') {
+ return JSON.stringify(data)
+ } else {
+ return data.toString()
+ }
+}
+function getMockDispatch (mockDispatches, key) {
+ const basePath = key.query ? buildURL(key.path, key.query) : key.path
+ const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
-const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(72847)
-const { kState } = __nccwpck_require__(63730)
-const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(17005)
-const { webidl } = __nccwpck_require__(94354)
-const { Blob, File: NativeFile } = __nccwpck_require__(20181)
+ // Match path
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
+ }
-/** @type {globalThis['File']} */
-const File = NativeFile ?? UndiciFile
+ // Match method
+ matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`)
+ }
-// https://xhr.spec.whatwg.org/#formdata
-class FormData {
- constructor (form) {
- if (form !== undefined) {
- throw webidl.errors.conversionFailed({
- prefix: 'FormData constructor',
- argument: 'Argument 1',
- types: ['undefined']
- })
- }
+ // Match body
+ matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`)
+ }
- this[kState] = []
+ // Match headers
+ matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
+ if (matchedMockDispatches.length === 0) {
+ throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)
}
- append (name, value, filename = undefined) {
- webidl.brandCheck(this, FormData)
+ return matchedMockDispatches[0]
+}
- webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' })
+function addMockDispatch (mockDispatches, key, data) {
+ const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
+ const replyData = typeof data === 'function' ? { callback: data } : { ...data }
+ const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
+ mockDispatches.push(newMockDispatch)
+ return newMockDispatch
+}
- if (arguments.length === 3 && !isBlobLike(value)) {
- throw new TypeError(
- "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'"
- )
+function deleteMockDispatch (mockDispatches, key) {
+ const index = mockDispatches.findIndex(dispatch => {
+ if (!dispatch.consumed) {
+ return false
}
+ return matchKey(dispatch, key)
+ })
+ if (index !== -1) {
+ mockDispatches.splice(index, 1)
+ }
+}
- // 1. Let value be value if given; otherwise blobValue.
+function buildKey (opts) {
+ const { path, method, body, headers, query } = opts
+ return {
+ path,
+ method,
+ body,
+ headers,
+ query
+ }
+}
- name = webidl.converters.USVString(name)
- value = isBlobLike(value)
- ? webidl.converters.Blob(value, { strict: false })
- : webidl.converters.USVString(value)
- filename = arguments.length === 3
- ? webidl.converters.USVString(filename)
- : undefined
+function generateKeyValues (data) {
+ return Object.entries(data).reduce((keyValuePairs, [key, value]) => [
+ ...keyValuePairs,
+ Buffer.from(`${key}`),
+ Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)
+ ], [])
+}
- // 2. Let entry be the result of creating an entry with
- // name, value, and filename if given.
- const entry = makeEntry(name, value, filename)
+/**
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
+ * @param {number} statusCode
+ */
+function getStatusText (statusCode) {
+ return STATUS_CODES[statusCode] || 'unknown'
+}
- // 3. Append entry to this’s entry list.
- this[kState].push(entry)
+async function getResponse (body) {
+ const buffers = []
+ for await (const data of body) {
+ buffers.push(data)
}
+ return Buffer.concat(buffers).toString('utf8')
+}
- delete (name) {
- webidl.brandCheck(this, FormData)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' })
+/**
+ * Mock dispatch function used to simulate undici dispatches
+ */
+function mockDispatch (opts, handler) {
+ // Get mock dispatch from built key
+ const key = buildKey(opts)
+ const mockDispatch = getMockDispatch(this[kDispatches], key)
- name = webidl.converters.USVString(name)
+ mockDispatch.timesInvoked++
- // The delete(name) method steps are to remove all entries whose name
- // is name from this’s entry list.
- this[kState] = this[kState].filter(entry => entry.name !== name)
+ // Here's where we resolve a callback if a callback is present for the dispatch data.
+ if (mockDispatch.data.callback) {
+ mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }
}
- get (name) {
- webidl.brandCheck(this, FormData)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' })
+ // Parse mockDispatch data
+ const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch
+ const { timesInvoked, times } = mockDispatch
- name = webidl.converters.USVString(name)
+ // If it's used up and not persistent, mark as consumed
+ mockDispatch.consumed = !persist && timesInvoked >= times
+ mockDispatch.pending = timesInvoked < times
- // 1. If there is no entry whose name is name in this’s entry list,
- // then return null.
- const idx = this[kState].findIndex((entry) => entry.name === name)
- if (idx === -1) {
- return null
- }
+ // If specified, trigger dispatch error
+ if (error !== null) {
+ deleteMockDispatch(this[kDispatches], key)
+ handler.onError(error)
+ return true
+ }
- // 2. Return the value of the first entry whose name is name from
- // this’s entry list.
- return this[kState][idx].value
+ // Handle the request with a delay if necessary
+ if (typeof delay === 'number' && delay > 0) {
+ setTimeout(() => {
+ handleReply(this[kDispatches])
+ }, delay)
+ } else {
+ handleReply(this[kDispatches])
}
- getAll (name) {
- webidl.brandCheck(this, FormData)
+ function handleReply (mockDispatches, _data = data) {
+ // fetch's HeadersList is a 1D string array
+ const optsHeaders = Array.isArray(opts.headers)
+ ? buildHeadersFromArray(opts.headers)
+ : opts.headers
+ const body = typeof _data === 'function'
+ ? _data({ ...opts, headers: optsHeaders })
+ : _data
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' })
+ // util.types.isPromise is likely needed for jest.
+ if (isPromise(body)) {
+ // If handleReply is asynchronous, throwing an error
+ // in the callback will reject the promise, rather than
+ // synchronously throw the error, which breaks some tests.
+ // Rather, we wait for the callback to resolve if it is a
+ // promise, and then re-run handleReply with the new body.
+ body.then((newData) => handleReply(mockDispatches, newData))
+ return
+ }
- name = webidl.converters.USVString(name)
+ const responseData = getResponseData(body)
+ const responseHeaders = generateKeyValues(headers)
+ const responseTrailers = generateKeyValues(trailers)
- // 1. If there is no entry whose name is name in this’s entry list,
- // then return the empty list.
- // 2. Return the values of all entries whose name is name, in order,
- // from this’s entry list.
- return this[kState]
- .filter((entry) => entry.name === name)
- .map((entry) => entry.value)
+ handler.abort = nop
+ handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))
+ handler.onData(Buffer.from(responseData))
+ handler.onComplete(responseTrailers)
+ deleteMockDispatch(mockDispatches, key)
}
- has (name) {
- webidl.brandCheck(this, FormData)
+ function resume () {}
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' })
+ return true
+}
- name = webidl.converters.USVString(name)
+function buildMockDispatch () {
+ const agent = this[kMockAgent]
+ const origin = this[kOrigin]
+ const originalDispatch = this[kOriginalDispatch]
- // The has(name) method steps are to return true if there is an entry
- // whose name is name in this’s entry list; otherwise false.
- return this[kState].findIndex((entry) => entry.name === name) !== -1
+ return function dispatch (opts, handler) {
+ if (agent.isMockActive) {
+ try {
+ mockDispatch.call(this, opts, handler)
+ } catch (error) {
+ if (error instanceof MockNotMatchedError) {
+ const netConnect = agent[kGetNetConnect]()
+ if (netConnect === false) {
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)
+ }
+ if (checkNetConnect(netConnect, origin)) {
+ originalDispatch.call(this, opts, handler)
+ } else {
+ throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)
+ }
+ } else {
+ throw error
+ }
+ }
+ } else {
+ originalDispatch.call(this, opts, handler)
+ }
}
+}
- set (name, value, filename = undefined) {
- webidl.brandCheck(this, FormData)
+function checkNetConnect (netConnect, origin) {
+ const url = new URL(origin)
+ if (netConnect === true) {
+ return true
+ } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
+ return true
+ }
+ return false
+}
- webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' })
+function buildMockOptions (opts) {
+ if (opts) {
+ const { agent, ...mockOptions } = opts
+ return mockOptions
+ }
+}
- if (arguments.length === 3 && !isBlobLike(value)) {
- throw new TypeError(
- "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'"
- )
- }
+module.exports = {
+ getResponseData,
+ getMockDispatch,
+ addMockDispatch,
+ deleteMockDispatch,
+ buildKey,
+ generateKeyValues,
+ matchValue,
+ getResponse,
+ getStatusText,
+ mockDispatch,
+ buildMockDispatch,
+ checkNetConnect,
+ buildMockOptions,
+ getHeaderByName
+}
- // The set(name, value) and set(name, blobValue, filename) method steps
- // are:
- // 1. Let value be value if given; otherwise blobValue.
+/***/ }),
- name = webidl.converters.USVString(name)
- value = isBlobLike(value)
- ? webidl.converters.Blob(value, { strict: false })
- : webidl.converters.USVString(value)
- filename = arguments.length === 3
- ? toUSVString(filename)
- : undefined
+/***/ 85738:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Let entry be the result of creating an entry with name, value, and
- // filename if given.
- const entry = makeEntry(name, value, filename)
- // 3. If there are entries in this’s entry list whose name is name, then
- // replace the first such entry with entry and remove the others.
- const idx = this[kState].findIndex((entry) => entry.name === name)
- if (idx !== -1) {
- this[kState] = [
- ...this[kState].slice(0, idx),
- entry,
- ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name)
- ]
- } else {
- // 4. Otherwise, append entry to this’s entry list.
- this[kState].push(entry)
- }
- }
- entries () {
- webidl.brandCheck(this, FormData)
+const { Transform } = __nccwpck_require__(2203)
+const { Console } = __nccwpck_require__(64236)
- return makeIterator(
- () => this[kState].map(pair => [pair.name, pair.value]),
- 'FormData',
- 'key+value'
- )
+/**
+ * Gets the output of `console.table(…)` as a string.
+ */
+module.exports = class PendingInterceptorsFormatter {
+ constructor ({ disableColors } = {}) {
+ this.transform = new Transform({
+ transform (chunk, _enc, cb) {
+ cb(null, chunk)
+ }
+ })
+
+ this.logger = new Console({
+ stdout: this.transform,
+ inspectOptions: {
+ colors: !disableColors && !process.env.CI
+ }
+ })
}
- keys () {
- webidl.brandCheck(this, FormData)
+ format (pendingInterceptors) {
+ const withPrettyHeaders = pendingInterceptors.map(
+ ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
+ Method: method,
+ Origin: origin,
+ Path: path,
+ 'Status code': statusCode,
+ Persistent: persist ? '✅' : '❌',
+ Invocations: timesInvoked,
+ Remaining: persist ? Infinity : times - timesInvoked
+ }))
- return makeIterator(
- () => this[kState].map(pair => [pair.name, pair.value]),
- 'FormData',
- 'key'
- )
+ this.logger.table(withPrettyHeaders)
+ return this.transform.read().toString()
}
+}
- values () {
- webidl.brandCheck(this, FormData)
- return makeIterator(
- () => this[kState].map(pair => [pair.name, pair.value]),
- 'FormData',
- 'value'
- )
- }
+/***/ }),
- /**
- * @param {(value: string, key: string, self: FormData) => void} callbackFn
- * @param {unknown} thisArg
- */
- forEach (callbackFn, thisArg = globalThis) {
- webidl.brandCheck(this, FormData)
+/***/ 35773:
+/***/ ((module) => {
- webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' })
- if (typeof callbackFn !== 'function') {
- throw new TypeError(
- "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'."
- )
- }
- for (const [key, value] of this) {
- callbackFn.apply(thisArg, [value, key, this])
- }
- }
+const singulars = {
+ pronoun: 'it',
+ is: 'is',
+ was: 'was',
+ this: 'this'
}
-FormData.prototype[Symbol.iterator] = FormData.prototype.entries
+const plurals = {
+ pronoun: 'they',
+ is: 'are',
+ was: 'were',
+ this: 'these'
+}
-Object.defineProperties(FormData.prototype, {
- [Symbol.toStringTag]: {
- value: 'FormData',
- configurable: true
+module.exports = class Pluralizer {
+ constructor (singular, plural) {
+ this.singular = singular
+ this.plural = plural
}
-})
-/**
- * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry
- * @param {string} name
- * @param {string|Blob} value
- * @param {?string} filename
- * @returns
- */
-function makeEntry (name, value, filename) {
- // 1. Set name to the result of converting name into a scalar value string.
- // "To convert a string into a scalar value string, replace any surrogates
- // with U+FFFD."
- // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end
- name = Buffer.from(name).toString('utf8')
+ pluralize (count) {
+ const one = count === 1
+ const keys = one ? singulars : plurals
+ const noun = one ? this.singular : this.plural
+ return { ...keys, count, noun }
+ }
+}
- // 2. If value is a string, then set value to the result of converting
- // value into a scalar value string.
- if (typeof value === 'string') {
- value = Buffer.from(value).toString('utf8')
- } else {
- // 3. Otherwise:
- // 1. If value is not a File object, then set value to a new File object,
- // representing the same bytes, whose name attribute value is "blob"
- if (!isFileLike(value)) {
- value = value instanceof Blob
- ? new File([value], 'blob', { type: value.type })
- : new FileLike(value, 'blob', { type: value.type })
- }
+/***/ }),
- // 2. If filename is given, then set value to a new File object,
- // representing the same bytes, whose name attribute is filename.
- if (filename !== undefined) {
- /** @type {FilePropertyBag} */
- const options = {
- type: value.type,
- lastModified: value.lastModified
- }
+/***/ 98721:
+/***/ ((module) => {
- value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile
- ? new File([value], filename, options)
- : new FileLike(value, filename, options)
- }
- }
+/* eslint-disable */
- // 4. Return an entry whose name is name and whose value is value.
- return { name, value }
-}
-module.exports = { FormData }
+// Extracted from node/lib/internal/fixed_queue.js
-/***/ }),
+// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.
+const kSize = 2048;
+const kMask = kSize - 1;
-/***/ 62896:
-/***/ ((module) => {
+// The FixedQueue is implemented as a singly-linked list of fixed-size
+// circular buffers. It looks something like this:
+//
+// head tail
+// | |
+// v v
+// +-----------+ <-----\ +-----------+ <------\ +-----------+
+// | [null] | \----- | next | \------- | next |
+// +-----------+ +-----------+ +-----------+
+// | item | <-- bottom | item | <-- bottom | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | | [empty] |
+// | item | | item | bottom --> | item |
+// | item | | item | | item |
+// | ... | | ... | | ... |
+// | item | | item | | item |
+// | item | | item | | item |
+// | [empty] | <-- top | item | | item |
+// | [empty] | | item | | item |
+// | [empty] | | [empty] | <-- top top --> | [empty] |
+// +-----------+ +-----------+ +-----------+
+//
+// Or, if there is only one circular buffer, it looks something
+// like either of these:
+//
+// head tail head tail
+// | | | |
+// v v v v
+// +-----------+ +-----------+
+// | [null] | | [null] |
+// +-----------+ +-----------+
+// | [empty] | | item |
+// | [empty] | | item |
+// | item | <-- bottom top --> | [empty] |
+// | item | | [empty] |
+// | [empty] | <-- top bottom --> | item |
+// | [empty] | | item |
+// +-----------+ +-----------+
+//
+// Adding a value means moving `top` forward by one, removing means
+// moving `bottom` forward by one. After reaching the end, the queue
+// wraps around.
+//
+// When `top === bottom` the current queue is empty and when
+// `top + 1 === bottom` it's full. This wastes a single space of storage
+// but allows much quicker checks.
+
+class FixedCircularBuffer {
+ constructor() {
+ this.bottom = 0;
+ this.top = 0;
+ this.list = new Array(kSize);
+ this.next = null;
+ }
+ isEmpty() {
+ return this.top === this.bottom;
+ }
+ isFull() {
+ return ((this.top + 1) & kMask) === this.bottom;
+ }
-// In case of breaking changes, increase the version
-// number to avoid conflicts.
-const globalOrigin = Symbol.for('undici.globalOrigin.1')
+ push(data) {
+ this.list[this.top] = data;
+ this.top = (this.top + 1) & kMask;
+ }
-function getGlobalOrigin () {
- return globalThis[globalOrigin]
+ shift() {
+ const nextItem = this.list[this.bottom];
+ if (nextItem === undefined)
+ return null;
+ this.list[this.bottom] = undefined;
+ this.bottom = (this.bottom + 1) & kMask;
+ return nextItem;
+ }
}
-function setGlobalOrigin (newOrigin) {
- if (newOrigin === undefined) {
- Object.defineProperty(globalThis, globalOrigin, {
- value: undefined,
- writable: true,
- enumerable: false,
- configurable: false
- })
-
- return
+module.exports = class FixedQueue {
+ constructor() {
+ this.head = this.tail = new FixedCircularBuffer();
}
- const parsedURL = new URL(newOrigin)
-
- if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') {
- throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`)
+ isEmpty() {
+ return this.head.isEmpty();
}
- Object.defineProperty(globalThis, globalOrigin, {
- value: parsedURL,
- writable: true,
- enumerable: false,
- configurable: false
- })
-}
+ push(data) {
+ if (this.head.isFull()) {
+ // Head is full: Creates a new queue, sets the old queue's `.next` to it,
+ // and sets it as the new main queue.
+ this.head = this.head.next = new FixedCircularBuffer();
+ }
+ this.head.push(data);
+ }
-module.exports = {
- getGlobalOrigin,
- setGlobalOrigin
-}
+ shift() {
+ const tail = this.tail;
+ const next = tail.shift();
+ if (tail.isEmpty() && tail.next !== null) {
+ // If there is another queue, it forms the new tail.
+ this.tail = tail.next;
+ }
+ return next;
+ }
+};
/***/ }),
-/***/ 12801:
+/***/ 18804:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// https://github.com/Ethan-Arrowood/undici-fetch
+const DispatcherBase = __nccwpck_require__(52421)
+const FixedQueue = __nccwpck_require__(98721)
+const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(68031)
+const PoolStats = __nccwpck_require__(29218)
-const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
-const { kGuard } = __nccwpck_require__(63730)
-const { kEnumerableProperty } = __nccwpck_require__(89500)
-const {
- makeIterator,
- isValidHeaderName,
- isValidHeaderValue
-} = __nccwpck_require__(72847)
-const { webidl } = __nccwpck_require__(94354)
-const assert = __nccwpck_require__(42613)
+const kClients = Symbol('clients')
+const kNeedDrain = Symbol('needDrain')
+const kQueue = Symbol('queue')
+const kClosedResolve = Symbol('closed resolve')
+const kOnDrain = Symbol('onDrain')
+const kOnConnect = Symbol('onConnect')
+const kOnDisconnect = Symbol('onDisconnect')
+const kOnConnectionError = Symbol('onConnectionError')
+const kGetDispatcher = Symbol('get dispatcher')
+const kAddClient = Symbol('add client')
+const kRemoveClient = Symbol('remove client')
+const kStats = Symbol('stats')
-const kHeadersMap = Symbol('headers map')
-const kHeadersSortedMap = Symbol('headers map sorted')
+class PoolBase extends DispatcherBase {
+ constructor () {
+ super()
-/**
- * @param {number} code
- */
-function isHTTPWhiteSpaceCharCode (code) {
- return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020
-}
+ this[kQueue] = new FixedQueue()
+ this[kClients] = []
+ this[kQueued] = 0
-/**
- * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize
- * @param {string} potentialValue
- */
-function headerValueNormalize (potentialValue) {
- // To normalize a byte sequence potentialValue, remove
- // any leading and trailing HTTP whitespace bytes from
- // potentialValue.
- let i = 0; let j = potentialValue.length
+ const pool = this
- while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j
- while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i
+ this[kOnDrain] = function onDrain (origin, targets) {
+ const queue = pool[kQueue]
- return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j)
-}
+ let needDrain = false
-function fill (headers, object) {
- // To fill a Headers object headers with a given object object, run these steps:
+ while (!needDrain) {
+ const item = queue.shift()
+ if (!item) {
+ break
+ }
+ pool[kQueued]--
+ needDrain = !this.dispatch(item.opts, item.handler)
+ }
- // 1. If object is a sequence, then for each header in object:
- // Note: webidl conversion to array has already been done.
- if (Array.isArray(object)) {
- for (let i = 0; i < object.length; ++i) {
- const header = object[i]
- // 1. If header does not contain exactly two items, then throw a TypeError.
- if (header.length !== 2) {
- throw webidl.errors.exception({
- header: 'Headers constructor',
- message: `expected name/value pair to be length 2, found ${header.length}.`
- })
+ this[kNeedDrain] = needDrain
+
+ if (!this[kNeedDrain] && pool[kNeedDrain]) {
+ pool[kNeedDrain] = false
+ pool.emit('drain', origin, [pool, ...targets])
}
- // 2. Append (header’s first item, header’s second item) to headers.
- appendHeader(headers, header[0], header[1])
+ if (pool[kClosedResolve] && queue.isEmpty()) {
+ Promise
+ .all(pool[kClients].map(c => c.close()))
+ .then(pool[kClosedResolve])
+ }
}
- } else if (typeof object === 'object' && object !== null) {
- // Note: null should throw
- // 2. Otherwise, object is a record, then for each key → value in object,
- // append (key, value) to headers
- const keys = Object.keys(object)
- for (let i = 0; i < keys.length; ++i) {
- appendHeader(headers, keys[i], object[keys[i]])
+ this[kOnConnect] = (origin, targets) => {
+ pool.emit('connect', origin, [pool, ...targets])
}
- } else {
- throw webidl.errors.conversionFailed({
- prefix: 'Headers constructor',
- argument: 'Argument 1',
- types: ['sequence>', 'record']
- })
- }
-}
-/**
- * @see https://fetch.spec.whatwg.org/#concept-headers-append
- */
-function appendHeader (headers, name, value) {
- // 1. Normalize value.
- value = headerValueNormalize(value)
+ this[kOnDisconnect] = (origin, targets, err) => {
+ pool.emit('disconnect', origin, [pool, ...targets], err)
+ }
- // 2. If name is not a header name or value is not a
- // header value, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.append',
- value: name,
- type: 'header name'
- })
- } else if (!isValidHeaderValue(value)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.append',
- value,
- type: 'header value'
- })
- }
+ this[kOnConnectionError] = (origin, targets, err) => {
+ pool.emit('connectionError', origin, [pool, ...targets], err)
+ }
- // 3. If headers’s guard is "immutable", then throw a TypeError.
- // 4. Otherwise, if headers’s guard is "request" and name is a
- // forbidden header name, return.
- // Note: undici does not implement forbidden header names
- if (headers[kGuard] === 'immutable') {
- throw new TypeError('immutable')
- } else if (headers[kGuard] === 'request-no-cors') {
- // 5. Otherwise, if headers’s guard is "request-no-cors":
- // TODO
+ this[kStats] = new PoolStats(this)
}
- // 6. Otherwise, if headers’s guard is "response" and name is a
- // forbidden response-header name, return.
-
- // 7. Append (name, value) to headers’s header list.
- return headers[kHeadersList].append(name, value)
-
- // 8. If headers’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from headers
-}
-
-class HeadersList {
- /** @type {[string, string][]|null} */
- cookies = null
-
- constructor (init) {
- if (init instanceof HeadersList) {
- this[kHeadersMap] = new Map(init[kHeadersMap])
- this[kHeadersSortedMap] = init[kHeadersSortedMap]
- this.cookies = init.cookies === null ? null : [...init.cookies]
- } else {
- this[kHeadersMap] = new Map(init)
- this[kHeadersSortedMap] = null
- }
+ get [kBusy] () {
+ return this[kNeedDrain]
}
- // https://fetch.spec.whatwg.org/#header-list-contains
- contains (name) {
- // A header list list contains a header name name if list
- // contains a header whose name is a byte-case-insensitive
- // match for name.
- name = name.toLowerCase()
-
- return this[kHeadersMap].has(name)
+ get [kConnected] () {
+ return this[kClients].filter(client => client[kConnected]).length
}
- clear () {
- this[kHeadersMap].clear()
- this[kHeadersSortedMap] = null
- this.cookies = null
+ get [kFree] () {
+ return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length
}
- // https://fetch.spec.whatwg.org/#concept-header-list-append
- append (name, value) {
- this[kHeadersSortedMap] = null
-
- // 1. If list contains name, then set name to the first such
- // header’s name.
- const lowercaseName = name.toLowerCase()
- const exists = this[kHeadersMap].get(lowercaseName)
-
- // 2. Append (name, value) to list.
- if (exists) {
- const delimiter = lowercaseName === 'cookie' ? '; ' : ', '
- this[kHeadersMap].set(lowercaseName, {
- name: exists.name,
- value: `${exists.value}${delimiter}${value}`
- })
- } else {
- this[kHeadersMap].set(lowercaseName, { name, value })
- }
-
- if (lowercaseName === 'set-cookie') {
- this.cookies ??= []
- this.cookies.push(value)
+ get [kPending] () {
+ let ret = this[kQueued]
+ for (const { [kPending]: pending } of this[kClients]) {
+ ret += pending
}
+ return ret
}
- // https://fetch.spec.whatwg.org/#concept-header-list-set
- set (name, value) {
- this[kHeadersSortedMap] = null
- const lowercaseName = name.toLowerCase()
-
- if (lowercaseName === 'set-cookie') {
- this.cookies = [value]
+ get [kRunning] () {
+ let ret = 0
+ for (const { [kRunning]: running } of this[kClients]) {
+ ret += running
}
-
- // 1. If list contains name, then set the value of
- // the first such header to value and remove the
- // others.
- // 2. Otherwise, append header (name, value) to list.
- this[kHeadersMap].set(lowercaseName, { name, value })
+ return ret
}
- // https://fetch.spec.whatwg.org/#concept-header-list-delete
- delete (name) {
- this[kHeadersSortedMap] = null
-
- name = name.toLowerCase()
-
- if (name === 'set-cookie') {
- this.cookies = null
+ get [kSize] () {
+ let ret = this[kQueued]
+ for (const { [kSize]: size } of this[kClients]) {
+ ret += size
}
-
- this[kHeadersMap].delete(name)
+ return ret
}
- // https://fetch.spec.whatwg.org/#concept-header-list-get
- get (name) {
- const value = this[kHeadersMap].get(name.toLowerCase())
-
- // 1. If list does not contain name, then return null.
- // 2. Return the values of all headers in list whose name
- // is a byte-case-insensitive match for name,
- // separated from each other by 0x2C 0x20, in order.
- return value === undefined ? null : value.value
+ get stats () {
+ return this[kStats]
}
- * [Symbol.iterator] () {
- // use the lowercased name
- for (const [name, { value }] of this[kHeadersMap]) {
- yield [name, value]
+ async [kClose] () {
+ if (this[kQueue].isEmpty()) {
+ return Promise.all(this[kClients].map(c => c.close()))
+ } else {
+ return new Promise((resolve) => {
+ this[kClosedResolve] = resolve
+ })
}
}
- get entries () {
- const headers = {}
-
- if (this[kHeadersMap].size) {
- for (const { name, value } of this[kHeadersMap].values()) {
- headers[name] = value
+ async [kDestroy] (err) {
+ while (true) {
+ const item = this[kQueue].shift()
+ if (!item) {
+ break
}
+ item.handler.onError(err)
}
- return headers
- }
-}
-
-// https://fetch.spec.whatwg.org/#headers-class
-class Headers {
- constructor (init = undefined) {
- if (init === kConstruct) {
- return
- }
- this[kHeadersList] = new HeadersList()
-
- // The new Headers(init) constructor steps are:
-
- // 1. Set this’s guard to "none".
- this[kGuard] = 'none'
-
- // 2. If init is given, then fill this with init.
- if (init !== undefined) {
- init = webidl.converters.HeadersInit(init)
- fill(this, init)
- }
- }
-
- // https://fetch.spec.whatwg.org/#dom-headers-append
- append (name, value) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' })
-
- name = webidl.converters.ByteString(name)
- value = webidl.converters.ByteString(value)
-
- return appendHeader(this, name, value)
+ return Promise.all(this[kClients].map(c => c.destroy(err)))
}
- // https://fetch.spec.whatwg.org/#dom-headers-delete
- delete (name) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' })
-
- name = webidl.converters.ByteString(name)
-
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.delete',
- value: name,
- type: 'header name'
- })
- }
-
- // 2. If this’s guard is "immutable", then throw a TypeError.
- // 3. Otherwise, if this’s guard is "request" and name is a
- // forbidden header name, return.
- // 4. Otherwise, if this’s guard is "request-no-cors", name
- // is not a no-CORS-safelisted request-header name, and
- // name is not a privileged no-CORS request-header name,
- // return.
- // 5. Otherwise, if this’s guard is "response" and name is
- // a forbidden response-header name, return.
- // Note: undici does not implement forbidden header names
- if (this[kGuard] === 'immutable') {
- throw new TypeError('immutable')
- } else if (this[kGuard] === 'request-no-cors') {
- // TODO
- }
+ [kDispatch] (opts, handler) {
+ const dispatcher = this[kGetDispatcher]()
- // 6. If this’s header list does not contain name, then
- // return.
- if (!this[kHeadersList].contains(name)) {
- return
+ if (!dispatcher) {
+ this[kNeedDrain] = true
+ this[kQueue].push({ opts, handler })
+ this[kQueued]++
+ } else if (!dispatcher.dispatch(opts, handler)) {
+ dispatcher[kNeedDrain] = true
+ this[kNeedDrain] = !this[kGetDispatcher]()
}
- // 7. Delete name from this’s header list.
- // 8. If this’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from this.
- this[kHeadersList].delete(name)
+ return !this[kNeedDrain]
}
- // https://fetch.spec.whatwg.org/#dom-headers-get
- get (name) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' })
+ [kAddClient] (client) {
+ client
+ .on('drain', this[kOnDrain])
+ .on('connect', this[kOnConnect])
+ .on('disconnect', this[kOnDisconnect])
+ .on('connectionError', this[kOnConnectionError])
- name = webidl.converters.ByteString(name)
+ this[kClients].push(client)
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.get',
- value: name,
- type: 'header name'
+ if (this[kNeedDrain]) {
+ process.nextTick(() => {
+ if (this[kNeedDrain]) {
+ this[kOnDrain](client[kUrl], [this, client])
+ }
})
}
- // 2. Return the result of getting name from this’s header
- // list.
- return this[kHeadersList].get(name)
+ return this
}
- // https://fetch.spec.whatwg.org/#dom-headers-has
- has (name) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' })
-
- name = webidl.converters.ByteString(name)
-
- // 1. If name is not a header name, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.has',
- value: name,
- type: 'header name'
- })
- }
+ [kRemoveClient] (client) {
+ client.close(() => {
+ const idx = this[kClients].indexOf(client)
+ if (idx !== -1) {
+ this[kClients].splice(idx, 1)
+ }
+ })
- // 2. Return true if this’s header list contains name;
- // otherwise false.
- return this[kHeadersList].contains(name)
+ this[kNeedDrain] = this[kClients].some(dispatcher => (
+ !dispatcher[kNeedDrain] &&
+ dispatcher.closed !== true &&
+ dispatcher.destroyed !== true
+ ))
}
+}
- // https://fetch.spec.whatwg.org/#dom-headers-set
- set (name, value) {
- webidl.brandCheck(this, Headers)
-
- webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' })
+module.exports = {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kRemoveClient,
+ kGetDispatcher
+}
- name = webidl.converters.ByteString(name)
- value = webidl.converters.ByteString(value)
- // 1. Normalize value.
- value = headerValueNormalize(value)
+/***/ }),
- // 2. If name is not a header name or value is not a
- // header value, then throw a TypeError.
- if (!isValidHeaderName(name)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.set',
- value: name,
- type: 'header name'
- })
- } else if (!isValidHeaderValue(value)) {
- throw webidl.errors.invalidArgument({
- prefix: 'Headers.set',
- value,
- type: 'header value'
- })
- }
+/***/ 29218:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 3. If this’s guard is "immutable", then throw a TypeError.
- // 4. Otherwise, if this’s guard is "request" and name is a
- // forbidden header name, return.
- // 5. Otherwise, if this’s guard is "request-no-cors" and
- // name/value is not a no-CORS-safelisted request-header,
- // return.
- // 6. Otherwise, if this’s guard is "response" and name is a
- // forbidden response-header name, return.
- // Note: undici does not implement forbidden header names
- if (this[kGuard] === 'immutable') {
- throw new TypeError('immutable')
- } else if (this[kGuard] === 'request-no-cors') {
- // TODO
- }
+const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(68031)
+const kPool = Symbol('pool')
- // 7. Set (name, value) in this’s header list.
- // 8. If this’s guard is "request-no-cors", then remove
- // privileged no-CORS request headers from this
- this[kHeadersList].set(name, value)
+class PoolStats {
+ constructor (pool) {
+ this[kPool] = pool
}
- // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie
- getSetCookie () {
- webidl.brandCheck(this, Headers)
+ get connected () {
+ return this[kPool][kConnected]
+ }
- // 1. If this’s header list does not contain `Set-Cookie`, then return « ».
- // 2. Return the values of all headers in this’s header list whose name is
- // a byte-case-insensitive match for `Set-Cookie`, in order.
+ get free () {
+ return this[kPool][kFree]
+ }
- const list = this[kHeadersList].cookies
+ get pending () {
+ return this[kPool][kPending]
+ }
- if (list) {
- return [...list]
- }
+ get queued () {
+ return this[kPool][kQueued]
+ }
- return []
+ get running () {
+ return this[kPool][kRunning]
}
- // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine
- get [kHeadersSortedMap] () {
- if (this[kHeadersList][kHeadersSortedMap]) {
- return this[kHeadersList][kHeadersSortedMap]
- }
+ get size () {
+ return this[kPool][kSize]
+ }
+}
- // 1. Let headers be an empty list of headers with the key being the name
- // and value the value.
- const headers = []
+module.exports = PoolStats
- // 2. Let names be the result of convert header names to a sorted-lowercase
- // set with all the names of the headers in list.
- const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)
- const cookies = this[kHeadersList].cookies
- // 3. For each name of names:
- for (let i = 0; i < names.length; ++i) {
- const [name, value] = names[i]
- // 1. If name is `set-cookie`, then:
- if (name === 'set-cookie') {
- // 1. Let values be a list of all values of headers in list whose name
- // is a byte-case-insensitive match for name, in order.
+/***/ }),
- // 2. For each value of values:
- // 1. Append (name, value) to headers.
- for (let j = 0; j < cookies.length; ++j) {
- headers.push([name, cookies[j]])
- }
- } else {
- // 2. Otherwise:
+/***/ 44288:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 1. Let value be the result of getting name from list.
- // 2. Assert: value is non-null.
- assert(value !== null)
- // 3. Append (name, value) to headers.
- headers.push([name, value])
- }
- }
+const {
+ PoolBase,
+ kClients,
+ kNeedDrain,
+ kAddClient,
+ kGetDispatcher
+} = __nccwpck_require__(18804)
+const Client = __nccwpck_require__(45513)
+const {
+ InvalidArgumentError
+} = __nccwpck_require__(53959)
+const util = __nccwpck_require__(89500)
+const { kUrl, kInterceptors } = __nccwpck_require__(68031)
+const buildConnector = __nccwpck_require__(91332)
- this[kHeadersList][kHeadersSortedMap] = headers
+const kOptions = Symbol('options')
+const kConnections = Symbol('connections')
+const kFactory = Symbol('factory')
- // 4. Return headers.
- return headers
- }
+function defaultFactory (origin, opts) {
+ return new Client(origin, opts)
+}
- keys () {
- webidl.brandCheck(this, Headers)
+class Pool extends PoolBase {
+ constructor (origin, {
+ connections,
+ factory = defaultFactory,
+ connect,
+ connectTimeout,
+ tls,
+ maxCachedSessions,
+ socketPath,
+ autoSelectFamily,
+ autoSelectFamilyAttemptTimeout,
+ allowH2,
+ ...options
+ } = {}) {
+ super()
- if (this[kGuard] === 'immutable') {
- const value = this[kHeadersSortedMap]
- return makeIterator(() => value, 'Headers',
- 'key')
+ if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
+ throw new InvalidArgumentError('invalid connections')
}
- return makeIterator(
- () => [...this[kHeadersSortedMap].values()],
- 'Headers',
- 'key'
- )
- }
+ if (typeof factory !== 'function') {
+ throw new InvalidArgumentError('factory must be a function.')
+ }
- values () {
- webidl.brandCheck(this, Headers)
+ if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
+ throw new InvalidArgumentError('connect must be a function or an object')
+ }
- if (this[kGuard] === 'immutable') {
- const value = this[kHeadersSortedMap]
- return makeIterator(() => value, 'Headers',
- 'value')
+ if (typeof connect !== 'function') {
+ connect = buildConnector({
+ ...tls,
+ maxCachedSessions,
+ allowH2,
+ socketPath,
+ timeout: connectTimeout,
+ ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
+ ...connect
+ })
}
- return makeIterator(
- () => [...this[kHeadersSortedMap].values()],
- 'Headers',
- 'value'
- )
+ this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)
+ ? options.interceptors.Pool
+ : []
+ this[kConnections] = connections || null
+ this[kUrl] = util.parseOrigin(origin)
+ this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
+ this[kOptions].interceptors = options.interceptors
+ ? { ...options.interceptors }
+ : undefined
+ this[kFactory] = factory
}
- entries () {
- webidl.brandCheck(this, Headers)
+ [kGetDispatcher] () {
+ let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])
- if (this[kGuard] === 'immutable') {
- const value = this[kHeadersSortedMap]
- return makeIterator(() => value, 'Headers',
- 'key+value')
+ if (dispatcher) {
+ return dispatcher
}
- return makeIterator(
- () => [...this[kHeadersSortedMap].values()],
- 'Headers',
- 'key+value'
- )
+ if (!this[kConnections] || this[kClients].length < this[kConnections]) {
+ dispatcher = this[kFactory](this[kUrl], this[kOptions])
+ this[kAddClient](dispatcher)
+ }
+
+ return dispatcher
}
+}
- /**
- * @param {(value: string, key: string, self: Headers) => void} callbackFn
- * @param {unknown} thisArg
- */
- forEach (callbackFn, thisArg = globalThis) {
- webidl.brandCheck(this, Headers)
+module.exports = Pool
- webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' })
- if (typeof callbackFn !== 'function') {
- throw new TypeError(
- "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'."
- )
- }
+/***/ }),
- for (const [key, value] of this) {
- callbackFn.apply(thisArg, [value, key, this])
- }
- }
+/***/ 79276:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- [Symbol.for('nodejs.util.inspect.custom')] () {
- webidl.brandCheck(this, Headers)
- return this[kHeadersList]
- }
-}
-Headers.prototype[Symbol.iterator] = Headers.prototype.entries
+const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(68031)
+const { URL } = __nccwpck_require__(87016)
+const Agent = __nccwpck_require__(92121)
+const Pool = __nccwpck_require__(44288)
+const DispatcherBase = __nccwpck_require__(52421)
+const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(53959)
+const buildConnector = __nccwpck_require__(91332)
-Object.defineProperties(Headers.prototype, {
- append: kEnumerableProperty,
- delete: kEnumerableProperty,
- get: kEnumerableProperty,
- has: kEnumerableProperty,
- set: kEnumerableProperty,
- getSetCookie: kEnumerableProperty,
- keys: kEnumerableProperty,
- values: kEnumerableProperty,
- entries: kEnumerableProperty,
- forEach: kEnumerableProperty,
- [Symbol.iterator]: { enumerable: false },
- [Symbol.toStringTag]: {
- value: 'Headers',
- configurable: true
- }
-})
+const kAgent = Symbol('proxy agent')
+const kClient = Symbol('proxy client')
+const kProxyHeaders = Symbol('proxy headers')
+const kRequestTls = Symbol('request tls settings')
+const kProxyTls = Symbol('proxy tls settings')
+const kConnectEndpoint = Symbol('connect endpoint function')
-webidl.converters.HeadersInit = function (V) {
- if (webidl.util.Type(V) === 'Object') {
- if (V[Symbol.iterator]) {
- return webidl.converters['sequence>'](V)
- }
+function defaultProtocolPort (protocol) {
+ return protocol === 'https:' ? 443 : 80
+}
- return webidl.converters['record'](V)
+function buildProxyOptions (opts) {
+ if (typeof opts === 'string') {
+ opts = { uri: opts }
}
- throw webidl.errors.conversionFailed({
- prefix: 'Headers constructor',
- argument: 'Argument 1',
- types: ['sequence>', 'record']
- })
-}
+ if (!opts || !opts.uri) {
+ throw new InvalidArgumentError('Proxy opts.uri is mandatory')
+ }
-module.exports = {
- fill,
- Headers,
- HeadersList
+ return {
+ uri: opts.uri,
+ protocol: opts.protocol || 'https'
+ }
}
+function defaultFactory (origin, opts) {
+ return new Pool(origin, opts)
+}
-/***/ }),
+class ProxyAgent extends DispatcherBase {
+ constructor (opts) {
+ super(opts)
+ this[kProxy] = buildProxyOptions(opts)
+ this[kAgent] = new Agent(opts)
+ this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
+ ? opts.interceptors.ProxyAgent
+ : []
-/***/ 11503:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (typeof opts === 'string') {
+ opts = { uri: opts }
+ }
-// https://github.com/Ethan-Arrowood/undici-fetch
+ if (!opts || !opts.uri) {
+ throw new InvalidArgumentError('Proxy opts.uri is mandatory')
+ }
+ const { clientFactory = defaultFactory } = opts
+ if (typeof clientFactory !== 'function') {
+ throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
+ }
-const {
- Response,
- makeNetworkError,
- makeAppropriateNetworkError,
- filterResponse,
- makeResponse
-} = __nccwpck_require__(89928)
-const { Headers } = __nccwpck_require__(12801)
-const { Request, makeRequest } = __nccwpck_require__(2630)
-const zlib = __nccwpck_require__(43106)
-const {
- bytesMatch,
- makePolicyContainer,
- clonePolicyContainer,
- requestBadPort,
- TAOCheck,
- appendRequestOriginHeader,
- responseLocationURL,
- requestCurrentURL,
- setRequestReferrerPolicyOnRedirect,
- tryUpgradeRequestToAPotentiallyTrustworthyURL,
- createOpaqueTimingInfo,
- appendFetchMetadata,
- corsCheck,
- crossOriginResourcePolicyCheck,
- determineRequestsReferrer,
- coarsenedSharedCurrentTime,
- createDeferredPromise,
- isBlobLike,
- sameOrigin,
- isCancelled,
- isAborted,
- isErrorLike,
- fullyReadBody,
- readableStreamClose,
- isomorphicEncode,
- urlIsLocal,
- urlIsHttpHttpsScheme,
- urlHasHttpsScheme
-} = __nccwpck_require__(72847)
-const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
-const assert = __nccwpck_require__(42613)
-const { safelyExtractBody } = __nccwpck_require__(37791)
-const {
- redirectStatusSet,
- nullBodyStatus,
- safeMethodsSet,
- requestBodyHeader,
- subresourceSet,
- DOMException
-} = __nccwpck_require__(21234)
-const { kHeadersList } = __nccwpck_require__(68031)
-const EE = __nccwpck_require__(24434)
-const { Readable, pipeline } = __nccwpck_require__(2203)
-const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(89500)
-const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(37246)
-const { TransformStream } = __nccwpck_require__(63774)
-const { getGlobalDispatcher } = __nccwpck_require__(61481)
-const { webidl } = __nccwpck_require__(94354)
-const { STATUS_CODES } = __nccwpck_require__(58611)
-const GET_OR_HEAD = ['GET', 'HEAD']
+ this[kRequestTls] = opts.requestTls
+ this[kProxyTls] = opts.proxyTls
+ this[kProxyHeaders] = opts.headers || {}
-/** @type {import('buffer').resolveObjectURL} */
-let resolveObjectURL
-let ReadableStream = globalThis.ReadableStream
+ const resolvedUrl = new URL(opts.uri)
+ const { origin, port, host, username, password } = resolvedUrl
-class Fetch extends EE {
- constructor (dispatcher) {
- super()
+ if (opts.auth && opts.token) {
+ throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
+ } else if (opts.auth) {
+ /* @deprecated in favour of opts.token */
+ this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
+ } else if (opts.token) {
+ this[kProxyHeaders]['proxy-authorization'] = opts.token
+ } else if (username && password) {
+ this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
+ }
- this.dispatcher = dispatcher
- this.connection = null
- this.dump = false
- this.state = 'ongoing'
- // 2 terminated listeners get added per request,
- // but only 1 gets removed. If there are 20 redirects,
- // 21 listeners will be added.
- // See https://github.com/nodejs/undici/issues/1711
- // TODO (fix): Find and fix root cause for leaked listener.
- this.setMaxListeners(21)
+ const connect = buildConnector({ ...opts.proxyTls })
+ this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
+ this[kClient] = clientFactory(resolvedUrl, { connect })
+ this[kAgent] = new Agent({
+ ...opts,
+ connect: async (opts, callback) => {
+ let requestedHost = opts.host
+ if (!opts.port) {
+ requestedHost += `:${defaultProtocolPort(opts.protocol)}`
+ }
+ try {
+ const { socket, statusCode } = await this[kClient].connect({
+ origin,
+ port,
+ path: requestedHost,
+ signal: opts.signal,
+ headers: {
+ ...this[kProxyHeaders],
+ host
+ }
+ })
+ if (statusCode !== 200) {
+ socket.on('error', () => {}).destroy()
+ callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
+ }
+ if (opts.protocol !== 'https:') {
+ callback(null, socket)
+ return
+ }
+ let servername
+ if (this[kRequestTls]) {
+ servername = this[kRequestTls].servername
+ } else {
+ servername = opts.servername
+ }
+ this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
+ } catch (err) {
+ callback(err)
+ }
+ }
+ })
}
- terminate (reason) {
- if (this.state !== 'ongoing') {
- return
- }
+ dispatch (opts, handler) {
+ const { host } = new URL(opts.origin)
+ const headers = buildHeaders(opts.headers)
+ throwIfProxyAuthIsSent(headers)
+ return this[kAgent].dispatch(
+ {
+ ...opts,
+ headers: {
+ ...headers,
+ host
+ }
+ },
+ handler
+ )
+ }
- this.state = 'terminated'
- this.connection?.destroy(reason)
- this.emit('terminated', reason)
+ async [kClose] () {
+ await this[kAgent].close()
+ await this[kClient].close()
}
- // https://fetch.spec.whatwg.org/#fetch-controller-abort
- abort (error) {
- if (this.state !== 'ongoing') {
- return
- }
+ async [kDestroy] () {
+ await this[kAgent].destroy()
+ await this[kClient].destroy()
+ }
+}
- // 1. Set controller’s state to "aborted".
- this.state = 'aborted'
+/**
+ * @param {string[] | Record} headers
+ * @returns {Record}
+ */
+function buildHeaders (headers) {
+ // When using undici.fetch, the headers list is stored
+ // as an array.
+ if (Array.isArray(headers)) {
+ /** @type {Record} */
+ const headersPair = {}
- // 2. Let fallbackError be an "AbortError" DOMException.
- // 3. Set error to fallbackError if it is not given.
- if (!error) {
- error = new DOMException('The operation was aborted.', 'AbortError')
+ for (let i = 0; i < headers.length; i += 2) {
+ headersPair[headers[i]] = headers[i + 1]
}
- // 4. Let serializedError be StructuredSerialize(error).
- // If that threw an exception, catch it, and let
- // serializedError be StructuredSerialize(fallbackError).
+ return headersPair
+ }
- // 5. Set controller’s serialized abort reason to serializedError.
- this.serializedAbortReason = error
+ return headers
+}
- this.connection?.destroy(error)
- this.emit('terminated', error)
+/**
+ * @param {Record} headers
+ *
+ * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
+ * Nevertheless, it was changed and to avoid a security vulnerability by end users
+ * this check was created.
+ * It should be removed in the next major version for performance reasons
+ */
+function throwIfProxyAuthIsSent (headers) {
+ const existProxyAuth = headers && Object.keys(headers)
+ .find((key) => key.toLowerCase() === 'proxy-authorization')
+ if (existProxyAuth) {
+ throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
}
}
-// https://fetch.spec.whatwg.org/#fetch-method
-function fetch (input, init = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' })
-
- // 1. Let p be a new promise.
- const p = createDeferredPromise()
-
- // 2. Let requestObject be the result of invoking the initial value of
- // Request as constructor with input and init as arguments. If this throws
- // an exception, reject p with it and return p.
- let requestObject
-
- try {
- requestObject = new Request(input, init)
- } catch (e) {
- p.reject(e)
- return p.promise
- }
+module.exports = ProxyAgent
- // 3. Let request be requestObject’s request.
- const request = requestObject[kState]
- // 4. If requestObject’s signal’s aborted flag is set, then:
- if (requestObject.signal.aborted) {
- // 1. Abort the fetch() call with p, request, null, and
- // requestObject’s signal’s abort reason.
- abortFetch(p, request, null, requestObject.signal.reason)
+/***/ }),
- // 2. Return p.
- return p.promise
- }
+/***/ 82576:
+/***/ ((module) => {
- // 5. Let globalObject be request’s client’s global object.
- const globalObject = request.client.globalObject
- // 6. If globalObject is a ServiceWorkerGlobalScope object, then set
- // request’s service-workers mode to "none".
- if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') {
- request.serviceWorkers = 'none'
- }
- // 7. Let responseObject be null.
- let responseObject = null
+let fastNow = Date.now()
+let fastNowTimeout
- // 8. Let relevantRealm be this’s relevant Realm.
- const relevantRealm = null
+const fastTimers = []
- // 9. Let locallyAborted be false.
- let locallyAborted = false
+function onTimeout () {
+ fastNow = Date.now()
- // 10. Let controller be null.
- let controller = null
+ let len = fastTimers.length
+ let idx = 0
+ while (idx < len) {
+ const timer = fastTimers[idx]
- // 11. Add the following abort steps to requestObject’s signal:
- addAbortListener(
- requestObject.signal,
- () => {
- // 1. Set locallyAborted to true.
- locallyAborted = true
+ if (timer.state === 0) {
+ timer.state = fastNow + timer.delay
+ } else if (timer.state > 0 && fastNow >= timer.state) {
+ timer.state = -1
+ timer.callback(timer.opaque)
+ }
- // 2. Assert: controller is non-null.
- assert(controller != null)
+ if (timer.state === -1) {
+ timer.state = -2
+ if (idx !== len - 1) {
+ fastTimers[idx] = fastTimers.pop()
+ } else {
+ fastTimers.pop()
+ }
+ len -= 1
+ } else {
+ idx += 1
+ }
+ }
- // 3. Abort controller with requestObject’s signal’s abort reason.
- controller.abort(requestObject.signal.reason)
+ if (fastTimers.length > 0) {
+ refreshTimeout()
+ }
+}
- // 4. Abort the fetch() call with p, request, responseObject,
- // and requestObject’s signal’s abort reason.
- abortFetch(p, request, responseObject, requestObject.signal.reason)
+function refreshTimeout () {
+ if (fastNowTimeout && fastNowTimeout.refresh) {
+ fastNowTimeout.refresh()
+ } else {
+ clearTimeout(fastNowTimeout)
+ fastNowTimeout = setTimeout(onTimeout, 1e3)
+ if (fastNowTimeout.unref) {
+ fastNowTimeout.unref()
}
- )
+ }
+}
- // 12. Let handleFetchDone given response response be to finalize and
- // report timing with response, globalObject, and "fetch".
- const handleFetchDone = (response) =>
- finalizeAndReportTiming(response, 'fetch')
+class Timeout {
+ constructor (callback, delay, opaque) {
+ this.callback = callback
+ this.delay = delay
+ this.opaque = opaque
- // 13. Set controller to the result of calling fetch given request,
- // with processResponseEndOfBody set to handleFetchDone, and processResponse
- // given response being these substeps:
+ // -2 not in timer list
+ // -1 in timer list but inactive
+ // 0 in timer list waiting for time
+ // > 0 in timer list waiting for time to expire
+ this.state = -2
- const processResponse = (response) => {
- // 1. If locallyAborted is true, terminate these substeps.
- if (locallyAborted) {
- return Promise.resolve()
+ this.refresh()
+ }
+
+ refresh () {
+ if (this.state === -2) {
+ fastTimers.push(this)
+ if (!fastNowTimeout || fastTimers.length === 1) {
+ refreshTimeout()
+ }
}
- // 2. If response’s aborted flag is set, then:
- if (response.aborted) {
- // 1. Let deserializedError be the result of deserialize a serialized
- // abort reason given controller’s serialized abort reason and
- // relevantRealm.
+ this.state = 0
+ }
- // 2. Abort the fetch() call with p, request, responseObject, and
- // deserializedError.
+ clear () {
+ this.state = -1
+ }
+}
- abortFetch(p, request, responseObject, controller.serializedAbortReason)
- return Promise.resolve()
+module.exports = {
+ setTimeout (callback, delay, opaque) {
+ return delay < 1e3
+ ? setTimeout(callback, delay, opaque)
+ : new Timeout(callback, delay, opaque)
+ },
+ clearTimeout (timeout) {
+ if (timeout instanceof Timeout) {
+ timeout.clear()
+ } else {
+ clearTimeout(timeout)
}
+ }
+}
- // 3. If response is a network error, then reject p with a TypeError
- // and terminate these substeps.
- if (response.type === 'error') {
- p.reject(
- Object.assign(new TypeError('fetch failed'), { cause: response.error })
- )
- return Promise.resolve()
- }
- // 4. Set responseObject to the result of creating a Response object,
- // given response, "immutable", and relevantRealm.
- responseObject = new Response()
- responseObject[kState] = response
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kHeadersList] = response.headersList
- responseObject[kHeaders][kGuard] = 'immutable'
- responseObject[kHeaders][kRealm] = relevantRealm
+/***/ }),
- // 5. Resolve p with responseObject.
- p.resolve(responseObject)
- }
+/***/ 96114:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- controller = fetching({
- request,
- processResponseEndOfBody: handleFetchDone,
- processResponse,
- dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici
- })
- // 14. Return p.
- return p.promise
-}
-// https://fetch.spec.whatwg.org/#finalize-and-report-timing
-function finalizeAndReportTiming (response, initiatorType = 'other') {
- // 1. If response is an aborted network error, then return.
- if (response.type === 'error' && response.aborted) {
- return
- }
+const diagnosticsChannel = __nccwpck_require__(31637)
+const { uid, states } = __nccwpck_require__(90077)
+const {
+ kReadyState,
+ kSentClose,
+ kByteParser,
+ kReceivedClose
+} = __nccwpck_require__(97945)
+const { fireEvent, failWebsocketConnection } = __nccwpck_require__(95506)
+const { CloseEvent } = __nccwpck_require__(47115)
+const { makeRequest } = __nccwpck_require__(2630)
+const { fetching } = __nccwpck_require__(11503)
+const { Headers } = __nccwpck_require__(12801)
+const { getGlobalDispatcher } = __nccwpck_require__(61481)
+const { kHeadersList } = __nccwpck_require__(68031)
- // 2. If response’s URL list is null or empty, then return.
- if (!response.urlList?.length) {
- return
- }
+const channels = {}
+channels.open = diagnosticsChannel.channel('undici:websocket:open')
+channels.close = diagnosticsChannel.channel('undici:websocket:close')
+channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')
- // 3. Let originalURL be response’s URL list[0].
- const originalURL = response.urlList[0]
+/** @type {import('crypto')} */
+let crypto
+try {
+ crypto = __nccwpck_require__(76982)
+} catch {
- // 4. Let timingInfo be response’s timing info.
- let timingInfo = response.timingInfo
+}
- // 5. Let cacheState be response’s cache state.
- let cacheState = response.cacheState
+/**
+ * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
+ * @param {URL} url
+ * @param {string|string[]} protocols
+ * @param {import('./websocket').WebSocket} ws
+ * @param {(response: any) => void} onEstablish
+ * @param {Partial} options
+ */
+function establishWebSocketConnection (url, protocols, ws, onEstablish, options) {
+ // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s
+ // scheme is "ws", and to "https" otherwise.
+ const requestURL = url
- // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return.
- if (!urlIsHttpHttpsScheme(originalURL)) {
- return
- }
+ requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
- // 7. If timingInfo is null, then return.
- if (timingInfo === null) {
- return
- }
+ // 2. Let request be a new request, whose URL is requestURL, client is client,
+ // service-workers mode is "none", referrer is "no-referrer", mode is
+ // "websocket", credentials mode is "include", cache mode is "no-store" ,
+ // and redirect mode is "error".
+ const request = makeRequest({
+ urlList: [requestURL],
+ serviceWorkers: 'none',
+ referrer: 'no-referrer',
+ mode: 'websocket',
+ credentials: 'include',
+ cache: 'no-store',
+ redirect: 'error'
+ })
- // 8. If response’s timing allow passed flag is not set, then:
- if (!response.timingAllowPassed) {
- // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo.
- timingInfo = createOpaqueTimingInfo({
- startTime: timingInfo.startTime
- })
+ // Note: undici extension, allow setting custom headers.
+ if (options.headers) {
+ const headersList = new Headers(options.headers)[kHeadersList]
- // 2. Set cacheState to the empty string.
- cacheState = ''
+ request.headersList = headersList
}
- // 9. Set timingInfo’s end time to the coarsened shared current time
- // given global’s relevant settings object’s cross-origin isolated
- // capability.
- // TODO: given global’s relevant settings object’s cross-origin isolated
- // capability?
- timingInfo.endTime = coarsenedSharedCurrentTime()
+ // 3. Append (`Upgrade`, `websocket`) to request’s header list.
+ // 4. Append (`Connection`, `Upgrade`) to request’s header list.
+ // Note: both of these are handled by undici currently.
+ // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
- // 10. Set response’s timing info to timingInfo.
- response.timingInfo = timingInfo
+ // 5. Let keyValue be a nonce consisting of a randomly selected
+ // 16-byte value that has been forgiving-base64-encoded and
+ // isomorphic encoded.
+ const keyValue = crypto.randomBytes(16).toString('base64')
- // 11. Mark resource timing for timingInfo, originalURL, initiatorType,
- // global, and cacheState.
- markResourceTiming(
- timingInfo,
- originalURL,
- initiatorType,
- globalThis,
- cacheState
- )
-}
+ // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
+ // header list.
+ request.headersList.append('sec-websocket-key', keyValue)
-// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing
-function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) {
- if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) {
- performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState)
- }
-}
+ // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
+ // header list.
+ request.headersList.append('sec-websocket-version', '13')
-// https://fetch.spec.whatwg.org/#abort-fetch
-function abortFetch (p, request, responseObject, error) {
- // Note: AbortSignal.reason was added in node v17.2.0
- // which would give us an undefined error to reject with.
- // Remove this once node v16 is no longer supported.
- if (!error) {
- error = new DOMException('The operation was aborted.', 'AbortError')
+ // 8. For each protocol in protocols, combine
+ // (`Sec-WebSocket-Protocol`, protocol) in request’s header
+ // list.
+ for (const protocol of protocols) {
+ request.headersList.append('sec-websocket-protocol', protocol)
}
- // 1. Reject promise with error.
- p.reject(error)
+ // 9. Let permessageDeflate be a user-agent defined
+ // "permessage-deflate" extension header value.
+ // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
+ // TODO: enable once permessage-deflate is supported
+ const permessageDeflate = '' // 'permessage-deflate; 15'
- // 2. If request’s body is not null and is readable, then cancel request’s
- // body with error.
- if (request.body != null && isReadable(request.body?.stream)) {
- request.body.stream.cancel(error).catch((err) => {
- if (err.code === 'ERR_INVALID_STATE') {
- // Node bug?
+ // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
+ // request’s header list.
+ // request.headersList.append('sec-websocket-extensions', permessageDeflate)
+
+ // 11. Fetch request with useParallelQueue set to true, and
+ // processResponse given response being these steps:
+ const controller = fetching({
+ request,
+ useParallelQueue: true,
+ dispatcher: options.dispatcher ?? getGlobalDispatcher(),
+ processResponse (response) {
+ // 1. If response is a network error or its status is not 101,
+ // fail the WebSocket connection.
+ if (response.type === 'error' || response.status !== 101) {
+ failWebsocketConnection(ws, 'Received network error or non-101 status code.')
return
}
- throw err
- })
- }
- // 3. If responseObject is null, then return.
- if (responseObject == null) {
- return
- }
+ // 2. If protocols is not the empty list and extracting header
+ // list values given `Sec-WebSocket-Protocol` and response’s
+ // header list results in null, failure, or the empty byte
+ // sequence, then fail the WebSocket connection.
+ if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
+ failWebsocketConnection(ws, 'Server did not respond with sent protocols.')
+ return
+ }
- // 4. Let response be responseObject’s response.
- const response = responseObject[kState]
+ // 3. Follow the requirements stated step 2 to step 6, inclusive,
+ // of the last set of steps in section 4.1 of The WebSocket
+ // Protocol to validate response. This either results in fail
+ // the WebSocket connection or the WebSocket connection is
+ // established.
- // 5. If response’s body is not null and is readable, then error response’s
- // body with error.
- if (response.body != null && isReadable(response.body?.stream)) {
- response.body.stream.cancel(error).catch((err) => {
- if (err.code === 'ERR_INVALID_STATE') {
- // Node bug?
+ // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
+ // header field contains a value that is not an ASCII case-
+ // insensitive match for the value "websocket", the client MUST
+ // _Fail the WebSocket Connection_.
+ if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
+ failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".')
return
}
- throw err
- })
- }
-}
-// https://fetch.spec.whatwg.org/#fetching
-function fetching ({
- request,
- processRequestBodyChunkLength,
- processRequestEndOfBody,
- processResponse,
- processResponseEndOfBody,
- processResponseConsumeBody,
- useParallelQueue = false,
- dispatcher // undici
-}) {
- // 1. Let taskDestination be null.
- let taskDestination = null
+ // 3. If the response lacks a |Connection| header field or the
+ // |Connection| header field doesn't contain a token that is an
+ // ASCII case-insensitive match for the value "Upgrade", the client
+ // MUST _Fail the WebSocket Connection_.
+ if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
+ failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".')
+ return
+ }
- // 2. Let crossOriginIsolatedCapability be false.
- let crossOriginIsolatedCapability = false
+ // 4. If the response lacks a |Sec-WebSocket-Accept| header field or
+ // the |Sec-WebSocket-Accept| contains a value other than the
+ // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
+ // Key| (as a string, not base64-decoded) with the string "258EAFA5-
+ // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
+ // trailing whitespace, the client MUST _Fail the WebSocket
+ // Connection_.
+ const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
+ const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
+ if (secWSAccept !== digest) {
+ failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
+ return
+ }
- // 3. If request’s client is non-null, then:
- if (request.client != null) {
- // 1. Set taskDestination to request’s client’s global object.
- taskDestination = request.client.globalObject
+ // 5. If the response includes a |Sec-WebSocket-Extensions| header
+ // field and this header field indicates the use of an extension
+ // that was not present in the client's handshake (the server has
+ // indicated an extension not requested by the client), the client
+ // MUST _Fail the WebSocket Connection_. (The parsing of this
+ // header field to determine which extensions are requested is
+ // discussed in Section 9.1.)
+ const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
- // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin
- // isolated capability.
- crossOriginIsolatedCapability =
- request.client.crossOriginIsolatedCapability
- }
+ if (secExtension !== null && secExtension !== permessageDeflate) {
+ failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')
+ return
+ }
- // 4. If useParallelQueue is true, then set taskDestination to the result of
- // starting a new parallel queue.
- // TODO
+ // 6. If the response includes a |Sec-WebSocket-Protocol| header field
+ // and this header field indicates the use of a subprotocol that was
+ // not present in the client's handshake (the server has indicated a
+ // subprotocol not requested by the client), the client MUST _Fail
+ // the WebSocket Connection_.
+ const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
- // 5. Let timingInfo be a new fetch timing info whose start time and
- // post-redirect start time are the coarsened shared current time given
- // crossOriginIsolatedCapability.
- const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability)
- const timingInfo = createOpaqueTimingInfo({
- startTime: currenTime
+ if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {
+ failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
+ return
+ }
+
+ response.socket.on('data', onSocketData)
+ response.socket.on('close', onSocketClose)
+ response.socket.on('error', onSocketError)
+
+ if (channels.open.hasSubscribers) {
+ channels.open.publish({
+ address: response.socket.address(),
+ protocol: secProtocol,
+ extensions: secExtension
+ })
+ }
+
+ onEstablish(response)
+ }
})
- // 6. Let fetchParams be a new fetch params whose
- // request is request,
- // timing info is timingInfo,
- // process request body chunk length is processRequestBodyChunkLength,
- // process request end-of-body is processRequestEndOfBody,
- // process response is processResponse,
- // process response consume body is processResponseConsumeBody,
- // process response end-of-body is processResponseEndOfBody,
- // task destination is taskDestination,
- // and cross-origin isolated capability is crossOriginIsolatedCapability.
- const fetchParams = {
- controller: new Fetch(dispatcher),
- request,
- timingInfo,
- processRequestBodyChunkLength,
- processRequestEndOfBody,
- processResponse,
- processResponseConsumeBody,
- processResponseEndOfBody,
- taskDestination,
- crossOriginIsolatedCapability
+ return controller
+}
+
+/**
+ * @param {Buffer} chunk
+ */
+function onSocketData (chunk) {
+ if (!this.ws[kByteParser].write(chunk)) {
+ this.pause()
}
+}
- // 7. If request’s body is a byte sequence, then set request’s body to
- // request’s body as a body.
- // NOTE: Since fetching is only called from fetch, body should already be
- // extracted.
- assert(!request.body || request.body.stream)
+/**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
+ */
+function onSocketClose () {
+ const { ws } = this
- // 8. If request’s window is "client", then set request’s window to request’s
- // client, if request’s client’s global object is a Window object; otherwise
- // "no-window".
- if (request.window === 'client') {
- // TODO: What if request.client is null?
- request.window =
- request.client?.globalObject?.constructor?.name === 'Window'
- ? request.client
- : 'no-window'
- }
+ // If the TCP connection was closed after the
+ // WebSocket closing handshake was completed, the WebSocket connection
+ // is said to have been closed _cleanly_.
+ const wasClean = ws[kSentClose] && ws[kReceivedClose]
- // 9. If request’s origin is "client", then set request’s origin to request’s
- // client’s origin.
- if (request.origin === 'client') {
- // TODO: What if request.client is null?
- request.origin = request.client?.origin
- }
+ let code = 1005
+ let reason = ''
- // 10. If all of the following conditions are true:
- // TODO
+ const result = ws[kByteParser].closingInfo
- // 11. If request’s policy container is "client", then:
- if (request.policyContainer === 'client') {
- // 1. If request’s client is non-null, then set request’s policy
- // container to a clone of request’s client’s policy container. [HTML]
- if (request.client != null) {
- request.policyContainer = clonePolicyContainer(
- request.client.policyContainer
- )
- } else {
- // 2. Otherwise, set request’s policy container to a new policy
- // container.
- request.policyContainer = makePolicyContainer()
- }
+ if (result) {
+ code = result.code ?? 1005
+ reason = result.reason
+ } else if (!ws[kSentClose]) {
+ // If _The WebSocket
+ // Connection is Closed_ and no Close control frame was received by the
+ // endpoint (such as could occur if the underlying transport connection
+ // is lost), _The WebSocket Connection Close Code_ is considered to be
+ // 1006.
+ code = 1006
}
- // 12. If request’s header list does not contain `Accept`, then:
- if (!request.headersList.contains('accept')) {
- // 1. Let value be `*/*`.
- const value = '*/*'
+ // 1. Change the ready state to CLOSED (3).
+ ws[kReadyState] = states.CLOSED
- // 2. A user agent should set value to the first matching statement, if
- // any, switching on request’s destination:
- // "document"
- // "frame"
- // "iframe"
- // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8`
- // "image"
- // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5`
- // "style"
- // `text/css,*/*;q=0.1`
- // TODO
+ // 2. If the user agent was required to fail the WebSocket
+ // connection, or if the WebSocket connection was closed
+ // after being flagged as full, fire an event named error
+ // at the WebSocket object.
+ // TODO
- // 3. Append `Accept`/value to request’s header list.
- request.headersList.append('accept', value)
- }
+ // 3. Fire an event named close at the WebSocket object,
+ // using CloseEvent, with the wasClean attribute
+ // initialized to true if the connection closed cleanly
+ // and false otherwise, the code attribute initialized to
+ // the WebSocket connection close code, and the reason
+ // attribute initialized to the result of applying UTF-8
+ // decode without BOM to the WebSocket connection close
+ // reason.
+ fireEvent('close', ws, CloseEvent, {
+ wasClean, code, reason
+ })
- // 13. If request’s header list does not contain `Accept-Language`, then
- // user agents should append `Accept-Language`/an appropriate value to
- // request’s header list.
- if (!request.headersList.contains('accept-language')) {
- request.headersList.append('accept-language', '*')
+ if (channels.close.hasSubscribers) {
+ channels.close.publish({
+ websocket: ws,
+ code,
+ reason
+ })
}
+}
- // 14. If request’s priority is null, then use request’s initiator and
- // destination appropriately in setting request’s priority to a
- // user-agent-defined object.
- if (request.priority === null) {
- // TODO
- }
+function onSocketError (error) {
+ const { ws } = this
- // 15. If request is a subresource request, then:
- if (subresourceSet.has(request.destination)) {
- // TODO
+ ws[kReadyState] = states.CLOSING
+
+ if (channels.socketError.hasSubscribers) {
+ channels.socketError.publish(error)
}
- // 16. Run main fetch given fetchParams.
- mainFetch(fetchParams)
- .catch(err => {
- fetchParams.controller.terminate(err)
- })
+ this.destroy()
+}
- // 17. Return fetchParam's controller
- return fetchParams.controller
+module.exports = {
+ establishWebSocketConnection
}
-// https://fetch.spec.whatwg.org/#concept-main-fetch
-async function mainFetch (fetchParams, recursive = false) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
- // 2. Let response be null.
- let response = null
+/***/ }),
- // 3. If request’s local-URLs-only flag is set and request’s current URL is
- // not local, then set response to a network error.
- if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) {
- response = makeNetworkError('local URLs only')
- }
+/***/ 90077:
+/***/ ((module) => {
- // 4. Run report Content Security Policy violations for request.
- // TODO
- // 5. Upgrade request to a potentially trustworthy URL, if appropriate.
- tryUpgradeRequestToAPotentiallyTrustworthyURL(request)
- // 6. If should request be blocked due to a bad port, should fetching request
- // be blocked as mixed content, or should request be blocked by Content
- // Security Policy returns blocked, then set response to a network error.
- if (requestBadPort(request) === 'blocked') {
- response = makeNetworkError('bad port')
- }
- // TODO: should fetching request be blocked as mixed content?
- // TODO: should request be blocked by Content Security Policy?
+// This is a Globally Unique Identifier unique used
+// to validate that the endpoint accepts websocket
+// connections.
+// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3
+const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
- // 7. If request’s referrer policy is the empty string, then set request’s
- // referrer policy to request’s policy container’s referrer policy.
- if (request.referrerPolicy === '') {
- request.referrerPolicy = request.policyContainer.referrerPolicy
- }
+/** @type {PropertyDescriptor} */
+const staticPropertyDescriptors = {
+ enumerable: true,
+ writable: false,
+ configurable: false
+}
- // 8. If request’s referrer is not "no-referrer", then set request’s
- // referrer to the result of invoking determine request’s referrer.
- if (request.referrer !== 'no-referrer') {
- request.referrer = determineRequestsReferrer(request)
- }
+const states = {
+ CONNECTING: 0,
+ OPEN: 1,
+ CLOSING: 2,
+ CLOSED: 3
+}
- // 9. Set request’s current URL’s scheme to "https" if all of the following
- // conditions are true:
- // - request’s current URL’s scheme is "http"
- // - request’s current URL’s host is a domain
- // - Matching request’s current URL’s host per Known HSTS Host Domain Name
- // Matching results in either a superdomain match with an asserted
- // includeSubDomains directive or a congruent match (with or without an
- // asserted includeSubDomains directive). [HSTS]
- // TODO
+const opcodes = {
+ CONTINUATION: 0x0,
+ TEXT: 0x1,
+ BINARY: 0x2,
+ CLOSE: 0x8,
+ PING: 0x9,
+ PONG: 0xA
+}
- // 10. If recursive is false, then run the remaining steps in parallel.
- // TODO
+const maxUnsigned16Bit = 2 ** 16 - 1 // 65535
- // 11. If response is null, then set response to the result of running
- // the steps corresponding to the first matching statement:
- if (response === null) {
- response = await (async () => {
- const currentURL = requestCurrentURL(request)
+const parserStates = {
+ INFO: 0,
+ PAYLOADLENGTH_16: 2,
+ PAYLOADLENGTH_64: 3,
+ READ_DATA: 4
+}
- if (
- // - request’s current URL’s origin is same origin with request’s origin,
- // and request’s response tainting is "basic"
- (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') ||
- // request’s current URL’s scheme is "data"
- (currentURL.protocol === 'data:') ||
- // - request’s mode is "navigate" or "websocket"
- (request.mode === 'navigate' || request.mode === 'websocket')
- ) {
- // 1. Set request’s response tainting to "basic".
- request.responseTainting = 'basic'
+const emptyBuffer = Buffer.allocUnsafe(0)
- // 2. Return the result of running scheme fetch given fetchParams.
- return await schemeFetch(fetchParams)
- }
+module.exports = {
+ uid,
+ staticPropertyDescriptors,
+ states,
+ opcodes,
+ maxUnsigned16Bit,
+ parserStates,
+ emptyBuffer
+}
- // request’s mode is "same-origin"
- if (request.mode === 'same-origin') {
- // 1. Return a network error.
- return makeNetworkError('request mode cannot be "same-origin"')
- }
- // request’s mode is "no-cors"
- if (request.mode === 'no-cors') {
- // 1. If request’s redirect mode is not "follow", then return a network
- // error.
- if (request.redirect !== 'follow') {
- return makeNetworkError(
- 'redirect mode cannot be "follow" for "no-cors" request'
- )
- }
+/***/ }),
- // 2. Set request’s response tainting to "opaque".
- request.responseTainting = 'opaque'
+/***/ 47115:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 3. Return the result of running scheme fetch given fetchParams.
- return await schemeFetch(fetchParams)
- }
- // request’s current URL’s scheme is not an HTTP(S) scheme
- if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) {
- // Return a network error.
- return makeNetworkError('URL scheme must be a HTTP(S) scheme')
- }
- // - request’s use-CORS-preflight flag is set
- // - request’s unsafe-request flag is set and either request’s method is
- // not a CORS-safelisted method or CORS-unsafe request-header names with
- // request’s header list is not empty
- // 1. Set request’s response tainting to "cors".
- // 2. Let corsWithPreflightResponse be the result of running HTTP fetch
- // given fetchParams and true.
- // 3. If corsWithPreflightResponse is a network error, then clear cache
- // entries using request.
- // 4. Return corsWithPreflightResponse.
- // TODO
+const { webidl } = __nccwpck_require__(94354)
+const { kEnumerableProperty } = __nccwpck_require__(89500)
+const { MessagePort } = __nccwpck_require__(28167)
- // Otherwise
- // 1. Set request’s response tainting to "cors".
- request.responseTainting = 'cors'
+/**
+ * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
+ */
+class MessageEvent extends Event {
+ #eventInit
- // 2. Return the result of running HTTP fetch given fetchParams.
- return await httpFetch(fetchParams)
- })()
- }
+ constructor (type, eventInitDict = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' })
- // 12. If recursive is true, then return response.
- if (recursive) {
- return response
- }
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.MessageEventInit(eventInitDict)
- // 13. If response is not a network error and response is not a filtered
- // response, then:
- if (response.status !== 0 && !response.internalResponse) {
- // If request’s response tainting is "cors", then:
- if (request.responseTainting === 'cors') {
- // 1. Let headerNames be the result of extracting header list values
- // given `Access-Control-Expose-Headers` and response’s header list.
- // TODO
- // 2. If request’s credentials mode is not "include" and headerNames
- // contains `*`, then set response’s CORS-exposed header-name list to
- // all unique header names in response’s header list.
- // TODO
- // 3. Otherwise, if headerNames is not null or failure, then set
- // response’s CORS-exposed header-name list to headerNames.
- // TODO
- }
+ super(type, eventInitDict)
- // Set response to the following filtered response with response as its
- // internal response, depending on request’s response tainting:
- if (request.responseTainting === 'basic') {
- response = filterResponse(response, 'basic')
- } else if (request.responseTainting === 'cors') {
- response = filterResponse(response, 'cors')
- } else if (request.responseTainting === 'opaque') {
- response = filterResponse(response, 'opaque')
- } else {
- assert(false)
- }
+ this.#eventInit = eventInitDict
}
- // 14. Let internalResponse be response, if response is a network error,
- // and response’s internal response otherwise.
- let internalResponse =
- response.status === 0 ? response : response.internalResponse
+ get data () {
+ webidl.brandCheck(this, MessageEvent)
- // 15. If internalResponse’s URL list is empty, then set it to a clone of
- // request’s URL list.
- if (internalResponse.urlList.length === 0) {
- internalResponse.urlList.push(...request.urlList)
+ return this.#eventInit.data
}
- // 16. If request’s timing allow failed flag is unset, then set
- // internalResponse’s timing allow passed flag.
- if (!request.timingAllowFailed) {
- response.timingAllowPassed = true
+ get origin () {
+ webidl.brandCheck(this, MessageEvent)
+
+ return this.#eventInit.origin
}
- // 17. If response is not a network error and any of the following returns
- // blocked
- // - should internalResponse to request be blocked as mixed content
- // - should internalResponse to request be blocked by Content Security Policy
- // - should internalResponse to request be blocked due to its MIME type
- // - should internalResponse to request be blocked due to nosniff
- // TODO
+ get lastEventId () {
+ webidl.brandCheck(this, MessageEvent)
- // 18. If response’s type is "opaque", internalResponse’s status is 206,
- // internalResponse’s range-requested flag is set, and request’s header
- // list does not contain `Range`, then set response and internalResponse
- // to a network error.
- if (
- response.type === 'opaque' &&
- internalResponse.status === 206 &&
- internalResponse.rangeRequested &&
- !request.headers.contains('range')
- ) {
- response = internalResponse = makeNetworkError()
+ return this.#eventInit.lastEventId
}
- // 19. If response is not a network error and either request’s method is
- // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status,
- // set internalResponse’s body to null and disregard any enqueuing toward
- // it (if any).
- if (
- response.status !== 0 &&
- (request.method === 'HEAD' ||
- request.method === 'CONNECT' ||
- nullBodyStatus.includes(internalResponse.status))
- ) {
- internalResponse.body = null
- fetchParams.controller.dump = true
+ get source () {
+ webidl.brandCheck(this, MessageEvent)
+
+ return this.#eventInit.source
}
- // 20. If request’s integrity metadata is not the empty string, then:
- if (request.integrity) {
- // 1. Let processBodyError be this step: run fetch finale given fetchParams
- // and a network error.
- const processBodyError = (reason) =>
- fetchFinale(fetchParams, makeNetworkError(reason))
+ get ports () {
+ webidl.brandCheck(this, MessageEvent)
- // 2. If request’s response tainting is "opaque", or response’s body is null,
- // then run processBodyError and abort these steps.
- if (request.responseTainting === 'opaque' || response.body == null) {
- processBodyError(response.error)
- return
+ if (!Object.isFrozen(this.#eventInit.ports)) {
+ Object.freeze(this.#eventInit.ports)
}
- // 3. Let processBody given bytes be these steps:
- const processBody = (bytes) => {
- // 1. If bytes do not match request’s integrity metadata,
- // then run processBodyError and abort these steps. [SRI]
- if (!bytesMatch(bytes, request.integrity)) {
- processBodyError('integrity mismatch')
- return
- }
+ return this.#eventInit.ports
+ }
- // 2. Set response’s body to bytes as a body.
- response.body = safelyExtractBody(bytes)[0]
+ initMessageEvent (
+ type,
+ bubbles = false,
+ cancelable = false,
+ data = null,
+ origin = '',
+ lastEventId = '',
+ source = null,
+ ports = []
+ ) {
+ webidl.brandCheck(this, MessageEvent)
- // 3. Run fetch finale given fetchParams and response.
- fetchFinale(fetchParams, response)
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' })
- // 4. Fully read response’s body given processBody and processBodyError.
- await fullyReadBody(response.body, processBody, processBodyError)
- } else {
- // 21. Otherwise, run fetch finale given fetchParams and response.
- fetchFinale(fetchParams, response)
+ return new MessageEvent(type, {
+ bubbles, cancelable, data, origin, lastEventId, source, ports
+ })
}
}
-// https://fetch.spec.whatwg.org/#concept-scheme-fetch
-// given a fetch params fetchParams
-function schemeFetch (fetchParams) {
- // Note: since the connection is destroyed on redirect, which sets fetchParams to a
- // cancelled state, we do not want this condition to trigger *unless* there have been
- // no redirects. See https://github.com/nodejs/undici/issues/1776
- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
- return Promise.resolve(makeAppropriateNetworkError(fetchParams))
- }
-
- // 2. Let request be fetchParams’s request.
- const { request } = fetchParams
-
- const { protocol: scheme } = requestCurrentURL(request)
-
- // 3. Switch on request’s current URL’s scheme and run the associated steps:
- switch (scheme) {
- case 'about:': {
- // If request’s current URL’s path is the string "blank", then return a new response
- // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) »,
- // and body is the empty byte sequence as a body.
+/**
+ * @see https://websockets.spec.whatwg.org/#the-closeevent-interface
+ */
+class CloseEvent extends Event {
+ #eventInit
- // Otherwise, return a network error.
- return Promise.resolve(makeNetworkError('about scheme is not supported'))
- }
- case 'blob:': {
- if (!resolveObjectURL) {
- resolveObjectURL = (__nccwpck_require__(20181).resolveObjectURL)
- }
+ constructor (type, eventInitDict = {}) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' })
- // 1. Let blobURLEntry be request’s current URL’s blob URL entry.
- const blobURLEntry = requestCurrentURL(request)
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.CloseEventInit(eventInitDict)
- // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56
- // Buffer.resolveObjectURL does not ignore URL queries.
- if (blobURLEntry.search.length !== 0) {
- return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.'))
- }
+ super(type, eventInitDict)
- const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString())
+ this.#eventInit = eventInitDict
+ }
- // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s
- // object is not a Blob object, then return a network error.
- if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) {
- return Promise.resolve(makeNetworkError('invalid method'))
- }
+ get wasClean () {
+ webidl.brandCheck(this, CloseEvent)
- // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object.
- const bodyWithType = safelyExtractBody(blobURLEntryObject)
+ return this.#eventInit.wasClean
+ }
- // 4. Let body be bodyWithType’s body.
- const body = bodyWithType[0]
+ get code () {
+ webidl.brandCheck(this, CloseEvent)
- // 5. Let length be body’s length, serialized and isomorphic encoded.
- const length = isomorphicEncode(`${body.length}`)
+ return this.#eventInit.code
+ }
- // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence.
- const type = bodyWithType[1] ?? ''
+ get reason () {
+ webidl.brandCheck(this, CloseEvent)
- // 7. Return a new response whose status message is `OK`, header list is
- // « (`Content-Length`, length), (`Content-Type`, type) », and body is body.
- const response = makeResponse({
- statusText: 'OK',
- headersList: [
- ['content-length', { name: 'Content-Length', value: length }],
- ['content-type', { name: 'Content-Type', value: type }]
- ]
- })
+ return this.#eventInit.reason
+ }
+}
- response.body = body
+// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
+class ErrorEvent extends Event {
+ #eventInit
- return Promise.resolve(response)
- }
- case 'data:': {
- // 1. Let dataURLStruct be the result of running the
- // data: URL processor on request’s current URL.
- const currentURL = requestCurrentURL(request)
- const dataURLStruct = dataURLProcessor(currentURL)
+ constructor (type, eventInitDict) {
+ webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' })
- // 2. If dataURLStruct is failure, then return a
- // network error.
- if (dataURLStruct === 'failure') {
- return Promise.resolve(makeNetworkError('failed to fetch the data URL'))
- }
+ super(type, eventInitDict)
- // 3. Let mimeType be dataURLStruct’s MIME type, serialized.
- const mimeType = serializeAMimeType(dataURLStruct.mimeType)
+ type = webidl.converters.DOMString(type)
+ eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})
- // 4. Return a response whose status message is `OK`,
- // header list is « (`Content-Type`, mimeType) »,
- // and body is dataURLStruct’s body as a body.
- return Promise.resolve(makeResponse({
- statusText: 'OK',
- headersList: [
- ['content-type', { name: 'Content-Type', value: mimeType }]
- ],
- body: safelyExtractBody(dataURLStruct.body)[0]
- }))
- }
- case 'file:': {
- // For now, unfortunate as it is, file URLs are left as an exercise for the reader.
- // When in doubt, return a network error.
- return Promise.resolve(makeNetworkError('not implemented... yet...'))
- }
- case 'http:':
- case 'https:': {
- // Return the result of running HTTP fetch given fetchParams.
+ this.#eventInit = eventInitDict
+ }
- return httpFetch(fetchParams)
- .catch((err) => makeNetworkError(err))
- }
- default: {
- return Promise.resolve(makeNetworkError('unknown scheme'))
- }
+ get message () {
+ webidl.brandCheck(this, ErrorEvent)
+
+ return this.#eventInit.message
}
-}
-// https://fetch.spec.whatwg.org/#finalize-response
-function finalizeResponse (fetchParams, response) {
- // 1. Set fetchParams’s request’s done flag.
- fetchParams.request.done = true
+ get filename () {
+ webidl.brandCheck(this, ErrorEvent)
- // 2, If fetchParams’s process response done is not null, then queue a fetch
- // task to run fetchParams’s process response done given response, with
- // fetchParams’s task destination.
- if (fetchParams.processResponseDone != null) {
- queueMicrotask(() => fetchParams.processResponseDone(response))
+ return this.#eventInit.filename
}
-}
-// https://fetch.spec.whatwg.org/#fetch-finale
-function fetchFinale (fetchParams, response) {
- // 1. If response is a network error, then:
- if (response.type === 'error') {
- // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ».
- response.urlList = [fetchParams.request.urlList[0]]
+ get lineno () {
+ webidl.brandCheck(this, ErrorEvent)
- // 2. Set response’s timing info to the result of creating an opaque timing
- // info for fetchParams’s timing info.
- response.timingInfo = createOpaqueTimingInfo({
- startTime: fetchParams.timingInfo.startTime
- })
+ return this.#eventInit.lineno
}
- // 2. Let processResponseEndOfBody be the following steps:
- const processResponseEndOfBody = () => {
- // 1. Set fetchParams’s request’s done flag.
- fetchParams.request.done = true
+ get colno () {
+ webidl.brandCheck(this, ErrorEvent)
- // If fetchParams’s process response end-of-body is not null,
- // then queue a fetch task to run fetchParams’s process response
- // end-of-body given response with fetchParams’s task destination.
- if (fetchParams.processResponseEndOfBody != null) {
- queueMicrotask(() => fetchParams.processResponseEndOfBody(response))
- }
+ return this.#eventInit.colno
}
- // 3. If fetchParams’s process response is non-null, then queue a fetch task
- // to run fetchParams’s process response given response, with fetchParams’s
- // task destination.
- if (fetchParams.processResponse != null) {
- queueMicrotask(() => fetchParams.processResponse(response))
+ get error () {
+ webidl.brandCheck(this, ErrorEvent)
+
+ return this.#eventInit.error
}
+}
- // 4. If response’s body is null, then run processResponseEndOfBody.
- if (response.body == null) {
- processResponseEndOfBody()
- } else {
- // 5. Otherwise:
+Object.defineProperties(MessageEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'MessageEvent',
+ configurable: true
+ },
+ data: kEnumerableProperty,
+ origin: kEnumerableProperty,
+ lastEventId: kEnumerableProperty,
+ source: kEnumerableProperty,
+ ports: kEnumerableProperty,
+ initMessageEvent: kEnumerableProperty
+})
- // 1. Let transformStream be a new a TransformStream.
+Object.defineProperties(CloseEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'CloseEvent',
+ configurable: true
+ },
+ reason: kEnumerableProperty,
+ code: kEnumerableProperty,
+ wasClean: kEnumerableProperty
+})
- // 2. Let identityTransformAlgorithm be an algorithm which, given chunk,
- // enqueues chunk in transformStream.
- const identityTransformAlgorithm = (chunk, controller) => {
- controller.enqueue(chunk)
- }
+Object.defineProperties(ErrorEvent.prototype, {
+ [Symbol.toStringTag]: {
+ value: 'ErrorEvent',
+ configurable: true
+ },
+ message: kEnumerableProperty,
+ filename: kEnumerableProperty,
+ lineno: kEnumerableProperty,
+ colno: kEnumerableProperty,
+ error: kEnumerableProperty
+})
- // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm
- // and flushAlgorithm set to processResponseEndOfBody.
- const transformStream = new TransformStream({
- start () {},
- transform: identityTransformAlgorithm,
- flush: processResponseEndOfBody
- }, {
- size () {
- return 1
- }
- }, {
- size () {
- return 1
- }
- })
+webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)
- // 4. Set response’s body to the result of piping response’s body through transformStream.
- response.body = { stream: response.body.stream.pipeThrough(transformStream) }
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.MessagePort
+)
+
+const eventInit = [
+ {
+ key: 'bubbles',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'cancelable',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'composed',
+ converter: webidl.converters.boolean,
+ defaultValue: false
}
+]
- // 6. If fetchParams’s process response consume body is non-null, then:
- if (fetchParams.processResponseConsumeBody != null) {
- // 1. Let processBody given nullOrBytes be this step: run fetchParams’s
- // process response consume body given response and nullOrBytes.
- const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes)
+webidl.converters.MessageEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: 'data',
+ converter: webidl.converters.any,
+ defaultValue: null
+ },
+ {
+ key: 'origin',
+ converter: webidl.converters.USVString,
+ defaultValue: ''
+ },
+ {
+ key: 'lastEventId',
+ converter: webidl.converters.DOMString,
+ defaultValue: ''
+ },
+ {
+ key: 'source',
+ // Node doesn't implement WindowProxy or ServiceWorker, so the only
+ // valid value for source is a MessagePort.
+ converter: webidl.nullableConverter(webidl.converters.MessagePort),
+ defaultValue: null
+ },
+ {
+ key: 'ports',
+ converter: webidl.converters['sequence'],
+ get defaultValue () {
+ return []
+ }
+ }
+])
- // 2. Let processBodyError be this step: run fetchParams’s process
- // response consume body given response and failure.
- const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure)
+webidl.converters.CloseEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: 'wasClean',
+ converter: webidl.converters.boolean,
+ defaultValue: false
+ },
+ {
+ key: 'code',
+ converter: webidl.converters['unsigned short'],
+ defaultValue: 0
+ },
+ {
+ key: 'reason',
+ converter: webidl.converters.USVString,
+ defaultValue: ''
+ }
+])
- // 3. If response’s body is null, then queue a fetch task to run processBody
- // given null, with fetchParams’s task destination.
- if (response.body == null) {
- queueMicrotask(() => processBody(null))
- } else {
- // 4. Otherwise, fully read response’s body given processBody, processBodyError,
- // and fetchParams’s task destination.
- return fullyReadBody(response.body, processBody, processBodyError)
- }
- return Promise.resolve()
+webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
+ ...eventInit,
+ {
+ key: 'message',
+ converter: webidl.converters.DOMString,
+ defaultValue: ''
+ },
+ {
+ key: 'filename',
+ converter: webidl.converters.USVString,
+ defaultValue: ''
+ },
+ {
+ key: 'lineno',
+ converter: webidl.converters['unsigned long'],
+ defaultValue: 0
+ },
+ {
+ key: 'colno',
+ converter: webidl.converters['unsigned long'],
+ defaultValue: 0
+ },
+ {
+ key: 'error',
+ converter: webidl.converters.any
}
+])
+
+module.exports = {
+ MessageEvent,
+ CloseEvent,
+ ErrorEvent
}
-// https://fetch.spec.whatwg.org/#http-fetch
-async function httpFetch (fetchParams) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
- // 2. Let response be null.
- let response = null
+/***/ }),
- // 3. Let actualResponse be null.
- let actualResponse = null
+/***/ 42697:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 4. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
- // 5. If request’s service-workers mode is "all", then:
- if (request.serviceWorkers === 'all') {
- // TODO
+
+const { maxUnsigned16Bit } = __nccwpck_require__(90077)
+
+/** @type {import('crypto')} */
+let crypto
+try {
+ crypto = __nccwpck_require__(76982)
+} catch {
+
+}
+
+class WebsocketFrameSend {
+ /**
+ * @param {Buffer|undefined} data
+ */
+ constructor (data) {
+ this.frameData = data
+ this.maskKey = crypto.randomBytes(4)
}
- // 6. If response is null, then:
- if (response === null) {
- // 1. If makeCORSPreflight is true and one of these conditions is true:
- // TODO
+ createFrame (opcode) {
+ const bodyLength = this.frameData?.byteLength ?? 0
- // 2. If request’s redirect mode is "follow", then set request’s
- // service-workers mode to "none".
- if (request.redirect === 'follow') {
- request.serviceWorkers = 'none'
+ /** @type {number} */
+ let payloadLength = bodyLength // 0-125
+ let offset = 6
+
+ if (bodyLength > maxUnsigned16Bit) {
+ offset += 8 // payload length is next 8 bytes
+ payloadLength = 127
+ } else if (bodyLength > 125) {
+ offset += 2 // payload length is next 2 bytes
+ payloadLength = 126
}
- // 3. Set response and actualResponse to the result of running
- // HTTP-network-or-cache fetch given fetchParams.
- actualResponse = response = await httpNetworkOrCacheFetch(fetchParams)
+ const buffer = Buffer.allocUnsafe(bodyLength + offset)
- // 4. If request’s response tainting is "cors" and a CORS check
- // for request and response returns failure, then return a network error.
- if (
- request.responseTainting === 'cors' &&
- corsCheck(request, response) === 'failure'
- ) {
- return makeNetworkError('cors failure')
- }
+ // Clear first 2 bytes, everything else is overwritten
+ buffer[0] = buffer[1] = 0
+ buffer[0] |= 0x80 // FIN
+ buffer[0] = (buffer[0] & 0xF0) + opcode // opcode
- // 5. If the TAO check for request and response returns failure, then set
- // request’s timing allow failed flag.
- if (TAOCheck(request, response) === 'failure') {
- request.timingAllowFailed = true
- }
- }
+ /*! ws. MIT License. Einar Otto Stangvik */
+ buffer[offset - 4] = this.maskKey[0]
+ buffer[offset - 3] = this.maskKey[1]
+ buffer[offset - 2] = this.maskKey[2]
+ buffer[offset - 1] = this.maskKey[3]
- // 7. If either request’s response tainting or response’s type
- // is "opaque", and the cross-origin resource policy check with
- // request’s origin, request’s client, request’s destination,
- // and actualResponse returns blocked, then return a network error.
- if (
- (request.responseTainting === 'opaque' || response.type === 'opaque') &&
- crossOriginResourcePolicyCheck(
- request.origin,
- request.client,
- request.destination,
- actualResponse
- ) === 'blocked'
- ) {
- return makeNetworkError('blocked')
- }
+ buffer[1] = payloadLength
- // 8. If actualResponse’s status is a redirect status, then:
- if (redirectStatusSet.has(actualResponse.status)) {
- // 1. If actualResponse’s status is not 303, request’s body is not null,
- // and the connection uses HTTP/2, then user agents may, and are even
- // encouraged to, transmit an RST_STREAM frame.
- // See, https://github.com/whatwg/fetch/issues/1288
- if (request.redirect !== 'manual') {
- fetchParams.controller.connection.destroy()
+ if (payloadLength === 126) {
+ buffer.writeUInt16BE(bodyLength, 2)
+ } else if (payloadLength === 127) {
+ // Clear extended payload length
+ buffer[2] = buffer[3] = 0
+ buffer.writeUIntBE(bodyLength, 4, 6)
}
- // 2. Switch on request’s redirect mode:
- if (request.redirect === 'error') {
- // Set response to a network error.
- response = makeNetworkError('unexpected redirect')
- } else if (request.redirect === 'manual') {
- // Set response to an opaque-redirect filtered response whose internal
- // response is actualResponse.
- // NOTE(spec): On the web this would return an `opaqueredirect` response,
- // but that doesn't make sense server side.
- // See https://github.com/nodejs/undici/issues/1193.
- response = actualResponse
- } else if (request.redirect === 'follow') {
- // Set response to the result of running HTTP-redirect fetch given
- // fetchParams and response.
- response = await httpRedirectFetch(fetchParams, response)
- } else {
- assert(false)
+ buffer[1] |= 0x80 // MASK
+
+ // mask body
+ for (let i = 0; i < bodyLength; i++) {
+ buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]
}
- }
- // 9. Set response’s timing info to timingInfo.
- response.timingInfo = timingInfo
+ return buffer
+ }
+}
- // 10. Return response.
- return response
+module.exports = {
+ WebsocketFrameSend
}
-// https://fetch.spec.whatwg.org/#http-redirect-fetch
-function httpRedirectFetch (fetchParams, response) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
- // 2. Let actualResponse be response, if response is not a filtered response,
- // and response’s internal response otherwise.
- const actualResponse = response.internalResponse
- ? response.internalResponse
- : response
+/***/ }),
- // 3. Let locationURL be actualResponse’s location URL given request’s current
- // URL’s fragment.
- let locationURL
+/***/ 13607:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- try {
- locationURL = responseLocationURL(
- actualResponse,
- requestCurrentURL(request).hash
- )
- // 4. If locationURL is null, then return response.
- if (locationURL == null) {
- return response
- }
- } catch (err) {
- // 5. If locationURL is failure, then return a network error.
- return Promise.resolve(makeNetworkError(err))
- }
- // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network
- // error.
- if (!urlIsHttpHttpsScheme(locationURL)) {
- return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme'))
- }
+const { Writable } = __nccwpck_require__(2203)
+const diagnosticsChannel = __nccwpck_require__(31637)
+const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(90077)
+const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(97945)
+const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(95506)
+const { WebsocketFrameSend } = __nccwpck_require__(42697)
+
+// This code was influenced by ws released under the MIT license.
+// Copyright (c) 2011 Einar Otto Stangvik
+// Copyright (c) 2013 Arnout Kazemier and contributors
+// Copyright (c) 2016 Luigi Pinca and contributors
+
+const channels = {}
+channels.ping = diagnosticsChannel.channel('undici:websocket:ping')
+channels.pong = diagnosticsChannel.channel('undici:websocket:pong')
- // 7. If request’s redirect count is 20, then return a network error.
- if (request.redirectCount === 20) {
- return Promise.resolve(makeNetworkError('redirect count exceeded'))
- }
+class ByteParser extends Writable {
+ #buffers = []
+ #byteOffset = 0
- // 8. Increase request’s redirect count by 1.
- request.redirectCount += 1
+ #state = parserStates.INFO
- // 9. If request’s mode is "cors", locationURL includes credentials, and
- // request’s origin is not same origin with locationURL’s origin, then return
- // a network error.
- if (
- request.mode === 'cors' &&
- (locationURL.username || locationURL.password) &&
- !sameOrigin(request, locationURL)
- ) {
- return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'))
- }
+ #info = {}
+ #fragments = []
- // 10. If request’s response tainting is "cors" and locationURL includes
- // credentials, then return a network error.
- if (
- request.responseTainting === 'cors' &&
- (locationURL.username || locationURL.password)
- ) {
- return Promise.resolve(makeNetworkError(
- 'URL cannot contain credentials for request mode "cors"'
- ))
- }
+ constructor (ws) {
+ super()
- // 11. If actualResponse’s status is not 303, request’s body is non-null,
- // and request’s body’s source is null, then return a network error.
- if (
- actualResponse.status !== 303 &&
- request.body != null &&
- request.body.source == null
- ) {
- return Promise.resolve(makeNetworkError())
+ this.ws = ws
}
- // 12. If one of the following is true
- // - actualResponse’s status is 301 or 302 and request’s method is `POST`
- // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD`
- if (
- ([301, 302].includes(actualResponse.status) && request.method === 'POST') ||
- (actualResponse.status === 303 &&
- !GET_OR_HEAD.includes(request.method))
- ) {
- // then:
- // 1. Set request’s method to `GET` and request’s body to null.
- request.method = 'GET'
- request.body = null
+ /**
+ * @param {Buffer} chunk
+ * @param {() => void} callback
+ */
+ _write (chunk, _, callback) {
+ this.#buffers.push(chunk)
+ this.#byteOffset += chunk.length
- // 2. For each headerName of request-body-header name, delete headerName from
- // request’s header list.
- for (const headerName of requestBodyHeader) {
- request.headersList.delete(headerName)
- }
+ this.run(callback)
}
- // 13. If request’s current URL’s origin is not same origin with locationURL’s
- // origin, then for each headerName of CORS non-wildcard request-header name,
- // delete headerName from request’s header list.
- if (!sameOrigin(requestCurrentURL(request), locationURL)) {
- // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name
- request.headersList.delete('authorization')
+ /**
+ * Runs whenever a new chunk is received.
+ * Callback is called whenever there are no more chunks buffering,
+ * or not enough bytes are buffered to parse.
+ */
+ run (callback) {
+ while (true) {
+ if (this.#state === parserStates.INFO) {
+ // If there aren't enough bytes to parse the payload length, etc.
+ if (this.#byteOffset < 2) {
+ return callback()
+ }
- // https://fetch.spec.whatwg.org/#authentication-entries
- request.headersList.delete('proxy-authorization', true)
+ const buffer = this.consume(2)
- // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement.
- request.headersList.delete('cookie')
- request.headersList.delete('host')
- }
+ this.#info.fin = (buffer[0] & 0x80) !== 0
+ this.#info.opcode = buffer[0] & 0x0F
- // 14. If request’s body is non-null, then set request’s body to the first return
- // value of safely extracting request’s body’s source.
- if (request.body != null) {
- assert(request.body.source != null)
- request.body = safelyExtractBody(request.body.source)[0]
- }
+ // If we receive a fragmented message, we use the type of the first
+ // frame to parse the full message as binary/text, when it's terminated
+ this.#info.originalOpcode ??= this.#info.opcode
- // 15. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
+ this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION
- // 16. Set timingInfo’s redirect end time and post-redirect start time to the
- // coarsened shared current time given fetchParams’s cross-origin isolated
- // capability.
- timingInfo.redirectEndTime = timingInfo.postRedirectStartTime =
- coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability)
+ if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) {
+ // Only text and binary frames can be fragmented
+ failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')
+ return
+ }
- // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s
- // redirect start time to timingInfo’s start time.
- if (timingInfo.redirectStartTime === 0) {
- timingInfo.redirectStartTime = timingInfo.startTime
- }
+ const payloadLength = buffer[1] & 0x7F
- // 18. Append locationURL to request’s URL list.
- request.urlList.push(locationURL)
+ if (payloadLength <= 125) {
+ this.#info.payloadLength = payloadLength
+ this.#state = parserStates.READ_DATA
+ } else if (payloadLength === 126) {
+ this.#state = parserStates.PAYLOADLENGTH_16
+ } else if (payloadLength === 127) {
+ this.#state = parserStates.PAYLOADLENGTH_64
+ }
- // 19. Invoke set request’s referrer policy on redirect on request and
- // actualResponse.
- setRequestReferrerPolicyOnRedirect(request, actualResponse)
+ if (this.#info.fragmented && payloadLength > 125) {
+ // A fragmented frame can't be fragmented itself
+ failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')
+ return
+ } else if (
+ (this.#info.opcode === opcodes.PING ||
+ this.#info.opcode === opcodes.PONG ||
+ this.#info.opcode === opcodes.CLOSE) &&
+ payloadLength > 125
+ ) {
+ // Control frames can have a payload length of 125 bytes MAX
+ failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.')
+ return
+ } else if (this.#info.opcode === opcodes.CLOSE) {
+ if (payloadLength === 1) {
+ failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')
+ return
+ }
- // 20. Return the result of running main fetch given fetchParams and true.
- return mainFetch(fetchParams, true)
-}
+ const body = this.consume(payloadLength)
-// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
-async function httpNetworkOrCacheFetch (
- fetchParams,
- isAuthenticationFetch = false,
- isNewConnectionFetch = false
-) {
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+ this.#info.closeInfo = this.parseCloseBody(false, body)
- // 2. Let httpFetchParams be null.
- let httpFetchParams = null
+ if (!this.ws[kSentClose]) {
+ // If an endpoint receives a Close frame and did not previously send a
+ // Close frame, the endpoint MUST send a Close frame in response. (When
+ // sending a Close frame in response, the endpoint typically echos the
+ // status code it received.)
+ const body = Buffer.allocUnsafe(2)
+ body.writeUInt16BE(this.#info.closeInfo.code, 0)
+ const closeFrame = new WebsocketFrameSend(body)
- // 3. Let httpRequest be null.
- let httpRequest = null
+ this.ws[kResponse].socket.write(
+ closeFrame.createFrame(opcodes.CLOSE),
+ (err) => {
+ if (!err) {
+ this.ws[kSentClose] = true
+ }
+ }
+ )
+ }
- // 4. Let response be null.
- let response = null
+ // Upon either sending or receiving a Close control frame, it is said
+ // that _The WebSocket Closing Handshake is Started_ and that the
+ // WebSocket connection is in the CLOSING state.
+ this.ws[kReadyState] = states.CLOSING
+ this.ws[kReceivedClose] = true
- // 5. Let storedResponse be null.
- // TODO: cache
+ this.end()
- // 6. Let httpCache be null.
- const httpCache = null
+ return
+ } else if (this.#info.opcode === opcodes.PING) {
+ // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
+ // response, unless it already received a Close frame.
+ // A Pong frame sent in response to a Ping frame must have identical
+ // "Application data"
- // 7. Let the revalidatingFlag be unset.
- const revalidatingFlag = false
+ const body = this.consume(payloadLength)
- // 8. Run these steps, but abort when the ongoing fetch is terminated:
+ if (!this.ws[kReceivedClose]) {
+ const frame = new WebsocketFrameSend(body)
- // 1. If request’s window is "no-window" and request’s redirect mode is
- // "error", then set httpFetchParams to fetchParams and httpRequest to
- // request.
- if (request.window === 'no-window' && request.redirect === 'error') {
- httpFetchParams = fetchParams
- httpRequest = request
- } else {
- // Otherwise:
+ this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))
- // 1. Set httpRequest to a clone of request.
- httpRequest = makeRequest(request)
+ if (channels.ping.hasSubscribers) {
+ channels.ping.publish({
+ payload: body
+ })
+ }
+ }
- // 2. Set httpFetchParams to a copy of fetchParams.
- httpFetchParams = { ...fetchParams }
+ this.#state = parserStates.INFO
- // 3. Set httpFetchParams’s request to httpRequest.
- httpFetchParams.request = httpRequest
- }
+ if (this.#byteOffset > 0) {
+ continue
+ } else {
+ callback()
+ return
+ }
+ } else if (this.#info.opcode === opcodes.PONG) {
+ // A Pong frame MAY be sent unsolicited. This serves as a
+ // unidirectional heartbeat. A response to an unsolicited Pong frame is
+ // not expected.
- // 3. Let includeCredentials be true if one of
- const includeCredentials =
- request.credentials === 'include' ||
- (request.credentials === 'same-origin' &&
- request.responseTainting === 'basic')
+ const body = this.consume(payloadLength)
- // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s
- // body is non-null; otherwise null.
- const contentLength = httpRequest.body ? httpRequest.body.length : null
+ if (channels.pong.hasSubscribers) {
+ channels.pong.publish({
+ payload: body
+ })
+ }
- // 5. Let contentLengthHeaderValue be null.
- let contentLengthHeaderValue = null
+ if (this.#byteOffset > 0) {
+ continue
+ } else {
+ callback()
+ return
+ }
+ }
+ } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
+ if (this.#byteOffset < 2) {
+ return callback()
+ }
- // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or
- // `PUT`, then set contentLengthHeaderValue to `0`.
- if (
- httpRequest.body == null &&
- ['POST', 'PUT'].includes(httpRequest.method)
- ) {
- contentLengthHeaderValue = '0'
- }
+ const buffer = this.consume(2)
- // 7. If contentLength is non-null, then set contentLengthHeaderValue to
- // contentLength, serialized and isomorphic encoded.
- if (contentLength != null) {
- contentLengthHeaderValue = isomorphicEncode(`${contentLength}`)
- }
+ this.#info.payloadLength = buffer.readUInt16BE(0)
+ this.#state = parserStates.READ_DATA
+ } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
+ if (this.#byteOffset < 8) {
+ return callback()
+ }
- // 8. If contentLengthHeaderValue is non-null, then append
- // `Content-Length`/contentLengthHeaderValue to httpRequest’s header
- // list.
- if (contentLengthHeaderValue != null) {
- httpRequest.headersList.append('content-length', contentLengthHeaderValue)
- }
+ const buffer = this.consume(8)
+ const upper = buffer.readUInt32BE(0)
- // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`,
- // contentLengthHeaderValue) to httpRequest’s header list.
+ // 2^31 is the maxinimum bytes an arraybuffer can contain
+ // on 32-bit systems. Although, on 64-bit systems, this is
+ // 2^53-1 bytes.
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length
+ // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275
+ // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e
+ if (upper > 2 ** 31 - 1) {
+ failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')
+ return
+ }
- // 10. If contentLength is non-null and httpRequest’s keepalive is true,
- // then:
- if (contentLength != null && httpRequest.keepalive) {
- // NOTE: keepalive is a noop outside of browser context.
- }
+ const lower = buffer.readUInt32BE(4)
- // 11. If httpRequest’s referrer is a URL, then append
- // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded,
- // to httpRequest’s header list.
- if (httpRequest.referrer instanceof URL) {
- httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href))
- }
+ this.#info.payloadLength = (upper << 8) + lower
+ this.#state = parserStates.READ_DATA
+ } else if (this.#state === parserStates.READ_DATA) {
+ if (this.#byteOffset < this.#info.payloadLength) {
+ // If there is still more data in this chunk that needs to be read
+ return callback()
+ } else if (this.#byteOffset >= this.#info.payloadLength) {
+ // If the server sent multiple frames in a single chunk
- // 12. Append a request `Origin` header for httpRequest.
- appendRequestOriginHeader(httpRequest)
+ const body = this.consume(this.#info.payloadLength)
- // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA]
- appendFetchMetadata(httpRequest)
+ this.#fragments.push(body)
- // 14. If httpRequest’s header list does not contain `User-Agent`, then
- // user agents should append `User-Agent`/default `User-Agent` value to
- // httpRequest’s header list.
- if (!httpRequest.headersList.contains('user-agent')) {
- httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node')
- }
+ // If the frame is unfragmented, or a fragmented frame was terminated,
+ // a message was received
+ if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) {
+ const fullMessage = Buffer.concat(this.#fragments)
- // 15. If httpRequest’s cache mode is "default" and httpRequest’s header
- // list contains `If-Modified-Since`, `If-None-Match`,
- // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set
- // httpRequest’s cache mode to "no-store".
- if (
- httpRequest.cache === 'default' &&
- (httpRequest.headersList.contains('if-modified-since') ||
- httpRequest.headersList.contains('if-none-match') ||
- httpRequest.headersList.contains('if-unmodified-since') ||
- httpRequest.headersList.contains('if-match') ||
- httpRequest.headersList.contains('if-range'))
- ) {
- httpRequest.cache = 'no-store'
- }
+ websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage)
- // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent
- // no-cache cache-control header modification flag is unset, and
- // httpRequest’s header list does not contain `Cache-Control`, then append
- // `Cache-Control`/`max-age=0` to httpRequest’s header list.
- if (
- httpRequest.cache === 'no-cache' &&
- !httpRequest.preventNoCacheCacheControlHeaderModification &&
- !httpRequest.headersList.contains('cache-control')
- ) {
- httpRequest.headersList.append('cache-control', 'max-age=0')
- }
+ this.#info = {}
+ this.#fragments.length = 0
+ }
- // 17. If httpRequest’s cache mode is "no-store" or "reload", then:
- if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') {
- // 1. If httpRequest’s header list does not contain `Pragma`, then append
- // `Pragma`/`no-cache` to httpRequest’s header list.
- if (!httpRequest.headersList.contains('pragma')) {
- httpRequest.headersList.append('pragma', 'no-cache')
- }
+ this.#state = parserStates.INFO
+ }
+ }
- // 2. If httpRequest’s header list does not contain `Cache-Control`,
- // then append `Cache-Control`/`no-cache` to httpRequest’s header list.
- if (!httpRequest.headersList.contains('cache-control')) {
- httpRequest.headersList.append('cache-control', 'no-cache')
+ if (this.#byteOffset > 0) {
+ continue
+ } else {
+ callback()
+ break
+ }
}
}
- // 18. If httpRequest’s header list contains `Range`, then append
- // `Accept-Encoding`/`identity` to httpRequest’s header list.
- if (httpRequest.headersList.contains('range')) {
- httpRequest.headersList.append('accept-encoding', 'identity')
- }
-
- // 19. Modify httpRequest’s header list per HTTP. Do not append a given
- // header if httpRequest’s header list contains that header’s name.
- // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129
- if (!httpRequest.headersList.contains('accept-encoding')) {
- if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) {
- httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate')
- } else {
- httpRequest.headersList.append('accept-encoding', 'gzip, deflate')
+ /**
+ * Take n bytes from the buffered Buffers
+ * @param {number} n
+ * @returns {Buffer|null}
+ */
+ consume (n) {
+ if (n > this.#byteOffset) {
+ return null
+ } else if (n === 0) {
+ return emptyBuffer
}
- }
- httpRequest.headersList.delete('host')
+ if (this.#buffers[0].length === n) {
+ this.#byteOffset -= this.#buffers[0].length
+ return this.#buffers.shift()
+ }
- // 20. If includeCredentials is true, then:
- if (includeCredentials) {
- // 1. If the user agent is not configured to block cookies for httpRequest
- // (see section 7 of [COOKIES]), then:
- // TODO: credentials
- // 2. If httpRequest’s header list does not contain `Authorization`, then:
- // TODO: credentials
- }
+ const buffer = Buffer.allocUnsafe(n)
+ let offset = 0
- // 21. If there’s a proxy-authentication entry, use it as appropriate.
- // TODO: proxy-authentication
+ while (offset !== n) {
+ const next = this.#buffers[0]
+ const { length } = next
- // 22. Set httpCache to the result of determining the HTTP cache
- // partition, given httpRequest.
- // TODO: cache
+ if (length + offset === n) {
+ buffer.set(this.#buffers.shift(), offset)
+ break
+ } else if (length + offset > n) {
+ buffer.set(next.subarray(0, n - offset), offset)
+ this.#buffers[0] = next.subarray(n - offset)
+ break
+ } else {
+ buffer.set(this.#buffers.shift(), offset)
+ offset += next.length
+ }
+ }
- // 23. If httpCache is null, then set httpRequest’s cache mode to
- // "no-store".
- if (httpCache == null) {
- httpRequest.cache = 'no-store'
- }
+ this.#byteOffset -= n
- // 24. If httpRequest’s cache mode is neither "no-store" nor "reload",
- // then:
- if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') {
- // TODO: cache
+ return buffer
}
- // 9. If aborted, then return the appropriate network error for fetchParams.
- // TODO
+ parseCloseBody (onlyCode, data) {
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
+ /** @type {number|undefined} */
+ let code
- // 10. If response is null, then:
- if (response == null) {
- // 1. If httpRequest’s cache mode is "only-if-cached", then return a
- // network error.
- if (httpRequest.mode === 'only-if-cached') {
- return makeNetworkError('only if cached')
+ if (data.length >= 2) {
+ // _The WebSocket Connection Close Code_ is
+ // defined as the status code (Section 7.4) contained in the first Close
+ // control frame received by the application
+ code = data.readUInt16BE(0)
}
- // 2. Let forwardResponse be the result of running HTTP-network fetch
- // given httpFetchParams, includeCredentials, and isNewConnectionFetch.
- const forwardResponse = await httpNetworkFetch(
- httpFetchParams,
- includeCredentials,
- isNewConnectionFetch
- )
-
- // 3. If httpRequest’s method is unsafe and forwardResponse’s status is
- // in the range 200 to 399, inclusive, invalidate appropriate stored
- // responses in httpCache, as per the "Invalidation" chapter of HTTP
- // Caching, and set storedResponse to null. [HTTP-CACHING]
- if (
- !safeMethodsSet.has(httpRequest.method) &&
- forwardResponse.status >= 200 &&
- forwardResponse.status <= 399
- ) {
- // TODO: cache
+ if (onlyCode) {
+ if (!isValidStatusCode(code)) {
+ return null
+ }
+
+ return { code }
}
- // 4. If the revalidatingFlag is set and forwardResponse’s status is 304,
- // then:
- if (revalidatingFlag && forwardResponse.status === 304) {
- // TODO: cache
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
+ /** @type {Buffer} */
+ let reason = data.subarray(2)
+
+ // Remove BOM
+ if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {
+ reason = reason.subarray(3)
}
- // 5. If response is null, then:
- if (response == null) {
- // 1. Set response to forwardResponse.
- response = forwardResponse
+ if (code !== undefined && !isValidStatusCode(code)) {
+ return null
+ }
- // 2. Store httpRequest and forwardResponse in httpCache, as per the
- // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING]
- // TODO: cache
+ try {
+ // TODO: optimize this
+ reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)
+ } catch {
+ return null
}
- }
- // 11. Set response’s URL list to a clone of httpRequest’s URL list.
- response.urlList = [...httpRequest.urlList]
+ return { code, reason }
+ }
- // 12. If httpRequest’s header list contains `Range`, then set response’s
- // range-requested flag.
- if (httpRequest.headersList.contains('range')) {
- response.rangeRequested = true
+ get closingInfo () {
+ return this.#info.closeInfo
}
+}
- // 13. Set response’s request-includes-credentials to includeCredentials.
- response.requestIncludesCredentials = includeCredentials
+module.exports = {
+ ByteParser
+}
- // 14. If response’s status is 401, httpRequest’s response tainting is not
- // "cors", includeCredentials is true, and request’s window is an environment
- // settings object, then:
- // TODO
- // 15. If response’s status is 407, then:
- if (response.status === 407) {
- // 1. If request’s window is "no-window", then return a network error.
- if (request.window === 'no-window') {
- return makeNetworkError()
- }
+/***/ }),
- // 2. ???
+/***/ 97945:
+/***/ ((module) => {
- // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams)) {
- return makeAppropriateNetworkError(fetchParams)
- }
- // 4. Prompt the end user as appropriate in request’s window and store
- // the result as a proxy-authentication entry. [HTTP-AUTH]
- // TODO: Invoke some kind of callback?
- // 5. Set response to the result of running HTTP-network-or-cache fetch given
- // fetchParams.
- // TODO
- return makeNetworkError('proxy authentication required')
- }
+module.exports = {
+ kWebSocketURL: Symbol('url'),
+ kReadyState: Symbol('ready state'),
+ kController: Symbol('controller'),
+ kResponse: Symbol('response'),
+ kBinaryType: Symbol('binary type'),
+ kSentClose: Symbol('sent close'),
+ kReceivedClose: Symbol('received close'),
+ kByteParser: Symbol('byte parser')
+}
- // 16. If all of the following are true
- if (
- // response’s status is 421
- response.status === 421 &&
- // isNewConnectionFetch is false
- !isNewConnectionFetch &&
- // request’s body is null, or request’s body is non-null and request’s body’s source is non-null
- (request.body == null || request.body.source != null)
- ) {
- // then:
- // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
- if (isCancelled(fetchParams)) {
- return makeAppropriateNetworkError(fetchParams)
- }
+/***/ }),
- // 2. Set response to the result of running HTTP-network-or-cache
- // fetch given fetchParams, isAuthenticationFetch, and true.
+/***/ 95506:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // TODO (spec): The spec doesn't specify this but we need to cancel
- // the active response before we can start a new one.
- // https://github.com/whatwg/fetch/issues/1293
- fetchParams.controller.connection.destroy()
- response = await httpNetworkOrCacheFetch(
- fetchParams,
- isAuthenticationFetch,
- true
- )
- }
- // 17. If isAuthenticationFetch is true, then create an authentication entry
- if (isAuthenticationFetch) {
- // TODO
- }
+const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(97945)
+const { states, opcodes } = __nccwpck_require__(90077)
+const { MessageEvent, ErrorEvent } = __nccwpck_require__(47115)
- // 18. Return response.
- return response
+/* globals Blob */
+
+/**
+ * @param {import('./websocket').WebSocket} ws
+ */
+function isEstablished (ws) {
+ // If the server's response is validated as provided for above, it is
+ // said that _The WebSocket Connection is Established_ and that the
+ // WebSocket Connection is in the OPEN state.
+ return ws[kReadyState] === states.OPEN
}
-// https://fetch.spec.whatwg.org/#http-network-fetch
-async function httpNetworkFetch (
- fetchParams,
- includeCredentials = false,
- forceNewConnection = false
-) {
- assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed)
+/**
+ * @param {import('./websocket').WebSocket} ws
+ */
+function isClosing (ws) {
+ // Upon either sending or receiving a Close control frame, it is said
+ // that _The WebSocket Closing Handshake is Started_ and that the
+ // WebSocket connection is in the CLOSING state.
+ return ws[kReadyState] === states.CLOSING
+}
- fetchParams.controller.connection = {
- abort: null,
- destroyed: false,
- destroy (err) {
- if (!this.destroyed) {
- this.destroyed = true
- this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError'))
- }
- }
- }
+/**
+ * @param {import('./websocket').WebSocket} ws
+ */
+function isClosed (ws) {
+ return ws[kReadyState] === states.CLOSED
+}
- // 1. Let request be fetchParams’s request.
- const request = fetchParams.request
+/**
+ * @see https://dom.spec.whatwg.org/#concept-event-fire
+ * @param {string} e
+ * @param {EventTarget} target
+ * @param {EventInit | undefined} eventInitDict
+ */
+function fireEvent (e, target, eventConstructor = Event, eventInitDict) {
+ // 1. If eventConstructor is not given, then let eventConstructor be Event.
- // 2. Let response be null.
- let response = null
+ // 2. Let event be the result of creating an event given eventConstructor,
+ // in the relevant realm of target.
+ // 3. Initialize event’s type attribute to e.
+ const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap
- // 3. Let timingInfo be fetchParams’s timing info.
- const timingInfo = fetchParams.timingInfo
+ // 4. Initialize any other IDL attributes of event as described in the
+ // invocation of this algorithm.
- // 4. Let httpCache be the result of determining the HTTP cache partition,
- // given request.
- // TODO: cache
- const httpCache = null
+ // 5. Return the result of dispatching event at target, with legacy target
+ // override flag set if set.
+ target.dispatchEvent(event)
+}
- // 5. If httpCache is null, then set request’s cache mode to "no-store".
- if (httpCache == null) {
- request.cache = 'no-store'
+/**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ * @param {import('./websocket').WebSocket} ws
+ * @param {number} type Opcode
+ * @param {Buffer} data application data
+ */
+function websocketMessageReceived (ws, type, data) {
+ // 1. If ready state is not OPEN (1), then return.
+ if (ws[kReadyState] !== states.OPEN) {
+ return
}
- // 6. Let networkPartitionKey be the result of determining the network
- // partition key given request.
- // TODO
+ // 2. Let dataForEvent be determined by switching on type and binary type:
+ let dataForEvent
- // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise
- // "no".
- const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars
+ if (type === opcodes.TEXT) {
+ // -> type indicates that the data is Text
+ // a new DOMString containing data
+ try {
+ dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)
+ } catch {
+ failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
+ return
+ }
+ } else if (type === opcodes.BINARY) {
+ if (ws[kBinaryType] === 'blob') {
+ // -> type indicates that the data is Binary and binary type is "blob"
+ // a new Blob object, created in the relevant Realm of the WebSocket
+ // object, that represents data as its raw data
+ dataForEvent = new Blob([data])
+ } else {
+ // -> type indicates that the data is Binary and binary type is "arraybuffer"
+ // a new ArrayBuffer object, created in the relevant Realm of the
+ // WebSocket object, whose contents are data
+ dataForEvent = new Uint8Array(data).buffer
+ }
+ }
- // 8. Switch on request’s mode:
- if (request.mode === 'websocket') {
- // Let connection be the result of obtaining a WebSocket connection,
- // given request’s current URL.
- // TODO
- } else {
- // Let connection be the result of obtaining a connection, given
- // networkPartitionKey, request’s current URL’s origin,
- // includeCredentials, and forceNewConnection.
- // TODO
+ // 3. Fire an event named message at the WebSocket object, using MessageEvent,
+ // with the origin attribute initialized to the serialization of the WebSocket
+ // object’s url's origin, and the data attribute initialized to dataForEvent.
+ fireEvent('message', ws, MessageEvent, {
+ origin: ws[kWebSocketURL].origin,
+ data: dataForEvent
+ })
+}
+
+/**
+ * @see https://datatracker.ietf.org/doc/html/rfc6455
+ * @see https://datatracker.ietf.org/doc/html/rfc2616
+ * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
+ * @param {string} protocol
+ */
+function isValidSubprotocol (protocol) {
+ // If present, this value indicates one
+ // or more comma-separated subprotocol the client wishes to speak,
+ // ordered by preference. The elements that comprise this value
+ // MUST be non-empty strings with characters in the range U+0021 to
+ // U+007E not including separator characters as defined in
+ // [RFC2616] and MUST all be unique strings.
+ if (protocol.length === 0) {
+ return false
}
- // 9. Run these steps, but abort when the ongoing fetch is terminated:
+ for (const char of protocol) {
+ const code = char.charCodeAt(0)
- // 1. If connection is failure, then return a network error.
+ if (
+ code < 0x21 ||
+ code > 0x7E ||
+ char === '(' ||
+ char === ')' ||
+ char === '<' ||
+ char === '>' ||
+ char === '@' ||
+ char === ',' ||
+ char === ';' ||
+ char === ':' ||
+ char === '\\' ||
+ char === '"' ||
+ char === '/' ||
+ char === '[' ||
+ char === ']' ||
+ char === '?' ||
+ char === '=' ||
+ char === '{' ||
+ char === '}' ||
+ code === 32 || // SP
+ code === 9 // HT
+ ) {
+ return false
+ }
+ }
- // 2. Set timingInfo’s final connection timing info to the result of
- // calling clamp and coarsen connection timing info with connection’s
- // timing info, timingInfo’s post-redirect start time, and fetchParams’s
- // cross-origin isolated capability.
+ return true
+}
- // 3. If connection is not an HTTP/2 connection, request’s body is non-null,
- // and request’s body’s source is null, then append (`Transfer-Encoding`,
- // `chunked`) to request’s header list.
+/**
+ * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
+ * @param {number} code
+ */
+function isValidStatusCode (code) {
+ if (code >= 1000 && code < 1015) {
+ return (
+ code !== 1004 && // reserved
+ code !== 1005 && // "MUST NOT be set as a status code"
+ code !== 1006 // "MUST NOT be set as a status code"
+ )
+ }
- // 4. Set timingInfo’s final network-request start time to the coarsened
- // shared current time given fetchParams’s cross-origin isolated
- // capability.
+ return code >= 3000 && code <= 4999
+}
- // 5. Set response to the result of making an HTTP request over connection
- // using request with the following caveats:
+/**
+ * @param {import('./websocket').WebSocket} ws
+ * @param {string|undefined} reason
+ */
+function failWebsocketConnection (ws, reason) {
+ const { [kController]: controller, [kResponse]: response } = ws
- // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS]
- // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH]
+ controller.abort()
- // - If request’s body is non-null, and request’s body’s source is null,
- // then the user agent may have a buffer of up to 64 kibibytes and store
- // a part of request’s body in that buffer. If the user agent reads from
- // request’s body beyond that buffer’s size and the user agent needs to
- // resend request, then instead return a network error.
+ if (response?.socket && !response.socket.destroyed) {
+ response.socket.destroy()
+ }
- // - Set timingInfo’s final network-response start time to the coarsened
- // shared current time given fetchParams’s cross-origin isolated capability,
- // immediately after the user agent’s HTTP parser receives the first byte
- // of the response (e.g., frame header bytes for HTTP/2 or response status
- // line for HTTP/1.x).
+ if (reason) {
+ fireEvent('error', ws, ErrorEvent, {
+ error: new Error(reason)
+ })
+ }
+}
- // - Wait until all the headers are transmitted.
+module.exports = {
+ isEstablished,
+ isClosing,
+ isClosed,
+ fireEvent,
+ isValidSubprotocol,
+ isValidStatusCode,
+ failWebsocketConnection,
+ websocketMessageReceived
+}
- // - Any responses whose status is in the range 100 to 199, inclusive,
- // and is not 101, are to be ignored, except for the purposes of setting
- // timingInfo’s final network-response start time above.
- // - If request’s header list contains `Transfer-Encoding`/`chunked` and
- // response is transferred via HTTP/1.0 or older, then return a network
- // error.
+/***/ }),
- // - If the HTTP request results in a TLS client certificate dialog, then:
+/***/ 90551:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 1. If request’s window is an environment settings object, make the
- // dialog available in request’s window.
- // 2. Otherwise, return a network error.
- // To transmit request’s body body, run these steps:
- let requestBody = null
- // 1. If body is null and fetchParams’s process request end-of-body is
- // non-null, then queue a fetch task given fetchParams’s process request
- // end-of-body and fetchParams’s task destination.
- if (request.body == null && fetchParams.processRequestEndOfBody) {
- queueMicrotask(() => fetchParams.processRequestEndOfBody())
- } else if (request.body != null) {
- // 2. Otherwise, if body is non-null:
+const { webidl } = __nccwpck_require__(94354)
+const { DOMException } = __nccwpck_require__(21234)
+const { URLSerializer } = __nccwpck_require__(37246)
+const { getGlobalOrigin } = __nccwpck_require__(62896)
+const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(90077)
+const {
+ kWebSocketURL,
+ kReadyState,
+ kController,
+ kBinaryType,
+ kResponse,
+ kSentClose,
+ kByteParser
+} = __nccwpck_require__(97945)
+const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(95506)
+const { establishWebSocketConnection } = __nccwpck_require__(96114)
+const { WebsocketFrameSend } = __nccwpck_require__(42697)
+const { ByteParser } = __nccwpck_require__(13607)
+const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(89500)
+const { getGlobalDispatcher } = __nccwpck_require__(61481)
+const { types } = __nccwpck_require__(39023)
- // 1. Let processBodyChunk given bytes be these steps:
- const processBodyChunk = async function * (bytes) {
- // 1. If the ongoing fetch is terminated, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
+let experimentalWarned = false
- // 2. Run this step in parallel: transmit bytes.
- yield bytes
+// https://websockets.spec.whatwg.org/#interface-definition
+class WebSocket extends EventTarget {
+ #events = {
+ open: null,
+ error: null,
+ close: null,
+ message: null
+ }
- // 3. If fetchParams’s process request body is non-null, then run
- // fetchParams’s process request body given bytes’s length.
- fetchParams.processRequestBodyChunkLength?.(bytes.byteLength)
- }
+ #bufferedAmount = 0
+ #protocol = ''
+ #extensions = ''
- // 2. Let processEndOfBody be these steps:
- const processEndOfBody = () => {
- // 1. If fetchParams is canceled, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
+ /**
+ * @param {string} url
+ * @param {string|string[]} protocols
+ */
+ constructor (url, protocols = []) {
+ super()
- // 2. If fetchParams’s process request end-of-body is non-null,
- // then run fetchParams’s process request end-of-body.
- if (fetchParams.processRequestEndOfBody) {
- fetchParams.processRequestEndOfBody()
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' })
+
+ if (!experimentalWarned) {
+ experimentalWarned = true
+ process.emitWarning('WebSockets are experimental, expect them to change at any time.', {
+ code: 'UNDICI-WS'
+ })
}
- // 3. Let processBodyError given e be these steps:
- const processBodyError = (e) => {
- // 1. If fetchParams is canceled, then abort these steps.
- if (isCancelled(fetchParams)) {
- return
- }
+ const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols)
- // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller.
- if (e.name === 'AbortError') {
- fetchParams.controller.abort()
- } else {
- fetchParams.controller.terminate(e)
- }
- }
+ url = webidl.converters.USVString(url)
+ protocols = options.protocols
- // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody,
- // processBodyError, and fetchParams’s task destination.
- requestBody = (async function * () {
- try {
- for await (const bytes of request.body.stream) {
- yield * processBodyChunk(bytes)
- }
- processEndOfBody()
- } catch (err) {
- processBodyError(err)
- }
- })()
- }
+ // 1. Let baseURL be this's relevant settings object's API base URL.
+ const baseURL = getGlobalOrigin()
- try {
- // socket is only provided for websockets
- const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody })
+ // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.
+ let urlRecord
- if (socket) {
- response = makeResponse({ status, statusText, headersList, socket })
- } else {
- const iterator = body[Symbol.asyncIterator]()
- fetchParams.controller.next = () => iterator.next()
+ try {
+ urlRecord = new URL(url, baseURL)
+ } catch (e) {
+ // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
+ throw new DOMException(e, 'SyntaxError')
+ }
+
+ // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
+ if (urlRecord.protocol === 'http:') {
+ urlRecord.protocol = 'ws:'
+ } else if (urlRecord.protocol === 'https:') {
+ // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
+ urlRecord.protocol = 'wss:'
+ }
- response = makeResponse({ status, statusText, headersList })
+ // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
+ if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {
+ throw new DOMException(
+ `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,
+ 'SyntaxError'
+ )
}
- } catch (err) {
- // 10. If aborted, then:
- if (err.name === 'AbortError') {
- // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame.
- fetchParams.controller.connection.destroy()
- // 2. Return the appropriate network error for fetchParams.
- return makeAppropriateNetworkError(fetchParams, err)
+ // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError"
+ // DOMException.
+ if (urlRecord.hash || urlRecord.href.endsWith('#')) {
+ throw new DOMException('Got fragment', 'SyntaxError')
}
- return makeNetworkError(err)
- }
+ // 8. If protocols is a string, set protocols to a sequence consisting
+ // of just that string.
+ if (typeof protocols === 'string') {
+ protocols = [protocols]
+ }
- // 11. Let pullAlgorithm be an action that resumes the ongoing fetch
- // if it is suspended.
- const pullAlgorithm = () => {
- fetchParams.controller.resume()
- }
+ // 9. If any of the values in protocols occur more than once or otherwise
+ // fail to match the requirements for elements that comprise the value
+ // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket
+ // protocol, then throw a "SyntaxError" DOMException.
+ if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {
+ throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
+ }
- // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s
- // controller with reason, given reason.
- const cancelAlgorithm = (reason) => {
- fetchParams.controller.abort(reason)
- }
+ if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {
+ throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
+ }
- // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by
- // the user agent.
- // TODO
+ // 10. Set this's url to urlRecord.
+ this[kWebSocketURL] = new URL(urlRecord.href)
- // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object
- // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent.
- // TODO
+ // 11. Let client be this's relevant settings object.
- // 15. Let stream be a new ReadableStream.
- // 16. Set up stream with pullAlgorithm set to pullAlgorithm,
- // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to
- // highWaterMark, and sizeAlgorithm set to sizeAlgorithm.
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(63774).ReadableStream)
- }
+ // 12. Run this step in parallel:
- const stream = new ReadableStream(
- {
- async start (controller) {
- fetchParams.controller.controller = controller
- },
- async pull (controller) {
- await pullAlgorithm(controller)
- },
- async cancel (reason) {
- await cancelAlgorithm(reason)
- }
- },
- {
- highWaterMark: 0,
- size () {
- return 1
- }
- }
- )
+ // 1. Establish a WebSocket connection given urlRecord, protocols,
+ // and client.
+ this[kController] = establishWebSocketConnection(
+ urlRecord,
+ protocols,
+ this,
+ (response) => this.#onConnectionEstablished(response),
+ options
+ )
- // 17. Run these steps, but abort when the ongoing fetch is terminated:
+ // Each WebSocket object has an associated ready state, which is a
+ // number representing the state of the connection. Initially it must
+ // be CONNECTING (0).
+ this[kReadyState] = WebSocket.CONNECTING
- // 1. Set response’s body to a new body whose stream is stream.
- response.body = { stream }
+ // The extensions attribute must initially return the empty string.
- // 2. If response is not a network error and request’s cache mode is
- // not "no-store", then update response in httpCache for request.
- // TODO
+ // The protocol attribute must initially return the empty string.
- // 3. If includeCredentials is true and the user agent is not configured
- // to block cookies for request (see section 7 of [COOKIES]), then run the
- // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on
- // the value of each header whose name is a byte-case-insensitive match for
- // `Set-Cookie` in response’s header list, if any, and request’s current URL.
- // TODO
+ // Each WebSocket object has an associated binary type, which is a
+ // BinaryType. Initially it must be "blob".
+ this[kBinaryType] = 'blob'
+ }
- // 18. If aborted, then:
- // TODO
+ /**
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-close
+ * @param {number|undefined} code
+ * @param {string|undefined} reason
+ */
+ close (code = undefined, reason = undefined) {
+ webidl.brandCheck(this, WebSocket)
- // 19. Run these steps in parallel:
+ if (code !== undefined) {
+ code = webidl.converters['unsigned short'](code, { clamp: true })
+ }
- // 1. Run these steps, but abort when fetchParams is canceled:
- fetchParams.controller.on('terminated', onAborted)
- fetchParams.controller.resume = async () => {
- // 1. While true
- while (true) {
- // 1-3. See onData...
+ if (reason !== undefined) {
+ reason = webidl.converters.USVString(reason)
+ }
- // 4. Set bytes to the result of handling content codings given
- // codings and bytes.
- let bytes
- let isFailure
- try {
- const { done, value } = await fetchParams.controller.next()
+ // 1. If code is present, but is neither an integer equal to 1000 nor an
+ // integer in the range 3000 to 4999, inclusive, throw an
+ // "InvalidAccessError" DOMException.
+ if (code !== undefined) {
+ if (code !== 1000 && (code < 3000 || code > 4999)) {
+ throw new DOMException('invalid code', 'InvalidAccessError')
+ }
+ }
- if (isAborted(fetchParams)) {
- break
- }
+ let reasonByteLength = 0
- bytes = done ? undefined : value
- } catch (err) {
- if (fetchParams.controller.ended && !timingInfo.encodedBodySize) {
- // zlib doesn't like empty streams.
- bytes = undefined
- } else {
- bytes = err
+ // 2. If reason is present, then run these substeps:
+ if (reason !== undefined) {
+ // 1. Let reasonBytes be the result of encoding reason.
+ // 2. If reasonBytes is longer than 123 bytes, then throw a
+ // "SyntaxError" DOMException.
+ reasonByteLength = Buffer.byteLength(reason)
- // err may be propagated from the result of calling readablestream.cancel,
- // which might not be an error. https://github.com/nodejs/undici/issues/2009
- isFailure = true
- }
+ if (reasonByteLength > 123) {
+ throw new DOMException(
+ `Reason must be less than 123 bytes; received ${reasonByteLength}`,
+ 'SyntaxError'
+ )
}
+ }
- if (bytes === undefined) {
- // 2. Otherwise, if the bytes transmission for response’s message
- // body is done normally and stream is readable, then close
- // stream, finalize response for fetchParams and response, and
- // abort these in-parallel steps.
- readableStreamClose(fetchParams.controller.controller)
-
- finalizeResponse(fetchParams, response)
+ // 3. Run the first matching steps from the following list:
+ if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) {
+ // If this's ready state is CLOSING (2) or CLOSED (3)
+ // Do nothing.
+ } else if (!isEstablished(this)) {
+ // If the WebSocket connection is not yet established
+ // Fail the WebSocket connection and set this's ready state
+ // to CLOSING (2).
+ failWebsocketConnection(this, 'Connection was closed before it was established.')
+ this[kReadyState] = WebSocket.CLOSING
+ } else if (!isClosing(this)) {
+ // If the WebSocket closing handshake has not yet been started
+ // Start the WebSocket closing handshake and set this's ready
+ // state to CLOSING (2).
+ // - If neither code nor reason is present, the WebSocket Close
+ // message must not have a body.
+ // - If code is present, then the status code to use in the
+ // WebSocket Close message must be the integer given by code.
+ // - If reason is also present, then reasonBytes must be
+ // provided in the Close message after the status code.
- return
- }
+ const frame = new WebsocketFrameSend()
- // 5. Increase timingInfo’s decoded body size by bytes’s length.
- timingInfo.decodedBodySize += bytes?.byteLength ?? 0
+ // If neither code nor reason is present, the WebSocket Close
+ // message must not have a body.
- // 6. If bytes is failure, then terminate fetchParams’s controller.
- if (isFailure) {
- fetchParams.controller.terminate(bytes)
- return
+ // If code is present, then the status code to use in the
+ // WebSocket Close message must be the integer given by code.
+ if (code !== undefined && reason === undefined) {
+ frame.frameData = Buffer.allocUnsafe(2)
+ frame.frameData.writeUInt16BE(code, 0)
+ } else if (code !== undefined && reason !== undefined) {
+ // If reason is also present, then reasonBytes must be
+ // provided in the Close message after the status code.
+ frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
+ frame.frameData.writeUInt16BE(code, 0)
+ // the body MAY contain UTF-8-encoded data with value /reason/
+ frame.frameData.write(reason, 2, 'utf-8')
+ } else {
+ frame.frameData = emptyBuffer
}
- // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes
- // into stream.
- fetchParams.controller.controller.enqueue(new Uint8Array(bytes))
+ /** @type {import('stream').Duplex} */
+ const socket = this[kResponse].socket
- // 8. If stream is errored, then terminate the ongoing fetch.
- if (isErrored(stream)) {
- fetchParams.controller.terminate()
- return
- }
+ socket.write(frame.createFrame(opcodes.CLOSE), (err) => {
+ if (!err) {
+ this[kSentClose] = true
+ }
+ })
- // 9. If stream doesn’t need more data ask the user agent to suspend
- // the ongoing fetch.
- if (!fetchParams.controller.controller.desiredSize) {
- return
- }
+ // Upon either sending or receiving a Close control frame, it is said
+ // that _The WebSocket Closing Handshake is Started_ and that the
+ // WebSocket connection is in the CLOSING state.
+ this[kReadyState] = states.CLOSING
+ } else {
+ // Otherwise
+ // Set this's ready state to CLOSING (2).
+ this[kReadyState] = WebSocket.CLOSING
}
}
- // 2. If aborted, then:
- function onAborted (reason) {
- // 2. If fetchParams is aborted, then:
- if (isAborted(fetchParams)) {
- // 1. Set response’s aborted flag.
- response.aborted = true
+ /**
+ * @see https://websockets.spec.whatwg.org/#dom-websocket-send
+ * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
+ */
+ send (data) {
+ webidl.brandCheck(this, WebSocket)
- // 2. If stream is readable, then error stream with the result of
- // deserialize a serialized abort reason given fetchParams’s
- // controller’s serialized abort reason and an
- // implementation-defined realm.
- if (isReadable(stream)) {
- fetchParams.controller.controller.error(
- fetchParams.controller.serializedAbortReason
- )
- }
- } else {
- // 3. Otherwise, if stream is readable, error stream with a TypeError.
- if (isReadable(stream)) {
- fetchParams.controller.controller.error(new TypeError('terminated', {
- cause: isErrorLike(reason) ? reason : undefined
- }))
- }
- }
+ webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' })
- // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame.
- // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so.
- fetchParams.controller.connection.destroy()
- }
+ data = webidl.converters.WebSocketSendData(data)
- // 20. Return response.
- return response
+ // 1. If this's ready state is CONNECTING, then throw an
+ // "InvalidStateError" DOMException.
+ if (this[kReadyState] === WebSocket.CONNECTING) {
+ throw new DOMException('Sent before connected.', 'InvalidStateError')
+ }
- async function dispatch ({ body }) {
- const url = requestCurrentURL(request)
- /** @type {import('../..').Agent} */
- const agent = fetchParams.controller.dispatcher
+ // 2. Run the appropriate set of steps from the following list:
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
- return new Promise((resolve, reject) => agent.dispatch(
- {
- path: url.pathname + url.search,
- origin: url.origin,
- method: request.method,
- body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body,
- headers: request.headersList.entries,
- maxRedirections: 0,
- upgrade: request.mode === 'websocket' ? 'websocket' : undefined
- },
- {
- body: null,
- abort: null,
+ if (!isEstablished(this) || isClosing(this)) {
+ return
+ }
- onConnect (abort) {
- // TODO (fix): Do we need connection here?
- const { connection } = fetchParams.controller
+ /** @type {import('stream').Duplex} */
+ const socket = this[kResponse].socket
- if (connection.destroyed) {
- abort(new DOMException('The operation was aborted.', 'AbortError'))
- } else {
- fetchParams.controller.on('terminated', abort)
- this.abort = connection.abort = abort
- }
- },
+ // If data is a string
+ if (typeof data === 'string') {
+ // If the WebSocket connection is established and the WebSocket
+ // closing handshake has not yet started, then the user agent
+ // must send a WebSocket Message comprised of the data argument
+ // using a text frame opcode; if the data cannot be sent, e.g.
+ // because it would need to be buffered but the buffer is full,
+ // the user agent must flag the WebSocket as full and then close
+ // the WebSocket connection. Any invocation of this method with a
+ // string argument that does not throw an exception must increase
+ // the bufferedAmount attribute by the number of bytes needed to
+ // express the argument as UTF-8.
- onHeaders (status, headersList, resume, statusText) {
- if (status < 200) {
- return
- }
+ const value = Buffer.from(data)
+ const frame = new WebsocketFrameSend(value)
+ const buffer = frame.createFrame(opcodes.TEXT)
- let codings = []
- let location = ''
+ this.#bufferedAmount += value.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= value.byteLength
+ })
+ } else if (types.isArrayBuffer(data)) {
+ // If the WebSocket connection is established, and the WebSocket
+ // closing handshake has not yet started, then the user agent must
+ // send a WebSocket Message comprised of data using a binary frame
+ // opcode; if the data cannot be sent, e.g. because it would need
+ // to be buffered but the buffer is full, the user agent must flag
+ // the WebSocket as full and then close the WebSocket connection.
+ // The data to be sent is the data stored in the buffer described
+ // by the ArrayBuffer object. Any invocation of this method with an
+ // ArrayBuffer argument that does not throw an exception must
+ // increase the bufferedAmount attribute by the length of the
+ // ArrayBuffer in bytes.
- const headers = new Headers()
+ const value = Buffer.from(data)
+ const frame = new WebsocketFrameSend(value)
+ const buffer = frame.createFrame(opcodes.BINARY)
- // For H2, the headers are a plain JS object
- // We distinguish between them and iterate accordingly
- if (Array.isArray(headersList)) {
- for (let n = 0; n < headersList.length; n += 2) {
- const key = headersList[n + 0].toString('latin1')
- const val = headersList[n + 1].toString('latin1')
- if (key.toLowerCase() === 'content-encoding') {
- // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
- // "All content-coding values are case-insensitive..."
- codings = val.toLowerCase().split(',').map((x) => x.trim())
- } else if (key.toLowerCase() === 'location') {
- location = val
- }
+ this.#bufferedAmount += value.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= value.byteLength
+ })
+ } else if (ArrayBuffer.isView(data)) {
+ // If the WebSocket connection is established, and the WebSocket
+ // closing handshake has not yet started, then the user agent must
+ // send a WebSocket Message comprised of data using a binary frame
+ // opcode; if the data cannot be sent, e.g. because it would need to
+ // be buffered but the buffer is full, the user agent must flag the
+ // WebSocket as full and then close the WebSocket connection. The
+ // data to be sent is the data stored in the section of the buffer
+ // described by the ArrayBuffer object that data references. Any
+ // invocation of this method with this kind of argument that does
+ // not throw an exception must increase the bufferedAmount attribute
+ // by the length of data’s buffer in bytes.
- headers[kHeadersList].append(key, val)
- }
- } else {
- const keys = Object.keys(headersList)
- for (const key of keys) {
- const val = headersList[key]
- if (key.toLowerCase() === 'content-encoding') {
- // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1
- // "All content-coding values are case-insensitive..."
- codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse()
- } else if (key.toLowerCase() === 'location') {
- location = val
- }
+ const ab = Buffer.from(data, data.byteOffset, data.byteLength)
- headers[kHeadersList].append(key, val)
- }
- }
+ const frame = new WebsocketFrameSend(ab)
+ const buffer = frame.createFrame(opcodes.BINARY)
- this.body = new Readable({ read: resume })
+ this.#bufferedAmount += ab.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= ab.byteLength
+ })
+ } else if (isBlobLike(data)) {
+ // If the WebSocket connection is established, and the WebSocket
+ // closing handshake has not yet started, then the user agent must
+ // send a WebSocket Message comprised of data using a binary frame
+ // opcode; if the data cannot be sent, e.g. because it would need to
+ // be buffered but the buffer is full, the user agent must flag the
+ // WebSocket as full and then close the WebSocket connection. The data
+ // to be sent is the raw data represented by the Blob object. Any
+ // invocation of this method with a Blob argument that does not throw
+ // an exception must increase the bufferedAmount attribute by the size
+ // of the Blob object’s raw data, in bytes.
- const decoders = []
+ const frame = new WebsocketFrameSend()
- const willFollow = request.redirect === 'follow' &&
- location &&
- redirectStatusSet.has(status)
+ data.arrayBuffer().then((ab) => {
+ const value = Buffer.from(ab)
+ frame.frameData = value
+ const buffer = frame.createFrame(opcodes.BINARY)
- // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
- if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
- for (const coding of codings) {
- // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2
- if (coding === 'x-gzip' || coding === 'gzip') {
- decoders.push(zlib.createGunzip({
- // Be less strict when decoding compressed responses, since sometimes
- // servers send slightly invalid responses that are still accepted
- // by common browsers.
- // Always using Z_SYNC_FLUSH is what cURL does.
- flush: zlib.constants.Z_SYNC_FLUSH,
- finishFlush: zlib.constants.Z_SYNC_FLUSH
- }))
- } else if (coding === 'deflate') {
- decoders.push(zlib.createInflate())
- } else if (coding === 'br') {
- decoders.push(zlib.createBrotliDecompress())
- } else {
- decoders.length = 0
- break
- }
- }
- }
+ this.#bufferedAmount += value.byteLength
+ socket.write(buffer, () => {
+ this.#bufferedAmount -= value.byteLength
+ })
+ })
+ }
+ }
- resolve({
- status,
- statusText,
- headersList: headers[kHeadersList],
- body: decoders.length
- ? pipeline(this.body, ...decoders, () => { })
- : this.body.on('error', () => {})
- })
+ get readyState () {
+ webidl.brandCheck(this, WebSocket)
- return true
- },
+ // The readyState getter steps are to return this's ready state.
+ return this[kReadyState]
+ }
- onData (chunk) {
- if (fetchParams.controller.dump) {
- return
- }
+ get bufferedAmount () {
+ webidl.brandCheck(this, WebSocket)
- // 1. If one or more bytes have been transmitted from response’s
- // message body, then:
+ return this.#bufferedAmount
+ }
- // 1. Let bytes be the transmitted bytes.
- const bytes = chunk
+ get url () {
+ webidl.brandCheck(this, WebSocket)
- // 2. Let codings be the result of extracting header list values
- // given `Content-Encoding` and response’s header list.
- // See pullAlgorithm.
+ // The url getter steps are to return this's url, serialized.
+ return URLSerializer(this[kWebSocketURL])
+ }
- // 3. Increase timingInfo’s encoded body size by bytes’s length.
- timingInfo.encodedBodySize += bytes.byteLength
+ get extensions () {
+ webidl.brandCheck(this, WebSocket)
- // 4. See pullAlgorithm...
+ return this.#extensions
+ }
- return this.body.push(bytes)
- },
+ get protocol () {
+ webidl.brandCheck(this, WebSocket)
- onComplete () {
- if (this.abort) {
- fetchParams.controller.off('terminated', this.abort)
- }
+ return this.#protocol
+ }
- fetchParams.controller.ended = true
+ get onopen () {
+ webidl.brandCheck(this, WebSocket)
- this.body.push(null)
- },
+ return this.#events.open
+ }
- onError (error) {
- if (this.abort) {
- fetchParams.controller.off('terminated', this.abort)
- }
+ set onopen (fn) {
+ webidl.brandCheck(this, WebSocket)
- this.body?.destroy(error)
+ if (this.#events.open) {
+ this.removeEventListener('open', this.#events.open)
+ }
- fetchParams.controller.terminate(error)
+ if (typeof fn === 'function') {
+ this.#events.open = fn
+ this.addEventListener('open', fn)
+ } else {
+ this.#events.open = null
+ }
+ }
- reject(error)
- },
+ get onerror () {
+ webidl.brandCheck(this, WebSocket)
- onUpgrade (status, headersList, socket) {
- if (status !== 101) {
- return
- }
+ return this.#events.error
+ }
- const headers = new Headers()
+ set onerror (fn) {
+ webidl.brandCheck(this, WebSocket)
- for (let n = 0; n < headersList.length; n += 2) {
- const key = headersList[n + 0].toString('latin1')
- const val = headersList[n + 1].toString('latin1')
+ if (this.#events.error) {
+ this.removeEventListener('error', this.#events.error)
+ }
- headers[kHeadersList].append(key, val)
- }
+ if (typeof fn === 'function') {
+ this.#events.error = fn
+ this.addEventListener('error', fn)
+ } else {
+ this.#events.error = null
+ }
+ }
- resolve({
- status,
- statusText: STATUS_CODES[status],
- headersList: headers[kHeadersList],
- socket
- })
+ get onclose () {
+ webidl.brandCheck(this, WebSocket)
- return true
- }
- }
- ))
+ return this.#events.close
}
-}
-module.exports = {
- fetch,
- Fetch,
- fetching,
- finalizeAndReportTiming
-}
+ set onclose (fn) {
+ webidl.brandCheck(this, WebSocket)
+ if (this.#events.close) {
+ this.removeEventListener('close', this.#events.close)
+ }
-/***/ }),
+ if (typeof fn === 'function') {
+ this.#events.close = fn
+ this.addEventListener('close', fn)
+ } else {
+ this.#events.close = null
+ }
+ }
-/***/ 2630:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ get onmessage () {
+ webidl.brandCheck(this, WebSocket)
-/* globals AbortController */
+ return this.#events.message
+ }
+ set onmessage (fn) {
+ webidl.brandCheck(this, WebSocket)
+ if (this.#events.message) {
+ this.removeEventListener('message', this.#events.message)
+ }
-const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(37791)
-const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(12801)
-const { FinalizationRegistry } = __nccwpck_require__(90022)()
-const util = __nccwpck_require__(89500)
-const {
- isValidHTTPToken,
- sameOrigin,
- normalizeMethod,
- makePolicyContainer,
- normalizeMethodRecord
-} = __nccwpck_require__(72847)
-const {
- forbiddenMethodsSet,
- corsSafeListedMethodsSet,
- referrerPolicy,
- requestRedirect,
- requestMode,
- requestCredentials,
- requestCache,
- requestDuplex
-} = __nccwpck_require__(21234)
-const { kEnumerableProperty } = util
-const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(63730)
-const { webidl } = __nccwpck_require__(94354)
-const { getGlobalOrigin } = __nccwpck_require__(62896)
-const { URLSerializer } = __nccwpck_require__(37246)
-const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
-const assert = __nccwpck_require__(42613)
-const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(24434)
+ if (typeof fn === 'function') {
+ this.#events.message = fn
+ this.addEventListener('message', fn)
+ } else {
+ this.#events.message = null
+ }
+ }
-let TransformStream = globalThis.TransformStream
+ get binaryType () {
+ webidl.brandCheck(this, WebSocket)
-const kAbortController = Symbol('abortController')
+ return this[kBinaryType]
+ }
-const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => {
- signal.removeEventListener('abort', abort)
-})
+ set binaryType (type) {
+ webidl.brandCheck(this, WebSocket)
-// https://fetch.spec.whatwg.org/#request-class
-class Request {
- // https://fetch.spec.whatwg.org/#dom-request
- constructor (input, init = {}) {
- if (input === kConstruct) {
- return
+ if (type !== 'blob' && type !== 'arraybuffer') {
+ this[kBinaryType] = 'blob'
+ } else {
+ this[kBinaryType] = type
}
+ }
- webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' })
+ /**
+ * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
+ */
+ #onConnectionEstablished (response) {
+ // processResponse is called when the "response’s header list has been received and initialized."
+ // once this happens, the connection is open
+ this[kResponse] = response
- input = webidl.converters.RequestInfo(input)
- init = webidl.converters.RequestInit(init)
+ const parser = new ByteParser(this)
+ parser.on('drain', function onParserDrain () {
+ this.ws[kResponse].socket.resume()
+ })
- // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object
- this[kRealm] = {
- settingsObject: {
- baseUrl: getGlobalOrigin(),
- get origin () {
- return this.baseUrl?.origin
- },
- policyContainer: makePolicyContainer()
- }
- }
+ response.socket.ws = this
+ this[kByteParser] = parser
- // 1. Let request be null.
- let request = null
+ // 1. Change the ready state to OPEN (1).
+ this[kReadyState] = states.OPEN
- // 2. Let fallbackMode be null.
- let fallbackMode = null
+ // 2. Change the extensions attribute’s value to the extensions in use, if
+ // it is not the null value.
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
+ const extensions = response.headersList.get('sec-websocket-extensions')
- // 3. Let baseURL be this’s relevant settings object’s API base URL.
- const baseUrl = this[kRealm].settingsObject.baseUrl
+ if (extensions !== null) {
+ this.#extensions = extensions
+ }
- // 4. Let signal be null.
- let signal = null
+ // 3. Change the protocol attribute’s value to the subprotocol in use, if
+ // it is not the null value.
+ // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9
+ const protocol = response.headersList.get('sec-websocket-protocol')
- // 5. If input is a string, then:
- if (typeof input === 'string') {
- // 1. Let parsedURL be the result of parsing input with baseURL.
- // 2. If parsedURL is failure, then throw a TypeError.
- let parsedURL
- try {
- parsedURL = new URL(input, baseUrl)
- } catch (err) {
- throw new TypeError('Failed to parse URL from ' + input, { cause: err })
- }
+ if (protocol !== null) {
+ this.#protocol = protocol
+ }
- // 3. If parsedURL includes credentials, then throw a TypeError.
- if (parsedURL.username || parsedURL.password) {
- throw new TypeError(
- 'Request cannot be constructed from a URL that includes credentials: ' +
- input
- )
- }
+ // 4. Fire an event named open at the WebSocket object.
+ fireEvent('open', this)
+ }
+}
- // 4. Set request to a new request whose URL is parsedURL.
- request = makeRequest({ urlList: [parsedURL] })
+// https://websockets.spec.whatwg.org/#dom-websocket-connecting
+WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING
+// https://websockets.spec.whatwg.org/#dom-websocket-open
+WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN
+// https://websockets.spec.whatwg.org/#dom-websocket-closing
+WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING
+// https://websockets.spec.whatwg.org/#dom-websocket-closed
+WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED
- // 5. Set fallbackMode to "cors".
- fallbackMode = 'cors'
- } else {
- // 6. Otherwise:
+Object.defineProperties(WebSocket.prototype, {
+ CONNECTING: staticPropertyDescriptors,
+ OPEN: staticPropertyDescriptors,
+ CLOSING: staticPropertyDescriptors,
+ CLOSED: staticPropertyDescriptors,
+ url: kEnumerableProperty,
+ readyState: kEnumerableProperty,
+ bufferedAmount: kEnumerableProperty,
+ onopen: kEnumerableProperty,
+ onerror: kEnumerableProperty,
+ onclose: kEnumerableProperty,
+ close: kEnumerableProperty,
+ onmessage: kEnumerableProperty,
+ binaryType: kEnumerableProperty,
+ send: kEnumerableProperty,
+ extensions: kEnumerableProperty,
+ protocol: kEnumerableProperty,
+ [Symbol.toStringTag]: {
+ value: 'WebSocket',
+ writable: false,
+ enumerable: false,
+ configurable: true
+ }
+})
- // 7. Assert: input is a Request object.
- assert(input instanceof Request)
+Object.defineProperties(WebSocket, {
+ CONNECTING: staticPropertyDescriptors,
+ OPEN: staticPropertyDescriptors,
+ CLOSING: staticPropertyDescriptors,
+ CLOSED: staticPropertyDescriptors
+})
- // 8. Set request to input’s request.
- request = input[kState]
+webidl.converters['sequence'] = webidl.sequenceConverter(
+ webidl.converters.DOMString
+)
- // 9. Set signal to input’s signal.
- signal = input[kSignal]
+webidl.converters['DOMString or sequence'] = function (V) {
+ if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {
+ return webidl.converters['sequence'](V)
+ }
+
+ return webidl.converters.DOMString(V)
+}
+
+// This implements the propsal made in https://github.com/whatwg/websockets/issues/42
+webidl.converters.WebSocketInit = webidl.dictionaryConverter([
+ {
+ key: 'protocols',
+ converter: webidl.converters['DOMString or sequence'],
+ get defaultValue () {
+ return []
}
+ },
+ {
+ key: 'dispatcher',
+ converter: (V) => V,
+ get defaultValue () {
+ return getGlobalDispatcher()
+ }
+ },
+ {
+ key: 'headers',
+ converter: webidl.nullableConverter(webidl.converters.HeadersInit)
+ }
+])
- // 7. Let origin be this’s relevant settings object’s origin.
- const origin = this[kRealm].settingsObject.origin
+webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {
+ if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {
+ return webidl.converters.WebSocketInit(V)
+ }
- // 8. Let window be "client".
- let window = 'client'
+ return { protocols: webidl.converters['DOMString or sequence'](V) }
+}
- // 9. If request’s window is an environment settings object and its origin
- // is same origin with origin, then set window to request’s window.
- if (
- request.window?.constructor?.name === 'EnvironmentSettingsObject' &&
- sameOrigin(request.window, origin)
- ) {
- window = request.window
+webidl.converters.WebSocketSendData = function (V) {
+ if (webidl.util.Type(V) === 'Object') {
+ if (isBlobLike(V)) {
+ return webidl.converters.Blob(V, { strict: false })
}
- // 10. If init["window"] exists and is non-null, then throw a TypeError.
- if (init.window != null) {
- throw new TypeError(`'window' option '${window}' must be null`)
+ if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) {
+ return webidl.converters.BufferSource(V)
}
+ }
- // 11. If init["window"] exists, then set window to "no-window".
- if ('window' in init) {
- window = 'no-window'
- }
+ return webidl.converters.USVString(V)
+}
- // 12. Set request to a new request with the following properties:
- request = makeRequest({
- // URL request’s URL.
- // undici implementation note: this is set as the first item in request's urlList in makeRequest
- // method request’s method.
- method: request.method,
- // header list A copy of request’s header list.
- // undici implementation note: headersList is cloned in makeRequest
- headersList: request.headersList,
- // unsafe-request flag Set.
- unsafeRequest: request.unsafeRequest,
- // client This’s relevant settings object.
- client: this[kRealm].settingsObject,
- // window window.
- window,
- // priority request’s priority.
- priority: request.priority,
- // origin request’s origin. The propagation of the origin is only significant for navigation requests
- // being handled by a service worker. In this scenario a request can have an origin that is different
- // from the current client.
- origin: request.origin,
- // referrer request’s referrer.
- referrer: request.referrer,
- // referrer policy request’s referrer policy.
- referrerPolicy: request.referrerPolicy,
- // mode request’s mode.
- mode: request.mode,
- // credentials mode request’s credentials mode.
- credentials: request.credentials,
- // cache mode request’s cache mode.
- cache: request.cache,
- // redirect mode request’s redirect mode.
- redirect: request.redirect,
- // integrity metadata request’s integrity metadata.
- integrity: request.integrity,
- // keepalive request’s keepalive.
- keepalive: request.keepalive,
- // reload-navigation flag request’s reload-navigation flag.
- reloadNavigation: request.reloadNavigation,
- // history-navigation flag request’s history-navigation flag.
- historyNavigation: request.historyNavigation,
- // URL list A clone of request’s URL list.
- urlList: [...request.urlList]
- })
+module.exports = {
+ WebSocket
+}
- const initHasKey = Object.keys(init).length !== 0
- // 13. If init is not empty, then:
- if (initHasKey) {
- // 1. If request’s mode is "navigate", then set it to "same-origin".
- if (request.mode === 'navigate') {
- request.mode = 'same-origin'
- }
+/***/ }),
- // 2. Unset request’s reload-navigation flag.
- request.reloadNavigation = false
+/***/ 49367:
+/***/ ((__unused_webpack_module, exports) => {
- // 3. Unset request’s history-navigation flag.
- request.historyNavigation = false
- // 4. Set request’s origin to "client".
- request.origin = 'client'
- // 5. Set request’s referrer to "client"
- request.referrer = 'client'
+Object.defineProperty(exports, "__esModule", ({ value: true }));
- // 6. Set request’s referrer policy to the empty string.
- request.referrerPolicy = ''
+function getUserAgent() {
+ if (typeof navigator === "object" && "userAgent" in navigator) {
+ return navigator.userAgent;
+ }
- // 7. Set request’s URL to request’s current URL.
- request.url = request.urlList[request.urlList.length - 1]
+ if (typeof process === "object" && process.version !== undefined) {
+ return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
+ }
- // 8. Set request’s URL list to « request’s URL ».
- request.urlList = [request.url]
- }
+ return "";
+}
- // 14. If init["referrer"] exists, then:
- if (init.referrer !== undefined) {
- // 1. Let referrer be init["referrer"].
- const referrer = init.referrer
+exports.getUserAgent = getUserAgent;
+//# sourceMappingURL=index.js.map
- // 2. If referrer is the empty string, then set request’s referrer to "no-referrer".
- if (referrer === '') {
- request.referrer = 'no-referrer'
- } else {
- // 1. Let parsedReferrer be the result of parsing referrer with
- // baseURL.
- // 2. If parsedReferrer is failure, then throw a TypeError.
- let parsedReferrer
- try {
- parsedReferrer = new URL(referrer, baseUrl)
- } catch (err) {
- throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err })
- }
- // 3. If one of the following is true
- // - parsedReferrer’s scheme is "about" and path is the string "client"
- // - parsedReferrer’s origin is not same origin with origin
- // then set request’s referrer to "client".
- if (
- (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') ||
- (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl))
- ) {
- request.referrer = 'client'
- } else {
- // 4. Otherwise, set request’s referrer to parsedReferrer.
- request.referrer = parsedReferrer
- }
- }
- }
+/***/ }),
- // 15. If init["referrerPolicy"] exists, then set request’s referrer policy
- // to it.
- if (init.referrerPolicy !== undefined) {
- request.referrerPolicy = init.referrerPolicy
- }
+/***/ 27460:
+/***/ ((module) => {
- // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise.
- let mode
- if (init.mode !== undefined) {
- mode = init.mode
- } else {
- mode = fallbackMode
- }
+// Returns a wrapper function that returns a wrapped callback
+// The wrapper function should do some stuff, and return a
+// presumably different callback function.
+// This makes sure that own properties are retained, so that
+// decorations and such are not lost along the way.
+module.exports = wrappy
+function wrappy (fn, cb) {
+ if (fn && cb) return wrappy(fn)(cb)
- // 17. If mode is "navigate", then throw a TypeError.
- if (mode === 'navigate') {
- throw webidl.errors.exception({
- header: 'Request constructor',
- message: 'invalid request mode navigate.'
- })
- }
+ if (typeof fn !== 'function')
+ throw new TypeError('need wrapper function')
+
+ Object.keys(fn).forEach(function (k) {
+ wrapper[k] = fn[k]
+ })
+
+ return wrapper
- // 18. If mode is non-null, set request’s mode to mode.
- if (mode != null) {
- request.mode = mode
+ function wrapper() {
+ var args = new Array(arguments.length)
+ for (var i = 0; i < args.length; i++) {
+ args[i] = arguments[i]
}
-
- // 19. If init["credentials"] exists, then set request’s credentials mode
- // to it.
- if (init.credentials !== undefined) {
- request.credentials = init.credentials
+ var ret = fn.apply(this, args)
+ var cb = args[args.length-1]
+ if (typeof ret === 'function' && ret !== cb) {
+ Object.keys(cb).forEach(function (k) {
+ ret[k] = cb[k]
+ })
}
+ return ret
+ }
+}
- // 18. If init["cache"] exists, then set request’s cache mode to it.
- if (init.cache !== undefined) {
- request.cache = init.cache
- }
- // 21. If request’s cache mode is "only-if-cached" and request’s mode is
- // not "same-origin", then throw a TypeError.
- if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
- throw new TypeError(
- "'only-if-cached' can be set only with 'same-origin' mode"
- )
- }
+/***/ }),
- // 22. If init["redirect"] exists, then set request’s redirect mode to it.
- if (init.redirect !== undefined) {
- request.redirect = init.redirect
- }
+/***/ 73700:
+/***/ ((module) => {
- // 23. If init["integrity"] exists, then set request’s integrity metadata to it.
- if (init.integrity != null) {
- request.integrity = String(init.integrity)
- }
+module.exports = eval("require")("osx-temperature-sensor");
- // 24. If init["keepalive"] exists, then set request’s keepalive to it.
- if (init.keepalive !== undefined) {
- request.keepalive = Boolean(init.keepalive)
- }
- // 25. If init["method"] exists, then:
- if (init.method !== undefined) {
- // 1. Let method be init["method"].
- let method = init.method
+/***/ }),
- // 2. If method is not a method or method is a forbidden method, then
- // throw a TypeError.
- if (!isValidHTTPToken(method)) {
- throw new TypeError(`'${method}' is not a valid HTTP method.`)
- }
+/***/ 52704:
+/***/ ((module) => {
- if (forbiddenMethodsSet.has(method.toUpperCase())) {
- throw new TypeError(`'${method}' HTTP method is unsupported.`)
- }
+module.exports = eval("require")("supports-color");
- // 3. Normalize method.
- method = normalizeMethodRecord[method] ?? normalizeMethod(method)
- // 4. Set request’s method to method.
- request.method = method
- }
+/***/ }),
- // 26. If init["signal"] exists, then set signal to it.
- if (init.signal !== undefined) {
- signal = init.signal
- }
+/***/ 42613:
+/***/ ((module) => {
- // 27. Set this’s request to request.
- this[kState] = request
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert");
- // 28. Set this’s signal to a new AbortSignal object with this’s relevant
- // Realm.
- // TODO: could this be simplified with AbortSignal.any
- // (https://dom.spec.whatwg.org/#dom-abortsignal-any)
- const ac = new AbortController()
- this[kSignal] = ac.signal
- this[kSignal][kRealm] = this[kRealm]
+/***/ }),
- // 29. If signal is not null, then make this’s signal follow signal.
- if (signal != null) {
- if (
- !signal ||
- typeof signal.aborted !== 'boolean' ||
- typeof signal.addEventListener !== 'function'
- ) {
- throw new TypeError(
- "Failed to construct 'Request': member signal is not of type AbortSignal."
- )
- }
+/***/ 90290:
+/***/ ((module) => {
- if (signal.aborted) {
- ac.abort(signal.reason)
- } else {
- // Keep a strong ref to ac while request object
- // is alive. This is needed to prevent AbortController
- // from being prematurely garbage collected.
- // See, https://github.com/nodejs/undici/issues/1926.
- this[kAbortController] = ac
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks");
- const acRef = new WeakRef(ac)
- const abort = function () {
- const ac = acRef.deref()
- if (ac !== undefined) {
- ac.abort(this.reason)
- }
- }
+/***/ }),
- // Third-party AbortControllers may not work with these.
- // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619.
- try {
- // If the max amount of listeners is equal to the default, increase it
- // This is only available in node >= v19.9.0
- if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) {
- setMaxListeners(100, signal)
- } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) {
- setMaxListeners(100, signal)
- }
- } catch {}
+/***/ 20181:
+/***/ ((module) => {
- util.addAbortListener(signal, abort)
- requestFinalizer.register(ac, { signal, abort })
- }
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer");
- // 30. Set this’s headers to a new Headers object with this’s relevant
- // Realm, whose header list is request’s header list and guard is
- // "request".
- this[kHeaders] = new Headers(kConstruct)
- this[kHeaders][kHeadersList] = request.headersList
- this[kHeaders][kGuard] = 'request'
- this[kHeaders][kRealm] = this[kRealm]
+/***/ }),
- // 31. If this’s request’s mode is "no-cors", then:
- if (mode === 'no-cors') {
- // 1. If this’s request’s method is not a CORS-safelisted method,
- // then throw a TypeError.
- if (!corsSafeListedMethodsSet.has(request.method)) {
- throw new TypeError(
- `'${request.method} is unsupported in no-cors mode.`
- )
- }
+/***/ 35317:
+/***/ ((module) => {
- // 2. Set this’s headers’s guard to "request-no-cors".
- this[kHeaders][kGuard] = 'request-no-cors'
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process");
- // 32. If init is not empty, then:
- if (initHasKey) {
- /** @type {HeadersList} */
- const headersList = this[kHeaders][kHeadersList]
- // 1. Let headers be a copy of this’s headers and its associated header
- // list.
- // 2. If init["headers"] exists, then set headers to init["headers"].
- const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList)
+/***/ }),
- // 3. Empty this’s headers’s header list.
- headersList.clear()
+/***/ 64236:
+/***/ ((module) => {
- // 4. If headers is a Headers object, then for each header in its header
- // list, append header’s name/header’s value to this’s headers.
- if (headers instanceof HeadersList) {
- for (const [key, val] of headers) {
- headersList.append(key, val)
- }
- // Note: Copy the `set-cookie` meta-data.
- headersList.cookies = headers.cookies
- } else {
- // 5. Otherwise, fill this’s headers with headers.
- fillHeaders(this[kHeaders], headers)
- }
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console");
- // 33. Let inputBody be input’s request’s body if input is a Request
- // object; otherwise null.
- const inputBody = input instanceof Request ? input[kState].body : null
+/***/ }),
- // 34. If either init["body"] exists and is non-null or inputBody is
- // non-null, and request’s method is `GET` or `HEAD`, then throw a
- // TypeError.
- if (
- (init.body != null || inputBody != null) &&
- (request.method === 'GET' || request.method === 'HEAD')
- ) {
- throw new TypeError('Request with GET/HEAD method cannot have body.')
- }
+/***/ 76982:
+/***/ ((module) => {
- // 35. Let initBody be null.
- let initBody = null
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto");
- // 36. If init["body"] exists and is non-null, then:
- if (init.body != null) {
- // 1. Let Content-Type be null.
- // 2. Set initBody and Content-Type to the result of extracting
- // init["body"], with keepalive set to request’s keepalive.
- const [extractedBody, contentType] = extractBody(
- init.body,
- request.keepalive
- )
- initBody = extractedBody
+/***/ }),
- // 3, If Content-Type is non-null and this’s headers’s header list does
- // not contain `Content-Type`, then append `Content-Type`/Content-Type to
- // this’s headers.
- if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) {
- this[kHeaders].append('content-type', contentType)
- }
- }
+/***/ 31637:
+/***/ ((module) => {
- // 37. Let inputOrInitBody be initBody if it is non-null; otherwise
- // inputBody.
- const inputOrInitBody = initBody ?? inputBody
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel");
- // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is
- // null, then:
- if (inputOrInitBody != null && inputOrInitBody.source == null) {
- // 1. If initBody is non-null and init["duplex"] does not exist,
- // then throw a TypeError.
- if (initBody != null && init.duplex == null) {
- throw new TypeError('RequestInit: duplex option is required when sending a body.')
- }
+/***/ }),
- // 2. If this’s request’s mode is neither "same-origin" nor "cors",
- // then throw a TypeError.
- if (request.mode !== 'same-origin' && request.mode !== 'cors') {
- throw new TypeError(
- 'If request is made from ReadableStream, mode should be "same-origin" or "cors"'
- )
- }
+/***/ 24434:
+/***/ ((module) => {
- // 3. Set this’s request’s use-CORS-preflight flag.
- request.useCORSPreflightFlag = true
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events");
- // 39. Let finalBody be inputOrInitBody.
- let finalBody = inputOrInitBody
+/***/ }),
- // 40. If initBody is null and inputBody is non-null, then:
- if (initBody == null && inputBody != null) {
- // 1. If input is unusable, then throw a TypeError.
- if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) {
- throw new TypeError(
- 'Cannot construct a Request with a Request object that has already been used.'
- )
- }
+/***/ 79896:
+/***/ ((module) => {
- // 2. Set finalBody to the result of creating a proxy for inputBody.
- if (!TransformStream) {
- TransformStream = (__nccwpck_require__(63774).TransformStream)
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");
- // https://streams.spec.whatwg.org/#readablestream-create-a-proxy
- const identityTransform = new TransformStream()
- inputBody.stream.pipeThrough(identityTransform)
- finalBody = {
- source: inputBody.source,
- length: inputBody.length,
- stream: identityTransform.readable
- }
- }
+/***/ }),
- // 41. Set this’s request’s body to finalBody.
- this[kState].body = finalBody
- }
+/***/ 58611:
+/***/ ((module) => {
- // Returns request’s HTTP method, which is "GET" by default.
- get method () {
- webidl.brandCheck(this, Request)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http");
- // The method getter steps are to return this’s request’s method.
- return this[kState].method
- }
+/***/ }),
- // Returns the URL of request as a string.
- get url () {
- webidl.brandCheck(this, Request)
+/***/ 85675:
+/***/ ((module) => {
- // The url getter steps are to return this’s request’s URL, serialized.
- return URLSerializer(this[kState].url)
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2");
- // Returns a Headers object consisting of the headers associated with request.
- // Note that headers added in the network layer by the user agent will not
- // be accounted for in this object, e.g., the "Host" header.
- get headers () {
- webidl.brandCheck(this, Request)
+/***/ }),
- // The headers getter steps are to return this’s headers.
- return this[kHeaders]
- }
+/***/ 65692:
+/***/ ((module) => {
- // Returns the kind of resource requested by request, e.g., "document"
- // or "script".
- get destination () {
- webidl.brandCheck(this, Request)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https");
- // The destination getter are to return this’s request’s destination.
- return this[kState].destination
- }
+/***/ }),
- // Returns the referrer of request. Its value can be a same-origin URL if
- // explicitly set in init, the empty string to indicate no referrer, and
- // "about:client" when defaulting to the global’s default. This is used
- // during fetching to determine the value of the `Referer` header of the
- // request being made.
- get referrer () {
- webidl.brandCheck(this, Request)
+/***/ 69278:
+/***/ ((module) => {
- // 1. If this’s request’s referrer is "no-referrer", then return the
- // empty string.
- if (this[kState].referrer === 'no-referrer') {
- return ''
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net");
- // 2. If this’s request’s referrer is "client", then return
- // "about:client".
- if (this[kState].referrer === 'client') {
- return 'about:client'
- }
+/***/ }),
- // Return this’s request’s referrer, serialized.
- return this[kState].referrer.toString()
- }
+/***/ 4573:
+/***/ ((module) => {
- // Returns the referrer policy associated with request.
- // This is used during fetching to compute the value of the request’s
- // referrer.
- get referrerPolicy () {
- webidl.brandCheck(this, Request)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer");
- // The referrerPolicy getter steps are to return this’s request’s referrer policy.
- return this[kState].referrerPolicy
- }
+/***/ }),
- // Returns the mode associated with request, which is a string indicating
- // whether the request will use CORS, or will be restricted to same-origin
- // URLs.
- get mode () {
- webidl.brandCheck(this, Request)
+/***/ 78474:
+/***/ ((module) => {
- // The mode getter steps are to return this’s request’s mode.
- return this[kState].mode
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events");
- // Returns the credentials mode associated with request,
- // which is a string indicating whether credentials will be sent with the
- // request always, never, or only when sent to a same-origin URL.
- get credentials () {
- // The credentials getter steps are to return this’s request’s credentials mode.
- return this[kState].credentials
- }
+/***/ }),
- // Returns the cache mode associated with request,
- // which is a string indicating how the request will
- // interact with the browser’s cache when fetching.
- get cache () {
- webidl.brandCheck(this, Request)
+/***/ 37067:
+/***/ ((module) => {
- // The cache getter steps are to return this’s request’s cache mode.
- return this[kState].cache
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http");
- // Returns the redirect mode associated with request,
- // which is a string indicating how redirects for the
- // request will be handled during fetching. A request
- // will follow redirects by default.
- get redirect () {
- webidl.brandCheck(this, Request)
+/***/ }),
- // The redirect getter steps are to return this’s request’s redirect mode.
- return this[kState].redirect
- }
+/***/ 44708:
+/***/ ((module) => {
- // Returns request’s subresource integrity metadata, which is a
- // cryptographic hash of the resource being fetched. Its value
- // consists of multiple hashes separated by whitespace. [SRI]
- get integrity () {
- webidl.brandCheck(this, Request)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:https");
- // The integrity getter steps are to return this’s request’s integrity
- // metadata.
- return this[kState].integrity
- }
+/***/ }),
- // Returns a boolean indicating whether or not request can outlive the
- // global in which it was created.
- get keepalive () {
- webidl.brandCheck(this, Request)
+/***/ 48161:
+/***/ ((module) => {
- // The keepalive getter steps are to return this’s request’s keepalive.
- return this[kState].keepalive
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:os");
- // Returns a boolean indicating whether or not request is for a reload
- // navigation.
- get isReloadNavigation () {
- webidl.brandCheck(this, Request)
+/***/ }),
- // The isReloadNavigation getter steps are to return true if this’s
- // request’s reload-navigation flag is set; otherwise false.
- return this[kState].reloadNavigation
- }
+/***/ 1708:
+/***/ ((module) => {
- // Returns a boolean indicating whether or not request is for a history
- // navigation (a.k.a. back-foward navigation).
- get isHistoryNavigation () {
- webidl.brandCheck(this, Request)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:process");
- // The isHistoryNavigation getter steps are to return true if this’s request’s
- // history-navigation flag is set; otherwise false.
- return this[kState].historyNavigation
- }
+/***/ }),
- // Returns the signal associated with request, which is an AbortSignal
- // object indicating whether or not request has been aborted, and its
- // abort event handler.
- get signal () {
- webidl.brandCheck(this, Request)
+/***/ 57075:
+/***/ ((module) => {
- // The signal getter steps are to return this’s signal.
- return this[kSignal]
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream");
- get body () {
- webidl.brandCheck(this, Request)
+/***/ }),
- return this[kState].body ? this[kState].body.stream : null
- }
+/***/ 57975:
+/***/ ((module) => {
- get bodyUsed () {
- webidl.brandCheck(this, Request)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util");
- return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
- }
+/***/ }),
- get duplex () {
- webidl.brandCheck(this, Request)
+/***/ 38522:
+/***/ ((module) => {
- return 'half'
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:zlib");
- // Returns a clone of request.
- clone () {
- webidl.brandCheck(this, Request)
+/***/ }),
- // 1. If this is unusable, then throw a TypeError.
- if (this.bodyUsed || this.body?.locked) {
- throw new TypeError('unusable')
- }
+/***/ 70857:
+/***/ ((module) => {
- // 2. Let clonedRequest be the result of cloning this’s request.
- const clonedRequest = cloneRequest(this[kState])
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os");
- // 3. Let clonedRequestObject be the result of creating a Request object,
- // given clonedRequest, this’s headers’s guard, and this’s relevant Realm.
- const clonedRequestObject = new Request(kConstruct)
- clonedRequestObject[kState] = clonedRequest
- clonedRequestObject[kRealm] = this[kRealm]
- clonedRequestObject[kHeaders] = new Headers(kConstruct)
- clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList
- clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]
- clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]
+/***/ }),
- // 4. Make clonedRequestObject’s signal follow this’s signal.
- const ac = new AbortController()
- if (this.signal.aborted) {
- ac.abort(this.signal.reason)
- } else {
- util.addAbortListener(
- this.signal,
- () => {
- ac.abort(this.signal.reason)
- }
- )
- }
- clonedRequestObject[kSignal] = ac.signal
+/***/ 16928:
+/***/ ((module) => {
- // 4. Return clonedRequestObject.
- return clonedRequestObject
- }
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");
-mixinBody(Request)
+/***/ }),
-function makeRequest (init) {
- // https://fetch.spec.whatwg.org/#requests
- const request = {
- method: 'GET',
- localURLsOnly: false,
- unsafeRequest: false,
- body: null,
- client: null,
- reservedClient: null,
- replacesClientId: '',
- window: 'client',
- keepalive: false,
- serviceWorkers: 'all',
- initiator: '',
- destination: '',
- priority: null,
- origin: 'client',
- policyContainer: 'client',
- referrer: 'client',
- referrerPolicy: '',
- mode: 'no-cors',
- useCORSPreflightFlag: false,
- credentials: 'same-origin',
- useCredentials: false,
- cache: 'default',
- redirect: 'follow',
- integrity: '',
- cryptoGraphicsNonceMetadata: '',
- parserMetadata: '',
- reloadNavigation: false,
- historyNavigation: false,
- userActivation: false,
- taintedOrigin: false,
- redirectCount: 0,
- responseTainting: 'basic',
- preventNoCacheCacheControlHeaderModification: false,
- done: false,
- timingAllowFailed: false,
- ...init,
- headersList: init.headersList
- ? new HeadersList(init.headersList)
- : new HeadersList()
- }
- request.url = request.urlList[0]
- return request
-}
+/***/ 82987:
+/***/ ((module) => {
-// https://fetch.spec.whatwg.org/#concept-request-clone
-function cloneRequest (request) {
- // To clone a request request, run these steps:
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks");
- // 1. Let newRequest be a copy of request, except for its body.
- const newRequest = makeRequest({ ...request, body: null })
+/***/ }),
- // 2. If request’s body is non-null, set newRequest’s body to the
- // result of cloning request’s body.
- if (request.body != null) {
- newRequest.body = cloneBody(request.body)
- }
+/***/ 83480:
+/***/ ((module) => {
- // 3. Return newRequest.
- return newRequest
-}
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring");
-Object.defineProperties(Request.prototype, {
- method: kEnumerableProperty,
- url: kEnumerableProperty,
- headers: kEnumerableProperty,
- redirect: kEnumerableProperty,
- clone: kEnumerableProperty,
- signal: kEnumerableProperty,
- duplex: kEnumerableProperty,
- destination: kEnumerableProperty,
- body: kEnumerableProperty,
- bodyUsed: kEnumerableProperty,
- isHistoryNavigation: kEnumerableProperty,
- isReloadNavigation: kEnumerableProperty,
- keepalive: kEnumerableProperty,
- integrity: kEnumerableProperty,
- cache: kEnumerableProperty,
- credentials: kEnumerableProperty,
- attribute: kEnumerableProperty,
- referrerPolicy: kEnumerableProperty,
- referrer: kEnumerableProperty,
- mode: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'Request',
- configurable: true
- }
-})
+/***/ }),
-webidl.converters.Request = webidl.interfaceConverter(
- Request
-)
+/***/ 2203:
+/***/ ((module) => {
-// https://fetch.spec.whatwg.org/#requestinfo
-webidl.converters.RequestInfo = function (V) {
- if (typeof V === 'string') {
- return webidl.converters.USVString(V)
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream");
- if (V instanceof Request) {
- return webidl.converters.Request(V)
- }
+/***/ }),
- return webidl.converters.USVString(V)
-}
+/***/ 63774:
+/***/ ((module) => {
-webidl.converters.AbortSignal = webidl.interfaceConverter(
- AbortSignal
-)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web");
-// https://fetch.spec.whatwg.org/#requestinit
-webidl.converters.RequestInit = webidl.dictionaryConverter([
- {
- key: 'method',
- converter: webidl.converters.ByteString
- },
- {
- key: 'headers',
- converter: webidl.converters.HeadersInit
- },
- {
- key: 'body',
- converter: webidl.nullableConverter(
- webidl.converters.BodyInit
- )
- },
- {
- key: 'referrer',
- converter: webidl.converters.USVString
- },
- {
- key: 'referrerPolicy',
- converter: webidl.converters.DOMString,
- // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy
- allowedValues: referrerPolicy
- },
- {
- key: 'mode',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#concept-request-mode
- allowedValues: requestMode
- },
- {
- key: 'credentials',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestcredentials
- allowedValues: requestCredentials
- },
- {
- key: 'cache',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestcache
- allowedValues: requestCache
- },
- {
- key: 'redirect',
- converter: webidl.converters.DOMString,
- // https://fetch.spec.whatwg.org/#requestredirect
- allowedValues: requestRedirect
- },
- {
- key: 'integrity',
- converter: webidl.converters.DOMString
- },
- {
- key: 'keepalive',
- converter: webidl.converters.boolean
- },
- {
- key: 'signal',
- converter: webidl.nullableConverter(
- (signal) => webidl.converters.AbortSignal(
- signal,
- { strict: false }
- )
- )
- },
- {
- key: 'window',
- converter: webidl.converters.any
- },
- {
- key: 'duplex',
- converter: webidl.converters.DOMString,
- allowedValues: requestDuplex
- }
-])
+/***/ }),
-module.exports = { Request, makeRequest }
+/***/ 13193:
+/***/ ((module) => {
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder");
/***/ }),
-/***/ 89928:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 53557:
+/***/ ((module) => {
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers");
+/***/ }),
-const { Headers, HeadersList, fill } = __nccwpck_require__(12801)
-const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(37791)
-const util = __nccwpck_require__(89500)
-const { kEnumerableProperty } = util
-const {
- isValidReasonPhrase,
- isCancelled,
- isAborted,
- isBlobLike,
- serializeJavascriptValueToJSONString,
- isErrorLike,
- isomorphicEncode
-} = __nccwpck_require__(72847)
-const {
- redirectStatusSet,
- nullBodyStatus,
- DOMException
-} = __nccwpck_require__(21234)
-const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(63730)
-const { webidl } = __nccwpck_require__(94354)
-const { FormData } = __nccwpck_require__(47453)
-const { getGlobalOrigin } = __nccwpck_require__(62896)
-const { URLSerializer } = __nccwpck_require__(37246)
-const { kHeadersList, kConstruct } = __nccwpck_require__(68031)
-const assert = __nccwpck_require__(42613)
-const { types } = __nccwpck_require__(39023)
+/***/ 64756:
+/***/ ((module) => {
-const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(63774).ReadableStream)
-const textEncoder = new TextEncoder('utf-8')
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls");
-// https://fetch.spec.whatwg.org/#response-class
-class Response {
- // Creates network error Response.
- static error () {
- // TODO
- const relevantRealm = { settingsObject: {} }
+/***/ }),
- // The static error() method steps are to return the result of creating a
- // Response object, given a new network error, "immutable", and this’s
- // relevant Realm.
- const responseObject = new Response()
- responseObject[kState] = makeNetworkError()
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList
- responseObject[kHeaders][kGuard] = 'immutable'
- responseObject[kHeaders][kRealm] = relevantRealm
- return responseObject
- }
+/***/ 52018:
+/***/ ((module) => {
- // https://fetch.spec.whatwg.org/#dom-response-json
- static json (data, init = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' })
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty");
- if (init !== null) {
- init = webidl.converters.ResponseInit(init)
- }
+/***/ }),
- // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data.
- const bytes = textEncoder.encode(
- serializeJavascriptValueToJSONString(data)
- )
+/***/ 87016:
+/***/ ((module) => {
- // 2. Let body be the result of extracting bytes.
- const body = extractBody(bytes)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url");
- // 3. Let responseObject be the result of creating a Response object, given a new response,
- // "response", and this’s relevant Realm.
- const relevantRealm = { settingsObject: {} }
- const responseObject = new Response()
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kGuard] = 'response'
- responseObject[kHeaders][kRealm] = relevantRealm
+/***/ }),
- // 4. Perform initialize a response given responseObject, init, and (body, "application/json").
- initializeResponse(responseObject, init, { body: body[0], type: 'application/json' })
+/***/ 39023:
+/***/ ((module) => {
- // 5. Return responseObject.
- return responseObject
- }
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util");
- // Creates a redirect Response that redirects to url with status status.
- static redirect (url, status = 302) {
- const relevantRealm = { settingsObject: {} }
+/***/ }),
- webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' })
+/***/ 98253:
+/***/ ((module) => {
- url = webidl.converters.USVString(url)
- status = webidl.converters['unsigned short'](status)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types");
- // 1. Let parsedURL be the result of parsing url with current settings
- // object’s API base URL.
- // 2. If parsedURL is failure, then throw a TypeError.
- // TODO: base-URL?
- let parsedURL
- try {
- parsedURL = new URL(url, getGlobalOrigin())
- } catch (err) {
- throw Object.assign(new TypeError('Failed to parse URL from ' + url), {
- cause: err
- })
- }
+/***/ }),
- // 3. If status is not a redirect status, then throw a RangeError.
- if (!redirectStatusSet.has(status)) {
- throw new RangeError('Invalid status code ' + status)
- }
+/***/ 28167:
+/***/ ((module) => {
- // 4. Let responseObject be the result of creating a Response object,
- // given a new response, "immutable", and this’s relevant Realm.
- const responseObject = new Response()
- responseObject[kRealm] = relevantRealm
- responseObject[kHeaders][kGuard] = 'immutable'
- responseObject[kHeaders][kRealm] = relevantRealm
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads");
- // 5. Set responseObject’s response’s status to status.
- responseObject[kState].status = status
+/***/ }),
- // 6. Let value be parsedURL, serialized and isomorphic encoded.
- const value = isomorphicEncode(URLSerializer(parsedURL))
+/***/ 43106:
+/***/ ((module) => {
- // 7. Append `Location`/value to responseObject’s response’s header list.
- responseObject[kState].headersList.append('location', value)
+module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib");
- // 8. Return responseObject.
- return responseObject
- }
+/***/ }),
- // https://fetch.spec.whatwg.org/#dom-response
- constructor (body = null, init = {}) {
- if (body !== null) {
- body = webidl.converters.BodyInit(body)
+/***/ 85276:
+/***/ ((__unused_webpack_module, exports) => {
+
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AbortError = void 0;
+/**
+ * This error is thrown when an asynchronous operation has been aborted.
+ * Check for this error by testing the `name` that the name property of the
+ * error matches `"AbortError"`.
+ *
+ * @example
+ * ```ts
+ * const controller = new AbortController();
+ * controller.abort();
+ * try {
+ * doAsyncWork(controller.signal)
+ * } catch (e) {
+ * if (e.name === 'AbortError') {
+ * // handle abort error here.
+ * }
+ * }
+ * ```
+ */
+class AbortError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "AbortError";
}
+}
+exports.AbortError = AbortError;
+//# sourceMappingURL=AbortError.js.map
- init = webidl.converters.ResponseInit(init)
+/***/ }),
- // TODO
- this[kRealm] = { settingsObject: {} }
+/***/ 92242:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 1. Set this’s response to a new response.
- this[kState] = makeResponse({})
- // 2. Set this’s headers to a new Headers object with this’s relevant
- // Realm, whose header list is this’s response’s header list and guard
- // is "response".
- this[kHeaders] = new Headers(kConstruct)
- this[kHeaders][kGuard] = 'response'
- this[kHeaders][kHeadersList] = this[kState].headersList
- this[kHeaders][kRealm] = this[kRealm]
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AbortError = void 0;
+var AbortError_js_1 = __nccwpck_require__(85276);
+Object.defineProperty(exports, "AbortError", ({ enumerable: true, get: function () { return AbortError_js_1.AbortError; } }));
+//# sourceMappingURL=index.js.map
- // 3. Let bodyWithType be null.
- let bodyWithType = null
+/***/ }),
- // 4. If body is non-null, then set bodyWithType to the result of extracting body.
- if (body != null) {
- const [extractedBody, type] = extractBody(body)
- bodyWithType = { body: extractedBody, type }
+/***/ 21746:
+/***/ ((__unused_webpack_module, exports) => {
+
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureKeyCredential = void 0;
+/**
+ * A static-key-based credential that supports updating
+ * the underlying key value.
+ */
+class AzureKeyCredential {
+ /**
+ * The value of the key to be used in authentication
+ */
+ get key() {
+ return this._key;
+ }
+ /**
+ * Create an instance of an AzureKeyCredential for use
+ * with a service client.
+ *
+ * @param key - The initial value of the key to use in authentication
+ */
+ constructor(key) {
+ if (!key) {
+ throw new Error("key must be a non-empty string");
+ }
+ this._key = key;
+ }
+ /**
+ * Change the value of the key.
+ *
+ * Updates will take effect upon the next request after
+ * updating the key value.
+ *
+ * @param newKey - The new key value to be used
+ */
+ update(newKey) {
+ this._key = newKey;
}
+}
+exports.AzureKeyCredential = AzureKeyCredential;
+//# sourceMappingURL=azureKeyCredential.js.map
- // 5. Perform initialize a response given this, init, and bodyWithType.
- initializeResponse(this, init, bodyWithType)
- }
+/***/ }),
- // Returns response’s type, e.g., "cors".
- get type () {
- webidl.brandCheck(this, Response)
+/***/ 37859:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // The type getter steps are to return this’s response’s type.
- return this[kState].type
- }
- // Returns response’s URL, if it has one; otherwise the empty string.
- get url () {
- webidl.brandCheck(this, Response)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureNamedKeyCredential = void 0;
+exports.isNamedKeyCredential = isNamedKeyCredential;
+const core_util_1 = __nccwpck_require__(30991);
+/**
+ * A static name/key-based credential that supports updating
+ * the underlying name and key values.
+ */
+class AzureNamedKeyCredential {
+ /**
+ * The value of the key to be used in authentication.
+ */
+ get key() {
+ return this._key;
+ }
+ /**
+ * The value of the name to be used in authentication.
+ */
+ get name() {
+ return this._name;
+ }
+ /**
+ * Create an instance of an AzureNamedKeyCredential for use
+ * with a service client.
+ *
+ * @param name - The initial value of the name to use in authentication.
+ * @param key - The initial value of the key to use in authentication.
+ */
+ constructor(name, key) {
+ if (!name || !key) {
+ throw new TypeError("name and key must be non-empty strings");
+ }
+ this._name = name;
+ this._key = key;
+ }
+ /**
+ * Change the value of the key.
+ *
+ * Updates will take effect upon the next request after
+ * updating the key value.
+ *
+ * @param newName - The new name value to be used.
+ * @param newKey - The new key value to be used.
+ */
+ update(newName, newKey) {
+ if (!newName || !newKey) {
+ throw new TypeError("newName and newKey must be non-empty strings");
+ }
+ this._name = newName;
+ this._key = newKey;
+ }
+}
+exports.AzureNamedKeyCredential = AzureNamedKeyCredential;
+/**
+ * Tests an object to determine whether it implements NamedKeyCredential.
+ *
+ * @param credential - The assumed NamedKeyCredential to be tested.
+ */
+function isNamedKeyCredential(credential) {
+ return ((0, core_util_1.isObjectWithProperties)(credential, ["name", "key"]) &&
+ typeof credential.key === "string" &&
+ typeof credential.name === "string");
+}
+//# sourceMappingURL=azureNamedKeyCredential.js.map
+
+/***/ }),
- const urlList = this[kState].urlList
+/***/ 52372:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // The url getter steps are to return the empty string if this’s
- // response’s URL is null; otherwise this’s response’s URL,
- // serialized with exclude fragment set to true.
- const url = urlList[urlList.length - 1] ?? null
- if (url === null) {
- return ''
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureSASCredential = void 0;
+exports.isSASCredential = isSASCredential;
+const core_util_1 = __nccwpck_require__(30991);
+/**
+ * A static-signature-based credential that supports updating
+ * the underlying signature value.
+ */
+class AzureSASCredential {
+ /**
+ * The value of the shared access signature to be used in authentication
+ */
+ get signature() {
+ return this._signature;
}
+ /**
+ * Create an instance of an AzureSASCredential for use
+ * with a service client.
+ *
+ * @param signature - The initial value of the shared access signature to use in authentication
+ */
+ constructor(signature) {
+ if (!signature) {
+ throw new Error("shared access signature must be a non-empty string");
+ }
+ this._signature = signature;
+ }
+ /**
+ * Change the value of the signature.
+ *
+ * Updates will take effect upon the next request after
+ * updating the signature value.
+ *
+ * @param newSignature - The new shared access signature value to be used
+ */
+ update(newSignature) {
+ if (!newSignature) {
+ throw new Error("shared access signature must be a non-empty string");
+ }
+ this._signature = newSignature;
+ }
+}
+exports.AzureSASCredential = AzureSASCredential;
+/**
+ * Tests an object to determine whether it implements SASCredential.
+ *
+ * @param credential - The assumed SASCredential to be tested.
+ */
+function isSASCredential(credential) {
+ return ((0, core_util_1.isObjectWithProperties)(credential, ["signature"]) && typeof credential.signature === "string");
+}
+//# sourceMappingURL=azureSASCredential.js.map
- return URLSerializer(url, true)
- }
-
- // Returns whether response was obtained through a redirect.
- get redirected () {
- webidl.brandCheck(this, Response)
+/***/ }),
- // The redirected getter steps are to return true if this’s response’s URL
- // list has more than one item; otherwise false.
- return this[kState].urlList.length > 1
- }
+/***/ 15269:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // Returns response’s status.
- get status () {
- webidl.brandCheck(this, Response)
- // The status getter steps are to return this’s response’s status.
- return this[kState].status
- }
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isTokenCredential = exports.isSASCredential = exports.AzureSASCredential = exports.isNamedKeyCredential = exports.AzureNamedKeyCredential = exports.isKeyCredential = exports.AzureKeyCredential = void 0;
+var azureKeyCredential_js_1 = __nccwpck_require__(21746);
+Object.defineProperty(exports, "AzureKeyCredential", ({ enumerable: true, get: function () { return azureKeyCredential_js_1.AzureKeyCredential; } }));
+var keyCredential_js_1 = __nccwpck_require__(67415);
+Object.defineProperty(exports, "isKeyCredential", ({ enumerable: true, get: function () { return keyCredential_js_1.isKeyCredential; } }));
+var azureNamedKeyCredential_js_1 = __nccwpck_require__(37859);
+Object.defineProperty(exports, "AzureNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.AzureNamedKeyCredential; } }));
+Object.defineProperty(exports, "isNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.isNamedKeyCredential; } }));
+var azureSASCredential_js_1 = __nccwpck_require__(52372);
+Object.defineProperty(exports, "AzureSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.AzureSASCredential; } }));
+Object.defineProperty(exports, "isSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.isSASCredential; } }));
+var tokenCredential_js_1 = __nccwpck_require__(64381);
+Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, get: function () { return tokenCredential_js_1.isTokenCredential; } }));
+//# sourceMappingURL=index.js.map
- // Returns whether response’s status is an ok status.
- get ok () {
- webidl.brandCheck(this, Response)
+/***/ }),
- // The ok getter steps are to return true if this’s response’s status is an
- // ok status; otherwise false.
- return this[kState].status >= 200 && this[kState].status <= 299
- }
+/***/ 67415:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // Returns response’s status message.
- get statusText () {
- webidl.brandCheck(this, Response)
- // The statusText getter steps are to return this’s response’s status
- // message.
- return this[kState].statusText
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isKeyCredential = isKeyCredential;
+const core_util_1 = __nccwpck_require__(30991);
+/**
+ * Tests an object to determine whether it implements KeyCredential.
+ *
+ * @param credential - The assumed KeyCredential to be tested.
+ */
+function isKeyCredential(credential) {
+ return (0, core_util_1.isObjectWithProperties)(credential, ["key"]) && typeof credential.key === "string";
+}
+//# sourceMappingURL=keyCredential.js.map
- // Returns response’s headers as Headers.
- get headers () {
- webidl.brandCheck(this, Response)
+/***/ }),
- // The headers getter steps are to return this’s headers.
- return this[kHeaders]
- }
+/***/ 64381:
+/***/ ((__unused_webpack_module, exports) => {
- get body () {
- webidl.brandCheck(this, Response)
- return this[kState].body ? this[kState].body.stream : null
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isBearerToken = isBearerToken;
+exports.isPopToken = isPopToken;
+exports.isTokenCredential = isTokenCredential;
+/**
+ * @internal
+ * @param accessToken - Access token
+ * @returns Whether a token is bearer type or not
+ */
+function isBearerToken(accessToken) {
+ return !accessToken.tokenType || accessToken.tokenType === "Bearer";
+}
+/**
+ * @internal
+ * @param accessToken - Access token
+ * @returns Whether a token is Pop token or not
+ */
+function isPopToken(accessToken) {
+ return accessToken.tokenType === "pop";
+}
+/**
+ * Tests an object to determine whether it implements TokenCredential.
+ *
+ * @param credential - The assumed TokenCredential to be tested.
+ */
+function isTokenCredential(credential) {
+ // Check for an object with a 'getToken' function and possibly with
+ // a 'signRequest' function. We do this check to make sure that
+ // a ServiceClientCredentials implementor (like TokenClientCredentials
+ // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
+ // it doesn't actually implement TokenCredential also.
+ const castCredential = credential;
+ return (castCredential &&
+ typeof castCredential.getToken === "function" &&
+ (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
+}
+//# sourceMappingURL=tokenCredential.js.map
- get bodyUsed () {
- webidl.brandCheck(this, Response)
+/***/ }),
- return !!this[kState].body && util.isDisturbed(this[kState].body.stream)
- }
+/***/ 85110:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // Returns a clone of response.
- clone () {
- webidl.brandCheck(this, Response)
- // 1. If this is unusable, then throw a TypeError.
- if (this.bodyUsed || (this.body && this.body.locked)) {
- throw webidl.errors.exception({
- header: 'Response.clone',
- message: 'Body has already been consumed.'
- })
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.authorizeRequestOnClaimChallenge = exports.parseCAEChallenge = void 0;
+const log_js_1 = __nccwpck_require__(75630);
+const base64_js_1 = __nccwpck_require__(59793);
+/**
+ * Converts: `Bearer a="b", c="d", Bearer d="e", f="g"`.
+ * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.
+ *
+ * @internal
+ */
+function parseCAEChallenge(challenges) {
+ const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x);
+ return bearerChallenges.map((challenge) => {
+ const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x);
+ const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="')));
+ // Key-value pairs to plain object:
+ return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
+ });
+}
+exports.parseCAEChallenge = parseCAEChallenge;
+/**
+ * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:
+ * [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).
+ *
+ * Call the `bearerTokenAuthenticationPolicy` with the following options:
+ *
+ * ```ts
+ * import { bearerTokenAuthenticationPolicy } from "@azure/core-rest-pipeline";
+ * import { authorizeRequestOnClaimChallenge } from "@azure/core-client";
+ *
+ * const bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy({
+ * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge
+ * });
+ * ```
+ *
+ * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.
+ * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.
+ *
+ * Example challenge with claims:
+ *
+ * ```
+ * Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
+ * error_description="User session has been revoked",
+ * claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
+ * ```
+ */
+async function authorizeRequestOnClaimChallenge(onChallengeOptions) {
+ const { scopes, response } = onChallengeOptions;
+ const logger = onChallengeOptions.logger || log_js_1.logger;
+ const challenge = response.headers.get("WWW-Authenticate");
+ if (!challenge) {
+ logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`);
+ return false;
}
-
- // 2. Let clonedResponse be the result of cloning this’s response.
- const clonedResponse = cloneResponse(this[kState])
-
- // 3. Return the result of creating a Response object, given
- // clonedResponse, this’s headers’s guard, and this’s relevant Realm.
- const clonedResponseObject = new Response()
- clonedResponseObject[kState] = clonedResponse
- clonedResponseObject[kRealm] = this[kRealm]
- clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList
- clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]
- clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]
-
- return clonedResponseObject
- }
+ const challenges = parseCAEChallenge(challenge) || [];
+ const parsedChallenge = challenges.find((x) => x.claims);
+ if (!parsedChallenge) {
+ logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`);
+ return false;
+ }
+ const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, {
+ claims: (0, base64_js_1.decodeStringToString)(parsedChallenge.claims),
+ });
+ if (!accessToken) {
+ return false;
+ }
+ onChallengeOptions.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
+ return true;
}
+exports.authorizeRequestOnClaimChallenge = authorizeRequestOnClaimChallenge;
+//# sourceMappingURL=authorizeRequestOnClaimChallenge.js.map
-mixinBody(Response)
-
-Object.defineProperties(Response.prototype, {
- type: kEnumerableProperty,
- url: kEnumerableProperty,
- status: kEnumerableProperty,
- ok: kEnumerableProperty,
- redirected: kEnumerableProperty,
- statusText: kEnumerableProperty,
- headers: kEnumerableProperty,
- clone: kEnumerableProperty,
- body: kEnumerableProperty,
- bodyUsed: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'Response',
- configurable: true
- }
-})
-
-Object.defineProperties(Response, {
- json: kEnumerableProperty,
- redirect: kEnumerableProperty,
- error: kEnumerableProperty
-})
-
-// https://fetch.spec.whatwg.org/#concept-response-clone
-function cloneResponse (response) {
- // To clone a response response, run these steps:
-
- // 1. If response is a filtered response, then return a new identical
- // filtered response whose internal response is a clone of response’s
- // internal response.
- if (response.internalResponse) {
- return filterResponse(
- cloneResponse(response.internalResponse),
- response.type
- )
- }
+/***/ }),
- // 2. Let newResponse be a copy of response, except for its body.
- const newResponse = makeResponse({ ...response, body: null })
+/***/ 75794:
+/***/ ((__unused_webpack_module, exports) => {
- // 3. If response’s body is non-null, then set newResponse’s body to the
- // result of cloning response’s body.
- if (response.body != null) {
- newResponse.body = cloneBody(response.body)
- }
- // 4. Return newResponse.
- return newResponse
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.authorizeRequestOnTenantChallenge = void 0;
+/**
+ * A set of constants used internally when processing requests.
+ */
+const Constants = {
+ DefaultScope: "/.default",
+ /**
+ * Defines constants for use with HTTP headers.
+ */
+ HeaderConstants: {
+ /**
+ * The Authorization header.
+ */
+ AUTHORIZATION: "authorization",
+ },
+};
+function isUuid(text) {
+ return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text);
}
-
-function makeResponse (init) {
- return {
- aborted: false,
- rangeRequested: false,
- timingAllowPassed: false,
- requestIncludesCredentials: false,
- type: 'default',
- status: 200,
- timingInfo: null,
- cacheState: '',
- statusText: '',
- ...init,
- headersList: init.headersList
- ? new HeadersList(init.headersList)
- : new HeadersList(),
- urlList: init.urlList ? [...init.urlList] : []
- }
+/**
+ * Defines a callback to handle auth challenge for Storage APIs.
+ * This implements the bearer challenge process described here: https://docs.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge
+ * Handling has specific features for storage that departs to the general AAD challenge docs.
+ **/
+const authorizeRequestOnTenantChallenge = async (challengeOptions) => {
+ const requestOptions = requestToOptions(challengeOptions.request);
+ const challenge = getChallenge(challengeOptions.response);
+ if (challenge) {
+ const challengeInfo = parseChallenge(challenge);
+ const challengeScopes = buildScopes(challengeOptions, challengeInfo);
+ const tenantId = extractTenantId(challengeInfo);
+ if (!tenantId) {
+ return false;
+ }
+ const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId }));
+ if (!accessToken) {
+ return false;
+ }
+ challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}`);
+ return true;
+ }
+ return false;
+};
+exports.authorizeRequestOnTenantChallenge = authorizeRequestOnTenantChallenge;
+/**
+ * Extracts the tenant id from the challenge information
+ * The tenant id is contained in the authorization_uri as the first
+ * path part.
+ */
+function extractTenantId(challengeInfo) {
+ const parsedAuthUri = new URL(challengeInfo.authorization_uri);
+ const pathSegments = parsedAuthUri.pathname.split("/");
+ const tenantId = pathSegments[1];
+ if (tenantId && isUuid(tenantId)) {
+ return tenantId;
+ }
+ return undefined;
}
-
-function makeNetworkError (reason) {
- const isError = isErrorLike(reason)
- return makeResponse({
- type: 'error',
- status: 0,
- error: isError
- ? reason
- : new Error(reason ? String(reason) : reason),
- aborted: reason && reason.name === 'AbortError'
- })
+/**
+ * Builds the authentication scopes based on the information that comes in the
+ * challenge information. Scopes url is present in the resource_id, if it is empty
+ * we keep using the original scopes.
+ */
+function buildScopes(challengeOptions, challengeInfo) {
+ if (!challengeInfo.resource_id) {
+ return challengeOptions.scopes;
+ }
+ const challengeScopes = new URL(challengeInfo.resource_id);
+ challengeScopes.pathname = Constants.DefaultScope;
+ let scope = challengeScopes.toString();
+ if (scope === "https://disk.azure.com/.default") {
+ // the extra slash is required by the service
+ scope = "https://disk.azure.com//.default";
+ }
+ return [scope];
}
-
-function makeFilteredResponse (response, state) {
- state = {
- internalResponse: response,
- ...state
- }
-
- return new Proxy(response, {
- get (target, p) {
- return p in state ? state[p] : target[p]
- },
- set (target, p, value) {
- assert(!(p in state))
- target[p] = value
- return true
+/**
+ * We will retrieve the challenge only if the response status code was 401,
+ * and if the response contained the header "WWW-Authenticate" with a non-empty value.
+ */
+function getChallenge(response) {
+ const challenge = response.headers.get("WWW-Authenticate");
+ if (response.status === 401 && challenge) {
+ return challenge;
}
- })
+ return;
}
+/**
+ * Converts: `Bearer a="b" c="d"`.
+ * Into: `[ { a: 'b', c: 'd' }]`.
+ *
+ * @internal
+ */
+function parseChallenge(challenge) {
+ const bearerChallenge = challenge.slice("Bearer ".length);
+ const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x);
+ const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("=")));
+ // Key-value pairs to plain object:
+ return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
+}
+/**
+ * Extracts the options form a Pipeline Request for later re-use
+ */
+function requestToOptions(request) {
+ return {
+ abortSignal: request.abortSignal,
+ requestOptions: {
+ timeout: request.timeout,
+ },
+ tracingOptions: request.tracingOptions,
+ };
+}
+//# sourceMappingURL=authorizeRequestOnTenantChallenge.js.map
-// https://fetch.spec.whatwg.org/#concept-filtered-response
-function filterResponse (response, type) {
- // Set response to the following filtered response with response as its
- // internal response, depending on request’s response tainting:
- if (type === 'basic') {
- // A basic filtered response is a filtered response whose type is "basic"
- // and header list excludes any headers in internal response’s header list
- // whose name is a forbidden response-header name.
-
- // Note: undici does not implement forbidden response-header names
- return makeFilteredResponse(response, {
- type: 'basic',
- headersList: response.headersList
- })
- } else if (type === 'cors') {
- // A CORS filtered response is a filtered response whose type is "cors"
- // and header list excludes any headers in internal response’s header
- // list whose name is not a CORS-safelisted response-header name, given
- // internal response’s CORS-exposed header-name list.
+/***/ }),
- // Note: undici does not implement CORS-safelisted response-header names
- return makeFilteredResponse(response, {
- type: 'cors',
- headersList: response.headersList
- })
- } else if (type === 'opaque') {
- // An opaque filtered response is a filtered response whose type is
- // "opaque", URL list is the empty list, status is 0, status message
- // is the empty byte sequence, header list is empty, and body is null.
+/***/ 59793:
+/***/ ((__unused_webpack_module, exports) => {
- return makeFilteredResponse(response, {
- type: 'opaque',
- urlList: Object.freeze([]),
- status: 0,
- statusText: '',
- body: null
- })
- } else if (type === 'opaqueredirect') {
- // An opaque-redirect filtered response is a filtered response whose type
- // is "opaqueredirect", status is 0, status message is the empty byte
- // sequence, header list is empty, and body is null.
- return makeFilteredResponse(response, {
- type: 'opaqueredirect',
- status: 0,
- statusText: '',
- headersList: [],
- body: null
- })
- } else {
- assert(false)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.decodeStringToString = exports.decodeString = exports.encodeByteArray = exports.encodeString = void 0;
+/**
+ * Encodes a string in base64 format.
+ * @param value - the string to encode
+ * @internal
+ */
+function encodeString(value) {
+ return Buffer.from(value).toString("base64");
}
-
-// https://fetch.spec.whatwg.org/#appropriate-network-error
-function makeAppropriateNetworkError (fetchParams, err = null) {
- // 1. Assert: fetchParams is canceled.
- assert(isCancelled(fetchParams))
-
- // 2. Return an aborted network error if fetchParams is aborted;
- // otherwise return a network error.
- return isAborted(fetchParams)
- ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err }))
- : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err }))
+exports.encodeString = encodeString;
+/**
+ * Encodes a byte array in base64 format.
+ * @param value - the Uint8Aray to encode
+ * @internal
+ */
+function encodeByteArray(value) {
+ const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer);
+ return bufferValue.toString("base64");
}
+exports.encodeByteArray = encodeByteArray;
+/**
+ * Decodes a base64 string into a byte array.
+ * @param value - the base64 string to decode
+ * @internal
+ */
+function decodeString(value) {
+ return Buffer.from(value, "base64");
+}
+exports.decodeString = decodeString;
+/**
+ * Decodes a base64 string into a string.
+ * @param value - the base64 string to decode
+ * @internal
+ */
+function decodeStringToString(value) {
+ return Buffer.from(value, "base64").toString();
+}
+exports.decodeStringToString = decodeStringToString;
+//# sourceMappingURL=base64.js.map
-// https://whatpr.org/fetch/1392.html#initialize-a-response
-function initializeResponse (response, init, body) {
- // 1. If init["status"] is not in the range 200 to 599, inclusive, then
- // throw a RangeError.
- if (init.status !== null && (init.status < 200 || init.status > 599)) {
- throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.')
- }
-
- // 2. If init["statusText"] does not match the reason-phrase token production,
- // then throw a TypeError.
- if ('statusText' in init && init.statusText != null) {
- // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2:
- // reason-phrase = *( HTAB / SP / VCHAR / obs-text )
- if (!isValidReasonPhrase(String(init.statusText))) {
- throw new TypeError('Invalid statusText')
- }
- }
-
- // 3. Set response’s response’s status to init["status"].
- if ('status' in init && init.status != null) {
- response[kState].status = init.status
- }
+/***/ }),
- // 4. Set response’s response’s status message to init["statusText"].
- if ('statusText' in init && init.statusText != null) {
- response[kState].statusText = init.statusText
- }
+/***/ 21795:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5. If init["headers"] exists, then fill response’s headers with init["headers"].
- if ('headers' in init && init.headers != null) {
- fill(response[kHeaders], init.headers)
- }
- // 6. If body was given, then:
- if (body) {
- // 1. If response's status is a null body status, then throw a TypeError.
- if (nullBodyStatus.includes(response.status)) {
- throw webidl.errors.exception({
- header: 'Response constructor',
- message: 'Invalid response status code ' + response.status
- })
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.deserializationPolicy = exports.deserializationPolicyName = void 0;
+const interfaces_js_1 = __nccwpck_require__(35590);
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+const serializer_js_1 = __nccwpck_require__(66774);
+const operationHelpers_js_1 = __nccwpck_require__(17036);
+const defaultJsonContentTypes = ["application/json", "text/json"];
+const defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
+/**
+ * The programmatic identifier of the deserializationPolicy.
+ */
+exports.deserializationPolicyName = "deserializationPolicy";
+/**
+ * This policy handles parsing out responses according to OperationSpecs on the request.
+ */
+function deserializationPolicy(options = {}) {
+ var _a, _b, _c, _d, _e, _f, _g;
+ const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes;
+ const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes;
+ const parseXML = options.parseXML;
+ const serializerOptions = options.serializerOptions;
+ const updatedOptions = {
+ xml: {
+ rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "",
+ includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false,
+ xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : interfaces_js_1.XML_CHARKEY,
+ },
+ };
+ return {
+ name: exports.deserializationPolicyName,
+ async sendRequest(request, next) {
+ const response = await next(request);
+ return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML);
+ },
+ };
+}
+exports.deserializationPolicy = deserializationPolicy;
+function getOperationResponseMap(parsedResponse) {
+ let result;
+ const request = parsedResponse.request;
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
+ if (operationSpec) {
+ if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) {
+ result = operationSpec.responses[parsedResponse.status];
+ }
+ else {
+ result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse);
+ }
}
-
- // 2. Set response's body to body's body.
- response[kState].body = body.body
-
- // 3. If body's type is non-null and response's header list does not contain
- // `Content-Type`, then append (`Content-Type`, body's type) to response's header list.
- if (body.type != null && !response[kState].headersList.contains('Content-Type')) {
- response[kState].headersList.append('content-type', body.type)
+ return result;
+}
+function shouldDeserializeResponse(parsedResponse) {
+ const request = parsedResponse.request;
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize;
+ let result;
+ if (shouldDeserialize === undefined) {
+ result = true;
}
- }
+ else if (typeof shouldDeserialize === "boolean") {
+ result = shouldDeserialize;
+ }
+ else {
+ result = shouldDeserialize(parsedResponse);
+ }
+ return result;
}
+async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) {
+ const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML);
+ if (!shouldDeserializeResponse(parsedResponse)) {
+ return parsedResponse;
+ }
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(parsedResponse.request);
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
+ if (!operationSpec || !operationSpec.responses) {
+ return parsedResponse;
+ }
+ const responseSpec = getOperationResponseMap(parsedResponse);
+ const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options);
+ if (error) {
+ throw error;
+ }
+ else if (shouldReturnResponse) {
+ return parsedResponse;
+ }
+ // An operation response spec does exist for current status code, so
+ // use it to deserialize the response.
+ if (responseSpec) {
+ if (responseSpec.bodyMapper) {
+ let valueToDeserialize = parsedResponse.parsedBody;
+ if (operationSpec.isXML && responseSpec.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
+ valueToDeserialize =
+ typeof valueToDeserialize === "object"
+ ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
+ : [];
+ }
+ try {
+ parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options);
+ }
+ catch (deserializeError) {
+ const restError = new core_rest_pipeline_1.RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, {
+ statusCode: parsedResponse.status,
+ request: parsedResponse.request,
+ response: parsedResponse,
+ });
+ throw restError;
+ }
+ }
+ else if (operationSpec.httpMethod === "HEAD") {
+ // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
+ parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
+ }
+ if (responseSpec.headersMapper) {
+ parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true });
+ }
+ }
+ return parsedResponse;
+}
+function isOperationSpecEmpty(operationSpec) {
+ const expectedStatusCodes = Object.keys(operationSpec.responses);
+ return (expectedStatusCodes.length === 0 ||
+ (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
+}
+function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) {
+ var _a;
+ const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;
+ const isExpectedStatusCode = isOperationSpecEmpty(operationSpec)
+ ? isSuccessByStatus
+ : !!responseSpec;
+ if (isExpectedStatusCode) {
+ if (responseSpec) {
+ if (!responseSpec.isError) {
+ return { error: null, shouldReturnResponse: false };
+ }
+ }
+ else {
+ return { error: null, shouldReturnResponse: false };
+ }
+ }
+ const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default;
+ const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status))
+ ? `Unexpected status code: ${parsedResponse.status}`
+ : parsedResponse.bodyAsText;
+ const error = new core_rest_pipeline_1.RestError(initialErrorMessage, {
+ statusCode: parsedResponse.status,
+ request: parsedResponse.request,
+ response: parsedResponse,
+ });
+ // If the item failed but there's no error spec or default spec to deserialize the error,
+ // we should fail so we just throw the parsed response
+ if (!errorResponseSpec) {
+ throw error;
+ }
+ const defaultBodyMapper = errorResponseSpec.bodyMapper;
+ const defaultHeadersMapper = errorResponseSpec.headersMapper;
+ try {
+ // If error response has a body, try to deserialize it using default body mapper.
+ // Then try to extract error code & message from it
+ if (parsedResponse.parsedBody) {
+ const parsedBody = parsedResponse.parsedBody;
+ let deserializedError;
+ if (defaultBodyMapper) {
+ let valueToDeserialize = parsedBody;
+ if (operationSpec.isXML && defaultBodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
+ valueToDeserialize = [];
+ const elementName = defaultBodyMapper.xmlElementName;
+ if (typeof parsedBody === "object" && elementName) {
+ valueToDeserialize = parsedBody[elementName];
+ }
+ }
+ deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options);
+ }
+ const internalError = parsedBody.error || deserializedError || parsedBody;
+ error.code = internalError.code;
+ if (internalError.message) {
+ error.message = internalError.message;
+ }
+ if (defaultBodyMapper) {
+ error.response.parsedBody = deserializedError;
+ }
+ }
+ // If error response has headers, try to deserialize it using default header mapper
+ if (parsedResponse.headers && defaultHeadersMapper) {
+ error.response.parsedHeaders =
+ operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders");
+ }
+ }
+ catch (defaultError) {
+ error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`;
+ }
+ return { error, shouldReturnResponse: false };
+}
+async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
+ var _a;
+ if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) &&
+ operationResponse.bodyAsText) {
+ const text = operationResponse.bodyAsText;
+ const contentType = operationResponse.headers.get("Content-Type") || "";
+ const contentComponents = !contentType
+ ? []
+ : contentType.split(";").map((component) => component.toLowerCase());
+ try {
+ if (contentComponents.length === 0 ||
+ contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) {
+ operationResponse.parsedBody = JSON.parse(text);
+ return operationResponse;
+ }
+ else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) {
+ if (!parseXML) {
+ throw new Error("Parsing XML not supported.");
+ }
+ const body = await parseXML(text, opts.xml);
+ operationResponse.parsedBody = body;
+ return operationResponse;
+ }
+ }
+ catch (err) {
+ const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;
+ const errCode = err.code || core_rest_pipeline_1.RestError.PARSE_ERROR;
+ const e = new core_rest_pipeline_1.RestError(msg, {
+ code: errCode,
+ statusCode: operationResponse.status,
+ request: operationResponse.request,
+ response: operationResponse,
+ });
+ throw e;
+ }
+ }
+ return operationResponse;
+}
+//# sourceMappingURL=deserializationPolicy.js.map
-webidl.converters.ReadableStream = webidl.interfaceConverter(
- ReadableStream
-)
-
-webidl.converters.FormData = webidl.interfaceConverter(
- FormData
-)
-
-webidl.converters.URLSearchParams = webidl.interfaceConverter(
- URLSearchParams
-)
+/***/ }),
-// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit
-webidl.converters.XMLHttpRequestBodyInit = function (V) {
- if (typeof V === 'string') {
- return webidl.converters.USVString(V)
- }
+/***/ 64663:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
- }
- if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) {
- return webidl.converters.BufferSource(V)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getCachedDefaultHttpClient = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+let cachedHttpClient;
+function getCachedDefaultHttpClient() {
+ if (!cachedHttpClient) {
+ cachedHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)();
+ }
+ return cachedHttpClient;
+}
+exports.getCachedDefaultHttpClient = getCachedDefaultHttpClient;
+//# sourceMappingURL=httpClientCache.js.map
- if (util.isFormDataLike(V)) {
- return webidl.converters.FormData(V, { strict: false })
- }
+/***/ }),
- if (V instanceof URLSearchParams) {
- return webidl.converters.URLSearchParams(V)
- }
+/***/ 6868:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- return webidl.converters.DOMString(V)
-}
-// https://fetch.spec.whatwg.org/#bodyinit
-webidl.converters.BodyInit = function (V) {
- if (V instanceof ReadableStream) {
- return webidl.converters.ReadableStream(V)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.authorizeRequestOnTenantChallenge = exports.authorizeRequestOnClaimChallenge = exports.serializationPolicyName = exports.serializationPolicy = exports.deserializationPolicyName = exports.deserializationPolicy = exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.createClientPipeline = exports.ServiceClient = exports.MapperTypeNames = exports.createSerializer = void 0;
+var serializer_js_1 = __nccwpck_require__(66774);
+Object.defineProperty(exports, "createSerializer", ({ enumerable: true, get: function () { return serializer_js_1.createSerializer; } }));
+Object.defineProperty(exports, "MapperTypeNames", ({ enumerable: true, get: function () { return serializer_js_1.MapperTypeNames; } }));
+var serviceClient_js_1 = __nccwpck_require__(22732);
+Object.defineProperty(exports, "ServiceClient", ({ enumerable: true, get: function () { return serviceClient_js_1.ServiceClient; } }));
+var pipeline_js_1 = __nccwpck_require__(64524);
+Object.defineProperty(exports, "createClientPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createClientPipeline; } }));
+var interfaces_js_1 = __nccwpck_require__(35590);
+Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_ATTRKEY; } }));
+Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_CHARKEY; } }));
+var deserializationPolicy_js_1 = __nccwpck_require__(21795);
+Object.defineProperty(exports, "deserializationPolicy", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicy; } }));
+Object.defineProperty(exports, "deserializationPolicyName", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicyName; } }));
+var serializationPolicy_js_1 = __nccwpck_require__(87054);
+Object.defineProperty(exports, "serializationPolicy", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicy; } }));
+Object.defineProperty(exports, "serializationPolicyName", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicyName; } }));
+var authorizeRequestOnClaimChallenge_js_1 = __nccwpck_require__(85110);
+Object.defineProperty(exports, "authorizeRequestOnClaimChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnClaimChallenge_js_1.authorizeRequestOnClaimChallenge; } }));
+var authorizeRequestOnTenantChallenge_js_1 = __nccwpck_require__(75794);
+Object.defineProperty(exports, "authorizeRequestOnTenantChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnTenantChallenge_js_1.authorizeRequestOnTenantChallenge; } }));
+//# sourceMappingURL=index.js.map
- // Note: the spec doesn't include async iterables,
- // this is an undici extension.
- if (V?.[Symbol.asyncIterator]) {
- return V
- }
+/***/ }),
- return webidl.converters.XMLHttpRequestBodyInit(V)
-}
+/***/ 91030:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-webidl.converters.ResponseInit = webidl.dictionaryConverter([
- {
- key: 'status',
- converter: webidl.converters['unsigned short'],
- defaultValue: 200
- },
- {
- key: 'statusText',
- converter: webidl.converters.ByteString,
- defaultValue: ''
- },
- {
- key: 'headers',
- converter: webidl.converters.HeadersInit
- }
-])
-module.exports = {
- makeNetworkError,
- makeResponse,
- makeAppropriateNetworkError,
- filterResponse,
- Response,
- cloneResponse
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getPathStringFromParameter = exports.getStreamingResponseStatusCodes = void 0;
+const serializer_js_1 = __nccwpck_require__(66774);
+/**
+ * Gets the list of status codes for streaming responses.
+ * @internal
+ */
+function getStreamingResponseStatusCodes(operationSpec) {
+ const result = new Set();
+ for (const statusCode in operationSpec.responses) {
+ const operationResponse = operationSpec.responses[statusCode];
+ if (operationResponse.bodyMapper &&
+ operationResponse.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Stream) {
+ result.add(Number(statusCode));
+ }
+ }
+ return result;
}
-
+exports.getStreamingResponseStatusCodes = getStreamingResponseStatusCodes;
+/**
+ * Get the path to this parameter's value as a dotted string (a.b.c).
+ * @param parameter - The parameter to get the path string for.
+ * @returns The path to this parameter's value as a dotted string.
+ * @internal
+ */
+function getPathStringFromParameter(parameter) {
+ const { parameterPath, mapper } = parameter;
+ let result;
+ if (typeof parameterPath === "string") {
+ result = parameterPath;
+ }
+ else if (Array.isArray(parameterPath)) {
+ result = parameterPath.join(".");
+ }
+ else {
+ result = mapper.serializedName;
+ }
+ return result;
+}
+exports.getPathStringFromParameter = getPathStringFromParameter;
+//# sourceMappingURL=interfaceHelpers.js.map
/***/ }),
-/***/ 63730:
-/***/ ((module) => {
-
-
+/***/ 35590:
+/***/ ((__unused_webpack_module, exports) => {
-module.exports = {
- kUrl: Symbol('url'),
- kHeaders: Symbol('headers'),
- kSignal: Symbol('signal'),
- kState: Symbol('state'),
- kGuard: Symbol('guard'),
- kRealm: Symbol('realm')
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0;
+/**
+ * Default key used to access the XML attributes.
+ */
+exports.XML_ATTRKEY = "$";
+/**
+ * Default key used to access the XML value content.
+ */
+exports.XML_CHARKEY = "_";
+//# sourceMappingURL=interfaces.js.map
/***/ }),
-/***/ 72847:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 75630:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logger = void 0;
+const logger_1 = __nccwpck_require__(50143);
+exports.logger = (0, logger_1.createClientLogger)("core-client");
+//# sourceMappingURL=log.js.map
-const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(21234)
-const { getGlobalOrigin } = __nccwpck_require__(62896)
-const { performance } = __nccwpck_require__(82987)
-const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(89500)
-const assert = __nccwpck_require__(42613)
-const { isUint8Array } = __nccwpck_require__(98253)
+/***/ }),
-let supportedHashes = []
+/***/ 17036:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable
-/** @type {import('crypto')|undefined} */
-let crypto
-try {
- crypto = __nccwpck_require__(76982)
- const possibleRelevantHashes = ['sha256', 'sha384', 'sha512']
- supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash))
-/* c8 ignore next 3 */
-} catch {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getOperationRequestInfo = exports.getOperationArgumentValueFromParameter = void 0;
+const state_js_1 = __nccwpck_require__(35077);
+/**
+ * @internal
+ * Retrieves the value to use for a given operation argument
+ * @param operationArguments - The arguments passed from the generated client
+ * @param parameter - The parameter description
+ * @param fallbackObject - If something isn't found in the arguments bag, look here.
+ * Generally used to look at the service client properties.
+ */
+function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) {
+ let parameterPath = parameter.parameterPath;
+ const parameterMapper = parameter.mapper;
+ let value;
+ if (typeof parameterPath === "string") {
+ parameterPath = [parameterPath];
+ }
+ if (Array.isArray(parameterPath)) {
+ if (parameterPath.length > 0) {
+ if (parameterMapper.isConstant) {
+ value = parameterMapper.defaultValue;
+ }
+ else {
+ let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
+ if (!propertySearchResult.propertyFound && fallbackObject) {
+ propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath);
+ }
+ let useDefaultValue = false;
+ if (!propertySearchResult.propertyFound) {
+ useDefaultValue =
+ parameterMapper.required ||
+ (parameterPath[0] === "options" && parameterPath.length === 2);
+ }
+ value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
+ }
+ }
+ }
+ else {
+ if (parameterMapper.required) {
+ value = {};
+ }
+ for (const propertyName in parameterPath) {
+ const propertyMapper = parameterMapper.type.modelProperties[propertyName];
+ const propertyPath = parameterPath[propertyName];
+ const propertyValue = getOperationArgumentValueFromParameter(operationArguments, {
+ parameterPath: propertyPath,
+ mapper: propertyMapper,
+ }, fallbackObject);
+ if (propertyValue !== undefined) {
+ if (!value) {
+ value = {};
+ }
+ value[propertyName] = propertyValue;
+ }
+ }
+ }
+ return value;
}
-
-function responseURL (response) {
- // https://fetch.spec.whatwg.org/#responses
- // A response has an associated URL. It is a pointer to the last URL
- // in response’s URL list and null if response’s URL list is empty.
- const urlList = response.urlList
- const length = urlList.length
- return length === 0 ? null : urlList[length - 1].toString()
+exports.getOperationArgumentValueFromParameter = getOperationArgumentValueFromParameter;
+function getPropertyFromParameterPath(parent, parameterPath) {
+ const result = { propertyFound: false };
+ let i = 0;
+ for (; i < parameterPath.length; ++i) {
+ const parameterPathPart = parameterPath[i];
+ // Make sure to check inherited properties too, so don't use hasOwnProperty().
+ if (parent && parameterPathPart in parent) {
+ parent = parent[parameterPathPart];
+ }
+ else {
+ break;
+ }
+ }
+ if (i === parameterPath.length) {
+ result.propertyValue = parent;
+ result.propertyFound = true;
+ }
+ return result;
}
+const originalRequestSymbol = Symbol.for("@azure/core-client original request");
+function hasOriginalRequest(request) {
+ return originalRequestSymbol in request;
+}
+function getOperationRequestInfo(request) {
+ if (hasOriginalRequest(request)) {
+ return getOperationRequestInfo(request[originalRequestSymbol]);
+ }
+ let info = state_js_1.state.operationRequestMap.get(request);
+ if (!info) {
+ info = {};
+ state_js_1.state.operationRequestMap.set(request, info);
+ }
+ return info;
+}
+exports.getOperationRequestInfo = getOperationRequestInfo;
+//# sourceMappingURL=operationHelpers.js.map
-// https://fetch.spec.whatwg.org/#concept-response-location-url
-function responseLocationURL (response, requestFragment) {
- // 1. If response’s status is not a redirect status, then return null.
- if (!redirectStatusSet.has(response.status)) {
- return null
- }
-
- // 2. Let location be the result of extracting header list values given
- // `Location` and response’s header list.
- let location = response.headersList.get('location')
+/***/ }),
- // 3. If location is a header value, then set location to the result of
- // parsing location with response’s URL.
- if (location !== null && isValidHeaderValue(location)) {
- location = new URL(location, responseURL(response))
- }
+/***/ 64524:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 4. If location is a URL whose fragment is null, then set location’s
- // fragment to requestFragment.
- if (location && !location.hash) {
- location.hash = requestFragment
- }
- // 5. Return location.
- return location
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createClientPipeline = void 0;
+const deserializationPolicy_js_1 = __nccwpck_require__(21795);
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+const serializationPolicy_js_1 = __nccwpck_require__(87054);
+/**
+ * Creates a new Pipeline for use with a Service Client.
+ * Adds in deserializationPolicy by default.
+ * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential.
+ * @param options - Options to customize the created pipeline.
+ */
+function createClientPipeline(options = {}) {
+ const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options !== null && options !== void 0 ? options : {});
+ if (options.credentialOptions) {
+ pipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({
+ credential: options.credentialOptions.credential,
+ scopes: options.credentialOptions.credentialScopes,
+ }));
+ }
+ pipeline.addPolicy((0, serializationPolicy_js_1.serializationPolicy)(options.serializationOptions), { phase: "Serialize" });
+ pipeline.addPolicy((0, deserializationPolicy_js_1.deserializationPolicy)(options.deserializationOptions), {
+ phase: "Deserialize",
+ });
+ return pipeline;
}
+exports.createClientPipeline = createClientPipeline;
+//# sourceMappingURL=pipeline.js.map
-/** @returns {URL} */
-function requestCurrentURL (request) {
- return request.urlList[request.urlList.length - 1]
-}
+/***/ }),
-function requestBadPort (request) {
- // 1. Let url be request’s current URL.
- const url = requestCurrentURL(request)
+/***/ 87054:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port,
- // then return blocked.
- if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) {
- return 'blocked'
- }
- // 3. Return allowed.
- return 'allowed'
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.serializeRequestBody = exports.serializeHeaders = exports.serializationPolicy = exports.serializationPolicyName = void 0;
+const interfaces_js_1 = __nccwpck_require__(35590);
+const operationHelpers_js_1 = __nccwpck_require__(17036);
+const serializer_js_1 = __nccwpck_require__(66774);
+const interfaceHelpers_js_1 = __nccwpck_require__(91030);
+/**
+ * The programmatic identifier of the serializationPolicy.
+ */
+exports.serializationPolicyName = "serializationPolicy";
+/**
+ * This policy handles assembling the request body and headers using
+ * an OperationSpec and OperationArguments on the request.
+ */
+function serializationPolicy(options = {}) {
+ const stringifyXML = options.stringifyXML;
+ return {
+ name: exports.serializationPolicyName,
+ async sendRequest(request, next) {
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
+ const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments;
+ if (operationSpec && operationArguments) {
+ serializeHeaders(request, operationArguments, operationSpec);
+ serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);
+ }
+ return next(request);
+ },
+ };
}
-
-function isErrorLike (object) {
- return object instanceof Error || (
- object?.constructor?.name === 'Error' ||
- object?.constructor?.name === 'DOMException'
- )
+exports.serializationPolicy = serializationPolicy;
+/**
+ * @internal
+ */
+function serializeHeaders(request, operationArguments, operationSpec) {
+ var _a, _b;
+ if (operationSpec.headerParameters) {
+ for (const headerParameter of operationSpec.headerParameters) {
+ let headerValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, headerParameter);
+ if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {
+ headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter));
+ const headerCollectionPrefix = headerParameter.mapper
+ .headerCollectionPrefix;
+ if (headerCollectionPrefix) {
+ for (const key of Object.keys(headerValue)) {
+ request.headers.set(headerCollectionPrefix + key, headerValue[key]);
+ }
+ }
+ else {
+ request.headers.set(headerParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter), headerValue);
+ }
+ }
+ }
+ }
+ const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders;
+ if (customHeaders) {
+ for (const customHeaderName of Object.keys(customHeaders)) {
+ request.headers.set(customHeaderName, customHeaders[customHeaderName]);
+ }
+ }
+}
+exports.serializeHeaders = serializeHeaders;
+/**
+ * @internal
+ */
+function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () {
+ throw new Error("XML serialization unsupported!");
+}) {
+ var _a, _b, _c, _d, _e;
+ const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions;
+ const updatedOptions = {
+ xml: {
+ rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "",
+ includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false,
+ xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : interfaces_js_1.XML_CHARKEY,
+ },
+ };
+ const xmlCharKey = updatedOptions.xml.xmlCharKey;
+ if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
+ request.body = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, operationSpec.requestBody);
+ const bodyMapper = operationSpec.requestBody.mapper;
+ const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper;
+ const typeName = bodyMapper.type.name;
+ try {
+ if ((request.body !== undefined && request.body !== null) ||
+ (nullable && request.body === null) ||
+ required) {
+ const requestBodyParameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(operationSpec.requestBody);
+ request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions);
+ const isStream = typeName === serializer_js_1.MapperTypeNames.Stream;
+ if (operationSpec.isXML) {
+ const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
+ const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions);
+ if (typeName === serializer_js_1.MapperTypeNames.Sequence) {
+ request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey });
+ }
+ else if (!isStream) {
+ request.body = stringifyXML(value, {
+ rootName: xmlName || serializedName,
+ xmlCharKey,
+ });
+ }
+ }
+ else if (typeName === serializer_js_1.MapperTypeNames.String &&
+ (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) {
+ // the String serializer has validated that request body is a string
+ // so just send the string.
+ return;
+ }
+ else if (!isStream) {
+ request.body = JSON.stringify(request.body);
+ }
+ }
+ }
+ catch (error) {
+ throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`);
+ }
+ }
+ else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
+ request.formData = {};
+ for (const formDataParameter of operationSpec.formDataParameters) {
+ const formDataParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, formDataParameter);
+ if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
+ const formDataParameterPropertyName = formDataParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter);
+ request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter), updatedOptions);
+ }
+ }
+ }
+}
+exports.serializeRequestBody = serializeRequestBody;
+/**
+ * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself
+ */
+function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) {
+ // Composite and Sequence schemas already got their root namespace set during serialization
+ // We just need to add xmlns to the other schema types
+ if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
+ const result = {};
+ result[options.xml.xmlCharKey] = serializedValue;
+ result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
+ return result;
+ }
+ return serializedValue;
+}
+function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) {
+ if (!Array.isArray(obj)) {
+ obj = [obj];
+ }
+ if (!xmlNamespaceKey || !xmlNamespace) {
+ return { [elementName]: obj };
+ }
+ const result = { [elementName]: obj };
+ result[interfaces_js_1.XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
+ return result;
}
+//# sourceMappingURL=serializationPolicy.js.map
-// Check whether |statusText| is a ByteString and
-// matches the Reason-Phrase token production.
-// RFC 2616: https://tools.ietf.org/html/rfc2616
-// RFC 7230: https://tools.ietf.org/html/rfc7230
-// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )"
-// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116
-function isValidReasonPhrase (statusText) {
- for (let i = 0; i < statusText.length; ++i) {
- const c = statusText.charCodeAt(i)
- if (
- !(
- (
- c === 0x09 || // HTAB
- (c >= 0x20 && c <= 0x7e) || // SP / VCHAR
- (c >= 0x80 && c <= 0xff)
- ) // obs-text
- )
- ) {
- return false
+/***/ }),
+
+/***/ 66774:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.MapperTypeNames = exports.createSerializer = void 0;
+const tslib_1 = __nccwpck_require__(94176);
+const base64 = tslib_1.__importStar(__nccwpck_require__(59793));
+const interfaces_js_1 = __nccwpck_require__(35590);
+const utils_js_1 = __nccwpck_require__(7805);
+class SerializerImpl {
+ constructor(modelMappers = {}, isXML = false) {
+ this.modelMappers = modelMappers;
+ this.isXML = isXML;
+ }
+ /**
+ * @deprecated Removing the constraints validation on client side.
+ */
+ validateConstraints(mapper, value, objectName) {
+ const failValidation = (constraintName, constraintValue) => {
+ throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`);
+ };
+ if (mapper.constraints && value !== undefined && value !== null) {
+ const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints;
+ if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {
+ failValidation("ExclusiveMaximum", ExclusiveMaximum);
+ }
+ if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {
+ failValidation("ExclusiveMinimum", ExclusiveMinimum);
+ }
+ if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {
+ failValidation("InclusiveMaximum", InclusiveMaximum);
+ }
+ if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {
+ failValidation("InclusiveMinimum", InclusiveMinimum);
+ }
+ if (MaxItems !== undefined && value.length > MaxItems) {
+ failValidation("MaxItems", MaxItems);
+ }
+ if (MaxLength !== undefined && value.length > MaxLength) {
+ failValidation("MaxLength", MaxLength);
+ }
+ if (MinItems !== undefined && value.length < MinItems) {
+ failValidation("MinItems", MinItems);
+ }
+ if (MinLength !== undefined && value.length < MinLength) {
+ failValidation("MinLength", MinLength);
+ }
+ if (MultipleOf !== undefined && value % MultipleOf !== 0) {
+ failValidation("MultipleOf", MultipleOf);
+ }
+ if (Pattern) {
+ const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
+ if (typeof value !== "string" || value.match(pattern) === null) {
+ failValidation("Pattern", Pattern);
+ }
+ }
+ if (UniqueItems &&
+ value.some((item, i, ar) => ar.indexOf(item) !== i)) {
+ failValidation("UniqueItems", UniqueItems);
+ }
+ }
+ }
+ /**
+ * Serialize the given object based on its metadata defined in the mapper
+ *
+ * @param mapper - The mapper which defines the metadata of the serializable object
+ *
+ * @param object - A valid Javascript object to be serialized
+ *
+ * @param objectName - Name of the serialized object
+ *
+ * @param options - additional options to serialization
+ *
+ * @returns A valid serialized Javascript object
+ */
+ serialize(mapper, object, objectName, options = { xml: {} }) {
+ var _a, _b, _c;
+ const updatedOptions = {
+ xml: {
+ rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
+ includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
+ xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
+ },
+ };
+ let payload = {};
+ const mapperType = mapper.type.name;
+ if (!objectName) {
+ objectName = mapper.serializedName;
+ }
+ if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = [];
+ }
+ if (mapper.isConstant) {
+ object = mapper.defaultValue;
+ }
+ // This table of allowed values should help explain
+ // the mapper.required and mapper.nullable properties.
+ // X means "neither undefined or null are allowed".
+ // || required
+ // || true | false
+ // nullable || ==========================
+ // true || null | undefined/null
+ // false || X | undefined
+ // undefined || X | undefined/null
+ const { required, nullable } = mapper;
+ if (required && nullable && object === undefined) {
+ throw new Error(`${objectName} cannot be undefined.`);
+ }
+ if (required && !nullable && (object === undefined || object === null)) {
+ throw new Error(`${objectName} cannot be null or undefined.`);
+ }
+ if (!required && nullable === false && object === null) {
+ throw new Error(`${objectName} cannot be null.`);
+ }
+ if (object === undefined || object === null) {
+ payload = object;
+ }
+ else {
+ if (mapperType.match(/^any$/i) !== null) {
+ payload = object;
+ }
+ else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
+ payload = serializeBasicTypes(mapperType, objectName, object);
+ }
+ else if (mapperType.match(/^Enum$/i) !== null) {
+ const enumMapper = mapper;
+ payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
+ }
+ else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
+ payload = serializeDateTypes(mapperType, object, objectName);
+ }
+ else if (mapperType.match(/^ByteArray$/i) !== null) {
+ payload = serializeByteArrayType(objectName, object);
+ }
+ else if (mapperType.match(/^Base64Url$/i) !== null) {
+ payload = serializeBase64UrlType(objectName, object);
+ }
+ else if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ else if (mapperType.match(/^Dictionary$/i) !== null) {
+ payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ else if (mapperType.match(/^Composite$/i) !== null) {
+ payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
+ }
+ }
+ return payload;
+ }
+ /**
+ * Deserialize the given object based on its metadata defined in the mapper
+ *
+ * @param mapper - The mapper which defines the metadata of the serializable object
+ *
+ * @param responseBody - A valid Javascript entity to be deserialized
+ *
+ * @param objectName - Name of the deserialized object
+ *
+ * @param options - Controls behavior of XML parser and builder.
+ *
+ * @returns A valid deserialized Javascript object
+ */
+ deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
+ var _a, _b, _c, _d;
+ const updatedOptions = {
+ xml: {
+ rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
+ includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
+ xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
+ },
+ ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false,
+ };
+ if (responseBody === undefined || responseBody === null) {
+ if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
+ // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
+ // between the list being empty versus being missing,
+ // so let's do the more user-friendly thing and return an empty list.
+ responseBody = [];
+ }
+ // specifically check for undefined as default value can be a falsey value `0, "", false, null`
+ if (mapper.defaultValue !== undefined) {
+ responseBody = mapper.defaultValue;
+ }
+ return responseBody;
+ }
+ let payload;
+ const mapperType = mapper.type.name;
+ if (!objectName) {
+ objectName = mapper.serializedName;
+ }
+ if (mapperType.match(/^Composite$/i) !== null) {
+ payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ else {
+ if (this.isXML) {
+ const xmlCharKey = updatedOptions.xml.xmlCharKey;
+ /**
+ * If the mapper specifies this as a non-composite type value but the responseBody contains
+ * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties,
+ * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property.
+ */
+ if (responseBody[interfaces_js_1.XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {
+ responseBody = responseBody[xmlCharKey];
+ }
+ }
+ if (mapperType.match(/^Number$/i) !== null) {
+ payload = parseFloat(responseBody);
+ if (isNaN(payload)) {
+ payload = responseBody;
+ }
+ }
+ else if (mapperType.match(/^Boolean$/i) !== null) {
+ if (responseBody === "true") {
+ payload = true;
+ }
+ else if (responseBody === "false") {
+ payload = false;
+ }
+ else {
+ payload = responseBody;
+ }
+ }
+ else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
+ payload = responseBody;
+ }
+ else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
+ payload = new Date(responseBody);
+ }
+ else if (mapperType.match(/^UnixTime$/i) !== null) {
+ payload = unixTimeToDate(responseBody);
+ }
+ else if (mapperType.match(/^ByteArray$/i) !== null) {
+ payload = base64.decodeString(responseBody);
+ }
+ else if (mapperType.match(/^Base64Url$/i) !== null) {
+ payload = base64UrlToByteArray(responseBody);
+ }
+ else if (mapperType.match(/^Sequence$/i) !== null) {
+ payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ else if (mapperType.match(/^Dictionary$/i) !== null) {
+ payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions);
+ }
+ }
+ if (mapper.isConstant) {
+ payload = mapper.defaultValue;
+ }
+ return payload;
}
- }
- return true
}
-
/**
- * @see https://tools.ietf.org/html/rfc7230#section-3.2.6
- * @param {number} c
+ * Method that creates and returns a Serializer.
+ * @param modelMappers - Known models to map
+ * @param isXML - If XML should be supported
*/
-function isTokenCharCode (c) {
- switch (c) {
- case 0x22:
- case 0x28:
- case 0x29:
- case 0x2c:
- case 0x2f:
- case 0x3a:
- case 0x3b:
- case 0x3c:
- case 0x3d:
- case 0x3e:
- case 0x3f:
- case 0x40:
- case 0x5b:
- case 0x5c:
- case 0x5d:
- case 0x7b:
- case 0x7d:
- // DQUOTE and "(),/:;<=>?@[\]{}"
- return false
- default:
- // VCHAR %x21-7E
- return c >= 0x21 && c <= 0x7e
- }
+function createSerializer(modelMappers = {}, isXML = false) {
+ return new SerializerImpl(modelMappers, isXML);
}
-
-/**
- * @param {string} characters
- */
-function isValidHTTPToken (characters) {
- if (characters.length === 0) {
- return false
- }
- for (let i = 0; i < characters.length; ++i) {
- if (!isTokenCharCode(characters.charCodeAt(i))) {
- return false
+exports.createSerializer = createSerializer;
+function trimEnd(str, ch) {
+ let len = str.length;
+ while (len - 1 >= 0 && str[len - 1] === ch) {
+ --len;
}
- }
- return true
+ return str.substr(0, len);
}
-
-/**
- * @see https://fetch.spec.whatwg.org/#header-name
- * @param {string} potentialValue
- */
-function isValidHeaderName (potentialValue) {
- return isValidHTTPToken(potentialValue)
+function bufferToBase64Url(buffer) {
+ if (!buffer) {
+ return undefined;
+ }
+ if (!(buffer instanceof Uint8Array)) {
+ throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
+ }
+ // Uint8Array to Base64.
+ const str = base64.encodeByteArray(buffer);
+ // Base64 to Base64Url.
+ return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
}
-
-/**
- * @see https://fetch.spec.whatwg.org/#header-value
- * @param {string} potentialValue
- */
-function isValidHeaderValue (potentialValue) {
- // - Has no leading or trailing HTTP tab or space bytes.
- // - Contains no 0x00 (NUL) or HTTP newline bytes.
- if (
- potentialValue.startsWith('\t') ||
- potentialValue.startsWith(' ') ||
- potentialValue.endsWith('\t') ||
- potentialValue.endsWith(' ')
- ) {
- return false
- }
-
- if (
- potentialValue.includes('\0') ||
- potentialValue.includes('\r') ||
- potentialValue.includes('\n')
- ) {
- return false
- }
-
- return true
+function base64UrlToByteArray(str) {
+ if (!str) {
+ return undefined;
+ }
+ if (str && typeof str.valueOf() !== "string") {
+ throw new Error("Please provide an input of type string for converting to Uint8Array");
+ }
+ // Base64Url to Base64.
+ str = str.replace(/-/g, "+").replace(/_/g, "/");
+ // Base64 to Uint8Array.
+ return base64.decodeString(str);
}
-
-// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect
-function setRequestReferrerPolicyOnRedirect (request, actualResponse) {
- // Given a request request and a response actualResponse, this algorithm
- // updates request’s referrer policy according to the Referrer-Policy
- // header (if any) in actualResponse.
-
- // 1. Let policy be the result of executing § 8.1 Parse a referrer policy
- // from a Referrer-Policy header on actualResponse.
-
- // 8.1 Parse a referrer policy from a Referrer-Policy header
- // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list.
- const { headersList } = actualResponse
- // 2. Let policy be the empty string.
- // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token.
- // 4. Return policy.
- const policyHeader = (headersList.get('referrer-policy') ?? '').split(',')
-
- // Note: As the referrer-policy can contain multiple policies
- // separated by comma, we need to loop through all of them
- // and pick the first valid one.
- // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy
- let policy = ''
- if (policyHeader.length > 0) {
- // The right-most policy takes precedence.
- // The left-most policy is the fallback.
- for (let i = policyHeader.length; i !== 0; i--) {
- const token = policyHeader[i - 1].trim()
- if (referrerPolicyTokens.has(token)) {
- policy = token
- break
- }
+function splitSerializeName(prop) {
+ const classes = [];
+ let partialclass = "";
+ if (prop) {
+ const subwords = prop.split(".");
+ for (const item of subwords) {
+ if (item.charAt(item.length - 1) === "\\") {
+ partialclass += item.substr(0, item.length - 1) + ".";
+ }
+ else {
+ partialclass += item;
+ classes.push(partialclass);
+ partialclass = "";
+ }
+ }
}
- }
-
- // 2. If policy is not the empty string, then set request’s referrer policy to policy.
- if (policy !== '') {
- request.referrerPolicy = policy
- }
+ return classes;
}
-
-// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check
-function crossOriginResourcePolicyCheck () {
- // TODO
- return 'allowed'
+function dateToUnixTime(d) {
+ if (!d) {
+ return undefined;
+ }
+ if (typeof d.valueOf() === "string") {
+ d = new Date(d);
+ }
+ return Math.floor(d.getTime() / 1000);
}
-
-// https://fetch.spec.whatwg.org/#concept-cors-check
-function corsCheck () {
- // TODO
- return 'success'
+function unixTimeToDate(n) {
+ if (!n) {
+ return undefined;
+ }
+ return new Date(n * 1000);
}
-
-// https://fetch.spec.whatwg.org/#concept-tao-check
-function TAOCheck () {
- // TODO
- return 'success'
+function serializeBasicTypes(typeName, objectName, value) {
+ if (value !== null && value !== undefined) {
+ if (typeName.match(/^Number$/i) !== null) {
+ if (typeof value !== "number") {
+ throw new Error(`${objectName} with value ${value} must be of type number.`);
+ }
+ }
+ else if (typeName.match(/^String$/i) !== null) {
+ if (typeof value.valueOf() !== "string") {
+ throw new Error(`${objectName} with value "${value}" must be of type string.`);
+ }
+ }
+ else if (typeName.match(/^Uuid$/i) !== null) {
+ if (!(typeof value.valueOf() === "string" && (0, utils_js_1.isValidUuid)(value))) {
+ throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`);
+ }
+ }
+ else if (typeName.match(/^Boolean$/i) !== null) {
+ if (typeof value !== "boolean") {
+ throw new Error(`${objectName} with value ${value} must be of type boolean.`);
+ }
+ }
+ else if (typeName.match(/^Stream$/i) !== null) {
+ const objectType = typeof value;
+ if (objectType !== "string" &&
+ typeof value.pipe !== "function" && // NodeJS.ReadableStream
+ typeof value.tee !== "function" && // browser ReadableStream
+ !(value instanceof ArrayBuffer) &&
+ !ArrayBuffer.isView(value) &&
+ // File objects count as a type of Blob, so we want to use instanceof explicitly
+ !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) &&
+ objectType !== "function") {
+ throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`);
+ }
+ }
+ }
+ return value;
}
-
-function appendFetchMetadata (httpRequest) {
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header
- // TODO
-
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header
-
- // 1. Assert: r’s url is a potentially trustworthy URL.
- // TODO
-
- // 2. Let header be a Structured Header whose value is a token.
- let header = null
-
- // 3. Set header’s value to r’s mode.
- header = httpRequest.mode
-
- // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list.
- httpRequest.headersList.set('sec-fetch-mode', header)
-
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header
- // TODO
-
- // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header
- // TODO
+function serializeEnumType(objectName, allowedValues, value) {
+ if (!allowedValues) {
+ throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);
+ }
+ const isPresent = allowedValues.some((item) => {
+ if (typeof item.valueOf() === "string") {
+ return item.toLowerCase() === value.toLowerCase();
+ }
+ return item === value;
+ });
+ if (!isPresent) {
+ throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`);
+ }
+ return value;
}
-
-// https://fetch.spec.whatwg.org/#append-a-request-origin-header
-function appendRequestOriginHeader (request) {
- // 1. Let serializedOrigin be the result of byte-serializing a request origin with request.
- let serializedOrigin = request.origin
-
- // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list.
- if (request.responseTainting === 'cors' || request.mode === 'websocket') {
- if (serializedOrigin) {
- request.headersList.append('origin', serializedOrigin)
+function serializeByteArrayType(objectName, value) {
+ if (value !== undefined && value !== null) {
+ if (!(value instanceof Uint8Array)) {
+ throw new Error(`${objectName} must be of type Uint8Array.`);
+ }
+ value = base64.encodeByteArray(value);
+ }
+ return value;
+}
+function serializeBase64UrlType(objectName, value) {
+ if (value !== undefined && value !== null) {
+ if (!(value instanceof Uint8Array)) {
+ throw new Error(`${objectName} must be of type Uint8Array.`);
+ }
+ value = bufferToBase64Url(value);
+ }
+ return value;
+}
+function serializeDateTypes(typeName, value, objectName) {
+ if (value !== undefined && value !== null) {
+ if (typeName.match(/^Date$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
+ }
+ value =
+ value instanceof Date
+ ? value.toISOString().substring(0, 10)
+ : new Date(value).toISOString().substring(0, 10);
+ }
+ else if (typeName.match(/^DateTime$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
+ }
+ value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
+ }
+ else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
+ }
+ value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
+ }
+ else if (typeName.match(/^UnixTime$/i) !== null) {
+ if (!(value instanceof Date ||
+ (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
+ throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +
+ `for it to be serialized in UnixTime/Epoch format.`);
+ }
+ value = dateToUnixTime(value);
+ }
+ else if (typeName.match(/^TimeSpan$/i) !== null) {
+ if (!(0, utils_js_1.isDuration)(value)) {
+ throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`);
+ }
+ }
+ }
+ return value;
+}
+function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) {
+ var _a;
+ if (!Array.isArray(object)) {
+ throw new Error(`${objectName} must be of type Array.`);
}
-
- // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then:
- } else if (request.method !== 'GET' && request.method !== 'HEAD') {
- // 1. Switch on request’s referrer policy:
- switch (request.referrerPolicy) {
- case 'no-referrer':
- // Set serializedOrigin to `null`.
- serializedOrigin = null
- break
- case 'no-referrer-when-downgrade':
- case 'strict-origin':
- case 'strict-origin-when-cross-origin':
- // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`.
- if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) {
- serializedOrigin = null
+ let elementType = mapper.type.element;
+ if (!elementType || typeof elementType !== "object") {
+ throw new Error(`element" metadata for an Array must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}.`);
+ }
+ // Quirk: Composite mappers referenced by `element` might
+ // not have *all* properties declared (like uberParent),
+ // so let's try to look up the full definition by name.
+ if (elementType.type.name === "Composite" && elementType.type.className) {
+ elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType;
+ }
+ const tempArray = [];
+ for (let i = 0; i < object.length; i++) {
+ const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
+ if (isXml && elementType.xmlNamespace) {
+ const xmlnsKey = elementType.xmlNamespacePrefix
+ ? `xmlns:${elementType.xmlNamespacePrefix}`
+ : "xmlns";
+ if (elementType.type.name === "Composite") {
+ tempArray[i] = Object.assign({}, serializedValue);
+ tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
+ }
+ else {
+ tempArray[i] = {};
+ tempArray[i][options.xml.xmlCharKey] = serializedValue;
+ tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
+ }
}
- break
- case 'same-origin':
- // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`.
- if (!sameOrigin(request, requestCurrentURL(request))) {
- serializedOrigin = null
+ else {
+ tempArray[i] = serializedValue;
}
- break
- default:
- // Do nothing.
}
-
- if (serializedOrigin) {
- // 2. Append (`Origin`, serializedOrigin) to request’s header list.
- request.headersList.append('origin', serializedOrigin)
+ return tempArray;
+}
+function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) {
+ if (typeof object !== "object") {
+ throw new Error(`${objectName} must be of type object.`);
}
- }
+ const valueType = mapper.type.value;
+ if (!valueType || typeof valueType !== "object") {
+ throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}.`);
+ }
+ const tempDictionary = {};
+ for (const key of Object.keys(object)) {
+ const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
+ // If the element needs an XML namespace we need to add it within the $ property
+ tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
+ }
+ // Add the namespace to the root element if needed
+ if (isXml && mapper.xmlNamespace) {
+ const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
+ const result = tempDictionary;
+ result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
+ return result;
+ }
+ return tempDictionary;
}
-
-function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) {
- // TODO
- return performance.now()
+/**
+ * Resolves the additionalProperties property from a referenced mapper
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ * @param objectName - name of the object being serialized
+ */
+function resolveAdditionalProperties(serializer, mapper, objectName) {
+ const additionalProperties = mapper.type.additionalProperties;
+ if (!additionalProperties && mapper.type.className) {
+ const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
+ return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties;
+ }
+ return additionalProperties;
}
-
-// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info
-function createOpaqueTimingInfo (timingInfo) {
- return {
- startTime: timingInfo.startTime ?? 0,
- redirectStartTime: 0,
- redirectEndTime: 0,
- postRedirectStartTime: timingInfo.startTime ?? 0,
- finalServiceWorkerStartTime: 0,
- finalNetworkResponseStartTime: 0,
- finalNetworkRequestStartTime: 0,
- endTime: 0,
- encodedBodySize: 0,
- decodedBodySize: 0,
- finalConnectionTimingInfo: null
- }
+/**
+ * Finds the mapper referenced by className
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ * @param objectName - name of the object being serialized
+ */
+function resolveReferencedMapper(serializer, mapper, objectName) {
+ const className = mapper.type.className;
+ if (!className) {
+ throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`);
+ }
+ return serializer.modelMappers[className];
}
-
-// https://html.spec.whatwg.org/multipage/origin.html#policy-container
-function makePolicyContainer () {
- // Note: the fetch spec doesn't make use of embedder policy or CSP list
- return {
- referrerPolicy: 'strict-origin-when-cross-origin'
- }
+/**
+ * Resolves a composite mapper's modelProperties.
+ * @param serializer - the serializer containing the entire set of mappers
+ * @param mapper - the composite mapper to resolve
+ */
+function resolveModelProperties(serializer, mapper, objectName) {
+ let modelProps = mapper.type.modelProperties;
+ if (!modelProps) {
+ const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
+ if (!modelMapper) {
+ throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
+ }
+ modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties;
+ if (!modelProps) {
+ throw new Error(`modelProperties cannot be null or undefined in the ` +
+ `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`);
+ }
+ }
+ return modelProps;
}
-
-// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container
-function clonePolicyContainer (policyContainer) {
- return {
- referrerPolicy: policyContainer.referrerPolicy
- }
+function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) {
+ if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
+ mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
+ }
+ if (object !== undefined && object !== null) {
+ const payload = {};
+ const modelProps = resolveModelProperties(serializer, mapper, objectName);
+ for (const key of Object.keys(modelProps)) {
+ const propertyMapper = modelProps[key];
+ if (propertyMapper.readOnly) {
+ continue;
+ }
+ let propName;
+ let parentObject = payload;
+ if (serializer.isXML) {
+ if (propertyMapper.xmlIsWrapped) {
+ propName = propertyMapper.xmlName;
+ }
+ else {
+ propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
+ }
+ }
+ else {
+ const paths = splitSerializeName(propertyMapper.serializedName);
+ propName = paths.pop();
+ for (const pathName of paths) {
+ const childObject = parentObject[pathName];
+ if ((childObject === undefined || childObject === null) &&
+ ((object[key] !== undefined && object[key] !== null) ||
+ propertyMapper.defaultValue !== undefined)) {
+ parentObject[pathName] = {};
+ }
+ parentObject = parentObject[pathName];
+ }
+ }
+ if (parentObject !== undefined && parentObject !== null) {
+ if (isXml && mapper.xmlNamespace) {
+ const xmlnsKey = mapper.xmlNamespacePrefix
+ ? `xmlns:${mapper.xmlNamespacePrefix}`
+ : "xmlns";
+ parentObject[interfaces_js_1.XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[interfaces_js_1.XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace });
+ }
+ const propertyObjectName = propertyMapper.serializedName !== ""
+ ? objectName + "." + propertyMapper.serializedName
+ : objectName;
+ let toSerialize = object[key];
+ const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
+ if (polymorphicDiscriminator &&
+ polymorphicDiscriminator.clientName === key &&
+ (toSerialize === undefined || toSerialize === null)) {
+ toSerialize = mapper.serializedName;
+ }
+ const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options);
+ if (serializedValue !== undefined && propName !== undefined && propName !== null) {
+ const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
+ if (isXml && propertyMapper.xmlIsAttribute) {
+ // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.
+ // This keeps things simple while preventing name collision
+ // with names in user documents.
+ parentObject[interfaces_js_1.XML_ATTRKEY] = parentObject[interfaces_js_1.XML_ATTRKEY] || {};
+ parentObject[interfaces_js_1.XML_ATTRKEY][propName] = serializedValue;
+ }
+ else if (isXml && propertyMapper.xmlIsWrapped) {
+ parentObject[propName] = { [propertyMapper.xmlElementName]: value };
+ }
+ else {
+ parentObject[propName] = value;
+ }
+ }
+ }
+ }
+ const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
+ if (additionalPropertiesMapper) {
+ const propNames = Object.keys(modelProps);
+ for (const clientPropName in object) {
+ const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
+ if (isAdditionalProperty) {
+ payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options);
+ }
+ }
+ }
+ return payload;
+ }
+ return object;
}
-
-// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
-function determineRequestsReferrer (request) {
- // 1. Let policy be request's referrer policy.
- const policy = request.referrerPolicy
-
- // Note: policy cannot (shouldn't) be null or an empty string.
- assert(policy)
-
- // 2. Let environment be request’s client.
-
- let referrerSource = null
-
- // 3. Switch on request’s referrer:
- if (request.referrer === 'client') {
- // Note: node isn't a browser and doesn't implement document/iframes,
- // so we bypass this step and replace it with our own.
-
- const globalOrigin = getGlobalOrigin()
-
- if (!globalOrigin || globalOrigin.origin === 'null') {
- return 'no-referrer'
+function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) {
+ if (!isXml || !propertyMapper.xmlNamespace) {
+ return serializedValue;
}
-
- // note: we need to clone it as it's mutated
- referrerSource = new URL(globalOrigin)
- } else if (request.referrer instanceof URL) {
- // Let referrerSource be request’s referrer.
- referrerSource = request.referrer
- }
-
- // 4. Let request’s referrerURL be the result of stripping referrerSource for
- // use as a referrer.
- let referrerURL = stripURLForReferrer(referrerSource)
-
- // 5. Let referrerOrigin be the result of stripping referrerSource for use as
- // a referrer, with the origin-only flag set to true.
- const referrerOrigin = stripURLForReferrer(referrerSource, true)
-
- // 6. If the result of serializing referrerURL is a string whose length is
- // greater than 4096, set referrerURL to referrerOrigin.
- if (referrerURL.toString().length > 4096) {
- referrerURL = referrerOrigin
- }
-
- const areSameOrigin = sameOrigin(request, referrerURL)
- const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) &&
- !isURLPotentiallyTrustworthy(request.url)
-
- // 8. Execute the switch statements corresponding to the value of policy:
- switch (policy) {
- case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true)
- case 'unsafe-url': return referrerURL
- case 'same-origin':
- return areSameOrigin ? referrerOrigin : 'no-referrer'
- case 'origin-when-cross-origin':
- return areSameOrigin ? referrerURL : referrerOrigin
- case 'strict-origin-when-cross-origin': {
- const currentURL = requestCurrentURL(request)
-
- // 1. If the origin of referrerURL and the origin of request’s current
- // URL are the same, then return referrerURL.
- if (sameOrigin(referrerURL, currentURL)) {
- return referrerURL
- }
-
- // 2. If referrerURL is a potentially trustworthy URL and request’s
- // current URL is not a potentially trustworthy URL, then return no
- // referrer.
- if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
- return 'no-referrer'
- }
-
- // 3. Return referrerOrigin.
- return referrerOrigin
+ const xmlnsKey = propertyMapper.xmlNamespacePrefix
+ ? `xmlns:${propertyMapper.xmlNamespacePrefix}`
+ : "xmlns";
+ const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
+ if (["Composite"].includes(propertyMapper.type.name)) {
+ if (serializedValue[interfaces_js_1.XML_ATTRKEY]) {
+ return serializedValue;
+ }
+ else {
+ const result = Object.assign({}, serializedValue);
+ result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
+ return result;
+ }
}
- case 'strict-origin': // eslint-disable-line
- /**
- * 1. If referrerURL is a potentially trustworthy URL and
- * request’s current URL is not a potentially trustworthy URL,
- * then return no referrer.
- * 2. Return referrerOrigin
- */
- case 'no-referrer-when-downgrade': // eslint-disable-line
- /**
- * 1. If referrerURL is a potentially trustworthy URL and
- * request’s current URL is not a potentially trustworthy URL,
- * then return no referrer.
- * 2. Return referrerOrigin
- */
-
- default: // eslint-disable-line
- return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin
- }
+ const result = {};
+ result[options.xml.xmlCharKey] = serializedValue;
+ result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
+ return result;
}
-
-/**
- * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url
- * @param {URL} url
- * @param {boolean|undefined} originOnly
- */
-function stripURLForReferrer (url, originOnly) {
- // 1. Assert: url is a URL.
- assert(url instanceof URL)
-
- // 2. If url’s scheme is a local scheme, then return no referrer.
- if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') {
- return 'no-referrer'
- }
-
- // 3. Set url’s username to the empty string.
- url.username = ''
-
- // 4. Set url’s password to the empty string.
- url.password = ''
-
- // 5. Set url’s fragment to null.
- url.hash = ''
-
- // 6. If the origin-only flag is true, then:
- if (originOnly) {
- // 1. Set url’s path to « the empty string ».
- url.pathname = ''
-
- // 2. Set url’s query to null.
- url.search = ''
- }
-
- // 7. Return url.
- return url
+function isSpecialXmlProperty(propertyName, options) {
+ return [interfaces_js_1.XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
}
-
-function isURLPotentiallyTrustworthy (url) {
- if (!(url instanceof URL)) {
- return false
- }
-
- // If child of about, return true
- if (url.href === 'about:blank' || url.href === 'about:srcdoc') {
- return true
- }
-
- // If scheme is data, return true
- if (url.protocol === 'data:') return true
-
- // If file, return true
- if (url.protocol === 'file:') return true
-
- return isOriginPotentiallyTrustworthy(url.origin)
-
- function isOriginPotentiallyTrustworthy (origin) {
- // If origin is explicitly null, return false
- if (origin == null || origin === 'null') return false
-
- const originAsURL = new URL(origin)
-
- // If secure, return true
- if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') {
- return true
+function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
+ var _a, _b;
+ const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : interfaces_js_1.XML_CHARKEY;
+ if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
+ mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
+ }
+ const modelProps = resolveModelProperties(serializer, mapper, objectName);
+ let instance = {};
+ const handledPropertyNames = [];
+ for (const key of Object.keys(modelProps)) {
+ const propertyMapper = modelProps[key];
+ const paths = splitSerializeName(modelProps[key].serializedName);
+ handledPropertyNames.push(paths[0]);
+ const { serializedName, xmlName, xmlElementName } = propertyMapper;
+ let propertyObjectName = objectName;
+ if (serializedName !== "" && serializedName !== undefined) {
+ propertyObjectName = objectName + "." + serializedName;
+ }
+ const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
+ if (headerCollectionPrefix) {
+ const dictionary = {};
+ for (const headerKey of Object.keys(responseBody)) {
+ if (headerKey.startsWith(headerCollectionPrefix)) {
+ dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options);
+ }
+ handledPropertyNames.push(headerKey);
+ }
+ instance[key] = dictionary;
+ }
+ else if (serializer.isXML) {
+ if (propertyMapper.xmlIsAttribute && responseBody[interfaces_js_1.XML_ATTRKEY]) {
+ instance[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options);
+ }
+ else if (propertyMapper.xmlIsMsText) {
+ if (responseBody[xmlCharKey] !== undefined) {
+ instance[key] = responseBody[xmlCharKey];
+ }
+ else if (typeof responseBody === "string") {
+ // The special case where xml parser parses "content" into JSON of
+ // `{ name: "content"}` instead of `{ name: { "_": "content" }}`
+ instance[key] = responseBody;
+ }
+ }
+ else {
+ const propertyName = xmlElementName || xmlName || serializedName;
+ if (propertyMapper.xmlIsWrapped) {
+ /* a list of wrapped by
+ For the xml example below
+
+ ...
+ ...
+
+ the responseBody has
+ {
+ Cors: {
+ CorsRule: [{...}, {...}]
+ }
+ }
+ xmlName is "Cors" and xmlElementName is"CorsRule".
+ */
+ const wrapped = responseBody[xmlName];
+ const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : [];
+ instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options);
+ handledPropertyNames.push(xmlName);
+ }
+ else {
+ const property = responseBody[propertyName];
+ instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
+ handledPropertyNames.push(propertyName);
+ }
+ }
+ }
+ else {
+ // deserialize the property if it is present in the provided responseBody instance
+ let propertyInstance;
+ let res = responseBody;
+ // traversing the object step by step.
+ let steps = 0;
+ for (const item of paths) {
+ if (!res)
+ break;
+ steps++;
+ res = res[item];
+ }
+ // only accept null when reaching the last position of object otherwise it would be undefined
+ if (res === null && steps < paths.length) {
+ res = undefined;
+ }
+ propertyInstance = res;
+ const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
+ // checking that the model property name (key)(ex: "fishtype") and the
+ // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
+ // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
+ // is a better approach. The generator is not consistent with escaping '\.' in the
+ // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
+ // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
+ // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
+ // the transformation of model property name (ex: "fishtype") is done consistently.
+ // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
+ if (polymorphicDiscriminator &&
+ key === polymorphicDiscriminator.clientName &&
+ (propertyInstance === undefined || propertyInstance === null)) {
+ propertyInstance = mapper.serializedName;
+ }
+ let serializedValue;
+ // paging
+ if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
+ propertyInstance = responseBody[key];
+ const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
+ // Copy over any properties that have already been added into the instance, where they do
+ // not exist on the newly de-serialized array
+ for (const [k, v] of Object.entries(instance)) {
+ if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
+ arrayInstance[k] = v;
+ }
+ }
+ instance = arrayInstance;
+ }
+ else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
+ serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
+ instance[key] = serializedValue;
+ }
+ }
}
-
- // If localhost or variants, return true
- if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) ||
- (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) ||
- (originAsURL.hostname.endsWith('.localhost'))) {
- return true
+ const additionalPropertiesMapper = mapper.type.additionalProperties;
+ if (additionalPropertiesMapper) {
+ const isAdditionalProperty = (responsePropName) => {
+ for (const clientPropName in modelProps) {
+ const paths = splitSerializeName(modelProps[clientPropName].serializedName);
+ if (paths[0] === responsePropName) {
+ return false;
+ }
+ }
+ return true;
+ };
+ for (const responsePropName in responseBody) {
+ if (isAdditionalProperty(responsePropName)) {
+ instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options);
+ }
+ }
}
-
- // If any other, return false
- return false
- }
+ else if (responseBody && !options.ignoreUnknownProperties) {
+ for (const key of Object.keys(responseBody)) {
+ if (instance[key] === undefined &&
+ !handledPropertyNames.includes(key) &&
+ !isSpecialXmlProperty(key, options)) {
+ instance[key] = responseBody[key];
+ }
+ }
+ }
+ return instance;
}
-
-/**
- * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist
- * @param {Uint8Array} bytes
- * @param {string} metadataList
- */
-function bytesMatch (bytes, metadataList) {
- // If node is not built with OpenSSL support, we cannot check
- // a request's integrity, so allow it by default (the spec will
- // allow requests if an invalid hash is given, as precedence).
- /* istanbul ignore if: only if node is built with --without-ssl */
- if (crypto === undefined) {
- return true
- }
-
- // 1. Let parsedMetadata be the result of parsing metadataList.
- const parsedMetadata = parseMetadata(metadataList)
-
- // 2. If parsedMetadata is no metadata, return true.
- if (parsedMetadata === 'no metadata') {
- return true
- }
-
- // 3. If response is not eligible for integrity validation, return false.
- // TODO
-
- // 4. If parsedMetadata is the empty set, return true.
- if (parsedMetadata.length === 0) {
- return true
- }
-
- // 5. Let metadata be the result of getting the strongest
- // metadata from parsedMetadata.
- const strongest = getStrongestMetadata(parsedMetadata)
- const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest)
-
- // 6. For each item in metadata:
- for (const item of metadata) {
- // 1. Let algorithm be the alg component of item.
- const algorithm = item.algo
-
- // 2. Let expectedValue be the val component of item.
- const expectedValue = item.hash
-
- // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e
- // "be liberal with padding". This is annoying, and it's not even in the spec.
-
- // 3. Let actualValue be the result of applying algorithm to bytes.
- let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64')
-
- if (actualValue[actualValue.length - 1] === '=') {
- if (actualValue[actualValue.length - 2] === '=') {
- actualValue = actualValue.slice(0, -2)
- } else {
- actualValue = actualValue.slice(0, -1)
- }
+function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) {
+ /* jshint validthis: true */
+ const value = mapper.type.value;
+ if (!value || typeof value !== "object") {
+ throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}`);
}
-
- // 4. If actualValue is a case-sensitive match for expectedValue,
- // return true.
- if (compareBase64Mixed(actualValue, expectedValue)) {
- return true
+ if (responseBody) {
+ const tempDictionary = {};
+ for (const key of Object.keys(responseBody)) {
+ tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
+ }
+ return tempDictionary;
}
- }
-
- // 7. Return false.
- return false
+ return responseBody;
}
-
-// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options
-// https://www.w3.org/TR/CSP2/#source-list-syntax
-// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1
-const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i
-
-/**
- * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata
- * @param {string} metadata
- */
-function parseMetadata (metadata) {
- // 1. Let result be the empty set.
- /** @type {{ algo: string, hash: string }[]} */
- const result = []
-
- // 2. Let empty be equal to true.
- let empty = true
-
- // 3. For each token returned by splitting metadata on spaces:
- for (const token of metadata.split(' ')) {
- // 1. Set empty to false.
- empty = false
-
- // 2. Parse token as a hash-with-options.
- const parsedToken = parseHashWithOptions.exec(token)
-
- // 3. If token does not parse, continue to the next token.
- if (
- parsedToken === null ||
- parsedToken.groups === undefined ||
- parsedToken.groups.algo === undefined
- ) {
- // Note: Chromium blocks the request at this point, but Firefox
- // gives a warning that an invalid integrity was given. The
- // correct behavior is to ignore these, and subsequently not
- // check the integrity of the resource.
- continue
+function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) {
+ var _a;
+ let element = mapper.type.element;
+ if (!element || typeof element !== "object") {
+ throw new Error(`element" metadata for an Array must be defined in the ` +
+ `mapper and it must of type "object" in ${objectName}`);
}
-
- // 4. Let algorithm be the hash-algo component of token.
- const algorithm = parsedToken.groups.algo.toLowerCase()
-
- // 5. If algorithm is a hash function recognized by the user
- // agent, add the parsed token to result.
- if (supportedHashes.includes(algorithm)) {
- result.push(parsedToken.groups)
+ if (responseBody) {
+ if (!Array.isArray(responseBody)) {
+ // xml2js will interpret a single element array as just the element, so force it to be an array
+ responseBody = [responseBody];
+ }
+ // Quirk: Composite mappers referenced by `element` might
+ // not have *all* properties declared (like uberParent),
+ // so let's try to look up the full definition by name.
+ if (element.type.name === "Composite" && element.type.className) {
+ element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element;
+ }
+ const tempArray = [];
+ for (let i = 0; i < responseBody.length; i++) {
+ tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options);
+ }
+ return tempArray;
}
- }
-
- // 4. Return no metadata if empty is true, otherwise return result.
- if (empty === true) {
- return 'no metadata'
- }
-
- return result
+ return responseBody;
}
-
-/**
- * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList
- */
-function getStrongestMetadata (metadataList) {
- // Let algorithm be the algo component of the first item in metadataList.
- // Can be sha256
- let algorithm = metadataList[0].algo
- // If the algorithm is sha512, then it is the strongest
- // and we can return immediately
- if (algorithm[3] === '5') {
- return algorithm
- }
-
- for (let i = 1; i < metadataList.length; ++i) {
- const metadata = metadataList[i]
- // If the algorithm is sha512, then it is the strongest
- // and we can break the loop immediately
- if (metadata.algo[3] === '5') {
- algorithm = 'sha512'
- break
- // If the algorithm is sha384, then a potential sha256 or sha384 is ignored
- } else if (algorithm[3] === '3') {
- continue
- // algorithm is sha256, check if algorithm is sha384 and if so, set it as
- // the strongest
- } else if (metadata.algo[3] === '3') {
- algorithm = 'sha384'
+function getIndexDiscriminator(discriminators, discriminatorValue, typeName) {
+ const typeNamesToCheck = [typeName];
+ while (typeNamesToCheck.length) {
+ const currentName = typeNamesToCheck.shift();
+ const indexDiscriminator = discriminatorValue === currentName
+ ? discriminatorValue
+ : currentName + "." + discriminatorValue;
+ if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
+ return discriminators[indexDiscriminator];
+ }
+ else {
+ for (const [name, mapper] of Object.entries(discriminators)) {
+ if (name.startsWith(currentName + ".") &&
+ mapper.type.uberParent === currentName &&
+ mapper.type.className) {
+ typeNamesToCheck.push(mapper.type.className);
+ }
+ }
+ }
}
- }
- return algorithm
+ return undefined;
}
-
-function filterMetadataListByAlgorithm (metadataList, algorithm) {
- if (metadataList.length === 1) {
- return metadataList
- }
-
- let pos = 0
- for (let i = 0; i < metadataList.length; ++i) {
- if (metadataList[i].algo === algorithm) {
- metadataList[pos++] = metadataList[i]
+function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
+ var _a;
+ const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
+ if (polymorphicDiscriminator) {
+ let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
+ if (discriminatorName) {
+ // The serializedName might have \\, which we just want to ignore
+ if (polymorphicPropertyName === "serializedName") {
+ discriminatorName = discriminatorName.replace(/\\/gi, "");
+ }
+ const discriminatorValue = object[discriminatorName];
+ const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className;
+ if (typeof discriminatorValue === "string" && typeName) {
+ const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName);
+ if (polymorphicMapper) {
+ mapper = polymorphicMapper;
+ }
+ }
+ }
}
- }
-
- metadataList.length = pos
-
- return metadataList
+ return mapper;
}
-
-/**
- * Compares two base64 strings, allowing for base64url
- * in the second string.
- *
-* @param {string} actualValue always base64
- * @param {string} expectedValue base64 or base64url
- * @returns {boolean}
- */
-function compareBase64Mixed (actualValue, expectedValue) {
- if (actualValue.length !== expectedValue.length) {
- return false
- }
- for (let i = 0; i < actualValue.length; ++i) {
- if (actualValue[i] !== expectedValue[i]) {
- if (
- (actualValue[i] === '+' && expectedValue[i] === '-') ||
- (actualValue[i] === '/' && expectedValue[i] === '_')
- ) {
- continue
- }
- return false
- }
- }
-
- return true
+function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
+ return (mapper.type.polymorphicDiscriminator ||
+ getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
+ getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
}
-
-// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request
-function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) {
- // TODO
+function getPolymorphicDiscriminatorSafely(serializer, typeName) {
+ return (typeName &&
+ serializer.modelMappers[typeName] &&
+ serializer.modelMappers[typeName].type.polymorphicDiscriminator);
}
-
/**
- * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin}
- * @param {URL} A
- * @param {URL} B
+ * Known types of Mappers
*/
-function sameOrigin (A, B) {
- // 1. If A and B are the same opaque origin, then return true.
- if (A.origin === B.origin && A.origin === 'null') {
- return true
- }
-
- // 2. If A and B are both tuple origins and their schemes,
- // hosts, and port are identical, then return true.
- if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) {
- return true
- }
-
- // 3. Return false.
- return false
-}
+exports.MapperTypeNames = {
+ Base64Url: "Base64Url",
+ Boolean: "Boolean",
+ ByteArray: "ByteArray",
+ Composite: "Composite",
+ Date: "Date",
+ DateTime: "DateTime",
+ DateTimeRfc1123: "DateTimeRfc1123",
+ Dictionary: "Dictionary",
+ Enum: "Enum",
+ Number: "Number",
+ Object: "Object",
+ Sequence: "Sequence",
+ String: "String",
+ Stream: "Stream",
+ TimeSpan: "TimeSpan",
+ UnixTime: "UnixTime",
+};
+//# sourceMappingURL=serializer.js.map
-function createDeferredPromise () {
- let res
- let rej
- const promise = new Promise((resolve, reject) => {
- res = resolve
- rej = reject
- })
+/***/ }),
- return { promise, resolve: res, reject: rej }
-}
+/***/ 22732:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-function isAborted (fetchParams) {
- return fetchParams.controller.state === 'aborted'
-}
-function isCancelled (fetchParams) {
- return fetchParams.controller.state === 'aborted' ||
- fetchParams.controller.state === 'terminated'
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ServiceClient = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+const pipeline_js_1 = __nccwpck_require__(64524);
+const utils_js_1 = __nccwpck_require__(7805);
+const httpClientCache_js_1 = __nccwpck_require__(64663);
+const operationHelpers_js_1 = __nccwpck_require__(17036);
+const urlHelpers_js_1 = __nccwpck_require__(36580);
+const interfaceHelpers_js_1 = __nccwpck_require__(91030);
+const log_js_1 = __nccwpck_require__(75630);
+/**
+ * Initializes a new instance of the ServiceClient.
+ */
+class ServiceClient {
+ /**
+ * The ServiceClient constructor
+ * @param credential - The credentials used for authentication with the service.
+ * @param options - The service client options that govern the behavior of the client.
+ */
+ constructor(options = {}) {
+ var _a, _b;
+ this._requestContentType = options.requestContentType;
+ this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri;
+ if (options.baseUri) {
+ log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
+ }
+ this._allowInsecureConnection = options.allowInsecureConnection;
+ this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)();
+ this.pipeline = options.pipeline || createDefaultPipeline(options);
+ if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) {
+ for (const { policy, position } of options.additionalPolicies) {
+ // Sign happens after Retry and is commonly needed to occur
+ // before policies that intercept post-retry.
+ const afterPhase = position === "perRetry" ? "Sign" : undefined;
+ this.pipeline.addPolicy(policy, {
+ afterPhase,
+ });
+ }
+ }
+ }
+ /**
+ * Send the provided httpRequest.
+ */
+ async sendRequest(request) {
+ return this.pipeline.sendRequest(this._httpClient, request);
+ }
+ /**
+ * Send an HTTP request that is populated using the provided OperationSpec.
+ * @typeParam T - The typed result of the request, based on the OperationSpec.
+ * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.
+ * @param operationSpec - The OperationSpec to use to populate the httpRequest.
+ */
+ async sendOperationRequest(operationArguments, operationSpec) {
+ const endpoint = operationSpec.baseUrl || this._endpoint;
+ if (!endpoint) {
+ throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.");
+ }
+ // Templatized URLs sometimes reference properties on the ServiceClient child class,
+ // so we have to pass `this` below in order to search these properties if they're
+ // not part of OperationArguments
+ const url = (0, urlHelpers_js_1.getRequestUrl)(endpoint, operationSpec, operationArguments, this);
+ const request = (0, core_rest_pipeline_1.createPipelineRequest)({
+ url,
+ });
+ request.method = operationSpec.httpMethod;
+ const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
+ operationInfo.operationSpec = operationSpec;
+ operationInfo.operationArguments = operationArguments;
+ const contentType = operationSpec.contentType || this._requestContentType;
+ if (contentType && operationSpec.requestBody) {
+ request.headers.set("Content-Type", contentType);
+ }
+ const options = operationArguments.options;
+ if (options) {
+ const requestOptions = options.requestOptions;
+ if (requestOptions) {
+ if (requestOptions.timeout) {
+ request.timeout = requestOptions.timeout;
+ }
+ if (requestOptions.onUploadProgress) {
+ request.onUploadProgress = requestOptions.onUploadProgress;
+ }
+ if (requestOptions.onDownloadProgress) {
+ request.onDownloadProgress = requestOptions.onDownloadProgress;
+ }
+ if (requestOptions.shouldDeserialize !== undefined) {
+ operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;
+ }
+ if (requestOptions.allowInsecureConnection) {
+ request.allowInsecureConnection = true;
+ }
+ }
+ if (options.abortSignal) {
+ request.abortSignal = options.abortSignal;
+ }
+ if (options.tracingOptions) {
+ request.tracingOptions = options.tracingOptions;
+ }
+ }
+ if (this._allowInsecureConnection) {
+ request.allowInsecureConnection = true;
+ }
+ if (request.streamResponseStatusCodes === undefined) {
+ request.streamResponseStatusCodes = (0, interfaceHelpers_js_1.getStreamingResponseStatusCodes)(operationSpec);
+ }
+ try {
+ const rawResponse = await this.sendRequest(request);
+ const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]);
+ if (options === null || options === void 0 ? void 0 : options.onResponse) {
+ options.onResponse(rawResponse, flatResponse);
+ }
+ return flatResponse;
+ }
+ catch (error) {
+ if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) {
+ const rawResponse = error.response;
+ const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]);
+ error.details = flatResponse;
+ if (options === null || options === void 0 ? void 0 : options.onResponse) {
+ options.onResponse(rawResponse, flatResponse, error);
+ }
+ }
+ throw error;
+ }
+ }
}
-
-const normalizeMethodRecord = {
- delete: 'DELETE',
- DELETE: 'DELETE',
- get: 'GET',
- GET: 'GET',
- head: 'HEAD',
- HEAD: 'HEAD',
- options: 'OPTIONS',
- OPTIONS: 'OPTIONS',
- post: 'POST',
- POST: 'POST',
- put: 'PUT',
- PUT: 'PUT'
+exports.ServiceClient = ServiceClient;
+function createDefaultPipeline(options) {
+ const credentialScopes = getCredentialScopes(options);
+ const credentialOptions = options.credential && credentialScopes
+ ? { credentialScopes, credential: options.credential }
+ : undefined;
+ return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions }));
}
-
-// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`.
-Object.setPrototypeOf(normalizeMethodRecord, null)
-
-/**
- * @see https://fetch.spec.whatwg.org/#concept-method-normalize
- * @param {string} method
- */
-function normalizeMethod (method) {
- return normalizeMethodRecord[method.toLowerCase()] ?? method
+function getCredentialScopes(options) {
+ if (options.credentialScopes) {
+ return options.credentialScopes;
+ }
+ if (options.endpoint) {
+ return `${options.endpoint}/.default`;
+ }
+ if (options.baseUri) {
+ return `${options.baseUri}/.default`;
+ }
+ if (options.credential && !options.credentialScopes) {
+ throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`);
+ }
+ return undefined;
}
+//# sourceMappingURL=serviceClient.js.map
-// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string
-function serializeJavascriptValueToJSONString (value) {
- // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »).
- const result = JSON.stringify(value)
-
- // 2. If result is undefined, then throw a TypeError.
- if (result === undefined) {
- throw new TypeError('Value is not JSON serializable')
- }
-
- // 3. Assert: result is a string.
- assert(typeof result === 'string')
+/***/ }),
- // 4. Return result.
- return result
-}
+/***/ 35077:
+/***/ ((__unused_webpack_module, exports) => {
-// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object
-const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.state = void 0;
/**
- * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object
- * @param {() => unknown[]} iterator
- * @param {string} name name of the instance
- * @param {'key'|'value'|'key+value'} kind
+ * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports.
*/
-function makeIterator (iterator, name, kind) {
- const object = {
- index: 0,
- kind,
- target: iterator
- }
-
- const i = {
- next () {
- // 1. Let interface be the interface for which the iterator prototype object exists.
-
- // 2. Let thisValue be the this value.
-
- // 3. Let object be ? ToObject(thisValue).
-
- // 4. If object is a platform object, then perform a security
- // check, passing:
-
- // 5. If object is not a default iterator object for interface,
- // then throw a TypeError.
- if (Object.getPrototypeOf(this) !== i) {
- throw new TypeError(
- `'next' called on an object that does not implement interface ${name} Iterator.`
- )
- }
-
- // 6. Let index be object’s index.
- // 7. Let kind be object’s kind.
- // 8. Let values be object’s target's value pairs to iterate over.
- const { index, kind, target } = object
- const values = target()
-
- // 9. Let len be the length of values.
- const len = values.length
-
- // 10. If index is greater than or equal to len, then return
- // CreateIterResultObject(undefined, true).
- if (index >= len) {
- return { value: undefined, done: true }
- }
-
- // 11. Let pair be the entry in values at index index.
- const pair = values[index]
-
- // 12. Set object’s index to index + 1.
- object.index = index + 1
+exports.state = {
+ operationRequestMap: new WeakMap(),
+};
+//# sourceMappingURL=state-cjs.cjs.map
- // 13. Return the iterator result for pair and kind.
- return iteratorResult(pair, kind)
- },
- // The class string of an iterator prototype object for a given interface is the
- // result of concatenating the identifier of the interface and the string " Iterator".
- [Symbol.toStringTag]: `${name} Iterator`
- }
+/***/ }),
- // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%.
- Object.setPrototypeOf(i, esIteratorPrototype)
- // esIteratorPrototype needs to be the prototype of i
- // which is the prototype of an empty object. Yes, it's confusing.
- return Object.setPrototypeOf({}, i)
-}
+/***/ 36580:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// https://webidl.spec.whatwg.org/#iterator-result
-function iteratorResult (pair, kind) {
- let result
- // 1. Let result be a value determined by the value of kind:
- switch (kind) {
- case 'key': {
- // 1. Let idlKey be pair’s key.
- // 2. Let key be the result of converting idlKey to an
- // ECMAScript value.
- // 3. result is key.
- result = pair[0]
- break
- }
- case 'value': {
- // 1. Let idlValue be pair’s value.
- // 2. Let value be the result of converting idlValue to
- // an ECMAScript value.
- // 3. result is value.
- result = pair[1]
- break
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.appendQueryParams = exports.getRequestUrl = void 0;
+const operationHelpers_js_1 = __nccwpck_require__(17036);
+const interfaceHelpers_js_1 = __nccwpck_require__(91030);
+const CollectionFormatToDelimiterMap = {
+ CSV: ",",
+ SSV: " ",
+ Multi: "Multi",
+ TSV: "\t",
+ Pipes: "|",
+};
+function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) {
+ const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject);
+ let isAbsolutePath = false;
+ let requestUrl = replaceAll(baseUri, urlReplacements);
+ if (operationSpec.path) {
+ let path = replaceAll(operationSpec.path, urlReplacements);
+ // QUIRK: sometimes we get a path component like /{nextLink}
+ // which may be a fully formed URL with a leading /. In that case, we should
+ // remove the leading /
+ if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) {
+ path = path.substring(1);
+ }
+ // QUIRK: sometimes we get a path component like {nextLink}
+ // which may be a fully formed URL. In that case, we should
+ // ignore the baseUri.
+ if (isAbsoluteUrl(path)) {
+ requestUrl = path;
+ isAbsolutePath = true;
+ }
+ else {
+ requestUrl = appendPath(requestUrl, path);
+ }
}
- case 'key+value': {
- // 1. Let idlKey be pair’s key.
- // 2. Let idlValue be pair’s value.
- // 3. Let key be the result of converting idlKey to an
- // ECMAScript value.
- // 4. Let value be the result of converting idlValue to
- // an ECMAScript value.
- // 5. Let array be ! ArrayCreate(2).
- // 6. Call ! CreateDataProperty(array, "0", key).
- // 7. Call ! CreateDataProperty(array, "1", value).
- // 8. result is array.
- result = pair
- break
+ const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject);
+ /**
+ * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`
+ * is an absolute path. This ensures that existing query parameter values in `requestUrl`
+ * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it
+ * is still being built so there is nothing to overwrite.
+ */
+ requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);
+ return requestUrl;
+}
+exports.getRequestUrl = getRequestUrl;
+function replaceAll(input, replacements) {
+ let result = input;
+ for (const [searchValue, replaceValue] of replacements) {
+ result = result.split(searchValue).join(replaceValue);
}
- }
-
- // 2. Return CreateIterResultObject(result, false).
- return { value: result, done: false }
+ return result;
}
-
-/**
- * @see https://fetch.spec.whatwg.org/#body-fully-read
- */
-async function fullyReadBody (body, processBody, processBodyError) {
- // 1. If taskDestination is null, then set taskDestination to
- // the result of starting a new parallel queue.
-
- // 2. Let successSteps given a byte sequence bytes be to queue a
- // fetch task to run processBody given bytes, with taskDestination.
- const successSteps = processBody
-
- // 3. Let errorSteps be to queue a fetch task to run processBodyError,
- // with taskDestination.
- const errorSteps = processBodyError
-
- // 4. Let reader be the result of getting a reader for body’s stream.
- // If that threw an exception, then run errorSteps with that
- // exception and return.
- let reader
-
- try {
- reader = body.stream.getReader()
- } catch (e) {
- errorSteps(e)
- return
- }
-
- // 5. Read all bytes from reader, given successSteps and errorSteps.
- try {
- const result = await readAllBytes(reader)
- successSteps(result)
- } catch (e) {
- errorSteps(e)
- }
+function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
+ var _a;
+ const result = new Map();
+ if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) {
+ for (const urlParameter of operationSpec.urlParameters) {
+ let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject);
+ const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter);
+ urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString);
+ if (!urlParameter.skipEncoding) {
+ urlParameterValue = encodeURIComponent(urlParameterValue);
+ }
+ result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue);
+ }
+ }
+ return result;
}
-
-/** @type {ReadableStream} */
-let ReadableStream = globalThis.ReadableStream
-
-function isReadableStreamLike (stream) {
- if (!ReadableStream) {
- ReadableStream = (__nccwpck_require__(63774).ReadableStream)
- }
-
- return stream instanceof ReadableStream || (
- stream[Symbol.toStringTag] === 'ReadableStream' &&
- typeof stream.tee === 'function'
- )
+function isAbsoluteUrl(url) {
+ return url.includes("://");
}
-
-const MAXIMUM_ARGUMENT_LENGTH = 65535
-
-/**
- * @see https://infra.spec.whatwg.org/#isomorphic-decode
- * @param {number[]|Uint8Array} input
- */
-function isomorphicDecode (input) {
- // 1. To isomorphic decode a byte sequence input, return a string whose code point
- // length is equal to input’s length and whose code points have the same values
- // as the values of input’s bytes, in the same order.
-
- if (input.length < MAXIMUM_ARGUMENT_LENGTH) {
- return String.fromCharCode(...input)
- }
-
- return input.reduce((previous, current) => previous + String.fromCharCode(current), '')
+function appendPath(url, pathToAppend) {
+ if (!pathToAppend) {
+ return url;
+ }
+ const parsedUrl = new URL(url);
+ let newPath = parsedUrl.pathname;
+ if (!newPath.endsWith("/")) {
+ newPath = `${newPath}/`;
+ }
+ if (pathToAppend.startsWith("/")) {
+ pathToAppend = pathToAppend.substring(1);
+ }
+ const searchStart = pathToAppend.indexOf("?");
+ if (searchStart !== -1) {
+ const path = pathToAppend.substring(0, searchStart);
+ const search = pathToAppend.substring(searchStart + 1);
+ newPath = newPath + path;
+ if (search) {
+ parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;
+ }
+ }
+ else {
+ newPath = newPath + pathToAppend;
+ }
+ parsedUrl.pathname = newPath;
+ return parsedUrl.toString();
}
-
-/**
- * @param {ReadableStreamController} controller
- */
-function readableStreamClose (controller) {
- try {
- controller.close()
- } catch (err) {
- // TODO: add comment explaining why this error occurs.
- if (!err.message.includes('Controller is already closed')) {
- throw err
+function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
+ var _a;
+ const result = new Map();
+ const sequenceParams = new Set();
+ if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) {
+ for (const queryParameter of operationSpec.queryParameters) {
+ if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
+ sequenceParams.add(queryParameter.mapper.serializedName);
+ }
+ let queryParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, queryParameter, fallbackObject);
+ if ((queryParameterValue !== undefined && queryParameterValue !== null) ||
+ queryParameter.mapper.required) {
+ queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter));
+ const delimiter = queryParameter.collectionFormat
+ ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]
+ : "";
+ if (Array.isArray(queryParameterValue)) {
+ // replace null and undefined
+ queryParameterValue = queryParameterValue.map((item) => {
+ if (item === null || item === undefined) {
+ return "";
+ }
+ return item;
+ });
+ }
+ if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) {
+ continue;
+ }
+ else if (Array.isArray(queryParameterValue) &&
+ (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) {
+ queryParameterValue = queryParameterValue.join(delimiter);
+ }
+ if (!queryParameter.skipEncoding) {
+ if (Array.isArray(queryParameterValue)) {
+ queryParameterValue = queryParameterValue.map((item) => {
+ return encodeURIComponent(item);
+ });
+ }
+ else {
+ queryParameterValue = encodeURIComponent(queryParameterValue);
+ }
+ }
+ // Join pipes and CSV *after* encoding, or the server will be upset.
+ if (Array.isArray(queryParameterValue) &&
+ (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) {
+ queryParameterValue = queryParameterValue.join(delimiter);
+ }
+ result.set(queryParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter), queryParameterValue);
+ }
+ }
}
- }
+ return {
+ queryParams: result,
+ sequenceParams,
+ };
}
-
-/**
- * @see https://infra.spec.whatwg.org/#isomorphic-encode
- * @param {string} input
- */
-function isomorphicEncode (input) {
- // 1. Assert: input contains no code points greater than U+00FF.
- for (let i = 0; i < input.length; i++) {
- assert(input.charCodeAt(i) <= 0xFF)
- }
-
- // 2. Return a byte sequence whose length is equal to input’s code
- // point length and whose bytes have the same values as the
- // values of input’s code points, in the same order
- return input
+function simpleParseQueryParams(queryString) {
+ const result = new Map();
+ if (!queryString || queryString[0] !== "?") {
+ return result;
+ }
+ // remove the leading ?
+ queryString = queryString.slice(1);
+ const pairs = queryString.split("&");
+ for (const pair of pairs) {
+ const [name, value] = pair.split("=", 2);
+ const existingValue = result.get(name);
+ if (existingValue) {
+ if (Array.isArray(existingValue)) {
+ existingValue.push(value);
+ }
+ else {
+ result.set(name, [existingValue, value]);
+ }
+ }
+ else {
+ result.set(name, value);
+ }
+ }
+ return result;
}
-
-/**
- * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes
- * @see https://streams.spec.whatwg.org/#read-loop
- * @param {ReadableStreamDefaultReader} reader
- */
-async function readAllBytes (reader) {
- const bytes = []
- let byteLength = 0
-
- while (true) {
- const { done, value: chunk } = await reader.read()
-
- if (done) {
- // 1. Call successSteps with bytes.
- return Buffer.concat(bytes, byteLength)
+/** @internal */
+function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) {
+ if (queryParams.size === 0) {
+ return url;
+ }
+ const parsedUrl = new URL(url);
+ // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which
+ // can change their meaning to the server, such as in the case of a SAS signature.
+ // To avoid accidentally un-encoding a query param, we parse the key/values ourselves
+ const combinedParams = simpleParseQueryParams(parsedUrl.search);
+ for (const [name, value] of queryParams) {
+ const existingValue = combinedParams.get(name);
+ if (Array.isArray(existingValue)) {
+ if (Array.isArray(value)) {
+ existingValue.push(...value);
+ const valueSet = new Set(existingValue);
+ combinedParams.set(name, Array.from(valueSet));
+ }
+ else {
+ existingValue.push(value);
+ }
+ }
+ else if (existingValue) {
+ if (Array.isArray(value)) {
+ value.unshift(existingValue);
+ }
+ else if (sequenceParams.has(name)) {
+ combinedParams.set(name, [existingValue, value]);
+ }
+ if (!noOverwrite) {
+ combinedParams.set(name, value);
+ }
+ }
+ else {
+ combinedParams.set(name, value);
+ }
}
-
- // 1. If chunk is not a Uint8Array object, call failureSteps
- // with a TypeError and abort these steps.
- if (!isUint8Array(chunk)) {
- throw new TypeError('Received non-Uint8Array chunk')
+ const searchPieces = [];
+ for (const [name, value] of combinedParams) {
+ if (typeof value === "string") {
+ searchPieces.push(`${name}=${value}`);
+ }
+ else if (Array.isArray(value)) {
+ // QUIRK: If we get an array of values, include multiple key/value pairs
+ for (const subValue of value) {
+ searchPieces.push(`${name}=${subValue}`);
+ }
+ }
+ else {
+ searchPieces.push(`${name}=${value}`);
+ }
}
-
- // 2. Append the bytes represented by chunk to bytes.
- bytes.push(chunk)
- byteLength += chunk.length
-
- // 3. Read-loop given reader, bytes, successSteps, and failureSteps.
- }
+ // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.
+ parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
+ return parsedUrl.toString();
}
+exports.appendQueryParams = appendQueryParams;
+//# sourceMappingURL=urlHelpers.js.map
-/**
- * @see https://fetch.spec.whatwg.org/#is-local
- * @param {URL} url
- */
-function urlIsLocal (url) {
- assert('protocol' in url) // ensure it's a url object
+/***/ }),
- const protocol = url.protocol
+/***/ 7805:
+/***/ ((__unused_webpack_module, exports) => {
- return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:'
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.flattenResponse = exports.isValidUuid = exports.isDuration = exports.isPrimitiveBody = void 0;
/**
- * @param {string|URL} url
+ * A type guard for a primitive response body.
+ * @param value - Value to test
+ *
+ * @internal
*/
-function urlHasHttpsScheme (url) {
- if (typeof url === 'string') {
- return url.startsWith('https:')
- }
-
- return url.protocol === 'https:'
+function isPrimitiveBody(value, mapperTypeName) {
+ return (mapperTypeName !== "Composite" &&
+ mapperTypeName !== "Dictionary" &&
+ (typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean" ||
+ (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !==
+ null ||
+ value === undefined ||
+ value === null));
}
-
+exports.isPrimitiveBody = isPrimitiveBody;
+const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
/**
- * @see https://fetch.spec.whatwg.org/#http-scheme
- * @param {URL} url
+ * Returns true if the given string is in ISO 8601 format.
+ * @param value - The value to be validated for ISO 8601 duration format.
+ * @internal
*/
-function urlIsHttpHttpsScheme (url) {
- assert('protocol' in url) // ensure it's a url object
-
- const protocol = url.protocol
-
- return protocol === 'http:' || protocol === 'https:'
+function isDuration(value) {
+ return validateISODuration.test(value);
}
-
+exports.isDuration = isDuration;
+const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
/**
- * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0.
+ * Returns true if the provided uuid is valid.
+ *
+ * @param uuid - The uuid that needs to be validated.
+ *
+ * @internal
*/
-const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key))
-
-module.exports = {
- isAborted,
- isCancelled,
- createDeferredPromise,
- ReadableStreamFrom,
- toUSVString,
- tryUpgradeRequestToAPotentiallyTrustworthyURL,
- coarsenedSharedCurrentTime,
- determineRequestsReferrer,
- makePolicyContainer,
- clonePolicyContainer,
- appendFetchMetadata,
- appendRequestOriginHeader,
- TAOCheck,
- corsCheck,
- crossOriginResourcePolicyCheck,
- createOpaqueTimingInfo,
- setRequestReferrerPolicyOnRedirect,
- isValidHTTPToken,
- requestBadPort,
- requestCurrentURL,
- responseURL,
- responseLocationURL,
- isBlobLike,
- isURLPotentiallyTrustworthy,
- isValidReasonPhrase,
- sameOrigin,
- normalizeMethod,
- serializeJavascriptValueToJSONString,
- makeIterator,
- isValidHeaderName,
- isValidHeaderValue,
- hasOwn,
- isErrorLike,
- fullyReadBody,
- bytesMatch,
- isReadableStreamLike,
- readableStreamClose,
- isomorphicEncode,
- isomorphicDecode,
- urlIsLocal,
- urlHasHttpsScheme,
- urlIsHttpHttpsScheme,
- readAllBytes,
- normalizeMethodRecord,
- parseMetadata
-}
-
-
-/***/ }),
-
-/***/ 94354:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { types } = __nccwpck_require__(39023)
-const { hasOwn, toUSVString } = __nccwpck_require__(72847)
-
-/** @type {import('../../types/webidl').Webidl} */
-const webidl = {}
-webidl.converters = {}
-webidl.util = {}
-webidl.errors = {}
-
-webidl.errors.exception = function (message) {
- return new TypeError(`${message.header}: ${message.message}`)
-}
-
-webidl.errors.conversionFailed = function (context) {
- const plural = context.types.length === 1 ? '' : ' one of'
- const message =
- `${context.argument} could not be converted to` +
- `${plural}: ${context.types.join(', ')}.`
-
- return webidl.errors.exception({
- header: context.prefix,
- message
- })
-}
-
-webidl.errors.invalidArgument = function (context) {
- return webidl.errors.exception({
- header: context.prefix,
- message: `"${context.value}" is an invalid ${context.type}.`
- })
-}
-
-// https://webidl.spec.whatwg.org/#implements
-webidl.brandCheck = function (V, I, opts = undefined) {
- if (opts?.strict !== false && !(V instanceof I)) {
- throw new TypeError('Illegal invocation')
- } else {
- return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag]
- }
-}
-
-webidl.argumentLengthCheck = function ({ length }, min, ctx) {
- if (length < min) {
- throw webidl.errors.exception({
- message: `${min} argument${min !== 1 ? 's' : ''} required, ` +
- `but${length ? ' only' : ''} ${length} found.`,
- ...ctx
- })
- }
-}
-
-webidl.illegalConstructor = function () {
- throw webidl.errors.exception({
- header: 'TypeError',
- message: 'Illegal constructor'
- })
+function isValidUuid(uuid) {
+ return validUuidRegex.test(uuid);
}
-
-// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values
-webidl.util.Type = function (V) {
- switch (typeof V) {
- case 'undefined': return 'Undefined'
- case 'boolean': return 'Boolean'
- case 'string': return 'String'
- case 'symbol': return 'Symbol'
- case 'number': return 'Number'
- case 'bigint': return 'BigInt'
- case 'function':
- case 'object': {
- if (V === null) {
- return 'Null'
- }
-
- return 'Object'
+exports.isValidUuid = isValidUuid;
+/**
+ * Maps the response as follows:
+ * - wraps the response body if needed (typically if its type is primitive).
+ * - returns null if the combination of the headers and the body is empty.
+ * - otherwise, returns the combination of the headers and the body.
+ *
+ * @param responseObject - a representation of the parsed response
+ * @returns the response that will be returned to the user which can be null and/or wrapped
+ *
+ * @internal
+ */
+function handleNullableResponseAndWrappableBody(responseObject) {
+ const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body);
+ if (responseObject.hasNullableType &&
+ Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
+ return responseObject.shouldWrapBody ? { body: null } : null;
}
- }
-}
-
-// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint
-webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) {
- let upperBound
- let lowerBound
-
- // 1. If bitLength is 64, then:
- if (bitLength === 64) {
- // 1. Let upperBound be 2^53 − 1.
- upperBound = Math.pow(2, 53) - 1
-
- // 2. If signedness is "unsigned", then let lowerBound be 0.
- if (signedness === 'unsigned') {
- lowerBound = 0
- } else {
- // 3. Otherwise let lowerBound be −2^53 + 1.
- lowerBound = Math.pow(-2, 53) + 1
+ else {
+ return responseObject.shouldWrapBody
+ ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody;
}
- } else if (signedness === 'unsigned') {
- // 2. Otherwise, if signedness is "unsigned", then:
-
- // 1. Let lowerBound be 0.
- lowerBound = 0
-
- // 2. Let upperBound be 2^bitLength − 1.
- upperBound = Math.pow(2, bitLength) - 1
- } else {
- // 3. Otherwise:
-
- // 1. Let lowerBound be -2^bitLength − 1.
- lowerBound = Math.pow(-2, bitLength) - 1
-
- // 2. Let upperBound be 2^bitLength − 1 − 1.
- upperBound = Math.pow(2, bitLength - 1) - 1
- }
-
- // 4. Let x be ? ToNumber(V).
- let x = Number(V)
-
- // 5. If x is −0, then set x to +0.
- if (x === 0) {
- x = 0
- }
-
- // 6. If the conversion is to an IDL type associated
- // with the [EnforceRange] extended attribute, then:
- if (opts.enforceRange === true) {
- // 1. If x is NaN, +∞, or −∞, then throw a TypeError.
- if (
- Number.isNaN(x) ||
- x === Number.POSITIVE_INFINITY ||
- x === Number.NEGATIVE_INFINITY
- ) {
- throw webidl.errors.exception({
- header: 'Integer conversion',
- message: `Could not convert ${V} to an integer.`
- })
+}
+/**
+ * Take a `FullOperationResponse` and turn it into a flat
+ * response object to hand back to the consumer.
+ * @param fullResponse - The processed response from the operation request
+ * @param responseSpec - The response map from the OperationSpec
+ *
+ * @internal
+ */
+function flattenResponse(fullResponse, responseSpec) {
+ var _a, _b;
+ const parsedHeaders = fullResponse.parsedHeaders;
+ // head methods never have a body, but we return a boolean set to body property
+ // to indicate presence/absence of the resource
+ if (fullResponse.request.method === "HEAD") {
+ return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody });
}
-
- // 2. Set x to IntegerPart(x).
- x = webidl.util.IntegerPart(x)
-
- // 3. If x < lowerBound or x > upperBound, then
- // throw a TypeError.
- if (x < lowerBound || x > upperBound) {
- throw webidl.errors.exception({
- header: 'Integer conversion',
- message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.`
- })
+ const bodyMapper = responseSpec && responseSpec.bodyMapper;
+ const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable);
+ const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name;
+ /** If the body is asked for, we look at the expected body type to handle it */
+ if (expectedBodyTypeName === "Stream") {
+ return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody });
}
-
- // 4. Return x.
- return x
- }
-
- // 7. If x is not NaN and the conversion is to an IDL
- // type associated with the [Clamp] extended
- // attribute, then:
- if (!Number.isNaN(x) && opts.clamp === true) {
- // 1. Set x to min(max(x, lowerBound), upperBound).
- x = Math.min(Math.max(x, lowerBound), upperBound)
-
- // 2. Round x to the nearest integer, choosing the
- // even integer if it lies halfway between two,
- // and choosing +0 rather than −0.
- if (Math.floor(x) % 2 === 0) {
- x = Math.floor(x)
- } else {
- x = Math.ceil(x)
+ const modelProperties = (expectedBodyTypeName === "Composite" &&
+ bodyMapper.type.modelProperties) ||
+ {};
+ const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === "");
+ if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
+ const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : [];
+ for (const key of Object.keys(modelProperties)) {
+ if (modelProperties[key].serializedName) {
+ arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key];
+ }
+ }
+ if (parsedHeaders) {
+ for (const key of Object.keys(parsedHeaders)) {
+ arrayResponse[key] = parsedHeaders[key];
+ }
+ }
+ return isNullable &&
+ !fullResponse.parsedBody &&
+ !parsedHeaders &&
+ Object.getOwnPropertyNames(modelProperties).length === 0
+ ? null
+ : arrayResponse;
}
+ return handleNullableResponseAndWrappableBody({
+ body: fullResponse.parsedBody,
+ headers: parsedHeaders,
+ hasNullableType: isNullable,
+ shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),
+ });
+}
+exports.flattenResponse = flattenResponse;
+//# sourceMappingURL=utils.js.map
- // 3. Return x.
- return x
- }
-
- // 8. If x is NaN, +0, +∞, or −∞, then return +0.
- if (
- Number.isNaN(x) ||
- (x === 0 && Object.is(0, x)) ||
- x === Number.POSITIVE_INFINITY ||
- x === Number.NEGATIVE_INFINITY
- ) {
- return 0
- }
-
- // 9. Set x to IntegerPart(x).
- x = webidl.util.IntegerPart(x)
+/***/ }),
- // 10. Set x to x modulo 2^bitLength.
- x = x % Math.pow(2, bitLength)
+/***/ 39448:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 11. If signedness is "signed" and x ≥ 2^bitLength − 1,
- // then return x − 2^bitLength.
- if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) {
- return x - Math.pow(2, bitLength)
- }
- // 12. Otherwise, return x.
- return x
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ExtendedServiceClient = void 0;
+const disableKeepAlivePolicy_js_1 = __nccwpck_require__(56531);
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+const core_client_1 = __nccwpck_require__(6868);
+const response_js_1 = __nccwpck_require__(79093);
+/**
+ * Client to provide compatability between core V1 & V2.
+ */
+class ExtendedServiceClient extends core_client_1.ServiceClient {
+ constructor(options) {
+ var _a, _b;
+ super(options);
+ if (((_a = options.keepAliveOptions) === null || _a === void 0 ? void 0 : _a.enable) === false &&
+ !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) {
+ this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)());
+ }
+ if (((_b = options.redirectOptions) === null || _b === void 0 ? void 0 : _b.handleRedirects) === false) {
+ this.pipeline.removePolicy({
+ name: core_rest_pipeline_1.redirectPolicyName,
+ });
+ }
+ }
+ /**
+ * Compatible send operation request function.
+ *
+ * @param operationArguments - Operation arguments
+ * @param operationSpec - Operation Spec
+ * @returns
+ */
+ async sendOperationRequest(operationArguments, operationSpec) {
+ var _a;
+ const userProvidedCallBack = (_a = operationArguments === null || operationArguments === void 0 ? void 0 : operationArguments.options) === null || _a === void 0 ? void 0 : _a.onResponse;
+ let lastResponse;
+ function onResponse(rawResponse, flatResponse, error) {
+ lastResponse = rawResponse;
+ if (userProvidedCallBack) {
+ userProvidedCallBack(rawResponse, flatResponse, error);
+ }
+ }
+ operationArguments.options = Object.assign(Object.assign({}, operationArguments.options), { onResponse });
+ const result = await super.sendOperationRequest(operationArguments, operationSpec);
+ if (lastResponse) {
+ Object.defineProperty(result, "_response", {
+ value: (0, response_js_1.toCompatResponse)(lastResponse),
+ });
+ }
+ return result;
+ }
}
+exports.ExtendedServiceClient = ExtendedServiceClient;
+//# sourceMappingURL=extendedClient.js.map
-// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
-webidl.util.IntegerPart = function (n) {
- // 1. Let r be floor(abs(n)).
- const r = Math.floor(Math.abs(n))
+/***/ }),
- // 2. If n < 0, then return -1 × r.
- if (n < 0) {
- return -1 * r
- }
+/***/ 22842:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 3. Otherwise, return r.
- return r
-}
-// https://webidl.spec.whatwg.org/#es-sequence
-webidl.sequenceConverter = function (converter) {
- return (V) => {
- // 1. If Type(V) is not Object, throw a TypeError.
- if (webidl.util.Type(V) !== 'Object') {
- throw webidl.errors.exception({
- header: 'Sequence',
- message: `Value of type ${webidl.util.Type(V)} is not an Object.`
- })
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.convertHttpClient = void 0;
+const response_js_1 = __nccwpck_require__(79093);
+const util_js_1 = __nccwpck_require__(46);
+/**
+ * Converts a RequestPolicy based HttpClient to a PipelineRequest based HttpClient.
+ * @param requestPolicyClient - A HttpClient compatible with core-http
+ * @returns A HttpClient compatible with core-rest-pipeline
+ */
+function convertHttpClient(requestPolicyClient) {
+ return {
+ sendRequest: async (request) => {
+ const response = await requestPolicyClient.sendRequest((0, util_js_1.toWebResourceLike)(request, { createProxy: true }));
+ return (0, response_js_1.toPipelineResponse)(response);
+ },
+ };
+}
+exports.convertHttpClient = convertHttpClient;
+//# sourceMappingURL=httpClientAdapter.js.map
- // 2. Let method be ? GetMethod(V, @@iterator).
- /** @type {Generator} */
- const method = V?.[Symbol.iterator]?.()
- const seq = []
+/***/ }),
- // 3. If method is undefined, throw a TypeError.
- if (
- method === undefined ||
- typeof method.next !== 'function'
- ) {
- throw webidl.errors.exception({
- header: 'Sequence',
- message: 'Object is not an iterator.'
- })
- }
+/***/ 14508:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // https://webidl.spec.whatwg.org/#create-sequence-from-iterable
- while (true) {
- const { done, value } = method.next()
- if (done) {
- break
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toHttpHeadersLike = exports.convertHttpClient = exports.disableKeepAlivePolicyName = exports.HttpPipelineLogLevel = exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.ExtendedServiceClient = void 0;
+/**
+ * A Shim Library that provides compatibility between Core V1 & V2 Packages.
+ *
+ * @packageDocumentation
+ */
+var extendedClient_js_1 = __nccwpck_require__(39448);
+Object.defineProperty(exports, "ExtendedServiceClient", ({ enumerable: true, get: function () { return extendedClient_js_1.ExtendedServiceClient; } }));
+var requestPolicyFactoryPolicy_js_1 = __nccwpck_require__(15190);
+Object.defineProperty(exports, "requestPolicyFactoryPolicyName", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.requestPolicyFactoryPolicyName; } }));
+Object.defineProperty(exports, "createRequestPolicyFactoryPolicy", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.createRequestPolicyFactoryPolicy; } }));
+Object.defineProperty(exports, "HttpPipelineLogLevel", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.HttpPipelineLogLevel; } }));
+var disableKeepAlivePolicy_js_1 = __nccwpck_require__(56531);
+Object.defineProperty(exports, "disableKeepAlivePolicyName", ({ enumerable: true, get: function () { return disableKeepAlivePolicy_js_1.disableKeepAlivePolicyName; } }));
+var httpClientAdapter_js_1 = __nccwpck_require__(22842);
+Object.defineProperty(exports, "convertHttpClient", ({ enumerable: true, get: function () { return httpClientAdapter_js_1.convertHttpClient; } }));
+var util_js_1 = __nccwpck_require__(46);
+Object.defineProperty(exports, "toHttpHeadersLike", ({ enumerable: true, get: function () { return util_js_1.toHttpHeadersLike; } }));
+//# sourceMappingURL=index.js.map
- seq.push(converter(value))
- }
+/***/ }),
- return seq
- }
+/***/ 56531:
+/***/ ((__unused_webpack_module, exports) => {
+
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.pipelineContainsDisableKeepAlivePolicy = exports.createDisableKeepAlivePolicy = exports.disableKeepAlivePolicyName = void 0;
+exports.disableKeepAlivePolicyName = "DisableKeepAlivePolicy";
+function createDisableKeepAlivePolicy() {
+ return {
+ name: exports.disableKeepAlivePolicyName,
+ async sendRequest(request, next) {
+ request.disableKeepAlive = true;
+ return next(request);
+ },
+ };
+}
+exports.createDisableKeepAlivePolicy = createDisableKeepAlivePolicy;
+/**
+ * @internal
+ */
+function pipelineContainsDisableKeepAlivePolicy(pipeline) {
+ return pipeline.getOrderedPolicies().some((policy) => policy.name === exports.disableKeepAlivePolicyName);
}
+exports.pipelineContainsDisableKeepAlivePolicy = pipelineContainsDisableKeepAlivePolicy;
+//# sourceMappingURL=disableKeepAlivePolicy.js.map
-// https://webidl.spec.whatwg.org/#es-to-record
-webidl.recordConverter = function (keyConverter, valueConverter) {
- return (O) => {
- // 1. If Type(O) is not Object, throw a TypeError.
- if (webidl.util.Type(O) !== 'Object') {
- throw webidl.errors.exception({
- header: 'Record',
- message: `Value of type ${webidl.util.Type(O)} is not an Object.`
- })
- }
+/***/ }),
- // 2. Let result be a new empty instance of record.
- const result = {}
+/***/ 15190:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (!types.isProxy(O)) {
- // Object.keys only returns enumerable properties
- const keys = Object.keys(O)
- for (const key of keys) {
- // 1. Let typedKey be key converted to an IDL value of type K.
- const typedKey = keyConverter(key)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.HttpPipelineLogLevel = void 0;
+const util_js_1 = __nccwpck_require__(46);
+const response_js_1 = __nccwpck_require__(79093);
+/**
+ * An enum for compatibility with RequestPolicy
+ */
+var HttpPipelineLogLevel;
+(function (HttpPipelineLogLevel) {
+ HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
+ HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
+})(HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = HttpPipelineLogLevel = {}));
+const mockRequestPolicyOptions = {
+ log(_logLevel, _message) {
+ /* do nothing */
+ },
+ shouldLog(_logLevel) {
+ return false;
+ },
+};
+/**
+ * The name of the RequestPolicyFactoryPolicy
+ */
+exports.requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy";
+/**
+ * A policy that wraps policies written for core-http.
+ * @param factories - An array of `RequestPolicyFactory` objects from a core-http pipeline
+ */
+function createRequestPolicyFactoryPolicy(factories) {
+ const orderedFactories = factories.slice().reverse();
+ return {
+ name: exports.requestPolicyFactoryPolicyName,
+ async sendRequest(request, next) {
+ let httpPipeline = {
+ async sendRequest(httpRequest) {
+ const response = await next((0, util_js_1.toPipelineRequest)(httpRequest));
+ return (0, response_js_1.toCompatResponse)(response, { createProxy: true });
+ },
+ };
+ for (const factory of orderedFactories) {
+ httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions);
+ }
+ const webResourceLike = (0, util_js_1.toWebResourceLike)(request, { createProxy: true });
+ const response = await httpPipeline.sendRequest(webResourceLike);
+ return (0, response_js_1.toPipelineResponse)(response);
+ },
+ };
+}
+exports.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy;
+//# sourceMappingURL=requestPolicyFactoryPolicy.js.map
- // 2. Let value be ? Get(O, key).
- // 3. Let typedValue be value converted to an IDL value of type V.
- const typedValue = valueConverter(O[key])
+/***/ }),
- // 4. Set result[typedKey] to typedValue.
- result[typedKey] = typedValue
- }
+/***/ 79093:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 5. Return result.
- return result
- }
- // 3. Let keys be ? O.[[OwnPropertyKeys]]().
- const keys = Reflect.ownKeys(O)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.toPipelineResponse = exports.toCompatResponse = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+const util_js_1 = __nccwpck_require__(46);
+const originalResponse = Symbol("Original FullOperationResponse");
+/**
+ * A helper to convert response objects from the new pipeline back to the old one.
+ * @param response - A response object from core-client.
+ * @returns A response compatible with `HttpOperationResponse` from core-http.
+ */
+function toCompatResponse(response, options) {
+ let request = (0, util_js_1.toWebResourceLike)(response.request);
+ let headers = (0, util_js_1.toHttpHeadersLike)(response.headers);
+ if (options === null || options === void 0 ? void 0 : options.createProxy) {
+ return new Proxy(response, {
+ get(target, prop, receiver) {
+ if (prop === "headers") {
+ return headers;
+ }
+ else if (prop === "request") {
+ return request;
+ }
+ else if (prop === originalResponse) {
+ return response;
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ set(target, prop, value, receiver) {
+ if (prop === "headers") {
+ headers = value;
+ }
+ else if (prop === "request") {
+ request = value;
+ }
+ return Reflect.set(target, prop, value, receiver);
+ },
+ });
+ }
+ else {
+ return Object.assign(Object.assign({}, response), { request,
+ headers });
+ }
+}
+exports.toCompatResponse = toCompatResponse;
+/**
+ * A helper to convert back to a PipelineResponse
+ * @param compatResponse - A response compatible with `HttpOperationResponse` from core-http.
+ */
+function toPipelineResponse(compatResponse) {
+ const extendedCompatResponse = compatResponse;
+ const response = extendedCompatResponse[originalResponse];
+ const headers = (0, core_rest_pipeline_1.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true }));
+ if (response) {
+ response.headers = headers;
+ return response;
+ }
+ else {
+ return Object.assign(Object.assign({}, compatResponse), { headers, request: (0, util_js_1.toPipelineRequest)(compatResponse.request) });
+ }
+}
+exports.toPipelineResponse = toPipelineResponse;
+//# sourceMappingURL=response.js.map
- // 4. For each key of keys.
- for (const key of keys) {
- // 1. Let desc be ? O.[[GetOwnProperty]](key).
- const desc = Reflect.getOwnPropertyDescriptor(O, key)
+/***/ }),
- // 2. If desc is not undefined and desc.[[Enumerable]] is true:
- if (desc?.enumerable) {
- // 1. Let typedKey be key converted to an IDL value of type K.
- const typedKey = keyConverter(key)
+/***/ 46:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 2. Let value be ? Get(O, key).
- // 3. Let typedValue be value converted to an IDL value of type V.
- const typedValue = valueConverter(O[key])
- // 4. Set result[typedKey] to typedValue.
- result[typedKey] = typedValue
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.HttpHeaders = exports.toHttpHeadersLike = exports.toWebResourceLike = exports.toPipelineRequest = void 0;
+const core_rest_pipeline_1 = __nccwpck_require__(95582);
+// We use a custom symbol to cache a reference to the original request without
+// exposing it on the public interface.
+const originalRequestSymbol = Symbol("Original PipelineRequest");
+// Symbol.for() will return the same symbol if it's already been created
+// This particular one is used in core-client to handle the case of when a request is
+// cloned but we need to retrieve the OperationSpec and OperationArguments from the
+// original request.
+const originalClientRequestSymbol = Symbol.for("@azure/core-client original request");
+function toPipelineRequest(webResource, options = {}) {
+ const compatWebResource = webResource;
+ const request = compatWebResource[originalRequestSymbol];
+ const headers = (0, core_rest_pipeline_1.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true }));
+ if (request) {
+ request.headers = headers;
+ return request;
+ }
+ else {
+ const newRequest = (0, core_rest_pipeline_1.createPipelineRequest)({
+ url: webResource.url,
+ method: webResource.method,
+ headers,
+ withCredentials: webResource.withCredentials,
+ timeout: webResource.timeout,
+ requestId: webResource.requestId,
+ abortSignal: webResource.abortSignal,
+ body: webResource.body,
+ formData: webResource.formData,
+ disableKeepAlive: !!webResource.keepAlive,
+ onDownloadProgress: webResource.onDownloadProgress,
+ onUploadProgress: webResource.onUploadProgress,
+ proxySettings: webResource.proxySettings,
+ streamResponseStatusCodes: webResource.streamResponseStatusCodes,
+ });
+ if (options.originalRequest) {
+ newRequest[originalClientRequestSymbol] =
+ options.originalRequest;
+ }
+ return newRequest;
}
-
- // 5. Return result.
- return result
- }
}
-
-webidl.interfaceConverter = function (i) {
- return (V, opts = {}) => {
- if (opts.strict !== false && !(V instanceof i)) {
- throw webidl.errors.exception({
- header: i.name,
- message: `Expected ${V} to be an instance of ${i.name}.`
- })
+exports.toPipelineRequest = toPipelineRequest;
+function toWebResourceLike(request, options) {
+ var _a;
+ const originalRequest = (_a = options === null || options === void 0 ? void 0 : options.originalRequest) !== null && _a !== void 0 ? _a : request;
+ const webResource = {
+ url: request.url,
+ method: request.method,
+ headers: toHttpHeadersLike(request.headers),
+ withCredentials: request.withCredentials,
+ timeout: request.timeout,
+ requestId: request.headers.get("x-ms-client-request-id") || request.requestId,
+ abortSignal: request.abortSignal,
+ body: request.body,
+ formData: request.formData,
+ keepAlive: !!request.disableKeepAlive,
+ onDownloadProgress: request.onDownloadProgress,
+ onUploadProgress: request.onUploadProgress,
+ proxySettings: request.proxySettings,
+ streamResponseStatusCodes: request.streamResponseStatusCodes,
+ clone() {
+ throw new Error("Cannot clone a non-proxied WebResourceLike");
+ },
+ prepare() {
+ throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat");
+ },
+ validateRequestProperties() {
+ /** do nothing */
+ },
+ };
+ if (options === null || options === void 0 ? void 0 : options.createProxy) {
+ return new Proxy(webResource, {
+ get(target, prop, receiver) {
+ if (prop === originalRequestSymbol) {
+ return request;
+ }
+ else if (prop === "clone") {
+ return () => {
+ return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), {
+ createProxy: true,
+ originalRequest,
+ });
+ };
+ }
+ return Reflect.get(target, prop, receiver);
+ },
+ set(target, prop, value, receiver) {
+ if (prop === "keepAlive") {
+ request.disableKeepAlive = !value;
+ }
+ const passThroughProps = [
+ "url",
+ "method",
+ "withCredentials",
+ "timeout",
+ "requestId",
+ "abortSignal",
+ "body",
+ "formData",
+ "onDownloadProgress",
+ "onUploadProgress",
+ "proxySettings",
+ "streamResponseStatusCodes",
+ ];
+ if (typeof prop === "string" && passThroughProps.includes(prop)) {
+ request[prop] = value;
+ }
+ return Reflect.set(target, prop, value, receiver);
+ },
+ });
+ }
+ else {
+ return webResource;
+ }
+}
+exports.toWebResourceLike = toWebResourceLike;
+/**
+ * Converts HttpHeaders from core-rest-pipeline to look like
+ * HttpHeaders from core-http.
+ * @param headers - HttpHeaders from core-rest-pipeline
+ * @returns HttpHeaders as they looked in core-http
+ */
+function toHttpHeadersLike(headers) {
+ return new HttpHeaders(headers.toJSON({ preserveCase: true }));
+}
+exports.toHttpHeadersLike = toHttpHeadersLike;
+/**
+ * A collection of HttpHeaders that can be sent with a HTTP request.
+ */
+function getHeaderKey(headerName) {
+ return headerName.toLowerCase();
+}
+/**
+ * A collection of HTTP header key/value pairs.
+ */
+class HttpHeaders {
+ constructor(rawHeaders) {
+ this._headersMap = {};
+ if (rawHeaders) {
+ for (const headerName in rawHeaders) {
+ this.set(headerName, rawHeaders[headerName]);
+ }
+ }
+ }
+ /**
+ * Set a header in this collection with the provided name and value. The name is
+ * case-insensitive.
+ * @param headerName - The name of the header to set. This value is case-insensitive.
+ * @param headerValue - The value of the header to set.
+ */
+ set(headerName, headerValue) {
+ this._headersMap[getHeaderKey(headerName)] = {
+ name: headerName,
+ value: headerValue.toString(),
+ };
+ }
+ /**
+ * Get the header value for the provided header name, or undefined if no header exists in this
+ * collection with the provided name.
+ * @param headerName - The name of the header.
+ */
+ get(headerName) {
+ const header = this._headersMap[getHeaderKey(headerName)];
+ return !header ? undefined : header.value;
+ }
+ /**
+ * Get whether or not this header collection contains a header entry for the provided header name.
+ */
+ contains(headerName) {
+ return !!this._headersMap[getHeaderKey(headerName)];
+ }
+ /**
+ * Remove the header with the provided headerName. Return whether or not the header existed and
+ * was removed.
+ * @param headerName - The name of the header to remove.
+ */
+ remove(headerName) {
+ const result = this.contains(headerName);
+ delete this._headersMap[getHeaderKey(headerName)];
+ return result;
+ }
+ /**
+ * Get the headers that are contained this collection as an object.
+ */
+ rawHeaders() {
+ return this.toJson({ preserveCase: true });
+ }
+ /**
+ * Get the headers that are contained in this collection as an array.
+ */
+ headersArray() {
+ const headers = [];
+ for (const headerKey in this._headersMap) {
+ headers.push(this._headersMap[headerKey]);
+ }
+ return headers;
+ }
+ /**
+ * Get the header names that are contained in this collection.
+ */
+ headerNames() {
+ const headerNames = [];
+ const headers = this.headersArray();
+ for (let i = 0; i < headers.length; ++i) {
+ headerNames.push(headers[i].name);
+ }
+ return headerNames;
+ }
+ /**
+ * Get the header values that are contained in this collection.
+ */
+ headerValues() {
+ const headerValues = [];
+ const headers = this.headersArray();
+ for (let i = 0; i < headers.length; ++i) {
+ headerValues.push(headers[i].value);
+ }
+ return headerValues;
+ }
+ /**
+ * Get the JSON object representation of this HTTP header collection.
+ */
+ toJson(options = {}) {
+ const result = {};
+ if (options.preserveCase) {
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ result[header.name] = header.value;
+ }
+ }
+ else {
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ result[getHeaderKey(header.name)] = header.value;
+ }
+ }
+ return result;
+ }
+ /**
+ * Get the string representation of this HTTP header collection.
+ */
+ toString() {
+ return JSON.stringify(this.toJson({ preserveCase: true }));
+ }
+ /**
+ * Create a deep clone/copy of this HttpHeaders collection.
+ */
+ clone() {
+ const resultPreservingCasing = {};
+ for (const headerKey in this._headersMap) {
+ const header = this._headersMap[headerKey];
+ resultPreservingCasing[header.name] = header.value;
+ }
+ return new HttpHeaders(resultPreservingCasing);
}
-
- return V
- }
}
+exports.HttpHeaders = HttpHeaders;
+//# sourceMappingURL=util.js.map
-webidl.dictionaryConverter = function (converters) {
- return (dictionary) => {
- const type = webidl.util.Type(dictionary)
- const dict = {}
+/***/ }),
- if (type === 'Null' || type === 'Undefined') {
- return dict
- } else if (type !== 'Object') {
- throw webidl.errors.exception({
- header: 'Dictionary',
- message: `Expected ${dictionary} to be one of: Null, Undefined, Object.`
- })
- }
+/***/ 27826:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- for (const options of converters) {
- const { key, defaultValue, required, converter } = options
- if (required === true) {
- if (!hasOwn(dictionary, key)) {
- throw webidl.errors.exception({
- header: 'Dictionary',
- message: `Missing required key "${key}".`
- })
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.pollHttpOperation = exports.isOperationError = exports.getResourceLocation = exports.getOperationStatus = exports.getOperationLocation = exports.initHttpOperation = exports.getStatusFromInitialResponse = exports.getErrorFromResponse = exports.parseRetryAfter = exports.inferLroMode = void 0;
+const operation_js_1 = __nccwpck_require__(26588);
+const logger_js_1 = __nccwpck_require__(80692);
+function getOperationLocationPollingUrl(inputs) {
+ const { azureAsyncOperation, operationLocation } = inputs;
+ return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
+}
+function getLocationHeader(rawResponse) {
+ return rawResponse.headers["location"];
+}
+function getOperationLocationHeader(rawResponse) {
+ return rawResponse.headers["operation-location"];
+}
+function getAzureAsyncOperationHeader(rawResponse) {
+ return rawResponse.headers["azure-asyncoperation"];
+}
+function findResourceLocation(inputs) {
+ var _a;
+ const { location, requestMethod, requestPath, resourceLocationConfig } = inputs;
+ switch (requestMethod) {
+ case "PUT": {
+ return requestPath;
}
- }
-
- let value = dictionary[key]
- const hasDefault = hasOwn(options, 'defaultValue')
-
- // Only use defaultValue if value is undefined and
- // a defaultValue options was provided.
- if (hasDefault && value !== null) {
- value = value ?? defaultValue
- }
-
- // A key can be optional and have no default value.
- // When this happens, do not perform a conversion,
- // and do not assign the key a value.
- if (required || hasDefault || value !== undefined) {
- value = converter(value)
-
- if (
- options.allowedValues &&
- !options.allowedValues.includes(value)
- ) {
- throw webidl.errors.exception({
- header: 'Dictionary',
- message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.`
- })
+ case "DELETE": {
+ return undefined;
+ }
+ case "PATCH": {
+ return (_a = getDefault()) !== null && _a !== void 0 ? _a : requestPath;
+ }
+ default: {
+ return getDefault();
+ }
+ }
+ function getDefault() {
+ switch (resourceLocationConfig) {
+ case "azure-async-operation": {
+ return undefined;
+ }
+ case "original-uri": {
+ return requestPath;
+ }
+ case "location":
+ default: {
+ return location;
+ }
}
-
- dict[key] = value
- }
}
-
- return dict
- }
}
-
-webidl.nullableConverter = function (converter) {
- return (V) => {
- if (V === null) {
- return V
+function inferLroMode(inputs) {
+ const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs;
+ const operationLocation = getOperationLocationHeader(rawResponse);
+ const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse);
+ const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation });
+ const location = getLocationHeader(rawResponse);
+ const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase();
+ if (pollingUrl !== undefined) {
+ return {
+ mode: "OperationLocation",
+ operationLocation: pollingUrl,
+ resourceLocation: findResourceLocation({
+ requestMethod: normalizedRequestMethod,
+ location,
+ requestPath,
+ resourceLocationConfig,
+ }),
+ };
+ }
+ else if (location !== undefined) {
+ return {
+ mode: "ResourceLocation",
+ operationLocation: location,
+ };
+ }
+ else if (normalizedRequestMethod === "PUT" && requestPath) {
+ return {
+ mode: "Body",
+ operationLocation: requestPath,
+ };
+ }
+ else {
+ return undefined;
}
-
- return converter(V)
- }
}
-
-// https://webidl.spec.whatwg.org/#es-DOMString
-webidl.converters.DOMString = function (V, opts = {}) {
- // 1. If V is null and the conversion is to an IDL type
- // associated with the [LegacyNullToEmptyString]
- // extended attribute, then return the DOMString value
- // that represents the empty string.
- if (V === null && opts.legacyNullToEmptyString) {
- return ''
- }
-
- // 2. Let x be ? ToString(V).
- if (typeof V === 'symbol') {
- throw new TypeError('Could not convert argument of type symbol to string.')
- }
-
- // 3. Return the IDL DOMString value that represents the
- // same sequence of code units as the one the
- // ECMAScript String value x represents.
- return String(V)
+exports.inferLroMode = inferLroMode;
+function transformStatus(inputs) {
+ const { status, statusCode } = inputs;
+ if (typeof status !== "string" && status !== undefined) {
+ throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`);
+ }
+ switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) {
+ case undefined:
+ return toOperationStatus(statusCode);
+ case "succeeded":
+ return "succeeded";
+ case "failed":
+ return "failed";
+ case "running":
+ case "accepted":
+ case "started":
+ case "canceling":
+ case "cancelling":
+ return "running";
+ case "canceled":
+ case "cancelled":
+ return "canceled";
+ default: {
+ logger_js_1.logger.verbose(`LRO: unrecognized operation status: ${status}`);
+ return status;
+ }
+ }
}
-
-// https://webidl.spec.whatwg.org/#es-ByteString
-webidl.converters.ByteString = function (V) {
- // 1. Let x be ? ToString(V).
- // Note: DOMString converter perform ? ToString(V)
- const x = webidl.converters.DOMString(V)
-
- // 2. If the value of any element of x is greater than
- // 255, then throw a TypeError.
- for (let index = 0; index < x.length; index++) {
- if (x.charCodeAt(index) > 255) {
- throw new TypeError(
- 'Cannot convert argument to a ByteString because the character at ' +
- `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.`
- )
+function getStatus(rawResponse) {
+ var _a;
+ const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
+ return transformStatus({ status, statusCode: rawResponse.statusCode });
+}
+function getProvisioningState(rawResponse) {
+ var _a, _b;
+ const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
+ const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
+ return transformStatus({ status, statusCode: rawResponse.statusCode });
+}
+function toOperationStatus(statusCode) {
+ if (statusCode === 202) {
+ return "running";
+ }
+ else if (statusCode < 300) {
+ return "succeeded";
+ }
+ else {
+ return "failed";
}
- }
-
- // 3. Return an IDL ByteString value whose length is the
- // length of x, and where the value of each element is
- // the value of the corresponding element of x.
- return x
}
-
-// https://webidl.spec.whatwg.org/#es-USVString
-webidl.converters.USVString = toUSVString
-
-// https://webidl.spec.whatwg.org/#es-boolean
-webidl.converters.boolean = function (V) {
- // 1. Let x be the result of computing ToBoolean(V).
- const x = Boolean(V)
-
- // 2. Return the IDL boolean value that is the one that represents
- // the same truth value as the ECMAScript Boolean value x.
- return x
+function parseRetryAfter({ rawResponse }) {
+ const retryAfter = rawResponse.headers["retry-after"];
+ if (retryAfter !== undefined) {
+ // Retry-After header value is either in HTTP date format, or in seconds
+ const retryAfterInSeconds = parseInt(retryAfter);
+ return isNaN(retryAfterInSeconds)
+ ? calculatePollingIntervalFromDate(new Date(retryAfter))
+ : retryAfterInSeconds * 1000;
+ }
+ return undefined;
}
-
-// https://webidl.spec.whatwg.org/#es-any
-webidl.converters.any = function (V) {
- return V
+exports.parseRetryAfter = parseRetryAfter;
+function getErrorFromResponse(response) {
+ const error = accessBodyProperty(response, "error");
+ if (!error) {
+ logger_js_1.logger.warning(`The long-running operation failed but there is no error property in the response's body`);
+ return;
+ }
+ if (!error.code || !error.message) {
+ logger_js_1.logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`);
+ return;
+ }
+ return error;
}
-
-// https://webidl.spec.whatwg.org/#es-long-long
-webidl.converters['long long'] = function (V) {
- // 1. Let x be ? ConvertToInt(V, 64, "signed").
- const x = webidl.util.ConvertToInt(V, 64, 'signed')
-
- // 2. Return the IDL long long value that represents
- // the same numeric value as x.
- return x
+exports.getErrorFromResponse = getErrorFromResponse;
+function calculatePollingIntervalFromDate(retryAfterDate) {
+ const timeNow = Math.floor(new Date().getTime());
+ const retryAfterTime = retryAfterDate.getTime();
+ if (timeNow < retryAfterTime) {
+ return retryAfterTime - timeNow;
+ }
+ return undefined;
}
-
-// https://webidl.spec.whatwg.org/#es-unsigned-long-long
-webidl.converters['unsigned long long'] = function (V) {
- // 1. Let x be ? ConvertToInt(V, 64, "unsigned").
- const x = webidl.util.ConvertToInt(V, 64, 'unsigned')
-
- // 2. Return the IDL unsigned long long value that
- // represents the same numeric value as x.
- return x
+function getStatusFromInitialResponse(inputs) {
+ const { response, state, operationLocation } = inputs;
+ function helper() {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case undefined:
+ return toOperationStatus(response.rawResponse.statusCode);
+ case "Body":
+ return getOperationStatus(response, state);
+ default:
+ return "running";
+ }
+ }
+ const status = helper();
+ return status === "running" && operationLocation === undefined ? "succeeded" : status;
}
-
-// https://webidl.spec.whatwg.org/#es-unsigned-long
-webidl.converters['unsigned long'] = function (V) {
- // 1. Let x be ? ConvertToInt(V, 32, "unsigned").
- const x = webidl.util.ConvertToInt(V, 32, 'unsigned')
-
- // 2. Return the IDL unsigned long value that
- // represents the same numeric value as x.
- return x
+exports.getStatusFromInitialResponse = getStatusFromInitialResponse;
+/**
+ * Initiates the long-running operation.
+ */
+async function initHttpOperation(inputs) {
+ const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs;
+ return (0, operation_js_1.initOperation)({
+ init: async () => {
+ const response = await lro.sendInitialRequest();
+ const config = inferLroMode({
+ rawResponse: response.rawResponse,
+ requestPath: lro.requestPath,
+ requestMethod: lro.requestMethod,
+ resourceLocationConfig,
+ });
+ return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+ },
+ stateProxy,
+ processResult: processResult
+ ? ({ flatResponse }, state) => processResult(flatResponse, state)
+ : ({ flatResponse }) => flatResponse,
+ getOperationStatus: getStatusFromInitialResponse,
+ setErrorAsResult,
+ });
}
-
-// https://webidl.spec.whatwg.org/#es-unsigned-short
-webidl.converters['unsigned short'] = function (V, opts) {
- // 1. Let x be ? ConvertToInt(V, 16, "unsigned").
- const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts)
-
- // 2. Return the IDL unsigned short value that represents
- // the same numeric value as x.
- return x
+exports.initHttpOperation = initHttpOperation;
+function getOperationLocation({ rawResponse }, state) {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case "OperationLocation": {
+ return getOperationLocationPollingUrl({
+ operationLocation: getOperationLocationHeader(rawResponse),
+ azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse),
+ });
+ }
+ case "ResourceLocation": {
+ return getLocationHeader(rawResponse);
+ }
+ case "Body":
+ default: {
+ return undefined;
+ }
+ }
}
-
-// https://webidl.spec.whatwg.org/#idl-ArrayBuffer
-webidl.converters.ArrayBuffer = function (V, opts = {}) {
- // 1. If Type(V) is not Object, or V does not have an
- // [[ArrayBufferData]] internal slot, then throw a
- // TypeError.
- // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances
- // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances
- if (
- webidl.util.Type(V) !== 'Object' ||
- !types.isAnyArrayBuffer(V)
- ) {
- throw webidl.errors.conversionFailed({
- prefix: `${V}`,
- argument: `${V}`,
- types: ['ArrayBuffer']
- })
- }
-
- // 2. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V) is true, then throw a
- // TypeError.
- if (opts.allowShared === false && types.isSharedArrayBuffer(V)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
-
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V) is true, then throw a
- // TypeError.
- // Note: resizable ArrayBuffers are currently a proposal.
-
- // 4. Return the IDL ArrayBuffer value that is a
- // reference to the same object as V.
- return V
+exports.getOperationLocation = getOperationLocation;
+function getOperationStatus({ rawResponse }, state) {
+ var _a;
+ const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
+ switch (mode) {
+ case "OperationLocation": {
+ return getStatus(rawResponse);
+ }
+ case "ResourceLocation": {
+ return toOperationStatus(rawResponse.statusCode);
+ }
+ case "Body": {
+ return getProvisioningState(rawResponse);
+ }
+ default:
+ throw new Error(`Internal error: Unexpected operation mode: ${mode}`);
+ }
}
-
-webidl.converters.TypedArray = function (V, T, opts = {}) {
- // 1. Let T be the IDL type V is being converted to.
-
- // 2. If Type(V) is not Object, or V does not have a
- // [[TypedArrayName]] internal slot with a value
- // equal to T’s name, then throw a TypeError.
- if (
- webidl.util.Type(V) !== 'Object' ||
- !types.isTypedArray(V) ||
- V.constructor.name !== T.name
- ) {
- throw webidl.errors.conversionFailed({
- prefix: `${T.name}`,
- argument: `${V}`,
- types: [T.name]
- })
- }
-
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
-
- // 4. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- // Note: resizable array buffers are currently a proposal
-
- // 5. Return the IDL value of type T that is a reference
- // to the same object as V.
- return V
+exports.getOperationStatus = getOperationStatus;
+function accessBodyProperty({ flatResponse, rawResponse }, prop) {
+ var _a, _b;
+ return (_a = flatResponse === null || flatResponse === void 0 ? void 0 : flatResponse[prop]) !== null && _a !== void 0 ? _a : (_b = rawResponse.body) === null || _b === void 0 ? void 0 : _b[prop];
}
-
-webidl.converters.DataView = function (V, opts = {}) {
- // 1. If Type(V) is not Object, or V does not have a
- // [[DataView]] internal slot, then throw a TypeError.
- if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) {
- throw webidl.errors.exception({
- header: 'DataView',
- message: 'Object is not a DataView.'
- })
- }
-
- // 2. If the conversion is not to an IDL type associated
- // with the [AllowShared] extended attribute, and
- // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true,
- // then throw a TypeError.
- if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) {
- throw webidl.errors.exception({
- header: 'ArrayBuffer',
- message: 'SharedArrayBuffer is not allowed.'
- })
- }
-
- // 3. If the conversion is not to an IDL type associated
- // with the [AllowResizable] extended attribute, and
- // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is
- // true, then throw a TypeError.
- // Note: resizable ArrayBuffers are currently a proposal
-
- // 4. Return the IDL DataView value that is a reference
- // to the same object as V.
- return V
+function getResourceLocation(res, state) {
+ const loc = accessBodyProperty(res, "resourceLocation");
+ if (loc && typeof loc === "string") {
+ state.config.resourceLocation = loc;
+ }
+ return state.config.resourceLocation;
}
-
-// https://webidl.spec.whatwg.org/#BufferSource
-webidl.converters.BufferSource = function (V, opts = {}) {
- if (types.isAnyArrayBuffer(V)) {
- return webidl.converters.ArrayBuffer(V, opts)
- }
-
- if (types.isTypedArray(V)) {
- return webidl.converters.TypedArray(V, V.constructor)
- }
-
- if (types.isDataView(V)) {
- return webidl.converters.DataView(V, opts)
- }
-
- throw new TypeError(`Could not convert ${V} to a BufferSource.`)
+exports.getResourceLocation = getResourceLocation;
+function isOperationError(e) {
+ return e.name === "RestError";
}
-
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.ByteString
-)
-
-webidl.converters['sequence>'] = webidl.sequenceConverter(
- webidl.converters['sequence']
-)
-
-webidl.converters['record'] = webidl.recordConverter(
- webidl.converters.ByteString,
- webidl.converters.ByteString
-)
-
-module.exports = {
- webidl
+exports.isOperationError = isOperationError;
+/** Polls the long-running operation. */
+async function pollHttpOperation(inputs) {
+ const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs;
+ return (0, operation_js_1.pollOperation)({
+ state,
+ stateProxy,
+ setDelay,
+ processResult: processResult
+ ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState)
+ : ({ flatResponse }) => flatResponse,
+ getError: getErrorFromResponse,
+ updateState,
+ getPollingInterval: parseRetryAfter,
+ getOperationLocation,
+ getOperationStatus,
+ isOperationError,
+ getResourceLocation,
+ options,
+ /**
+ * The expansion here is intentional because `lro` could be an object that
+ * references an inner this, so we need to preserve a reference to it.
+ */
+ poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions),
+ setErrorAsResult,
+ });
}
-
+exports.pollHttpOperation = pollHttpOperation;
+//# sourceMappingURL=operation.js.map
/***/ }),
-/***/ 68064:
-/***/ ((module) => {
-
+/***/ 74681:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createHttpPoller = void 0;
+const operation_js_1 = __nccwpck_require__(27826);
+const poller_js_1 = __nccwpck_require__(81327);
/**
- * @see https://encoding.spec.whatwg.org/#concept-encoding-get
- * @param {string|undefined} label
+ * Creates a poller that can be used to poll a long-running operation.
+ * @param lro - Description of the long-running operation
+ * @param options - options to configure the poller
+ * @returns an initialized poller
*/
-function getEncoding (label) {
- if (!label) {
- return 'failure'
- }
-
- // 1. Remove any leading and trailing ASCII whitespace from label.
- // 2. If label is an ASCII case-insensitive match for any of the
- // labels listed in the table below, then return the
- // corresponding encoding; otherwise return failure.
- switch (label.trim().toLowerCase()) {
- case 'unicode-1-1-utf-8':
- case 'unicode11utf8':
- case 'unicode20utf8':
- case 'utf-8':
- case 'utf8':
- case 'x-unicode20utf8':
- return 'UTF-8'
- case '866':
- case 'cp866':
- case 'csibm866':
- case 'ibm866':
- return 'IBM866'
- case 'csisolatin2':
- case 'iso-8859-2':
- case 'iso-ir-101':
- case 'iso8859-2':
- case 'iso88592':
- case 'iso_8859-2':
- case 'iso_8859-2:1987':
- case 'l2':
- case 'latin2':
- return 'ISO-8859-2'
- case 'csisolatin3':
- case 'iso-8859-3':
- case 'iso-ir-109':
- case 'iso8859-3':
- case 'iso88593':
- case 'iso_8859-3':
- case 'iso_8859-3:1988':
- case 'l3':
- case 'latin3':
- return 'ISO-8859-3'
- case 'csisolatin4':
- case 'iso-8859-4':
- case 'iso-ir-110':
- case 'iso8859-4':
- case 'iso88594':
- case 'iso_8859-4':
- case 'iso_8859-4:1988':
- case 'l4':
- case 'latin4':
- return 'ISO-8859-4'
- case 'csisolatincyrillic':
- case 'cyrillic':
- case 'iso-8859-5':
- case 'iso-ir-144':
- case 'iso8859-5':
- case 'iso88595':
- case 'iso_8859-5':
- case 'iso_8859-5:1988':
- return 'ISO-8859-5'
- case 'arabic':
- case 'asmo-708':
- case 'csiso88596e':
- case 'csiso88596i':
- case 'csisolatinarabic':
- case 'ecma-114':
- case 'iso-8859-6':
- case 'iso-8859-6-e':
- case 'iso-8859-6-i':
- case 'iso-ir-127':
- case 'iso8859-6':
- case 'iso88596':
- case 'iso_8859-6':
- case 'iso_8859-6:1987':
- return 'ISO-8859-6'
- case 'csisolatingreek':
- case 'ecma-118':
- case 'elot_928':
- case 'greek':
- case 'greek8':
- case 'iso-8859-7':
- case 'iso-ir-126':
- case 'iso8859-7':
- case 'iso88597':
- case 'iso_8859-7':
- case 'iso_8859-7:1987':
- case 'sun_eu_greek':
- return 'ISO-8859-7'
- case 'csiso88598e':
- case 'csisolatinhebrew':
- case 'hebrew':
- case 'iso-8859-8':
- case 'iso-8859-8-e':
- case 'iso-ir-138':
- case 'iso8859-8':
- case 'iso88598':
- case 'iso_8859-8':
- case 'iso_8859-8:1988':
- case 'visual':
- return 'ISO-8859-8'
- case 'csiso88598i':
- case 'iso-8859-8-i':
- case 'logical':
- return 'ISO-8859-8-I'
- case 'csisolatin6':
- case 'iso-8859-10':
- case 'iso-ir-157':
- case 'iso8859-10':
- case 'iso885910':
- case 'l6':
- case 'latin6':
- return 'ISO-8859-10'
- case 'iso-8859-13':
- case 'iso8859-13':
- case 'iso885913':
- return 'ISO-8859-13'
- case 'iso-8859-14':
- case 'iso8859-14':
- case 'iso885914':
- return 'ISO-8859-14'
- case 'csisolatin9':
- case 'iso-8859-15':
- case 'iso8859-15':
- case 'iso885915':
- case 'iso_8859-15':
- case 'l9':
- return 'ISO-8859-15'
- case 'iso-8859-16':
- return 'ISO-8859-16'
- case 'cskoi8r':
- case 'koi':
- case 'koi8':
- case 'koi8-r':
- case 'koi8_r':
- return 'KOI8-R'
- case 'koi8-ru':
- case 'koi8-u':
- return 'KOI8-U'
- case 'csmacintosh':
- case 'mac':
- case 'macintosh':
- case 'x-mac-roman':
- return 'macintosh'
- case 'iso-8859-11':
- case 'iso8859-11':
- case 'iso885911':
- case 'tis-620':
- case 'windows-874':
- return 'windows-874'
- case 'cp1250':
- case 'windows-1250':
- case 'x-cp1250':
- return 'windows-1250'
- case 'cp1251':
- case 'windows-1251':
- case 'x-cp1251':
- return 'windows-1251'
- case 'ansi_x3.4-1968':
- case 'ascii':
- case 'cp1252':
- case 'cp819':
- case 'csisolatin1':
- case 'ibm819':
- case 'iso-8859-1':
- case 'iso-ir-100':
- case 'iso8859-1':
- case 'iso88591':
- case 'iso_8859-1':
- case 'iso_8859-1:1987':
- case 'l1':
- case 'latin1':
- case 'us-ascii':
- case 'windows-1252':
- case 'x-cp1252':
- return 'windows-1252'
- case 'cp1253':
- case 'windows-1253':
- case 'x-cp1253':
- return 'windows-1253'
- case 'cp1254':
- case 'csisolatin5':
- case 'iso-8859-9':
- case 'iso-ir-148':
- case 'iso8859-9':
- case 'iso88599':
- case 'iso_8859-9':
- case 'iso_8859-9:1989':
- case 'l5':
- case 'latin5':
- case 'windows-1254':
- case 'x-cp1254':
- return 'windows-1254'
- case 'cp1255':
- case 'windows-1255':
- case 'x-cp1255':
- return 'windows-1255'
- case 'cp1256':
- case 'windows-1256':
- case 'x-cp1256':
- return 'windows-1256'
- case 'cp1257':
- case 'windows-1257':
- case 'x-cp1257':
- return 'windows-1257'
- case 'cp1258':
- case 'windows-1258':
- case 'x-cp1258':
- return 'windows-1258'
- case 'x-mac-cyrillic':
- case 'x-mac-ukrainian':
- return 'x-mac-cyrillic'
- case 'chinese':
- case 'csgb2312':
- case 'csiso58gb231280':
- case 'gb2312':
- case 'gb_2312':
- case 'gb_2312-80':
- case 'gbk':
- case 'iso-ir-58':
- case 'x-gbk':
- return 'GBK'
- case 'gb18030':
- return 'gb18030'
- case 'big5':
- case 'big5-hkscs':
- case 'cn-big5':
- case 'csbig5':
- case 'x-x-big5':
- return 'Big5'
- case 'cseucpkdfmtjapanese':
- case 'euc-jp':
- case 'x-euc-jp':
- return 'EUC-JP'
- case 'csiso2022jp':
- case 'iso-2022-jp':
- return 'ISO-2022-JP'
- case 'csshiftjis':
- case 'ms932':
- case 'ms_kanji':
- case 'shift-jis':
- case 'shift_jis':
- case 'sjis':
- case 'windows-31j':
- case 'x-sjis':
- return 'Shift_JIS'
- case 'cseuckr':
- case 'csksc56011987':
- case 'euc-kr':
- case 'iso-ir-149':
- case 'korean':
- case 'ks_c_5601-1987':
- case 'ks_c_5601-1989':
- case 'ksc5601':
- case 'ksc_5601':
- case 'windows-949':
- return 'EUC-KR'
- case 'csiso2022kr':
- case 'hz-gb-2312':
- case 'iso-2022-cn':
- case 'iso-2022-cn-ext':
- case 'iso-2022-kr':
- case 'replacement':
- return 'replacement'
- case 'unicodefffe':
- case 'utf-16be':
- return 'UTF-16BE'
- case 'csunicode':
- case 'iso-10646-ucs-2':
- case 'ucs-2':
- case 'unicode':
- case 'unicodefeff':
- case 'utf-16':
- case 'utf-16le':
- return 'UTF-16LE'
- case 'x-user-defined':
- return 'x-user-defined'
- default: return 'failure'
- }
-}
-
-module.exports = {
- getEncoding
+async function createHttpPoller(lro, options) {
+ const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {};
+ return (0, poller_js_1.buildCreatePoller)({
+ getStatusFromInitialResponse: operation_js_1.getStatusFromInitialResponse,
+ getStatusFromPollResponse: operation_js_1.getOperationStatus,
+ isOperationError: operation_js_1.isOperationError,
+ getOperationLocation: operation_js_1.getOperationLocation,
+ getResourceLocation: operation_js_1.getResourceLocation,
+ getPollingInterval: operation_js_1.parseRetryAfter,
+ getError: operation_js_1.getErrorFromResponse,
+ resolveOnUnsuccessful,
+ })({
+ init: async () => {
+ const response = await lro.sendInitialRequest();
+ const config = (0, operation_js_1.inferLroMode)({
+ rawResponse: response.rawResponse,
+ requestPath: lro.requestPath,
+ requestMethod: lro.requestMethod,
+ resourceLocationConfig,
+ });
+ return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
+ },
+ poll: lro.sendPollRequest,
+ }, {
+ intervalInMs,
+ withOperationLocation,
+ restoreFrom,
+ updateState,
+ processResult: processResult
+ ? ({ flatResponse }, state) => processResult(flatResponse, state)
+ : ({ flatResponse }) => flatResponse,
+ });
}
-
+exports.createHttpPoller = createHttpPoller;
+//# sourceMappingURL=poller.js.map
/***/ }),
-/***/ 30052:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
+/***/ 1814:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const {
- staticPropertyDescriptors,
- readOperation,
- fireAProgressEvent
-} = __nccwpck_require__(94273)
-const {
- kState,
- kError,
- kResult,
- kEvents,
- kAborted
-} = __nccwpck_require__(52736)
-const { webidl } = __nccwpck_require__(94354)
-const { kEnumerableProperty } = __nccwpck_require__(89500)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createHttpPoller = void 0;
+const tslib_1 = __nccwpck_require__(94176);
+var poller_js_1 = __nccwpck_require__(74681);
+Object.defineProperty(exports, "createHttpPoller", ({ enumerable: true, get: function () { return poller_js_1.createHttpPoller; } }));
+/**
+ * This can be uncommented to expose the protocol-agnostic poller
+ */
+// export {
+// BuildCreatePollerOptions,
+// Operation,
+// CreatePollerOptions,
+// OperationConfig,
+// RestorableOperationState,
+// } from "./poller/models";
+// export { buildCreatePoller } from "./poller/poller";
+/** legacy */
+tslib_1.__exportStar(__nccwpck_require__(5618), exports);
+tslib_1.__exportStar(__nccwpck_require__(25796), exports);
+tslib_1.__exportStar(__nccwpck_require__(67130), exports);
+//# sourceMappingURL=index.js.map
-class FileReader extends EventTarget {
- constructor () {
- super()
+/***/ }),
- this[kState] = 'empty'
- this[kResult] = null
- this[kError] = null
- this[kEvents] = {
- loadend: null,
- error: null,
- abort: null,
- load: null,
- progress: null,
- loadstart: null
- }
- }
+/***/ 5618:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
- * @param {import('buffer').Blob} blob
- */
- readAsArrayBuffer (blob) {
- webidl.brandCheck(this, FileReader)
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' })
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.LroEngine = void 0;
+var lroEngine_js_1 = __nccwpck_require__(24203);
+Object.defineProperty(exports, "LroEngine", ({ enumerable: true, get: function () { return lroEngine_js_1.LroEngine; } }));
+//# sourceMappingURL=index.js.map
- blob = webidl.converters.Blob(blob, { strict: false })
+/***/ }),
- // The readAsArrayBuffer(blob) method, when invoked,
- // must initiate a read operation for blob with ArrayBuffer.
- readOperation(this, blob, 'ArrayBuffer')
- }
+/***/ 24203:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- /**
- * @see https://w3c.github.io/FileAPI/#readAsBinaryString
- * @param {import('buffer').Blob} blob
- */
- readAsBinaryString (blob) {
- webidl.brandCheck(this, FileReader)
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' })
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.LroEngine = void 0;
+const operation_js_1 = __nccwpck_require__(52175);
+const constants_js_1 = __nccwpck_require__(94288);
+const poller_js_1 = __nccwpck_require__(25796);
+const operation_js_2 = __nccwpck_require__(26588);
+/**
+ * The LRO Engine, a class that performs polling.
+ */
+class LroEngine extends poller_js_1.Poller {
+ constructor(lro, options) {
+ const { intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {};
+ const state = resumeFrom
+ ? (0, operation_js_2.deserializeState)(resumeFrom)
+ : {};
+ const operation = new operation_js_1.GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone);
+ super(operation);
+ this.resolveOnUnsuccessful = resolveOnUnsuccessful;
+ this.config = { intervalInMs: intervalInMs };
+ operation.setPollerConfig(this.config);
+ }
+ /**
+ * The method used by the poller to wait before attempting to update its operation.
+ */
+ delay() {
+ return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs));
+ }
+}
+exports.LroEngine = LroEngine;
+//# sourceMappingURL=lroEngine.js.map
- blob = webidl.converters.Blob(blob, { strict: false })
+/***/ }),
- // The readAsBinaryString(blob) method, when invoked,
- // must initiate a read operation for blob with BinaryString.
- readOperation(this, blob, 'BinaryString')
- }
+/***/ 52175:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- /**
- * @see https://w3c.github.io/FileAPI/#readAsDataText
- * @param {import('buffer').Blob} blob
- * @param {string?} encoding
- */
- readAsText (blob, encoding = undefined) {
- webidl.brandCheck(this, FileReader)
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' })
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.GenericPollOperation = void 0;
+const operation_js_1 = __nccwpck_require__(27826);
+const logger_js_1 = __nccwpck_require__(80692);
+const createStateProxy = () => ({
+ initState: (config) => ({ config, isStarted: true }),
+ setCanceled: (state) => (state.isCancelled = true),
+ setError: (state, error) => (state.error = error),
+ setResult: (state, result) => (state.result = result),
+ setRunning: (state) => (state.isStarted = true),
+ setSucceeded: (state) => (state.isCompleted = true),
+ setFailed: () => {
+ /** empty body */
+ },
+ getError: (state) => state.error,
+ getResult: (state) => state.result,
+ isCanceled: (state) => !!state.isCancelled,
+ isFailed: (state) => !!state.error,
+ isRunning: (state) => !!state.isStarted,
+ isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error),
+});
+class GenericPollOperation {
+ constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) {
+ this.state = state;
+ this.lro = lro;
+ this.setErrorAsResult = setErrorAsResult;
+ this.lroResourceLocationConfig = lroResourceLocationConfig;
+ this.processResult = processResult;
+ this.updateState = updateState;
+ this.isDone = isDone;
+ }
+ setPollerConfig(pollerConfig) {
+ this.pollerConfig = pollerConfig;
+ }
+ async update(options) {
+ var _a;
+ const stateProxy = createStateProxy();
+ if (!this.state.isStarted) {
+ this.state = Object.assign(Object.assign({}, this.state), (await (0, operation_js_1.initHttpOperation)({
+ lro: this.lro,
+ stateProxy,
+ resourceLocationConfig: this.lroResourceLocationConfig,
+ processResult: this.processResult,
+ setErrorAsResult: this.setErrorAsResult,
+ })));
+ }
+ const updateState = this.updateState;
+ const isDone = this.isDone;
+ if (!this.state.isCompleted && this.state.error === undefined) {
+ await (0, operation_js_1.pollHttpOperation)({
+ lro: this.lro,
+ state: this.state,
+ stateProxy,
+ processResult: this.processResult,
+ updateState: updateState
+ ? (state, { rawResponse }) => updateState(state, rawResponse)
+ : undefined,
+ isDone: isDone
+ ? ({ flatResponse }, state) => isDone(flatResponse, state)
+ : undefined,
+ options,
+ setDelay: (intervalInMs) => {
+ this.pollerConfig.intervalInMs = intervalInMs;
+ },
+ setErrorAsResult: this.setErrorAsResult,
+ });
+ }
+ (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state);
+ return this;
+ }
+ async cancel() {
+ logger_js_1.logger.error("`cancelOperation` is deprecated because it wasn't implemented");
+ return this;
+ }
+ /**
+ * Serializes the Poller operation.
+ */
+ toString() {
+ return JSON.stringify({
+ state: this.state,
+ });
+ }
+}
+exports.GenericPollOperation = GenericPollOperation;
+//# sourceMappingURL=operation.js.map
- blob = webidl.converters.Blob(blob, { strict: false })
+/***/ }),
- if (encoding !== undefined) {
- encoding = webidl.converters.DOMString(encoding)
- }
+/***/ 67130:
+/***/ ((__unused_webpack_module, exports) => {
- // The readAsText(blob, encoding) method, when invoked,
- // must initiate a read operation for blob with Text and encoding.
- readOperation(this, blob, 'Text', encoding)
- }
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL
- * @param {import('buffer').Blob} blob
- */
- readAsDataURL (blob) {
- webidl.brandCheck(this, FileReader)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+//# sourceMappingURL=pollOperation.js.map
- webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' })
+/***/ }),
- blob = webidl.converters.Blob(blob, { strict: false })
+/***/ 25796:
+/***/ ((__unused_webpack_module, exports) => {
- // The readAsDataURL(blob) method, when invoked, must
- // initiate a read operation for blob with DataURL.
- readOperation(this, blob, 'DataURL')
- }
- /**
- * @see https://w3c.github.io/FileAPI/#dfn-abort
- */
- abort () {
- // 1. If this's state is "empty" or if this's state is
- // "done" set this's result to null and terminate
- // this algorithm.
- if (this[kState] === 'empty' || this[kState] === 'done') {
- this[kResult] = null
- return
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Poller = exports.PollerCancelledError = exports.PollerStoppedError = void 0;
+/**
+ * When a poller is manually stopped through the `stopPolling` method,
+ * the poller will be rejected with an instance of the PollerStoppedError.
+ */
+class PollerStoppedError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "PollerStoppedError";
+ Object.setPrototypeOf(this, PollerStoppedError.prototype);
}
-
- // 2. If this's state is "loading" set this's state to
- // "done" and set this's result to null.
- if (this[kState] === 'loading') {
- this[kState] = 'done'
- this[kResult] = null
+}
+exports.PollerStoppedError = PollerStoppedError;
+/**
+ * When the operation is cancelled, the poller will be rejected with an instance
+ * of the PollerCancelledError.
+ */
+class PollerCancelledError extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "PollerCancelledError";
+ Object.setPrototypeOf(this, PollerCancelledError.prototype);
}
-
- // 3. If there are any tasks from this on the file reading
- // task source in an affiliated task queue, then remove
- // those tasks from that task queue.
- this[kAborted] = true
-
- // 4. Terminate the algorithm for the read method being processed.
- // TODO
-
- // 5. Fire a progress event called abort at this.
- fireAProgressEvent('abort', this)
-
- // 6. If this's state is not "loading", fire a progress
- // event called loadend at this.
- if (this[kState] !== 'loading') {
- fireAProgressEvent('loadend', this)
+}
+exports.PollerCancelledError = PollerCancelledError;
+/**
+ * A class that represents the definition of a program that polls through consecutive requests
+ * until it reaches a state of completion.
+ *
+ * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed.
+ * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes.
+ * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation.
+ *
+ * ```ts
+ * const poller = new MyPoller();
+ *
+ * // Polling just once:
+ * await poller.poll();
+ *
+ * // We can try to cancel the request here, by calling:
+ * //
+ * // await poller.cancelOperation();
+ * //
+ *
+ * // Getting the final result:
+ * const result = await poller.pollUntilDone();
+ * ```
+ *
+ * The Poller is defined by two types, a type representing the state of the poller, which
+ * must include a basic set of properties from `PollOperationState`,
+ * and a return type defined by `TResult`, which can be anything.
+ *
+ * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having
+ * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type.
+ *
+ * ```ts
+ * class Client {
+ * public async makePoller: PollerLike {
+ * const poller = new MyPoller({});
+ * // It might be preferred to return the poller after the first request is made,
+ * // so that some information can be obtained right away.
+ * await poller.poll();
+ * return poller;
+ * }
+ * }
+ *
+ * const poller: PollerLike = myClient.makePoller();
+ * ```
+ *
+ * A poller can be created through its constructor, then it can be polled until it's completed.
+ * At any point in time, the state of the poller can be obtained without delay through the getOperationState method.
+ * At any point in time, the intermediate forms of the result type can be requested without delay.
+ * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned.
+ *
+ * ```ts
+ * const poller = myClient.makePoller();
+ * const state: MyOperationState = poller.getOperationState();
+ *
+ * // The intermediate result can be obtained at any time.
+ * const result: MyResult | undefined = poller.getResult();
+ *
+ * // The final result can only be obtained after the poller finishes.
+ * const result: MyResult = await poller.pollUntilDone();
+ * ```
+ *
+ */
+// eslint-disable-next-line no-use-before-define
+class Poller {
+ /**
+ * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation`.
+ *
+ * When writing an implementation of a Poller, this implementation needs to deal with the initialization
+ * of any custom state beyond the basic definition of the poller. The basic poller assumes that the poller's
+ * operation has already been defined, at least its basic properties. The code below shows how to approach
+ * the definition of the constructor of a new custom poller.
+ *
+ * ```ts
+ * export class MyPoller extends Poller {
+ * constructor({
+ * // Anything you might need outside of the basics
+ * }) {
+ * let state: MyOperationState = {
+ * privateProperty: private,
+ * publicProperty: public,
+ * };
+ *
+ * const operation = {
+ * state,
+ * update,
+ * cancel,
+ * toString
+ * }
+ *
+ * // Sending the operation to the parent's constructor.
+ * super(operation);
+ *
+ * // You can assign more local properties here.
+ * }
+ * }
+ * ```
+ *
+ * Inside of this constructor, a new promise is created. This will be used to
+ * tell the user when the poller finishes (see `pollUntilDone()`). The promise's
+ * resolve and reject methods are also used internally to control when to resolve
+ * or reject anyone waiting for the poller to finish.
+ *
+ * The constructor of a custom implementation of a poller is where any serialized version of
+ * a previous poller's operation should be deserialized into the operation sent to the
+ * base constructor. For example:
+ *
+ * ```ts
+ * export class MyPoller extends Poller {
+ * constructor(
+ * baseOperation: string | undefined
+ * ) {
+ * let state: MyOperationState = {};
+ * if (baseOperation) {
+ * state = {
+ * ...JSON.parse(baseOperation).state,
+ * ...state
+ * };
+ * }
+ * const operation = {
+ * state,
+ * // ...
+ * }
+ * super(operation);
+ * }
+ * }
+ * ```
+ *
+ * @param operation - Must contain the basic properties of `PollOperation`.
+ */
+ constructor(operation) {
+ /** controls whether to throw an error if the operation failed or was canceled. */
+ this.resolveOnUnsuccessful = false;
+ this.stopped = true;
+ this.pollProgressCallbacks = [];
+ this.operation = operation;
+ this.promise = new Promise((resolve, reject) => {
+ this.resolve = resolve;
+ this.reject = reject;
+ });
+ // This prevents the UnhandledPromiseRejectionWarning in node.js from being thrown.
+ // The above warning would get thrown if `poller.poll` is called, it returns an error,
+ // and pullUntilDone did not have a .catch or await try/catch on it's return value.
+ this.promise.catch(() => {
+ /* intentionally blank */
+ });
}
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate
- */
- get readyState () {
- webidl.brandCheck(this, FileReader)
-
- switch (this[kState]) {
- case 'empty': return this.EMPTY
- case 'loading': return this.LOADING
- case 'done': return this.DONE
+ /**
+ * Starts a loop that will break only if the poller is done
+ * or if the poller is stopped.
+ */
+ async startPolling(pollOptions = {}) {
+ if (this.stopped) {
+ this.stopped = false;
+ }
+ while (!this.isStopped() && !this.isDone()) {
+ await this.poll(pollOptions);
+ await this.delay();
+ }
+ }
+ /**
+ * pollOnce does one polling, by calling to the update method of the underlying
+ * poll operation to make any relevant change effective.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ async pollOnce(options = {}) {
+ if (!this.isDone()) {
+ this.operation = await this.operation.update({
+ abortSignal: options.abortSignal,
+ fireProgress: this.fireProgress.bind(this),
+ });
+ }
+ this.processUpdatedState();
+ }
+ /**
+ * fireProgress calls the functions passed in via onProgress the method of the poller.
+ *
+ * It loops over all of the callbacks received from onProgress, and executes them, sending them
+ * the current operation state.
+ *
+ * @param state - The current operation state.
+ */
+ fireProgress(state) {
+ for (const callback of this.pollProgressCallbacks) {
+ callback(state);
+ }
+ }
+ /**
+ * Invokes the underlying operation's cancel method.
+ */
+ async cancelOnce(options = {}) {
+ this.operation = await this.operation.cancel(options);
+ }
+ /**
+ * Returns a promise that will resolve once a single polling request finishes.
+ * It does this by calling the update method of the Poller's operation.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ poll(options = {}) {
+ if (!this.pollOncePromise) {
+ this.pollOncePromise = this.pollOnce(options);
+ const clearPollOncePromise = () => {
+ this.pollOncePromise = undefined;
+ };
+ this.pollOncePromise.then(clearPollOncePromise, clearPollOncePromise).catch(this.reject);
+ }
+ return this.pollOncePromise;
+ }
+ processUpdatedState() {
+ if (this.operation.state.error) {
+ this.stopped = true;
+ if (!this.resolveOnUnsuccessful) {
+ this.reject(this.operation.state.error);
+ throw this.operation.state.error;
+ }
+ }
+ if (this.operation.state.isCancelled) {
+ this.stopped = true;
+ if (!this.resolveOnUnsuccessful) {
+ const error = new PollerCancelledError("Operation was canceled");
+ this.reject(error);
+ throw error;
+ }
+ }
+ if (this.isDone() && this.resolve) {
+ // If the poller has finished polling, this means we now have a result.
+ // However, it can be the case that TResult is instantiated to void, so
+ // we are not expecting a result anyway. To assert that we might not
+ // have a result eventually after finishing polling, we cast the result
+ // to TResult.
+ this.resolve(this.getResult());
+ }
+ }
+ /**
+ * Returns a promise that will resolve once the underlying operation is completed.
+ */
+ async pollUntilDone(pollOptions = {}) {
+ if (this.stopped) {
+ this.startPolling(pollOptions).catch(this.reject);
+ }
+ // This is needed because the state could have been updated by
+ // `cancelOperation`, e.g. the operation is canceled or an error occurred.
+ this.processUpdatedState();
+ return this.promise;
+ }
+ /**
+ * Invokes the provided callback after each polling is completed,
+ * sending the current state of the poller's operation.
+ *
+ * It returns a method that can be used to stop receiving updates on the given callback function.
+ */
+ onProgress(callback) {
+ this.pollProgressCallbacks.push(callback);
+ return () => {
+ this.pollProgressCallbacks = this.pollProgressCallbacks.filter((c) => c !== callback);
+ };
+ }
+ /**
+ * Returns true if the poller has finished polling.
+ */
+ isDone() {
+ const state = this.operation.state;
+ return Boolean(state.isCompleted || state.isCancelled || state.error);
+ }
+ /**
+ * Stops the poller from continuing to poll.
+ */
+ stopPolling() {
+ if (!this.stopped) {
+ this.stopped = true;
+ if (this.reject) {
+ this.reject(new PollerStoppedError("This poller is already stopped"));
+ }
+ }
+ }
+ /**
+ * Returns true if the poller is stopped.
+ */
+ isStopped() {
+ return this.stopped;
+ }
+ /**
+ * Attempts to cancel the underlying operation.
+ *
+ * It only optionally receives an object with an abortSignal property, from \@azure/abort-controller's AbortSignalLike.
+ *
+ * If it's called again before it finishes, it will throw an error.
+ *
+ * @param options - Optional properties passed to the operation's update method.
+ */
+ cancelOperation(options = {}) {
+ if (!this.cancelPromise) {
+ this.cancelPromise = this.cancelOnce(options);
+ }
+ else if (options.abortSignal) {
+ throw new Error("A cancel request is currently pending");
+ }
+ return this.cancelPromise;
}
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-result
- */
- get result () {
- webidl.brandCheck(this, FileReader)
-
- // The result attribute’s getter, when invoked, must return
- // this's result.
- return this[kResult]
- }
-
- /**
- * @see https://w3c.github.io/FileAPI/#dom-filereader-error
- */
- get error () {
- webidl.brandCheck(this, FileReader)
-
- // The error attribute’s getter, when invoked, must return
- // this's error.
- return this[kError]
- }
-
- get onloadend () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].loadend
- }
-
- set onloadend (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].loadend) {
- this.removeEventListener('loadend', this[kEvents].loadend)
+ /**
+ * Returns the state of the operation.
+ *
+ * Even though TState will be the same type inside any of the methods of any extension of the Poller class,
+ * implementations of the pollers can customize what's shared with the public by writing their own
+ * version of the `getOperationState` method, and by defining two types, one representing the internal state of the poller
+ * and a public type representing a safe to share subset of the properties of the internal state.
+ * Their definition of getOperationState can then return their public type.
+ *
+ * Example:
+ *
+ * ```ts
+ * // Let's say we have our poller's operation state defined as:
+ * interface MyOperationState extends PollOperationState {
+ * privateProperty?: string;
+ * publicProperty?: string;
+ * }
+ *
+ * // To allow us to have a true separation of public and private state, we have to define another interface:
+ * interface PublicState extends PollOperationState {
+ * publicProperty?: string;
+ * }
+ *
+ * // Then, we define our Poller as follows:
+ * export class MyPoller extends Poller {
+ * // ... More content is needed here ...
+ *
+ * public getOperationState(): PublicState {
+ * const state: PublicState = this.operation.state;
+ * return {
+ * // Properties from PollOperationState
+ * isStarted: state.isStarted,
+ * isCompleted: state.isCompleted,
+ * isCancelled: state.isCancelled,
+ * error: state.error,
+ * result: state.result,
+ *
+ * // The only other property needed by PublicState.
+ * publicProperty: state.publicProperty
+ * }
+ * }
+ * }
+ * ```
+ *
+ * You can see this in the tests of this repository, go to the file:
+ * `../test/utils/testPoller.ts`
+ * and look for the getOperationState implementation.
+ */
+ getOperationState() {
+ return this.operation.state;
}
-
- if (typeof fn === 'function') {
- this[kEvents].loadend = fn
- this.addEventListener('loadend', fn)
- } else {
- this[kEvents].loadend = null
+ /**
+ * Returns the result value of the operation,
+ * regardless of the state of the poller.
+ * It can return undefined or an incomplete form of the final TResult value
+ * depending on the implementation.
+ */
+ getResult() {
+ const state = this.operation.state;
+ return state.result;
}
- }
-
- get onerror () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].error
- }
+ /**
+ * Returns a serialized version of the poller's operation
+ * by invoking the operation's toString method.
+ */
+ toString() {
+ return this.operation.toString();
+ }
+}
+exports.Poller = Poller;
+//# sourceMappingURL=poller.js.map
- set onerror (fn) {
- webidl.brandCheck(this, FileReader)
+/***/ }),
- if (this[kEvents].error) {
- this.removeEventListener('error', this[kEvents].error)
- }
+/***/ 80692:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (typeof fn === 'function') {
- this[kEvents].error = fn
- this.addEventListener('error', fn)
- } else {
- this[kEvents].error = null
- }
- }
- get onloadstart () {
- webidl.brandCheck(this, FileReader)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logger = void 0;
+const logger_1 = __nccwpck_require__(50143);
+/**
+ * The `@azure/logger` configuration for this package.
+ * @internal
+ */
+exports.logger = (0, logger_1.createClientLogger)("core-lro");
+//# sourceMappingURL=logger.js.map
- return this[kEvents].loadstart
- }
+/***/ }),
- set onloadstart (fn) {
- webidl.brandCheck(this, FileReader)
+/***/ 94288:
+/***/ ((__unused_webpack_module, exports) => {
- if (this[kEvents].loadstart) {
- this.removeEventListener('loadstart', this[kEvents].loadstart)
- }
- if (typeof fn === 'function') {
- this[kEvents].loadstart = fn
- this.addEventListener('loadstart', fn)
- } else {
- this[kEvents].loadstart = null
- }
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.terminalStates = exports.POLL_INTERVAL_IN_MS = void 0;
+/**
+ * The default time interval to wait before sending the next polling request.
+ */
+exports.POLL_INTERVAL_IN_MS = 2000;
+/**
+ * The closed set of terminal states.
+ */
+exports.terminalStates = ["succeeded", "canceled", "failed"];
+//# sourceMappingURL=constants.js.map
- get onprogress () {
- webidl.brandCheck(this, FileReader)
+/***/ }),
- return this[kEvents].progress
- }
+/***/ 26588:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- set onprogress (fn) {
- webidl.brandCheck(this, FileReader)
- if (this[kEvents].progress) {
- this.removeEventListener('progress', this[kEvents].progress)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.pollOperation = exports.initOperation = exports.deserializeState = void 0;
+const logger_js_1 = __nccwpck_require__(80692);
+const constants_js_1 = __nccwpck_require__(94288);
+/**
+ * Deserializes the state
+ */
+function deserializeState(serializedState) {
+ try {
+ return JSON.parse(serializedState).state;
}
-
- if (typeof fn === 'function') {
- this[kEvents].progress = fn
- this.addEventListener('progress', fn)
- } else {
- this[kEvents].progress = null
+ catch (e) {
+ throw new Error(`Unable to deserialize input state: ${serializedState}`);
}
- }
-
- get onload () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].load
- }
-
- set onload (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].load) {
- this.removeEventListener('load', this[kEvents].load)
+}
+exports.deserializeState = deserializeState;
+function setStateError(inputs) {
+ const { state, stateProxy, isOperationError } = inputs;
+ return (error) => {
+ if (isOperationError(error)) {
+ stateProxy.setError(state, error);
+ stateProxy.setFailed(state);
+ }
+ throw error;
+ };
+}
+function appendReadableErrorMessage(currentMessage, innerMessage) {
+ let message = currentMessage;
+ if (message.slice(-1) !== ".") {
+ message = message + ".";
}
-
- if (typeof fn === 'function') {
- this[kEvents].load = fn
- this.addEventListener('load', fn)
- } else {
- this[kEvents].load = null
+ return message + " " + innerMessage;
+}
+function simplifyError(err) {
+ let message = err.message;
+ let code = err.code;
+ let curErr = err;
+ while (curErr.innererror) {
+ curErr = curErr.innererror;
+ code = curErr.code;
+ message = appendReadableErrorMessage(message, curErr.message);
}
- }
-
- get onabort () {
- webidl.brandCheck(this, FileReader)
-
- return this[kEvents].abort
- }
-
- set onabort (fn) {
- webidl.brandCheck(this, FileReader)
-
- if (this[kEvents].abort) {
- this.removeEventListener('abort', this[kEvents].abort)
+ return {
+ code,
+ message,
+ };
+}
+function processOperationStatus(result) {
+ const { state, stateProxy, status, isDone, processResult, getError, response, setErrorAsResult } = result;
+ switch (status) {
+ case "succeeded": {
+ stateProxy.setSucceeded(state);
+ break;
+ }
+ case "failed": {
+ const err = getError === null || getError === void 0 ? void 0 : getError(response);
+ let postfix = "";
+ if (err) {
+ const { code, message } = simplifyError(err);
+ postfix = `. ${code}. ${message}`;
+ }
+ const errStr = `The long-running operation has failed${postfix}`;
+ stateProxy.setError(state, new Error(errStr));
+ stateProxy.setFailed(state);
+ logger_js_1.logger.warning(errStr);
+ break;
+ }
+ case "canceled": {
+ stateProxy.setCanceled(state);
+ break;
+ }
}
-
- if (typeof fn === 'function') {
- this[kEvents].abort = fn
- this.addEventListener('abort', fn)
- } else {
- this[kEvents].abort = null
+ if ((isDone === null || isDone === void 0 ? void 0 : isDone(response, state)) ||
+ (isDone === undefined &&
+ ["succeeded", "canceled"].concat(setErrorAsResult ? [] : ["failed"]).includes(status))) {
+ stateProxy.setResult(state, buildResult({
+ response,
+ state,
+ processResult,
+ }));
}
- }
}
-
-// https://w3c.github.io/FileAPI/#dom-filereader-empty
-FileReader.EMPTY = FileReader.prototype.EMPTY = 0
-// https://w3c.github.io/FileAPI/#dom-filereader-loading
-FileReader.LOADING = FileReader.prototype.LOADING = 1
-// https://w3c.github.io/FileAPI/#dom-filereader-done
-FileReader.DONE = FileReader.prototype.DONE = 2
-
-Object.defineProperties(FileReader.prototype, {
- EMPTY: staticPropertyDescriptors,
- LOADING: staticPropertyDescriptors,
- DONE: staticPropertyDescriptors,
- readAsArrayBuffer: kEnumerableProperty,
- readAsBinaryString: kEnumerableProperty,
- readAsText: kEnumerableProperty,
- readAsDataURL: kEnumerableProperty,
- abort: kEnumerableProperty,
- readyState: kEnumerableProperty,
- result: kEnumerableProperty,
- error: kEnumerableProperty,
- onloadstart: kEnumerableProperty,
- onprogress: kEnumerableProperty,
- onload: kEnumerableProperty,
- onabort: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onloadend: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'FileReader',
- writable: false,
- enumerable: false,
- configurable: true
- }
-})
-
-Object.defineProperties(FileReader, {
- EMPTY: staticPropertyDescriptors,
- LOADING: staticPropertyDescriptors,
- DONE: staticPropertyDescriptors
-})
-
-module.exports = {
- FileReader
+function buildResult(inputs) {
+ const { processResult, response, state } = inputs;
+ return processResult ? processResult(response, state) : response;
}
-
-
-/***/ }),
-
-/***/ 92804:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { webidl } = __nccwpck_require__(94354)
-
-const kState = Symbol('ProgressEvent state')
-
/**
- * @see https://xhr.spec.whatwg.org/#progressevent
+ * Initiates the long-running operation.
*/
-class ProgressEvent extends Event {
- constructor (type, eventInitDict = {}) {
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {})
-
- super(type, eventInitDict)
-
- this[kState] = {
- lengthComputable: eventInitDict.lengthComputable,
- loaded: eventInitDict.loaded,
- total: eventInitDict.total
+async function initOperation(inputs) {
+ const { init, stateProxy, processResult, getOperationStatus, withOperationLocation, setErrorAsResult, } = inputs;
+ const { operationLocation, resourceLocation, metadata, response } = await init();
+ if (operationLocation)
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
+ const config = {
+ metadata,
+ operationLocation,
+ resourceLocation,
+ };
+ logger_js_1.logger.verbose(`LRO: Operation description:`, config);
+ const state = stateProxy.initState(config);
+ const status = getOperationStatus({ response, state, operationLocation });
+ processOperationStatus({ state, status, stateProxy, response, setErrorAsResult, processResult });
+ return state;
+}
+exports.initOperation = initOperation;
+async function pollOperationHelper(inputs) {
+ const { poll, state, stateProxy, operationLocation, getOperationStatus, getResourceLocation, isOperationError, options, } = inputs;
+ const response = await poll(operationLocation, options).catch(setStateError({
+ state,
+ stateProxy,
+ isOperationError,
+ }));
+ const status = getOperationStatus(response, state);
+ logger_js_1.logger.verbose(`LRO: Status:\n\tPolling from: ${state.config.operationLocation}\n\tOperation status: ${status}\n\tPolling status: ${constants_js_1.terminalStates.includes(status) ? "Stopped" : "Running"}`);
+ if (status === "succeeded") {
+ const resourceLocation = getResourceLocation(response, state);
+ if (resourceLocation !== undefined) {
+ return {
+ response: await poll(resourceLocation).catch(setStateError({ state, stateProxy, isOperationError })),
+ status,
+ };
+ }
}
- }
-
- get lengthComputable () {
- webidl.brandCheck(this, ProgressEvent)
-
- return this[kState].lengthComputable
- }
-
- get loaded () {
- webidl.brandCheck(this, ProgressEvent)
-
- return this[kState].loaded
- }
-
- get total () {
- webidl.brandCheck(this, ProgressEvent)
-
- return this[kState].total
- }
+ return { response, status };
}
-
-webidl.converters.ProgressEventInit = webidl.dictionaryConverter([
- {
- key: 'lengthComputable',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'loaded',
- converter: webidl.converters['unsigned long long'],
- defaultValue: 0
- },
- {
- key: 'total',
- converter: webidl.converters['unsigned long long'],
- defaultValue: 0
- },
- {
- key: 'bubbles',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'cancelable',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'composed',
- converter: webidl.converters.boolean,
- defaultValue: false
- }
-])
-
-module.exports = {
- ProgressEvent
+/** Polls the long-running operation. */
+async function pollOperation(inputs) {
+ const { poll, state, stateProxy, options, getOperationStatus, getResourceLocation, getOperationLocation, isOperationError, withOperationLocation, getPollingInterval, processResult, getError, updateState, setDelay, isDone, setErrorAsResult, } = inputs;
+ const { operationLocation } = state.config;
+ if (operationLocation !== undefined) {
+ const { response, status } = await pollOperationHelper({
+ poll,
+ getOperationStatus,
+ state,
+ stateProxy,
+ operationLocation,
+ getResourceLocation,
+ isOperationError,
+ options,
+ });
+ processOperationStatus({
+ status,
+ response,
+ state,
+ stateProxy,
+ isDone,
+ processResult,
+ getError,
+ setErrorAsResult,
+ });
+ if (!constants_js_1.terminalStates.includes(status)) {
+ const intervalInMs = getPollingInterval === null || getPollingInterval === void 0 ? void 0 : getPollingInterval(response);
+ if (intervalInMs)
+ setDelay(intervalInMs);
+ const location = getOperationLocation === null || getOperationLocation === void 0 ? void 0 : getOperationLocation(response, state);
+ if (location !== undefined) {
+ const isUpdated = operationLocation !== location;
+ state.config.operationLocation = location;
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(location, isUpdated);
+ }
+ else
+ withOperationLocation === null || withOperationLocation === void 0 ? void 0 : withOperationLocation(operationLocation, false);
+ }
+ updateState === null || updateState === void 0 ? void 0 : updateState(state, response);
+ }
}
-
+exports.pollOperation = pollOperation;
+//# sourceMappingURL=operation.js.map
/***/ }),
-/***/ 52736:
-/***/ ((module) => {
-
+/***/ 81327:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = {
- kState: Symbol('FileReader state'),
- kResult: Symbol('FileReader result'),
- kError: Symbol('FileReader error'),
- kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'),
- kEvents: Symbol('FileReader events'),
- kAborted: Symbol('FileReader aborted')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.buildCreatePoller = void 0;
+const operation_js_1 = __nccwpck_require__(26588);
+const constants_js_1 = __nccwpck_require__(94288);
+const core_util_1 = __nccwpck_require__(30991);
+const createStateProxy = () => ({
+ /**
+ * The state at this point is created to be of type OperationState.
+ * It will be updated later to be of type TState when the
+ * customer-provided callback, `updateState`, is called during polling.
+ */
+ initState: (config) => ({ status: "running", config }),
+ setCanceled: (state) => (state.status = "canceled"),
+ setError: (state, error) => (state.error = error),
+ setResult: (state, result) => (state.result = result),
+ setRunning: (state) => (state.status = "running"),
+ setSucceeded: (state) => (state.status = "succeeded"),
+ setFailed: (state) => (state.status = "failed"),
+ getError: (state) => state.error,
+ getResult: (state) => state.result,
+ isCanceled: (state) => state.status === "canceled",
+ isFailed: (state) => state.status === "failed",
+ isRunning: (state) => state.status === "running",
+ isSucceeded: (state) => state.status === "succeeded",
+});
+/**
+ * Returns a poller factory.
+ */
+function buildCreatePoller(inputs) {
+ const { getOperationLocation, getStatusFromInitialResponse, getStatusFromPollResponse, isOperationError, getResourceLocation, getPollingInterval, getError, resolveOnUnsuccessful, } = inputs;
+ return async ({ init, poll }, options) => {
+ const { processResult, updateState, withOperationLocation: withOperationLocationCallback, intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, restoreFrom, } = options || {};
+ const stateProxy = createStateProxy();
+ const withOperationLocation = withOperationLocationCallback
+ ? (() => {
+ let called = false;
+ return (operationLocation, isUpdated) => {
+ if (isUpdated)
+ withOperationLocationCallback(operationLocation);
+ else if (!called)
+ withOperationLocationCallback(operationLocation);
+ called = true;
+ };
+ })()
+ : undefined;
+ const state = restoreFrom
+ ? (0, operation_js_1.deserializeState)(restoreFrom)
+ : await (0, operation_js_1.initOperation)({
+ init,
+ stateProxy,
+ processResult,
+ getOperationStatus: getStatusFromInitialResponse,
+ withOperationLocation,
+ setErrorAsResult: !resolveOnUnsuccessful,
+ });
+ let resultPromise;
+ const abortController = new AbortController();
+ const handlers = new Map();
+ const handleProgressEvents = async () => handlers.forEach((h) => h(state));
+ const cancelErrMsg = "Operation was canceled";
+ let currentPollIntervalInMs = intervalInMs;
+ const poller = {
+ getOperationState: () => state,
+ getResult: () => state.result,
+ isDone: () => ["succeeded", "failed", "canceled"].includes(state.status),
+ isStopped: () => resultPromise === undefined,
+ stopPolling: () => {
+ abortController.abort();
+ },
+ toString: () => JSON.stringify({
+ state,
+ }),
+ onProgress: (callback) => {
+ const s = Symbol();
+ handlers.set(s, callback);
+ return () => handlers.delete(s);
+ },
+ pollUntilDone: (pollOptions) => (resultPromise !== null && resultPromise !== void 0 ? resultPromise : (resultPromise = (async () => {
+ const { abortSignal: inputAbortSignal } = pollOptions || {};
+ // In the future we can use AbortSignal.any() instead
+ function abortListener() {
+ abortController.abort();
+ }
+ const abortSignal = abortController.signal;
+ if (inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.aborted) {
+ abortController.abort();
+ }
+ else if (!abortSignal.aborted) {
+ inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.addEventListener("abort", abortListener, { once: true });
+ }
+ try {
+ if (!poller.isDone()) {
+ await poller.poll({ abortSignal });
+ while (!poller.isDone()) {
+ await (0, core_util_1.delay)(currentPollIntervalInMs, { abortSignal });
+ await poller.poll({ abortSignal });
+ }
+ }
+ }
+ finally {
+ inputAbortSignal === null || inputAbortSignal === void 0 ? void 0 : inputAbortSignal.removeEventListener("abort", abortListener);
+ }
+ if (resolveOnUnsuccessful) {
+ return poller.getResult();
+ }
+ else {
+ switch (state.status) {
+ case "succeeded":
+ return poller.getResult();
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ case "notStarted":
+ case "running":
+ throw new Error(`Polling completed without succeeding or failing`);
+ }
+ }
+ })().finally(() => {
+ resultPromise = undefined;
+ }))),
+ async poll(pollOptions) {
+ if (resolveOnUnsuccessful) {
+ if (poller.isDone())
+ return;
+ }
+ else {
+ switch (state.status) {
+ case "succeeded":
+ return;
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ }
+ }
+ await (0, operation_js_1.pollOperation)({
+ poll,
+ state,
+ stateProxy,
+ getOperationLocation,
+ isOperationError,
+ withOperationLocation,
+ getPollingInterval,
+ getOperationStatus: getStatusFromPollResponse,
+ getResourceLocation,
+ processResult,
+ getError,
+ updateState,
+ options: pollOptions,
+ setDelay: (pollIntervalInMs) => {
+ currentPollIntervalInMs = pollIntervalInMs;
+ },
+ setErrorAsResult: !resolveOnUnsuccessful,
+ });
+ await handleProgressEvents();
+ if (!resolveOnUnsuccessful) {
+ switch (state.status) {
+ case "canceled":
+ throw new Error(cancelErrMsg);
+ case "failed":
+ throw state.error;
+ }
+ }
+ },
+ };
+ return poller;
+ };
}
-
+exports.buildCreatePoller = buildCreatePoller;
+//# sourceMappingURL=poller.js.map
/***/ }),
-/***/ 94273:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 91791:
+/***/ ((__unused_webpack_module, exports) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.DEFAULT_RETRY_POLICY_COUNT = exports.SDK_VERSION = void 0;
+exports.SDK_VERSION = "1.18.1";
+exports.DEFAULT_RETRY_POLICY_COUNT = 3;
+//# sourceMappingURL=constants.js.map
-const {
- kState,
- kError,
- kResult,
- kAborted,
- kLastProgressEventFired
-} = __nccwpck_require__(52736)
-const { ProgressEvent } = __nccwpck_require__(92804)
-const { getEncoding } = __nccwpck_require__(68064)
-const { DOMException } = __nccwpck_require__(21234)
-const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(37246)
-const { types } = __nccwpck_require__(39023)
-const { StringDecoder } = __nccwpck_require__(13193)
-const { btoa } = __nccwpck_require__(20181)
+/***/ }),
+
+/***/ 1130:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-/** @type {PropertyDescriptor} */
-const staticPropertyDescriptors = {
- enumerable: true,
- writable: false,
- configurable: false
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPipelineFromOptions = createPipelineFromOptions;
+const logPolicy_js_1 = __nccwpck_require__(19937);
+const pipeline_js_1 = __nccwpck_require__(37050);
+const redirectPolicy_js_1 = __nccwpck_require__(86947);
+const userAgentPolicy_js_1 = __nccwpck_require__(69795);
+const multipartPolicy_js_1 = __nccwpck_require__(77915);
+const decompressResponsePolicy_js_1 = __nccwpck_require__(13299);
+const defaultRetryPolicy_js_1 = __nccwpck_require__(47494);
+const formDataPolicy_js_1 = __nccwpck_require__(37997);
+const core_util_1 = __nccwpck_require__(30991);
+const proxyPolicy_js_1 = __nccwpck_require__(73723);
+const setClientRequestIdPolicy_js_1 = __nccwpck_require__(63866);
+const tlsPolicy_js_1 = __nccwpck_require__(39370);
+const tracingPolicy_js_1 = __nccwpck_require__(14113);
/**
- * @see https://w3c.github.io/FileAPI/#readOperation
- * @param {import('./filereader').FileReader} fr
- * @param {import('buffer').Blob} blob
- * @param {string} type
- * @param {string?} encodingName
+ * Create a new pipeline with a default set of customizable policies.
+ * @param options - Options to configure a custom pipeline.
*/
-function readOperation (fr, blob, type, encodingName) {
- // 1. If fr’s state is "loading", throw an InvalidStateError
- // DOMException.
- if (fr[kState] === 'loading') {
- throw new DOMException('Invalid state', 'InvalidStateError')
- }
-
- // 2. Set fr’s state to "loading".
- fr[kState] = 'loading'
-
- // 3. Set fr’s result to null.
- fr[kResult] = null
-
- // 4. Set fr’s error to null.
- fr[kError] = null
-
- // 5. Let stream be the result of calling get stream on blob.
- /** @type {import('stream/web').ReadableStream} */
- const stream = blob.stream()
-
- // 6. Let reader be the result of getting a reader from stream.
- const reader = stream.getReader()
-
- // 7. Let bytes be an empty byte sequence.
- /** @type {Uint8Array[]} */
- const bytes = []
-
- // 8. Let chunkPromise be the result of reading a chunk from
- // stream with reader.
- let chunkPromise = reader.read()
-
- // 9. Let isFirstChunk be true.
- let isFirstChunk = true
-
- // 10. In parallel, while true:
- // Note: "In parallel" just means non-blocking
- // Note 2: readOperation itself cannot be async as double
- // reading the body would then reject the promise, instead
- // of throwing an error.
- ;(async () => {
- while (!fr[kAborted]) {
- // 1. Wait for chunkPromise to be fulfilled or rejected.
- try {
- const { done, value } = await chunkPromise
-
- // 2. If chunkPromise is fulfilled, and isFirstChunk is
- // true, queue a task to fire a progress event called
- // loadstart at fr.
- if (isFirstChunk && !fr[kAborted]) {
- queueMicrotask(() => {
- fireAProgressEvent('loadstart', fr)
- })
+function createPipelineFromOptions(options) {
+ var _a;
+ const pipeline = (0, pipeline_js_1.createEmptyPipeline)();
+ if (core_util_1.isNodeLike) {
+ if (options.tlsOptions) {
+ pipeline.addPolicy((0, tlsPolicy_js_1.tlsPolicy)(options.tlsOptions));
}
+ pipeline.addPolicy((0, proxyPolicy_js_1.proxyPolicy)(options.proxyOptions));
+ pipeline.addPolicy((0, decompressResponsePolicy_js_1.decompressResponsePolicy)());
+ }
+ pipeline.addPolicy((0, formDataPolicy_js_1.formDataPolicy)(), { beforePolicies: [multipartPolicy_js_1.multipartPolicyName] });
+ pipeline.addPolicy((0, userAgentPolicy_js_1.userAgentPolicy)(options.userAgentOptions));
+ pipeline.addPolicy((0, setClientRequestIdPolicy_js_1.setClientRequestIdPolicy)((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName));
+ // The multipart policy is added after policies with no phase, so that
+ // policies can be added between it and formDataPolicy to modify
+ // properties (e.g., making the boundary constant in recorded tests).
+ pipeline.addPolicy((0, multipartPolicy_js_1.multipartPolicy)(), { afterPhase: "Deserialize" });
+ pipeline.addPolicy((0, defaultRetryPolicy_js_1.defaultRetryPolicy)(options.retryOptions), { phase: "Retry" });
+ pipeline.addPolicy((0, tracingPolicy_js_1.tracingPolicy)(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), {
+ afterPhase: "Retry",
+ });
+ if (core_util_1.isNodeLike) {
+ // Both XHR and Fetch expect to handle redirects automatically,
+ // so only include this policy when we're in Node.
+ pipeline.addPolicy((0, redirectPolicy_js_1.redirectPolicy)(options.redirectOptions), { afterPhase: "Retry" });
+ }
+ pipeline.addPolicy((0, logPolicy_js_1.logPolicy)(options.loggingOptions), { afterPhase: "Sign" });
+ return pipeline;
+}
+//# sourceMappingURL=createPipelineFromOptions.js.map
- // 3. Set isFirstChunk to false.
- isFirstChunk = false
-
- // 4. If chunkPromise is fulfilled with an object whose
- // done property is false and whose value property is
- // a Uint8Array object, run these steps:
- if (!done && types.isUint8Array(value)) {
- // 1. Let bs be the byte sequence represented by the
- // Uint8Array object.
-
- // 2. Append bs to bytes.
- bytes.push(value)
-
- // 3. If roughly 50ms have passed since these steps
- // were last invoked, queue a task to fire a
- // progress event called progress at fr.
- if (
- (
- fr[kLastProgressEventFired] === undefined ||
- Date.now() - fr[kLastProgressEventFired] >= 50
- ) &&
- !fr[kAborted]
- ) {
- fr[kLastProgressEventFired] = Date.now()
- queueMicrotask(() => {
- fireAProgressEvent('progress', fr)
- })
- }
-
- // 4. Set chunkPromise to the result of reading a
- // chunk from stream with reader.
- chunkPromise = reader.read()
- } else if (done) {
- // 5. Otherwise, if chunkPromise is fulfilled with an
- // object whose done property is true, queue a task
- // to run the following steps and abort this algorithm:
- queueMicrotask(() => {
- // 1. Set fr’s state to "done".
- fr[kState] = 'done'
+/***/ }),
- // 2. Let result be the result of package data given
- // bytes, type, blob’s type, and encodingName.
- try {
- const result = packageData(bytes, type, blob.type, encodingName)
+/***/ 55316:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 4. Else:
- if (fr[kAborted]) {
- return
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createDefaultHttpClient = createDefaultHttpClient;
+const nodeHttpClient_js_1 = __nccwpck_require__(56583);
+/**
+ * Create the correct HttpClient for the current environment.
+ */
+function createDefaultHttpClient() {
+ return (0, nodeHttpClient_js_1.createNodeHttpClient)();
+}
+//# sourceMappingURL=defaultHttpClient.js.map
- // 1. Set fr’s result to result.
- fr[kResult] = result
+/***/ }),
- // 2. Fire a progress event called load at the fr.
- fireAProgressEvent('load', fr)
- } catch (error) {
- // 3. If package data threw an exception error:
+/***/ 30596:
+/***/ ((__unused_webpack_module, exports) => {
- // 1. Set fr’s error to error.
- fr[kError] = error
- // 2. Fire a progress event called error at fr.
- fireAProgressEvent('error', fr)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createHttpHeaders = createHttpHeaders;
+function normalizeName(name) {
+ return name.toLowerCase();
+}
+function* headerIterator(map) {
+ for (const entry of map.values()) {
+ yield [entry.name, entry.value];
+ }
+}
+class HttpHeadersImpl {
+ constructor(rawHeaders) {
+ this._headersMap = new Map();
+ if (rawHeaders) {
+ for (const headerName of Object.keys(rawHeaders)) {
+ this.set(headerName, rawHeaders[headerName]);
}
-
- // 5. If fr’s state is not "loading", fire a progress
- // event called loadend at the fr.
- if (fr[kState] !== 'loading') {
- fireAProgressEvent('loadend', fr)
+ }
+ }
+ /**
+ * Set a header in this collection with the provided name and value. The name is
+ * case-insensitive.
+ * @param name - The name of the header to set. This value is case-insensitive.
+ * @param value - The value of the header to set.
+ */
+ set(name, value) {
+ this._headersMap.set(normalizeName(name), { name, value: String(value).trim() });
+ }
+ /**
+ * Get the header value for the provided header name, or undefined if no header exists in this
+ * collection with the provided name.
+ * @param name - The name of the header. This value is case-insensitive.
+ */
+ get(name) {
+ var _a;
+ return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value;
+ }
+ /**
+ * Get whether or not this header collection contains a header entry for the provided header name.
+ * @param name - The name of the header to set. This value is case-insensitive.
+ */
+ has(name) {
+ return this._headersMap.has(normalizeName(name));
+ }
+ /**
+ * Remove the header with the provided headerName.
+ * @param name - The name of the header to remove.
+ */
+ delete(name) {
+ this._headersMap.delete(normalizeName(name));
+ }
+ /**
+ * Get the JSON object representation of this HTTP header collection.
+ */
+ toJSON(options = {}) {
+ const result = {};
+ if (options.preserveCase) {
+ for (const entry of this._headersMap.values()) {
+ result[entry.name] = entry.value;
}
- })
-
- break
}
- } catch (error) {
- if (fr[kAborted]) {
- return
+ else {
+ for (const [normalizedName, entry] of this._headersMap) {
+ result[normalizedName] = entry.value;
+ }
}
-
- // 6. Otherwise, if chunkPromise is rejected with an
- // error error, queue a task to run the following
- // steps and abort this algorithm:
- queueMicrotask(() => {
- // 1. Set fr’s state to "done".
- fr[kState] = 'done'
-
- // 2. Set fr’s error to error.
- fr[kError] = error
-
- // 3. Fire a progress event called error at fr.
- fireAProgressEvent('error', fr)
-
- // 4. If fr’s state is not "loading", fire a progress
- // event called loadend at fr.
- if (fr[kState] !== 'loading') {
- fireAProgressEvent('loadend', fr)
- }
- })
-
- break
- }
+ return result;
+ }
+ /**
+ * Get the string representation of this HTTP header collection.
+ */
+ toString() {
+ return JSON.stringify(this.toJSON({ preserveCase: true }));
+ }
+ /**
+ * Iterate over tuples of header [name, value] pairs.
+ */
+ [Symbol.iterator]() {
+ return headerIterator(this._headersMap);
}
- })()
}
-
/**
- * @see https://w3c.github.io/FileAPI/#fire-a-progress-event
- * @see https://dom.spec.whatwg.org/#concept-event-fire
- * @param {string} e The name of the event
- * @param {import('./filereader').FileReader} reader
+ * Creates an object that satisfies the `HttpHeaders` interface.
+ * @param rawHeaders - A simple object representing initial headers
*/
-function fireAProgressEvent (e, reader) {
- // The progress event e does not bubble. e.bubbles must be false
- // The progress event e is NOT cancelable. e.cancelable must be false
- const event = new ProgressEvent(e, {
- bubbles: false,
- cancelable: false
- })
-
- reader.dispatchEvent(event)
+function createHttpHeaders(rawHeaders) {
+ return new HttpHeadersImpl(rawHeaders);
}
+//# sourceMappingURL=httpHeaders.js.map
-/**
- * @see https://w3c.github.io/FileAPI/#blob-package-data
- * @param {Uint8Array[]} bytes
- * @param {string} type
- * @param {string?} mimeType
- * @param {string?} encodingName
- */
-function packageData (bytes, type, mimeType, encodingName) {
- // 1. A Blob has an associated package data algorithm, given
- // bytes, a type, a optional mimeType, and a optional
- // encodingName, which switches on type and runs the
- // associated steps:
-
- switch (type) {
- case 'DataURL': {
- // 1. Return bytes as a DataURL [RFC2397] subject to
- // the considerations below:
- // * Use mimeType as part of the Data URL if it is
- // available in keeping with the Data URL
- // specification [RFC2397].
- // * If mimeType is not available return a Data URL
- // without a media-type. [RFC2397].
+/***/ }),
- // https://datatracker.ietf.org/doc/html/rfc2397#section-3
- // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data
- // mediatype := [ type "/" subtype ] *( ";" parameter )
- // data := *urlchar
- // parameter := attribute "=" value
- let dataURL = 'data:'
+/***/ 95582:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- const parsed = parseMIMEType(mimeType || 'application/octet-stream')
- if (parsed !== 'failure') {
- dataURL += serializeAMimeType(parsed)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createFileFromStream = exports.createFile = exports.auxiliaryAuthenticationHeaderPolicyName = exports.auxiliaryAuthenticationHeaderPolicy = exports.ndJsonPolicyName = exports.ndJsonPolicy = exports.bearerTokenAuthenticationPolicyName = exports.bearerTokenAuthenticationPolicy = exports.formDataPolicyName = exports.formDataPolicy = exports.tlsPolicyName = exports.tlsPolicy = exports.userAgentPolicyName = exports.userAgentPolicy = exports.defaultRetryPolicy = exports.tracingPolicyName = exports.tracingPolicy = exports.retryPolicy = exports.throttlingRetryPolicyName = exports.throttlingRetryPolicy = exports.systemErrorRetryPolicyName = exports.systemErrorRetryPolicy = exports.redirectPolicyName = exports.redirectPolicy = exports.getDefaultProxySettings = exports.proxyPolicyName = exports.proxyPolicy = exports.multipartPolicyName = exports.multipartPolicy = exports.logPolicyName = exports.logPolicy = exports.setClientRequestIdPolicyName = exports.setClientRequestIdPolicy = exports.exponentialRetryPolicyName = exports.exponentialRetryPolicy = exports.decompressResponsePolicyName = exports.decompressResponsePolicy = exports.isRestError = exports.RestError = exports.createPipelineRequest = exports.createHttpHeaders = exports.createDefaultHttpClient = exports.createPipelineFromOptions = exports.createEmptyPipeline = void 0;
+var pipeline_js_1 = __nccwpck_require__(37050);
+Object.defineProperty(exports, "createEmptyPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createEmptyPipeline; } }));
+var createPipelineFromOptions_js_1 = __nccwpck_require__(1130);
+Object.defineProperty(exports, "createPipelineFromOptions", ({ enumerable: true, get: function () { return createPipelineFromOptions_js_1.createPipelineFromOptions; } }));
+var defaultHttpClient_js_1 = __nccwpck_require__(55316);
+Object.defineProperty(exports, "createDefaultHttpClient", ({ enumerable: true, get: function () { return defaultHttpClient_js_1.createDefaultHttpClient; } }));
+var httpHeaders_js_1 = __nccwpck_require__(30596);
+Object.defineProperty(exports, "createHttpHeaders", ({ enumerable: true, get: function () { return httpHeaders_js_1.createHttpHeaders; } }));
+var pipelineRequest_js_1 = __nccwpck_require__(82425);
+Object.defineProperty(exports, "createPipelineRequest", ({ enumerable: true, get: function () { return pipelineRequest_js_1.createPipelineRequest; } }));
+var restError_js_1 = __nccwpck_require__(97558);
+Object.defineProperty(exports, "RestError", ({ enumerable: true, get: function () { return restError_js_1.RestError; } }));
+Object.defineProperty(exports, "isRestError", ({ enumerable: true, get: function () { return restError_js_1.isRestError; } }));
+var decompressResponsePolicy_js_1 = __nccwpck_require__(13299);
+Object.defineProperty(exports, "decompressResponsePolicy", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicy; } }));
+Object.defineProperty(exports, "decompressResponsePolicyName", ({ enumerable: true, get: function () { return decompressResponsePolicy_js_1.decompressResponsePolicyName; } }));
+var exponentialRetryPolicy_js_1 = __nccwpck_require__(43048);
+Object.defineProperty(exports, "exponentialRetryPolicy", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicy; } }));
+Object.defineProperty(exports, "exponentialRetryPolicyName", ({ enumerable: true, get: function () { return exponentialRetryPolicy_js_1.exponentialRetryPolicyName; } }));
+var setClientRequestIdPolicy_js_1 = __nccwpck_require__(63866);
+Object.defineProperty(exports, "setClientRequestIdPolicy", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicy; } }));
+Object.defineProperty(exports, "setClientRequestIdPolicyName", ({ enumerable: true, get: function () { return setClientRequestIdPolicy_js_1.setClientRequestIdPolicyName; } }));
+var logPolicy_js_1 = __nccwpck_require__(19937);
+Object.defineProperty(exports, "logPolicy", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicy; } }));
+Object.defineProperty(exports, "logPolicyName", ({ enumerable: true, get: function () { return logPolicy_js_1.logPolicyName; } }));
+var multipartPolicy_js_1 = __nccwpck_require__(77915);
+Object.defineProperty(exports, "multipartPolicy", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicy; } }));
+Object.defineProperty(exports, "multipartPolicyName", ({ enumerable: true, get: function () { return multipartPolicy_js_1.multipartPolicyName; } }));
+var proxyPolicy_js_1 = __nccwpck_require__(73723);
+Object.defineProperty(exports, "proxyPolicy", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicy; } }));
+Object.defineProperty(exports, "proxyPolicyName", ({ enumerable: true, get: function () { return proxyPolicy_js_1.proxyPolicyName; } }));
+Object.defineProperty(exports, "getDefaultProxySettings", ({ enumerable: true, get: function () { return proxyPolicy_js_1.getDefaultProxySettings; } }));
+var redirectPolicy_js_1 = __nccwpck_require__(86947);
+Object.defineProperty(exports, "redirectPolicy", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicy; } }));
+Object.defineProperty(exports, "redirectPolicyName", ({ enumerable: true, get: function () { return redirectPolicy_js_1.redirectPolicyName; } }));
+var systemErrorRetryPolicy_js_1 = __nccwpck_require__(14298);
+Object.defineProperty(exports, "systemErrorRetryPolicy", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicy; } }));
+Object.defineProperty(exports, "systemErrorRetryPolicyName", ({ enumerable: true, get: function () { return systemErrorRetryPolicy_js_1.systemErrorRetryPolicyName; } }));
+var throttlingRetryPolicy_js_1 = __nccwpck_require__(96352);
+Object.defineProperty(exports, "throttlingRetryPolicy", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicy; } }));
+Object.defineProperty(exports, "throttlingRetryPolicyName", ({ enumerable: true, get: function () { return throttlingRetryPolicy_js_1.throttlingRetryPolicyName; } }));
+var retryPolicy_js_1 = __nccwpck_require__(85001);
+Object.defineProperty(exports, "retryPolicy", ({ enumerable: true, get: function () { return retryPolicy_js_1.retryPolicy; } }));
+var tracingPolicy_js_1 = __nccwpck_require__(14113);
+Object.defineProperty(exports, "tracingPolicy", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicy; } }));
+Object.defineProperty(exports, "tracingPolicyName", ({ enumerable: true, get: function () { return tracingPolicy_js_1.tracingPolicyName; } }));
+var defaultRetryPolicy_js_1 = __nccwpck_require__(47494);
+Object.defineProperty(exports, "defaultRetryPolicy", ({ enumerable: true, get: function () { return defaultRetryPolicy_js_1.defaultRetryPolicy; } }));
+var userAgentPolicy_js_1 = __nccwpck_require__(69795);
+Object.defineProperty(exports, "userAgentPolicy", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicy; } }));
+Object.defineProperty(exports, "userAgentPolicyName", ({ enumerable: true, get: function () { return userAgentPolicy_js_1.userAgentPolicyName; } }));
+var tlsPolicy_js_1 = __nccwpck_require__(39370);
+Object.defineProperty(exports, "tlsPolicy", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicy; } }));
+Object.defineProperty(exports, "tlsPolicyName", ({ enumerable: true, get: function () { return tlsPolicy_js_1.tlsPolicyName; } }));
+var formDataPolicy_js_1 = __nccwpck_require__(37997);
+Object.defineProperty(exports, "formDataPolicy", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicy; } }));
+Object.defineProperty(exports, "formDataPolicyName", ({ enumerable: true, get: function () { return formDataPolicy_js_1.formDataPolicyName; } }));
+var bearerTokenAuthenticationPolicy_js_1 = __nccwpck_require__(42081);
+Object.defineProperty(exports, "bearerTokenAuthenticationPolicy", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicy; } }));
+Object.defineProperty(exports, "bearerTokenAuthenticationPolicyName", ({ enumerable: true, get: function () { return bearerTokenAuthenticationPolicy_js_1.bearerTokenAuthenticationPolicyName; } }));
+var ndJsonPolicy_js_1 = __nccwpck_require__(7303);
+Object.defineProperty(exports, "ndJsonPolicy", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicy; } }));
+Object.defineProperty(exports, "ndJsonPolicyName", ({ enumerable: true, get: function () { return ndJsonPolicy_js_1.ndJsonPolicyName; } }));
+var auxiliaryAuthenticationHeaderPolicy_js_1 = __nccwpck_require__(7250);
+Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicy", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicy; } }));
+Object.defineProperty(exports, "auxiliaryAuthenticationHeaderPolicyName", ({ enumerable: true, get: function () { return auxiliaryAuthenticationHeaderPolicy_js_1.auxiliaryAuthenticationHeaderPolicyName; } }));
+var file_js_1 = __nccwpck_require__(8581);
+Object.defineProperty(exports, "createFile", ({ enumerable: true, get: function () { return file_js_1.createFile; } }));
+Object.defineProperty(exports, "createFileFromStream", ({ enumerable: true, get: function () { return file_js_1.createFileFromStream; } }));
+//# sourceMappingURL=index.js.map
- dataURL += ';base64,'
+/***/ }),
- const decoder = new StringDecoder('latin1')
+/***/ 58564:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- for (const chunk of bytes) {
- dataURL += btoa(decoder.write(chunk))
- }
- dataURL += btoa(decoder.end())
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logger = void 0;
+const logger_1 = __nccwpck_require__(50143);
+exports.logger = (0, logger_1.createClientLogger)("core-rest-pipeline");
+//# sourceMappingURL=log.js.map
- return dataURL
- }
- case 'Text': {
- // 1. Let encoding be failure
- let encoding = 'failure'
+/***/ }),
- // 2. If the encodingName is present, set encoding to the
- // result of getting an encoding from encodingName.
- if (encodingName) {
- encoding = getEncoding(encodingName)
- }
+/***/ 56583:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // 3. If encoding is failure, and mimeType is present:
- if (encoding === 'failure' && mimeType) {
- // 1. Let type be the result of parse a MIME type
- // given mimeType.
- const type = parseMIMEType(mimeType)
- // 2. If type is not failure, set encoding to the result
- // of getting an encoding from type’s parameters["charset"].
- if (type !== 'failure') {
- encoding = getEncoding(type.parameters.get('charset'))
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getBodyLength = getBodyLength;
+exports.createNodeHttpClient = createNodeHttpClient;
+const tslib_1 = __nccwpck_require__(94176);
+const http = tslib_1.__importStar(__nccwpck_require__(37067));
+const https = tslib_1.__importStar(__nccwpck_require__(44708));
+const zlib = tslib_1.__importStar(__nccwpck_require__(38522));
+const node_stream_1 = __nccwpck_require__(57075);
+const abort_controller_1 = __nccwpck_require__(92242);
+const httpHeaders_js_1 = __nccwpck_require__(30596);
+const restError_js_1 = __nccwpck_require__(97558);
+const log_js_1 = __nccwpck_require__(58564);
+const DEFAULT_TLS_SETTINGS = {};
+function isReadableStream(body) {
+ return body && typeof body.pipe === "function";
+}
+function isStreamComplete(stream) {
+ if (stream.readable === false) {
+ return Promise.resolve();
+ }
+ return new Promise((resolve) => {
+ const handler = () => {
+ resolve();
+ stream.removeListener("close", handler);
+ stream.removeListener("end", handler);
+ stream.removeListener("error", handler);
+ };
+ stream.on("close", handler);
+ stream.on("end", handler);
+ stream.on("error", handler);
+ });
+}
+function isArrayBuffer(body) {
+ return body && typeof body.byteLength === "number";
+}
+class ReportTransform extends node_stream_1.Transform {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
+ _transform(chunk, _encoding, callback) {
+ this.push(chunk);
+ this.loadedBytes += chunk.length;
+ try {
+ this.progressCallback({ loadedBytes: this.loadedBytes });
+ callback();
+ }
+ catch (e) {
+ callback(e);
}
- }
-
- // 4. If encoding is failure, then set encoding to UTF-8.
- if (encoding === 'failure') {
- encoding = 'UTF-8'
- }
-
- // 5. Decode bytes using fallback encoding encoding, and
- // return the result.
- return decode(bytes, encoding)
}
- case 'ArrayBuffer': {
- // Return a new ArrayBuffer whose contents are bytes.
- const sequence = combineByteSequences(bytes)
-
- return sequence.buffer
+ constructor(progressCallback) {
+ super();
+ this.loadedBytes = 0;
+ this.progressCallback = progressCallback;
+ }
+}
+/**
+ * A HttpClient implementation that uses Node's "https" module to send HTTPS requests.
+ * @internal
+ */
+class NodeHttpClient {
+ constructor() {
+ this.cachedHttpsAgents = new WeakMap();
+ }
+ /**
+ * Makes a request over an underlying transport layer and returns the response.
+ * @param request - The request to be made.
+ */
+ async sendRequest(request) {
+ var _a, _b, _c;
+ const abortController = new AbortController();
+ let abortListener;
+ if (request.abortSignal) {
+ if (request.abortSignal.aborted) {
+ throw new abort_controller_1.AbortError("The operation was aborted.");
+ }
+ abortListener = (event) => {
+ if (event.type === "abort") {
+ abortController.abort();
+ }
+ };
+ request.abortSignal.addEventListener("abort", abortListener);
+ }
+ if (request.timeout > 0) {
+ setTimeout(() => {
+ abortController.abort();
+ }, request.timeout);
+ }
+ const acceptEncoding = request.headers.get("Accept-Encoding");
+ const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate"));
+ let body = typeof request.body === "function" ? request.body() : request.body;
+ if (body && !request.headers.has("Content-Length")) {
+ const bodyLength = getBodyLength(body);
+ if (bodyLength !== null) {
+ request.headers.set("Content-Length", bodyLength);
+ }
+ }
+ let responseStream;
+ try {
+ if (body && request.onUploadProgress) {
+ const onUploadProgress = request.onUploadProgress;
+ const uploadReportStream = new ReportTransform(onUploadProgress);
+ uploadReportStream.on("error", (e) => {
+ log_js_1.logger.error("Error in upload progress", e);
+ });
+ if (isReadableStream(body)) {
+ body.pipe(uploadReportStream);
+ }
+ else {
+ uploadReportStream.end(body);
+ }
+ body = uploadReportStream;
+ }
+ const res = await this.makeRequest(request, abortController, body);
+ const headers = getResponseHeaders(res);
+ const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0;
+ const response = {
+ status,
+ headers,
+ request,
+ };
+ // Responses to HEAD must not have a body.
+ // If they do return a body, that body must be ignored.
+ if (request.method === "HEAD") {
+ // call resume() and not destroy() to avoid closing the socket
+ // and losing keep alive
+ res.resume();
+ return response;
+ }
+ responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res;
+ const onDownloadProgress = request.onDownloadProgress;
+ if (onDownloadProgress) {
+ const downloadReportStream = new ReportTransform(onDownloadProgress);
+ downloadReportStream.on("error", (e) => {
+ log_js_1.logger.error("Error in download progress", e);
+ });
+ responseStream.pipe(downloadReportStream);
+ responseStream = downloadReportStream;
+ }
+ if (
+ // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code
+ ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) ||
+ ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))) {
+ response.readableStreamBody = responseStream;
+ }
+ else {
+ response.bodyAsText = await streamToText(responseStream);
+ }
+ return response;
+ }
+ finally {
+ // clean up event listener
+ if (request.abortSignal && abortListener) {
+ let uploadStreamDone = Promise.resolve();
+ if (isReadableStream(body)) {
+ uploadStreamDone = isStreamComplete(body);
+ }
+ let downloadStreamDone = Promise.resolve();
+ if (isReadableStream(responseStream)) {
+ downloadStreamDone = isStreamComplete(responseStream);
+ }
+ Promise.all([uploadStreamDone, downloadStreamDone])
+ .then(() => {
+ var _a;
+ // eslint-disable-next-line promise/always-return
+ if (abortListener) {
+ (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
+ }
+ })
+ .catch((e) => {
+ log_js_1.logger.warning("Error when cleaning up abortListener on httpRequest", e);
+ });
+ }
+ }
+ }
+ makeRequest(request, abortController, body) {
+ var _a;
+ const url = new URL(request.url);
+ const isInsecure = url.protocol !== "https:";
+ if (isInsecure && !request.allowInsecureConnection) {
+ throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`);
+ }
+ const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure);
+ const options = {
+ agent,
+ hostname: url.hostname,
+ path: `${url.pathname}${url.search}`,
+ port: url.port,
+ method: request.method,
+ headers: request.headers.toJSON({ preserveCase: true }),
+ };
+ return new Promise((resolve, reject) => {
+ const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve);
+ req.once("error", (err) => {
+ var _a;
+ reject(new restError_js_1.RestError(err.message, { code: (_a = err.code) !== null && _a !== void 0 ? _a : restError_js_1.RestError.REQUEST_SEND_ERROR, request }));
+ });
+ abortController.signal.addEventListener("abort", () => {
+ const abortError = new abort_controller_1.AbortError("The operation was aborted.");
+ req.destroy(abortError);
+ reject(abortError);
+ });
+ if (body && isReadableStream(body)) {
+ body.pipe(req);
+ }
+ else if (body) {
+ if (typeof body === "string" || Buffer.isBuffer(body)) {
+ req.end(body);
+ }
+ else if (isArrayBuffer(body)) {
+ req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body));
+ }
+ else {
+ log_js_1.logger.error("Unrecognized body type", body);
+ reject(new restError_js_1.RestError("Unrecognized body type"));
+ }
+ }
+ else {
+ // streams don't like "undefined" being passed as data
+ req.end();
+ }
+ });
+ }
+ getOrCreateAgent(request, isInsecure) {
+ var _a;
+ const disableKeepAlive = request.disableKeepAlive;
+ // Handle Insecure requests first
+ if (isInsecure) {
+ if (disableKeepAlive) {
+ // keepAlive:false is the default so we don't need a custom Agent
+ return http.globalAgent;
+ }
+ if (!this.cachedHttpAgent) {
+ // If there is no cached agent create a new one and cache it.
+ this.cachedHttpAgent = new http.Agent({ keepAlive: true });
+ }
+ return this.cachedHttpAgent;
+ }
+ else {
+ if (disableKeepAlive && !request.tlsSettings) {
+ // When there are no tlsSettings and keepAlive is false
+ // we don't need a custom agent
+ return https.globalAgent;
+ }
+ // We use the tlsSettings to index cached clients
+ const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS;
+ // Get the cached agent or create a new one with the
+ // provided values for keepAlive and tlsSettings
+ let agent = this.cachedHttpsAgents.get(tlsSettings);
+ if (agent && agent.options.keepAlive === !disableKeepAlive) {
+ return agent;
+ }
+ log_js_1.logger.info("No cached TLS Agent exist, creating a new Agent");
+ agent = new https.Agent(Object.assign({
+ // keepAlive is true if disableKeepAlive is false.
+ keepAlive: !disableKeepAlive }, tlsSettings));
+ this.cachedHttpsAgents.set(tlsSettings, agent);
+ return agent;
+ }
+ }
+}
+function getResponseHeaders(res) {
+ const headers = (0, httpHeaders_js_1.createHttpHeaders)();
+ for (const header of Object.keys(res.headers)) {
+ const value = res.headers[header];
+ if (Array.isArray(value)) {
+ if (value.length > 0) {
+ headers.set(header, value[0]);
+ }
+ }
+ else if (value) {
+ headers.set(header, value);
+ }
+ }
+ return headers;
+}
+function getDecodedResponseStream(stream, headers) {
+ const contentEncoding = headers.get("Content-Encoding");
+ if (contentEncoding === "gzip") {
+ const unzip = zlib.createGunzip();
+ stream.pipe(unzip);
+ return unzip;
+ }
+ else if (contentEncoding === "deflate") {
+ const inflate = zlib.createInflate();
+ stream.pipe(inflate);
+ return inflate;
+ }
+ return stream;
+}
+function streamToText(stream) {
+ return new Promise((resolve, reject) => {
+ const buffer = [];
+ stream.on("data", (chunk) => {
+ if (Buffer.isBuffer(chunk)) {
+ buffer.push(chunk);
+ }
+ else {
+ buffer.push(Buffer.from(chunk));
+ }
+ });
+ stream.on("end", () => {
+ resolve(Buffer.concat(buffer).toString("utf8"));
+ });
+ stream.on("error", (e) => {
+ if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") {
+ reject(e);
+ }
+ else {
+ reject(new restError_js_1.RestError(`Error reading response as text: ${e.message}`, {
+ code: restError_js_1.RestError.PARSE_ERROR,
+ }));
+ }
+ });
+ });
+}
+/** @internal */
+function getBodyLength(body) {
+ if (!body) {
+ return 0;
+ }
+ else if (Buffer.isBuffer(body)) {
+ return body.length;
+ }
+ else if (isReadableStream(body)) {
+ return null;
+ }
+ else if (isArrayBuffer(body)) {
+ return body.byteLength;
}
- case 'BinaryString': {
- // Return bytes as a binary string, in which every byte
- // is represented by a code unit of equal value [0..255].
- let binaryString = ''
-
- const decoder = new StringDecoder('latin1')
-
- for (const chunk of bytes) {
- binaryString += decoder.write(chunk)
- }
-
- binaryString += decoder.end()
-
- return binaryString
+ else if (typeof body === "string") {
+ return Buffer.from(body).length;
+ }
+ else {
+ return null;
}
- }
}
-
/**
- * @see https://encoding.spec.whatwg.org/#decode
- * @param {Uint8Array[]} ioQueue
- * @param {string} encoding
+ * Create a new HttpClient instance for the NodeJS environment.
+ * @internal
*/
-function decode (ioQueue, encoding) {
- const bytes = combineByteSequences(ioQueue)
-
- // 1. Let BOMEncoding be the result of BOM sniffing ioQueue.
- const BOMEncoding = BOMSniffing(bytes)
-
- let slice = 0
-
- // 2. If BOMEncoding is non-null:
- if (BOMEncoding !== null) {
- // 1. Set encoding to BOMEncoding.
- encoding = BOMEncoding
-
- // 2. Read three bytes from ioQueue, if BOMEncoding is
- // UTF-8; otherwise read two bytes.
- // (Do nothing with those bytes.)
- slice = BOMEncoding === 'UTF-8' ? 3 : 2
- }
-
- // 3. Process a queue with an instance of encoding’s
- // decoder, ioQueue, output, and "replacement".
-
- // 4. Return output.
-
- const sliced = bytes.slice(slice)
- return new TextDecoder(encoding).decode(sliced)
+function createNodeHttpClient() {
+ return new NodeHttpClient();
}
+//# sourceMappingURL=nodeHttpClient.js.map
-/**
- * @see https://encoding.spec.whatwg.org/#bom-sniff
- * @param {Uint8Array} ioQueue
- */
-function BOMSniffing (ioQueue) {
- // 1. Let BOM be the result of peeking 3 bytes from ioQueue,
- // converted to a byte sequence.
- const [a, b, c] = ioQueue
+/***/ }),
- // 2. For each of the rows in the table below, starting with
- // the first one and going down, if BOM starts with the
- // bytes given in the first column, then return the
- // encoding given in the cell in the second column of that
- // row. Otherwise, return null.
- if (a === 0xEF && b === 0xBB && c === 0xBF) {
- return 'UTF-8'
- } else if (a === 0xFE && b === 0xFF) {
- return 'UTF-16BE'
- } else if (a === 0xFF && b === 0xFE) {
- return 'UTF-16LE'
- }
+/***/ 37050:
+/***/ ((__unused_webpack_module, exports) => {
- return null
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createEmptyPipeline = createEmptyPipeline;
+const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]);
/**
- * @param {Uint8Array[]} sequences
+ * A private implementation of Pipeline.
+ * Do not export this class from the package.
+ * @internal
*/
-function combineByteSequences (sequences) {
- const size = sequences.reduce((a, b) => {
- return a + b.byteLength
- }, 0)
-
- let offset = 0
-
- return sequences.reduce((a, b) => {
- a.set(b, offset)
- offset += b.byteLength
- return a
- }, new Uint8Array(size))
-}
-
-module.exports = {
- staticPropertyDescriptors,
- readOperation,
- fireAProgressEvent
-}
-
-
-/***/ }),
-
-/***/ 61481:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-// We include a version number for the Dispatcher API. In case of breaking changes,
-// this version number must be increased to avoid conflicts.
-const globalDispatcher = Symbol.for('undici.globalDispatcher.1')
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-const Agent = __nccwpck_require__(92121)
-
-if (getGlobalDispatcher() === undefined) {
- setGlobalDispatcher(new Agent())
-}
-
-function setGlobalDispatcher (agent) {
- if (!agent || typeof agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument agent must implement Agent')
- }
- Object.defineProperty(globalThis, globalDispatcher, {
- value: agent,
- writable: true,
- enumerable: false,
- configurable: false
- })
-}
-
-function getGlobalDispatcher () {
- return globalThis[globalDispatcher]
-}
-
-module.exports = {
- setGlobalDispatcher,
- getGlobalDispatcher
-}
-
-
-/***/ }),
-
-/***/ 41468:
-/***/ ((module) => {
-
-
-
-module.exports = class DecoratorHandler {
- constructor (handler) {
- this.handler = handler
- }
-
- onConnect (...args) {
- return this.handler.onConnect(...args)
- }
-
- onError (...args) {
- return this.handler.onError(...args)
- }
-
- onUpgrade (...args) {
- return this.handler.onUpgrade(...args)
- }
-
- onHeaders (...args) {
- return this.handler.onHeaders(...args)
- }
-
- onData (...args) {
- return this.handler.onData(...args)
- }
-
- onComplete (...args) {
- return this.handler.onComplete(...args)
- }
-
- onBodySent (...args) {
- return this.handler.onBodySent(...args)
- }
-}
-
-
-/***/ }),
-
-/***/ 8591:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const util = __nccwpck_require__(89500)
-const { kBodyUsed } = __nccwpck_require__(68031)
-const assert = __nccwpck_require__(42613)
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-const EE = __nccwpck_require__(24434)
-
-const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]
-
-const kBody = Symbol('body')
-
-class BodyAsyncIterable {
- constructor (body) {
- this[kBody] = body
- this[kBodyUsed] = false
- }
-
- async * [Symbol.asyncIterator] () {
- assert(!this[kBodyUsed], 'disturbed')
- this[kBodyUsed] = true
- yield * this[kBody]
- }
-}
-
-class RedirectHandler {
- constructor (dispatch, maxRedirections, opts, handler) {
- if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) {
- throw new InvalidArgumentError('maxRedirections must be a positive number')
+class HttpPipeline {
+ constructor(policies) {
+ var _a;
+ this._policies = [];
+ this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : [];
+ this._orderedPolicies = undefined;
}
-
- util.validateHandler(handler, opts.method, opts.upgrade)
-
- this.dispatch = dispatch
- this.location = null
- this.abort = null
- this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy
- this.maxRedirections = maxRedirections
- this.handler = handler
- this.history = []
-
- if (util.isStream(this.opts.body)) {
- // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp
- // so that it can be dispatched again?
- // TODO (fix): Do we need 100-expect support to provide a way to do this properly?
- if (util.bodyLength(this.opts.body) === 0) {
- this.opts.body
- .on('data', function () {
- assert(false)
- })
- }
-
- if (typeof this.opts.body.readableDidRead !== 'boolean') {
- this.opts.body[kBodyUsed] = false
- EE.prototype.on.call(this.opts.body, 'data', function () {
- this[kBodyUsed] = true
- })
- }
- } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') {
- // TODO (fix): We can't access ReadableStream internal state
- // to determine whether or not it has been disturbed. This is just
- // a workaround.
- this.opts.body = new BodyAsyncIterable(this.opts.body)
- } else if (
- this.opts.body &&
- typeof this.opts.body !== 'string' &&
- !ArrayBuffer.isView(this.opts.body) &&
- util.isIterable(this.opts.body)
- ) {
- // TODO: Should we allow re-using iterable if !this.opts.idempotent
- // or through some other flag?
- this.opts.body = new BodyAsyncIterable(this.opts.body)
+ addPolicy(policy, options = {}) {
+ if (options.phase && options.afterPhase) {
+ throw new Error("Policies inside a phase cannot specify afterPhase.");
+ }
+ if (options.phase && !ValidPhaseNames.has(options.phase)) {
+ throw new Error(`Invalid phase name: ${options.phase}`);
+ }
+ if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) {
+ throw new Error(`Invalid afterPhase name: ${options.afterPhase}`);
+ }
+ this._policies.push({
+ policy,
+ options,
+ });
+ this._orderedPolicies = undefined;
}
- }
-
- onConnect (abort) {
- this.abort = abort
- this.handler.onConnect(abort, { history: this.history })
- }
-
- onUpgrade (statusCode, headers, socket) {
- this.handler.onUpgrade(statusCode, headers, socket)
- }
-
- onError (error) {
- this.handler.onError(error)
- }
-
- onHeaders (statusCode, headers, resume, statusText) {
- this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body)
- ? null
- : parseLocation(statusCode, headers)
-
- if (this.opts.origin) {
- this.history.push(new URL(this.opts.path, this.opts.origin))
+ removePolicy(options) {
+ const removedPolicies = [];
+ this._policies = this._policies.filter((policyDescriptor) => {
+ if ((options.name && policyDescriptor.policy.name === options.name) ||
+ (options.phase && policyDescriptor.options.phase === options.phase)) {
+ removedPolicies.push(policyDescriptor.policy);
+ return false;
+ }
+ else {
+ return true;
+ }
+ });
+ this._orderedPolicies = undefined;
+ return removedPolicies;
+ }
+ sendRequest(httpClient, request) {
+ const policies = this.getOrderedPolicies();
+ const pipeline = policies.reduceRight((next, policy) => {
+ return (req) => {
+ return policy.sendRequest(req, next);
+ };
+ }, (req) => httpClient.sendRequest(req));
+ return pipeline(request);
+ }
+ getOrderedPolicies() {
+ if (!this._orderedPolicies) {
+ this._orderedPolicies = this.orderPolicies();
+ }
+ return this._orderedPolicies;
+ }
+ clone() {
+ return new HttpPipeline(this._policies);
+ }
+ static create() {
+ return new HttpPipeline();
+ }
+ orderPolicies() {
+ /**
+ * The goal of this method is to reliably order pipeline policies
+ * based on their declared requirements when they were added.
+ *
+ * Order is first determined by phase:
+ *
+ * 1. Serialize Phase
+ * 2. Policies not in a phase
+ * 3. Deserialize Phase
+ * 4. Retry Phase
+ * 5. Sign Phase
+ *
+ * Within each phase, policies are executed in the order
+ * they were added unless they were specified to execute
+ * before/after other policies or after a particular phase.
+ *
+ * To determine the final order, we will walk the policy list
+ * in phase order multiple times until all dependencies are
+ * satisfied.
+ *
+ * `afterPolicies` are the set of policies that must be
+ * executed before a given policy. This requirement is
+ * considered satisfied when each of the listed policies
+ * have been scheduled.
+ *
+ * `beforePolicies` are the set of policies that must be
+ * executed after a given policy. Since this dependency
+ * can be expressed by converting it into a equivalent
+ * `afterPolicies` declarations, they are normalized
+ * into that form for simplicity.
+ *
+ * An `afterPhase` dependency is considered satisfied when all
+ * policies in that phase have scheduled.
+ *
+ */
+ const result = [];
+ // Track all policies we know about.
+ const policyMap = new Map();
+ function createPhase(name) {
+ return {
+ name,
+ policies: new Set(),
+ hasRun: false,
+ hasAfterPolicies: false,
+ };
+ }
+ // Track policies for each phase.
+ const serializePhase = createPhase("Serialize");
+ const noPhase = createPhase("None");
+ const deserializePhase = createPhase("Deserialize");
+ const retryPhase = createPhase("Retry");
+ const signPhase = createPhase("Sign");
+ // a list of phases in order
+ const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase];
+ // Small helper function to map phase name to each Phase
+ function getPhase(phase) {
+ if (phase === "Retry") {
+ return retryPhase;
+ }
+ else if (phase === "Serialize") {
+ return serializePhase;
+ }
+ else if (phase === "Deserialize") {
+ return deserializePhase;
+ }
+ else if (phase === "Sign") {
+ return signPhase;
+ }
+ else {
+ return noPhase;
+ }
+ }
+ // First walk each policy and create a node to track metadata.
+ for (const descriptor of this._policies) {
+ const policy = descriptor.policy;
+ const options = descriptor.options;
+ const policyName = policy.name;
+ if (policyMap.has(policyName)) {
+ throw new Error("Duplicate policy names not allowed in pipeline");
+ }
+ const node = {
+ policy,
+ dependsOn: new Set(),
+ dependants: new Set(),
+ };
+ if (options.afterPhase) {
+ node.afterPhase = getPhase(options.afterPhase);
+ node.afterPhase.hasAfterPolicies = true;
+ }
+ policyMap.set(policyName, node);
+ const phase = getPhase(options.phase);
+ phase.policies.add(node);
+ }
+ // Now that each policy has a node, connect dependency references.
+ for (const descriptor of this._policies) {
+ const { policy, options } = descriptor;
+ const policyName = policy.name;
+ const node = policyMap.get(policyName);
+ if (!node) {
+ throw new Error(`Missing node for policy ${policyName}`);
+ }
+ if (options.afterPolicies) {
+ for (const afterPolicyName of options.afterPolicies) {
+ const afterNode = policyMap.get(afterPolicyName);
+ if (afterNode) {
+ // Linking in both directions helps later
+ // when we want to notify dependants.
+ node.dependsOn.add(afterNode);
+ afterNode.dependants.add(node);
+ }
+ }
+ }
+ if (options.beforePolicies) {
+ for (const beforePolicyName of options.beforePolicies) {
+ const beforeNode = policyMap.get(beforePolicyName);
+ if (beforeNode) {
+ // To execute before another node, make it
+ // depend on the current node.
+ beforeNode.dependsOn.add(node);
+ node.dependants.add(beforeNode);
+ }
+ }
+ }
+ }
+ function walkPhase(phase) {
+ phase.hasRun = true;
+ // Sets iterate in insertion order
+ for (const node of phase.policies) {
+ if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) {
+ // If this node is waiting on a phase to complete,
+ // we need to skip it for now.
+ // Even if the phase is empty, we should wait for it
+ // to be walked to avoid re-ordering policies.
+ continue;
+ }
+ if (node.dependsOn.size === 0) {
+ // If there's nothing else we're waiting for, we can
+ // add this policy to the result list.
+ result.push(node.policy);
+ // Notify anything that depends on this policy that
+ // the policy has been scheduled.
+ for (const dependant of node.dependants) {
+ dependant.dependsOn.delete(node);
+ }
+ policyMap.delete(node.policy.name);
+ phase.policies.delete(node);
+ }
+ }
+ }
+ function walkPhases() {
+ for (const phase of orderedPhases) {
+ walkPhase(phase);
+ // if the phase isn't complete
+ if (phase.policies.size > 0 && phase !== noPhase) {
+ if (!noPhase.hasRun) {
+ // Try running noPhase to see if that unblocks this phase next tick.
+ // This can happen if a phase that happens before noPhase
+ // is waiting on a noPhase policy to complete.
+ walkPhase(noPhase);
+ }
+ // Don't proceed to the next phase until this phase finishes.
+ return;
+ }
+ if (phase.hasAfterPolicies) {
+ // Run any policies unblocked by this phase
+ walkPhase(noPhase);
+ }
+ }
+ }
+ // Iterate until we've put every node in the result list.
+ let iteration = 0;
+ while (policyMap.size > 0) {
+ iteration++;
+ const initialResultLength = result.length;
+ // Keep walking each phase in order until we can order every node.
+ walkPhases();
+ // The result list *should* get at least one larger each time
+ // after the first full pass.
+ // Otherwise, we're going to loop forever.
+ if (result.length <= initialResultLength && iteration > 1) {
+ throw new Error("Cannot satisfy policy dependencies due to requirements cycle.");
+ }
+ }
+ return result;
}
+}
+/**
+ * Creates a totally empty pipeline.
+ * Useful for testing or creating a custom one.
+ */
+function createEmptyPipeline() {
+ return HttpPipeline.create();
+}
+//# sourceMappingURL=pipeline.js.map
- if (!this.location) {
- return this.handler.onHeaders(statusCode, headers, resume, statusText)
- }
+/***/ }),
- const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))
- const path = search ? `${pathname}${search}` : pathname
+/***/ 82425:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // Remove headers referring to the original URL.
- // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers.
- // https://tools.ietf.org/html/rfc7231#section-6.4
- this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin)
- this.opts.path = path
- this.opts.origin = origin
- this.opts.maxRedirections = 0
- this.opts.query = null
- // https://tools.ietf.org/html/rfc7231#section-6.4.4
- // In case of HTTP 303, always replace method to be either HEAD or GET
- if (statusCode === 303 && this.opts.method !== 'HEAD') {
- this.opts.method = 'GET'
- this.opts.body = null
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createPipelineRequest = createPipelineRequest;
+const httpHeaders_js_1 = __nccwpck_require__(30596);
+const core_util_1 = __nccwpck_require__(30991);
+class PipelineRequestImpl {
+ constructor(options) {
+ var _a, _b, _c, _d, _e, _f, _g;
+ this.url = options.url;
+ this.body = options.body;
+ this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : (0, httpHeaders_js_1.createHttpHeaders)();
+ this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET";
+ this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0;
+ this.multipartBody = options.multipartBody;
+ this.formData = options.formData;
+ this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false;
+ this.proxySettings = options.proxySettings;
+ this.streamResponseStatusCodes = options.streamResponseStatusCodes;
+ this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false;
+ this.abortSignal = options.abortSignal;
+ this.tracingOptions = options.tracingOptions;
+ this.onUploadProgress = options.onUploadProgress;
+ this.onDownloadProgress = options.onDownloadProgress;
+ this.requestId = options.requestId || (0, core_util_1.randomUUID)();
+ this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false;
+ this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false;
}
- }
-
- onData (chunk) {
- if (this.location) {
- /*
- https://tools.ietf.org/html/rfc7231#section-6.4
-
- TLDR: undici always ignores 3xx response bodies.
+}
+/**
+ * Creates a new pipeline request with the given options.
+ * This method is to allow for the easy setting of default values and not required.
+ * @param options - The options to create the request with.
+ */
+function createPipelineRequest(options) {
+ return new PipelineRequestImpl(options);
+}
+//# sourceMappingURL=pipelineRequest.js.map
- Redirection is used to serve the requested resource from another URL, so it is assumes that
- no body is generated (and thus can be ignored). Even though generating a body is not prohibited.
+/***/ }),
- For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually
- (which means it's optional and not mandated) contain just an hyperlink to the value of
- the Location response header, so the body can be ignored safely.
+/***/ 7250:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- For status 300, which is "Multiple Choices", the spec mentions both generating a Location
- response header AND a response body with the other possible location to follow.
- Since the spec explicitily chooses not to specify a format for such body and leave it to
- servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it.
- */
- } else {
- return this.handler.onData(chunk)
- }
- }
- onComplete (trailers) {
- if (this.location) {
- /*
- https://tools.ietf.org/html/rfc7231#section-6.4
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.auxiliaryAuthenticationHeaderPolicyName = void 0;
+exports.auxiliaryAuthenticationHeaderPolicy = auxiliaryAuthenticationHeaderPolicy;
+const tokenCycler_js_1 = __nccwpck_require__(82534);
+const log_js_1 = __nccwpck_require__(58564);
+/**
+ * The programmatic identifier of the auxiliaryAuthenticationHeaderPolicy.
+ */
+exports.auxiliaryAuthenticationHeaderPolicyName = "auxiliaryAuthenticationHeaderPolicy";
+const AUTHORIZATION_AUXILIARY_HEADER = "x-ms-authorization-auxiliary";
+async function sendAuthorizeRequest(options) {
+ var _a, _b;
+ const { scopes, getAccessToken, request } = options;
+ const getTokenOptions = {
+ abortSignal: request.abortSignal,
+ tracingOptions: request.tracingOptions,
+ };
+ return (_b = (_a = (await getAccessToken(scopes, getTokenOptions))) === null || _a === void 0 ? void 0 : _a.token) !== null && _b !== void 0 ? _b : "";
+}
+/**
+ * A policy for external tokens to `x-ms-authorization-auxiliary` header.
+ * This header will be used when creating a cross-tenant application we may need to handle authentication requests
+ * for resources that are in different tenants.
+ * You could see [ARM docs](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant) for a rundown of how this feature works
+ */
+function auxiliaryAuthenticationHeaderPolicy(options) {
+ const { credentials, scopes } = options;
+ const logger = options.logger || log_js_1.logger;
+ const tokenCyclerMap = new WeakMap();
+ return {
+ name: exports.auxiliaryAuthenticationHeaderPolicyName,
+ async sendRequest(request, next) {
+ if (!request.url.toLowerCase().startsWith("https://")) {
+ throw new Error("Bearer token authentication for auxiliary header is not permitted for non-TLS protected (non-https) URLs.");
+ }
+ if (!credentials || credentials.length === 0) {
+ logger.info(`${exports.auxiliaryAuthenticationHeaderPolicyName} header will not be set due to empty credentials.`);
+ return next(request);
+ }
+ const tokenPromises = [];
+ for (const credential of credentials) {
+ let getAccessToken = tokenCyclerMap.get(credential);
+ if (!getAccessToken) {
+ getAccessToken = (0, tokenCycler_js_1.createTokenCycler)(credential);
+ tokenCyclerMap.set(credential, getAccessToken);
+ }
+ tokenPromises.push(sendAuthorizeRequest({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ getAccessToken,
+ logger,
+ }));
+ }
+ const auxiliaryTokens = (await Promise.all(tokenPromises)).filter((token) => Boolean(token));
+ if (auxiliaryTokens.length === 0) {
+ logger.warning(`None of the auxiliary tokens are valid. ${AUTHORIZATION_AUXILIARY_HEADER} header will not be set.`);
+ return next(request);
+ }
+ request.headers.set(AUTHORIZATION_AUXILIARY_HEADER, auxiliaryTokens.map((token) => `Bearer ${token}`).join(", "));
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=auxiliaryAuthenticationHeaderPolicy.js.map
- TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections
- and neither are useful if present.
+/***/ }),
- See comment on onData method above for more detailed informations.
- */
+/***/ 42081:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this.location = null
- this.abort = null
- this.dispatch(this.opts, this)
- } else {
- this.handler.onComplete(trailers)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.bearerTokenAuthenticationPolicyName = void 0;
+exports.bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy;
+exports.parseChallenges = parseChallenges;
+const tokenCycler_js_1 = __nccwpck_require__(82534);
+const log_js_1 = __nccwpck_require__(58564);
+const restError_js_1 = __nccwpck_require__(97558);
+/**
+ * The programmatic identifier of the bearerTokenAuthenticationPolicy.
+ */
+exports.bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy";
+/**
+ * Try to send the given request.
+ *
+ * When a response is received, returns a tuple of the response received and, if the response was received
+ * inside a thrown RestError, the RestError that was thrown.
+ *
+ * Otherwise, if an error was thrown while sending the request that did not provide an underlying response, it
+ * will be rethrown.
+ */
+async function trySendRequest(request, next) {
+ try {
+ return [await next(request), undefined];
}
- }
-
- onBodySent (chunk) {
- if (this.handler.onBodySent) {
- this.handler.onBodySent(chunk)
+ catch (e) {
+ if ((0, restError_js_1.isRestError)(e) && e.response) {
+ return [e.response, e];
+ }
+ else {
+ throw e;
+ }
}
- }
}
-
-function parseLocation (statusCode, headers) {
- if (redirectableStatusCodes.indexOf(statusCode) === -1) {
- return null
- }
-
- for (let i = 0; i < headers.length; i += 2) {
- if (headers[i].toString().toLowerCase() === 'location') {
- return headers[i + 1]
+/**
+ * Default authorize request handler
+ */
+async function defaultAuthorizeRequest(options) {
+ const { scopes, getAccessToken, request } = options;
+ // Enable CAE true by default
+ const getTokenOptions = {
+ abortSignal: request.abortSignal,
+ tracingOptions: request.tracingOptions,
+ enableCae: true,
+ };
+ const accessToken = await getAccessToken(scopes, getTokenOptions);
+ if (accessToken) {
+ options.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
}
- }
}
-
-// https://tools.ietf.org/html/rfc7231#section-6.4.4
-function shouldRemoveHeader (header, removeContent, unknownOrigin) {
- if (header.length === 4) {
- return util.headerNameToString(header) === 'host'
- }
- if (removeContent && util.headerNameToString(header).startsWith('content-')) {
- return true
- }
- if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) {
- const name = util.headerNameToString(header)
- return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization'
- }
- return false
+/**
+ * We will retrieve the challenge only if the response status code was 401,
+ * and if the response contained the header "WWW-Authenticate" with a non-empty value.
+ */
+function isChallengeResponse(response) {
+ return response.status === 401 && response.headers.has("WWW-Authenticate");
}
-
-// https://tools.ietf.org/html/rfc7231#section-6.4
-function cleanRequestHeaders (headers, removeContent, unknownOrigin) {
- const ret = []
- if (Array.isArray(headers)) {
- for (let i = 0; i < headers.length; i += 2) {
- if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) {
- ret.push(headers[i], headers[i + 1])
- }
- }
- } else if (headers && typeof headers === 'object') {
- for (const key of Object.keys(headers)) {
- if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) {
- ret.push(key, headers[key])
- }
+/**
+ * Re-authorize the request for CAE challenge.
+ * The response containing the challenge is `options.response`.
+ * If this method returns true, the underlying request will be sent once again.
+ */
+async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) {
+ var _a;
+ const { scopes } = onChallengeOptions;
+ const accessToken = await onChallengeOptions.getAccessToken(scopes, {
+ enableCae: true,
+ claims: caeClaims,
+ });
+ if (!accessToken) {
+ return false;
}
- } else {
- assert(headers == null, 'headers must be an object or an array')
- }
- return ret
-}
-
-module.exports = RedirectHandler
-
-
-/***/ }),
-
-/***/ 49569:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const assert = __nccwpck_require__(42613)
-
-const { kRetryHandlerDefaultRetry } = __nccwpck_require__(68031)
-const { RequestRetryError } = __nccwpck_require__(53959)
-const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(89500)
-
-function calculateRetryAfterHeader (retryAfter) {
- const current = Date.now()
- const diff = new Date(retryAfter).getTime() - current
-
- return diff
+ onChallengeOptions.request.headers.set("Authorization", `${(_a = accessToken.tokenType) !== null && _a !== void 0 ? _a : "Bearer"} ${accessToken.token}`);
+ return true;
}
-
-class RetryHandler {
- constructor (opts, handlers) {
- const { retryOptions, ...dispatchOpts } = opts
- const {
- // Retry scoped
- retry: retryFn,
- maxRetries,
- maxTimeout,
- minTimeout,
- timeoutFactor,
- // Response scoped
- methods,
- errorCodes,
- retryAfter,
- statusCodes
- } = retryOptions ?? {}
-
- this.dispatch = handlers.dispatch
- this.handler = handlers.handler
- this.opts = dispatchOpts
- this.abort = null
- this.aborted = false
- this.retryOpts = {
- retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry],
- retryAfter: retryAfter ?? true,
- maxTimeout: maxTimeout ?? 30 * 1000, // 30s,
- timeout: minTimeout ?? 500, // .5s
- timeoutFactor: timeoutFactor ?? 2,
- maxRetries: maxRetries ?? 5,
- // What errors we should retry
- methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'],
- // Indicates which errors to retry
- statusCodes: statusCodes ?? [500, 502, 503, 504, 429],
- // List of errors to retry
- errorCodes: errorCodes ?? [
- 'ECONNRESET',
- 'ECONNREFUSED',
- 'ENOTFOUND',
- 'ENETDOWN',
- 'ENETUNREACH',
- 'EHOSTDOWN',
- 'EHOSTUNREACH',
- 'EPIPE'
- ]
- }
-
- this.retryCount = 0
- this.start = 0
- this.end = null
- this.etag = null
- this.resume = null
-
- // Handle possible onConnect duplication
- this.handler.onConnect(reason => {
- this.aborted = true
- if (this.abort) {
- this.abort(reason)
- } else {
- this.reason = reason
- }
- })
- }
-
- onRequestSent () {
- if (this.handler.onRequestSent) {
- this.handler.onRequestSent()
- }
- }
-
- onUpgrade (statusCode, headers, socket) {
- if (this.handler.onUpgrade) {
- this.handler.onUpgrade(statusCode, headers, socket)
- }
- }
-
- onConnect (abort) {
- if (this.aborted) {
- abort(this.reason)
- } else {
- this.abort = abort
- }
- }
-
- onBodySent (chunk) {
- if (this.handler.onBodySent) return this.handler.onBodySent(chunk)
- }
-
- static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) {
- const { statusCode, code, headers } = err
- const { method, retryOptions } = opts
- const {
- maxRetries,
- timeout,
- maxTimeout,
- timeoutFactor,
- statusCodes,
- errorCodes,
- methods
- } = retryOptions
- let { counter, currentTimeout } = state
-
- currentTimeout =
- currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout
-
- // Any code that is not a Undici's originated and allowed to retry
- if (
- code &&
- code !== 'UND_ERR_REQ_RETRY' &&
- code !== 'UND_ERR_SOCKET' &&
- !errorCodes.includes(code)
- ) {
- cb(err)
- return
+/**
+ * A policy that can request a token from a TokenCredential implementation and
+ * then apply it to the Authorization header of a request as a Bearer token.
+ */
+function bearerTokenAuthenticationPolicy(options) {
+ var _a, _b, _c;
+ const { credential, scopes, challengeCallbacks } = options;
+ const logger = options.logger || log_js_1.logger;
+ const callbacks = {
+ authorizeRequest: (_b = (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) === null || _a === void 0 ? void 0 : _a.bind(challengeCallbacks)) !== null && _b !== void 0 ? _b : defaultAuthorizeRequest,
+ authorizeRequestOnChallenge: (_c = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge) === null || _c === void 0 ? void 0 : _c.bind(challengeCallbacks),
+ };
+ // This function encapsulates the entire process of reliably retrieving the token
+ // The options are left out of the public API until there's demand to configure this.
+ // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions`
+ // in order to pass through the `options` object.
+ const getAccessToken = credential
+ ? (0, tokenCycler_js_1.createTokenCycler)(credential /* , options */)
+ : () => Promise.resolve(null);
+ return {
+ name: exports.bearerTokenAuthenticationPolicyName,
+ /**
+ * If there's no challenge parameter:
+ * - It will try to retrieve the token using the cache, or the credential's getToken.
+ * - Then it will try the next policy with or without the retrieved token.
+ *
+ * It uses the challenge parameters to:
+ * - Skip a first attempt to get the token from the credential if there's no cached token,
+ * since it expects the token to be retrievable only after the challenge.
+ * - Prepare the outgoing request if the `prepareRequest` method has been provided.
+ * - Send an initial request to receive the challenge if it fails.
+ * - Process a challenge if the response contains it.
+ * - Retrieve a token with the challenge information, then re-send the request.
+ */
+ async sendRequest(request, next) {
+ if (!request.url.toLowerCase().startsWith("https://")) {
+ throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs.");
+ }
+ await callbacks.authorizeRequest({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ getAccessToken,
+ logger,
+ });
+ let response;
+ let error;
+ let shouldSendRequest;
+ [response, error] = await trySendRequest(request, next);
+ if (isChallengeResponse(response)) {
+ let claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
+ // Handle CAE by default when receive CAE claim
+ if (claims) {
+ let parsedClaim;
+ // Return the response immediately if claims is not a valid base64 encoded string
+ try {
+ parsedClaim = atob(claims);
+ }
+ catch (e) {
+ logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
+ return response;
+ }
+ shouldSendRequest = await authorizeRequestOnCaeChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ response,
+ request,
+ getAccessToken,
+ logger,
+ }, parsedClaim);
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ }
+ else if (callbacks.authorizeRequestOnChallenge) {
+ // Handle custom challenges when client provides custom callback
+ shouldSendRequest = await callbacks.authorizeRequestOnChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ request,
+ response,
+ getAccessToken,
+ logger,
+ });
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ // If we get another CAE Claim, we will handle it by default and return whatever value we receive for this
+ if (isChallengeResponse(response)) {
+ claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate"));
+ if (claims) {
+ let parsedClaim;
+ try {
+ parsedClaim = atob(claims);
+ }
+ catch (e) {
+ logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`);
+ return response;
+ }
+ shouldSendRequest = await authorizeRequestOnCaeChallenge({
+ scopes: Array.isArray(scopes) ? scopes : [scopes],
+ response,
+ request,
+ getAccessToken,
+ logger,
+ }, parsedClaim);
+ // Send updated request and handle response for RestError
+ if (shouldSendRequest) {
+ [response, error] = await trySendRequest(request, next);
+ }
+ }
+ }
+ }
+ }
+ if (error) {
+ throw error;
+ }
+ else {
+ return response;
+ }
+ },
+ };
+}
+/**
+ * Converts: `Bearer a="b", c="d", Pop e="f", g="h"`.
+ * Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`.
+ *
+ * @internal
+ */
+function parseChallenges(challenges) {
+ // Challenge regex seperates the string to individual challenges with different schemes in the format `Scheme a="b", c=d`
+ // The challenge regex captures parameteres with either quotes values or unquoted values
+ const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g;
+ // Parameter regex captures the claims group removed from the scheme in the format `a="b"` and `c="d"`
+ // CAE challenge always have quoted parameters. For more reference, https://learn.microsoft.com/entra/identity-platform/claims-challenge
+ const paramRegex = /(\w+)="([^"]*)"/g;
+ const parsedChallenges = [];
+ let match;
+ // Iterate over each challenge match
+ while ((match = challengeRegex.exec(challenges)) !== null) {
+ const scheme = match[1];
+ const paramsString = match[2];
+ const params = {};
+ let paramMatch;
+ // Iterate over each parameter match
+ while ((paramMatch = paramRegex.exec(paramsString)) !== null) {
+ params[paramMatch[1]] = paramMatch[2];
+ }
+ parsedChallenges.push({ scheme, params });
}
-
- // If a set of method are provided and the current method is not in the list
- if (Array.isArray(methods) && !methods.includes(method)) {
- cb(err)
- return
+ return parsedChallenges;
+}
+/**
+ * Parse a pipeline response and look for a CAE challenge with "Bearer" scheme
+ * Return the value in the header without parsing the challenge
+ * @internal
+ */
+function getCaeChallengeClaims(challenges) {
+ var _a;
+ if (!challenges) {
+ return;
}
+ // Find all challenges present in the header
+ const parsedChallenges = parseChallenges(challenges);
+ return (_a = parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")) === null || _a === void 0 ? void 0 : _a.params.claims;
+}
+//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map
- // If a set of status code are provided and the current status code is not in the list
- if (
- statusCode != null &&
- Array.isArray(statusCodes) &&
- !statusCodes.includes(statusCode)
- ) {
- cb(err)
- return
- }
+/***/ }),
- // If we reached the max number of retries
- if (counter > maxRetries) {
- cb(err)
- return
- }
+/***/ 13299:
+/***/ ((__unused_webpack_module, exports) => {
- let retryAfterHeader = headers != null && headers['retry-after']
- if (retryAfterHeader) {
- retryAfterHeader = Number(retryAfterHeader)
- retryAfterHeader = isNaN(retryAfterHeader)
- ? calculateRetryAfterHeader(retryAfterHeader)
- : retryAfterHeader * 1e3 // Retry-After is in seconds
- }
- const retryTimeout =
- retryAfterHeader > 0
- ? Math.min(retryAfterHeader, maxTimeout)
- : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.decompressResponsePolicyName = void 0;
+exports.decompressResponsePolicy = decompressResponsePolicy;
+/**
+ * The programmatic identifier of the decompressResponsePolicy.
+ */
+exports.decompressResponsePolicyName = "decompressResponsePolicy";
+/**
+ * A policy to enable response decompression according to Accept-Encoding header
+ * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding
+ */
+function decompressResponsePolicy() {
+ return {
+ name: exports.decompressResponsePolicyName,
+ async sendRequest(request, next) {
+ // HEAD requests have no body
+ if (request.method !== "HEAD") {
+ request.headers.set("Accept-Encoding", "gzip,deflate");
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=decompressResponsePolicy.js.map
- state.currentTimeout = retryTimeout
+/***/ }),
- setTimeout(() => cb(null), retryTimeout)
- }
+/***/ 47494:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- onHeaders (statusCode, rawHeaders, resume, statusMessage) {
- const headers = parseHeaders(rawHeaders)
- this.retryCount += 1
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.defaultRetryPolicyName = void 0;
+exports.defaultRetryPolicy = defaultRetryPolicy;
+const exponentialRetryStrategy_js_1 = __nccwpck_require__(34750);
+const throttlingRetryStrategy_js_1 = __nccwpck_require__(40288);
+const retryPolicy_js_1 = __nccwpck_require__(85001);
+const constants_js_1 = __nccwpck_require__(91791);
+/**
+ * Name of the {@link defaultRetryPolicy}
+ */
+exports.defaultRetryPolicyName = "defaultRetryPolicy";
+/**
+ * A policy that retries according to three strategies:
+ * - When the server sends a 429 response with a Retry-After header.
+ * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
+ * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay.
+ */
+function defaultRetryPolicy(options = {}) {
+ var _a;
+ return {
+ name: exports.defaultRetryPolicyName,
+ sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)(), (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(options)], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
+}
+//# sourceMappingURL=defaultRetryPolicy.js.map
- if (statusCode >= 300) {
- this.abort(
- new RequestRetryError('Request failed', statusCode, {
- headers,
- count: this.retryCount
- })
- )
- return false
- }
+/***/ }),
- // Checkpoint for resume from where we left it
- if (this.resume != null) {
- this.resume = null
+/***/ 43048:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (statusCode !== 206) {
- return true
- }
- const contentRange = parseRangeHeader(headers['content-range'])
- // If no content range
- if (!contentRange) {
- this.abort(
- new RequestRetryError('Content-Range mismatch', statusCode, {
- headers,
- count: this.retryCount
- })
- )
- return false
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.exponentialRetryPolicyName = void 0;
+exports.exponentialRetryPolicy = exponentialRetryPolicy;
+const exponentialRetryStrategy_js_1 = __nccwpck_require__(34750);
+const retryPolicy_js_1 = __nccwpck_require__(85001);
+const constants_js_1 = __nccwpck_require__(91791);
+/**
+ * The programmatic identifier of the exponentialRetryPolicy.
+ */
+exports.exponentialRetryPolicyName = "exponentialRetryPolicy";
+/**
+ * A policy that attempts to retry requests while introducing an exponentially increasing delay.
+ * @param options - Options that configure retry logic.
+ */
+function exponentialRetryPolicy(options = {}) {
+ var _a;
+ return (0, retryPolicy_js_1.retryPolicy)([
+ (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreSystemErrors: true })),
+ ], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ });
+}
+//# sourceMappingURL=exponentialRetryPolicy.js.map
- // Let's start with a weak etag check
- if (this.etag != null && this.etag !== headers.etag) {
- this.abort(
- new RequestRetryError('ETag mismatch', statusCode, {
- headers,
- count: this.retryCount
- })
- )
- return false
- }
+/***/ }),
- const { start, size, end = size } = contentRange
+/***/ 37997:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- assert(this.start === start, 'content-range mismatch')
- assert(this.end == null || this.end === end, 'content-range mismatch')
- this.resume = resume
- return true
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.formDataPolicyName = void 0;
+exports.formDataPolicy = formDataPolicy;
+const core_util_1 = __nccwpck_require__(30991);
+const httpHeaders_js_1 = __nccwpck_require__(30596);
+/**
+ * The programmatic identifier of the formDataPolicy.
+ */
+exports.formDataPolicyName = "formDataPolicy";
+function formDataToFormDataMap(formData) {
+ var _a;
+ const formDataMap = {};
+ for (const [key, value] of formData.entries()) {
+ (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : (formDataMap[key] = []);
+ formDataMap[key].push(value);
}
-
- if (this.end == null) {
- if (statusCode === 206) {
- // First time we receive 206
- const range = parseRangeHeader(headers['content-range'])
-
- if (range == null) {
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
+ return formDataMap;
+}
+/**
+ * A policy that encodes FormData on the request into the body.
+ */
+function formDataPolicy() {
+ return {
+ name: exports.formDataPolicyName,
+ async sendRequest(request, next) {
+ if (core_util_1.isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) {
+ request.formData = formDataToFormDataMap(request.body);
+ request.body = undefined;
+ }
+ if (request.formData) {
+ const contentType = request.headers.get("Content-Type");
+ if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) {
+ request.body = wwwFormUrlEncode(request.formData);
+ }
+ else {
+ await prepareFormData(request.formData, request);
+ }
+ request.formData = undefined;
+ }
+ return next(request);
+ },
+ };
+}
+function wwwFormUrlEncode(formData) {
+ const urlSearchParams = new URLSearchParams();
+ for (const [key, value] of Object.entries(formData)) {
+ if (Array.isArray(value)) {
+ for (const subValue of value) {
+ urlSearchParams.append(key, subValue.toString());
+ }
+ }
+ else {
+ urlSearchParams.append(key, value.toString());
}
-
- const { start, size, end = size } = range
-
- assert(
- start != null && Number.isFinite(start) && this.start !== start,
- 'content-range mismatch'
- )
- assert(Number.isFinite(start))
- assert(
- end != null && Number.isFinite(end) && this.end !== end,
- 'invalid content-length'
- )
-
- this.start = start
- this.end = end
- }
-
- // We make our best to checkpoint the body for further range headers
- if (this.end == null) {
- const contentLength = headers['content-length']
- this.end = contentLength != null ? Number(contentLength) : null
- }
-
- assert(Number.isFinite(this.start))
- assert(
- this.end == null || Number.isFinite(this.end),
- 'invalid content-length'
- )
-
- this.resume = resume
- this.etag = headers.etag != null ? headers.etag : null
-
- return this.handler.onHeaders(
- statusCode,
- rawHeaders,
- resume,
- statusMessage
- )
}
-
- const err = new RequestRetryError('Request failed', statusCode, {
- headers,
- count: this.retryCount
- })
-
- this.abort(err)
-
- return false
- }
-
- onData (chunk) {
- this.start += chunk.length
-
- return this.handler.onData(chunk)
- }
-
- onComplete (rawTrailers) {
- this.retryCount = 0
- return this.handler.onComplete(rawTrailers)
- }
-
- onError (err) {
- if (this.aborted || isDisturbed(this.opts.body)) {
- return this.handler.onError(err)
+ return urlSearchParams.toString();
+}
+async function prepareFormData(formData, request) {
+ // validate content type (multipart/form-data)
+ const contentType = request.headers.get("Content-Type");
+ if (contentType && !contentType.startsWith("multipart/form-data")) {
+ // content type is specified and is not multipart/form-data. Exit.
+ return;
}
-
- this.retryOpts.retry(
- err,
- {
- state: { counter: this.retryCount++, currentTimeout: this.retryAfter },
- opts: { retryOptions: this.retryOpts, ...this.opts }
- },
- onRetry.bind(this)
- )
-
- function onRetry (err) {
- if (err != null || this.aborted || isDisturbed(this.opts.body)) {
- return this.handler.onError(err)
- }
-
- if (this.start !== 0) {
- this.opts = {
- ...this.opts,
- headers: {
- ...this.opts.headers,
- range: `bytes=${this.start}-${this.end ?? ''}`
- }
+ request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data");
+ // set body to MultipartRequestBody using content from FormDataMap
+ const parts = [];
+ for (const [fieldName, values] of Object.entries(formData)) {
+ for (const value of Array.isArray(values) ? values : [values]) {
+ if (typeof value === "string") {
+ parts.push({
+ headers: (0, httpHeaders_js_1.createHttpHeaders)({
+ "Content-Disposition": `form-data; name="${fieldName}"`,
+ }),
+ body: (0, core_util_1.stringToUint8Array)(value, "utf-8"),
+ });
+ }
+ else if (value === undefined || value === null || typeof value !== "object") {
+ throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`);
+ }
+ else {
+ // using || instead of ?? here since if value.name is empty we should create a file name
+ const fileName = value.name || "blob";
+ const headers = (0, httpHeaders_js_1.createHttpHeaders)();
+ headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`);
+ // again, || is used since an empty value.type means the content type is unset
+ headers.set("Content-Type", value.type || "application/octet-stream");
+ parts.push({
+ headers,
+ body: value,
+ });
+ }
}
- }
-
- try {
- this.dispatch(this.opts, this)
- } catch (err) {
- this.handler.onError(err)
- }
}
- }
+ request.multipartBody = { parts };
}
-
-module.exports = RetryHandler
-
+//# sourceMappingURL=formDataPolicy.js.map
/***/ }),
-/***/ 99299:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const RedirectHandler = __nccwpck_require__(8591)
-
-function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) {
- return (dispatch) => {
- return function Intercept (opts, handler) {
- const { maxRedirections = defaultMaxRedirections } = opts
+/***/ 19937:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (!maxRedirections) {
- return dispatch(opts, handler)
- }
- const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler)
- opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting.
- return dispatch(opts, redirectHandler)
- }
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.logPolicyName = void 0;
+exports.logPolicy = logPolicy;
+const log_js_1 = __nccwpck_require__(58564);
+const sanitizer_js_1 = __nccwpck_require__(44720);
+/**
+ * The programmatic identifier of the logPolicy.
+ */
+exports.logPolicyName = "logPolicy";
+/**
+ * A policy that logs all requests and responses.
+ * @param options - Options to configure logPolicy.
+ */
+function logPolicy(options = {}) {
+ var _a;
+ const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : log_js_1.logger.info;
+ const sanitizer = new sanitizer_js_1.Sanitizer({
+ additionalAllowedHeaderNames: options.additionalAllowedHeaderNames,
+ additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
+ });
+ return {
+ name: exports.logPolicyName,
+ async sendRequest(request, next) {
+ if (!logger.enabled) {
+ return next(request);
+ }
+ logger(`Request: ${sanitizer.sanitize(request)}`);
+ const response = await next(request);
+ logger(`Response status code: ${response.status}`);
+ logger(`Headers: ${sanitizer.sanitize(response.headers)}`);
+ return response;
+ },
+ };
}
-
-module.exports = createRedirectInterceptor
-
+//# sourceMappingURL=logPolicy.js.map
/***/ }),
-/***/ 40748:
+/***/ 77915:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0;
-const utils_1 = __nccwpck_require__(34608);
-// C headers
-var ERROR;
-(function (ERROR) {
- ERROR[ERROR["OK"] = 0] = "OK";
- ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL";
- ERROR[ERROR["STRICT"] = 2] = "STRICT";
- ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED";
- ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH";
- ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION";
- ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD";
- ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL";
- ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT";
- ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION";
- ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN";
- ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH";
- ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE";
- ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS";
- ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE";
- ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING";
- ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN";
- ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE";
- ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE";
- ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER";
- ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE";
- ERROR[ERROR["PAUSED"] = 21] = "PAUSED";
- ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE";
- ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE";
- ERROR[ERROR["USER"] = 24] = "USER";
-})(ERROR = exports.ERROR || (exports.ERROR = {}));
-var TYPE;
-(function (TYPE) {
- TYPE[TYPE["BOTH"] = 0] = "BOTH";
- TYPE[TYPE["REQUEST"] = 1] = "REQUEST";
- TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE";
-})(TYPE = exports.TYPE || (exports.TYPE = {}));
-var FLAGS;
-(function (FLAGS) {
- FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE";
- FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE";
- FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE";
- FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED";
- FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE";
- FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH";
- FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY";
- FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING";
- // 1 << 8 is unused
- FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING";
-})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
-var LENIENT_FLAGS;
-(function (LENIENT_FLAGS) {
- LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS";
- LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH";
- LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE";
-})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {}));
-var METHODS;
-(function (METHODS) {
- METHODS[METHODS["DELETE"] = 0] = "DELETE";
- METHODS[METHODS["GET"] = 1] = "GET";
- METHODS[METHODS["HEAD"] = 2] = "HEAD";
- METHODS[METHODS["POST"] = 3] = "POST";
- METHODS[METHODS["PUT"] = 4] = "PUT";
- /* pathological */
- METHODS[METHODS["CONNECT"] = 5] = "CONNECT";
- METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS";
- METHODS[METHODS["TRACE"] = 7] = "TRACE";
- /* WebDAV */
- METHODS[METHODS["COPY"] = 8] = "COPY";
- METHODS[METHODS["LOCK"] = 9] = "LOCK";
- METHODS[METHODS["MKCOL"] = 10] = "MKCOL";
- METHODS[METHODS["MOVE"] = 11] = "MOVE";
- METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND";
- METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH";
- METHODS[METHODS["SEARCH"] = 14] = "SEARCH";
- METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK";
- METHODS[METHODS["BIND"] = 16] = "BIND";
- METHODS[METHODS["REBIND"] = 17] = "REBIND";
- METHODS[METHODS["UNBIND"] = 18] = "UNBIND";
- METHODS[METHODS["ACL"] = 19] = "ACL";
- /* subversion */
- METHODS[METHODS["REPORT"] = 20] = "REPORT";
- METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY";
- METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT";
- METHODS[METHODS["MERGE"] = 23] = "MERGE";
- /* upnp */
- METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH";
- METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY";
- METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE";
- METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE";
- /* RFC-5789 */
- METHODS[METHODS["PATCH"] = 28] = "PATCH";
- METHODS[METHODS["PURGE"] = 29] = "PURGE";
- /* CalDAV */
- METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR";
- /* RFC-2068, section 19.6.1.2 */
- METHODS[METHODS["LINK"] = 31] = "LINK";
- METHODS[METHODS["UNLINK"] = 32] = "UNLINK";
- /* icecast */
- METHODS[METHODS["SOURCE"] = 33] = "SOURCE";
- /* RFC-7540, section 11.6 */
- METHODS[METHODS["PRI"] = 34] = "PRI";
- /* RFC-2326 RTSP */
- METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE";
- METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE";
- METHODS[METHODS["SETUP"] = 37] = "SETUP";
- METHODS[METHODS["PLAY"] = 38] = "PLAY";
- METHODS[METHODS["PAUSE"] = 39] = "PAUSE";
- METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN";
- METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER";
- METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER";
- METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT";
- METHODS[METHODS["RECORD"] = 44] = "RECORD";
- /* RAOP */
- METHODS[METHODS["FLUSH"] = 45] = "FLUSH";
-})(METHODS = exports.METHODS || (exports.METHODS = {}));
-exports.METHODS_HTTP = [
- METHODS.DELETE,
- METHODS.GET,
- METHODS.HEAD,
- METHODS.POST,
- METHODS.PUT,
- METHODS.CONNECT,
- METHODS.OPTIONS,
- METHODS.TRACE,
- METHODS.COPY,
- METHODS.LOCK,
- METHODS.MKCOL,
- METHODS.MOVE,
- METHODS.PROPFIND,
- METHODS.PROPPATCH,
- METHODS.SEARCH,
- METHODS.UNLOCK,
- METHODS.BIND,
- METHODS.REBIND,
- METHODS.UNBIND,
- METHODS.ACL,
- METHODS.REPORT,
- METHODS.MKACTIVITY,
- METHODS.CHECKOUT,
- METHODS.MERGE,
- METHODS['M-SEARCH'],
- METHODS.NOTIFY,
- METHODS.SUBSCRIBE,
- METHODS.UNSUBSCRIBE,
- METHODS.PATCH,
- METHODS.PURGE,
- METHODS.MKCALENDAR,
- METHODS.LINK,
- METHODS.UNLINK,
- METHODS.PRI,
- // TODO(indutny): should we allow it with HTTP?
- METHODS.SOURCE,
-];
-exports.METHODS_ICE = [
- METHODS.SOURCE,
-];
-exports.METHODS_RTSP = [
- METHODS.OPTIONS,
- METHODS.DESCRIBE,
- METHODS.ANNOUNCE,
- METHODS.SETUP,
- METHODS.PLAY,
- METHODS.PAUSE,
- METHODS.TEARDOWN,
- METHODS.GET_PARAMETER,
- METHODS.SET_PARAMETER,
- METHODS.REDIRECT,
- METHODS.RECORD,
- METHODS.FLUSH,
- // For AirPlay
- METHODS.GET,
- METHODS.POST,
-];
-exports.METHOD_MAP = utils_1.enumToMap(METHODS);
-exports.H_METHOD_MAP = {};
-Object.keys(exports.METHOD_MAP).forEach((key) => {
- if (/^H/.test(key)) {
- exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key];
+exports.multipartPolicyName = void 0;
+exports.multipartPolicy = multipartPolicy;
+const core_util_1 = __nccwpck_require__(30991);
+const concat_js_1 = __nccwpck_require__(85307);
+const typeGuards_js_1 = __nccwpck_require__(24449);
+function generateBoundary() {
+ return `----AzSDKFormBoundary${(0, core_util_1.randomUUID)()}`;
+}
+function encodeHeaders(headers) {
+ let result = "";
+ for (const [key, value] of headers) {
+ result += `${key}: ${value}\r\n`;
}
-});
-var FINISH;
-(function (FINISH) {
- FINISH[FINISH["SAFE"] = 0] = "SAFE";
- FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB";
- FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE";
-})(FINISH = exports.FINISH || (exports.FINISH = {}));
-exports.ALPHA = [];
-for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) {
- // Upper case
- exports.ALPHA.push(String.fromCharCode(i));
- // Lower case
- exports.ALPHA.push(String.fromCharCode(i + 0x20));
+ return result;
}
-exports.NUM_MAP = {
- 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
- 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
-};
-exports.HEX_MAP = {
- 0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
- 5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
- A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF,
- a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf,
-};
-exports.NUM = [
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
-];
-exports.ALPHANUM = exports.ALPHA.concat(exports.NUM);
-exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')'];
-exports.USERINFO_CHARS = exports.ALPHANUM
- .concat(exports.MARK)
- .concat(['%', ';', ':', '&', '=', '+', '$', ',']);
-// TODO(indutny): use RFC
-exports.STRICT_URL_CHAR = [
- '!', '"', '$', '%', '&', '\'',
- '(', ')', '*', '+', ',', '-', '.', '/',
- ':', ';', '<', '=', '>',
- '@', '[', '\\', ']', '^', '_',
- '`',
- '{', '|', '}', '~',
-].concat(exports.ALPHANUM);
-exports.URL_CHAR = exports.STRICT_URL_CHAR
- .concat(['\t', '\f']);
-// All characters with 0x80 bit set to 1
-for (let i = 0x80; i <= 0xff; i++) {
- exports.URL_CHAR.push(i);
+function getLength(source) {
+ if (source instanceof Uint8Array) {
+ return source.byteLength;
+ }
+ else if ((0, typeGuards_js_1.isBlob)(source)) {
+ // if was created using createFile then -1 means we have an unknown size
+ return source.size === -1 ? undefined : source.size;
+ }
+ else {
+ return undefined;
+ }
}
-exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']);
-/* Tokens as defined by rfc 2616. Also lowercases them.
- * token = 1*
- * separators = "(" | ")" | "<" | ">" | "@"
- * | "," | ";" | ":" | "\" | <">
- * | "/" | "[" | "]" | "?" | "="
- * | "{" | "}" | SP | HT
- */
-exports.STRICT_TOKEN = [
- '!', '#', '$', '%', '&', '\'',
- '*', '+', '-', '.',
- '^', '_', '`',
- '|', '~',
-].concat(exports.ALPHANUM);
-exports.TOKEN = exports.STRICT_TOKEN.concat([' ']);
-/*
- * Verify that a char is a valid visible (printable) US-ASCII
- * character or %x80-FF
+function getTotalLength(sources) {
+ let total = 0;
+ for (const source of sources) {
+ const partLength = getLength(source);
+ if (partLength === undefined) {
+ return undefined;
+ }
+ else {
+ total += partLength;
+ }
+ }
+ return total;
+}
+async function buildRequestBody(request, parts, boundary) {
+ const sources = [
+ (0, core_util_1.stringToUint8Array)(`--${boundary}`, "utf-8"),
+ ...parts.flatMap((part) => [
+ (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
+ (0, core_util_1.stringToUint8Array)(encodeHeaders(part.headers), "utf-8"),
+ (0, core_util_1.stringToUint8Array)("\r\n", "utf-8"),
+ part.body,
+ (0, core_util_1.stringToUint8Array)(`\r\n--${boundary}`, "utf-8"),
+ ]),
+ (0, core_util_1.stringToUint8Array)("--\r\n\r\n", "utf-8"),
+ ];
+ const contentLength = getTotalLength(sources);
+ if (contentLength) {
+ request.headers.set("Content-Length", contentLength);
+ }
+ request.body = await (0, concat_js_1.concat)(sources);
+}
+/**
+ * Name of multipart policy
*/
-exports.HEADER_CHARS = ['\t'];
-for (let i = 32; i <= 255; i++) {
- if (i !== 127) {
- exports.HEADER_CHARS.push(i);
+exports.multipartPolicyName = "multipartPolicy";
+const maxBoundaryLength = 70;
+const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`);
+function assertValidBoundary(boundary) {
+ if (boundary.length > maxBoundaryLength) {
+ throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`);
+ }
+ if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) {
+ throw new Error(`Multipart boundary "${boundary}" contains invalid characters`);
}
}
-// ',' = \x44
-exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44);
-exports.MAJOR = exports.NUM_MAP;
-exports.MINOR = exports.MAJOR;
-var HEADER_STATE;
-(function (HEADER_STATE) {
- HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL";
- HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION";
- HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH";
- HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING";
- HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE";
- HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE";
- HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE";
- HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE";
- HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED";
-})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {}));
-exports.SPECIAL_HEADERS = {
- 'connection': HEADER_STATE.CONNECTION,
- 'content-length': HEADER_STATE.CONTENT_LENGTH,
- 'proxy-connection': HEADER_STATE.CONNECTION,
- 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING,
- 'upgrade': HEADER_STATE.UPGRADE,
-};
-//# sourceMappingURL=constants.js.map
-
-/***/ }),
-
-/***/ 63922:
-/***/ ((module) => {
-
-module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQA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md0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJA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EAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAA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ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/AcABwQHCAc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CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA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AwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8='
-
+/**
+ * Pipeline policy for multipart requests
+ */
+function multipartPolicy() {
+ return {
+ name: exports.multipartPolicyName,
+ async sendRequest(request, next) {
+ var _a;
+ if (!request.multipartBody) {
+ return next(request);
+ }
+ if (request.body) {
+ throw new Error("multipartBody and regular body cannot be set at the same time");
+ }
+ let boundary = request.multipartBody.boundary;
+ const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed";
+ const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/);
+ if (!parsedHeader) {
+ throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`);
+ }
+ const [, contentType, parsedBoundary] = parsedHeader;
+ if (parsedBoundary && boundary && parsedBoundary !== boundary) {
+ throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`);
+ }
+ boundary !== null && boundary !== void 0 ? boundary : (boundary = parsedBoundary);
+ if (boundary) {
+ assertValidBoundary(boundary);
+ }
+ else {
+ boundary = generateBoundary();
+ }
+ request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`);
+ await buildRequestBody(request, request.multipartBody.parts, boundary);
+ request.multipartBody = undefined;
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=multipartPolicy.js.map
/***/ }),
-/***/ 53742:
-/***/ ((module) => {
+/***/ 7303:
+/***/ ((__unused_webpack_module, exports) => {
-module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ2V0X2h0dHBfbWlub3IAEBFsbGh0dHBfZ2V0X21ldGhvZAARFmxsaHR0cF9nZXRfc3RhdHVzX2NvZGUAEhJsbGh0dHBfZ2V0X3VwZ3JhZGUAEwxsbGh0dHBfcmVzZXQAFA5sbGh0dHBfZXhlY3V0ZQAVFGxsaHR0cF9zZXR0aW5nc19pbml0ABYNbGxodHRwX2ZpbmlzaAAXDGxsaHR0cF9wYXVzZQAYDWxsaHR0cF9yZXN1bWUAGR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JAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJA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FCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgAC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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.ndJsonPolicyName = void 0;
+exports.ndJsonPolicy = ndJsonPolicy;
+/**
+ * The programmatic identifier of the ndJsonPolicy.
+ */
+exports.ndJsonPolicyName = "ndJsonPolicy";
+/**
+ * ndJsonPolicy is a policy used to control keep alive settings for every request.
+ */
+function ndJsonPolicy() {
+ return {
+ name: exports.ndJsonPolicyName,
+ async sendRequest(request, next) {
+ // There currently isn't a good way to bypass the serializer
+ if (typeof request.body === "string" && request.body.startsWith("[")) {
+ const body = JSON.parse(request.body);
+ if (Array.isArray(body)) {
+ request.body = body.map((item) => JSON.stringify(item) + "\n").join("");
+ }
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=ndJsonPolicy.js.map
/***/ }),
-/***/ 34608:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 73723:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.enumToMap = void 0;
-function enumToMap(obj) {
- const res = {};
- Object.keys(obj).forEach((key) => {
- const value = obj[key];
- if (typeof value === 'number') {
- res[key] = value;
+exports.globalNoProxyList = exports.proxyPolicyName = void 0;
+exports.loadNoProxy = loadNoProxy;
+exports.getDefaultProxySettings = getDefaultProxySettings;
+exports.proxyPolicy = proxyPolicy;
+const https_proxy_agent_1 = __nccwpck_require__(54129);
+const http_proxy_agent_1 = __nccwpck_require__(31286);
+const log_js_1 = __nccwpck_require__(58564);
+const HTTPS_PROXY = "HTTPS_PROXY";
+const HTTP_PROXY = "HTTP_PROXY";
+const ALL_PROXY = "ALL_PROXY";
+const NO_PROXY = "NO_PROXY";
+/**
+ * The programmatic identifier of the proxyPolicy.
+ */
+exports.proxyPolicyName = "proxyPolicy";
+/**
+ * Stores the patterns specified in NO_PROXY environment variable.
+ * @internal
+ */
+exports.globalNoProxyList = [];
+let noProxyListLoaded = false;
+/** A cache of whether a host should bypass the proxy. */
+const globalBypassedMap = new Map();
+function getEnvironmentValue(name) {
+ if (process.env[name]) {
+ return process.env[name];
+ }
+ else if (process.env[name.toLowerCase()]) {
+ return process.env[name.toLowerCase()];
+ }
+ return undefined;
+}
+function loadEnvironmentProxyValue() {
+ if (!process) {
+ return undefined;
+ }
+ const httpsProxy = getEnvironmentValue(HTTPS_PROXY);
+ const allProxy = getEnvironmentValue(ALL_PROXY);
+ const httpProxy = getEnvironmentValue(HTTP_PROXY);
+ return httpsProxy || allProxy || httpProxy;
+}
+/**
+ * Check whether the host of a given `uri` matches any pattern in the no proxy list.
+ * If there's a match, any request sent to the same host shouldn't have the proxy settings set.
+ * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210
+ */
+function isBypassed(uri, noProxyList, bypassedMap) {
+ if (noProxyList.length === 0) {
+ return false;
+ }
+ const host = new URL(uri).hostname;
+ if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) {
+ return bypassedMap.get(host);
+ }
+ let isBypassedFlag = false;
+ for (const pattern of noProxyList) {
+ if (pattern[0] === ".") {
+ // This should match either domain it self or any subdomain or host
+ // .foo.com will match foo.com it self or *.foo.com
+ if (host.endsWith(pattern)) {
+ isBypassedFlag = true;
+ }
+ else {
+ if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
+ isBypassedFlag = true;
+ }
+ }
}
- });
- return res;
+ else {
+ if (host === pattern) {
+ isBypassedFlag = true;
+ }
+ }
+ }
+ bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag);
+ return isBypassedFlag;
}
-exports.enumToMap = enumToMap;
-//# sourceMappingURL=utils.js.map
-
-/***/ }),
-
-/***/ 77017:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { kClients } = __nccwpck_require__(68031)
-const Agent = __nccwpck_require__(92121)
-const {
- kAgent,
- kMockAgentSet,
- kMockAgentGet,
- kDispatches,
- kIsMockActive,
- kNetConnect,
- kGetNetConnect,
- kOptions,
- kFactory
-} = __nccwpck_require__(52305)
-const MockClient = __nccwpck_require__(72361)
-const MockPool = __nccwpck_require__(36480)
-const { matchValue, buildMockOptions } = __nccwpck_require__(73193)
-const { InvalidArgumentError, UndiciError } = __nccwpck_require__(53959)
-const Dispatcher = __nccwpck_require__(20303)
-const Pluralizer = __nccwpck_require__(35773)
-const PendingInterceptorsFormatter = __nccwpck_require__(85738)
-
-class FakeWeakRef {
- constructor (value) {
- this.value = value
- }
-
- deref () {
- return this.value
- }
+function loadNoProxy() {
+ const noProxy = getEnvironmentValue(NO_PROXY);
+ noProxyListLoaded = true;
+ if (noProxy) {
+ return noProxy
+ .split(",")
+ .map((item) => item.trim())
+ .filter((item) => item.length);
+ }
+ return [];
}
-
-class MockAgent extends Dispatcher {
- constructor (opts) {
- super(opts)
-
- this[kNetConnect] = true
- this[kIsMockActive] = true
-
- // Instantiate Agent and encapsulate
- if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+/**
+ * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy.
+ * If no argument is given, it attempts to parse a proxy URL from the environment
+ * variables `HTTPS_PROXY` or `HTTP_PROXY`.
+ * @param proxyUrl - The url of the proxy to use. May contain authentication information.
+ * @deprecated - Internally this method is no longer necessary when setting proxy information.
+ */
+function getDefaultProxySettings(proxyUrl) {
+ if (!proxyUrl) {
+ proxyUrl = loadEnvironmentProxyValue();
+ if (!proxyUrl) {
+ return undefined;
+ }
}
- const agent = opts && opts.agent ? opts.agent : new Agent(opts)
- this[kAgent] = agent
-
- this[kClients] = agent[kClients]
- this[kOptions] = buildMockOptions(opts)
- }
-
- get (origin) {
- let dispatcher = this[kMockAgentGet](origin)
-
- if (!dispatcher) {
- dispatcher = this[kFactory](origin)
- this[kMockAgentSet](origin, dispatcher)
+ const parsedUrl = new URL(proxyUrl);
+ const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : "";
+ return {
+ host: schema + parsedUrl.hostname,
+ port: Number.parseInt(parsedUrl.port || "80"),
+ username: parsedUrl.username,
+ password: parsedUrl.password,
+ };
+}
+/**
+ * This method attempts to parse a proxy URL from the environment
+ * variables `HTTPS_PROXY` or `HTTP_PROXY`.
+ */
+function getDefaultProxySettingsInternal() {
+ const envProxy = loadEnvironmentProxyValue();
+ return envProxy ? new URL(envProxy) : undefined;
+}
+function getUrlFromProxySettings(settings) {
+ let parsedProxyUrl;
+ try {
+ parsedProxyUrl = new URL(settings.host);
}
- return dispatcher
- }
-
- dispatch (opts, handler) {
- // Call MockAgent.get to perform additional setup before dispatching as normal
- this.get(opts.origin)
- return this[kAgent].dispatch(opts, handler)
- }
-
- async close () {
- await this[kAgent].close()
- this[kClients].clear()
- }
-
- deactivate () {
- this[kIsMockActive] = false
- }
-
- activate () {
- this[kIsMockActive] = true
- }
-
- enableNetConnect (matcher) {
- if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) {
- if (Array.isArray(this[kNetConnect])) {
- this[kNetConnect].push(matcher)
- } else {
- this[kNetConnect] = [matcher]
- }
- } else if (typeof matcher === 'undefined') {
- this[kNetConnect] = true
- } else {
- throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.')
+ catch (_a) {
+ throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`);
}
- }
-
- disableNetConnect () {
- this[kNetConnect] = false
- }
-
- // This is required to bypass issues caused by using global symbols - see:
- // https://github.com/nodejs/undici/issues/1447
- get isMockActive () {
- return this[kIsMockActive]
- }
-
- [kMockAgentSet] (origin, dispatcher) {
- this[kClients].set(origin, new FakeWeakRef(dispatcher))
- }
-
- [kFactory] (origin) {
- const mockOptions = Object.assign({ agent: this }, this[kOptions])
- return this[kOptions] && this[kOptions].connections === 1
- ? new MockClient(origin, mockOptions)
- : new MockPool(origin, mockOptions)
- }
-
- [kMockAgentGet] (origin) {
- // First check if we can immediately find it
- const ref = this[kClients].get(origin)
- if (ref) {
- return ref.deref()
+ parsedProxyUrl.port = String(settings.port);
+ if (settings.username) {
+ parsedProxyUrl.username = settings.username;
}
-
- // If the origin is not a string create a dummy parent pool and return to user
- if (typeof origin !== 'string') {
- const dispatcher = this[kFactory]('http://localhost:9999')
- this[kMockAgentSet](origin, dispatcher)
- return dispatcher
+ if (settings.password) {
+ parsedProxyUrl.password = settings.password;
}
-
- // If we match, create a pool and assign the same dispatches
- for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) {
- const nonExplicitDispatcher = nonExplicitRef.deref()
- if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) {
- const dispatcher = this[kFactory](origin)
- this[kMockAgentSet](origin, dispatcher)
- dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]
- return dispatcher
- }
+ return parsedProxyUrl;
+}
+function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) {
+ // Custom Agent should take precedence so if one is present
+ // we should skip to avoid overwriting it.
+ if (request.agent) {
+ return;
}
- }
-
- [kGetNetConnect] () {
- return this[kNetConnect]
- }
-
- pendingInterceptors () {
- const mockAgentClients = this[kClients]
-
- return Array.from(mockAgentClients.entries())
- .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin })))
- .filter(({ pending }) => pending)
- }
-
- assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) {
- const pending = this.pendingInterceptors()
-
- if (pending.length === 0) {
- return
+ const url = new URL(request.url);
+ const isInsecure = url.protocol !== "https:";
+ if (request.tlsSettings) {
+ log_js_1.logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored.");
+ }
+ const headers = request.headers.toJSON();
+ if (isInsecure) {
+ if (!cachedAgents.httpProxyAgent) {
+ cachedAgents.httpProxyAgent = new http_proxy_agent_1.HttpProxyAgent(proxyUrl, { headers });
+ }
+ request.agent = cachedAgents.httpProxyAgent;
+ }
+ else {
+ if (!cachedAgents.httpsProxyAgent) {
+ cachedAgents.httpsProxyAgent = new https_proxy_agent_1.HttpsProxyAgent(proxyUrl, { headers });
+ }
+ request.agent = cachedAgents.httpsProxyAgent;
}
-
- const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length)
-
- throw new UndiciError(`
-${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending:
-
-${pendingInterceptorsFormatter.format(pending)}
-`.trim())
- }
}
-
-module.exports = MockAgent
-
+/**
+ * A policy that allows one to apply proxy settings to all requests.
+ * If not passed static settings, they will be retrieved from the HTTPS_PROXY
+ * or HTTP_PROXY environment variables.
+ * @param proxySettings - ProxySettings to use on each request.
+ * @param options - additional settings, for example, custom NO_PROXY patterns
+ */
+function proxyPolicy(proxySettings, options) {
+ if (!noProxyListLoaded) {
+ exports.globalNoProxyList.push(...loadNoProxy());
+ }
+ const defaultProxy = proxySettings
+ ? getUrlFromProxySettings(proxySettings)
+ : getDefaultProxySettingsInternal();
+ const cachedAgents = {};
+ return {
+ name: exports.proxyPolicyName,
+ async sendRequest(request, next) {
+ var _a;
+ if (!request.proxySettings &&
+ defaultProxy &&
+ !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : exports.globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? undefined : globalBypassedMap)) {
+ setProxyAgentOnRequest(request, cachedAgents, defaultProxy);
+ }
+ else if (request.proxySettings) {
+ setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings));
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=proxyPolicy.js.map
/***/ }),
-/***/ 72361:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 86947:
+/***/ ((__unused_webpack_module, exports) => {
-const { promisify } = __nccwpck_require__(39023)
-const Client = __nccwpck_require__(45513)
-const { buildMockDispatch } = __nccwpck_require__(73193)
-const {
- kDispatches,
- kMockAgent,
- kClose,
- kOriginalClose,
- kOrigin,
- kOriginalDispatch,
- kConnected
-} = __nccwpck_require__(52305)
-const { MockInterceptor } = __nccwpck_require__(5843)
-const Symbols = __nccwpck_require__(68031)
-const { InvalidArgumentError } = __nccwpck_require__(53959)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.redirectPolicyName = void 0;
+exports.redirectPolicy = redirectPolicy;
/**
- * MockClient provides an API that extends the Client to influence the mockDispatches.
+ * The programmatic identifier of the redirectPolicy.
*/
-class MockClient extends Client {
- constructor (origin, opts) {
- super(origin, opts)
-
- if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+exports.redirectPolicyName = "redirectPolicy";
+/**
+ * Methods that are allowed to follow redirects 301 and 302
+ */
+const allowedRedirect = ["GET", "HEAD"];
+/**
+ * A policy to follow Location headers from the server in order
+ * to support server-side redirection.
+ * In the browser, this policy is not used.
+ * @param options - Options to control policy behavior.
+ */
+function redirectPolicy(options = {}) {
+ const { maxRetries = 20 } = options;
+ return {
+ name: exports.redirectPolicyName,
+ async sendRequest(request, next) {
+ const response = await next(request);
+ return handleRedirect(next, response, maxRetries);
+ },
+ };
+}
+async function handleRedirect(next, response, maxRetries, currentRetries = 0) {
+ const { request, status, headers } = response;
+ const locationHeader = headers.get("location");
+ if (locationHeader &&
+ (status === 300 ||
+ (status === 301 && allowedRedirect.includes(request.method)) ||
+ (status === 302 && allowedRedirect.includes(request.method)) ||
+ (status === 303 && request.method === "POST") ||
+ status === 307) &&
+ currentRetries < maxRetries) {
+ const url = new URL(locationHeader, request.url);
+ request.url = url.toString();
+ // POST request with Status code 303 should be converted into a
+ // redirected GET request if the redirect url is present in the location header
+ if (status === 303) {
+ request.method = "GET";
+ request.headers.delete("Content-Length");
+ delete request.body;
+ }
+ request.headers.delete("Authorization");
+ const res = await next(request);
+ return handleRedirect(next, res, maxRetries, currentRetries + 1);
}
+ return response;
+}
+//# sourceMappingURL=redirectPolicy.js.map
- this[kMockAgent] = opts.agent
- this[kOrigin] = origin
- this[kDispatches] = []
- this[kConnected] = 1
- this[kOriginalDispatch] = this.dispatch
- this[kOriginalClose] = this.close.bind(this)
-
- this.dispatch = buildMockDispatch.call(this)
- this.close = this[kClose]
- }
+/***/ }),
- get [Symbols.kConnected] () {
- return this[kConnected]
- }
+/***/ 85001:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- /**
- * Sets up the base interceptor for mocking replies from undici.
- */
- intercept (opts) {
- return new MockInterceptor(opts, this[kDispatches])
- }
- async [kClose] () {
- await promisify(this[kOriginalClose])()
- this[kConnected] = 0
- this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.retryPolicy = retryPolicy;
+const helpers_js_1 = __nccwpck_require__(94982);
+const logger_1 = __nccwpck_require__(50143);
+const abort_controller_1 = __nccwpck_require__(92242);
+const constants_js_1 = __nccwpck_require__(91791);
+const retryPolicyLogger = (0, logger_1.createClientLogger)("core-rest-pipeline retryPolicy");
+/**
+ * The programmatic identifier of the retryPolicy.
+ */
+const retryPolicyName = "retryPolicy";
+/**
+ * retryPolicy is a generic policy to enable retrying requests when certain conditions are met
+ */
+function retryPolicy(strategies, options = { maxRetries: constants_js_1.DEFAULT_RETRY_POLICY_COUNT }) {
+ const logger = options.logger || retryPolicyLogger;
+ return {
+ name: retryPolicyName,
+ async sendRequest(request, next) {
+ var _a, _b;
+ let response;
+ let responseError;
+ let retryCount = -1;
+ // eslint-disable-next-line no-constant-condition
+ retryRequest: while (true) {
+ retryCount += 1;
+ response = undefined;
+ responseError = undefined;
+ try {
+ logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId);
+ response = await next(request);
+ logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId);
+ }
+ catch (e) {
+ logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId);
+ // RestErrors are valid targets for the retry strategies.
+ // If none of the retry strategies can work with them, they will be thrown later in this policy.
+ // If the received error is not a RestError, it is immediately thrown.
+ responseError = e;
+ if (!e || responseError.name !== "RestError") {
+ throw e;
+ }
+ response = responseError.response;
+ }
+ if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) {
+ logger.error(`Retry ${retryCount}: Request aborted.`);
+ const abortError = new abort_controller_1.AbortError();
+ throw abortError;
+ }
+ if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : constants_js_1.DEFAULT_RETRY_POLICY_COUNT)) {
+ logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`);
+ if (responseError) {
+ throw responseError;
+ }
+ else if (response) {
+ return response;
+ }
+ else {
+ throw new Error("Maximum retries reached with no response or error to throw");
+ }
+ }
+ logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`);
+ strategiesLoop: for (const strategy of strategies) {
+ const strategyLogger = strategy.logger || retryPolicyLogger;
+ strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`);
+ const modifiers = strategy.retry({
+ retryCount,
+ response,
+ responseError,
+ });
+ if (modifiers.skipStrategy) {
+ strategyLogger.info(`Retry ${retryCount}: Skipped.`);
+ continue strategiesLoop;
+ }
+ const { errorToThrow, retryAfterInMs, redirectTo } = modifiers;
+ if (errorToThrow) {
+ strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow);
+ throw errorToThrow;
+ }
+ if (retryAfterInMs || retryAfterInMs === 0) {
+ strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`);
+ await (0, helpers_js_1.delay)(retryAfterInMs, undefined, { abortSignal: request.abortSignal });
+ continue retryRequest;
+ }
+ if (redirectTo) {
+ strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`);
+ request.url = redirectTo;
+ continue retryRequest;
+ }
+ }
+ if (responseError) {
+ logger.info(`None of the retry strategies could work with the received error. Throwing it.`);
+ throw responseError;
+ }
+ if (response) {
+ logger.info(`None of the retry strategies could work with the received response. Returning it.`);
+ return response;
+ }
+ // If all the retries skip and there's no response,
+ // we're still in the retry loop, so a new request will be sent
+ // until `maxRetries` is reached.
+ }
+ },
+ };
}
+//# sourceMappingURL=retryPolicy.js.map
+
+/***/ }),
+
+/***/ 63866:
+/***/ ((__unused_webpack_module, exports) => {
-module.exports = MockClient
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.setClientRequestIdPolicyName = void 0;
+exports.setClientRequestIdPolicy = setClientRequestIdPolicy;
+/**
+ * The programmatic identifier of the setClientRequestIdPolicy.
+ */
+exports.setClientRequestIdPolicyName = "setClientRequestIdPolicy";
+/**
+ * Each PipelineRequest gets a unique id upon creation.
+ * This policy passes that unique id along via an HTTP header to enable better
+ * telemetry and tracing.
+ * @param requestIdHeaderName - The name of the header to pass the request ID to.
+ */
+function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") {
+ return {
+ name: exports.setClientRequestIdPolicyName,
+ async sendRequest(request, next) {
+ if (!request.headers.has(requestIdHeaderName)) {
+ request.headers.set(requestIdHeaderName, request.requestId);
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=setClientRequestIdPolicy.js.map
/***/ }),
-/***/ 12673:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 14298:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const { UndiciError } = __nccwpck_require__(53959)
-class MockNotMatchedError extends UndiciError {
- constructor (message) {
- super(message)
- Error.captureStackTrace(this, MockNotMatchedError)
- this.name = 'MockNotMatchedError'
- this.message = message || 'The request does not match any registered mock dispatches'
- this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.systemErrorRetryPolicyName = void 0;
+exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
+const exponentialRetryStrategy_js_1 = __nccwpck_require__(34750);
+const retryPolicy_js_1 = __nccwpck_require__(85001);
+const constants_js_1 = __nccwpck_require__(91791);
+/**
+ * Name of the {@link systemErrorRetryPolicy}
+ */
+exports.systemErrorRetryPolicyName = "systemErrorRetryPolicy";
+/**
+ * A retry policy that specifically seeks to handle errors in the
+ * underlying transport layer (e.g. DNS lookup failures) rather than
+ * retryable error codes from the server itself.
+ * @param options - Options that customize the policy.
+ */
+function systemErrorRetryPolicy(options = {}) {
+ var _a;
+ return {
+ name: exports.systemErrorRetryPolicyName,
+ sendRequest: (0, retryPolicy_js_1.retryPolicy)([
+ (0, exponentialRetryStrategy_js_1.exponentialRetryStrategy)(Object.assign(Object.assign({}, options), { ignoreHttpStatusCodes: true })),
+ ], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
}
+//# sourceMappingURL=systemErrorRetryPolicy.js.map
-module.exports = {
- MockNotMatchedError
-}
+/***/ }),
+/***/ 96352:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-/***/ }),
-/***/ 5843:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.throttlingRetryPolicyName = void 0;
+exports.throttlingRetryPolicy = throttlingRetryPolicy;
+const throttlingRetryStrategy_js_1 = __nccwpck_require__(40288);
+const retryPolicy_js_1 = __nccwpck_require__(85001);
+const constants_js_1 = __nccwpck_require__(91791);
+/**
+ * Name of the {@link throttlingRetryPolicy}
+ */
+exports.throttlingRetryPolicyName = "throttlingRetryPolicy";
+/**
+ * A policy that retries when the server sends a 429 response with a Retry-After header.
+ *
+ * To learn more, please refer to
+ * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
+ * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
+ * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
+ *
+ * @param options - Options that configure retry logic.
+ */
+function throttlingRetryPolicy(options = {}) {
+ var _a;
+ return {
+ name: exports.throttlingRetryPolicyName,
+ sendRequest: (0, retryPolicy_js_1.retryPolicy)([(0, throttlingRetryStrategy_js_1.throttlingRetryStrategy)()], {
+ maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : constants_js_1.DEFAULT_RETRY_POLICY_COUNT,
+ }).sendRequest,
+ };
+}
+//# sourceMappingURL=throttlingRetryPolicy.js.map
+/***/ }),
+/***/ 39370:
+/***/ ((__unused_webpack_module, exports) => {
-const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(73193)
-const {
- kDispatches,
- kDispatchKey,
- kDefaultHeaders,
- kDefaultTrailers,
- kContentLength,
- kMockDispatch
-} = __nccwpck_require__(52305)
-const { InvalidArgumentError } = __nccwpck_require__(53959)
-const { buildURL } = __nccwpck_require__(89500)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.tlsPolicyName = void 0;
+exports.tlsPolicy = tlsPolicy;
/**
- * Defines the scope API for an interceptor reply
+ * Name of the TLS Policy
*/
-class MockScope {
- constructor (mockDispatch) {
- this[kMockDispatch] = mockDispatch
- }
-
- /**
- * Delay a reply by a set amount in ms.
- */
- delay (waitInMs) {
- if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) {
- throw new InvalidArgumentError('waitInMs must be a valid integer > 0')
- }
-
- this[kMockDispatch].delay = waitInMs
- return this
- }
+exports.tlsPolicyName = "tlsPolicy";
+/**
+ * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication.
+ */
+function tlsPolicy(tlsSettings) {
+ return {
+ name: exports.tlsPolicyName,
+ sendRequest: async (req, next) => {
+ // Users may define a request tlsSettings, honor those over the client level one
+ if (!req.tlsSettings) {
+ req.tlsSettings = tlsSettings;
+ }
+ return next(req);
+ },
+ };
+}
+//# sourceMappingURL=tlsPolicy.js.map
- /**
- * For a defined reply, never mark as consumed.
- */
- persist () {
- this[kMockDispatch].persist = true
- return this
- }
+/***/ }),
- /**
- * Allow one to define a reply for a set amount of matching requests.
- */
- times (repeatTimes) {
- if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) {
- throw new InvalidArgumentError('repeatTimes must be a valid integer > 0')
- }
+/***/ 14113:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this[kMockDispatch].times = repeatTimes
- return this
- }
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.tracingPolicyName = void 0;
+exports.tracingPolicy = tracingPolicy;
+const core_tracing_1 = __nccwpck_require__(7651);
+const constants_js_1 = __nccwpck_require__(91791);
+const userAgent_js_1 = __nccwpck_require__(87747);
+const log_js_1 = __nccwpck_require__(58564);
+const core_util_1 = __nccwpck_require__(30991);
+const restError_js_1 = __nccwpck_require__(97558);
+const sanitizer_js_1 = __nccwpck_require__(44720);
/**
- * Defines an interceptor for a Mock
+ * The programmatic identifier of the tracingPolicy.
*/
-class MockInterceptor {
- constructor (opts, mockDispatches) {
- if (typeof opts !== 'object') {
- throw new InvalidArgumentError('opts must be an object')
+exports.tracingPolicyName = "tracingPolicy";
+/**
+ * A simple policy to create OpenTelemetry Spans for each request made by the pipeline
+ * that has SpanOptions with a parent.
+ * Requests made without a parent Span will not be recorded.
+ * @param options - Options to configure the telemetry logged by the tracing policy.
+ */
+function tracingPolicy(options = {}) {
+ const userAgentPromise = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
+ const sanitizer = new sanitizer_js_1.Sanitizer({
+ additionalAllowedQueryParameters: options.additionalAllowedQueryParameters,
+ });
+ const tracingClient = tryCreateTracingClient();
+ return {
+ name: exports.tracingPolicyName,
+ async sendRequest(request, next) {
+ var _a;
+ if (!tracingClient) {
+ return next(request);
+ }
+ const userAgent = await userAgentPromise;
+ const spanAttributes = {
+ "http.url": sanitizer.sanitizeUrl(request.url),
+ "http.method": request.method,
+ "http.user_agent": userAgent,
+ requestId: request.requestId,
+ };
+ if (userAgent) {
+ spanAttributes["http.user_agent"] = userAgent;
+ }
+ const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {};
+ if (!span || !tracingContext) {
+ return next(request);
+ }
+ try {
+ const response = await tracingClient.withContext(tracingContext, next, request);
+ tryProcessResponse(span, response);
+ return response;
+ }
+ catch (err) {
+ tryProcessError(span, err);
+ throw err;
+ }
+ },
+ };
+}
+function tryCreateTracingClient() {
+ try {
+ return (0, core_tracing_1.createTracingClient)({
+ namespace: "",
+ packageName: "@azure/core-rest-pipeline",
+ packageVersion: constants_js_1.SDK_VERSION,
+ });
}
- if (typeof opts.path === 'undefined') {
- throw new InvalidArgumentError('opts.path must be defined')
+ catch (e) {
+ log_js_1.logger.warning(`Error when creating the TracingClient: ${(0, core_util_1.getErrorMessage)(e)}`);
+ return undefined;
}
- if (typeof opts.method === 'undefined') {
- opts.method = 'GET'
+}
+function tryCreateSpan(tracingClient, request, spanAttributes) {
+ try {
+ // As per spec, we do not need to differentiate between HTTP and HTTPS in span name.
+ const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, {
+ spanKind: "client",
+ spanAttributes,
+ });
+ // If the span is not recording, don't do any more work.
+ if (!span.isRecording()) {
+ span.end();
+ return undefined;
+ }
+ // set headers
+ const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext);
+ for (const [key, value] of Object.entries(headers)) {
+ request.headers.set(key, value);
+ }
+ return { span, tracingContext: updatedOptions.tracingOptions.tracingContext };
}
- // See https://github.com/nodejs/undici/issues/1245
- // As per RFC 3986, clients are not supposed to send URI
- // fragments to servers when they retrieve a document,
- if (typeof opts.path === 'string') {
- if (opts.query) {
- opts.path = buildURL(opts.path, opts.query)
- } else {
- // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811
- const parsedURL = new URL(opts.path, 'data://')
- opts.path = parsedURL.pathname + parsedURL.search
- }
+ catch (e) {
+ log_js_1.logger.warning(`Skipping creating a tracing span due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
+ return undefined;
}
- if (typeof opts.method === 'string') {
- opts.method = opts.method.toUpperCase()
+}
+function tryProcessError(span, error) {
+ try {
+ span.setStatus({
+ status: "error",
+ error: (0, core_util_1.isError)(error) ? error : undefined,
+ });
+ if ((0, restError_js_1.isRestError)(error) && error.statusCode) {
+ span.setAttribute("http.status_code", error.statusCode);
+ }
+ span.end();
}
-
- this[kDispatchKey] = buildKey(opts)
- this[kDispatches] = mockDispatches
- this[kDefaultHeaders] = {}
- this[kDefaultTrailers] = {}
- this[kContentLength] = false
- }
-
- createMockScopeDispatchData (statusCode, data, responseOptions = {}) {
- const responseData = getResponseData(data)
- const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {}
- const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers }
- const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers }
-
- return { statusCode, data, headers, trailers }
- }
-
- validateReplyParameters (statusCode, data, responseOptions) {
- if (typeof statusCode === 'undefined') {
- throw new InvalidArgumentError('statusCode must be defined')
+ catch (e) {
+ log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
}
- if (typeof data === 'undefined') {
- throw new InvalidArgumentError('data must be defined')
+}
+function tryProcessResponse(span, response) {
+ try {
+ span.setAttribute("http.status_code", response.status);
+ const serviceRequestId = response.headers.get("x-ms-request-id");
+ if (serviceRequestId) {
+ span.setAttribute("serviceRequestId", serviceRequestId);
+ }
+ span.setStatus({
+ status: "success",
+ });
+ span.end();
}
- if (typeof responseOptions !== 'object') {
- throw new InvalidArgumentError('responseOptions must be an object')
+ catch (e) {
+ log_js_1.logger.warning(`Skipping tracing span processing due to an error: ${(0, core_util_1.getErrorMessage)(e)}`);
}
- }
-
- /**
- * Mock an undici request with a defined reply.
- */
- reply (replyData) {
- // Values of reply aren't available right now as they
- // can only be available when the reply callback is invoked.
- if (typeof replyData === 'function') {
- // We'll first wrap the provided callback in another function,
- // this function will properly resolve the data from the callback
- // when invoked.
- const wrappedDefaultsCallback = (opts) => {
- // Our reply options callback contains the parameter for statusCode, data and options.
- const resolvedData = replyData(opts)
+}
+//# sourceMappingURL=tracingPolicy.js.map
- // Check if it is in the right format
- if (typeof resolvedData !== 'object') {
- throw new InvalidArgumentError('reply options callback must return an object')
- }
+/***/ }),
- const { statusCode, data = '', responseOptions = {} } = resolvedData
- this.validateReplyParameters(statusCode, data, responseOptions)
- // Since the values can be obtained immediately we return them
- // from this higher order function that will be resolved later.
- return {
- ...this.createMockScopeDispatchData(statusCode, data, responseOptions)
- }
- }
+/***/ 69795:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data.
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback)
- return new MockScope(newMockDispatch)
- }
- // We can have either one or three parameters, if we get here,
- // we should have 1-3 parameters. So we spread the arguments of
- // this function to obtain the parameters, since replyData will always
- // just be the statusCode.
- const [statusCode, data = '', responseOptions = {}] = [...arguments]
- this.validateReplyParameters(statusCode, data, responseOptions)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.userAgentPolicyName = void 0;
+exports.userAgentPolicy = userAgentPolicy;
+const userAgent_js_1 = __nccwpck_require__(87747);
+const UserAgentHeaderName = (0, userAgent_js_1.getUserAgentHeaderName)();
+/**
+ * The programmatic identifier of the userAgentPolicy.
+ */
+exports.userAgentPolicyName = "userAgentPolicy";
+/**
+ * A policy that sets the User-Agent header (or equivalent) to reflect
+ * the library version.
+ * @param options - Options to customize the user agent value.
+ */
+function userAgentPolicy(options = {}) {
+ const userAgentValue = (0, userAgent_js_1.getUserAgentValue)(options.userAgentPrefix);
+ return {
+ name: exports.userAgentPolicyName,
+ async sendRequest(request, next) {
+ if (!request.headers.has(UserAgentHeaderName)) {
+ request.headers.set(UserAgentHeaderName, await userAgentValue);
+ }
+ return next(request);
+ },
+ };
+}
+//# sourceMappingURL=userAgentPolicy.js.map
- // Send in-already provided data like usual
- const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions)
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData)
- return new MockScope(newMockDispatch)
- }
+/***/ }),
- /**
- * Mock an undici request with a defined error.
- */
- replyWithError (error) {
- if (typeof error === 'undefined') {
- throw new InvalidArgumentError('error must be defined')
- }
+/***/ 97558:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error })
- return new MockScope(newMockDispatch)
- }
- /**
- * Set default reply headers on the interceptor for subsequent replies
- */
- defaultReplyHeaders (headers) {
- if (typeof headers === 'undefined') {
- throw new InvalidArgumentError('headers must be defined')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.RestError = void 0;
+exports.isRestError = isRestError;
+const core_util_1 = __nccwpck_require__(30991);
+const inspect_js_1 = __nccwpck_require__(84111);
+const sanitizer_js_1 = __nccwpck_require__(44720);
+const errorSanitizer = new sanitizer_js_1.Sanitizer();
+/**
+ * A custom error type for failed pipeline requests.
+ */
+class RestError extends Error {
+ constructor(message, options = {}) {
+ super(message);
+ this.name = "RestError";
+ this.code = options.code;
+ this.statusCode = options.statusCode;
+ // The request and response may contain sensitive information in the headers or body.
+ // To help prevent this sensitive information being accidentally logged, the request and response
+ // properties are marked as non-enumerable here. This prevents them showing up in the output of
+ // JSON.stringify and console.log.
+ Object.defineProperty(this, "request", { value: options.request, enumerable: false });
+ Object.defineProperty(this, "response", { value: options.response, enumerable: false });
+ Object.setPrototypeOf(this, RestError.prototype);
}
-
- this[kDefaultHeaders] = headers
- return this
- }
-
- /**
- * Set default reply trailers on the interceptor for subsequent replies
- */
- defaultReplyTrailers (trailers) {
- if (typeof trailers === 'undefined') {
- throw new InvalidArgumentError('trailers must be defined')
+ /**
+ * Logging method for util.inspect in Node
+ */
+ [inspect_js_1.custom]() {
+ // Extract non-enumerable properties and add them back. This is OK since in this output the request and
+ // response get sanitized.
+ return `RestError: ${this.message} \n ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`;
}
-
- this[kDefaultTrailers] = trailers
- return this
- }
-
- /**
- * Set reply content length header for replies on the interceptor
- */
- replyContentLength () {
- this[kContentLength] = true
- return this
- }
}
-
-module.exports.MockInterceptor = MockInterceptor
-module.exports.MockScope = MockScope
-
+exports.RestError = RestError;
+/**
+ * Something went wrong when making the request.
+ * This means the actual request failed for some reason,
+ * such as a DNS issue or the connection being lost.
+ */
+RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
+/**
+ * This means that parsing the response from the server failed.
+ * It may have been malformed.
+ */
+RestError.PARSE_ERROR = "PARSE_ERROR";
+/**
+ * Typeguard for RestError
+ * @param e - Something caught by a catch clause.
+ */
+function isRestError(e) {
+ if (e instanceof RestError) {
+ return true;
+ }
+ return (0, core_util_1.isError)(e) && e.name === "RestError";
+}
+//# sourceMappingURL=restError.js.map
/***/ }),
-/***/ 36480:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 34750:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const { promisify } = __nccwpck_require__(39023)
-const Pool = __nccwpck_require__(44288)
-const { buildMockDispatch } = __nccwpck_require__(73193)
-const {
- kDispatches,
- kMockAgent,
- kClose,
- kOriginalClose,
- kOrigin,
- kOriginalDispatch,
- kConnected
-} = __nccwpck_require__(52305)
-const { MockInterceptor } = __nccwpck_require__(5843)
-const Symbols = __nccwpck_require__(68031)
-const { InvalidArgumentError } = __nccwpck_require__(53959)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.exponentialRetryStrategy = exponentialRetryStrategy;
+exports.isExponentialRetryResponse = isExponentialRetryResponse;
+exports.isSystemError = isSystemError;
+const core_util_1 = __nccwpck_require__(30991);
+const throttlingRetryStrategy_js_1 = __nccwpck_require__(40288);
+// intervals are in milliseconds
+const DEFAULT_CLIENT_RETRY_INTERVAL = 1000;
+const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64;
/**
- * MockPool provides an API that extends the Pool to influence the mockDispatches.
+ * A retry strategy that retries with an exponentially increasing delay in these two cases:
+ * - When there are errors in the underlying transport layer (e.g. DNS lookup failures).
+ * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505).
*/
-class MockPool extends Pool {
- constructor (origin, opts) {
- super(origin, opts)
-
- if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') {
- throw new InvalidArgumentError('Argument opts.agent must implement Agent')
+function exponentialRetryStrategy(options = {}) {
+ var _a, _b;
+ const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL;
+ const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
+ return {
+ name: "exponentialRetryStrategy",
+ retry({ retryCount, response, responseError }) {
+ const matchedSystemError = isSystemError(responseError);
+ const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors;
+ const isExponential = isExponentialRetryResponse(response);
+ const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes;
+ const unknownResponse = response && ((0, throttlingRetryStrategy_js_1.isThrottlingRetryResponse)(response) || !isExponential);
+ if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) {
+ return { skipStrategy: true };
+ }
+ if (responseError && !matchedSystemError && !isExponential) {
+ return { errorToThrow: responseError };
+ }
+ return (0, core_util_1.calculateRetryDelay)(retryCount, {
+ retryDelayInMs: retryInterval,
+ maxRetryDelayInMs: maxRetryInterval,
+ });
+ },
+ };
+}
+/**
+ * A response is a retry response if it has status codes:
+ * - 408, or
+ * - Greater or equal than 500, except for 501 and 505.
+ */
+function isExponentialRetryResponse(response) {
+ return Boolean(response &&
+ response.status !== undefined &&
+ (response.status >= 500 || response.status === 408) &&
+ response.status !== 501 &&
+ response.status !== 505);
+}
+/**
+ * Determines whether an error from a pipeline response was triggered in the network layer.
+ */
+function isSystemError(err) {
+ if (!err) {
+ return false;
}
-
- this[kMockAgent] = opts.agent
- this[kOrigin] = origin
- this[kDispatches] = []
- this[kConnected] = 1
- this[kOriginalDispatch] = this.dispatch
- this[kOriginalClose] = this.close.bind(this)
-
- this.dispatch = buildMockDispatch.call(this)
- this.close = this[kClose]
- }
-
- get [Symbols.kConnected] () {
- return this[kConnected]
- }
-
- /**
- * Sets up the base interceptor for mocking replies from undici.
- */
- intercept (opts) {
- return new MockInterceptor(opts, this[kDispatches])
- }
-
- async [kClose] () {
- await promisify(this[kOriginalClose])()
- this[kConnected] = 0
- this[kMockAgent][Symbols.kClients].delete(this[kOrigin])
- }
+ return (err.code === "ETIMEDOUT" ||
+ err.code === "ESOCKETTIMEDOUT" ||
+ err.code === "ECONNREFUSED" ||
+ err.code === "ECONNRESET" ||
+ err.code === "ENOENT" ||
+ err.code === "ENOTFOUND");
}
-
-module.exports = MockPool
-
+//# sourceMappingURL=exponentialRetryStrategy.js.map
/***/ }),
-/***/ 52305:
-/***/ ((module) => {
-
+/***/ 40288:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = {
- kAgent: Symbol('agent'),
- kOptions: Symbol('options'),
- kFactory: Symbol('factory'),
- kDispatches: Symbol('dispatches'),
- kDispatchKey: Symbol('dispatch key'),
- kDefaultHeaders: Symbol('default headers'),
- kDefaultTrailers: Symbol('default trailers'),
- kContentLength: Symbol('content length'),
- kMockAgent: Symbol('mock agent'),
- kMockAgentSet: Symbol('mock agent set'),
- kMockAgentGet: Symbol('mock agent get'),
- kMockDispatch: Symbol('mock dispatch'),
- kClose: Symbol('close'),
- kOriginalClose: Symbol('original agent close'),
- kOrigin: Symbol('origin'),
- kIsMockActive: Symbol('is mock active'),
- kNetConnect: Symbol('net connect'),
- kGetNetConnect: Symbol('get net connect'),
- kConnected: Symbol('connected')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isThrottlingRetryResponse = isThrottlingRetryResponse;
+exports.throttlingRetryStrategy = throttlingRetryStrategy;
+const helpers_js_1 = __nccwpck_require__(94982);
+/**
+ * The header that comes back from Azure services representing
+ * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry).
+ */
+const RetryAfterHeader = "Retry-After";
+/**
+ * The headers that come back from Azure services representing
+ * the amount of time (minimum) to wait to retry.
+ *
+ * "retry-after-ms", "x-ms-retry-after-ms" : milliseconds
+ * "Retry-After" : seconds or timestamp
+ */
+const AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader];
+/**
+ * A response is a throttling retry response if it has a throttling status code (429 or 503),
+ * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
+ *
+ * Returns the `retryAfterInMs` value if the response is a throttling retry response.
+ * If not throttling retry response, returns `undefined`.
+ *
+ * @internal
+ */
+function getRetryAfterInMs(response) {
+ if (!(response && [429, 503].includes(response.status)))
+ return undefined;
+ try {
+ // Headers: "retry-after-ms", "x-ms-retry-after-ms", "Retry-After"
+ for (const header of AllRetryAfterHeaders) {
+ const retryAfterValue = (0, helpers_js_1.parseHeaderValueAsNumber)(response, header);
+ if (retryAfterValue === 0 || retryAfterValue) {
+ // "Retry-After" header ==> seconds
+ // "retry-after-ms", "x-ms-retry-after-ms" headers ==> milli-seconds
+ const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1;
+ return retryAfterValue * multiplyingFactor; // in milli-seconds
+ }
+ }
+ // RetryAfterHeader ("Retry-After") has a special case where it might be formatted as a date instead of a number of seconds
+ const retryAfterHeader = response.headers.get(RetryAfterHeader);
+ if (!retryAfterHeader)
+ return;
+ const date = Date.parse(retryAfterHeader);
+ const diff = date - Date.now();
+ // negative diff would mean a date in the past, so retry asap with 0 milliseconds
+ return Number.isFinite(diff) ? Math.max(0, diff) : undefined;
+ }
+ catch (_a) {
+ return undefined;
+ }
}
-
+/**
+ * A response is a retry response if it has a throttling status code (429 or 503),
+ * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value.
+ */
+function isThrottlingRetryResponse(response) {
+ return Number.isFinite(getRetryAfterInMs(response));
+}
+function throttlingRetryStrategy() {
+ return {
+ name: "throttlingRetryStrategy",
+ retry({ response }) {
+ const retryAfterInMs = getRetryAfterInMs(response);
+ if (!Number.isFinite(retryAfterInMs)) {
+ return { skipStrategy: true };
+ }
+ return {
+ retryAfterInMs,
+ };
+ },
+ };
+}
+//# sourceMappingURL=throttlingRetryStrategy.js.map
/***/ }),
-/***/ 73193:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 85307:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const { MockNotMatchedError } = __nccwpck_require__(12673)
-const {
- kDispatches,
- kMockAgent,
- kOriginalDispatch,
- kOrigin,
- kGetNetConnect
-} = __nccwpck_require__(52305)
-const { buildURL, nop } = __nccwpck_require__(89500)
-const { STATUS_CODES } = __nccwpck_require__(58611)
-const {
- types: {
- isPromise
- }
-} = __nccwpck_require__(39023)
-function matchValue (match, value) {
- if (typeof match === 'string') {
- return match === value
- }
- if (match instanceof RegExp) {
- return match.test(value)
- }
- if (typeof match === 'function') {
- return match(value) === true
- }
- return false
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.concat = concat;
+const tslib_1 = __nccwpck_require__(94176);
+const node_stream_1 = __nccwpck_require__(57075);
+const typeGuards_js_1 = __nccwpck_require__(24449);
+const file_js_1 = __nccwpck_require__(8581);
+function streamAsyncIterator() {
+ return tslib_1.__asyncGenerator(this, arguments, function* streamAsyncIterator_1() {
+ const reader = this.getReader();
+ try {
+ while (true) {
+ const { done, value } = yield tslib_1.__await(reader.read());
+ if (done) {
+ return yield tslib_1.__await(void 0);
+ }
+ yield yield tslib_1.__await(value);
+ }
+ }
+ finally {
+ reader.releaseLock();
+ }
+ });
}
-
-function lowerCaseEntries (headers) {
- return Object.fromEntries(
- Object.entries(headers).map(([headerName, headerValue]) => {
- return [headerName.toLocaleLowerCase(), headerValue]
- })
- )
+function makeAsyncIterable(webStream) {
+ if (!webStream[Symbol.asyncIterator]) {
+ webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream);
+ }
+ if (!webStream.values) {
+ webStream.values = streamAsyncIterator.bind(webStream);
+ }
+}
+function ensureNodeStream(stream) {
+ if (stream instanceof ReadableStream) {
+ makeAsyncIterable(stream);
+ return node_stream_1.Readable.fromWeb(stream);
+ }
+ else {
+ return stream;
+ }
+}
+function toStream(source) {
+ if (source instanceof Uint8Array) {
+ return node_stream_1.Readable.from(Buffer.from(source));
+ }
+ else if ((0, typeGuards_js_1.isBlob)(source)) {
+ return toStream((0, file_js_1.getRawContent)(source));
+ }
+ else {
+ return ensureNodeStream(source);
+ }
}
-
/**
- * @param {import('../../index').Headers|string[]|Record} headers
- * @param {string} key
+ * Utility function that concatenates a set of binary inputs into one combined output.
+ *
+ * @param sources - array of sources for the concatenation
+ * @returns - in Node, a (() =\> NodeJS.ReadableStream) which, when read, produces a concatenation of all the inputs.
+ * In browser, returns a `Blob` representing all the concatenated inputs.
+ *
+ * @internal
*/
-function getHeaderByName (headers, key) {
- if (Array.isArray(headers)) {
- for (let i = 0; i < headers.length; i += 2) {
- if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) {
- return headers[i + 1]
- }
- }
-
- return undefined
- } else if (typeof headers.get === 'function') {
- return headers.get(key)
- } else {
- return lowerCaseEntries(headers)[key.toLocaleLowerCase()]
- }
+async function concat(sources) {
+ return function () {
+ const streams = sources.map((x) => (typeof x === "function" ? x() : x)).map(toStream);
+ return node_stream_1.Readable.from((function () {
+ return tslib_1.__asyncGenerator(this, arguments, function* () {
+ var _a, e_1, _b, _c;
+ for (const stream of streams) {
+ try {
+ for (var _d = true, stream_1 = (e_1 = void 0, tslib_1.__asyncValues(stream)), stream_1_1; stream_1_1 = yield tslib_1.__await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) {
+ _c = stream_1_1.value;
+ _d = false;
+ const chunk = _c;
+ yield yield tslib_1.__await(chunk);
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (!_d && !_a && (_b = stream_1.return)) yield tslib_1.__await(_b.call(stream_1));
+ }
+ finally { if (e_1) throw e_1.error; }
+ }
+ }
+ });
+ })());
+ };
}
+//# sourceMappingURL=concat.js.map
-/** @param {string[]} headers */
-function buildHeadersFromArray (headers) { // fetch HeadersList
- const clone = headers.slice()
- const entries = []
- for (let index = 0; index < clone.length; index += 2) {
- entries.push([clone[index], clone[index + 1]])
- }
- return Object.fromEntries(entries)
-}
+/***/ }),
-function matchHeaders (mockDispatch, headers) {
- if (typeof mockDispatch.headers === 'function') {
- if (Array.isArray(headers)) { // fetch HeadersList
- headers = buildHeadersFromArray(headers)
- }
- return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {})
- }
- if (typeof mockDispatch.headers === 'undefined') {
- return true
- }
- if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') {
- return false
- }
+/***/ 8581:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) {
- const headerValue = getHeaderByName(headers, matchHeaderName)
- if (!matchValue(matchHeaderValue, headerValue)) {
- return false
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getRawContent = getRawContent;
+exports.createFileFromStream = createFileFromStream;
+exports.createFile = createFile;
+const core_util_1 = __nccwpck_require__(30991);
+const typeGuards_js_1 = __nccwpck_require__(24449);
+const unimplementedMethods = {
+ arrayBuffer: () => {
+ throw new Error("Not implemented");
+ },
+ slice: () => {
+ throw new Error("Not implemented");
+ },
+ text: () => {
+ throw new Error("Not implemented");
+ },
+};
+/**
+ * Private symbol used as key on objects created using createFile containing the
+ * original source of the file object.
+ *
+ * This is used in Node to access the original Node stream without using Blob#stream, which
+ * returns a web stream. This is done to avoid a couple of bugs to do with Blob#stream and
+ * Readable#to/fromWeb in Node versions we support:
+ * - https://github.com/nodejs/node/issues/42694 (fixed in Node 18.14)
+ * - https://github.com/nodejs/node/issues/48916 (fixed in Node 20.6)
+ *
+ * Once these versions are no longer supported, we may be able to stop doing this.
+ *
+ * @internal
+ */
+const rawContent = Symbol("rawContent");
+function hasRawContent(x) {
+ return typeof x[rawContent] === "function";
+}
+/**
+ * Extract the raw content from a given blob-like object. If the input was created using createFile
+ * or createFileFromStream, the exact content passed into createFile/createFileFromStream will be used.
+ * For true instances of Blob and File, returns the blob's content as a Web ReadableStream.
+ *
+ * @internal
+ */
+function getRawContent(blob) {
+ if (hasRawContent(blob)) {
+ return blob[rawContent]();
+ }
+ else {
+ return blob.stream();
}
- }
- return true
}
+/**
+ * Create an object that implements the File interface. This object is intended to be
+ * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
+ * other situations.
+ *
+ * Use this function to:
+ * - Create a File object for use in RequestBodyType.formData in environments where the
+ * global File object is unavailable.
+ * - Create a File-like object from a readable stream without reading the stream into memory.
+ *
+ * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is
+ * passed in a request's form data map, the stream will not be read into memory
+ * and instead will be streamed when the request is made. In the event of a retry, the
+ * stream needs to be read again, so this callback SHOULD return a fresh stream if possible.
+ * @param name - the name of the file.
+ * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
+ */
+function createFileFromStream(stream, name, options = {}) {
+ var _a, _b, _c, _d;
+ return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => {
+ const s = stream();
+ if ((0, typeGuards_js_1.isNodeReadableStream)(s)) {
+ throw new Error("Not supported: a Node stream was provided as input to createFileFromStream.");
+ }
+ return s;
+ }, [rawContent]: stream });
+}
+/**
+ * Create an object that implements the File interface. This object is intended to be
+ * passed into RequestBodyType.formData, and is not guaranteed to work as expected in
+ * other situations.
+ *
+ * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable.
+ *
+ * @param content - the content of the file as a Uint8Array in memory.
+ * @param name - the name of the file.
+ * @param options - optional metadata about the file, e.g. file name, file size, MIME type.
+ */
+function createFile(content, name, options = {}) {
+ var _a, _b, _c;
+ if (core_util_1.isNodeLike) {
+ return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content });
+ }
+ else {
+ return new File([content], name, options);
+ }
+}
+//# sourceMappingURL=file.js.map
-function safeUrl (path) {
- if (typeof path !== 'string') {
- return path
- }
-
- const pathSegments = path.split('?')
+/***/ }),
- if (pathSegments.length !== 2) {
- return path
- }
+/***/ 94982:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- const qp = new URLSearchParams(pathSegments.pop())
- qp.sort()
- return [...pathSegments, qp.toString()].join('?')
-}
-function matchKey (mockDispatch, { path, method, body, headers }) {
- const pathMatch = matchValue(mockDispatch.path, path)
- const methodMatch = matchValue(mockDispatch.method, method)
- const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true
- const headersMatch = matchHeaders(mockDispatch, headers)
- return pathMatch && methodMatch && bodyMatch && headersMatch
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.delay = delay;
+exports.parseHeaderValueAsNumber = parseHeaderValueAsNumber;
+const abort_controller_1 = __nccwpck_require__(92242);
+const StandardAbortMessage = "The operation was aborted.";
+/**
+ * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds.
+ * @param delayInMs - The number of milliseconds to be delayed.
+ * @param value - The value to be resolved with after a timeout of t milliseconds.
+ * @param options - The options for delay - currently abort options
+ * - abortSignal - The abortSignal associated with containing operation.
+ * - abortErrorMsg - The abort error message associated with containing operation.
+ * @returns Resolved promise
+ */
+function delay(delayInMs, value, options) {
+ return new Promise((resolve, reject) => {
+ let timer = undefined;
+ let onAborted = undefined;
+ const rejectOnAbort = () => {
+ return reject(new abort_controller_1.AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage));
+ };
+ const removeListeners = () => {
+ if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) {
+ options.abortSignal.removeEventListener("abort", onAborted);
+ }
+ };
+ onAborted = () => {
+ if (timer) {
+ clearTimeout(timer);
+ }
+ removeListeners();
+ return rejectOnAbort();
+ };
+ if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) {
+ return rejectOnAbort();
+ }
+ timer = setTimeout(() => {
+ removeListeners();
+ resolve(value);
+ }, delayInMs);
+ if (options === null || options === void 0 ? void 0 : options.abortSignal) {
+ options.abortSignal.addEventListener("abort", onAborted);
+ }
+ });
}
-
-function getResponseData (data) {
- if (Buffer.isBuffer(data)) {
- return data
- } else if (typeof data === 'object') {
- return JSON.stringify(data)
- } else {
- return data.toString()
- }
+/**
+ * @internal
+ * @returns the parsed value or undefined if the parsed value is invalid.
+ */
+function parseHeaderValueAsNumber(response, headerName) {
+ const value = response.headers.get(headerName);
+ if (!value)
+ return;
+ const valueAsNum = Number(value);
+ if (Number.isNaN(valueAsNum))
+ return;
+ return valueAsNum;
}
+//# sourceMappingURL=helpers.js.map
-function getMockDispatch (mockDispatches, key) {
- const basePath = key.query ? buildURL(key.path, key.query) : key.path
- const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath
+/***/ }),
- // Match path
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`)
- }
+/***/ 84111:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- // Match method
- matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`)
- }
- // Match body
- matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true)
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.custom = void 0;
+const node_util_1 = __nccwpck_require__(57975);
+exports.custom = node_util_1.inspect.custom;
+//# sourceMappingURL=inspect.js.map
- // Match headers
- matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers))
- if (matchedMockDispatches.length === 0) {
- throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`)
- }
+/***/ }),
- return matchedMockDispatches[0]
-}
+/***/ 44720:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-function addMockDispatch (mockDispatches, key, data) {
- const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }
- const replyData = typeof data === 'function' ? { callback: data } : { ...data }
- const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }
- mockDispatches.push(newMockDispatch)
- return newMockDispatch
-}
-function deleteMockDispatch (mockDispatches, key) {
- const index = mockDispatches.findIndex(dispatch => {
- if (!dispatch.consumed) {
- return false
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.Sanitizer = void 0;
+const core_util_1 = __nccwpck_require__(30991);
+const RedactedString = "REDACTED";
+// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts
+const defaultAllowedHeaderNames = [
+ "x-ms-client-request-id",
+ "x-ms-return-client-request-id",
+ "x-ms-useragent",
+ "x-ms-correlation-request-id",
+ "x-ms-request-id",
+ "client-request-id",
+ "ms-cv",
+ "return-client-request-id",
+ "traceparent",
+ "Access-Control-Allow-Credentials",
+ "Access-Control-Allow-Headers",
+ "Access-Control-Allow-Methods",
+ "Access-Control-Allow-Origin",
+ "Access-Control-Expose-Headers",
+ "Access-Control-Max-Age",
+ "Access-Control-Request-Headers",
+ "Access-Control-Request-Method",
+ "Origin",
+ "Accept",
+ "Accept-Encoding",
+ "Cache-Control",
+ "Connection",
+ "Content-Length",
+ "Content-Type",
+ "Date",
+ "ETag",
+ "Expires",
+ "If-Match",
+ "If-Modified-Since",
+ "If-None-Match",
+ "If-Unmodified-Since",
+ "Last-Modified",
+ "Pragma",
+ "Request-Id",
+ "Retry-After",
+ "Server",
+ "Transfer-Encoding",
+ "User-Agent",
+ "WWW-Authenticate",
+];
+const defaultAllowedQueryParameters = ["api-version"];
+/**
+ * @internal
+ */
+class Sanitizer {
+ constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) {
+ allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames);
+ allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters);
+ this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase()));
+ this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase()));
+ }
+ sanitize(obj) {
+ const seen = new Set();
+ return JSON.stringify(obj, (key, value) => {
+ // Ensure Errors include their interesting non-enumerable members
+ if (value instanceof Error) {
+ return Object.assign(Object.assign({}, value), { name: value.name, message: value.message });
+ }
+ if (key === "headers") {
+ return this.sanitizeHeaders(value);
+ }
+ else if (key === "url") {
+ return this.sanitizeUrl(value);
+ }
+ else if (key === "query") {
+ return this.sanitizeQuery(value);
+ }
+ else if (key === "body") {
+ // Don't log the request body
+ return undefined;
+ }
+ else if (key === "response") {
+ // Don't log response again
+ return undefined;
+ }
+ else if (key === "operationSpec") {
+ // When using sendOperationRequest, the request carries a massive
+ // field with the autorest spec. No need to log it.
+ return undefined;
+ }
+ else if (Array.isArray(value) || (0, core_util_1.isObject)(value)) {
+ if (seen.has(value)) {
+ return "[Circular]";
+ }
+ seen.add(value);
+ }
+ return value;
+ }, 2);
+ }
+ sanitizeUrl(value) {
+ if (typeof value !== "string" || value === null || value === "") {
+ return value;
+ }
+ const url = new URL(value);
+ if (!url.search) {
+ return value;
+ }
+ for (const [key] of url.searchParams) {
+ if (!this.allowedQueryParameters.has(key.toLowerCase())) {
+ url.searchParams.set(key, RedactedString);
+ }
+ }
+ return url.toString();
+ }
+ sanitizeHeaders(obj) {
+ const sanitized = {};
+ for (const key of Object.keys(obj)) {
+ if (this.allowedHeaderNames.has(key.toLowerCase())) {
+ sanitized[key] = obj[key];
+ }
+ else {
+ sanitized[key] = RedactedString;
+ }
+ }
+ return sanitized;
+ }
+ sanitizeQuery(value) {
+ if (typeof value !== "object" || value === null) {
+ return value;
+ }
+ const sanitized = {};
+ for (const k of Object.keys(value)) {
+ if (this.allowedQueryParameters.has(k.toLowerCase())) {
+ sanitized[k] = value[k];
+ }
+ else {
+ sanitized[k] = RedactedString;
+ }
+ }
+ return sanitized;
}
- return matchKey(dispatch, key)
- })
- if (index !== -1) {
- mockDispatches.splice(index, 1)
- }
}
+exports.Sanitizer = Sanitizer;
+//# sourceMappingURL=sanitizer.js.map
-function buildKey (opts) {
- const { path, method, body, headers, query } = opts
- return {
- path,
- method,
- body,
- headers,
- query
- }
-}
+/***/ }),
-function generateKeyValues (data) {
- return Object.entries(data).reduce((keyValuePairs, [key, value]) => [
- ...keyValuePairs,
- Buffer.from(`${key}`),
- Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`)
- ], [])
-}
+/***/ 82534:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.DEFAULT_CYCLER_OPTIONS = void 0;
+exports.createTokenCycler = createTokenCycler;
+const helpers_js_1 = __nccwpck_require__(94982);
+// Default options for the cycler if none are provided
+exports.DEFAULT_CYCLER_OPTIONS = {
+ forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires
+ retryIntervalInMs: 3000, // Allow refresh attempts every 3s
+ refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry
+};
/**
- * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
- * @param {number} statusCode
+ * Converts an an unreliable access token getter (which may resolve with null)
+ * into an AccessTokenGetter by retrying the unreliable getter in a regular
+ * interval.
+ *
+ * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null.
+ * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts.
+ * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception.
+ * @returns - A promise that, if it resolves, will resolve with an access token.
*/
-function getStatusText (statusCode) {
- return STATUS_CODES[statusCode] || 'unknown'
-}
-
-async function getResponse (body) {
- const buffers = []
- for await (const data of body) {
- buffers.push(data)
- }
- return Buffer.concat(buffers).toString('utf8')
+async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) {
+ // This wrapper handles exceptions gracefully as long as we haven't exceeded
+ // the timeout.
+ async function tryGetAccessToken() {
+ if (Date.now() < refreshTimeout) {
+ try {
+ return await getAccessToken();
+ }
+ catch (_a) {
+ return null;
+ }
+ }
+ else {
+ const finalToken = await getAccessToken();
+ // Timeout is up, so throw if it's still null
+ if (finalToken === null) {
+ throw new Error("Failed to refresh access token.");
+ }
+ return finalToken;
+ }
+ }
+ let token = await tryGetAccessToken();
+ while (token === null) {
+ await (0, helpers_js_1.delay)(retryIntervalInMs);
+ token = await tryGetAccessToken();
+ }
+ return token;
}
-
/**
- * Mock dispatch function used to simulate undici dispatches
+ * Creates a token cycler from a credential, scopes, and optional settings.
+ *
+ * A token cycler represents a way to reliably retrieve a valid access token
+ * from a TokenCredential. It will handle initializing the token, refreshing it
+ * when it nears expiration, and synchronizes refresh attempts to avoid
+ * concurrency hazards.
+ *
+ * @param credential - the underlying TokenCredential that provides the access
+ * token
+ * @param tokenCyclerOptions - optionally override default settings for the cycler
+ *
+ * @returns - a function that reliably produces a valid access token
*/
-function mockDispatch (opts, handler) {
- // Get mock dispatch from built key
- const key = buildKey(opts)
- const mockDispatch = getMockDispatch(this[kDispatches], key)
-
- mockDispatch.timesInvoked++
-
- // Here's where we resolve a callback if a callback is present for the dispatch data.
- if (mockDispatch.data.callback) {
- mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }
- }
-
- // Parse mockDispatch data
- const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch
- const { timesInvoked, times } = mockDispatch
-
- // If it's used up and not persistent, mark as consumed
- mockDispatch.consumed = !persist && timesInvoked >= times
- mockDispatch.pending = timesInvoked < times
-
- // If specified, trigger dispatch error
- if (error !== null) {
- deleteMockDispatch(this[kDispatches], key)
- handler.onError(error)
- return true
- }
-
- // Handle the request with a delay if necessary
- if (typeof delay === 'number' && delay > 0) {
- setTimeout(() => {
- handleReply(this[kDispatches])
- }, delay)
- } else {
- handleReply(this[kDispatches])
- }
-
- function handleReply (mockDispatches, _data = data) {
- // fetch's HeadersList is a 1D string array
- const optsHeaders = Array.isArray(opts.headers)
- ? buildHeadersFromArray(opts.headers)
- : opts.headers
- const body = typeof _data === 'function'
- ? _data({ ...opts, headers: optsHeaders })
- : _data
-
- // util.types.isPromise is likely needed for jest.
- if (isPromise(body)) {
- // If handleReply is asynchronous, throwing an error
- // in the callback will reject the promise, rather than
- // synchronously throw the error, which breaks some tests.
- // Rather, we wait for the callback to resolve if it is a
- // promise, and then re-run handleReply with the new body.
- body.then((newData) => handleReply(mockDispatches, newData))
- return
- }
-
- const responseData = getResponseData(body)
- const responseHeaders = generateKeyValues(headers)
- const responseTrailers = generateKeyValues(trailers)
-
- handler.abort = nop
- handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode))
- handler.onData(Buffer.from(responseData))
- handler.onComplete(responseTrailers)
- deleteMockDispatch(mockDispatches, key)
- }
+function createTokenCycler(credential, tokenCyclerOptions) {
+ let refreshWorker = null;
+ let token = null;
+ let tenantId;
+ const options = Object.assign(Object.assign({}, exports.DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions);
+ /**
+ * This little holder defines several predicates that we use to construct
+ * the rules of refreshing the token.
+ */
+ const cycler = {
+ /**
+ * Produces true if a refresh job is currently in progress.
+ */
+ get isRefreshing() {
+ return refreshWorker !== null;
+ },
+ /**
+ * Produces true if the cycler SHOULD refresh (we are within the refresh
+ * window and not already refreshing)
+ */
+ get shouldRefresh() {
+ var _a;
+ if (cycler.isRefreshing) {
+ return false;
+ }
+ if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) {
+ return true;
+ }
+ return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now();
+ },
+ /**
+ * Produces true if the cycler MUST refresh (null or nearly-expired
+ * token).
+ */
+ get mustRefresh() {
+ return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now());
+ },
+ };
+ /**
+ * Starts a refresh job or returns the existing job if one is already
+ * running.
+ */
+ function refresh(scopes, getTokenOptions) {
+ var _a;
+ if (!cycler.isRefreshing) {
+ // We bind `scopes` here to avoid passing it around a lot
+ const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions);
+ // Take advantage of promise chaining to insert an assignment to `token`
+ // before the refresh can be considered done.
+ refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs,
+ // If we don't have a token, then we should timeout immediately
+ (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now())
+ .then((_token) => {
+ refreshWorker = null;
+ token = _token;
+ tenantId = getTokenOptions.tenantId;
+ return token;
+ })
+ .catch((reason) => {
+ // We also should reset the refresher if we enter a failed state. All
+ // existing awaiters will throw, but subsequent requests will start a
+ // new retry chain.
+ refreshWorker = null;
+ token = null;
+ tenantId = undefined;
+ throw reason;
+ });
+ }
+ return refreshWorker;
+ }
+ return async (scopes, tokenOptions) => {
+ //
+ // Simple rules:
+ // - If we MUST refresh, then return the refresh task, blocking
+ // the pipeline until a token is available.
+ // - If we SHOULD refresh, then run refresh but don't return it
+ // (we can still use the cached token).
+ // - Return the token, since it's fine if we didn't return in
+ // step 1.
+ //
+ const hasClaimChallenge = Boolean(tokenOptions.claims);
+ const tenantIdChanged = tenantId !== tokenOptions.tenantId;
+ if (hasClaimChallenge) {
+ // If we've received a claim, we know the existing token isn't valid
+ // We want to clear it so that that refresh worker won't use the old expiration time as a timeout
+ token = null;
+ }
+ // If the tenantId passed in token options is different to the one we have
+ // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to
+ // refresh the token with the new tenantId or token.
+ const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh;
+ if (mustRefresh) {
+ return refresh(scopes, tokenOptions);
+ }
+ if (cycler.shouldRefresh) {
+ refresh(scopes, tokenOptions);
+ }
+ return token;
+ };
+}
+//# sourceMappingURL=tokenCycler.js.map
- function resume () {}
+/***/ }),
- return true
-}
+/***/ 24449:
+/***/ ((__unused_webpack_module, exports) => {
-function buildMockDispatch () {
- const agent = this[kMockAgent]
- const origin = this[kOrigin]
- const originalDispatch = this[kOriginalDispatch]
- return function dispatch (opts, handler) {
- if (agent.isMockActive) {
- try {
- mockDispatch.call(this, opts, handler)
- } catch (error) {
- if (error instanceof MockNotMatchedError) {
- const netConnect = agent[kGetNetConnect]()
- if (netConnect === false) {
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`)
- }
- if (checkNetConnect(netConnect, origin)) {
- originalDispatch.call(this, opts, handler)
- } else {
- throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`)
- }
- } else {
- throw error
- }
- }
- } else {
- originalDispatch.call(this, opts, handler)
- }
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isNodeReadableStream = isNodeReadableStream;
+exports.isWebReadableStream = isWebReadableStream;
+exports.isReadableStream = isReadableStream;
+exports.isBlob = isBlob;
+function isNodeReadableStream(x) {
+ return Boolean(x && typeof x["pipe"] === "function");
}
-
-function checkNetConnect (netConnect, origin) {
- const url = new URL(origin)
- if (netConnect === true) {
- return true
- } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) {
- return true
- }
- return false
+function isWebReadableStream(x) {
+ return Boolean(x &&
+ typeof x.getReader === "function" &&
+ typeof x.tee === "function");
}
-
-function buildMockOptions (opts) {
- if (opts) {
- const { agent, ...mockOptions } = opts
- return mockOptions
- }
+function isReadableStream(x) {
+ return isNodeReadableStream(x) || isWebReadableStream(x);
}
-
-module.exports = {
- getResponseData,
- getMockDispatch,
- addMockDispatch,
- deleteMockDispatch,
- buildKey,
- generateKeyValues,
- matchValue,
- getResponse,
- getStatusText,
- mockDispatch,
- buildMockDispatch,
- checkNetConnect,
- buildMockOptions,
- getHeaderByName
+function isBlob(x) {
+ return typeof x.stream === "function";
}
-
+//# sourceMappingURL=typeGuards.js.map
/***/ }),
-/***/ 85738:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
+/***/ 87747:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const { Transform } = __nccwpck_require__(2203)
-const { Console } = __nccwpck_require__(64236)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getUserAgentHeaderName = getUserAgentHeaderName;
+exports.getUserAgentValue = getUserAgentValue;
+const userAgentPlatform_js_1 = __nccwpck_require__(72100);
+const constants_js_1 = __nccwpck_require__(91791);
+function getUserAgentString(telemetryInfo) {
+ const parts = [];
+ for (const [key, value] of telemetryInfo) {
+ const token = value ? `${key}/${value}` : key;
+ parts.push(token);
+ }
+ return parts.join(" ");
+}
/**
- * Gets the output of `console.table(…)` as a string.
+ * @internal
*/
-module.exports = class PendingInterceptorsFormatter {
- constructor ({ disableColors } = {}) {
- this.transform = new Transform({
- transform (chunk, _enc, cb) {
- cb(null, chunk)
- }
- })
-
- this.logger = new Console({
- stdout: this.transform,
- inspectOptions: {
- colors: !disableColors && !process.env.CI
- }
- })
- }
-
- format (pendingInterceptors) {
- const withPrettyHeaders = pendingInterceptors.map(
- ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
- Method: method,
- Origin: origin,
- Path: path,
- 'Status code': statusCode,
- Persistent: persist ? '✅' : '❌',
- Invocations: timesInvoked,
- Remaining: persist ? Infinity : times - timesInvoked
- }))
-
- this.logger.table(withPrettyHeaders)
- return this.transform.read().toString()
- }
+function getUserAgentHeaderName() {
+ return (0, userAgentPlatform_js_1.getHeaderName)();
}
-
+/**
+ * @internal
+ */
+async function getUserAgentValue(prefix) {
+ const runtimeInfo = new Map();
+ runtimeInfo.set("core-rest-pipeline", constants_js_1.SDK_VERSION);
+ await (0, userAgentPlatform_js_1.setPlatformSpecificData)(runtimeInfo);
+ const defaultAgent = getUserAgentString(runtimeInfo);
+ const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent;
+ return userAgentValue;
+}
+//# sourceMappingURL=userAgent.js.map
/***/ }),
-/***/ 35773:
-/***/ ((module) => {
-
-
+/***/ 72100:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const singulars = {
- pronoun: 'it',
- is: 'is',
- was: 'was',
- this: 'this'
-}
-const plurals = {
- pronoun: 'they',
- is: 'are',
- was: 'were',
- this: 'these'
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getHeaderName = getHeaderName;
+exports.setPlatformSpecificData = setPlatformSpecificData;
+const tslib_1 = __nccwpck_require__(94176);
+const os = tslib_1.__importStar(__nccwpck_require__(48161));
+const process = tslib_1.__importStar(__nccwpck_require__(1708));
+/**
+ * @internal
+ */
+function getHeaderName() {
+ return "User-Agent";
}
-
-module.exports = class Pluralizer {
- constructor (singular, plural) {
- this.singular = singular
- this.plural = plural
- }
-
- pluralize (count) {
- const one = count === 1
- const keys = one ? singulars : plurals
- const noun = one ? this.singular : this.plural
- return { ...keys, count, noun }
- }
+/**
+ * @internal
+ */
+async function setPlatformSpecificData(map) {
+ if (process && process.versions) {
+ const versions = process.versions;
+ if (versions.bun) {
+ map.set("Bun", versions.bun);
+ }
+ else if (versions.deno) {
+ map.set("Deno", versions.deno);
+ }
+ else if (versions.node) {
+ map.set("Node", versions.node);
+ }
+ }
+ map.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`);
}
-
+//# sourceMappingURL=userAgentPlatform.js.map
/***/ }),
-/***/ 98721:
-/***/ ((module) => {
+/***/ 7651:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-/* eslint-disable */
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createTracingClient = exports.useInstrumenter = void 0;
+var instrumenter_js_1 = __nccwpck_require__(7565);
+Object.defineProperty(exports, "useInstrumenter", ({ enumerable: true, get: function () { return instrumenter_js_1.useInstrumenter; } }));
+var tracingClient_js_1 = __nccwpck_require__(30530);
+Object.defineProperty(exports, "createTracingClient", ({ enumerable: true, get: function () { return tracingClient_js_1.createTracingClient; } }));
+//# sourceMappingURL=index.js.map
+/***/ }),
-// Extracted from node/lib/internal/fixed_queue.js
+/***/ 7565:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two.
-const kSize = 2048;
-const kMask = kSize - 1;
-// The FixedQueue is implemented as a singly-linked list of fixed-size
-// circular buffers. It looks something like this:
-//
-// head tail
-// | |
-// v v
-// +-----------+ <-----\ +-----------+ <------\ +-----------+
-// | [null] | \----- | next | \------- | next |
-// +-----------+ +-----------+ +-----------+
-// | item | <-- bottom | item | <-- bottom | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | | [empty] |
-// | item | | item | bottom --> | item |
-// | item | | item | | item |
-// | ... | | ... | | ... |
-// | item | | item | | item |
-// | item | | item | | item |
-// | [empty] | <-- top | item | | item |
-// | [empty] | | item | | item |
-// | [empty] | | [empty] | <-- top top --> | [empty] |
-// +-----------+ +-----------+ +-----------+
-//
-// Or, if there is only one circular buffer, it looks something
-// like either of these:
-//
-// head tail head tail
-// | | | |
-// v v v v
-// +-----------+ +-----------+
-// | [null] | | [null] |
-// +-----------+ +-----------+
-// | [empty] | | item |
-// | [empty] | | item |
-// | item | <-- bottom top --> | [empty] |
-// | item | | [empty] |
-// | [empty] | <-- top bottom --> | item |
-// | [empty] | | item |
-// +-----------+ +-----------+
-//
-// Adding a value means moving `top` forward by one, removing means
-// moving `bottom` forward by one. After reaching the end, the queue
-// wraps around.
-//
-// When `top === bottom` the current queue is empty and when
-// `top + 1 === bottom` it's full. This wastes a single space of storage
-// but allows much quicker checks.
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createDefaultTracingSpan = createDefaultTracingSpan;
+exports.createDefaultInstrumenter = createDefaultInstrumenter;
+exports.useInstrumenter = useInstrumenter;
+exports.getInstrumenter = getInstrumenter;
+const tracingContext_js_1 = __nccwpck_require__(81334);
+const state_js_1 = __nccwpck_require__(53398);
+function createDefaultTracingSpan() {
+ return {
+ end: () => {
+ // noop
+ },
+ isRecording: () => false,
+ recordException: () => {
+ // noop
+ },
+ setAttribute: () => {
+ // noop
+ },
+ setStatus: () => {
+ // noop
+ },
+ addEvent: () => {
+ // noop
+ },
+ };
+}
+function createDefaultInstrumenter() {
+ return {
+ createRequestHeaders: () => {
+ return {};
+ },
+ parseTraceparentHeader: () => {
+ return undefined;
+ },
+ startSpan: (_name, spanOptions) => {
+ return {
+ span: createDefaultTracingSpan(),
+ tracingContext: (0, tracingContext_js_1.createTracingContext)({ parentContext: spanOptions.tracingContext }),
+ };
+ },
+ withContext(_context, callback, ...callbackArgs) {
+ return callback(...callbackArgs);
+ },
+ };
+}
+/**
+ * Extends the Azure SDK with support for a given instrumenter implementation.
+ *
+ * @param instrumenter - The instrumenter implementation to use.
+ */
+function useInstrumenter(instrumenter) {
+ state_js_1.state.instrumenterImplementation = instrumenter;
+}
+/**
+ * Gets the currently set instrumenter, a No-Op instrumenter by default.
+ *
+ * @returns The currently set instrumenter
+ */
+function getInstrumenter() {
+ if (!state_js_1.state.instrumenterImplementation) {
+ state_js_1.state.instrumenterImplementation = createDefaultInstrumenter();
+ }
+ return state_js_1.state.instrumenterImplementation;
+}
+//# sourceMappingURL=instrumenter.js.map
-class FixedCircularBuffer {
- constructor() {
- this.bottom = 0;
- this.top = 0;
- this.list = new Array(kSize);
- this.next = null;
- }
+/***/ }),
- isEmpty() {
- return this.top === this.bottom;
- }
+/***/ 53398:
+/***/ ((__unused_webpack_module, exports) => {
- isFull() {
- return ((this.top + 1) & kMask) === this.bottom;
- }
- push(data) {
- this.list[this.top] = data;
- this.top = (this.top + 1) & kMask;
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.state = void 0;
+/**
+ * @internal
+ *
+ * Holds the singleton instrumenter, to be shared across CJS and ESM imports.
+ */
+exports.state = {
+ instrumenterImplementation: undefined,
+};
+//# sourceMappingURL=state-cjs.cjs.map
- shift() {
- const nextItem = this.list[this.bottom];
- if (nextItem === undefined)
- return null;
- this.list[this.bottom] = undefined;
- this.bottom = (this.bottom + 1) & kMask;
- return nextItem;
- }
-}
+/***/ }),
-module.exports = class FixedQueue {
- constructor() {
- this.head = this.tail = new FixedCircularBuffer();
- }
+/***/ 30530:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- isEmpty() {
- return this.head.isEmpty();
- }
- push(data) {
- if (this.head.isFull()) {
- // Head is full: Creates a new queue, sets the old queue's `.next` to it,
- // and sets it as the new main queue.
- this.head = this.head.next = new FixedCircularBuffer();
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createTracingClient = createTracingClient;
+const instrumenter_js_1 = __nccwpck_require__(7565);
+const tracingContext_js_1 = __nccwpck_require__(81334);
+/**
+ * Creates a new tracing client.
+ *
+ * @param options - Options used to configure the tracing client.
+ * @returns - An instance of {@link TracingClient}.
+ */
+function createTracingClient(options) {
+ const { namespace, packageName, packageVersion } = options;
+ function startSpan(name, operationOptions, spanOptions) {
+ var _a;
+ const startSpanResult = (0, instrumenter_js_1.getInstrumenter)().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName: packageName, packageVersion: packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext }));
+ let tracingContext = startSpanResult.tracingContext;
+ const span = startSpanResult.span;
+ if (!tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace)) {
+ tracingContext = tracingContext.setValue(tracingContext_js_1.knownContextKeys.namespace, namespace);
+ }
+ span.setAttribute("az.namespace", tracingContext.getValue(tracingContext_js_1.knownContextKeys.namespace));
+ const updatedOptions = Object.assign({}, operationOptions, {
+ tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }),
+ });
+ return {
+ span,
+ updatedOptions,
+ };
}
- this.head.push(data);
- }
-
- shift() {
- const tail = this.tail;
- const next = tail.shift();
- if (tail.isEmpty() && tail.next !== null) {
- // If there is another queue, it forms the new tail.
- this.tail = tail.next;
+ async function withSpan(name, operationOptions, callback, spanOptions) {
+ const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions);
+ try {
+ const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span)));
+ span.setStatus({ status: "success" });
+ return result;
+ }
+ catch (err) {
+ span.setStatus({ status: "error", error: err });
+ throw err;
+ }
+ finally {
+ span.end();
+ }
+ }
+ function withContext(context, callback, ...callbackArgs) {
+ return (0, instrumenter_js_1.getInstrumenter)().withContext(context, callback, ...callbackArgs);
+ }
+ /**
+ * Parses a traceparent header value into a span identifier.
+ *
+ * @param traceparentHeader - The traceparent header to parse.
+ * @returns An implementation-specific identifier for the span.
+ */
+ function parseTraceparentHeader(traceparentHeader) {
+ return (0, instrumenter_js_1.getInstrumenter)().parseTraceparentHeader(traceparentHeader);
+ }
+ /**
+ * Creates a set of request headers to propagate tracing information to a backend.
+ *
+ * @param tracingContext - The context containing the span to serialize.
+ * @returns The set of headers to add to a request.
+ */
+ function createRequestHeaders(tracingContext) {
+ return (0, instrumenter_js_1.getInstrumenter)().createRequestHeaders(tracingContext);
}
- return next;
- }
-};
-
+ return {
+ startSpan,
+ withSpan,
+ withContext,
+ parseTraceparentHeader,
+ createRequestHeaders,
+ };
+}
+//# sourceMappingURL=tracingClient.js.map
/***/ }),
-/***/ 18804:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+/***/ 81334:
+/***/ ((__unused_webpack_module, exports) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.TracingContextImpl = exports.knownContextKeys = void 0;
+exports.createTracingContext = createTracingContext;
+/** @internal */
+exports.knownContextKeys = {
+ span: Symbol.for("@azure/core-tracing span"),
+ namespace: Symbol.for("@azure/core-tracing namespace"),
+};
+/**
+ * Creates a new {@link TracingContext} with the given options.
+ * @param options - A set of known keys that may be set on the context.
+ * @returns A new {@link TracingContext} with the given options.
+ *
+ * @internal
+ */
+function createTracingContext(options = {}) {
+ let context = new TracingContextImpl(options.parentContext);
+ if (options.span) {
+ context = context.setValue(exports.knownContextKeys.span, options.span);
+ }
+ if (options.namespace) {
+ context = context.setValue(exports.knownContextKeys.namespace, options.namespace);
+ }
+ return context;
+}
+/** @internal */
+class TracingContextImpl {
+ constructor(initialContext) {
+ this._contextMap =
+ initialContext instanceof TracingContextImpl
+ ? new Map(initialContext._contextMap)
+ : new Map();
+ }
+ setValue(key, value) {
+ const newContext = new TracingContextImpl(this);
+ newContext._contextMap.set(key, value);
+ return newContext;
+ }
+ getValue(key) {
+ return this._contextMap.get(key);
+ }
+ deleteValue(key) {
+ const newContext = new TracingContextImpl(this);
+ newContext._contextMap.delete(key);
+ return newContext;
+ }
+}
+exports.TracingContextImpl = TracingContextImpl;
+//# sourceMappingURL=tracingContext.js.map
-const DispatcherBase = __nccwpck_require__(52421)
-const FixedQueue = __nccwpck_require__(98721)
-const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(68031)
-const PoolStats = __nccwpck_require__(29218)
+/***/ }),
-const kClients = Symbol('clients')
-const kNeedDrain = Symbol('needDrain')
-const kQueue = Symbol('queue')
-const kClosedResolve = Symbol('closed resolve')
-const kOnDrain = Symbol('onDrain')
-const kOnConnect = Symbol('onConnect')
-const kOnDisconnect = Symbol('onDisconnect')
-const kOnConnectionError = Symbol('onConnectionError')
-const kGetDispatcher = Symbol('get dispatcher')
-const kAddClient = Symbol('add client')
-const kRemoveClient = Symbol('remove client')
-const kStats = Symbol('stats')
+/***/ 86805:
+/***/ ((__unused_webpack_module, exports) => {
-class PoolBase extends DispatcherBase {
- constructor () {
- super()
- this[kQueue] = new FixedQueue()
- this[kClients] = []
- this[kQueued] = 0
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.cancelablePromiseRace = cancelablePromiseRace;
+/**
+ * promise.race() wrapper that aborts rest of promises as soon as the first promise settles.
+ */
+async function cancelablePromiseRace(abortablePromiseBuilders, options) {
+ var _a, _b;
+ const aborter = new AbortController();
+ function abortHandler() {
+ aborter.abort();
+ }
+ (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.addEventListener("abort", abortHandler);
+ try {
+ return await Promise.race(abortablePromiseBuilders.map((p) => p({ abortSignal: aborter.signal })));
+ }
+ finally {
+ aborter.abort();
+ (_b = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _b === void 0 ? void 0 : _b.removeEventListener("abort", abortHandler);
+ }
+}
+//# sourceMappingURL=aborterUtils.js.map
- const pool = this
+/***/ }),
- this[kOnDrain] = function onDrain (origin, targets) {
- const queue = pool[kQueue]
+/***/ 84073:
+/***/ ((__unused_webpack_module, exports) => {
- let needDrain = false
- while (!needDrain) {
- const item = queue.shift()
- if (!item) {
- break
- }
- pool[kQueued]--
- needDrain = !this.dispatch(item.opts, item.handler)
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.uint8ArrayToString = uint8ArrayToString;
+exports.stringToUint8Array = stringToUint8Array;
+/**
+ * The helper that transforms bytes with specific character encoding into string
+ * @param bytes - the uint8array bytes
+ * @param format - the format we use to encode the byte
+ * @returns a string of the encoded string
+ */
+function uint8ArrayToString(bytes, format) {
+ return Buffer.from(bytes).toString(format);
+}
+/**
+ * The helper that transforms string to specific character encoded bytes array.
+ * @param value - the string to be converted
+ * @param format - the format we use to decode the value
+ * @returns a uint8array
+ */
+function stringToUint8Array(value, format) {
+ return Buffer.from(value, format);
+}
+//# sourceMappingURL=bytesEncoding.js.map
- this[kNeedDrain] = needDrain
+/***/ }),
- if (!this[kNeedDrain] && pool[kNeedDrain]) {
- pool[kNeedDrain] = false
- pool.emit('drain', origin, [pool, ...targets])
- }
+/***/ 2910:
+/***/ ((__unused_webpack_module, exports) => {
- if (pool[kClosedResolve] && queue.isEmpty()) {
- Promise
- .all(pool[kClients].map(c => c.close()))
- .then(pool[kClosedResolve])
- }
- }
- this[kOnConnect] = (origin, targets) => {
- pool.emit('connect', origin, [pool, ...targets])
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+var _a, _b, _c, _d;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isReactNative = exports.isNodeRuntime = exports.isNode = exports.isNodeLike = exports.isBun = exports.isDeno = exports.isWebWorker = exports.isBrowser = void 0;
+/**
+ * A constant that indicates whether the environment the code is running is a Web Browser.
+ */
+// eslint-disable-next-line @azure/azure-sdk/ts-no-window
+exports.isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is a Web Worker.
+ */
+exports.isWebWorker = typeof self === "object" &&
+ typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" &&
+ (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" ||
+ ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" ||
+ ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope");
+/**
+ * A constant that indicates whether the environment the code is running is Deno.
+ */
+exports.isDeno = typeof Deno !== "undefined" &&
+ typeof Deno.version !== "undefined" &&
+ typeof Deno.version.deno !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is Bun.sh.
+ */
+exports.isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined";
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ */
+exports.isNodeLike = typeof globalThis.process !== "undefined" &&
+ Boolean(globalThis.process.version) &&
+ Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node);
+/**
+ * A constant that indicates whether the environment the code is running is a Node.js compatible environment.
+ * @deprecated Use `isNodeLike` instead.
+ */
+exports.isNode = exports.isNodeLike;
+/**
+ * A constant that indicates whether the environment the code is running is Node.JS.
+ */
+exports.isNodeRuntime = exports.isNodeLike && !exports.isBun && !exports.isDeno;
+/**
+ * A constant that indicates whether the environment the code is running is in React-Native.
+ */
+// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js
+exports.isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative";
+//# sourceMappingURL=checkEnvironment.js.map
- this[kOnDisconnect] = (origin, targets, err) => {
- pool.emit('disconnect', origin, [pool, ...targets], err)
- }
+/***/ }),
- this[kOnConnectionError] = (origin, targets, err) => {
- pool.emit('connectionError', origin, [pool, ...targets], err)
- }
+/***/ 33716:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- this[kStats] = new PoolStats(this)
- }
- get [kBusy] () {
- return this[kNeedDrain]
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.createAbortablePromise = createAbortablePromise;
+const abort_controller_1 = __nccwpck_require__(92242);
+/**
+ * Creates an abortable promise.
+ * @param buildPromise - A function that takes the resolve and reject functions as parameters.
+ * @param options - The options for the abortable promise.
+ * @returns A promise that can be aborted.
+ */
+function createAbortablePromise(buildPromise, options) {
+ const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
+ return new Promise((resolve, reject) => {
+ function rejectOnAbort() {
+ reject(new abort_controller_1.AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted."));
+ }
+ function removeListeners() {
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort);
+ }
+ function onAbort() {
+ cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort();
+ removeListeners();
+ rejectOnAbort();
+ }
+ if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) {
+ return rejectOnAbort();
+ }
+ try {
+ buildPromise((x) => {
+ removeListeners();
+ resolve(x);
+ }, (x) => {
+ removeListeners();
+ reject(x);
+ });
+ }
+ catch (err) {
+ reject(err);
+ }
+ abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort);
+ });
+}
+//# sourceMappingURL=createAbortablePromise.js.map
- get [kConnected] () {
- return this[kClients].filter(client => client[kConnected]).length
- }
+/***/ }),
- get [kFree] () {
- return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length
- }
+/***/ 54744:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- get [kPending] () {
- let ret = this[kQueued]
- for (const { [kPending]: pending } of this[kClients]) {
- ret += pending
- }
- return ret
- }
- get [kRunning] () {
- let ret = 0
- for (const { [kRunning]: running } of this[kClients]) {
- ret += running
- }
- return ret
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.delay = delay;
+exports.calculateRetryDelay = calculateRetryDelay;
+const createAbortablePromise_js_1 = __nccwpck_require__(33716);
+const random_js_1 = __nccwpck_require__(50832);
+const StandardAbortMessage = "The delay was aborted.";
+/**
+ * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds.
+ * @param timeInMs - The number of milliseconds to be delayed.
+ * @param options - The options for delay - currently abort options
+ * @returns Promise that is resolved after timeInMs
+ */
+function delay(timeInMs, options) {
+ let token;
+ const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {};
+ return (0, createAbortablePromise_js_1.createAbortablePromise)((resolve) => {
+ token = setTimeout(resolve, timeInMs);
+ }, {
+ cleanupBeforeAbort: () => clearTimeout(token),
+ abortSignal,
+ abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage,
+ });
+}
+/**
+ * Calculates the delay interval for retry attempts using exponential delay with jitter.
+ * @param retryAttempt - The current retry attempt number.
+ * @param config - The exponential retry configuration.
+ * @returns An object containing the calculated retry delay.
+ */
+function calculateRetryDelay(retryAttempt, config) {
+ // Exponentially increase the delay each time
+ const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt);
+ // Don't let the delay exceed the maximum
+ const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay);
+ // Allow the final value to have some "jitter" (within 50% of the delay size) so
+ // that retries across multiple clients don't occur simultaneously.
+ const retryAfterInMs = clampedDelay / 2 + (0, random_js_1.getRandomIntegerInclusive)(0, clampedDelay / 2);
+ return { retryAfterInMs };
+}
+//# sourceMappingURL=delay.js.map
- get [kSize] () {
- let ret = this[kQueued]
- for (const { [kSize]: size } of this[kClients]) {
- ret += size
- }
- return ret
- }
+/***/ }),
- get stats () {
- return this[kStats]
- }
+/***/ 69213:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- async [kClose] () {
- if (this[kQueue].isEmpty()) {
- return Promise.all(this[kClients].map(c => c.close()))
- } else {
- return new Promise((resolve) => {
- this[kClosedResolve] = resolve
- })
- }
- }
- async [kDestroy] (err) {
- while (true) {
- const item = this[kQueue].shift()
- if (!item) {
- break
- }
- item.handler.onError(err)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isError = isError;
+exports.getErrorMessage = getErrorMessage;
+const object_js_1 = __nccwpck_require__(15360);
+/**
+ * Typeguard for an error object shape (has name and message)
+ * @param e - Something caught by a catch clause.
+ */
+function isError(e) {
+ if ((0, object_js_1.isObject)(e)) {
+ const hasName = typeof e.name === "string";
+ const hasMessage = typeof e.message === "string";
+ return hasName && hasMessage;
}
-
- return Promise.all(this[kClients].map(c => c.destroy(err)))
- }
-
- [kDispatch] (opts, handler) {
- const dispatcher = this[kGetDispatcher]()
-
- if (!dispatcher) {
- this[kNeedDrain] = true
- this[kQueue].push({ opts, handler })
- this[kQueued]++
- } else if (!dispatcher.dispatch(opts, handler)) {
- dispatcher[kNeedDrain] = true
- this[kNeedDrain] = !this[kGetDispatcher]()
+ return false;
+}
+/**
+ * Given what is thought to be an error object, return the message if possible.
+ * If the message is missing, returns a stringified version of the input.
+ * @param e - Something thrown from a try block
+ * @returns The error message or a string of the input
+ */
+function getErrorMessage(e) {
+ if (isError(e)) {
+ return e.message;
}
-
- return !this[kNeedDrain]
- }
-
- [kAddClient] (client) {
- client
- .on('drain', this[kOnDrain])
- .on('connect', this[kOnConnect])
- .on('disconnect', this[kOnDisconnect])
- .on('connectionError', this[kOnConnectionError])
-
- this[kClients].push(client)
-
- if (this[kNeedDrain]) {
- process.nextTick(() => {
- if (this[kNeedDrain]) {
- this[kOnDrain](client[kUrl], [this, client])
+ else {
+ let stringified;
+ try {
+ if (typeof e === "object" && e) {
+ stringified = JSON.stringify(e);
+ }
+ else {
+ stringified = String(e);
+ }
}
- })
+ catch (err) {
+ stringified = "[unable to stringify input]";
+ }
+ return `Unknown error ${stringified}`;
}
+}
+//# sourceMappingURL=error.js.map
- return this
- }
-
- [kRemoveClient] (client) {
- client.close(() => {
- const idx = this[kClients].indexOf(client)
- if (idx !== -1) {
- this[kClients].splice(idx, 1)
- }
- })
+/***/ }),
- this[kNeedDrain] = this[kClients].some(dispatcher => (
- !dispatcher[kNeedDrain] &&
- dispatcher.closed !== true &&
- dispatcher.destroyed !== true
- ))
- }
-}
+/***/ 30991:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kRemoveClient,
- kGetDispatcher
-}
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.stringToUint8Array = exports.uint8ArrayToString = exports.isWebWorker = exports.isReactNative = exports.isDeno = exports.isNodeRuntime = exports.isNodeLike = exports.isNode = exports.isBun = exports.isBrowser = exports.randomUUID = exports.objectHasProperty = exports.isObjectWithProperties = exports.isDefined = exports.computeSha256Hmac = exports.computeSha256Hash = exports.getErrorMessage = exports.isError = exports.isObject = exports.getRandomIntegerInclusive = exports.createAbortablePromise = exports.cancelablePromiseRace = exports.calculateRetryDelay = exports.delay = void 0;
+var delay_js_1 = __nccwpck_require__(54744);
+Object.defineProperty(exports, "delay", ({ enumerable: true, get: function () { return delay_js_1.delay; } }));
+Object.defineProperty(exports, "calculateRetryDelay", ({ enumerable: true, get: function () { return delay_js_1.calculateRetryDelay; } }));
+var aborterUtils_js_1 = __nccwpck_require__(86805);
+Object.defineProperty(exports, "cancelablePromiseRace", ({ enumerable: true, get: function () { return aborterUtils_js_1.cancelablePromiseRace; } }));
+var createAbortablePromise_js_1 = __nccwpck_require__(33716);
+Object.defineProperty(exports, "createAbortablePromise", ({ enumerable: true, get: function () { return createAbortablePromise_js_1.createAbortablePromise; } }));
+var random_js_1 = __nccwpck_require__(50832);
+Object.defineProperty(exports, "getRandomIntegerInclusive", ({ enumerable: true, get: function () { return random_js_1.getRandomIntegerInclusive; } }));
+var object_js_1 = __nccwpck_require__(15360);
+Object.defineProperty(exports, "isObject", ({ enumerable: true, get: function () { return object_js_1.isObject; } }));
+var error_js_1 = __nccwpck_require__(69213);
+Object.defineProperty(exports, "isError", ({ enumerable: true, get: function () { return error_js_1.isError; } }));
+Object.defineProperty(exports, "getErrorMessage", ({ enumerable: true, get: function () { return error_js_1.getErrorMessage; } }));
+var sha256_js_1 = __nccwpck_require__(83712);
+Object.defineProperty(exports, "computeSha256Hash", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hash; } }));
+Object.defineProperty(exports, "computeSha256Hmac", ({ enumerable: true, get: function () { return sha256_js_1.computeSha256Hmac; } }));
+var typeGuards_js_1 = __nccwpck_require__(98489);
+Object.defineProperty(exports, "isDefined", ({ enumerable: true, get: function () { return typeGuards_js_1.isDefined; } }));
+Object.defineProperty(exports, "isObjectWithProperties", ({ enumerable: true, get: function () { return typeGuards_js_1.isObjectWithProperties; } }));
+Object.defineProperty(exports, "objectHasProperty", ({ enumerable: true, get: function () { return typeGuards_js_1.objectHasProperty; } }));
+var uuidUtils_js_1 = __nccwpck_require__(50751);
+Object.defineProperty(exports, "randomUUID", ({ enumerable: true, get: function () { return uuidUtils_js_1.randomUUID; } }));
+var checkEnvironment_js_1 = __nccwpck_require__(2910);
+Object.defineProperty(exports, "isBrowser", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBrowser; } }));
+Object.defineProperty(exports, "isBun", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isBun; } }));
+Object.defineProperty(exports, "isNode", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNode; } }));
+Object.defineProperty(exports, "isNodeLike", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNodeLike; } }));
+Object.defineProperty(exports, "isNodeRuntime", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isNodeRuntime; } }));
+Object.defineProperty(exports, "isDeno", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isDeno; } }));
+Object.defineProperty(exports, "isReactNative", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isReactNative; } }));
+Object.defineProperty(exports, "isWebWorker", ({ enumerable: true, get: function () { return checkEnvironment_js_1.isWebWorker; } }));
+var bytesEncoding_js_1 = __nccwpck_require__(84073);
+Object.defineProperty(exports, "uint8ArrayToString", ({ enumerable: true, get: function () { return bytesEncoding_js_1.uint8ArrayToString; } }));
+Object.defineProperty(exports, "stringToUint8Array", ({ enumerable: true, get: function () { return bytesEncoding_js_1.stringToUint8Array; } }));
+//# sourceMappingURL=index.js.map
/***/ }),
-/***/ 29218:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(68031)
-const kPool = Symbol('pool')
-
-class PoolStats {
- constructor (pool) {
- this[kPool] = pool
- }
+/***/ 15360:
+/***/ ((__unused_webpack_module, exports) => {
- get connected () {
- return this[kPool][kConnected]
- }
- get free () {
- return this[kPool][kFree]
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isObject = isObject;
+/**
+ * Helper to determine when an input is a generic JS object.
+ * @returns true when input is an object type that is not null, Array, RegExp, or Date.
+ */
+function isObject(input) {
+ return (typeof input === "object" &&
+ input !== null &&
+ !Array.isArray(input) &&
+ !(input instanceof RegExp) &&
+ !(input instanceof Date));
+}
+//# sourceMappingURL=object.js.map
- get pending () {
- return this[kPool][kPending]
- }
+/***/ }),
- get queued () {
- return this[kPool][kQueued]
- }
+/***/ 50832:
+/***/ ((__unused_webpack_module, exports) => {
- get running () {
- return this[kPool][kRunning]
- }
- get size () {
- return this[kPool][kSize]
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.getRandomIntegerInclusive = getRandomIntegerInclusive;
+/**
+ * Returns a random integer value between a lower and upper bound,
+ * inclusive of both bounds.
+ * Note that this uses Math.random and isn't secure. If you need to use
+ * this for any kind of security purpose, find a better source of random.
+ * @param min - The smallest integer value allowed.
+ * @param max - The largest integer value allowed.
+ */
+function getRandomIntegerInclusive(min, max) {
+ // Make sure inputs are integers.
+ min = Math.ceil(min);
+ max = Math.floor(max);
+ // Pick a random offset from zero to the size of the range.
+ // Since Math.random() can never return 1, we have to make the range one larger
+ // in order to be inclusive of the maximum value after we take the floor.
+ const offset = Math.floor(Math.random() * (max - min + 1));
+ return offset + min;
}
-
-module.exports = PoolStats
-
+//# sourceMappingURL=random.js.map
/***/ }),
-/***/ 44288:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const {
- PoolBase,
- kClients,
- kNeedDrain,
- kAddClient,
- kGetDispatcher
-} = __nccwpck_require__(18804)
-const Client = __nccwpck_require__(45513)
-const {
- InvalidArgumentError
-} = __nccwpck_require__(53959)
-const util = __nccwpck_require__(89500)
-const { kUrl, kInterceptors } = __nccwpck_require__(68031)
-const buildConnector = __nccwpck_require__(91332)
+/***/ 83712:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-const kOptions = Symbol('options')
-const kConnections = Symbol('connections')
-const kFactory = Symbol('factory')
-function defaultFactory (origin, opts) {
- return new Client(origin, opts)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.computeSha256Hmac = computeSha256Hmac;
+exports.computeSha256Hash = computeSha256Hash;
+const crypto_1 = __nccwpck_require__(76982);
+/**
+ * Generates a SHA-256 HMAC signature.
+ * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash.
+ * @param stringToSign - The data to be signed.
+ * @param encoding - The textual encoding to use for the returned HMAC digest.
+ */
+async function computeSha256Hmac(key, stringToSign, encoding) {
+ const decodedKey = Buffer.from(key, "base64");
+ return (0, crypto_1.createHmac)("sha256", decodedKey).update(stringToSign).digest(encoding);
+}
+/**
+ * Generates a SHA-256 hash.
+ * @param content - The data to be included in the hash.
+ * @param encoding - The textual encoding to use for the returned hash.
+ */
+async function computeSha256Hash(content, encoding) {
+ return (0, crypto_1.createHash)("sha256").update(content).digest(encoding);
}
+//# sourceMappingURL=sha256.js.map
-class Pool extends PoolBase {
- constructor (origin, {
- connections,
- factory = defaultFactory,
- connect,
- connectTimeout,
- tls,
- maxCachedSessions,
- socketPath,
- autoSelectFamily,
- autoSelectFamilyAttemptTimeout,
- allowH2,
- ...options
- } = {}) {
- super()
+/***/ }),
- if (connections != null && (!Number.isFinite(connections) || connections < 0)) {
- throw new InvalidArgumentError('invalid connections')
- }
+/***/ 98489:
+/***/ ((__unused_webpack_module, exports) => {
- if (typeof factory !== 'function') {
- throw new InvalidArgumentError('factory must be a function.')
- }
- if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') {
- throw new InvalidArgumentError('connect must be a function or an object')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.isDefined = isDefined;
+exports.isObjectWithProperties = isObjectWithProperties;
+exports.objectHasProperty = objectHasProperty;
+/**
+ * Helper TypeGuard that checks if something is defined or not.
+ * @param thing - Anything
+ */
+function isDefined(thing) {
+ return typeof thing !== "undefined" && thing !== null;
+}
+/**
+ * Helper TypeGuard that checks if the input is an object with the specified properties.
+ * @param thing - Anything.
+ * @param properties - The name of the properties that should appear in the object.
+ */
+function isObjectWithProperties(thing, properties) {
+ if (!isDefined(thing) || typeof thing !== "object") {
+ return false;
}
-
- if (typeof connect !== 'function') {
- connect = buildConnector({
- ...tls,
- maxCachedSessions,
- allowH2,
- socketPath,
- timeout: connectTimeout,
- ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined),
- ...connect
- })
+ for (const property of properties) {
+ if (!objectHasProperty(thing, property)) {
+ return false;
+ }
}
+ return true;
+}
+/**
+ * Helper TypeGuard that checks if the input is an object with the specified property.
+ * @param thing - Any object.
+ * @param property - The name of the property that should appear in the object.
+ */
+function objectHasProperty(thing, property) {
+ return (isDefined(thing) && typeof thing === "object" && property in thing);
+}
+//# sourceMappingURL=typeGuards.js.map
- this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool)
- ? options.interceptors.Pool
- : []
- this[kConnections] = connections || null
- this[kUrl] = util.parseOrigin(origin)
- this[kOptions] = { ...util.deepClone(options), connect, allowH2 }
- this[kOptions].interceptors = options.interceptors
- ? { ...options.interceptors }
- : undefined
- this[kFactory] = factory
- }
-
- [kGetDispatcher] () {
- let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain])
+/***/ }),
- if (dispatcher) {
- return dispatcher
- }
+/***/ 50751:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (!this[kConnections] || this[kClients].length < this[kConnections]) {
- dispatcher = this[kFactory](this[kUrl], this[kOptions])
- this[kAddClient](dispatcher)
- }
- return dispatcher
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+var _a;
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.randomUUID = randomUUID;
+const crypto_1 = __nccwpck_require__(76982);
+// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+.
+const uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function"
+ ? globalThis.crypto.randomUUID.bind(globalThis.crypto)
+ : crypto_1.randomUUID;
+/**
+ * Generated Universally Unique Identifier
+ *
+ * @returns RFC4122 v4 UUID.
+ */
+function randomUUID() {
+ return uuidFunction();
}
+//# sourceMappingURL=uuidUtils.js.map
-module.exports = Pool
+/***/ }),
+/***/ 21328:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-/***/ }),
-/***/ 79276:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.parseXML = exports.stringifyXML = void 0;
+var xml_js_1 = __nccwpck_require__(86537);
+Object.defineProperty(exports, "stringifyXML", ({ enumerable: true, get: function () { return xml_js_1.stringifyXML; } }));
+Object.defineProperty(exports, "parseXML", ({ enumerable: true, get: function () { return xml_js_1.parseXML; } }));
+var xml_common_js_1 = __nccwpck_require__(51882);
+Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return xml_common_js_1.XML_ATTRKEY; } }));
+Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return xml_common_js_1.XML_CHARKEY; } }));
+//# sourceMappingURL=index.js.map
+/***/ }),
+/***/ 51882:
+/***/ ((__unused_webpack_module, exports) => {
-const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(68031)
-const { URL } = __nccwpck_require__(87016)
-const Agent = __nccwpck_require__(92121)
-const Pool = __nccwpck_require__(44288)
-const DispatcherBase = __nccwpck_require__(52421)
-const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(53959)
-const buildConnector = __nccwpck_require__(91332)
-const kAgent = Symbol('proxy agent')
-const kClient = Symbol('proxy client')
-const kProxyHeaders = Symbol('proxy headers')
-const kRequestTls = Symbol('request tls settings')
-const kProxyTls = Symbol('proxy tls settings')
-const kConnectEndpoint = Symbol('connect endpoint function')
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0;
+/**
+ * Default key used to access the XML attributes.
+ */
+exports.XML_ATTRKEY = "$";
+/**
+ * Default key used to access the XML value content.
+ */
+exports.XML_CHARKEY = "_";
+//# sourceMappingURL=xml.common.js.map
-function defaultProtocolPort (protocol) {
- return protocol === 'https:' ? 443 : 80
-}
+/***/ }),
-function buildProxyOptions (opts) {
- if (typeof opts === 'string') {
- opts = { uri: opts }
- }
+/***/ 86537:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (!opts || !opts.uri) {
- throw new InvalidArgumentError('Proxy opts.uri is mandatory')
- }
- return {
- uri: opts.uri,
- protocol: opts.protocol || 'https'
- }
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.stringifyXML = stringifyXML;
+exports.parseXML = parseXML;
+const fast_xml_parser_1 = __nccwpck_require__(1537);
+const xml_common_js_1 = __nccwpck_require__(51882);
+function getCommonOptions(options) {
+ var _a;
+ return {
+ attributesGroupName: xml_common_js_1.XML_ATTRKEY,
+ textNodeName: (_a = options.xmlCharKey) !== null && _a !== void 0 ? _a : xml_common_js_1.XML_CHARKEY,
+ ignoreAttributes: false,
+ suppressBooleanAttributes: false,
+ };
}
-
-function defaultFactory (origin, opts) {
- return new Pool(origin, opts)
+function getSerializerOptions(options = {}) {
+ var _a, _b;
+ return Object.assign(Object.assign({}, getCommonOptions(options)), { attributeNamePrefix: "@_", format: true, suppressEmptyNode: true, indentBy: "", rootNodeName: (_a = options.rootName) !== null && _a !== void 0 ? _a : "root", cdataPropName: (_b = options.cdataPropName) !== null && _b !== void 0 ? _b : "__cdata" });
}
-
-class ProxyAgent extends DispatcherBase {
- constructor (opts) {
- super(opts)
- this[kProxy] = buildProxyOptions(opts)
- this[kAgent] = new Agent(opts)
- this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent)
- ? opts.interceptors.ProxyAgent
- : []
-
- if (typeof opts === 'string') {
- opts = { uri: opts }
+function getParserOptions(options = {}) {
+ return Object.assign(Object.assign({}, getCommonOptions(options)), { parseAttributeValue: false, parseTagValue: false, attributeNamePrefix: "", stopNodes: options.stopNodes, processEntities: true });
+}
+/**
+ * Converts given JSON object to XML string
+ * @param obj - JSON object to be converted into XML string
+ * @param opts - Options that govern the XML building of given JSON object
+ * `rootName` indicates the name of the root element in the resulting XML
+ */
+function stringifyXML(obj, opts = {}) {
+ const parserOptions = getSerializerOptions(opts);
+ const j2x = new fast_xml_parser_1.XMLBuilder(parserOptions);
+ const node = { [parserOptions.rootNodeName]: obj };
+ const xmlData = j2x.build(node);
+ return `${xmlData}`.replace(/\n/g, "");
+}
+/**
+ * Converts given XML string into JSON
+ * @param str - String containing the XML content to be parsed into JSON
+ * @param opts - Options that govern the parsing of given xml string
+ * `includeRoot` indicates whether the root element is to be included or not in the output
+ */
+async function parseXML(str, opts = {}) {
+ if (!str) {
+ throw new Error("Document is empty");
}
-
- if (!opts || !opts.uri) {
- throw new InvalidArgumentError('Proxy opts.uri is mandatory')
+ const validation = fast_xml_parser_1.XMLValidator.validate(str);
+ if (validation !== true) {
+ throw validation;
}
-
- const { clientFactory = defaultFactory } = opts
-
- if (typeof clientFactory !== 'function') {
- throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.')
+ const parser = new fast_xml_parser_1.XMLParser(getParserOptions(opts));
+ const parsedXml = parser.parse(str);
+ // Remove the node.
+ // This is a change in behavior on fxp v4. Issue #424
+ if (parsedXml["?xml"]) {
+ delete parsedXml["?xml"];
+ }
+ if (!opts.includeRoot) {
+ for (const key of Object.keys(parsedXml)) {
+ const value = parsedXml[key];
+ return typeof value === "object" ? Object.assign({}, value) : value;
+ }
}
+ return parsedXml;
+}
+//# sourceMappingURL=xml.js.map
- this[kRequestTls] = opts.requestTls
- this[kProxyTls] = opts.proxyTls
- this[kProxyHeaders] = opts.headers || {}
+/***/ }),
- const resolvedUrl = new URL(opts.uri)
- const { origin, port, host, username, password } = resolvedUrl
+/***/ 37024:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (opts.auth && opts.token) {
- throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token')
- } else if (opts.auth) {
- /* @deprecated in favour of opts.token */
- this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`
- } else if (opts.token) {
- this[kProxyHeaders]['proxy-authorization'] = opts.token
- } else if (username && password) {
- this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}`
- }
- const connect = buildConnector({ ...opts.proxyTls })
- this[kConnectEndpoint] = buildConnector({ ...opts.requestTls })
- this[kClient] = clientFactory(resolvedUrl, { connect })
- this[kAgent] = new Agent({
- ...opts,
- connect: async (opts, callback) => {
- let requestedHost = opts.host
- if (!opts.port) {
- requestedHost += `:${defaultProtocolPort(opts.protocol)}`
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+const log_js_1 = __nccwpck_require__(30881);
+const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined;
+let enabledString;
+let enabledNamespaces = [];
+let skippedNamespaces = [];
+const debuggers = [];
+if (debugEnvVariable) {
+ enable(debugEnvVariable);
+}
+const debugObj = Object.assign((namespace) => {
+ return createDebugger(namespace);
+}, {
+ enable,
+ enabled,
+ disable,
+ log: log_js_1.log,
+});
+function enable(namespaces) {
+ enabledString = namespaces;
+ enabledNamespaces = [];
+ skippedNamespaces = [];
+ const wildcard = /\*/g;
+ const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?"));
+ for (const ns of namespaceList) {
+ if (ns.startsWith("-")) {
+ skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`));
}
- try {
- const { socket, statusCode } = await this[kClient].connect({
- origin,
- port,
- path: requestedHost,
- signal: opts.signal,
- headers: {
- ...this[kProxyHeaders],
- host
- }
- })
- if (statusCode !== 200) {
- socket.on('error', () => {}).destroy()
- callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`))
- }
- if (opts.protocol !== 'https:') {
- callback(null, socket)
- return
- }
- let servername
- if (this[kRequestTls]) {
- servername = this[kRequestTls].servername
- } else {
- servername = opts.servername
- }
- this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback)
- } catch (err) {
- callback(err)
+ else {
+ enabledNamespaces.push(new RegExp(`^${ns}$`));
+ }
+ }
+ for (const instance of debuggers) {
+ instance.enabled = enabled(instance.namespace);
+ }
+}
+function enabled(namespace) {
+ if (namespace.endsWith("*")) {
+ return true;
+ }
+ for (const skipped of skippedNamespaces) {
+ if (skipped.test(namespace)) {
+ return false;
+ }
+ }
+ for (const enabledNamespace of enabledNamespaces) {
+ if (enabledNamespace.test(namespace)) {
+ return true;
+ }
+ }
+ return false;
+}
+function disable() {
+ const result = enabledString || "";
+ enable("");
+ return result;
+}
+function createDebugger(namespace) {
+ const newDebugger = Object.assign(debug, {
+ enabled: enabled(namespace),
+ destroy,
+ log: debugObj.log,
+ namespace,
+ extend,
+ });
+ function debug(...args) {
+ if (!newDebugger.enabled) {
+ return;
}
- }
- })
- }
-
- dispatch (opts, handler) {
- const { host } = new URL(opts.origin)
- const headers = buildHeaders(opts.headers)
- throwIfProxyAuthIsSent(headers)
- return this[kAgent].dispatch(
- {
- ...opts,
- headers: {
- ...headers,
- host
+ if (args.length > 0) {
+ args[0] = `${namespace} ${args[0]}`;
}
- },
- handler
- )
- }
-
- async [kClose] () {
- await this[kAgent].close()
- await this[kClient].close()
- }
-
- async [kDestroy] () {
- await this[kAgent].destroy()
- await this[kClient].destroy()
- }
+ newDebugger.log(...args);
+ }
+ debuggers.push(newDebugger);
+ return newDebugger;
}
-
-/**
- * @param {string[] | Record} headers
- * @returns {Record}
- */
-function buildHeaders (headers) {
- // When using undici.fetch, the headers list is stored
- // as an array.
- if (Array.isArray(headers)) {
- /** @type {Record} */
- const headersPair = {}
-
- for (let i = 0; i < headers.length; i += 2) {
- headersPair[headers[i]] = headers[i + 1]
+function destroy() {
+ const index = debuggers.indexOf(this);
+ if (index >= 0) {
+ debuggers.splice(index, 1);
+ return true;
}
-
- return headersPair
- }
-
- return headers
+ return false;
}
-
-/**
- * @param {Record} headers
- *
- * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers
- * Nevertheless, it was changed and to avoid a security vulnerability by end users
- * this check was created.
- * It should be removed in the next major version for performance reasons
- */
-function throwIfProxyAuthIsSent (headers) {
- const existProxyAuth = headers && Object.keys(headers)
- .find((key) => key.toLowerCase() === 'proxy-authorization')
- if (existProxyAuth) {
- throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor')
- }
+function extend(namespace) {
+ const newDebugger = createDebugger(`${this.namespace}:${namespace}`);
+ newDebugger.log = this.log;
+ return newDebugger;
}
-
-module.exports = ProxyAgent
-
+exports["default"] = debugObj;
+//# sourceMappingURL=debug.js.map
/***/ }),
-/***/ 82576:
-/***/ ((module) => {
-
-
-
-let fastNow = Date.now()
-let fastNowTimeout
-
-const fastTimers = []
-
-function onTimeout () {
- fastNow = Date.now()
+/***/ 50143:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- let len = fastTimers.length
- let idx = 0
- while (idx < len) {
- const timer = fastTimers[idx]
- if (timer.state === 0) {
- timer.state = fastNow + timer.delay
- } else if (timer.state > 0 && fastNow >= timer.state) {
- timer.state = -1
- timer.callback(timer.opaque)
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.AzureLogger = void 0;
+exports.setLogLevel = setLogLevel;
+exports.getLogLevel = getLogLevel;
+exports.createClientLogger = createClientLogger;
+const tslib_1 = __nccwpck_require__(94176);
+const debug_js_1 = tslib_1.__importDefault(__nccwpck_require__(37024));
+const registeredLoggers = new Set();
+const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env.AZURE_LOG_LEVEL) || undefined;
+let azureLogLevel;
+/**
+ * The AzureLogger provides a mechanism for overriding where logs are output to.
+ * By default, logs are sent to stderr.
+ * Override the `log` method to redirect logs to another location.
+ */
+exports.AzureLogger = (0, debug_js_1.default)("azure");
+exports.AzureLogger.log = (...args) => {
+ debug_js_1.default.log(...args);
+};
+const AZURE_LOG_LEVELS = ["verbose", "info", "warning", "error"];
+if (logLevelFromEnv) {
+ // avoid calling setLogLevel because we don't want a mis-set environment variable to crash
+ if (isAzureLogLevel(logLevelFromEnv)) {
+ setLogLevel(logLevelFromEnv);
}
-
- if (timer.state === -1) {
- timer.state = -2
- if (idx !== len - 1) {
- fastTimers[idx] = fastTimers.pop()
- } else {
- fastTimers.pop()
- }
- len -= 1
- } else {
- idx += 1
+ else {
+ console.error(`AZURE_LOG_LEVEL set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${AZURE_LOG_LEVELS.join(", ")}.`);
}
- }
-
- if (fastTimers.length > 0) {
- refreshTimeout()
- }
}
-
-function refreshTimeout () {
- if (fastNowTimeout && fastNowTimeout.refresh) {
- fastNowTimeout.refresh()
- } else {
- clearTimeout(fastNowTimeout)
- fastNowTimeout = setTimeout(onTimeout, 1e3)
- if (fastNowTimeout.unref) {
- fastNowTimeout.unref()
+/**
+ * Immediately enables logging at the specified log level. If no level is specified, logging is disabled.
+ * @param level - The log level to enable for logging.
+ * Options from most verbose to least verbose are:
+ * - verbose
+ * - info
+ * - warning
+ * - error
+ */
+function setLogLevel(level) {
+ if (level && !isAzureLogLevel(level)) {
+ throw new Error(`Unknown log level '${level}'. Acceptable values: ${AZURE_LOG_LEVELS.join(",")}`);
}
- }
-}
-
-class Timeout {
- constructor (callback, delay, opaque) {
- this.callback = callback
- this.delay = delay
- this.opaque = opaque
-
- // -2 not in timer list
- // -1 in timer list but inactive
- // 0 in timer list waiting for time
- // > 0 in timer list waiting for time to expire
- this.state = -2
-
- this.refresh()
- }
-
- refresh () {
- if (this.state === -2) {
- fastTimers.push(this)
- if (!fastNowTimeout || fastTimers.length === 1) {
- refreshTimeout()
- }
+ azureLogLevel = level;
+ const enabledNamespaces = [];
+ for (const logger of registeredLoggers) {
+ if (shouldEnable(logger)) {
+ enabledNamespaces.push(logger.namespace);
+ }
}
-
- this.state = 0
- }
-
- clear () {
- this.state = -1
- }
+ debug_js_1.default.enable(enabledNamespaces.join(","));
}
-
-module.exports = {
- setTimeout (callback, delay, opaque) {
- return delay < 1e3
- ? setTimeout(callback, delay, opaque)
- : new Timeout(callback, delay, opaque)
- },
- clearTimeout (timeout) {
- if (timeout instanceof Timeout) {
- timeout.clear()
- } else {
- clearTimeout(timeout)
+/**
+ * Retrieves the currently specified log level.
+ */
+function getLogLevel() {
+ return azureLogLevel;
+}
+const levelMap = {
+ verbose: 400,
+ info: 300,
+ warning: 200,
+ error: 100,
+};
+/**
+ * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`.
+ * @param namespace - The name of the SDK package.
+ * @hidden
+ */
+function createClientLogger(namespace) {
+ const clientRootLogger = exports.AzureLogger.extend(namespace);
+ patchLogMethod(exports.AzureLogger, clientRootLogger);
+ return {
+ error: createLogger(clientRootLogger, "error"),
+ warning: createLogger(clientRootLogger, "warning"),
+ info: createLogger(clientRootLogger, "info"),
+ verbose: createLogger(clientRootLogger, "verbose"),
+ };
+}
+function patchLogMethod(parent, child) {
+ child.log = (...args) => {
+ parent.log(...args);
+ };
+}
+function createLogger(parent, level) {
+ const logger = Object.assign(parent.extend(level), {
+ level,
+ });
+ patchLogMethod(parent, logger);
+ if (shouldEnable(logger)) {
+ const enabledNamespaces = debug_js_1.default.disable();
+ debug_js_1.default.enable(enabledNamespaces + "," + logger.namespace);
}
- }
+ registeredLoggers.add(logger);
+ return logger;
}
-
+function shouldEnable(logger) {
+ return Boolean(azureLogLevel && levelMap[logger.level] <= levelMap[azureLogLevel]);
+}
+function isAzureLogLevel(logLevel) {
+ return AZURE_LOG_LEVELS.includes(logLevel);
+}
+//# sourceMappingURL=index.js.map
/***/ }),
-/***/ 96114:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const diagnosticsChannel = __nccwpck_require__(31637)
-const { uid, states } = __nccwpck_require__(90077)
-const {
- kReadyState,
- kSentClose,
- kByteParser,
- kReceivedClose
-} = __nccwpck_require__(97945)
-const { fireEvent, failWebsocketConnection } = __nccwpck_require__(95506)
-const { CloseEvent } = __nccwpck_require__(47115)
-const { makeRequest } = __nccwpck_require__(2630)
-const { fetching } = __nccwpck_require__(11503)
-const { Headers } = __nccwpck_require__(12801)
-const { getGlobalDispatcher } = __nccwpck_require__(61481)
-const { kHeadersList } = __nccwpck_require__(68031)
-
-const channels = {}
-channels.open = diagnosticsChannel.channel('undici:websocket:open')
-channels.close = diagnosticsChannel.channel('undici:websocket:close')
-channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')
+/***/ 30881:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-/** @type {import('crypto')} */
-let crypto
-try {
- crypto = __nccwpck_require__(76982)
-} catch {
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT license.
+Object.defineProperty(exports, "__esModule", ({ value: true }));
+exports.log = log;
+const tslib_1 = __nccwpck_require__(94176);
+const node_os_1 = __nccwpck_require__(48161);
+const node_util_1 = tslib_1.__importDefault(__nccwpck_require__(57975));
+const process = tslib_1.__importStar(__nccwpck_require__(1708));
+function log(message, ...args) {
+ process.stderr.write(`${node_util_1.default.format(message, ...args)}${node_os_1.EOL}`);
}
+//# sourceMappingURL=log.js.map
-/**
- * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
- * @param {URL} url
- * @param {string|string[]} protocols
- * @param {import('./websocket').WebSocket} ws
- * @param {(response: any) => void} onEstablish
- * @param {Partial} options
- */
-function establishWebSocketConnection (url, protocols, ws, onEstablish, options) {
- // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s
- // scheme is "ws", and to "https" otherwise.
- const requestURL = url
+/***/ }),
- requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
+/***/ 8946:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- // 2. Let request be a new request, whose URL is requestURL, client is client,
- // service-workers mode is "none", referrer is "no-referrer", mode is
- // "websocket", credentials mode is "include", cache mode is "no-store" ,
- // and redirect mode is "error".
- const request = makeRequest({
- urlList: [requestURL],
- serviceWorkers: 'none',
- referrer: 'no-referrer',
- mode: 'websocket',
- credentials: 'include',
- cache: 'no-store',
- redirect: 'error'
- })
- // Note: undici extension, allow setting custom headers.
- if (options.headers) {
- const headersList = new Headers(options.headers)[kHeadersList]
- request.headersList = headersList
- }
+const WritableStream = (__nccwpck_require__(57075).Writable)
+const inherits = (__nccwpck_require__(57975).inherits)
- // 3. Append (`Upgrade`, `websocket`) to request’s header list.
- // 4. Append (`Connection`, `Upgrade`) to request’s header list.
- // Note: both of these are handled by undici currently.
- // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
+const StreamSearch = __nccwpck_require__(86484)
- // 5. Let keyValue be a nonce consisting of a randomly selected
- // 16-byte value that has been forgiving-base64-encoded and
- // isomorphic encoded.
- const keyValue = crypto.randomBytes(16).toString('base64')
+const PartStream = __nccwpck_require__(87952)
+const HeaderParser = __nccwpck_require__(87003)
- // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
- // header list.
- request.headersList.append('sec-websocket-key', keyValue)
+const DASH = 45
+const B_ONEDASH = Buffer.from('-')
+const B_CRLF = Buffer.from('\r\n')
+const EMPTY_FN = function () {}
- // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
- // header list.
- request.headersList.append('sec-websocket-version', '13')
+function Dicer (cfg) {
+ if (!(this instanceof Dicer)) { return new Dicer(cfg) }
+ WritableStream.call(this, cfg)
- // 8. For each protocol in protocols, combine
- // (`Sec-WebSocket-Protocol`, protocol) in request’s header
- // list.
- for (const protocol of protocols) {
- request.headersList.append('sec-websocket-protocol', protocol)
- }
+ if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') }
- // 9. Let permessageDeflate be a user-agent defined
- // "permessage-deflate" extension header value.
- // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
- // TODO: enable once permessage-deflate is supported
- const permessageDeflate = '' // 'permessage-deflate; 15'
+ if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined }
- // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
- // request’s header list.
- // request.headersList.append('sec-websocket-extensions', permessageDeflate)
+ this._headerFirst = cfg.headerFirst
- // 11. Fetch request with useParallelQueue set to true, and
- // processResponse given response being these steps:
- const controller = fetching({
- request,
- useParallelQueue: true,
- dispatcher: options.dispatcher ?? getGlobalDispatcher(),
- processResponse (response) {
- // 1. If response is a network error or its status is not 101,
- // fail the WebSocket connection.
- if (response.type === 'error' || response.status !== 101) {
- failWebsocketConnection(ws, 'Received network error or non-101 status code.')
- return
- }
+ this._dashes = 0
+ this._parts = 0
+ this._finished = false
+ this._realFinish = false
+ this._isPreamble = true
+ this._justMatched = false
+ this._firstWrite = true
+ this._inHeader = true
+ this._part = undefined
+ this._cb = undefined
+ this._ignoreData = false
+ this._partOpts = { highWaterMark: cfg.partHwm }
+ this._pause = false
- // 2. If protocols is not the empty list and extracting header
- // list values given `Sec-WebSocket-Protocol` and response’s
- // header list results in null, failure, or the empty byte
- // sequence, then fail the WebSocket connection.
- if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
- failWebsocketConnection(ws, 'Server did not respond with sent protocols.')
- return
- }
+ const self = this
+ this._hparser = new HeaderParser(cfg)
+ this._hparser.on('header', function (header) {
+ self._inHeader = false
+ self._part.emit('header', header)
+ })
+}
+inherits(Dicer, WritableStream)
- // 3. Follow the requirements stated step 2 to step 6, inclusive,
- // of the last set of steps in section 4.1 of The WebSocket
- // Protocol to validate response. This either results in fail
- // the WebSocket connection or the WebSocket connection is
- // established.
+Dicer.prototype.emit = function (ev) {
+ if (ev === 'finish' && !this._realFinish) {
+ if (!this._finished) {
+ const self = this
+ process.nextTick(function () {
+ self.emit('error', new Error('Unexpected end of multipart data'))
+ if (self._part && !self._ignoreData) {
+ const type = (self._isPreamble ? 'Preamble' : 'Part')
+ self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'))
+ self._part.push(null)
+ process.nextTick(function () {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ })
+ return
+ }
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ })
+ }
+ } else { WritableStream.prototype.emit.apply(this, arguments) }
+}
- // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
- // header field contains a value that is not an ASCII case-
- // insensitive match for the value "websocket", the client MUST
- // _Fail the WebSocket Connection_.
- if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
- failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".')
- return
- }
+Dicer.prototype._write = function (data, encoding, cb) {
+ // ignore unexpected data (e.g. extra trailer data after finished)
+ if (!this._hparser && !this._bparser) { return cb() }
- // 3. If the response lacks a |Connection| header field or the
- // |Connection| header field doesn't contain a token that is an
- // ASCII case-insensitive match for the value "Upgrade", the client
- // MUST _Fail the WebSocket Connection_.
- if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
- failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".')
- return
- }
+ if (this._headerFirst && this._isPreamble) {
+ if (!this._part) {
+ this._part = new PartStream(this._partOpts)
+ if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() }
+ }
+ const r = this._hparser.push(data)
+ if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() }
+ }
- // 4. If the response lacks a |Sec-WebSocket-Accept| header field or
- // the |Sec-WebSocket-Accept| contains a value other than the
- // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
- // Key| (as a string, not base64-decoded) with the string "258EAFA5-
- // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
- // trailing whitespace, the client MUST _Fail the WebSocket
- // Connection_.
- const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
- const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
- if (secWSAccept !== digest) {
- failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
- return
- }
+ // allows for "easier" testing
+ if (this._firstWrite) {
+ this._bparser.push(B_CRLF)
+ this._firstWrite = false
+ }
- // 5. If the response includes a |Sec-WebSocket-Extensions| header
- // field and this header field indicates the use of an extension
- // that was not present in the client's handshake (the server has
- // indicated an extension not requested by the client), the client
- // MUST _Fail the WebSocket Connection_. (The parsing of this
- // header field to determine which extensions are requested is
- // discussed in Section 9.1.)
- const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
+ this._bparser.push(data)
- if (secExtension !== null && secExtension !== permessageDeflate) {
- failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')
- return
- }
+ if (this._pause) { this._cb = cb } else { cb() }
+}
- // 6. If the response includes a |Sec-WebSocket-Protocol| header field
- // and this header field indicates the use of a subprotocol that was
- // not present in the client's handshake (the server has indicated a
- // subprotocol not requested by the client), the client MUST _Fail
- // the WebSocket Connection_.
- const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
+Dicer.prototype.reset = function () {
+ this._part = undefined
+ this._bparser = undefined
+ this._hparser = undefined
+}
- if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {
- failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
- return
- }
+Dicer.prototype.setBoundary = function (boundary) {
+ const self = this
+ this._bparser = new StreamSearch('\r\n--' + boundary)
+ this._bparser.on('info', function (isMatch, data, start, end) {
+ self._oninfo(isMatch, data, start, end)
+ })
+}
- response.socket.on('data', onSocketData)
- response.socket.on('close', onSocketClose)
- response.socket.on('error', onSocketError)
+Dicer.prototype._ignore = function () {
+ if (this._part && !this._ignoreData) {
+ this._ignoreData = true
+ this._part.on('error', EMPTY_FN)
+ // we must perform some kind of read on the stream even though we are
+ // ignoring the data, otherwise node's Readable stream will not emit 'end'
+ // after pushing null to the stream
+ this._part.resume()
+ }
+}
- if (channels.open.hasSubscribers) {
- channels.open.publish({
- address: response.socket.address(),
- protocol: secProtocol,
- extensions: secExtension
+Dicer.prototype._oninfo = function (isMatch, data, start, end) {
+ let buf; const self = this; let i = 0; let r; let shouldWriteMore = true
+
+ if (!this._part && this._justMatched && data) {
+ while (this._dashes < 2 && (start + i) < end) {
+ if (data[start + i] === DASH) {
+ ++i
+ ++this._dashes
+ } else {
+ if (this._dashes) { buf = B_ONEDASH }
+ this._dashes = 0
+ break
+ }
+ }
+ if (this._dashes === 2) {
+ if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) }
+ this.reset()
+ this._finished = true
+ // no more parts will be added
+ if (self._parts === 0) {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ }
+ }
+ if (this._dashes) { return }
+ }
+ if (this._justMatched) { this._justMatched = false }
+ if (!this._part) {
+ this._part = new PartStream(this._partOpts)
+ this._part._read = function (n) {
+ self._unpause()
+ }
+ if (this._isPreamble && this.listenerCount('preamble') !== 0) {
+ this.emit('preamble', this._part)
+ } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) {
+ this.emit('part', this._part)
+ } else {
+ this._ignore()
+ }
+ if (!this._isPreamble) { this._inHeader = true }
+ }
+ if (data && start < end && !this._ignoreData) {
+ if (this._isPreamble || !this._inHeader) {
+ if (buf) { shouldWriteMore = this._part.push(buf) }
+ shouldWriteMore = this._part.push(data.slice(start, end))
+ if (!shouldWriteMore) { this._pause = true }
+ } else if (!this._isPreamble && this._inHeader) {
+ if (buf) { this._hparser.push(buf) }
+ r = this._hparser.push(data.slice(start, end))
+ if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) }
+ }
+ }
+ if (isMatch) {
+ this._hparser.reset()
+ if (this._isPreamble) { this._isPreamble = false } else {
+ if (start !== end) {
+ ++this._parts
+ this._part.on('end', function () {
+ if (--self._parts === 0) {
+ if (self._finished) {
+ self._realFinish = true
+ self.emit('finish')
+ self._realFinish = false
+ } else {
+ self._unpause()
+ }
+ }
})
}
-
- onEstablish(response)
}
- })
-
- return controller
+ this._part.push(null)
+ this._part = undefined
+ this._ignoreData = false
+ this._justMatched = true
+ this._dashes = 0
+ }
}
-/**
- * @param {Buffer} chunk
- */
-function onSocketData (chunk) {
- if (!this.ws[kByteParser].write(chunk)) {
- this.pause()
+Dicer.prototype._unpause = function () {
+ if (!this._pause) { return }
+
+ this._pause = false
+ if (this._cb) {
+ const cb = this._cb
+ this._cb = undefined
+ cb()
}
}
-/**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
- */
-function onSocketClose () {
- const { ws } = this
+module.exports = Dicer
- // If the TCP connection was closed after the
- // WebSocket closing handshake was completed, the WebSocket connection
- // is said to have been closed _cleanly_.
- const wasClean = ws[kSentClose] && ws[kReceivedClose]
- let code = 1005
- let reason = ''
+/***/ }),
- const result = ws[kByteParser].closingInfo
+/***/ 87003:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (result) {
- code = result.code ?? 1005
- reason = result.reason
- } else if (!ws[kSentClose]) {
- // If _The WebSocket
- // Connection is Closed_ and no Close control frame was received by the
- // endpoint (such as could occur if the underlying transport connection
- // is lost), _The WebSocket Connection Close Code_ is considered to be
- // 1006.
- code = 1006
- }
- // 1. Change the ready state to CLOSED (3).
- ws[kReadyState] = states.CLOSED
- // 2. If the user agent was required to fail the WebSocket
- // connection, or if the WebSocket connection was closed
- // after being flagged as full, fire an event named error
- // at the WebSocket object.
- // TODO
+const EventEmitter = (__nccwpck_require__(78474).EventEmitter)
+const inherits = (__nccwpck_require__(57975).inherits)
+const getLimit = __nccwpck_require__(5245)
- // 3. Fire an event named close at the WebSocket object,
- // using CloseEvent, with the wasClean attribute
- // initialized to true if the connection closed cleanly
- // and false otherwise, the code attribute initialized to
- // the WebSocket connection close code, and the reason
- // attribute initialized to the result of applying UTF-8
- // decode without BOM to the WebSocket connection close
- // reason.
- fireEvent('close', ws, CloseEvent, {
- wasClean, code, reason
- })
+const StreamSearch = __nccwpck_require__(86484)
- if (channels.close.hasSubscribers) {
- channels.close.publish({
- websocket: ws,
- code,
- reason
- })
- }
-}
+const B_DCRLF = Buffer.from('\r\n\r\n')
+const RE_CRLF = /\r\n/g
+const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex
-function onSocketError (error) {
- const { ws } = this
+function HeaderParser (cfg) {
+ EventEmitter.call(this)
- ws[kReadyState] = states.CLOSING
+ cfg = cfg || {}
+ const self = this
+ this.nread = 0
+ this.maxed = false
+ this.npairs = 0
+ this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000)
+ this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024)
+ this.buffer = ''
+ this.header = {}
+ this.finished = false
+ this.ss = new StreamSearch(B_DCRLF)
+ this.ss.on('info', function (isMatch, data, start, end) {
+ if (data && !self.maxed) {
+ if (self.nread + end - start >= self.maxHeaderSize) {
+ end = self.maxHeaderSize - self.nread + start
+ self.nread = self.maxHeaderSize
+ self.maxed = true
+ } else { self.nread += (end - start) }
- if (channels.socketError.hasSubscribers) {
- channels.socketError.publish(error)
- }
+ self.buffer += data.toString('binary', start, end)
+ }
+ if (isMatch) { self._finish() }
+ })
+}
+inherits(HeaderParser, EventEmitter)
- this.destroy()
+HeaderParser.prototype.push = function (data) {
+ const r = this.ss.push(data)
+ if (this.finished) { return r }
}
-module.exports = {
- establishWebSocketConnection
+HeaderParser.prototype.reset = function () {
+ this.finished = false
+ this.buffer = ''
+ this.header = {}
+ this.ss.reset()
+}
+
+HeaderParser.prototype._finish = function () {
+ if (this.buffer) { this._parseHeader() }
+ this.ss.matches = this.ss.maxMatches
+ const header = this.header
+ this.header = {}
+ this.buffer = ''
+ this.finished = true
+ this.nread = this.npairs = 0
+ this.maxed = false
+ this.emit('header', header)
}
+HeaderParser.prototype._parseHeader = function () {
+ if (this.npairs === this.maxHeaderPairs) { return }
-/***/ }),
+ const lines = this.buffer.split(RE_CRLF)
+ const len = lines.length
+ let m, h
-/***/ 90077:
-/***/ ((module) => {
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ if (lines[i].length === 0) { continue }
+ if (lines[i][0] === '\t' || lines[i][0] === ' ') {
+ // folded header content
+ // RFC2822 says to just remove the CRLF and not the whitespace following
+ // it, so we follow the RFC and include the leading whitespace ...
+ if (h) {
+ this.header[h][this.header[h].length - 1] += lines[i]
+ continue
+ }
+ }
+ const posColon = lines[i].indexOf(':')
+ if (
+ posColon === -1 ||
+ posColon === 0
+ ) {
+ return
+ }
+ m = RE_HDR.exec(lines[i])
+ h = m[1].toLowerCase()
+ this.header[h] = this.header[h] || []
+ this.header[h].push((m[2] || ''))
+ if (++this.npairs === this.maxHeaderPairs) { break }
+ }
+}
+module.exports = HeaderParser
-// This is a Globally Unique Identifier unique used
-// to validate that the endpoint accepts websocket
-// connections.
-// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3
-const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
-/** @type {PropertyDescriptor} */
-const staticPropertyDescriptors = {
- enumerable: true,
- writable: false,
- configurable: false
-}
+/***/ }),
-const states = {
- CONNECTING: 0,
- OPEN: 1,
- CLOSING: 2,
- CLOSED: 3
-}
+/***/ 87952:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const opcodes = {
- CONTINUATION: 0x0,
- TEXT: 0x1,
- BINARY: 0x2,
- CLOSE: 0x8,
- PING: 0x9,
- PONG: 0xA
-}
-const maxUnsigned16Bit = 2 ** 16 - 1 // 65535
-const parserStates = {
- INFO: 0,
- PAYLOADLENGTH_16: 2,
- PAYLOADLENGTH_64: 3,
- READ_DATA: 4
+const inherits = (__nccwpck_require__(57975).inherits)
+const ReadableStream = (__nccwpck_require__(57075).Readable)
+
+function PartStream (opts) {
+ ReadableStream.call(this, opts)
}
+inherits(PartStream, ReadableStream)
-const emptyBuffer = Buffer.allocUnsafe(0)
+PartStream.prototype._read = function (n) {}
-module.exports = {
- uid,
- staticPropertyDescriptors,
- states,
- opcodes,
- maxUnsigned16Bit,
- parserStates,
- emptyBuffer
-}
+module.exports = PartStream
/***/ }),
-/***/ 47115:
+/***/ 86484:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { webidl } = __nccwpck_require__(94354)
-const { kEnumerableProperty } = __nccwpck_require__(89500)
-const { MessagePort } = __nccwpck_require__(28167)
-
/**
- * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
+ * Copyright Brian White. All rights reserved.
+ *
+ * @see https://github.com/mscdex/streamsearch
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to
+ * deal in the Software without restriction, including without limitation the
+ * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ * sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ * IN THE SOFTWARE.
+ *
+ * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
+ * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
*/
-class MessageEvent extends Event {
- #eventInit
+const EventEmitter = (__nccwpck_require__(78474).EventEmitter)
+const inherits = (__nccwpck_require__(57975).inherits)
- constructor (type, eventInitDict = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' })
+function SBMH (needle) {
+ if (typeof needle === 'string') {
+ needle = Buffer.from(needle)
+ }
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.MessageEventInit(eventInitDict)
+ if (!Buffer.isBuffer(needle)) {
+ throw new TypeError('The needle has to be a String or a Buffer.')
+ }
- super(type, eventInitDict)
+ const needleLength = needle.length
- this.#eventInit = eventInitDict
+ if (needleLength === 0) {
+ throw new Error('The needle cannot be an empty String/Buffer.')
}
- get data () {
- webidl.brandCheck(this, MessageEvent)
-
- return this.#eventInit.data
+ if (needleLength > 256) {
+ throw new Error('The needle cannot have a length bigger than 256.')
}
- get origin () {
- webidl.brandCheck(this, MessageEvent)
+ this.maxMatches = Infinity
+ this.matches = 0
- return this.#eventInit.origin
+ this._occ = new Array(256)
+ .fill(needleLength) // Initialize occurrence table.
+ this._lookbehind_size = 0
+ this._needle = needle
+ this._bufpos = 0
+
+ this._lookbehind = Buffer.alloc(needleLength)
+
+ // Populate occurrence table with analysis of the needle,
+ // ignoring last letter.
+ for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var
+ this._occ[needle[i]] = needleLength - 1 - i
}
+}
+inherits(SBMH, EventEmitter)
- get lastEventId () {
- webidl.brandCheck(this, MessageEvent)
+SBMH.prototype.reset = function () {
+ this._lookbehind_size = 0
+ this.matches = 0
+ this._bufpos = 0
+}
- return this.#eventInit.lastEventId
+SBMH.prototype.push = function (chunk, pos) {
+ if (!Buffer.isBuffer(chunk)) {
+ chunk = Buffer.from(chunk, 'binary')
}
+ const chlen = chunk.length
+ this._bufpos = pos || 0
+ let r
+ while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) }
+ return r
+}
- get source () {
- webidl.brandCheck(this, MessageEvent)
+SBMH.prototype._sbmh_feed = function (data) {
+ const len = data.length
+ const needle = this._needle
+ const needleLength = needle.length
+ const lastNeedleChar = needle[needleLength - 1]
+
+ // Positive: points to a position in `data`
+ // pos == 3 points to data[3]
+ // Negative: points to a position in the lookbehind buffer
+ // pos == -2 points to lookbehind[lookbehind_size - 2]
+ let pos = -this._lookbehind_size
+ let ch
+
+ if (pos < 0) {
+ // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
+ // search with character lookup code that considers both the
+ // lookbehind buffer and the current round's haystack data.
+ //
+ // Loop until
+ // there is a match.
+ // or until
+ // we've moved past the position that requires the
+ // lookbehind buffer. In this case we switch to the
+ // optimized loop.
+ // or until
+ // the character to look at lies outside the haystack.
+ while (pos < 0 && pos <= len - needleLength) {
+ ch = this._sbmh_lookup_char(data, pos + needleLength - 1)
+
+ if (
+ ch === lastNeedleChar &&
+ this._sbmh_memcmp(data, pos, needleLength - 1)
+ ) {
+ this._lookbehind_size = 0
+ ++this.matches
+ this.emit('info', true)
+
+ return (this._bufpos = pos + needleLength)
+ }
+ pos += this._occ[ch]
+ }
+
+ // No match.
+
+ if (pos < 0) {
+ // There's too few data for Boyer-Moore-Horspool to run,
+ // so let's use a different algorithm to skip as much as
+ // we can.
+ // Forward pos until
+ // the trailing part of lookbehind + data
+ // looks like the beginning of the needle
+ // or until
+ // pos == 0
+ while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos }
+ }
+
+ if (pos >= 0) {
+ // Discard lookbehind buffer.
+ this.emit('info', false, this._lookbehind, 0, this._lookbehind_size)
+ this._lookbehind_size = 0
+ } else {
+ // Cut off part of the lookbehind buffer that has
+ // been processed and append the entire haystack
+ // into it.
+ const bytesToCutOff = this._lookbehind_size + pos
+ if (bytesToCutOff > 0) {
+ // The cut off data is guaranteed not to contain the needle.
+ this.emit('info', false, this._lookbehind, 0, bytesToCutOff)
+ }
- return this.#eventInit.source
- }
+ this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff,
+ this._lookbehind_size - bytesToCutOff)
+ this._lookbehind_size -= bytesToCutOff
- get ports () {
- webidl.brandCheck(this, MessageEvent)
+ data.copy(this._lookbehind, this._lookbehind_size)
+ this._lookbehind_size += len
- if (!Object.isFrozen(this.#eventInit.ports)) {
- Object.freeze(this.#eventInit.ports)
+ this._bufpos = len
+ return len
}
-
- return this.#eventInit.ports
}
- initMessageEvent (
- type,
- bubbles = false,
- cancelable = false,
- data = null,
- origin = '',
- lastEventId = '',
- source = null,
- ports = []
- ) {
- webidl.brandCheck(this, MessageEvent)
+ pos += (pos >= 0) * this._bufpos
- webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' })
+ // Lookbehind buffer is now empty. We only need to check if the
+ // needle is in the haystack.
+ if (data.indexOf(needle, pos) !== -1) {
+ pos = data.indexOf(needle, pos)
+ ++this.matches
+ if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) }
- return new MessageEvent(type, {
- bubbles, cancelable, data, origin, lastEventId, source, ports
- })
+ return (this._bufpos = pos + needleLength)
+ } else {
+ pos = len - needleLength
}
-}
-
-/**
- * @see https://websockets.spec.whatwg.org/#the-closeevent-interface
- */
-class CloseEvent extends Event {
- #eventInit
-
- constructor (type, eventInitDict = {}) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' })
-
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.CloseEventInit(eventInitDict)
-
- super(type, eventInitDict)
- this.#eventInit = eventInitDict
+ // There was no match. If there's trailing haystack data that we cannot
+ // match yet using the Boyer-Moore-Horspool algorithm (because the trailing
+ // data is less than the needle size) then match using a modified
+ // algorithm that starts matching from the beginning instead of the end.
+ // Whatever trailing data is left after running this algorithm is added to
+ // the lookbehind buffer.
+ while (
+ pos < len &&
+ (
+ data[pos] !== needle[0] ||
+ (
+ (Buffer.compare(
+ data.subarray(pos, pos + len - pos),
+ needle.subarray(0, len - pos)
+ ) !== 0)
+ )
+ )
+ ) {
+ ++pos
}
-
- get wasClean () {
- webidl.brandCheck(this, CloseEvent)
-
- return this.#eventInit.wasClean
+ if (pos < len) {
+ data.copy(this._lookbehind, 0, pos, pos + (len - pos))
+ this._lookbehind_size = len - pos
}
- get code () {
- webidl.brandCheck(this, CloseEvent)
+ // Everything until pos is guaranteed not to contain needle data.
+ if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) }
- return this.#eventInit.code
- }
+ this._bufpos = len
+ return len
+}
- get reason () {
- webidl.brandCheck(this, CloseEvent)
+SBMH.prototype._sbmh_lookup_char = function (data, pos) {
+ return (pos < 0)
+ ? this._lookbehind[this._lookbehind_size + pos]
+ : data[pos]
+}
- return this.#eventInit.reason
+SBMH.prototype._sbmh_memcmp = function (data, pos, len) {
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false }
}
+ return true
}
-// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface
-class ErrorEvent extends Event {
- #eventInit
-
- constructor (type, eventInitDict) {
- webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' })
+module.exports = SBMH
- super(type, eventInitDict)
- type = webidl.converters.DOMString(type)
- eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {})
+/***/ }),
- this.#eventInit = eventInitDict
- }
+/***/ 75249:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- get message () {
- webidl.brandCheck(this, ErrorEvent)
- return this.#eventInit.message
- }
- get filename () {
- webidl.brandCheck(this, ErrorEvent)
+const WritableStream = (__nccwpck_require__(57075).Writable)
+const { inherits } = __nccwpck_require__(57975)
+const Dicer = __nccwpck_require__(8946)
- return this.#eventInit.filename
- }
+const MultipartParser = __nccwpck_require__(35764)
+const UrlencodedParser = __nccwpck_require__(21411)
+const parseParams = __nccwpck_require__(60717)
- get lineno () {
- webidl.brandCheck(this, ErrorEvent)
+function Busboy (opts) {
+ if (!(this instanceof Busboy)) { return new Busboy(opts) }
- return this.#eventInit.lineno
+ if (typeof opts !== 'object') {
+ throw new TypeError('Busboy expected an options-Object.')
+ }
+ if (typeof opts.headers !== 'object') {
+ throw new TypeError('Busboy expected an options-Object with headers-attribute.')
+ }
+ if (typeof opts.headers['content-type'] !== 'string') {
+ throw new TypeError('Missing Content-Type-header.')
}
- get colno () {
- webidl.brandCheck(this, ErrorEvent)
+ const {
+ headers,
+ ...streamOptions
+ } = opts
- return this.#eventInit.colno
+ this.opts = {
+ autoDestroy: false,
+ ...streamOptions
}
+ WritableStream.call(this, this.opts)
- get error () {
- webidl.brandCheck(this, ErrorEvent)
+ this._done = false
+ this._parser = this.getParserByHeaders(headers)
+ this._finished = false
+}
+inherits(Busboy, WritableStream)
- return this.#eventInit.error
+Busboy.prototype.emit = function (ev) {
+ if (ev === 'finish') {
+ if (!this._done) {
+ this._parser?.end()
+ return
+ } else if (this._finished) {
+ return
+ }
+ this._finished = true
}
+ WritableStream.prototype.emit.apply(this, arguments)
}
-Object.defineProperties(MessageEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'MessageEvent',
- configurable: true
- },
- data: kEnumerableProperty,
- origin: kEnumerableProperty,
- lastEventId: kEnumerableProperty,
- source: kEnumerableProperty,
- ports: kEnumerableProperty,
- initMessageEvent: kEnumerableProperty
-})
-
-Object.defineProperties(CloseEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'CloseEvent',
- configurable: true
- },
- reason: kEnumerableProperty,
- code: kEnumerableProperty,
- wasClean: kEnumerableProperty
-})
-
-Object.defineProperties(ErrorEvent.prototype, {
- [Symbol.toStringTag]: {
- value: 'ErrorEvent',
- configurable: true
- },
- message: kEnumerableProperty,
- filename: kEnumerableProperty,
- lineno: kEnumerableProperty,
- colno: kEnumerableProperty,
- error: kEnumerableProperty
-})
-
-webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort)
-
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.MessagePort
-)
-
-const eventInit = [
- {
- key: 'bubbles',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'cancelable',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'composed',
- converter: webidl.converters.boolean,
- defaultValue: false
- }
-]
+Busboy.prototype.getParserByHeaders = function (headers) {
+ const parsed = parseParams(headers['content-type'])
-webidl.converters.MessageEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'data',
- converter: webidl.converters.any,
- defaultValue: null
- },
- {
- key: 'origin',
- converter: webidl.converters.USVString,
- defaultValue: ''
- },
- {
- key: 'lastEventId',
- converter: webidl.converters.DOMString,
- defaultValue: ''
- },
- {
- key: 'source',
- // Node doesn't implement WindowProxy or ServiceWorker, so the only
- // valid value for source is a MessagePort.
- converter: webidl.nullableConverter(webidl.converters.MessagePort),
- defaultValue: null
- },
- {
- key: 'ports',
- converter: webidl.converters['sequence'],
- get defaultValue () {
- return []
- }
+ const cfg = {
+ defCharset: this.opts.defCharset,
+ fileHwm: this.opts.fileHwm,
+ headers,
+ highWaterMark: this.opts.highWaterMark,
+ isPartAFile: this.opts.isPartAFile,
+ limits: this.opts.limits,
+ parsedConType: parsed,
+ preservePath: this.opts.preservePath
}
-])
-webidl.converters.CloseEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'wasClean',
- converter: webidl.converters.boolean,
- defaultValue: false
- },
- {
- key: 'code',
- converter: webidl.converters['unsigned short'],
- defaultValue: 0
- },
- {
- key: 'reason',
- converter: webidl.converters.USVString,
- defaultValue: ''
+ if (MultipartParser.detect.test(parsed[0])) {
+ return new MultipartParser(this, cfg)
}
-])
-
-webidl.converters.ErrorEventInit = webidl.dictionaryConverter([
- ...eventInit,
- {
- key: 'message',
- converter: webidl.converters.DOMString,
- defaultValue: ''
- },
- {
- key: 'filename',
- converter: webidl.converters.USVString,
- defaultValue: ''
- },
- {
- key: 'lineno',
- converter: webidl.converters['unsigned long'],
- defaultValue: 0
- },
- {
- key: 'colno',
- converter: webidl.converters['unsigned long'],
- defaultValue: 0
- },
- {
- key: 'error',
- converter: webidl.converters.any
+ if (UrlencodedParser.detect.test(parsed[0])) {
+ return new UrlencodedParser(this, cfg)
}
-])
+ throw new Error('Unsupported Content-Type.')
+}
-module.exports = {
- MessageEvent,
- CloseEvent,
- ErrorEvent
+Busboy.prototype._write = function (chunk, encoding, cb) {
+ this._parser.write(chunk, cb)
}
+module.exports = Busboy
+module.exports["default"] = Busboy
+module.exports.Busboy = Busboy
+
+module.exports.Dicer = Dicer
+
/***/ }),
-/***/ 42697:
+/***/ 35764:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-const { maxUnsigned16Bit } = __nccwpck_require__(90077)
+// TODO:
+// * support 1 nested multipart level
+// (see second multipart example here:
+// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
+// * support limits.fieldNameSize
+// -- this will require modifications to utils.parseParams
-/** @type {import('crypto')} */
-let crypto
-try {
- crypto = __nccwpck_require__(76982)
-} catch {
+const { Readable } = __nccwpck_require__(57075)
+const { inherits } = __nccwpck_require__(57975)
-}
+const Dicer = __nccwpck_require__(8946)
-class WebsocketFrameSend {
- /**
- * @param {Buffer|undefined} data
- */
- constructor (data) {
- this.frameData = data
- this.maskKey = crypto.randomBytes(4)
- }
+const parseParams = __nccwpck_require__(60717)
+const decodeText = __nccwpck_require__(16607)
+const basename = __nccwpck_require__(15080)
+const getLimit = __nccwpck_require__(5245)
- createFrame (opcode) {
- const bodyLength = this.frameData?.byteLength ?? 0
+const RE_BOUNDARY = /^boundary$/i
+const RE_FIELD = /^form-data$/i
+const RE_CHARSET = /^charset$/i
+const RE_FILENAME = /^filename$/i
+const RE_NAME = /^name$/i
- /** @type {number} */
- let payloadLength = bodyLength // 0-125
- let offset = 6
+Multipart.detect = /^multipart\/form-data/i
+function Multipart (boy, cfg) {
+ let i
+ let len
+ const self = this
+ let boundary
+ const limits = cfg.limits
+ const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined))
+ const parsedConType = cfg.parsedConType || []
+ const defCharset = cfg.defCharset || 'utf8'
+ const preservePath = cfg.preservePath
+ const fileOpts = { highWaterMark: cfg.fileHwm }
- if (bodyLength > maxUnsigned16Bit) {
- offset += 8 // payload length is next 8 bytes
- payloadLength = 127
- } else if (bodyLength > 125) {
- offset += 2 // payload length is next 2 bytes
- payloadLength = 126
+ for (i = 0, len = parsedConType.length; i < len; ++i) {
+ if (Array.isArray(parsedConType[i]) &&
+ RE_BOUNDARY.test(parsedConType[i][0])) {
+ boundary = parsedConType[i][1]
+ break
}
+ }
- const buffer = Buffer.allocUnsafe(bodyLength + offset)
-
- // Clear first 2 bytes, everything else is overwritten
- buffer[0] = buffer[1] = 0
- buffer[0] |= 0x80 // FIN
- buffer[0] = (buffer[0] & 0xF0) + opcode // opcode
-
- /*! ws. MIT License. Einar Otto Stangvik */
- buffer[offset - 4] = this.maskKey[0]
- buffer[offset - 3] = this.maskKey[1]
- buffer[offset - 2] = this.maskKey[2]
- buffer[offset - 1] = this.maskKey[3]
+ function checkFinished () {
+ if (nends === 0 && finished && !boy._done) {
+ finished = false
+ self.end()
+ }
+ }
- buffer[1] = payloadLength
+ if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') }
- if (payloadLength === 126) {
- buffer.writeUInt16BE(bodyLength, 2)
- } else if (payloadLength === 127) {
- // Clear extended payload length
- buffer[2] = buffer[3] = 0
- buffer.writeUIntBE(bodyLength, 4, 6)
- }
+ const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
+ const fileSizeLimit = getLimit(limits, 'fileSize', Infinity)
+ const filesLimit = getLimit(limits, 'files', Infinity)
+ const fieldsLimit = getLimit(limits, 'fields', Infinity)
+ const partsLimit = getLimit(limits, 'parts', Infinity)
+ const headerPairsLimit = getLimit(limits, 'headerPairs', 2000)
+ const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024)
- buffer[1] |= 0x80 // MASK
+ let nfiles = 0
+ let nfields = 0
+ let nends = 0
+ let curFile
+ let curField
+ let finished = false
- // mask body
- for (let i = 0; i < bodyLength; i++) {
- buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]
- }
+ this._needDrain = false
+ this._pause = false
+ this._cb = undefined
+ this._nparts = 0
+ this._boy = boy
- return buffer
+ const parserCfg = {
+ boundary,
+ maxHeaderPairs: headerPairsLimit,
+ maxHeaderSize: headerSizeLimit,
+ partHwm: fileOpts.highWaterMark,
+ highWaterMark: cfg.highWaterMark
}
-}
-module.exports = {
- WebsocketFrameSend
-}
+ this.parser = new Dicer(parserCfg)
+ this.parser.on('drain', function () {
+ self._needDrain = false
+ if (self._cb && !self._pause) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ }).on('part', function onPart (part) {
+ if (++self._nparts > partsLimit) {
+ self.parser.removeListener('part', onPart)
+ self.parser.on('part', skipPart)
+ boy.hitPartsLimit = true
+ boy.emit('partsLimit')
+ return skipPart(part)
+ }
+ // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
+ // us emit 'end' early since we know the part has ended if we are already
+ // seeing the next part
+ if (curField) {
+ const field = curField
+ field.emit('end')
+ field.removeAllListeners('end')
+ }
-/***/ }),
+ part.on('header', function (header) {
+ let contype
+ let fieldname
+ let parsed
+ let charset
+ let encoding
+ let filename
+ let nsize = 0
-/***/ 13607:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
+ if (header['content-type']) {
+ parsed = parseParams(header['content-type'][0])
+ if (parsed[0]) {
+ contype = parsed[0].toLowerCase()
+ for (i = 0, len = parsed.length; i < len; ++i) {
+ if (RE_CHARSET.test(parsed[i][0])) {
+ charset = parsed[i][1].toLowerCase()
+ break
+ }
+ }
+ }
+ }
+ if (contype === undefined) { contype = 'text/plain' }
+ if (charset === undefined) { charset = defCharset }
+ if (header['content-disposition']) {
+ parsed = parseParams(header['content-disposition'][0])
+ if (!RE_FIELD.test(parsed[0])) { return skipPart(part) }
+ for (i = 0, len = parsed.length; i < len; ++i) {
+ if (RE_NAME.test(parsed[i][0])) {
+ fieldname = parsed[i][1]
+ } else if (RE_FILENAME.test(parsed[i][0])) {
+ filename = parsed[i][1]
+ if (!preservePath) { filename = basename(filename) }
+ }
+ }
+ } else { return skipPart(part) }
-const { Writable } = __nccwpck_require__(2203)
-const diagnosticsChannel = __nccwpck_require__(31637)
-const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(90077)
-const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(97945)
-const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(95506)
-const { WebsocketFrameSend } = __nccwpck_require__(42697)
+ if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' }
-// This code was influenced by ws released under the MIT license.
-// Copyright (c) 2011 Einar Otto Stangvik
-// Copyright (c) 2013 Arnout Kazemier and contributors
-// Copyright (c) 2016 Luigi Pinca and contributors
+ let onData,
+ onEnd
-const channels = {}
-channels.ping = diagnosticsChannel.channel('undici:websocket:ping')
-channels.pong = diagnosticsChannel.channel('undici:websocket:pong')
+ if (isPartAFile(fieldname, contype, filename)) {
+ // file/binary field
+ if (nfiles === filesLimit) {
+ if (!boy.hitFilesLimit) {
+ boy.hitFilesLimit = true
+ boy.emit('filesLimit')
+ }
+ return skipPart(part)
+ }
-class ByteParser extends Writable {
- #buffers = []
- #byteOffset = 0
+ ++nfiles
- #state = parserStates.INFO
+ if (boy.listenerCount('file') === 0) {
+ self.parser._ignore()
+ return
+ }
- #info = {}
- #fragments = []
+ ++nends
+ const file = new FileStream(fileOpts)
+ curFile = file
+ file.on('end', function () {
+ --nends
+ self._pause = false
+ checkFinished()
+ if (self._cb && !self._needDrain) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ })
+ file._read = function (n) {
+ if (!self._pause) { return }
+ self._pause = false
+ if (self._cb && !self._needDrain) {
+ const cb = self._cb
+ self._cb = undefined
+ cb()
+ }
+ }
+ boy.emit('file', fieldname, file, filename, encoding, contype)
- constructor (ws) {
- super()
+ onData = function (data) {
+ if ((nsize += data.length) > fileSizeLimit) {
+ const extralen = fileSizeLimit - nsize + data.length
+ if (extralen > 0) { file.push(data.slice(0, extralen)) }
+ file.truncated = true
+ file.bytesRead = fileSizeLimit
+ part.removeAllListeners('data')
+ file.emit('limit')
+ return
+ } else if (!file.push(data)) { self._pause = true }
- this.ws = ws
- }
+ file.bytesRead = nsize
+ }
- /**
- * @param {Buffer} chunk
- * @param {() => void} callback
- */
- _write (chunk, _, callback) {
- this.#buffers.push(chunk)
- this.#byteOffset += chunk.length
+ onEnd = function () {
+ curFile = undefined
+ file.push(null)
+ }
+ } else {
+ // non-file field
+ if (nfields === fieldsLimit) {
+ if (!boy.hitFieldsLimit) {
+ boy.hitFieldsLimit = true
+ boy.emit('fieldsLimit')
+ }
+ return skipPart(part)
+ }
- this.run(callback)
- }
+ ++nfields
+ ++nends
+ let buffer = ''
+ let truncated = false
+ curField = part
- /**
- * Runs whenever a new chunk is received.
- * Callback is called whenever there are no more chunks buffering,
- * or not enough bytes are buffered to parse.
- */
- run (callback) {
- while (true) {
- if (this.#state === parserStates.INFO) {
- // If there aren't enough bytes to parse the payload length, etc.
- if (this.#byteOffset < 2) {
- return callback()
+ onData = function (data) {
+ if ((nsize += data.length) > fieldSizeLimit) {
+ const extralen = (fieldSizeLimit - (nsize - data.length))
+ buffer += data.toString('binary', 0, extralen)
+ truncated = true
+ part.removeAllListeners('data')
+ } else { buffer += data.toString('binary') }
}
- const buffer = this.consume(2)
+ onEnd = function () {
+ curField = undefined
+ if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) }
+ boy.emit('field', fieldname, buffer, false, truncated, encoding, contype)
+ --nends
+ checkFinished()
+ }
+ }
- this.#info.fin = (buffer[0] & 0x80) !== 0
- this.#info.opcode = buffer[0] & 0x0F
+ /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
+ broken. Streams2/streams3 is a huge black box of confusion, but
+ somehow overriding the sync state seems to fix things again (and still
+ seems to work for previous node versions).
+ */
+ part._readableState.sync = false
- // If we receive a fragmented message, we use the type of the first
- // frame to parse the full message as binary/text, when it's terminated
- this.#info.originalOpcode ??= this.#info.opcode
+ part.on('data', onData)
+ part.on('end', onEnd)
+ }).on('error', function (err) {
+ if (curFile) { curFile.emit('error', err) }
+ })
+ }).on('error', function (err) {
+ boy.emit('error', err)
+ }).on('finish', function () {
+ finished = true
+ checkFinished()
+ })
+}
- this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION
+Multipart.prototype.write = function (chunk, cb) {
+ const r = this.parser.write(chunk)
+ if (r && !this._pause) {
+ cb()
+ } else {
+ this._needDrain = !r
+ this._cb = cb
+ }
+}
- if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) {
- // Only text and binary frames can be fragmented
- failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.')
- return
- }
+Multipart.prototype.end = function () {
+ const self = this
- const payloadLength = buffer[1] & 0x7F
+ if (self.parser.writable) {
+ self.parser.end()
+ } else if (!self._boy._done) {
+ process.nextTick(function () {
+ self._boy._done = true
+ self._boy.emit('finish')
+ })
+ }
+}
- if (payloadLength <= 125) {
- this.#info.payloadLength = payloadLength
- this.#state = parserStates.READ_DATA
- } else if (payloadLength === 126) {
- this.#state = parserStates.PAYLOADLENGTH_16
- } else if (payloadLength === 127) {
- this.#state = parserStates.PAYLOADLENGTH_64
- }
+function skipPart (part) {
+ part.resume()
+}
- if (this.#info.fragmented && payloadLength > 125) {
- // A fragmented frame can't be fragmented itself
- failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.')
- return
- } else if (
- (this.#info.opcode === opcodes.PING ||
- this.#info.opcode === opcodes.PONG ||
- this.#info.opcode === opcodes.CLOSE) &&
- payloadLength > 125
- ) {
- // Control frames can have a payload length of 125 bytes MAX
- failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.')
- return
- } else if (this.#info.opcode === opcodes.CLOSE) {
- if (payloadLength === 1) {
- failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.')
- return
- }
+function FileStream (opts) {
+ Readable.call(this, opts)
- const body = this.consume(payloadLength)
+ this.bytesRead = 0
- this.#info.closeInfo = this.parseCloseBody(false, body)
+ this.truncated = false
+}
- if (!this.ws[kSentClose]) {
- // If an endpoint receives a Close frame and did not previously send a
- // Close frame, the endpoint MUST send a Close frame in response. (When
- // sending a Close frame in response, the endpoint typically echos the
- // status code it received.)
- const body = Buffer.allocUnsafe(2)
- body.writeUInt16BE(this.#info.closeInfo.code, 0)
- const closeFrame = new WebsocketFrameSend(body)
+inherits(FileStream, Readable)
- this.ws[kResponse].socket.write(
- closeFrame.createFrame(opcodes.CLOSE),
- (err) => {
- if (!err) {
- this.ws[kSentClose] = true
- }
- }
- )
- }
+FileStream.prototype._read = function (n) {}
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- this.ws[kReadyState] = states.CLOSING
- this.ws[kReceivedClose] = true
+module.exports = Multipart
- this.end()
- return
- } else if (this.#info.opcode === opcodes.PING) {
- // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in
- // response, unless it already received a Close frame.
- // A Pong frame sent in response to a Ping frame must have identical
- // "Application data"
+/***/ }),
- const body = this.consume(payloadLength)
+/***/ 21411:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (!this.ws[kReceivedClose]) {
- const frame = new WebsocketFrameSend(body)
- this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG))
- if (channels.ping.hasSubscribers) {
- channels.ping.publish({
- payload: body
- })
- }
- }
+const Decoder = __nccwpck_require__(4364)
+const decodeText = __nccwpck_require__(16607)
+const getLimit = __nccwpck_require__(5245)
- this.#state = parserStates.INFO
+const RE_CHARSET = /^charset$/i
- if (this.#byteOffset > 0) {
- continue
- } else {
- callback()
- return
- }
- } else if (this.#info.opcode === opcodes.PONG) {
- // A Pong frame MAY be sent unsolicited. This serves as a
- // unidirectional heartbeat. A response to an unsolicited Pong frame is
- // not expected.
+UrlEncoded.detect = /^application\/x-www-form-urlencoded/i
+function UrlEncoded (boy, cfg) {
+ const limits = cfg.limits
+ const parsedConType = cfg.parsedConType
+ this.boy = boy
- const body = this.consume(payloadLength)
+ this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024)
+ this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100)
+ this.fieldsLimit = getLimit(limits, 'fields', Infinity)
- if (channels.pong.hasSubscribers) {
- channels.pong.publish({
- payload: body
- })
- }
+ let charset
+ for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var
+ if (Array.isArray(parsedConType[i]) &&
+ RE_CHARSET.test(parsedConType[i][0])) {
+ charset = parsedConType[i][1].toLowerCase()
+ break
+ }
+ }
- if (this.#byteOffset > 0) {
- continue
- } else {
- callback()
- return
- }
- }
- } else if (this.#state === parserStates.PAYLOADLENGTH_16) {
- if (this.#byteOffset < 2) {
- return callback()
- }
+ if (charset === undefined) { charset = cfg.defCharset || 'utf8' }
- const buffer = this.consume(2)
+ this.decoder = new Decoder()
+ this.charset = charset
+ this._fields = 0
+ this._state = 'key'
+ this._checkingBytes = true
+ this._bytesKey = 0
+ this._bytesVal = 0
+ this._key = ''
+ this._val = ''
+ this._keyTrunc = false
+ this._valTrunc = false
+ this._hitLimit = false
+}
- this.#info.payloadLength = buffer.readUInt16BE(0)
- this.#state = parserStates.READ_DATA
- } else if (this.#state === parserStates.PAYLOADLENGTH_64) {
- if (this.#byteOffset < 8) {
- return callback()
- }
+UrlEncoded.prototype.write = function (data, cb) {
+ if (this._fields === this.fieldsLimit) {
+ if (!this.boy.hitFieldsLimit) {
+ this.boy.hitFieldsLimit = true
+ this.boy.emit('fieldsLimit')
+ }
+ return cb()
+ }
- const buffer = this.consume(8)
- const upper = buffer.readUInt32BE(0)
+ let idxeq; let idxamp; let i; let p = 0; const len = data.length
- // 2^31 is the maxinimum bytes an arraybuffer can contain
- // on 32-bit systems. Although, on 64-bit systems, this is
- // 2^53-1 bytes.
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length
- // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275
- // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e
- if (upper > 2 ** 31 - 1) {
- failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.')
- return
+ while (p < len) {
+ if (this._state === 'key') {
+ idxeq = idxamp = undefined
+ for (i = p; i < len; ++i) {
+ if (!this._checkingBytes) { ++p }
+ if (data[i] === 0x3D/* = */) {
+ idxeq = i
+ break
+ } else if (data[i] === 0x26/* & */) {
+ idxamp = i
+ break
}
+ if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
+ this._hitLimit = true
+ break
+ } else if (this._checkingBytes) { ++this._bytesKey }
+ }
- const lower = buffer.readUInt32BE(4)
-
- this.#info.payloadLength = (upper << 8) + lower
- this.#state = parserStates.READ_DATA
- } else if (this.#state === parserStates.READ_DATA) {
- if (this.#byteOffset < this.#info.payloadLength) {
- // If there is still more data in this chunk that needs to be read
- return callback()
- } else if (this.#byteOffset >= this.#info.payloadLength) {
- // If the server sent multiple frames in a single chunk
-
- const body = this.consume(this.#info.payloadLength)
-
- this.#fragments.push(body)
+ if (idxeq !== undefined) {
+ // key with assignment
+ if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) }
+ this._state = 'val'
- // If the frame is unfragmented, or a fragmented frame was terminated,
- // a message was received
- if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) {
- const fullMessage = Buffer.concat(this.#fragments)
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._val = ''
+ this._bytesVal = 0
+ this._valTrunc = false
+ this.decoder.reset()
- websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage)
+ p = idxeq + 1
+ } else if (idxamp !== undefined) {
+ // key with no assignment
+ ++this._fields
+ let key; const keyTrunc = this._keyTrunc
+ if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key }
- this.#info = {}
- this.#fragments.length = 0
- }
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._key = ''
+ this._bytesKey = 0
+ this._keyTrunc = false
+ this.decoder.reset()
- this.#state = parserStates.INFO
+ if (key.length) {
+ this.boy.emit('field', decodeText(key, 'binary', this.charset),
+ '',
+ keyTrunc,
+ false)
}
- }
- if (this.#byteOffset > 0) {
- continue
+ p = idxamp + 1
+ if (this._fields === this.fieldsLimit) { return cb() }
+ } else if (this._hitLimit) {
+ // we may not have hit the actual limit if there are encoded bytes...
+ if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) }
+ p = i
+ if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
+ // yep, we actually did hit the limit
+ this._checkingBytes = false
+ this._keyTrunc = true
+ }
} else {
- callback()
- break
+ if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) }
+ p = len
+ }
+ } else {
+ idxamp = undefined
+ for (i = p; i < len; ++i) {
+ if (!this._checkingBytes) { ++p }
+ if (data[i] === 0x26/* & */) {
+ idxamp = i
+ break
+ }
+ if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
+ this._hitLimit = true
+ break
+ } else if (this._checkingBytes) { ++this._bytesVal }
}
- }
- }
-
- /**
- * Take n bytes from the buffered Buffers
- * @param {number} n
- * @returns {Buffer|null}
- */
- consume (n) {
- if (n > this.#byteOffset) {
- return null
- } else if (n === 0) {
- return emptyBuffer
- }
-
- if (this.#buffers[0].length === n) {
- this.#byteOffset -= this.#buffers[0].length
- return this.#buffers.shift()
- }
- const buffer = Buffer.allocUnsafe(n)
- let offset = 0
+ if (idxamp !== undefined) {
+ ++this._fields
+ if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) }
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ decodeText(this._val, 'binary', this.charset),
+ this._keyTrunc,
+ this._valTrunc)
+ this._state = 'key'
- while (offset !== n) {
- const next = this.#buffers[0]
- const { length } = next
+ this._hitLimit = false
+ this._checkingBytes = true
+ this._key = ''
+ this._bytesKey = 0
+ this._keyTrunc = false
+ this.decoder.reset()
- if (length + offset === n) {
- buffer.set(this.#buffers.shift(), offset)
- break
- } else if (length + offset > n) {
- buffer.set(next.subarray(0, n - offset), offset)
- this.#buffers[0] = next.subarray(n - offset)
- break
+ p = idxamp + 1
+ if (this._fields === this.fieldsLimit) { return cb() }
+ } else if (this._hitLimit) {
+ // we may not have hit the actual limit if there are encoded bytes...
+ if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) }
+ p = i
+ if ((this._val === '' && this.fieldSizeLimit === 0) ||
+ (this._bytesVal = this._val.length) === this.fieldSizeLimit) {
+ // yep, we actually did hit the limit
+ this._checkingBytes = false
+ this._valTrunc = true
+ }
} else {
- buffer.set(this.#buffers.shift(), offset)
- offset += next.length
+ if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) }
+ p = len
}
}
+ }
+ cb()
+}
- this.#byteOffset -= n
+UrlEncoded.prototype.end = function () {
+ if (this.boy._done) { return }
- return buffer
+ if (this._state === 'key' && this._key.length > 0) {
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ '',
+ this._keyTrunc,
+ false)
+ } else if (this._state === 'val') {
+ this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
+ decodeText(this._val, 'binary', this.charset),
+ this._keyTrunc,
+ this._valTrunc)
}
+ this.boy._done = true
+ this.boy.emit('finish')
+}
- parseCloseBody (onlyCode, data) {
- // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5
- /** @type {number|undefined} */
- let code
-
- if (data.length >= 2) {
- // _The WebSocket Connection Close Code_ is
- // defined as the status code (Section 7.4) contained in the first Close
- // control frame received by the application
- code = data.readUInt16BE(0)
- }
+module.exports = UrlEncoded
- if (onlyCode) {
- if (!isValidStatusCode(code)) {
- return null
- }
- return { code }
- }
+/***/ }),
- // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6
- /** @type {Buffer} */
- let reason = data.subarray(2)
+/***/ 4364:
+/***/ ((module) => {
- // Remove BOM
- if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) {
- reason = reason.subarray(3)
- }
- if (code !== undefined && !isValidStatusCode(code)) {
- return null
- }
- try {
- // TODO: optimize this
- reason = new TextDecoder('utf-8', { fatal: true }).decode(reason)
- } catch {
- return null
- }
+const RE_PLUS = /\+/g
- return { code, reason }
- }
+const HEX = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+]
- get closingInfo () {
- return this.#info.closeInfo
+function Decoder () {
+ this.buffer = undefined
+}
+Decoder.prototype.write = function (str) {
+ // Replace '+' with ' ' before decoding
+ str = str.replace(RE_PLUS, ' ')
+ let res = ''
+ let i = 0; let p = 0; const len = str.length
+ for (; i < len; ++i) {
+ if (this.buffer !== undefined) {
+ if (!HEX[str.charCodeAt(i)]) {
+ res += '%' + this.buffer
+ this.buffer = undefined
+ --i // retry character
+ } else {
+ this.buffer += str[i]
+ ++p
+ if (this.buffer.length === 2) {
+ res += String.fromCharCode(parseInt(this.buffer, 16))
+ this.buffer = undefined
+ }
+ }
+ } else if (str[i] === '%') {
+ if (i > p) {
+ res += str.substring(p, i)
+ p = i
+ }
+ this.buffer = ''
+ ++p
+ }
}
+ if (p < len && this.buffer === undefined) { res += str.substring(p) }
+ return res
}
-
-module.exports = {
- ByteParser
+Decoder.prototype.reset = function () {
+ this.buffer = undefined
}
+module.exports = Decoder
+
/***/ }),
-/***/ 97945:
+/***/ 15080:
/***/ ((module) => {
-module.exports = {
- kWebSocketURL: Symbol('url'),
- kReadyState: Symbol('ready state'),
- kController: Symbol('controller'),
- kResponse: Symbol('response'),
- kBinaryType: Symbol('binary type'),
- kSentClose: Symbol('sent close'),
- kReceivedClose: Symbol('received close'),
- kByteParser: Symbol('byte parser')
+module.exports = function basename (path) {
+ if (typeof path !== 'string') { return '' }
+ for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var
+ switch (path.charCodeAt(i)) {
+ case 0x2F: // '/'
+ case 0x5C: // '\'
+ path = path.slice(i + 1)
+ return (path === '..' || path === '.' ? '' : path)
+ }
+ }
+ return (path === '..' || path === '.' ? '' : path)
}
/***/ }),
-/***/ 95506:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(97945)
-const { states, opcodes } = __nccwpck_require__(90077)
-const { MessageEvent, ErrorEvent } = __nccwpck_require__(47115)
-
-/* globals Blob */
-
-/**
- * @param {import('./websocket').WebSocket} ws
- */
-function isEstablished (ws) {
- // If the server's response is validated as provided for above, it is
- // said that _The WebSocket Connection is Established_ and that the
- // WebSocket Connection is in the OPEN state.
- return ws[kReadyState] === states.OPEN
-}
-
-/**
- * @param {import('./websocket').WebSocket} ws
- */
-function isClosing (ws) {
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- return ws[kReadyState] === states.CLOSING
-}
-
-/**
- * @param {import('./websocket').WebSocket} ws
- */
-function isClosed (ws) {
- return ws[kReadyState] === states.CLOSED
-}
-
-/**
- * @see https://dom.spec.whatwg.org/#concept-event-fire
- * @param {string} e
- * @param {EventTarget} target
- * @param {EventInit | undefined} eventInitDict
- */
-function fireEvent (e, target, eventConstructor = Event, eventInitDict) {
- // 1. If eventConstructor is not given, then let eventConstructor be Event.
+/***/ 16607:
+/***/ (function(module) {
- // 2. Let event be the result of creating an event given eventConstructor,
- // in the relevant realm of target.
- // 3. Initialize event’s type attribute to e.
- const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap
- // 4. Initialize any other IDL attributes of event as described in the
- // invocation of this algorithm.
- // 5. Return the result of dispatching event at target, with legacy target
- // override flag set if set.
- target.dispatchEvent(event)
-}
+// Node has always utf-8
+const utf8Decoder = new TextDecoder('utf-8')
+const textDecoders = new Map([
+ ['utf-8', utf8Decoder],
+ ['utf8', utf8Decoder]
+])
-/**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- * @param {import('./websocket').WebSocket} ws
- * @param {number} type Opcode
- * @param {Buffer} data application data
- */
-function websocketMessageReceived (ws, type, data) {
- // 1. If ready state is not OPEN (1), then return.
- if (ws[kReadyState] !== states.OPEN) {
- return
+function getDecoder (charset) {
+ let lc
+ while (true) {
+ switch (charset) {
+ case 'utf-8':
+ case 'utf8':
+ return decoders.utf8
+ case 'latin1':
+ case 'ascii': // TODO: Make these a separate, strict decoder?
+ case 'us-ascii':
+ case 'iso-8859-1':
+ case 'iso8859-1':
+ case 'iso88591':
+ case 'iso_8859-1':
+ case 'windows-1252':
+ case 'iso_8859-1:1987':
+ case 'cp1252':
+ case 'x-cp1252':
+ return decoders.latin1
+ case 'utf16le':
+ case 'utf-16le':
+ case 'ucs2':
+ case 'ucs-2':
+ return decoders.utf16le
+ case 'base64':
+ return decoders.base64
+ default:
+ if (lc === undefined) {
+ lc = true
+ charset = charset.toLowerCase()
+ continue
+ }
+ return decoders.other.bind(charset)
+ }
}
+}
- // 2. Let dataForEvent be determined by switching on type and binary type:
- let dataForEvent
-
- if (type === opcodes.TEXT) {
- // -> type indicates that the data is Text
- // a new DOMString containing data
- try {
- dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)
- } catch {
- failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
- return
+const decoders = {
+ utf8: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
}
- } else if (type === opcodes.BINARY) {
- if (ws[kBinaryType] === 'blob') {
- // -> type indicates that the data is Binary and binary type is "blob"
- // a new Blob object, created in the relevant Realm of the WebSocket
- // object, that represents data as its raw data
- dataForEvent = new Blob([data])
- } else {
- // -> type indicates that the data is Binary and binary type is "arraybuffer"
- // a new ArrayBuffer object, created in the relevant Realm of the
- // WebSocket object, whose contents are data
- dataForEvent = new Uint8Array(data).buffer
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
}
- }
-
- // 3. Fire an event named message at the WebSocket object, using MessageEvent,
- // with the origin attribute initialized to the serialization of the WebSocket
- // object’s url's origin, and the data attribute initialized to dataForEvent.
- fireEvent('message', ws, MessageEvent, {
- origin: ws[kWebSocketURL].origin,
- data: dataForEvent
- })
-}
+ return data.utf8Slice(0, data.length)
+ },
-/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455
- * @see https://datatracker.ietf.org/doc/html/rfc2616
- * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
- * @param {string} protocol
- */
-function isValidSubprotocol (protocol) {
- // If present, this value indicates one
- // or more comma-separated subprotocol the client wishes to speak,
- // ordered by preference. The elements that comprise this value
- // MUST be non-empty strings with characters in the range U+0021 to
- // U+007E not including separator characters as defined in
- // [RFC2616] and MUST all be unique strings.
- if (protocol.length === 0) {
- return false
- }
+ latin1: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ return data
+ }
+ return data.latin1Slice(0, data.length)
+ },
- for (const char of protocol) {
- const code = char.charCodeAt(0)
+ utf16le: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
+ }
+ return data.ucs2Slice(0, data.length)
+ },
- if (
- code < 0x21 ||
- code > 0x7E ||
- char === '(' ||
- char === ')' ||
- char === '<' ||
- char === '>' ||
- char === '@' ||
- char === ',' ||
- char === ';' ||
- char === ':' ||
- char === '\\' ||
- char === '"' ||
- char === '/' ||
- char === '[' ||
- char === ']' ||
- char === '?' ||
- char === '=' ||
- char === '{' ||
- char === '}' ||
- code === 32 || // SP
- code === 9 // HT
- ) {
- return false
+ base64: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
}
- }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
+ }
+ return data.base64Slice(0, data.length)
+ },
- return true
-}
+ other: (data, sourceEncoding) => {
+ if (data.length === 0) {
+ return ''
+ }
+ if (typeof data === 'string') {
+ data = Buffer.from(data, sourceEncoding)
+ }
-/**
- * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
- * @param {number} code
- */
-function isValidStatusCode (code) {
- if (code >= 1000 && code < 1015) {
- return (
- code !== 1004 && // reserved
- code !== 1005 && // "MUST NOT be set as a status code"
- code !== 1006 // "MUST NOT be set as a status code"
- )
+ if (textDecoders.has(this.toString())) {
+ try {
+ return textDecoders.get(this).decode(data)
+ } catch {}
+ }
+ return typeof data === 'string'
+ ? data
+ : data.toString()
}
-
- return code >= 3000 && code <= 4999
}
-/**
- * @param {import('./websocket').WebSocket} ws
- * @param {string|undefined} reason
- */
-function failWebsocketConnection (ws, reason) {
- const { [kController]: controller, [kResponse]: response } = ws
-
- controller.abort()
-
- if (response?.socket && !response.socket.destroyed) {
- response.socket.destroy()
- }
-
- if (reason) {
- fireEvent('error', ws, ErrorEvent, {
- error: new Error(reason)
- })
+function decodeText (text, sourceEncoding, destEncoding) {
+ if (text) {
+ return getDecoder(destEncoding)(text, sourceEncoding)
}
+ return text
}
-module.exports = {
- isEstablished,
- isClosing,
- isClosed,
- fireEvent,
- isValidSubprotocol,
- isValidStatusCode,
- failWebsocketConnection,
- websocketMessageReceived
-}
+module.exports = decodeText
/***/ }),
-/***/ 90551:
-/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-
-
-
-const { webidl } = __nccwpck_require__(94354)
-const { DOMException } = __nccwpck_require__(21234)
-const { URLSerializer } = __nccwpck_require__(37246)
-const { getGlobalOrigin } = __nccwpck_require__(62896)
-const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(90077)
-const {
- kWebSocketURL,
- kReadyState,
- kController,
- kBinaryType,
- kResponse,
- kSentClose,
- kByteParser
-} = __nccwpck_require__(97945)
-const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(95506)
-const { establishWebSocketConnection } = __nccwpck_require__(96114)
-const { WebsocketFrameSend } = __nccwpck_require__(42697)
-const { ByteParser } = __nccwpck_require__(13607)
-const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(89500)
-const { getGlobalDispatcher } = __nccwpck_require__(61481)
-const { types } = __nccwpck_require__(39023)
-
-let experimentalWarned = false
-
-// https://websockets.spec.whatwg.org/#interface-definition
-class WebSocket extends EventTarget {
- #events = {
- open: null,
- error: null,
- close: null,
- message: null
- }
-
- #bufferedAmount = 0
- #protocol = ''
- #extensions = ''
-
- /**
- * @param {string} url
- * @param {string|string[]} protocols
- */
- constructor (url, protocols = []) {
- super()
-
- webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' })
-
- if (!experimentalWarned) {
- experimentalWarned = true
- process.emitWarning('WebSockets are experimental, expect them to change at any time.', {
- code: 'UNDICI-WS'
- })
- }
-
- const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols)
-
- url = webidl.converters.USVString(url)
- protocols = options.protocols
+/***/ 5245:
+/***/ ((module) => {
- // 1. Let baseURL be this's relevant settings object's API base URL.
- const baseURL = getGlobalOrigin()
- // 1. Let urlRecord be the result of applying the URL parser to url with baseURL.
- let urlRecord
- try {
- urlRecord = new URL(url, baseURL)
- } catch (e) {
- // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException.
- throw new DOMException(e, 'SyntaxError')
- }
+module.exports = function getLimit (limits, name, defaultLimit) {
+ if (
+ !limits ||
+ limits[name] === undefined ||
+ limits[name] === null
+ ) { return defaultLimit }
- // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws".
- if (urlRecord.protocol === 'http:') {
- urlRecord.protocol = 'ws:'
- } else if (urlRecord.protocol === 'https:') {
- // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss".
- urlRecord.protocol = 'wss:'
- }
+ if (
+ typeof limits[name] !== 'number' ||
+ isNaN(limits[name])
+ ) { throw new TypeError('Limit ' + name + ' is not a valid number') }
- // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.
- if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {
- throw new DOMException(
- `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`,
- 'SyntaxError'
- )
- }
+ return limits[name]
+}
- // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError"
- // DOMException.
- if (urlRecord.hash || urlRecord.href.endsWith('#')) {
- throw new DOMException('Got fragment', 'SyntaxError')
- }
- // 8. If protocols is a string, set protocols to a sequence consisting
- // of just that string.
- if (typeof protocols === 'string') {
- protocols = [protocols]
- }
+/***/ }),
- // 9. If any of the values in protocols occur more than once or otherwise
- // fail to match the requirements for elements that comprise the value
- // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket
- // protocol, then throw a "SyntaxError" DOMException.
- if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) {
- throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
- }
+/***/ 60717:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) {
- throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError')
- }
+/* eslint-disable object-property-newline */
- // 10. Set this's url to urlRecord.
- this[kWebSocketURL] = new URL(urlRecord.href)
- // 11. Let client be this's relevant settings object.
+const decodeText = __nccwpck_require__(16607)
- // 12. Run this step in parallel:
+const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g
- // 1. Establish a WebSocket connection given urlRecord, protocols,
- // and client.
- this[kController] = establishWebSocketConnection(
- urlRecord,
- protocols,
- this,
- (response) => this.#onConnectionEstablished(response),
- options
- )
+const EncodedLookup = {
+ '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04',
+ '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09',
+ '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c',
+ '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e',
+ '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12',
+ '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17',
+ '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b',
+ '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d',
+ '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20',
+ '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25',
+ '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a',
+ '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c',
+ '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f',
+ '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33',
+ '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38',
+ '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b',
+ '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e',
+ '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41',
+ '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46',
+ '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a',
+ '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d',
+ '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f',
+ '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54',
+ '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59',
+ '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c',
+ '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e',
+ '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62',
+ '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67',
+ '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b',
+ '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d',
+ '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70',
+ '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75',
+ '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a',
+ '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c',
+ '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f',
+ '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83',
+ '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88',
+ '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b',
+ '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e',
+ '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91',
+ '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96',
+ '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a',
+ '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d',
+ '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f',
+ '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2',
+ '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4',
+ '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7',
+ '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9',
+ '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab',
+ '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac',
+ '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad',
+ '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae',
+ '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0',
+ '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2',
+ '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5',
+ '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7',
+ '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba',
+ '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb',
+ '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc',
+ '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd',
+ '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf',
+ '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0',
+ '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3',
+ '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5',
+ '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8',
+ '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca',
+ '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb',
+ '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc',
+ '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce',
+ '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf',
+ '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1',
+ '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3',
+ '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6',
+ '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8',
+ '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda',
+ '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb',
+ '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd',
+ '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde',
+ '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf',
+ '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1',
+ '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4',
+ '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6',
+ '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9',
+ '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea',
+ '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec',
+ '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed',
+ '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee',
+ '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef',
+ '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2',
+ '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4',
+ '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7',
+ '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9',
+ '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb',
+ '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc',
+ '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd',
+ '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe',
+ '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff'
+}
- // Each WebSocket object has an associated ready state, which is a
- // number representing the state of the connection. Initially it must
- // be CONNECTING (0).
- this[kReadyState] = WebSocket.CONNECTING
+function encodedReplacer (match) {
+ return EncodedLookup[match]
+}
- // The extensions attribute must initially return the empty string.
+const STATE_KEY = 0
+const STATE_VALUE = 1
+const STATE_CHARSET = 2
+const STATE_LANG = 3
- // The protocol attribute must initially return the empty string.
+function parseParams (str) {
+ const res = []
+ let state = STATE_KEY
+ let charset = ''
+ let inquote = false
+ let escaping = false
+ let p = 0
+ let tmp = ''
+ const len = str.length
- // Each WebSocket object has an associated binary type, which is a
- // BinaryType. Initially it must be "blob".
- this[kBinaryType] = 'blob'
+ for (var i = 0; i < len; ++i) { // eslint-disable-line no-var
+ const char = str[i]
+ if (char === '\\' && inquote) {
+ if (escaping) { escaping = false } else {
+ escaping = true
+ continue
+ }
+ } else if (char === '"') {
+ if (!escaping) {
+ if (inquote) {
+ inquote = false
+ state = STATE_KEY
+ } else { inquote = true }
+ continue
+ } else { escaping = false }
+ } else {
+ if (escaping && inquote) { tmp += '\\' }
+ escaping = false
+ if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") {
+ if (state === STATE_CHARSET) {
+ state = STATE_LANG
+ charset = tmp.substring(1)
+ } else { state = STATE_VALUE }
+ tmp = ''
+ continue
+ } else if (state === STATE_KEY &&
+ (char === '*' || char === '=') &&
+ res.length) {
+ state = char === '*'
+ ? STATE_CHARSET
+ : STATE_VALUE
+ res[p] = [tmp, undefined]
+ tmp = ''
+ continue
+ } else if (!inquote && char === ';') {
+ state = STATE_KEY
+ if (charset) {
+ if (tmp.length) {
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+ 'binary',
+ charset)
+ }
+ charset = ''
+ } else if (tmp.length) {
+ tmp = decodeText(tmp, 'binary', 'utf8')
+ }
+ if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp }
+ tmp = ''
+ ++p
+ continue
+ } else if (!inquote && (char === ' ' || char === '\t')) { continue }
+ }
+ tmp += char
+ }
+ if (charset && tmp.length) {
+ tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
+ 'binary',
+ charset)
+ } else if (tmp) {
+ tmp = decodeText(tmp, 'binary', 'utf8')
}
- /**
- * @see https://websockets.spec.whatwg.org/#dom-websocket-close
- * @param {number|undefined} code
- * @param {string|undefined} reason
- */
- close (code = undefined, reason = undefined) {
- webidl.brandCheck(this, WebSocket)
+ if (res[p] === undefined) {
+ if (tmp) { res[p] = tmp }
+ } else { res[p][1] = tmp }
- if (code !== undefined) {
- code = webidl.converters['unsigned short'](code, { clamp: true })
- }
+ return res
+}
- if (reason !== undefined) {
- reason = webidl.converters.USVString(reason)
- }
+module.exports = parseParams
- // 1. If code is present, but is neither an integer equal to 1000 nor an
- // integer in the range 3000 to 4999, inclusive, throw an
- // "InvalidAccessError" DOMException.
- if (code !== undefined) {
- if (code !== 1000 && (code < 3000 || code > 4999)) {
- throw new DOMException('invalid code', 'InvalidAccessError')
- }
- }
- let reasonByteLength = 0
+/***/ }),
- // 2. If reason is present, then run these substeps:
- if (reason !== undefined) {
- // 1. Let reasonBytes be the result of encoding reason.
- // 2. If reasonBytes is longer than 123 bytes, then throw a
- // "SyntaxError" DOMException.
- reasonByteLength = Buffer.byteLength(reason)
+/***/ 74352:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- if (reasonByteLength > 123) {
- throw new DOMException(
- `Reason must be less than 123 bytes; received ${reasonByteLength}`,
- 'SyntaxError'
- )
- }
- }
- // 3. Run the first matching steps from the following list:
- if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) {
- // If this's ready state is CLOSING (2) or CLOSED (3)
- // Do nothing.
- } else if (!isEstablished(this)) {
- // If the WebSocket connection is not yet established
- // Fail the WebSocket connection and set this's ready state
- // to CLOSING (2).
- failWebsocketConnection(this, 'Connection was closed before it was established.')
- this[kReadyState] = WebSocket.CLOSING
- } else if (!isClosing(this)) {
- // If the WebSocket closing handshake has not yet been started
- // Start the WebSocket closing handshake and set this's ready
- // state to CLOSING (2).
- // - If neither code nor reason is present, the WebSocket Close
- // message must not have a body.
- // - If code is present, then the status code to use in the
- // WebSocket Close message must be the integer given by code.
- // - If reason is also present, then reasonBytes must be
- // provided in the Close message after the status code.
+// @ts-check
+// ==================================================================================
+// audio.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 16. audio
+// ----------------------------------------------------------------------------------
- const frame = new WebsocketFrameSend()
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const util = __nccwpck_require__(77496);
- // If neither code nor reason is present, the WebSocket Close
- // message must not have a body.
+let _platform = process.platform;
- // If code is present, then the status code to use in the
- // WebSocket Close message must be the integer given by code.
- if (code !== undefined && reason === undefined) {
- frame.frameData = Buffer.allocUnsafe(2)
- frame.frameData.writeUInt16BE(code, 0)
- } else if (code !== undefined && reason !== undefined) {
- // If reason is also present, then reasonBytes must be
- // provided in the Close message after the status code.
- frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
- frame.frameData.writeUInt16BE(code, 0)
- // the body MAY contain UTF-8-encoded data with value /reason/
- frame.frameData.write(reason, 2, 'utf-8')
- } else {
- frame.frameData = emptyBuffer
- }
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
- /** @type {import('stream').Duplex} */
- const socket = this[kResponse].socket
+function parseAudioType(str, input, output) {
+ str = str.toLowerCase();
+ let result = '';
- socket.write(frame.createFrame(opcodes.CLOSE), (err) => {
- if (!err) {
- this[kSentClose] = true
- }
- })
+ if (str.indexOf('input') >= 0) { result = 'Microphone'; }
+ if (str.indexOf('display audio') >= 0) { result = 'Speaker'; }
+ if (str.indexOf('speak') >= 0) { result = 'Speaker'; }
+ if (str.indexOf('laut') >= 0) { result = 'Speaker'; }
+ if (str.indexOf('loud') >= 0) { result = 'Speaker'; }
+ if (str.indexOf('head') >= 0) { result = 'Headset'; }
+ if (str.indexOf('mic') >= 0) { result = 'Microphone'; }
+ if (str.indexOf('mikr') >= 0) { result = 'Microphone'; }
+ if (str.indexOf('phone') >= 0) { result = 'Phone'; }
+ if (str.indexOf('controll') >= 0) { result = 'Controller'; }
+ if (str.indexOf('line o') >= 0) { result = 'Line Out'; }
+ if (str.indexOf('digital o') >= 0) { result = 'Digital Out'; }
+ if (str.indexOf('smart sound technology') >= 0) { result = 'Digital Signal Processor'; }
+ if (str.indexOf('high definition audio') >= 0) { result = 'Sound Driver'; }
- // Upon either sending or receiving a Close control frame, it is said
- // that _The WebSocket Closing Handshake is Started_ and that the
- // WebSocket connection is in the CLOSING state.
- this[kReadyState] = states.CLOSING
- } else {
- // Otherwise
- // Set this's ready state to CLOSING (2).
- this[kReadyState] = WebSocket.CLOSING
- }
+ if (!result && output) {
+ result = 'Speaker';
+ } else if (!result && input) {
+ result = 'Microphone';
}
+ return result;
+}
- /**
- * @see https://websockets.spec.whatwg.org/#dom-websocket-send
- * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data
- */
- send (data) {
- webidl.brandCheck(this, WebSocket)
- webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' })
+function getLinuxAudioPci() {
+ let cmd = 'lspci -v 2>/dev/null';
+ let result = [];
+ try {
+ const parts = execSync(cmd, util.execOptsLinux).toString().split('\n\n');
+ parts.forEach(element => {
+ const lines = element.split('\n');
+ if (lines && lines.length && lines[0].toLowerCase().indexOf('audio') >= 0) {
+ const audio = {};
+ audio.slotId = lines[0].split(' ')[0];
+ audio.driver = util.getValue(lines, 'Kernel driver in use', ':', true) || util.getValue(lines, 'Kernel modules', ':', true);
+ result.push(audio);
+ }
+ });
+ return result;
+ } catch (e) {
+ return result;
+ }
+}
- data = webidl.converters.WebSocketSendData(data)
+function parseLinuxAudioPciMM(lines, audioPCI) {
+ const result = {};
+ const slotId = util.getValue(lines, 'Slot');
- // 1. If this's ready state is CONNECTING, then throw an
- // "InvalidStateError" DOMException.
- if (this[kReadyState] === WebSocket.CONNECTING) {
- throw new DOMException('Sent before connected.', 'InvalidStateError')
- }
+ const pciMatch = audioPCI.filter(function (item) { return item.slotId === slotId; });
- // 2. Run the appropriate set of steps from the following list:
- // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1
- // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2
+ result.id = slotId;
+ result.name = util.getValue(lines, 'SDevice');
+ result.manufacturer = util.getValue(lines, 'SVendor');
+ result.revision = util.getValue(lines, 'Rev');
+ result.driver = pciMatch && pciMatch.length === 1 && pciMatch[0].driver ? pciMatch[0].driver : '';
+ result.default = null;
+ result.channel = 'PCIe';
+ result.type = parseAudioType(result.name, null, null);
+ result.in = null;
+ result.out = null;
+ result.status = 'online';
- if (!isEstablished(this) || isClosing(this)) {
- return
- }
+ return result;
+}
- /** @type {import('stream').Duplex} */
- const socket = this[kResponse].socket
+function parseDarwinChannel(str) {
+ let result = '';
- // If data is a string
- if (typeof data === 'string') {
- // If the WebSocket connection is established and the WebSocket
- // closing handshake has not yet started, then the user agent
- // must send a WebSocket Message comprised of the data argument
- // using a text frame opcode; if the data cannot be sent, e.g.
- // because it would need to be buffered but the buffer is full,
- // the user agent must flag the WebSocket as full and then close
- // the WebSocket connection. Any invocation of this method with a
- // string argument that does not throw an exception must increase
- // the bufferedAmount attribute by the number of bytes needed to
- // express the argument as UTF-8.
+ if (str.indexOf('builtin') >= 0) { result = 'Built-In'; }
+ if (str.indexOf('extern') >= 0) { result = 'Audio-Jack'; }
+ if (str.indexOf('hdmi') >= 0) { result = 'HDMI'; }
+ if (str.indexOf('displayport') >= 0) { result = 'Display-Port'; }
+ if (str.indexOf('usb') >= 0) { result = 'USB'; }
+ if (str.indexOf('pci') >= 0) { result = 'PCIe'; }
- const value = Buffer.from(data)
- const frame = new WebsocketFrameSend(value)
- const buffer = frame.createFrame(opcodes.TEXT)
+ return result;
+}
- this.#bufferedAmount += value.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= value.byteLength
- })
- } else if (types.isArrayBuffer(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need
- // to be buffered but the buffer is full, the user agent must flag
- // the WebSocket as full and then close the WebSocket connection.
- // The data to be sent is the data stored in the buffer described
- // by the ArrayBuffer object. Any invocation of this method with an
- // ArrayBuffer argument that does not throw an exception must
- // increase the bufferedAmount attribute by the length of the
- // ArrayBuffer in bytes.
+function parseDarwinAudio(audioObject, id) {
+ const result = {};
+ const channelStr = ((audioObject.coreaudio_device_transport || '') + ' ' + (audioObject._name || '')).toLowerCase();
+
+ result.id = id;
+ result.name = audioObject._name;
+ result.manufacturer = audioObject.coreaudio_device_manufacturer;
+ result.revision = null;
+ result.driver = null;
+ result.default = !!(audioObject.coreaudio_default_audio_input_device || '') || !!(audioObject.coreaudio_default_audio_output_device || '');
+ result.channel = parseDarwinChannel(channelStr);
+ result.type = parseAudioType(result.name, !!(audioObject.coreaudio_device_input || ''), !!(audioObject.coreaudio_device_output || ''));
+ result.in = !!(audioObject.coreaudio_device_input || '');
+ result.out = !!(audioObject.coreaudio_device_output || '');
+ result.status = 'online';
+
+ return result;
+}
+
+function parseWindowsAudio(lines) {
+ const result = {};
+ const status = util.getValue(lines, 'StatusInfo', ':');
+
+ result.id = util.getValue(lines, 'DeviceID', ':'); // PNPDeviceID??
+ result.name = util.getValue(lines, 'name', ':');
+ result.manufacturer = util.getValue(lines, 'manufacturer', ':');
+ result.revision = null;
+ result.driver = null;
+ result.default = null;
+ result.channel = null;
+ result.type = parseAudioType(result.name, null, null);
+ result.in = null;
+ result.out = null;
+ result.status = status;
+
+ return result;
+}
- const value = Buffer.from(data)
- const frame = new WebsocketFrameSend(value)
- const buffer = frame.createFrame(opcodes.BINARY)
+function audio(callback) {
- this.#bufferedAmount += value.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= value.byteLength
- })
- } else if (ArrayBuffer.isView(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need to
- // be buffered but the buffer is full, the user agent must flag the
- // WebSocket as full and then close the WebSocket connection. The
- // data to be sent is the data stored in the section of the buffer
- // described by the ArrayBuffer object that data references. Any
- // invocation of this method with this kind of argument that does
- // not throw an exception must increase the bufferedAmount attribute
- // by the length of data’s buffer in bytes.
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = [];
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ let cmd = 'lspci -vmm 2>/dev/null';
+ exec(cmd, function (error, stdout) {
+ // PCI
+ if (!error) {
+ const audioPCI = getLinuxAudioPci();
+ const parts = stdout.toString().split('\n\n');
+ parts.forEach(element => {
+ const lines = element.split('\n');
+ if (util.getValue(lines, 'class', ':', true).toLowerCase().indexOf('audio') >= 0) {
+ const audio = parseLinuxAudioPciMM(lines, audioPCI);
+ result.push(audio);
+ }
+ });
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ let cmd = 'system_profiler SPAudioDataType -json';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ try {
+ const outObj = JSON.parse(stdout.toString());
+ if (outObj.SPAudioDataType && outObj.SPAudioDataType.length && outObj.SPAudioDataType[0] && outObj.SPAudioDataType[0]['_items'] && outObj.SPAudioDataType[0]['_items'].length) {
+ for (let i = 0; i < outObj.SPAudioDataType[0]['_items'].length; i++) {
+ const audio = parseDarwinAudio(outObj.SPAudioDataType[0]['_items'][i], i);
+ result.push(audio);
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_windows) {
+ util.powerShell('Get-CimInstance Win32_SoundDevice | select DeviceID,StatusInfo,Name,Manufacturer | fl').then((stdout, error) => {
+ if (!error) {
+ const parts = stdout.toString().split(/\n\s*\n/);
+ parts.forEach(element => {
+ const lines = element.split('\n');
+ if (util.getValue(lines, 'name', ':')) {
+ result.push(parseWindowsAudio(lines));
+ }
+ });
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ resolve(null);
+ }
+ });
+ });
+}
- const ab = Buffer.from(data, data.byteOffset, data.byteLength)
+exports.audio = audio;
- const frame = new WebsocketFrameSend(ab)
- const buffer = frame.createFrame(opcodes.BINARY)
- this.#bufferedAmount += ab.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= ab.byteLength
- })
- } else if (isBlobLike(data)) {
- // If the WebSocket connection is established, and the WebSocket
- // closing handshake has not yet started, then the user agent must
- // send a WebSocket Message comprised of data using a binary frame
- // opcode; if the data cannot be sent, e.g. because it would need to
- // be buffered but the buffer is full, the user agent must flag the
- // WebSocket as full and then close the WebSocket connection. The data
- // to be sent is the raw data represented by the Blob object. Any
- // invocation of this method with a Blob argument that does not throw
- // an exception must increase the bufferedAmount attribute by the size
- // of the Blob object’s raw data, in bytes.
+/***/ }),
- const frame = new WebsocketFrameSend()
+/***/ 63179:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
- data.arrayBuffer().then((ab) => {
- const value = Buffer.from(ab)
- frame.frameData = value
- const buffer = frame.createFrame(opcodes.BINARY)
- this.#bufferedAmount += value.byteLength
- socket.write(buffer, () => {
- this.#bufferedAmount -= value.byteLength
- })
- })
- }
- }
+// @ts-check;
+// ==================================================================================
+// battery.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 6. Battery
+// ----------------------------------------------------------------------------------
- get readyState () {
- webidl.brandCheck(this, WebSocket)
+const exec = (__nccwpck_require__(35317).exec);
+const fs = __nccwpck_require__(79896);
+const util = __nccwpck_require__(77496);
- // The readyState getter steps are to return this's ready state.
- return this[kReadyState]
- }
+let _platform = process.platform;
- get bufferedAmount () {
- webidl.brandCheck(this, WebSocket)
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
- return this.#bufferedAmount
+function parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity) {
+ const result = {};
+ let status = util.getValue(lines, 'BatteryStatus', ':').trim();
+ // 1 = "Discharging"
+ // 2 = "On A/C"
+ // 3 = "Fully Charged"
+ // 4 = "Low"
+ // 5 = "Critical"
+ // 6 = "Charging"
+ // 7 = "Charging High"
+ // 8 = "Charging Low"
+ // 9 = "Charging Critical"
+ // 10 = "Undefined"
+ // 11 = "Partially Charged"
+ if (status >= 0) {
+ const statusValue = status ? parseInt(status) : 0;
+ result.status = statusValue;
+ result.hasBattery = true;
+ result.maxCapacity = fullChargeCapacity || parseInt(util.getValue(lines, 'DesignCapacity', ':') || 0);
+ result.designedCapacity = parseInt(util.getValue(lines, 'DesignCapacity', ':') || designedCapacity);
+ result.voltage = parseInt(util.getValue(lines, 'DesignVoltage', ':') || 0) / 1000.0;
+ result.capacityUnit = 'mWh';
+ result.percent = parseInt(util.getValue(lines, 'EstimatedChargeRemaining', ':') || 0);
+ result.currentCapacity = parseInt(result.maxCapacity * result.percent / 100);
+ result.isCharging = (statusValue >= 6 && statusValue <= 9) || statusValue === 11 || ((statusValue !== 3) && (statusValue !== 1) && result.percent < 100);
+ result.acConnected = result.isCharging || statusValue === 2;
+ result.model = util.getValue(lines, 'DeviceID', ':');
+ } else {
+ result.status = -1;
}
- get url () {
- webidl.brandCheck(this, WebSocket)
+ return result;
+}
- // The url getter steps are to return this's url, serialized.
- return URLSerializer(this[kWebSocketURL])
- }
+module.exports = function (callback) {
- get extensions () {
- webidl.brandCheck(this, WebSocket)
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ hasBattery: false,
+ cycleCount: 0,
+ isCharging: false,
+ designedCapacity: 0,
+ maxCapacity: 0,
+ currentCapacity: 0,
+ voltage: 0,
+ capacityUnit: '',
+ percent: 0,
+ timeRemaining: null,
+ acConnected: true,
+ type: '',
+ model: '',
+ manufacturer: '',
+ serial: ''
+ };
- return this.#extensions
- }
+ if (_linux) {
+ let battery_path = '';
+ if (fs.existsSync('/sys/class/power_supply/BAT1/uevent')) {
+ battery_path = '/sys/class/power_supply/BAT1/';
+ } else if (fs.existsSync('/sys/class/power_supply/BAT0/uevent')) {
+ battery_path = '/sys/class/power_supply/BAT0/';
+ }
- get protocol () {
- webidl.brandCheck(this, WebSocket)
+ let acConnected = false;
+ let acPath = '';
+ if (fs.existsSync('/sys/class/power_supply/AC/online')) {
+ acPath = '/sys/class/power_supply/AC/online';
+ } else if (fs.existsSync('/sys/class/power_supply/AC0/online')) {
+ acPath = '/sys/class/power_supply/AC0/online';
+ }
- return this.#protocol
- }
+ if (acPath) {
+ const file = fs.readFileSync(acPath);
+ acConnected = file.toString().trim() === '1';
+ }
- get onopen () {
- webidl.brandCheck(this, WebSocket)
+ if (battery_path) {
+ fs.readFile(battery_path + 'uevent', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
- return this.#events.open
- }
+ result.isCharging = (util.getValue(lines, 'POWER_SUPPLY_STATUS', '=').toLowerCase() === 'charging');
+ result.acConnected = acConnected || result.isCharging;
+ result.voltage = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_VOLTAGE_NOW', '='), 10) / 1000000.0;
+ result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
+ result.cycleCount = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CYCLE_COUNT', '='), 10);
+ result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL', '=', true, true), 10) / 1000.0 * (result.voltage || 1));
+ const desingedMinVoltage = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_VOLTAGE_MIN_DESIGN', '='), 10) / 1000000.0;
+ result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_FULL_DESIGN', '=', true, true), 10) / 1000.0 * (desingedMinVoltage || result.voltage || 1));
+ result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10) / 1000.0 * (result.voltage || 1));
+ if (!result.maxCapacity) {
+ result.maxCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL', '=', true, true), 10) / 1000.0;
+ result.designedCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_FULL_DESIGN', '=', true, true), 10) / 1000.0 | result.maxCapacity;
+ result.currentCapacity = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10) / 1000.0;
+ }
+ const percent = util.getValue(lines, 'POWER_SUPPLY_CAPACITY', '=');
+ const energy = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_ENERGY_NOW', '='), 10);
+ const power = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_POWER_NOW', '='), 10);
+ const current = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CURRENT_NOW', '='), 10);
+ const charge = parseInt('0' + util.getValue(lines, 'POWER_SUPPLY_CHARGE_NOW', '='), 10);
- set onopen (fn) {
- webidl.brandCheck(this, WebSocket)
+ result.percent = parseInt('0' + percent, 10);
+ if (result.maxCapacity && result.currentCapacity) {
+ result.hasBattery = true;
+ if (!percent) {
+ result.percent = 100.0 * result.currentCapacity / result.maxCapacity;
+ }
+ }
+ if (result.isCharging) {
+ result.hasBattery = true;
+ }
+ if (energy && power) {
+ result.timeRemaining = Math.floor(energy / power * 60);
+ } else if (current && charge) {
+ result.timeRemaining = Math.floor(charge / current * 60);
+ } else if (current && result.currentCapacity) {
+ result.timeRemaining = Math.floor(result.currentCapacity / current * 60);
+ }
+ result.type = util.getValue(lines, 'POWER_SUPPLY_TECHNOLOGY', '=');
+ result.model = util.getValue(lines, 'POWER_SUPPLY_MODEL_NAME', '=');
+ result.manufacturer = util.getValue(lines, 'POWER_SUPPLY_MANUFACTURER', '=');
+ result.serial = util.getValue(lines, 'POWER_SUPPLY_SERIAL_NUMBER', '=');
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ exec('sysctl -i hw.acpi.battery hw.acpi.acline', function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ const batteries = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.units'), 10);
+ const percent = parseInt('0' + util.getValue(lines, 'hw.acpi.battery.life'), 10);
+ result.hasBattery = (batteries > 0);
+ result.cycleCount = null;
+ result.isCharging = util.getValue(lines, 'hw.acpi.acline') !== '1';
+ result.acConnected = result.isCharging;
+ result.maxCapacity = null;
+ result.currentCapacity = null;
+ result.capacityUnit = 'unknown';
+ result.percent = batteries ? percent : null;
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
- if (this.#events.open) {
- this.removeEventListener('open', this.#events.open)
- }
+ if (_darwin) {
+ exec('ioreg -n AppleSmartBattery -r | egrep "CycleCount|IsCharging|DesignCapacity|MaxCapacity|CurrentCapacity|DeviceName|BatterySerialNumber|Serial|TimeRemaining|Voltage"; pmset -g batt | grep %', function (error, stdout) {
+ if (stdout) {
+ let lines = stdout.toString().replace(/ +/g, '').replace(/"+/g, '').replace(/-/g, '').split('\n');
+ result.cycleCount = parseInt('0' + util.getValue(lines, 'cyclecount', '='), 10);
+ result.voltage = parseInt('0' + util.getValue(lines, 'voltage', '='), 10) / 1000.0;
+ result.capacityUnit = result.voltage ? 'mWh' : 'mAh';
+ result.maxCapacity = Math.round(parseInt('0' + util.getValue(lines, 'applerawmaxcapacity', '='), 10) * (result.voltage || 1));
+ result.currentCapacity = Math.round(parseInt('0' + util.getValue(lines, 'applerawcurrentcapacity', '='), 10) * (result.voltage || 1));
+ result.designedCapacity = Math.round(parseInt('0' + util.getValue(lines, 'DesignCapacity', '='), 10) * (result.voltage || 1));
+ result.manufacturer = 'Apple';
+ result.serial = util.getValue(lines, 'BatterySerialNumber', '=') || util.getValue(lines, 'Serial', '=');
+ result.model = util.getValue(lines, 'DeviceName', '=');
+ let percent = null;
+ const line = util.getValue(lines, 'internal', 'Battery');
+ let parts = line.split(';');
+ if (parts && parts[0]) {
+ let parts2 = parts[0].split('\t');
+ if (parts2 && parts2[1]) {
+ percent = parseFloat(parts2[1].trim().replace(/%/g, ''));
+ }
+ }
+ if (parts && parts[1]) {
+ result.isCharging = (parts[1].trim() === 'charging');
+ result.acConnected = (parts[1].trim() !== 'discharging');
+ } else {
+ result.isCharging = util.getValue(lines, 'ischarging', '=').toLowerCase() === 'yes';
+ result.acConnected = result.isCharging;
+ }
+ if (result.maxCapacity && result.currentCapacity) {
+ result.hasBattery = true;
+ result.type = 'Li-ion';
+ result.percent = percent !== null ? percent : Math.round(100.0 * result.currentCapacity / result.maxCapacity);
+ if (!result.isCharging) {
+ result.timeRemaining = parseInt('0' + util.getValue(lines, 'TimeRemaining', '='), 10);
+ }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_windows) {
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance Win32_Battery | select BatteryStatus, DesignCapacity, DesignVoltage, EstimatedChargeRemaining, DeviceID | fl'));
+ workload.push(util.powerShell('(Get-WmiObject -Class BatteryStaticData -Namespace ROOT/WMI).DesignedCapacity'));
+ workload.push(util.powerShell('(Get-CimInstance -Class BatteryFullChargedCapacity -Namespace ROOT/WMI).FullChargedCapacity'));
+ util.promiseAll(
+ workload
+ ).then((data) => {
+ if (data) {
+ let parts = data.results[0].split(/\n\s*\n/);
+ let batteries = [];
+ const hasValue = value => /\S/.test(value);
+ for (let i = 0; i < parts.length; i++) {
+ if (hasValue(parts[i]) && (!batteries.length || !hasValue(parts[i - 1]))) {
+ batteries.push([]);
+ }
+ if (hasValue(parts[i])) {
+ batteries[batteries.length - 1].push(parts[i]);
+ }
+ }
+ let designCapacities = data.results[1].split('\r\n').filter(e => e);
+ let fullChargeCapacities = data.results[2].split('\r\n').filter(e => e);
+ if (batteries.length) {
+ let first = false;
+ let additionalBatteries = [];
+ for (let i = 0; i < batteries.length; i++) {
+ let lines = batteries[i][0].split('\r\n');
+ const designedCapacity = designCapacities && designCapacities.length >= (i + 1) && designCapacities[i] ? util.toInt(designCapacities[i]) : 0;
+ const fullChargeCapacity = fullChargeCapacities && fullChargeCapacities.length >= (i + 1) && fullChargeCapacities[i] ? util.toInt(fullChargeCapacities[i]) : 0;
+ const parsed = parseWinBatteryPart(lines, designedCapacity, fullChargeCapacity);
+ if (!first && parsed.status > 0 && parsed.status !== 10) {
+ result.hasBattery = parsed.hasBattery;
+ result.maxCapacity = parsed.maxCapacity;
+ result.designedCapacity = parsed.designedCapacity;
+ result.voltage = parsed.voltage;
+ result.capacityUnit = parsed.capacityUnit;
+ result.percent = parsed.percent;
+ result.currentCapacity = parsed.currentCapacity;
+ result.isCharging = parsed.isCharging;
+ result.acConnected = parsed.acConnected;
+ result.model = parsed.model;
+ first = true;
+ } else if (parsed.status !== -1) {
+ additionalBatteries.push(
+ {
+ hasBattery: parsed.hasBattery,
+ maxCapacity: parsed.maxCapacity,
+ designedCapacity: parsed.designedCapacity,
+ voltage: parsed.voltage,
+ capacityUnit: parsed.capacityUnit,
+ percent: parsed.percent,
+ currentCapacity: parsed.currentCapacity,
+ isCharging: parsed.isCharging,
+ timeRemaining: null,
+ acConnected: parsed.acConnected,
+ model: parsed.model,
+ type: '',
+ manufacturer: '',
+ serial: ''
+ }
+ );
+ }
+ }
+ if (!first && additionalBatteries.length) {
+ result = additionalBatteries[0];
+ additionalBatteries.shift();
+ }
+ if (additionalBatteries.length) {
+ result.additionalBatteries = additionalBatteries;
+ }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ });
+ });
+};
- if (typeof fn === 'function') {
- this.#events.open = fn
- this.addEventListener('open', fn)
- } else {
- this.#events.open = null
- }
- }
- get onerror () {
- webidl.brandCheck(this, WebSocket)
+/***/ }),
- return this.#events.error
- }
+/***/ 6588:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
- set onerror (fn) {
- webidl.brandCheck(this, WebSocket)
- if (this.#events.error) {
- this.removeEventListener('error', this.#events.error)
- }
+// @ts-check
+// ==================================================================================
+// audio.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 17. bluetooth
+// ----------------------------------------------------------------------------------
- if (typeof fn === 'function') {
- this.#events.error = fn
- this.addEventListener('error', fn)
- } else {
- this.#events.error = null
- }
- }
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const path = __nccwpck_require__(16928);
+const util = __nccwpck_require__(77496);
+const bluetoothVendors = __nccwpck_require__(25173);
+const fs = __nccwpck_require__(79896);
- get onclose () {
- webidl.brandCheck(this, WebSocket)
+let _platform = process.platform;
- return this.#events.close
- }
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+
+function parseBluetoothType(str) {
+ let result = '';
+
+ if (str.indexOf('keyboard') >= 0) { result = 'Keyboard'; }
+ if (str.indexOf('mouse') >= 0) { result = 'Mouse'; }
+ if (str.indexOf('trackpad') >= 0) { result = 'Trackpad'; }
+ if (str.indexOf('speaker') >= 0) { result = 'Speaker'; }
+ if (str.indexOf('headset') >= 0) { result = 'Headset'; }
+ if (str.indexOf('phone') >= 0) { result = 'Phone'; }
+ if (str.indexOf('macbook') >= 0) { result = 'Computer'; }
+ if (str.indexOf('imac') >= 0) { result = 'Computer'; }
+ if (str.indexOf('ipad') >= 0) { result = 'Tablet'; }
+ if (str.indexOf('watch') >= 0) { result = 'Watch'; }
+ if (str.indexOf('headphone') >= 0) { result = 'Headset'; }
+ // to be continued ...
- set onclose (fn) {
- webidl.brandCheck(this, WebSocket)
+ return result;
+}
- if (this.#events.close) {
- this.removeEventListener('close', this.#events.close)
- }
+function parseBluetoothManufacturer(str) {
+ let result = str.split(' ')[0];
+ str = str.toLowerCase();
+ if (str.indexOf('apple') >= 0) { result = 'Apple'; }
+ if (str.indexOf('ipad') >= 0) { result = 'Apple'; }
+ if (str.indexOf('imac') >= 0) { result = 'Apple'; }
+ if (str.indexOf('iphone') >= 0) { result = 'Apple'; }
+ if (str.indexOf('magic mouse') >= 0) { result = 'Apple'; }
+ if (str.indexOf('magic track') >= 0) { result = 'Apple'; }
+ if (str.indexOf('macbook') >= 0) { result = 'Apple'; }
+ // to be continued ...
- if (typeof fn === 'function') {
- this.#events.close = fn
- this.addEventListener('close', fn)
- } else {
- this.#events.close = null
- }
- }
+ return result;
+}
- get onmessage () {
- webidl.brandCheck(this, WebSocket)
+function parseBluetoothVendor(str) {
+ const id = parseInt(str);
+ if (!isNaN(id)) return bluetoothVendors[id];
+}
- return this.#events.message
- }
+function parseLinuxBluetoothInfo(lines, macAddr1, macAddr2) {
+ const result = {};
- set onmessage (fn) {
- webidl.brandCheck(this, WebSocket)
+ result.device = null;
+ result.name = util.getValue(lines, 'name', '=');
+ result.manufacturer = null;
+ result.macDevice = macAddr1;
+ result.macHost = macAddr2;
+ result.batteryPercent = null;
+ result.type = parseBluetoothType(result.name.toLowerCase());
+ result.connected = false;
- if (this.#events.message) {
- this.removeEventListener('message', this.#events.message)
- }
+ return result;
+}
- if (typeof fn === 'function') {
- this.#events.message = fn
- this.addEventListener('message', fn)
- } else {
- this.#events.message = null
- }
- }
+function parseDarwinBluetoothDevices(bluetoothObject, macAddr2) {
+ const result = {};
+ const typeStr = ((bluetoothObject.device_minorClassOfDevice_string || bluetoothObject.device_majorClassOfDevice_string || bluetoothObject.device_minorType || '') + (bluetoothObject.device_name || '')).toLowerCase();
- get binaryType () {
- webidl.brandCheck(this, WebSocket)
+ result.device = bluetoothObject.device_services || '';
+ result.name = bluetoothObject.device_name || '';
+ result.manufacturer = bluetoothObject.device_manufacturer || parseBluetoothVendor(bluetoothObject.device_vendorID) || parseBluetoothManufacturer(bluetoothObject.device_name || '') || '';
+ result.macDevice = (bluetoothObject.device_addr || bluetoothObject.device_address || '').toLowerCase().replace(/-/g, ':');
+ result.macHost = macAddr2;
+ result.batteryPercent = bluetoothObject.device_batteryPercent || null;
+ result.type = parseBluetoothType(typeStr);
+ result.connected = bluetoothObject.device_isconnected === 'attrib_Yes' || false;
- return this[kBinaryType]
- }
+ return result;
+}
- set binaryType (type) {
- webidl.brandCheck(this, WebSocket)
+function parseWindowsBluetooth(lines) {
+ const result = {};
- if (type !== 'blob' && type !== 'arraybuffer') {
- this[kBinaryType] = 'blob'
- } else {
- this[kBinaryType] = type
- }
- }
+ result.device = null;
+ result.name = util.getValue(lines, 'name', ':');
+ result.manufacturer = util.getValue(lines, 'manufacturer', ':');
+ result.macDevice = null;
+ result.macHost = null;
+ result.batteryPercent = null;
+ result.type = parseBluetoothType(result.name.toLowerCase());
+ result.connected = null;
- /**
- * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
- */
- #onConnectionEstablished (response) {
- // processResponse is called when the "response’s header list has been received and initialized."
- // once this happens, the connection is open
- this[kResponse] = response
+ return result;
+}
- const parser = new ByteParser(this)
- parser.on('drain', function onParserDrain () {
- this.ws[kResponse].socket.resume()
- })
+function bluetoothDevices(callback) {
- response.socket.ws = this
- this[kByteParser] = parser
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = [];
+ if (_linux) {
+ // get files in /var/lib/bluetooth/ recursive
+ const btFiles = util.getFilesInPath('/var/lib/bluetooth/');
+ btFiles.forEach((element) => {
+ const filename = path.basename(element);
+ const pathParts = element.split('/');
+ const macAddr1 = pathParts.length >= 6 ? pathParts[pathParts.length - 2] : null;
+ const macAddr2 = pathParts.length >= 7 ? pathParts[pathParts.length - 3] : null;
+ if (filename === 'info') {
+ const infoFile = fs.readFileSync(element, { encoding: 'utf8' }).split('\n');
+ result.push(parseLinuxBluetoothInfo(infoFile, macAddr1, macAddr2));
+ }
+ });
+ // determine "connected" with hcitool con
+ try {
+ const hdicon = execSync('hcitool con', util.execOptsLinux).toString().toLowerCase();
+ for (let i = 0; i < result.length; i++) {
+ if (result[i].macDevice && result[i].macDevice.length > 10 && hdicon.indexOf(result[i].macDevice.toLowerCase()) >= 0) {
+ result[i].connected = true;
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
- // 1. Change the ready state to OPEN (1).
- this[kReadyState] = states.OPEN
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ if (_darwin) {
+ let cmd = 'system_profiler SPBluetoothDataType -json';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ try {
+ const outObj = JSON.parse(stdout.toString());
+ if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_title'] && outObj.SPBluetoothDataType[0]['device_title'].length) {
+ // missing: host BT Adapter macAddr ()
+ let macAddr2 = null;
+ if (outObj.SPBluetoothDataType[0]['local_device_title'] && outObj.SPBluetoothDataType[0].local_device_title.general_address) {
+ macAddr2 = outObj.SPBluetoothDataType[0].local_device_title.general_address.toLowerCase().replace(/-/g, ':');
+ }
+ outObj.SPBluetoothDataType[0]['device_title'].forEach((element) => {
+ const obj = element;
+ const objKey = Object.keys(obj);
+ if (objKey && objKey.length === 1) {
+ const innerObject = obj[objKey[0]];
+ innerObject.device_name = objKey[0];
+ const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
+ result.push(bluetoothDevice);
+ }
+ });
+ }
+ if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_connected'] && outObj.SPBluetoothDataType[0]['device_connected'].length) {
+ const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null;
+ outObj.SPBluetoothDataType[0]['device_connected'].forEach((element) => {
+ const obj = element;
+ const objKey = Object.keys(obj);
+ if (objKey && objKey.length === 1) {
+ const innerObject = obj[objKey[0]];
+ innerObject.device_name = objKey[0];
+ innerObject.device_isconnected = 'attrib_Yes';
+ const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
+ result.push(bluetoothDevice);
+ }
+ });
+ }
+ if (outObj.SPBluetoothDataType && outObj.SPBluetoothDataType.length && outObj.SPBluetoothDataType[0] && outObj.SPBluetoothDataType[0]['device_not_connected'] && outObj.SPBluetoothDataType[0]['device_not_connected'].length) {
+ const macAddr2 = outObj.SPBluetoothDataType[0].controller_properties && outObj.SPBluetoothDataType[0].controller_properties.controller_address ? outObj.SPBluetoothDataType[0].controller_properties.controller_address.toLowerCase().replace(/-/g, ':') : null;
+ outObj.SPBluetoothDataType[0]['device_not_connected'].forEach((element) => {
+ const obj = element;
+ const objKey = Object.keys(obj);
+ if (objKey && objKey.length === 1) {
+ const innerObject = obj[objKey[0]];
+ innerObject.device_name = objKey[0];
+ innerObject.device_isconnected = 'attrib_No';
+ const bluetoothDevice = parseDarwinBluetoothDevices(innerObject, macAddr2);
+ result.push(bluetoothDevice);
+ }
+ });
+ }
+ } catch (e) {
+ util.noop();
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_windows) {
+ util.powerShell('Get-CimInstance Win32_PNPEntity | select PNPClass, Name, Manufacturer | fl').then((stdout, error) => {
+ if (!error) {
+ const parts = stdout.toString().split(/\n\s*\n/);
+ parts.forEach((part) => {
+ if (util.getValue(part.split('\n'), 'PNPClass', ':') === 'Bluetooth') {
+ result.push(parseWindowsBluetooth(part.split('\n')));
+ }
+ });
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_freebsd || _netbsd || _openbsd || _sunos) {
+ resolve(null);
+ }
+ });
+ });
+}
- // 2. Change the extensions attribute’s value to the extensions in use, if
- // it is not the null value.
- // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
- const extensions = response.headersList.get('sec-websocket-extensions')
+exports.bluetoothDevices = bluetoothDevices;
- if (extensions !== null) {
- this.#extensions = extensions
- }
- // 3. Change the protocol attribute’s value to the subprotocol in use, if
- // it is not the null value.
- // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9
- const protocol = response.headersList.get('sec-websocket-protocol')
+/***/ }),
- if (protocol !== null) {
- this.#protocol = protocol
- }
+/***/ 25173:
+/***/ ((module) => {
- // 4. Fire an event named open at the WebSocket object.
- fireEvent('open', this)
- }
-}
-// https://websockets.spec.whatwg.org/#dom-websocket-connecting
-WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING
-// https://websockets.spec.whatwg.org/#dom-websocket-open
-WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN
-// https://websockets.spec.whatwg.org/#dom-websocket-closing
-WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING
-// https://websockets.spec.whatwg.org/#dom-websocket-closed
-WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED
+// @ts-check
+module.exports = {
+ 0x0000: 'Ericsson Technology Licensing',
+ 0x0001: 'Nokia Mobile Phones',
+ 0x0002: 'Intel Corp.',
+ 0x0003: 'IBM Corp.',
+ 0x0004: 'Toshiba Corp.',
+ 0x0005: '3Com',
+ 0x0006: 'Microsoft',
+ 0x0007: 'Lucent',
+ 0x0008: 'Motorola',
+ 0x0009: 'Infineon Technologies AG',
+ 0x000a: 'Cambridge Silicon Radio',
+ 0x000b: 'Silicon Wave',
+ 0x000c: 'Digianswer A/S',
+ 0x000d: 'Texas Instruments Inc.',
+ 0x000e: 'Ceva, Inc. (formerly Parthus Technologies, Inc.)',
+ 0x000f: 'Broadcom Corporation',
+ 0x0010: 'Mitel Semiconductor',
+ 0x0011: 'Widcomm, Inc',
+ 0x0012: 'Zeevo, Inc.',
+ 0x0013: 'Atmel Corporation',
+ 0x0014: 'Mitsubishi Electric Corporation',
+ 0x0015: 'RTX Telecom A/S',
+ 0x0016: 'KC Technology Inc.',
+ 0x0017: 'NewLogic',
+ 0x0018: 'Transilica, Inc.',
+ 0x0019: 'Rohde & Schwarz GmbH & Co. KG',
+ 0x001a: 'TTPCom Limited',
+ 0x001b: 'Signia Technologies, Inc.',
+ 0x001c: 'Conexant Systems Inc.',
+ 0x001d: 'Qualcomm',
+ 0x001e: 'Inventel',
+ 0x001f: 'AVM Berlin',
+ 0x0020: 'BandSpeed, Inc.',
+ 0x0021: 'Mansella Ltd',
+ 0x0022: 'NEC Corporation',
+ 0x0023: 'WavePlus Technology Co., Ltd.',
+ 0x0024: 'Alcatel',
+ 0x0025: 'NXP Semiconductors (formerly Philips Semiconductors)',
+ 0x0026: 'C Technologies',
+ 0x0027: 'Open Interface',
+ 0x0028: 'R F Micro Devices',
+ 0x0029: 'Hitachi Ltd',
+ 0x002a: 'Symbol Technologies, Inc.',
+ 0x002b: 'Tenovis',
+ 0x002c: 'Macronix International Co. Ltd.',
+ 0x002d: 'GCT Semiconductor',
+ 0x002e: 'Norwood Systems',
+ 0x002f: 'MewTel Technology Inc.',
+ 0x0030: 'ST Microelectronics',
+ 0x0031: 'Synopsis',
+ 0x0032: 'Red-M (Communications) Ltd',
+ 0x0033: 'Commil Ltd',
+ 0x0034: 'Computer Access Technology Corporation (CATC)',
+ 0x0035: 'Eclipse (HQ Espana) S.L.',
+ 0x0036: 'Renesas Electronics Corporation',
+ 0x0037: 'Mobilian Corporation',
+ 0x0038: 'Terax',
+ 0x0039: 'Integrated System Solution Corp.',
+ 0x003a: 'Matsushita Electric Industrial Co., Ltd.',
+ 0x003b: 'Gennum Corporation',
+ 0x003c: 'BlackBerry Limited (formerly Research In Motion)',
+ 0x003d: 'IPextreme, Inc.',
+ 0x003e: 'Systems and Chips, Inc.',
+ 0x003f: 'Bluetooth SIG, Inc.',
+ 0x0040: 'Seiko Epson Corporation',
+ 0x0041: 'Integrated Silicon Solution Taiwan, Inc.',
+ 0x0042: 'CONWISE Technology Corporation Ltd',
+ 0x0043: 'PARROT SA',
+ 0x0044: 'Socket Mobile',
+ 0x0045: 'Atheros Communications, Inc.',
+ 0x0046: 'MediaTek, Inc.',
+ 0x0047: 'Bluegiga',
+ 0x0048: 'Marvell Technology Group Ltd.',
+ 0x0049: '3DSP Corporation',
+ 0x004a: 'Accel Semiconductor Ltd.',
+ 0x004b: 'Continental Automotive Systems',
+ 0x004c: 'Apple, Inc.',
+ 0x004d: 'Staccato Communications, Inc.',
+ 0x004e: 'Avago Technologies',
+ 0x004f: 'APT Licensing Ltd.',
+ 0x0050: 'SiRF Technology',
+ 0x0051: 'Tzero Technologies, Inc.',
+ 0x0052: 'J&M Corporation',
+ 0x0053: 'Free2move AB',
+ 0x0054: '3DiJoy Corporation',
+ 0x0055: 'Plantronics, Inc.',
+ 0x0056: 'Sony Ericsson Mobile Communications',
+ 0x0057: 'Harman International Industries, Inc.',
+ 0x0058: 'Vizio, Inc.',
+ 0x0059: 'Nordic Semiconductor ASA',
+ 0x005a: 'EM Microelectronic-Marin SA',
+ 0x005b: 'Ralink Technology Corporation',
+ 0x005c: 'Belkin International, Inc.',
+ 0x005d: 'Realtek Semiconductor Corporation',
+ 0x005e: 'Stonestreet One, LLC',
+ 0x005f: 'Wicentric, Inc.',
+ 0x0060: 'RivieraWaves S.A.S',
+ 0x0061: 'RDA Microelectronics',
+ 0x0062: 'Gibson Guitars',
+ 0x0063: 'MiCommand Inc.',
+ 0x0064: 'Band XI International, LLC',
+ 0x0065: 'Hewlett-Packard Company',
+ 0x0066: '9Solutions Oy',
+ 0x0067: 'GN Netcom A/S',
+ 0x0068: 'General Motors',
+ 0x0069: 'A&D Engineering, Inc.',
+ 0x006a: 'MindTree Ltd.',
+ 0x006b: 'Polar Electro OY',
+ 0x006c: 'Beautiful Enterprise Co., Ltd.',
+ 0x006d: 'BriarTek, Inc.',
+ 0x006e: 'Summit Data Communications, Inc.',
+ 0x006f: 'Sound ID',
+ 0x0070: 'Monster, LLC',
+ 0x0071: 'connectBlue AB',
+ 0x0072: 'ShangHai Super Smart Electronics Co. Ltd.',
+ 0x0073: 'Group Sense Ltd.',
+ 0x0074: 'Zomm, LLC',
+ 0x0075: 'Samsung Electronics Co. Ltd.',
+ 0x0076: 'Creative Technology Ltd.',
+ 0x0077: 'Laird Technologies',
+ 0x0078: 'Nike, Inc.',
+ 0x0079: 'lesswire AG',
+ 0x007a: 'MStar Semiconductor, Inc.',
+ 0x007b: 'Hanlynn Technologies',
+ 0x007c: 'A & R Cambridge',
+ 0x007d: 'Seers Technology Co. Ltd',
+ 0x007e: 'Sports Tracking Technologies Ltd.',
+ 0x007f: 'Autonet Mobile',
+ 0x0080: 'DeLorme Publishing Company, Inc.',
+ 0x0081: 'WuXi Vimicro',
+ 0x0082: 'Sennheiser Communications A/S',
+ 0x0083: 'TimeKeeping Systems, Inc.',
+ 0x0084: 'Ludus Helsinki Ltd.',
+ 0x0085: 'BlueRadios, Inc.',
+ 0x0086: 'equinox AG',
+ 0x0087: 'Garmin International, Inc.',
+ 0x0088: 'Ecotest',
+ 0x0089: 'GN ReSound A/S',
+ 0x008a: 'Jawbone',
+ 0x008b: 'Topcorn Positioning Systems, LLC',
+ 0x008c: 'Gimbal Inc. (formerly Qualcomm Labs, Inc. and Qualcomm Retail Solutions, Inc.)',
+ 0x008d: 'Zscan Software',
+ 0x008e: 'Quintic Corp.',
+ 0x008f: 'Stollman E+V GmbH',
+ 0x0090: 'Funai Electric Co., Ltd.',
+ 0x0091: 'Advanced PANMOBIL Systems GmbH & Co. KG',
+ 0x0092: 'ThinkOptics, Inc.',
+ 0x0093: 'Universal Electronics, Inc.',
+ 0x0094: 'Airoha Technology Corp.',
+ 0x0095: 'NEC Lighting, Ltd.',
+ 0x0096: 'ODM Technology, Inc.',
+ 0x0097: 'ConnecteDevice Ltd.',
+ 0x0098: 'zer01.tv GmbH',
+ 0x0099: 'i.Tech Dynamic Global Distribution Ltd.',
+ 0x009a: 'Alpwise',
+ 0x009b: 'Jiangsu Toppower Automotive Electronics Co., Ltd.',
+ 0x009c: 'Colorfy, Inc.',
+ 0x009d: 'Geoforce Inc.',
+ 0x009e: 'Bose Corporation',
+ 0x009f: 'Suunto Oy',
+ 0x00a0: 'Kensington Computer Products Group',
+ 0x00a1: 'SR-Medizinelektronik',
+ 0x00a2: 'Vertu Corporation Limited',
+ 0x00a3: 'Meta Watch Ltd.',
+ 0x00a4: 'LINAK A/S',
+ 0x00a5: 'OTL Dynamics LLC',
+ 0x00a6: 'Panda Ocean Inc.',
+ 0x00a7: 'Visteon Corporation',
+ 0x00a8: 'ARP Devices Limited',
+ 0x00a9: 'Magneti Marelli S.p.A',
+ 0x00aa: 'CAEN RFID srl',
+ 0x00ab: 'Ingenieur-Systemgruppe Zahn GmbH',
+ 0x00ac: 'Green Throttle Games',
+ 0x00ad: 'Peter Systemtechnik GmbH',
+ 0x00ae: 'Omegawave Oy',
+ 0x00af: 'Cinetix',
+ 0x00b0: 'Passif Semiconductor Corp',
+ 0x00b1: 'Saris Cycling Group, Inc',
+ 0x00b2: 'Bekey A/S',
+ 0x00b3: 'Clarinox Technologies Pty. Ltd.',
+ 0x00b4: 'BDE Technology Co., Ltd.',
+ 0x00b5: 'Swirl Networks',
+ 0x00b6: 'Meso international',
+ 0x00b7: 'TreLab Ltd',
+ 0x00b8: 'Qualcomm Innovation Center, Inc. (QuIC)',
+ 0x00b9: 'Johnson Controls, Inc.',
+ 0x00ba: 'Starkey Laboratories Inc.',
+ 0x00bb: 'S-Power Electronics Limited',
+ 0x00bc: 'Ace Sensor Inc',
+ 0x00bd: 'Aplix Corporation',
+ 0x00be: 'AAMP of America',
+ 0x00bf: 'Stalmart Technology Limited',
+ 0x00c0: 'AMICCOM Electronics Corporation',
+ 0x00c1: 'Shenzhen Excelsecu Data Technology Co.,Ltd',
+ 0x00c2: 'Geneq Inc.',
+ 0x00c3: 'adidas AG',
+ 0x00c4: 'LG Electronics',
+ 0x00c5: 'Onset Computer Corporation',
+ 0x00c6: 'Selfly BV',
+ 0x00C7: 'Quuppa Oy.',
+ 0x00C8: 'GeLo Inc',
+ 0x00C9: 'Evluma',
+ 0x00CA: 'MC10',
+ 0x00CB: 'Binauric SE',
+ 0x00CC: 'Beats Electronics',
+ 0x00CD: 'Microchip Technology Inc.',
+ 0x00CE: 'Elgato Systems GmbH',
+ 0x00CF: 'ARCHOS SA',
+ 0x00D0: 'Dexcom, Inc.',
+ 0x00D1: 'Polar Electro Europe B.V.',
+ 0x00D2: 'Dialog Semiconductor B.V.',
+ 0x00D3: 'Taixingbang Technology (HK) Co,. LTD.',
+ 0x00D4: 'Kawantech',
+ 0x00D5: 'Austco Communication Systems',
+ 0x00D6: 'Timex Group USA, Inc.',
+ 0x00D7: 'Qualcomm Technologies, Inc.',
+ 0x00D8: 'Qualcomm Connected Experiences, Inc.',
+ 0x00D9: 'Voyetra Turtle Beach',
+ 0x00DA: 'txtr GmbH',
+ 0x00DB: 'Biosentronics',
+ 0x00DC: 'Procter & Gamble',
+ 0x00DD: 'Hosiden Corporation',
+ 0x00DE: 'Muzik LLC',
+ 0x00DF: 'Misfit Wearables Corp',
+ 0x00E0: 'Google',
+ 0x00E1: 'Danlers Ltd',
+ 0x00E2: 'Semilink Inc',
+ 0x00E3: 'inMusic Brands, Inc',
+ 0x00E4: 'L.S. Research Inc.',
+ 0x00E5: 'Eden Software Consultants Ltd.',
+ 0x00E6: 'Freshtemp',
+ 0x00e7: 'KS Technologies',
+ 0x00e8: 'ACTS Technologies',
+ 0x00e9: 'Vtrack Systems',
+ 0x00ea: 'Nielsen-Kellerman Company',
+ 0x00eb: 'Server Technology, Inc.',
+ 0x00ec: 'BioResearch Associates',
+ 0x00ed: 'Jolly Logic, LLC',
+ 0x00ee: 'Above Average Outcomes, Inc.',
+ 0x00ef: 'Bitsplitters GmbH',
+ 0x00f0: 'PayPal, Inc.',
+ 0x00f1: 'Witron Technology Limited',
+ 0x00f2: 'Aether Things Inc. (formerly Morse Project Inc.)',
+ 0x00f3: 'Kent Displays Inc.',
+ 0x00f4: 'Nautilus Inc.',
+ 0x00f5: 'Smartifier Oy',
+ 0x00f6: 'Elcometer Limited',
+ 0x00f7: 'VSN Technologies Inc.',
+ 0x00f8: 'AceUni Corp., Ltd.',
+ 0x00f9: 'StickNFind',
+ 0x00fa: 'Crystal Code AB',
+ 0x00fb: 'KOUKAAM a.s.',
+ 0x00fc: 'Delphi Corporation',
+ 0x00fd: 'ValenceTech Limited',
+ 0x00fe: 'Reserved',
+ 0x00ff: 'Typo Products, LLC',
+ 0x0100: 'TomTom International BV',
+ 0x0101: 'Fugoo, Inc',
+ 0x0102: 'Keiser Corporation',
+ 0x0103: 'Bang & Olufsen A/S',
+ 0x0104: 'PLUS Locations Systems Pty Ltd',
+ 0x0105: 'Ubiquitous Computing Technology Corporation',
+ 0x0106: 'Innovative Yachtter Solutions',
+ 0x0107: 'William Demant Holding A/S',
+ 0x0108: 'Chicony Electronics Co., Ltd.',
+ 0x0109: 'Atus BV',
+ 0x010a: 'Codegate Ltd.',
+ 0x010b: 'ERi, Inc.',
+ 0x010c: 'Transducers Direct, LLC',
+ 0x010d: 'Fujitsu Ten Limited',
+ 0x010e: 'Audi AG',
+ 0x010f: 'HiSilicon Technologies Co., Ltd.',
+ 0x0110: 'Nippon Seiki Co., Ltd.',
+ 0x0111: 'Steelseries ApS',
+ 0x0112: 'vyzybl Inc.',
+ 0x0113: 'Openbrain Technologies, Co., Ltd.',
+ 0x0114: 'Xensr',
+ 0x0115: 'e.solutions',
+ 0x0116: '1OAK Technologies',
+ 0x0117: 'Wimoto Technologies Inc',
+ 0x0118: 'Radius Networks, Inc.',
+ 0x0119: 'Wize Technology Co., Ltd.',
+ 0x011a: 'Qualcomm Labs, Inc.',
+ 0x011b: 'Aruba Networks',
+ 0x011c: 'Baidu',
+ 0x011d: 'Arendi AG',
+ 0x011e: 'Skoda Auto a.s.',
+ 0x011f: 'Volkswagon AG',
+ 0x0120: 'Porsche AG',
+ 0x0121: 'Sino Wealth Electronic Ltd.',
+ 0x0122: 'AirTurn, Inc.',
+ 0x0123: 'Kinsa, Inc.',
+ 0x0124: 'HID Global',
+ 0x0125: 'SEAT es',
+ 0x0126: 'Promethean Ltd.',
+ 0x0127: 'Salutica Allied Solutions',
+ 0x0128: 'GPSI Group Pty Ltd',
+ 0x0129: 'Nimble Devices Oy',
+ 0x012a: 'Changzhou Yongse Infotech Co., Ltd',
+ 0x012b: 'SportIQ',
+ 0x012c: 'TEMEC Instruments B.V.',
+ 0x012d: 'Sony Corporation',
+ 0x012e: 'ASSA ABLOY',
+ 0x012f: 'Clarion Co., Ltd.',
+ 0x0130: 'Warehouse Innovations',
+ 0x0131: 'Cypress Semiconductor Corporation',
+ 0x0132: 'MADS Inc',
+ 0x0133: 'Blue Maestro Limited',
+ 0x0134: 'Resolution Products, Inc.',
+ 0x0135: 'Airewear LLC',
+ 0x0136: 'Seed Labs, Inc. (formerly ETC sp. z.o.o.)',
+ 0x0137: 'Prestigio Plaza Ltd.',
+ 0x0138: 'NTEO Inc.',
+ 0x0139: 'Focus Systems Corporation',
+ 0x013a: 'Tencent Holdings Limited',
+ 0x013b: 'Allegion',
+ 0x013c: 'Murata Manufacuring Co., Ltd.',
+ 0x013e: 'Nod, Inc.',
+ 0x013f: 'B&B Manufacturing Company',
+ 0x0140: 'Alpine Electronics (China) Co., Ltd',
+ 0x0141: 'FedEx Services',
+ 0x0142: 'Grape Systems Inc.',
+ 0x0143: 'Bkon Connect',
+ 0x0144: 'Lintech GmbH',
+ 0x0145: 'Novatel Wireless',
+ 0x0146: 'Ciright',
+ 0x0147: 'Mighty Cast, Inc.',
+ 0x0148: 'Ambimat Electronics',
+ 0x0149: 'Perytons Ltd.',
+ 0x014a: 'Tivoli Audio, LLC',
+ 0x014b: 'Master Lock',
+ 0x014c: 'Mesh-Net Ltd',
+ 0x014d: 'Huizhou Desay SV Automotive CO., LTD.',
+ 0x014e: 'Tangerine, Inc.',
+ 0x014f: 'B&W Group Ltd.',
+ 0x0150: 'Pioneer Corporation',
+ 0x0151: 'OnBeep',
+ 0x0152: 'Vernier Software & Technology',
+ 0x0153: 'ROL Ergo',
+ 0x0154: 'Pebble Technology',
+ 0x0155: 'NETATMO',
+ 0x0156: 'Accumulate AB',
+ 0x0157: 'Anhui Huami Information Technology Co., Ltd.',
+ 0x0158: 'Inmite s.r.o.',
+ 0x0159: 'ChefSteps, Inc.',
+ 0x015a: 'micas AG',
+ 0x015b: 'Biomedical Research Ltd.',
+ 0x015c: 'Pitius Tec S.L.',
+ 0x015d: 'Estimote, Inc.',
+ 0x015e: 'Unikey Technologies, Inc.',
+ 0x015f: 'Timer Cap Co.',
+ 0x0160: 'AwoX',
+ 0x0161: 'yikes',
+ 0x0162: 'MADSGlobal NZ Ltd.',
+ 0x0163: 'PCH International',
+ 0x0164: 'Qingdao Yeelink Information Technology Co., Ltd.',
+ 0x0165: 'Milwaukee Tool (formerly Milwaukee Electric Tools)',
+ 0x0166: 'MISHIK Pte Ltd',
+ 0x0167: 'Bayer HealthCare',
+ 0x0168: 'Spicebox LLC',
+ 0x0169: 'emberlight',
+ 0x016a: 'Cooper-Atkins Corporation',
+ 0x016b: 'Qblinks',
+ 0x016c: 'MYSPHERA',
+ 0x016d: 'LifeScan Inc',
+ 0x016e: 'Volantic AB',
+ 0x016f: 'Podo Labs, Inc',
+ 0x0170: 'Roche Diabetes Care AG',
+ 0x0171: 'Amazon Fulfillment Service',
+ 0x0172: 'Connovate Technology Private Limited',
+ 0x0173: 'Kocomojo, LLC',
+ 0x0174: 'Everykey LLC',
+ 0x0175: 'Dynamic Controls',
+ 0x0176: 'SentriLock',
+ 0x0177: 'I-SYST inc.',
+ 0x0178: 'CASIO COMPUTER CO., LTD.',
+ 0x0179: 'LAPIS Semiconductor Co., Ltd.',
+ 0x017a: 'Telemonitor, Inc.',
+ 0x017b: 'taskit GmbH',
+ 0x017c: 'Daimler AG',
+ 0x017d: 'BatAndCat',
+ 0x017e: 'BluDotz Ltd',
+ 0x017f: 'XTel ApS',
+ 0x0180: 'Gigaset Communications GmbH',
+ 0x0181: 'Gecko Health Innovations, Inc.',
+ 0x0182: 'HOP Ubiquitous',
+ 0x0183: 'To Be Assigned',
+ 0x0184: 'Nectar',
+ 0x0185: 'bel’apps LLC',
+ 0x0186: 'CORE Lighting Ltd',
+ 0x0187: 'Seraphim Sense Ltd',
+ 0x0188: 'Unico RBC',
+ 0x0189: 'Physical Enterprises Inc.',
+ 0x018a: 'Able Trend Technology Limited',
+ 0x018b: 'Konica Minolta, Inc.',
+ 0x018c: 'Wilo SE',
+ 0x018d: 'Extron Design Services',
+ 0x018e: 'Fitbit, Inc.',
+ 0x018f: 'Fireflies Systems',
+ 0x0190: 'Intelletto Technologies Inc.',
+ 0x0191: 'FDK CORPORATION',
+ 0x0192: 'Cloudleaf, Inc',
+ 0x0193: 'Maveric Automation LLC',
+ 0x0194: 'Acoustic Stream Corporation',
+ 0x0195: 'Zuli',
+ 0x0196: 'Paxton Access Ltd',
+ 0x0197: 'WiSilica Inc',
+ 0x0198: 'Vengit Limited',
+ 0x0199: 'SALTO SYSTEMS S.L.',
+ 0x019a: 'TRON Forum (formerly T-Engine Forum)',
+ 0x019b: 'CUBETECH s.r.o.',
+ 0x019c: 'Cokiya Incorporated',
+ 0x019d: 'CVS Health',
+ 0x019e: 'Ceruus',
+ 0x019f: 'Strainstall Ltd',
+ 0x01a0: 'Channel Enterprises (HK) Ltd.',
+ 0x01a1: 'FIAMM',
+ 0x01a2: 'GIGALANE.CO.,LTD',
+ 0x01a3: 'EROAD',
+ 0x01a4: 'Mine Safety Appliances',
+ 0x01a5: 'Icon Health and Fitness',
+ 0x01a6: 'Asandoo GmbH',
+ 0x01a7: 'ENERGOUS CORPORATION',
+ 0x01a8: 'Taobao',
+ 0x01a9: 'Canon Inc.',
+ 0x01aa: 'Geophysical Technology Inc.',
+ 0x01ab: 'Facebook, Inc.',
+ 0x01ac: 'Nipro Diagnostics, Inc.',
+ 0x01ad: 'FlightSafety International',
+ 0x01ae: 'Earlens Corporation',
+ 0x01af: 'Sunrise Micro Devices, Inc.',
+ 0x01b0: 'Star Micronics Co., Ltd.',
+ 0x01b1: 'Netizens Sp. z o.o.',
+ 0x01b2: 'Nymi Inc.',
+ 0x01b3: 'Nytec, Inc.',
+ 0x01b4: 'Trineo Sp. z o.o.',
+ 0x01b5: 'Nest Labs Inc.',
+ 0x01b6: 'LM Technologies Ltd',
+ 0x01b7: 'General Electric Company',
+ 0x01b8: 'i+D3 S.L.',
+ 0x01b9: 'HANA Micron',
+ 0x01ba: 'Stages Cycling LLC',
+ 0x01bb: 'Cochlear Bone Anchored Solutions AB',
+ 0x01bc: 'SenionLab AB',
+ 0x01bd: 'Syszone Co., Ltd',
+ 0x01be: 'Pulsate Mobile Ltd.',
+ 0x01bf: 'Hong Kong HunterSun Electronic Limited',
+ 0x01c0: 'pironex GmbH',
+ 0x01c1: 'BRADATECH Corp.',
+ 0x01c2: 'Transenergooil AG',
+ 0x01c3: 'Bunch',
+ 0x01c4: 'DME Microelectronics',
+ 0x01c5: 'Bitcraze AB',
+ 0x01c6: 'HASWARE Inc.',
+ 0x01c7: 'Abiogenix Inc.',
+ 0x01c8: 'Poly-Control ApS',
+ 0x01c9: 'Avi-on',
+ 0x01ca: 'Laerdal Medical AS',
+ 0x01cb: 'Fetch My Pet',
+ 0x01cc: 'Sam Labs Ltd.',
+ 0x01cd: 'Chengdu Synwing Technology Ltd',
+ 0x01ce: 'HOUWA SYSTEM DESIGN, k.k.',
+ 0x01cf: 'BSH',
+ 0x01d0: 'Primus Inter Pares Ltd',
+ 0x01d1: 'August',
+ 0x01d2: 'Gill Electronics',
+ 0x01d3: 'Sky Wave Design',
+ 0x01d4: 'Newlab S.r.l.',
+ 0x01d5: 'ELAD srl',
+ 0x01d6: 'G-wearables inc.',
+ 0x01d7: 'Squadrone Systems Inc.',
+ 0x01d8: 'Code Corporation',
+ 0x01d9: 'Savant Systems LLC',
+ 0x01da: 'Logitech International SA',
+ 0x01db: 'Innblue Consulting',
+ 0x01dc: 'iParking Ltd.',
+ 0x01dd: 'Koninklijke Philips Electronics N.V.',
+ 0x01de: 'Minelab Electronics Pty Limited',
+ 0x01df: 'Bison Group Ltd.',
+ 0x01e0: 'Widex A/S',
+ 0x01e1: 'Jolla Ltd',
+ 0x01e2: 'Lectronix, Inc.',
+ 0x01e3: 'Caterpillar Inc',
+ 0x01e4: 'Freedom Innovations',
+ 0x01e5: 'Dynamic Devices Ltd',
+ 0x01e6: 'Technology Solutions (UK) Ltd',
+ 0x01e7: 'IPS Group Inc.',
+ 0x01e8: 'STIR',
+ 0x01e9: 'Sano, Inc',
+ 0x01ea: 'Advanced Application Design, Inc.',
+ 0x01eb: 'AutoMap LLC',
+ 0x01ec: 'Spreadtrum Communications Shanghai Ltd',
+ 0x01ed: 'CuteCircuit LTD',
+ 0x01ee: 'Valeo Service',
+ 0x01ef: 'Fullpower Technologies, Inc.',
+ 0x01f0: 'KloudNation',
+ 0x01f1: 'Zebra Technologies Corporation',
+ 0x01f2: 'Itron, Inc.',
+ 0x01f3: 'The University of Tokyo',
+ 0x01f4: 'UTC Fire and Security',
+ 0x01f5: 'Cool Webthings Limited',
+ 0x01f6: 'DJO Global',
+ 0x01f7: 'Gelliner Limited',
+ 0x01f8: 'Anyka (Guangzhou) Microelectronics Technology Co, LTD',
+ 0x01f9: 'Medtronic, Inc.',
+ 0x01fa: 'Gozio, Inc.',
+ 0x01fb: 'Form Lifting, LLC',
+ 0x01fc: 'Wahoo Fitness, LLC',
+ 0x01fd: 'Kontakt Micro-Location Sp. z o.o.',
+ 0x01fe: 'Radio System Corporation',
+ 0x01ff: 'Freescale Semiconductor, Inc.',
+ 0x0200: 'Verifone Systems PTe Ltd. Taiwan Branch',
+ 0x0201: 'AR Timing',
+ 0x0202: 'Rigado LLC',
+ 0x0203: 'Kemppi Oy',
+ 0x0204: 'Tapcentive Inc.',
+ 0x0205: 'Smartbotics Inc.',
+ 0x0206: 'Otter Products, LLC',
+ 0x0207: 'STEMP Inc.',
+ 0x0208: 'LumiGeek LLC',
+ 0x0209: 'InvisionHeart Inc.',
+ 0x020A: 'Macnica Inc. ',
+ 0x020b: 'Jaguar Land Rover Limited',
+ 0x020c: 'CoroWare Technologies, Inc',
+ 0x020d: 'Simplo Technology Co., LTD',
+ 0x020e: 'Omron Healthcare Co., LTD',
+ 0x020f: 'Comodule GMBH',
+ 0x0210: 'ikeGPS',
+ 0x0211: 'Telink Semiconductor Co. Ltd',
+ 0x0212: 'Interplan Co., Ltd',
+ 0x0213: 'Wyler AG',
+ 0x0214: 'IK Multimedia Production srl',
+ 0x0215: 'Lukoton Experience Oy',
+ 0x0216: 'MTI Ltd',
+ 0x0217: 'Tech4home, Lda',
+ 0x0218: 'Hiotech AB',
+ 0x0219: 'DOTT Limited',
+ 0x021A: 'Blue Speck Labs, LLC',
+ 0x021B: 'Cisco Systems, Inc',
+ 0x021C: 'Mobicomm Inc',
+ 0x021D: 'Edamic',
+ 0x021E: 'Goodnet, Ltd',
+ 0x021F: 'Luster Leaf Products Inc',
+ 0x0220: 'Manus Machina BV',
+ 0x0221: 'Mobiquity Networks Inc',
+ 0x0222: 'Praxis Dynamics',
+ 0x0223: 'Philip Morris Products S.A.',
+ 0x0224: 'Comarch SA',
+ 0x0225: 'Nestl Nespresso S.A.',
+ 0x0226: 'Merlinia A/S',
+ 0x0227: 'LifeBEAM Technologies',
+ 0x0228: 'Twocanoes Labs, LLC',
+ 0x0229: 'Muoverti Limited',
+ 0x022A: 'Stamer Musikanlagen GMBH',
+ 0x022B: 'Tesla Motors',
+ 0x022C: 'Pharynks Corporation',
+ 0x022D: 'Lupine',
+ 0x022E: 'Siemens AG',
+ 0x022F: 'Huami (Shanghai) Culture Communication CO., LTD',
+ 0x0230: 'Foster Electric Company, Ltd',
+ 0x0231: 'ETA SA',
+ 0x0232: 'x-Senso Solutions Kft',
+ 0x0233: 'Shenzhen SuLong Communication Ltd',
+ 0x0234: 'FengFan (BeiJing) Technology Co, Ltd',
+ 0x0235: 'Qrio Inc',
+ 0x0236: 'Pitpatpet Ltd',
+ 0x0237: 'MSHeli s.r.l.',
+ 0x0238: 'Trakm8 Ltd',
+ 0x0239: 'JIN CO, Ltd',
+ 0x023A: 'Alatech Tehnology',
+ 0x023B: 'Beijing CarePulse Electronic Technology Co, Ltd',
+ 0x023C: 'Awarepoint',
+ 0x023D: 'ViCentra B.V.',
+ 0x023E: 'Raven Industries',
+ 0x023F: 'WaveWare Technologies Inc.',
+ 0x0240: 'Argenox Technologies',
+ 0x0241: 'Bragi GmbH',
+ 0x0242: '16Lab Inc',
+ 0x0243: 'Masimo Corp',
+ 0x0244: 'Iotera Inc',
+ 0x0245: 'Endress+Hauser',
+ 0x0246: 'ACKme Networks, Inc.',
+ 0x0247: 'FiftyThree Inc.',
+ 0x0248: 'Parker Hannifin Corp',
+ 0x0249: 'Transcranial Ltd',
+ 0x024A: 'Uwatec AG',
+ 0x024B: 'Orlan LLC',
+ 0x024C: 'Blue Clover Devices',
+ 0x024D: 'M-Way Solutions GmbH',
+ 0x024E: 'Microtronics Engineering GmbH',
+ 0x024F: 'Schneider Schreibgerte GmbH',
+ 0x0250: 'Sapphire Circuits LLC',
+ 0x0251: 'Lumo Bodytech Inc.',
+ 0x0252: 'UKC Technosolution',
+ 0x0253: 'Xicato Inc.',
+ 0x0254: 'Playbrush',
+ 0x0255: 'Dai Nippon Printing Co., Ltd.',
+ 0x0256: 'G24 Power Limited',
+ 0x0257: 'AdBabble Local Commerce Inc.',
+ 0x0258: 'Devialet SA',
+ 0x0259: 'ALTYOR',
+ 0x025A: 'University of Applied Sciences Valais/Haute Ecole Valaisanne',
+ 0x025B: 'Five Interactive, LLC dba Zendo',
+ 0x025C: 'NetEaseHangzhouNetwork co.Ltd.',
+ 0x025D: 'Lexmark International Inc.',
+ 0x025E: 'Fluke Corporation',
+ 0x025F: 'Yardarm Technologies',
+ 0x0260: 'SensaRx',
+ 0x0261: 'SECVRE GmbH',
+ 0x0262: 'Glacial Ridge Technologies',
+ 0x0263: 'Identiv, Inc.',
+ 0x0264: 'DDS, Inc.',
+ 0x0265: 'SMK Corporation',
+ 0x0266: 'Schawbel Technologies LLC',
+ 0x0267: 'XMI Systems SA',
+ 0x0268: 'Cerevo',
+ 0x0269: 'Torrox GmbH & Co KG',
+ 0x026A: 'Gemalto',
+ 0x026B: 'DEKA Research & Development Corp.',
+ 0x026C: 'Domster Tadeusz Szydlowski',
+ 0x026D: 'Technogym SPA',
+ 0x026E: 'FLEURBAEY BVBA',
+ 0x026F: 'Aptcode Solutions',
+ 0x0270: 'LSI ADL Technology',
+ 0x0271: 'Animas Corp',
+ 0x0272: 'Alps Electric Co., Ltd.',
+ 0x0273: 'OCEASOFT',
+ 0x0274: 'Motsai Research',
+ 0x0275: 'Geotab',
+ 0x0276: 'E.G.O. Elektro-Gertebau GmbH',
+ 0x0277: 'bewhere inc',
+ 0x0278: 'Johnson Outdoors Inc',
+ 0x0279: 'steute Schaltgerate GmbH & Co. KG',
+ 0x027A: 'Ekomini inc.',
+ 0x027B: 'DEFA AS',
+ 0x027C: 'Aseptika Ltd',
+ 0x027D: 'HUAWEI Technologies Co., Ltd. ( )',
+ 0x027E: 'HabitAware, LLC',
+ 0x027F: 'ruwido austria gmbh',
+ 0x0280: 'ITEC corporation',
+ 0x0281: 'StoneL',
+ 0x0282: 'Sonova AG',
+ 0x0283: 'Maven Machines, Inc.',
+ 0x0284: 'Synapse Electronics',
+ 0x0285: 'Standard Innovation Inc.',
+ 0x0286: 'RF Code, Inc.',
+ 0x0287: 'Wally Ventures S.L.',
+ 0x0288: 'Willowbank Electronics Ltd',
+ 0x0289: 'SK Telecom',
+ 0x028A: 'Jetro AS',
+ 0x028B: 'Code Gears LTD',
+ 0x028C: 'NANOLINK APS',
+ 0x028D: 'IF, LLC',
+ 0x028E: 'RF Digital Corp',
+ 0x028F: 'Church & Dwight Co., Inc',
+ 0x0290: 'Multibit Oy',
+ 0x0291: 'CliniCloud Inc',
+ 0x0292: 'SwiftSensors',
+ 0x0293: 'Blue Bite',
+ 0x0294: 'ELIAS GmbH',
+ 0x0295: 'Sivantos GmbH',
+ 0x0296: 'Petzl',
+ 0x0297: 'storm power ltd',
+ 0x0298: 'EISST Ltd',
+ 0x0299: 'Inexess Technology Simma KG',
+ 0x029A: 'Currant, Inc.',
+ 0x029B: 'C2 Development, Inc.',
+ 0x029C: 'Blue Sky Scientific, LLC',
+ 0x029D: 'ALOTTAZS LABS, LLC',
+ 0x029E: 'Kupson spol. s r.o.',
+ 0x029F: 'Areus Engineering GmbH',
+ 0x02A0: 'Impossible Camera GmbH',
+ 0x02A1: 'InventureTrack Systems',
+ 0x02A2: 'LockedUp',
+ 0x02A3: 'Itude',
+ 0x02A4: 'Pacific Lock Company',
+ 0x02A5: 'Tendyron Corporation ( )',
+ 0x02A6: 'Robert Bosch GmbH',
+ 0x02A7: 'Illuxtron international B.V.',
+ 0x02A8: 'miSport Ltd.',
+ 0x02A9: 'Chargelib',
+ 0x02AA: 'Doppler Lab',
+ 0x02AB: 'BBPOS Limited',
+ 0x02AC: 'RTB Elektronik GmbH & Co. KG',
+ 0x02AD: 'Rx Networks, Inc.',
+ 0x02AE: 'WeatherFlow, Inc.',
+ 0x02AF: 'Technicolor USA Inc.',
+ 0x02B0: 'Bestechnic(Shanghai),Ltd',
+ 0x02B1: 'Raden Inc',
+ 0x02B2: 'JouZen Oy',
+ 0x02B3: 'CLABER S.P.A.',
+ 0x02B4: 'Hyginex, Inc.',
+ 0x02B5: 'HANSHIN ELECTRIC RAILWAY CO.,LTD.',
+ 0x02B6: 'Schneider Electric',
+ 0x02B7: 'Oort Technologies LLC',
+ 0x02B8: 'Chrono Therapeutics',
+ 0x02B9: 'Rinnai Corporation',
+ 0x02BA: 'Swissprime Technologies AG',
+ 0x02BB: 'Koha.,Co.Ltd',
+ 0x02BC: 'Genevac Ltd',
+ 0x02BD: 'Chemtronics',
+ 0x02BE: 'Seguro Technology Sp. z o.o.',
+ 0x02BF: 'Redbird Flight Simulations',
+ 0x02C0: 'Dash Robotics',
+ 0x02C1: 'LINE Corporation',
+ 0x02C2: 'Guillemot Corporation',
+ 0x02C3: 'Techtronic Power Tools Technology Limited',
+ 0x02C4: 'Wilson Sporting Goods',
+ 0x02C5: 'Lenovo (Singapore) Pte Ltd. ( )',
+ 0x02C6: 'Ayatan Sensors',
+ 0x02C7: 'Electronics Tomorrow Limited',
+ 0x02C8: 'VASCO Data Security International, Inc.',
+ 0x02C9: 'PayRange Inc.',
+ 0x02CA: 'ABOV Semiconductor',
+ 0x02CB: 'AINA-Wireless Inc.',
+ 0x02CC: 'Eijkelkamp Soil & Water',
+ 0x02CD: 'BMA ergonomics b.v.',
+ 0x02CE: 'Teva Branded Pharmaceutical Products R&D, Inc.',
+ 0x02CF: 'Anima',
+ 0x02D0: '3M',
+ 0x02D1: 'Empatica Srl',
+ 0x02D2: 'Afero, Inc.',
+ 0x02D3: 'Powercast Corporation',
+ 0x02D4: 'Secuyou ApS',
+ 0x02D5: 'OMRON Corporation',
+ 0x02D6: 'Send Solutions',
+ 0x02D7: 'NIPPON SYSTEMWARE CO.,LTD.',
+ 0x02D8: 'Neosfar',
+ 0x02D9: 'Fliegl Agrartechnik GmbH',
+ 0x02DA: 'Gilvader',
+ 0x02DB: 'Digi International Inc (R)',
+ 0x02DC: 'DeWalch Technologies, Inc.',
+ 0x02DD: 'Flint Rehabilitation Devices, LLC',
+ 0x02DE: 'Samsung SDS Co., Ltd.',
+ 0x02DF: 'Blur Product Development',
+ 0x02E0: 'University of Michigan',
+ 0x02E1: 'Victron Energy BV',
+ 0x02E2: 'NTT docomo',
+ 0x02E3: 'Carmanah Technologies Corp.',
+ 0x02E4: 'Bytestorm Ltd.',
+ 0x02E5: 'Espressif Incorporated ( () )',
+ 0x02E6: 'Unwire',
+ 0x02E7: 'Connected Yard, Inc.',
+ 0x02E8: 'American Music Environments',
+ 0x02E9: 'Sensogram Technologies, Inc.',
+ 0x02EA: 'Fujitsu Limited',
+ 0x02EB: 'Ardic Technology',
+ 0x02EC: 'Delta Systems, Inc',
+ 0x02ED: 'HTC Corporation',
+ 0x02EE: 'Citizen Holdings Co., Ltd.',
+ 0x02EF: 'SMART-INNOVATION.inc',
+ 0x02F0: 'Blackrat Software',
+ 0x02F1: 'The Idea Cave, LLC',
+ 0x02F2: 'GoPro, Inc.',
+ 0x02F3: 'AuthAir, Inc',
+ 0x02F4: 'Vensi, Inc.',
+ 0x02F5: 'Indagem Tech LLC',
+ 0x02F6: 'Intemo Technologies',
+ 0x02F7: 'DreamVisions co., Ltd.',
+ 0x02F8: 'Runteq Oy Ltd',
+ 0x02F9: 'IMAGINATION TECHNOLOGIES LTD',
+ 0x02FA: 'CoSTAR TEchnologies',
+ 0x02FB: 'Clarius Mobile Health Corp.',
+ 0x02FC: 'Shanghai Frequen Microelectronics Co., Ltd.',
+ 0x02FD: 'Uwanna, Inc.',
+ 0x02FE: 'Lierda Science & Technology Group Co., Ltd.',
+ 0x02FF: 'Silicon Laboratories',
+ 0x0300: 'World Moto Inc.',
+ 0x0301: 'Giatec Scientific Inc.',
+ 0x0302: 'Loop Devices, Inc',
+ 0x0303: 'IACA electronique',
+ 0x0304: 'Martians Inc',
+ 0x0305: 'Swipp ApS',
+ 0x0306: 'Life Laboratory Inc.',
+ 0x0307: 'FUJI INDUSTRIAL CO.,LTD.',
+ 0x0308: 'Surefire, LLC',
+ 0x0309: 'Dolby Labs',
+ 0x030A: 'Ellisys',
+ 0x030B: 'Magnitude Lighting Converters',
+ 0x030C: 'Hilti AG',
+ 0x030D: 'Devdata S.r.l.',
+ 0x030E: 'Deviceworx',
+ 0x030F: 'Shortcut Labs',
+ 0x0310: 'SGL Italia S.r.l.',
+ 0x0311: 'PEEQ DATA',
+ 0x0312: 'Ducere Technologies Pvt Ltd',
+ 0x0313: 'DiveNav, Inc.',
+ 0x0314: 'RIIG AI Sp. z o.o.',
+ 0x0315: 'Thermo Fisher Scientific',
+ 0x0316: 'AG Measurematics Pvt. Ltd.',
+ 0x0317: 'CHUO Electronics CO., LTD.',
+ 0x0318: 'Aspenta International',
+ 0x0319: 'Eugster Frismag AG',
+ 0x031A: 'Amber wireless GmbH',
+ 0x031B: 'HQ Inc',
+ 0x031C: 'Lab Sensor Solutions',
+ 0x031D: 'Enterlab ApS',
+ 0x031E: 'Eyefi, Inc.',
+ 0x031F: 'MetaSystem S.p.A.',
+ 0x0320: 'SONO ELECTRONICS. CO., LTD',
+ 0x0321: 'Jewelbots',
+ 0x0322: 'Compumedics Limited',
+ 0x0323: 'Rotor Bike Components',
+ 0x0324: 'Astro, Inc.',
+ 0x0325: 'Amotus Solutions',
+ 0x0326: 'Healthwear Technologies (Changzhou)Ltd',
+ 0x0327: 'Essex Electronics',
+ 0x0328: 'Grundfos A/S',
+ 0x0329: 'Eargo, Inc.',
+ 0x032A: 'Electronic Design Lab',
+ 0x032B: 'ESYLUX',
+ 0x032C: 'NIPPON SMT.CO.,Ltd',
+ 0x032D: 'BM innovations GmbH',
+ 0x032E: 'indoormap',
+ 0x032F: 'OttoQ Inc',
+ 0x0330: 'North Pole Engineering',
+ 0x0331: '3flares Technologies Inc.',
+ 0x0332: 'Electrocompaniet A.S.',
+ 0x0333: 'Mul-T-Lock',
+ 0x0334: 'Corentium AS',
+ 0x0335: 'Enlighted Inc',
+ 0x0336: 'GISTIC',
+ 0x0337: 'AJP2 Holdings, LLC',
+ 0x0338: 'COBI GmbH',
+ 0x0339: 'Blue Sky Scientific, LLC',
+ 0x033A: 'Appception, Inc.',
+ 0x033B: 'Courtney Thorne Limited',
+ 0x033C: 'Virtuosys',
+ 0x033D: 'TPV Technology Limited',
+ 0x033E: 'Monitra SA',
+ 0x033F: 'Automation Components, Inc.',
+ 0x0340: 'Letsense s.r.l.',
+ 0x0341: 'Etesian Technologies LLC',
+ 0x0342: 'GERTEC BRASIL LTDA.',
+ 0x0343: 'Drekker Development Pty. Ltd.',
+ 0x0344: 'Whirl Inc',
+ 0x0345: 'Locus Positioning',
+ 0x0346: 'Acuity Brands Lighting, Inc',
+ 0x0347: 'Prevent Biometrics',
+ 0x0348: 'Arioneo',
+ 0x0349: 'VersaMe',
+ 0x034A: 'Vaddio',
+ 0x034B: 'Libratone A/S',
+ 0x034C: 'HM Electronics, Inc.',
+ 0x034D: 'TASER International, Inc.',
+ 0x034E: 'SafeTrust Inc.',
+ 0x034F: 'Heartland Payment Systems',
+ 0x0350: 'Bitstrata Systems Inc.',
+ 0x0351: 'Pieps GmbH',
+ 0x0352: 'iRiding(Xiamen)Technology Co.,Ltd.',
+ 0x0353: 'Alpha Audiotronics, Inc.',
+ 0x0354: 'TOPPAN FORMS CO.,LTD.',
+ 0x0355: 'Sigma Designs, Inc.',
+ 0x0356: 'Spectrum Brands, Inc.',
+ 0x0357: 'Polymap Wireless',
+ 0x0358: 'MagniWare Ltd.',
+ 0x0359: 'Novotec Medical GmbH',
+ 0x035A: 'Medicom Innovation Partner a/s',
+ 0x035B: 'Matrix Inc.',
+ 0x035C: 'Eaton Corporation',
+ 0x035D: 'KYS',
+ 0x035E: 'Naya Health, Inc.',
+ 0x035F: 'Acromag',
+ 0x0360: 'Insulet Corporation',
+ 0x0361: 'Wellinks Inc.',
+ 0x0362: 'ON Semiconductor',
+ 0x0363: 'FREELAP SA',
+ 0x0364: 'Favero Electronics Srl',
+ 0x0365: 'BioMech Sensor LLC',
+ 0x0366: 'BOLTT Sports technologies Private limited',
+ 0x0367: 'Saphe International',
+ 0x0368: 'Metormote AB',
+ 0x0369: 'littleBits',
+ 0x036A: 'SetPoint Medical',
+ 0x036B: 'BRControls Products BV',
+ 0x036C: 'Zipcar',
+ 0x036D: 'AirBolt Pty Ltd',
+ 0x036E: 'KeepTruckin Inc',
+ 0x036F: 'Motiv, Inc.',
+ 0x0370: 'Wazombi Labs O',
+ 0x0371: 'ORBCOMM',
+ 0x0372: 'Nixie Labs, Inc.',
+ 0x0373: 'AppNearMe Ltd',
+ 0x0374: 'Holman Industries',
+ 0x0375: 'Expain AS',
+ 0x0376: 'Electronic Temperature Instruments Ltd',
+ 0x0377: 'Plejd AB',
+ 0x0378: 'Propeller Health',
+ 0x0379: 'Shenzhen iMCO Electronic Technology Co.,Ltd',
+ 0x037A: 'Algoria',
+ 0x037B: 'Apption Labs Inc.',
+ 0x037C: 'Cronologics Corporation',
+ 0x037D: 'MICRODIA Ltd.',
+ 0x037E: 'lulabytes S.L.',
+ 0x037F: 'Nestec S.A.',
+ 0x0380: 'LLC MEGA - F service',
+ 0x0381: 'Sharp Corporation',
+ 0x0382: 'Precision Outcomes Ltd',
+ 0x0383: 'Kronos Incorporated',
+ 0x0384: 'OCOSMOS Co., Ltd.',
+ 0x0385: 'Embedded Electronic Solutions Ltd. dba e2Solutions',
+ 0x0386: 'Aterica Inc.',
+ 0x0387: 'BluStor PMC, Inc.',
+ 0x0388: 'Kapsch TrafficCom AB',
+ 0x0389: 'ActiveBlu Corporation',
+ 0x038A: 'Kohler Mira Limited',
+ 0x038B: 'Noke',
+ 0x038C: 'Appion Inc.',
+ 0x038D: 'Resmed Ltd',
+ 0x038E: 'Crownstone B.V.',
+ 0x038F: 'Xiaomi Inc.',
+ 0x0390: 'INFOTECH s.r.o.',
+ 0x0391: 'Thingsquare AB',
+ 0x0392: 'T&D',
+ 0x0393: 'LAVAZZA S.p.A.',
+ 0x0394: 'Netclearance Systems, Inc.',
+ 0x0395: 'SDATAWAY',
+ 0x0396: 'BLOKS GmbH',
+ 0x0397: 'LEGO System A/S',
+ 0x0398: 'Thetatronics Ltd',
+ 0x0399: 'Nikon Corporation',
+ 0x039A: 'NeST',
+ 0x039B: 'South Silicon Valley Microelectronics',
+ 0x039C: 'ALE International',
+ 0x039D: 'CareView Communications, Inc.',
+ 0x039E: 'SchoolBoard Limited',
+ 0x039F: 'Molex Corporation',
+ 0x03A0: 'IVT Wireless Limited',
+ 0x03A1: 'Alpine Labs LLC',
+ 0x03A2: 'Candura Instruments',
+ 0x03A3: 'SmartMovt Technology Co., Ltd',
+ 0x03A4: 'Token Zero Ltd',
+ 0x03A5: 'ACE CAD Enterprise Co., Ltd. (ACECAD)',
+ 0x03A6: 'Medela, Inc',
+ 0x03A7: 'AeroScout',
+ 0x03A8: 'Esrille Inc.',
+ 0x03A9: 'THINKERLY SRL',
+ 0x03AA: 'Exon Sp. z o.o.',
+ 0x03AB: 'Meizu Technology Co., Ltd.',
+ 0x03AC: 'Smablo LTD',
+ 0x03AD: 'XiQ',
+ 0x03AE: 'Allswell Inc.',
+ 0x03AF: 'Comm-N-Sense Corp DBA Verigo',
+ 0x03B0: 'VIBRADORM GmbH',
+ 0x03B1: 'Otodata Wireless Network Inc.',
+ 0x03B2: 'Propagation Systems Limited',
+ 0x03B3: 'Midwest Instruments & Controls',
+ 0x03B4: 'Alpha Nodus, inc.',
+ 0x03B5: 'petPOMM, Inc',
+ 0x03B6: 'Mattel',
+ 0x03B7: 'Airbly Inc.',
+ 0x03B8: 'A-Safe Limited',
+ 0x03B9: 'FREDERIQUE CONSTANT SA',
+ 0x03BA: 'Maxscend Microelectronics Company Limited',
+ 0x03BB: 'Abbott Diabetes Care',
+ 0x03BC: 'ASB Bank Ltd',
+ 0x03BD: 'amadas',
+ 0x03BE: 'Applied Science, Inc.',
+ 0x03BF: 'iLumi Solutions Inc.',
+ 0x03C0: 'Arch Systems Inc.',
+ 0x03C1: 'Ember Technologies, Inc.',
+ 0x03C2: 'Snapchat Inc',
+ 0x03C3: 'Casambi Technologies Oy',
+ 0x03C4: 'Pico Technology Inc.',
+ 0x03C5: 'St. Jude Medical, Inc.',
+ 0x03C6: 'Intricon',
+ 0x03C7: 'Structural Health Systems, Inc.',
+ 0x03C8: 'Avvel International',
+ 0x03C9: 'Gallagher Group',
+ 0x03CA: 'In2things Automation Pvt. Ltd.',
+ 0x03CB: 'SYSDEV Srl',
+ 0x03CC: 'Vonkil Technologies Ltd',
+ 0x03CD: 'Wynd Technologies, Inc.',
+ 0x03CE: 'CONTRINEX S.A.',
+ 0x03CF: 'MIRA, Inc.',
+ 0x03D0: 'Watteam Ltd',
+ 0x03D1: 'Density Inc.',
+ 0x03D2: 'IOT Pot India Private Limited',
+ 0x03D3: 'Sigma Connectivity AB',
+ 0x03D4: 'PEG PEREGO SPA',
+ 0x03D5: 'Wyzelink Systems Inc.',
+ 0x03D6: 'Yota Devices LTD',
+ 0x03D7: 'FINSECUR',
+ 0x03D8: 'Zen-Me Labs Ltd',
+ 0x03D9: '3IWare Co., Ltd.',
+ 0x03DA: 'EnOcean GmbH',
+ 0x03DB: 'Instabeat, Inc',
+ 0x03DC: 'Nima Labs',
+ 0x03DD: 'Andreas Stihl AG & Co. KG',
+ 0x03DE: 'Nathan Rhoades LLC',
+ 0x03DF: 'Grob Technologies, LLC',
+ 0x03E0: 'Actions (Zhuhai) Technology Co., Limited',
+ 0x03E1: 'SPD Development Company Ltd',
+ 0x03E2: 'Sensoan Oy',
+ 0x03E3: 'Qualcomm Life Inc',
+ 0x03E4: 'Chip-ing AG',
+ 0x03E5: 'ffly4u',
+ 0x03E6: 'IoT Instruments Oy',
+ 0x03E7: 'TRUE Fitness Technology',
+ 0x03E8: 'Reiner Kartengeraete GmbH & Co. KG.',
+ 0x03E9: 'SHENZHEN LEMONJOY TECHNOLOGY CO., LTD.',
+ 0x03EA: 'Hello Inc.',
+ 0x03EB: 'Evollve Inc.',
+ 0x03EC: 'Jigowatts Inc.',
+ 0x03ED: 'BASIC MICRO.COM,INC.',
+ 0x03EE: 'CUBE TECHNOLOGIES',
+ 0x03EF: 'foolography GmbH',
+ 0x03F0: 'CLINK',
+ 0x03F1: 'Hestan Smart Cooking Inc.',
+ 0x03F2: 'WindowMaster A/S',
+ 0x03F3: 'Flowscape AB',
+ 0x03F4: 'PAL Technologies Ltd',
+ 0x03F5: 'WHERE, Inc.',
+ 0x03F6: 'Iton Technology Corp.',
+ 0x03F7: 'Owl Labs Inc.',
+ 0x03F8: 'Rockford Corp.',
+ 0x03F9: 'Becon Technologies Co.,Ltd.',
+ 0x03FA: 'Vyassoft Technologies Inc',
+ 0x03FB: 'Nox Medical',
+ 0x03FC: 'Kimberly-Clark',
+ 0x03FD: 'Trimble Navigation Ltd.',
+ 0x03FE: 'Littelfuse',
+ 0x03FF: 'Withings',
+ 0x0400: 'i-developer IT Beratung UG',
+ 0x0402: 'Sears Holdings Corporation',
+ 0x0403: 'Gantner Electronic GmbH',
+ 0x0404: 'Authomate Inc',
+ 0x0405: 'Vertex International, Inc.',
+ 0x0406: 'Airtago',
+ 0x0407: 'Swiss Audio SA',
+ 0x0408: 'ToGetHome Inc.',
+ 0x0409: 'AXIS',
+ 0x040A: 'Openmatics',
+ 0x040B: 'Jana Care Inc.',
+ 0x040C: 'Senix Corporation',
+ 0x040D: 'NorthStar Battery Company, LLC',
+ 0x040E: 'SKF (U.K.) Limited',
+ 0x040F: 'CO-AX Technology, Inc.',
+ 0x0410: 'Fender Musical Instruments',
+ 0x0411: 'Luidia Inc',
+ 0x0412: 'SEFAM',
+ 0x0413: 'Wireless Cables Inc',
+ 0x0414: 'Lightning Protection International Pty Ltd',
+ 0x0415: 'Uber Technologies Inc',
+ 0x0416: 'SODA GmbH',
+ 0x0417: 'Fatigue Science',
+ 0x0418: 'Alpine Electronics Inc.',
+ 0x0419: 'Novalogy LTD',
+ 0x041A: 'Friday Labs Limited',
+ 0x041B: 'OrthoAccel Technologies',
+ 0x041C: 'WaterGuru, Inc.',
+ 0x041D: 'Benning Elektrotechnik und Elektronik GmbH & Co. KG',
+ 0x041E: 'Dell Computer Corporation',
+ 0x041F: 'Kopin Corporation',
+ 0x0420: 'TecBakery GmbH',
+ 0x0421: 'Backbone Labs, Inc.',
+ 0x0422: 'DELSEY SA',
+ 0x0423: 'Chargifi Limited',
+ 0x0424: 'Trainesense Ltd.',
+ 0x0425: 'Unify Software and Solutions GmbH & Co. KG',
+ 0x0426: 'Husqvarna AB',
+ 0x0427: 'Focus fleet and fuel management inc',
+ 0x0428: 'SmallLoop, LLC',
+ 0x0429: 'Prolon Inc.',
+ 0x042A: 'BD Medical',
+ 0x042B: 'iMicroMed Incorporated',
+ 0x042C: 'Ticto N.V.',
+ 0x042D: 'Meshtech AS',
+ 0x042E: 'MemCachier Inc.',
+ 0x042F: 'Danfoss A/S',
+ 0x0430: 'SnapStyk Inc.',
+ 0x0431: 'Amyway Corporation',
+ 0x0432: 'Silk Labs, Inc.',
+ 0x0433: 'Pillsy Inc.',
+ 0x0434: 'Hatch Baby, Inc.',
+ 0x0435: 'Blocks Wearables Ltd.',
+ 0x0436: 'Drayson Technologies (Europe) Limited',
+ 0x0437: 'eBest IOT Inc.',
+ 0x0438: 'Helvar Ltd',
+ 0x0439: 'Radiance Technologies',
+ 0x043A: 'Nuheara Limited',
+ 0x043B: 'Appside co., ltd.',
+ 0x043C: 'DeLaval',
+ 0x043D: 'Coiler Corporation',
+ 0x043E: 'Thermomedics, Inc.',
+ 0x043F: 'Tentacle Sync GmbH',
+ 0x0440: 'Valencell, Inc.',
+ 0x0441: 'iProtoXi Oy',
+ 0x0442: 'SECOM CO., LTD.',
+ 0x0443: 'Tucker International LLC',
+ 0x0444: 'Metanate Limited',
+ 0x0445: 'Kobian Canada Inc.',
+ 0x0446: 'NETGEAR, Inc.',
+ 0x0447: 'Fabtronics Australia Pty Ltd',
+ 0x0448: 'Grand Centrix GmbH',
+ 0x0449: '1UP USA.com llc',
+ 0x044A: 'SHIMANO INC.',
+ 0x044B: 'Nain Inc.',
+ 0x044C: 'LifeStyle Lock, LLC',
+ 0x044D: 'VEGA Grieshaber KG',
+ 0x044E: 'Xtrava Inc.',
+ 0x044F: 'TTS Tooltechnic Systems AG & Co. KG',
+ 0x0450: 'Teenage Engineering AB',
+ 0x0451: 'Tunstall Nordic AB',
+ 0x0452: 'Svep Design Center AB',
+ 0x0453: 'GreenPeak Technologies BV',
+ 0x0454: 'Sphinx Electronics GmbH & Co KG',
+ 0x0455: 'Atomation',
+ 0x0456: 'Nemik Consulting Inc',
+ 0x0457: 'RF INNOVATION',
+ 0x0458: 'Mini Solution Co., Ltd.',
+ 0x0459: 'Lumenetix, Inc',
+ 0x045A: '2048450 Ontario Inc',
+ 0x045B: 'SPACEEK LTD',
+ 0x045C: 'Delta T Corporation',
+ 0x045D: 'Boston Scientific Corporation',
+ 0x045E: 'Nuviz, Inc.',
+ 0x045F: 'Real Time Automation, Inc.',
+ 0x0460: 'Kolibree',
+ 0x0461: 'vhf elektronik GmbH',
+ 0x0462: 'Bonsai Systems GmbH',
+ 0x0463: 'Fathom Systems Inc.',
+ 0x0464: 'Bellman & Symfon',
+ 0x0465: 'International Forte Group LLC',
+ 0x0466: 'CycleLabs Solutions inc.',
+ 0x0467: 'Codenex Oy',
+ 0x0468: 'Kynesim Ltd',
+ 0x0469: 'Palago AB',
+ 0x046A: 'INSIGMA INC.',
+ 0x046B: 'PMD Solutions',
+ 0x046C: 'Qingdao Realtime Technology Co., Ltd.',
+ 0x046D: 'BEGA Gantenbrink-Leuchten KG',
+ 0x046E: 'Pambor Ltd.',
+ 0xFFFF: 'SPECIAL USE/DEFAULT'
+};
+
-Object.defineProperties(WebSocket.prototype, {
- CONNECTING: staticPropertyDescriptors,
- OPEN: staticPropertyDescriptors,
- CLOSING: staticPropertyDescriptors,
- CLOSED: staticPropertyDescriptors,
- url: kEnumerableProperty,
- readyState: kEnumerableProperty,
- bufferedAmount: kEnumerableProperty,
- onopen: kEnumerableProperty,
- onerror: kEnumerableProperty,
- onclose: kEnumerableProperty,
- close: kEnumerableProperty,
- onmessage: kEnumerableProperty,
- binaryType: kEnumerableProperty,
- send: kEnumerableProperty,
- extensions: kEnumerableProperty,
- protocol: kEnumerableProperty,
- [Symbol.toStringTag]: {
- value: 'WebSocket',
- writable: false,
- enumerable: false,
- configurable: true
- }
-})
+/***/ }),
-Object.defineProperties(WebSocket, {
- CONNECTING: staticPropertyDescriptors,
- OPEN: staticPropertyDescriptors,
- CLOSING: staticPropertyDescriptors,
- CLOSED: staticPropertyDescriptors
-})
+/***/ 16832:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-webidl.converters['sequence'] = webidl.sequenceConverter(
- webidl.converters.DOMString
-)
-webidl.converters['DOMString or sequence'] = function (V) {
- if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) {
- return webidl.converters['sequence'](V)
- }
+// @ts-check
+// ==================================================================================
+// cpu.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 4. CPU
+// ----------------------------------------------------------------------------------
- return webidl.converters.DOMString(V)
-}
+const os = __nccwpck_require__(70857);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const fs = __nccwpck_require__(79896);
+const util = __nccwpck_require__(77496);
-// This implements the propsal made in https://github.com/whatwg/websockets/issues/42
-webidl.converters.WebSocketInit = webidl.dictionaryConverter([
- {
- key: 'protocols',
- converter: webidl.converters['DOMString or sequence'],
- get defaultValue () {
- return []
- }
- },
- {
- key: 'dispatcher',
- converter: (V) => V,
- get defaultValue () {
- return getGlobalDispatcher()
- }
- },
- {
- key: 'headers',
- converter: webidl.nullableConverter(webidl.converters.HeadersInit)
- }
-])
+let _platform = process.platform;
-webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) {
- if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) {
- return webidl.converters.WebSocketInit(V)
- }
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
- return { protocols: webidl.converters['DOMString or sequence'](V) }
-}
+let _cpu_speed = 0;
+let _current_cpu = {
+ user: 0,
+ nice: 0,
+ system: 0,
+ idle: 0,
+ irq: 0,
+ steal: 0,
+ guest: 0,
+ load: 0,
+ tick: 0,
+ ms: 0,
+ currentLoad: 0,
+ currentLoadUser: 0,
+ currentLoadSystem: 0,
+ currentLoadNice: 0,
+ currentLoadIdle: 0,
+ currentLoadIrq: 0,
+ currentLoadSteal: 0,
+ currentLoadGuest: 0,
+ rawCurrentLoad: 0,
+ rawCurrentLoadUser: 0,
+ rawCurrentLoadSystem: 0,
+ rawCurrentLoadNice: 0,
+ rawCurrentLoadIdle: 0,
+ rawCurrentLoadIrq: 0,
+ rawCurrentLoadSteal: 0,
+ rawCurrentLoadGuest: 0
+};
+let _cpus = [];
+let _corecount = 0;
-webidl.converters.WebSocketSendData = function (V) {
- if (webidl.util.Type(V) === 'Object') {
- if (isBlobLike(V)) {
- return webidl.converters.Blob(V, { strict: false })
- }
+const AMDBaseFrequencies = {
+ '8346': '1.8',
+ '8347': '1.9',
+ '8350': '2.0',
+ '8354': '2.2',
+ '8356|SE': '2.4',
+ '8356': '2.3',
+ '8360': '2.5',
+ '2372': '2.1',
+ '2373': '2.1',
+ '2374': '2.2',
+ '2376': '2.3',
+ '2377': '2.3',
+ '2378': '2.4',
+ '2379': '2.4',
+ '2380': '2.5',
+ '2381': '2.5',
+ '2382': '2.6',
+ '2384': '2.7',
+ '2386': '2.8',
+ '2387': '2.8',
+ '2389': '2.9',
+ '2393': '3.1',
+ '8374': '2.2',
+ '8376': '2.3',
+ '8378': '2.4',
+ '8379': '2.4',
+ '8380': '2.5',
+ '8381': '2.5',
+ '8382': '2.6',
+ '8384': '2.7',
+ '8386': '2.8',
+ '8387': '2.8',
+ '8389': '2.9',
+ '8393': '3.1',
+ '2419EE': '1.8',
+ '2423HE': '2.0',
+ '2425HE': '2.1',
+ '2427': '2.2',
+ '2431': '2.4',
+ '2435': '2.6',
+ '2439SE': '2.8',
+ '8425HE': '2.1',
+ '8431': '2.4',
+ '8435': '2.6',
+ '8439SE': '2.8',
+ '4122': '2.2',
+ '4130': '2.6',
+ '4162EE': '1.7',
+ '4164EE': '1.8',
+ '4170HE': '2.1',
+ '4174HE': '2.3',
+ '4176HE': '2.4',
+ '4180': '2.6',
+ '4184': '2.8',
+ '6124HE': '1.8',
+ '6128HE': '2.0',
+ '6132HE': '2.2',
+ '6128': '2.0',
+ '6134': '2.3',
+ '6136': '2.4',
+ '6140': '2.6',
+ '6164HE': '1.7',
+ '6166HE': '1.8',
+ '6168': '1.9',
+ '6172': '2.1',
+ '6174': '2.2',
+ '6176': '2.3',
+ '6176SE': '2.3',
+ '6180SE': '2.5',
+ '3250': '2.5',
+ '3260': '2.7',
+ '3280': '2.4',
+ '4226': '2.7',
+ '4228': '2.8',
+ '4230': '2.9',
+ '4234': '3.1',
+ '4238': '3.3',
+ '4240': '3.4',
+ '4256': '1.6',
+ '4274': '2.5',
+ '4276': '2.6',
+ '4280': '2.8',
+ '4284': '3.0',
+ '6204': '3.3',
+ '6212': '2.6',
+ '6220': '3.0',
+ '6234': '2.4',
+ '6238': '2.6',
+ '6262HE': '1.6',
+ '6272': '2.1',
+ '6274': '2.2',
+ '6276': '2.3',
+ '6278': '2.4',
+ '6282SE': '2.6',
+ '6284SE': '2.7',
+ '6308': '3.5',
+ '6320': '2.8',
+ '6328': '3.2',
+ '6338P': '2.3',
+ '6344': '2.6',
+ '6348': '2.8',
+ '6366': '1.8',
+ '6370P': '2.0',
+ '6376': '2.3',
+ '6378': '2.4',
+ '6380': '2.5',
+ '6386': '2.8',
+ 'FX|4100': '3.6',
+ 'FX|4120': '3.9',
+ 'FX|4130': '3.8',
+ 'FX|4150': '3.8',
+ 'FX|4170': '4.2',
+ 'FX|6100': '3.3',
+ 'FX|6120': '3.6',
+ 'FX|6130': '3.6',
+ 'FX|6200': '3.8',
+ 'FX|8100': '2.8',
+ 'FX|8120': '3.1',
+ 'FX|8140': '3.2',
+ 'FX|8150': '3.6',
+ 'FX|8170': '3.9',
+ 'FX|4300': '3.8',
+ 'FX|4320': '4.0',
+ 'FX|4350': '4.2',
+ 'FX|6300': '3.5',
+ 'FX|6350': '3.9',
+ 'FX|8300': '3.3',
+ 'FX|8310': '3.4',
+ 'FX|8320': '3.5',
+ 'FX|8350': '4.0',
+ 'FX|8370': '4.0',
+ 'FX|9370': '4.4',
+ 'FX|9590': '4.7',
+ 'FX|8320E': '3.2',
+ 'FX|8370E': '3.3',
- if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) {
- return webidl.converters.BufferSource(V)
- }
- }
+ // ZEN Desktop CPUs
+ '1200': '3.1',
+ 'Pro 1200': '3.1',
+ '1300X': '3.5',
+ 'Pro 1300': '3.5',
+ '1400': '3.2',
+ '1500X': '3.5',
+ 'Pro 1500': '3.5',
+ '1600': '3.2',
+ '1600X': '3.6',
+ 'Pro 1600': '3.2',
+ '1700': '3.0',
+ 'Pro 1700': '3.0',
+ '1700X': '3.4',
+ 'Pro 1700X': '3.4',
+ '1800X': '3.6',
+ '1900X': '3.8',
+ '1920': '3.2',
+ '1920X': '3.5',
+ '1950X': '3.4',
- return webidl.converters.USVString(V)
-}
+ // ZEN Desktop APUs
+ '200GE': '3.2',
+ 'Pro 200GE': '3.2',
+ '220GE': '3.4',
+ '240GE': '3.5',
+ '3000G': '3.5',
+ '300GE': '3.4',
+ '3050GE': '3.4',
+ '2200G': '3.5',
+ 'Pro 2200G': '3.5',
+ '2200GE': '3.2',
+ 'Pro 2200GE': '3.2',
+ '2400G': '3.6',
+ 'Pro 2400G': '3.6',
+ '2400GE': '3.2',
+ 'Pro 2400GE': '3.2',
-module.exports = {
- WebSocket
-}
+ // ZEN Mobile APUs
+ 'Pro 200U': '2.3',
+ '300U': '2.4',
+ '2200U': '2.5',
+ '3200U': '2.6',
+ '2300U': '2.0',
+ 'Pro 2300U': '2.0',
+ '2500U': '2.0',
+ 'Pro 2500U': '2.2',
+ '2600H': '3.2',
+ '2700U': '2.0',
+ 'Pro 2700U': '2.2',
+ '2800H': '3.3',
+ // ZEN Server Processors
+ '7351': '2.4',
+ '7351P': '2.4',
+ '7401': '2.0',
+ '7401P': '2.0',
+ '7551P': '2.0',
+ '7551': '2.0',
+ '7251': '2.1',
+ '7261': '2.5',
+ '7281': '2.1',
+ '7301': '2.2',
+ '7371': '3.1',
+ '7451': '2.3',
+ '7501': '2.0',
+ '7571': '2.2',
+ '7601': '2.2',
-/***/ }),
+ // ZEN Embedded Processors
+ 'V1500B': '2.2',
+ 'V1780B': '3.35',
+ 'V1202B': '2.3',
+ 'V1404I': '2.0',
+ 'V1605B': '2.0',
+ 'V1756B': '3.25',
+ 'V1807B': '3.35',
-/***/ 49367:
-/***/ ((__unused_webpack_module, exports) => {
+ '3101': '2.1',
+ '3151': '2.7',
+ '3201': '1.5',
+ '3251': '2.5',
+ '3255': '2.5',
+ '3301': '2.0',
+ '3351': '1.9',
+ '3401': '1.85',
+ '3451': '2.15',
+ // ZEN+ Desktop
+ '1200|AF': '3.1',
+ '2300X': '3.5',
+ '2500X': '3.6',
+ '2600': '3.4',
+ '2600E': '3.1',
+ '1600|AF': '3.2',
+ '2600X': '3.6',
+ '2700': '3.2',
+ '2700E': '2.8',
+ 'Pro 2700': '3.2',
+ '2700X': '3.7',
+ 'Pro 2700X': '3.6',
+ '2920X': '3.5',
+ '2950X': '3.5',
+ '2970WX': '3.0',
+ '2990WX': '3.0',
+ // ZEN+ Desktop APU
+ 'Pro 300GE': '3.4',
+ 'Pro 3125GE': '3.4',
+ '3150G': '3.5',
+ 'Pro 3150G': '3.5',
+ '3150GE': '3.3',
+ 'Pro 3150GE': '3.3',
+ '3200G': '3.6',
+ 'Pro 3200G': '3.6',
+ '3200GE': '3.3',
+ 'Pro 3200GE': '3.3',
+ '3350G': '3.6',
+ 'Pro 3350G': '3.6',
+ '3350GE': '3.3',
+ 'Pro 3350GE': '3.3',
+ '3400G': '3.7',
+ 'Pro 3400G': '3.7',
+ '3400GE': '3.3',
+ 'Pro 3400GE': '3.3',
-Object.defineProperty(exports, "__esModule", ({ value: true }));
+ // ZEN+ Mobile
+ '3300U': '2.1',
+ 'PRO 3300U': '2.1',
+ '3450U': '2.1',
+ '3500U': '2.1',
+ 'PRO 3500U': '2.1',
+ '3500C': '2.1',
+ '3550H': '2.1',
+ '3580U': '2.1',
+ '3700U': '2.3',
+ 'PRO 3700U': '2.3',
+ '3700C': '2.3',
+ '3750H': '2.3',
+ '3780U': '2.3',
-function getUserAgent() {
- if (typeof navigator === "object" && "userAgent" in navigator) {
- return navigator.userAgent;
- }
+ // ZEN2 Desktop CPUS
+ '3100': '3.6',
+ '3300X': '3.8',
+ '3500': '3.6',
+ '3500X': '3.6',
+ '3600': '3.6',
+ 'Pro 3600': '3.6',
+ '3600X': '3.8',
+ '3600XT': '3.8',
+ 'Pro 3700': '3.6',
+ '3700X': '3.6',
+ '3800X': '3.9',
+ '3800XT': '3.9',
+ '3900': '3.1',
+ 'Pro 3900': '3.1',
+ '3900X': '3.8',
+ '3900XT': '3.8',
+ '3950X': '3.5',
+ '3960X': '3.8',
+ '3970X': '3.7',
+ '3990X': '2.9',
+ '3945WX': '4.0',
+ '3955WX': '3.9',
+ '3975WX': '3.5',
+ '3995WX': '2.7',
- if (typeof process === "object" && process.version !== undefined) {
- return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;
- }
+ // ZEN2 Desktop APUs
+ '4300GE': '3.5',
+ 'Pro 4300GE': '3.5',
+ '4300G': '3.8',
+ 'Pro 4300G': '3.8',
+ '4600GE': '3.3',
+ 'Pro 4650GE': '3.3',
+ '4600G': '3.7',
+ 'Pro 4650G': '3.7',
+ '4700GE': '3.1',
+ 'Pro 4750GE': '3.1',
+ '4700G': '3.6',
+ 'Pro 4750G': '3.6',
+ '4300U': '2.7',
+ '4450U': '2.5',
+ 'Pro 4450U': '2.5',
+ '4500U': '2.3',
+ '4600U': '2.1',
+ 'PRO 4650U': '2.1',
+ '4680U': '2.1',
+ '4600HS': '3.0',
+ '4600H': '3.0',
+ '4700U': '2.0',
+ 'PRO 4750U': '1.7',
+ '4800U': '1.8',
+ '4800HS': '2.9',
+ '4800H': '2.9',
+ '4900HS': '3.0',
+ '4900H': '3.3',
+ '5300U': '2.6',
+ '5500U': '2.1',
+ '5700U': '1.8',
- return "";
-}
+ // ZEN2 - EPYC
+ '7232P': '3.1',
+ '7302P': '3.0',
+ '7402P': '2.8',
+ '7502P': '2.5',
+ '7702P': '2.0',
+ '7252': '3.1',
+ '7262': '3.2',
+ '7272': '2.9',
+ '7282': '2.8',
+ '7302': '3.0',
+ '7352': '2.3',
+ '7402': '2.8',
+ '7452': '2.35',
+ '7502': '2.5',
+ '7532': '2.4',
+ '7542': '2.9',
+ '7552': '2.2',
+ '7642': '2.3',
+ '7662': '2.0',
+ '7702': '2.0',
+ '7742': '2.25',
+ '7H12': '2.6',
+ '7F32': '3.7',
+ '7F52': '3.5',
+ '7F72': '3.2',
-exports.getUserAgent = getUserAgent;
-//# sourceMappingURL=index.js.map
+ // Epyc (Milan)
+ '7773X': '2.2',
+ '7763': '2.45',
+ '7713': '2.0',
+ '7713P': '2.0',
+ '7663': '2.0',
+ '7643': '2.3',
+ '7573X': '2.8',
+ '75F3': '2.95',
+ '7543': '2.8',
+ '7543P': '2.8',
+ '7513': '2.6',
+ '7473X': '2.8',
+ '7453': '2.75',
+ '74F3': '3.2',
+ '7443': '2.85',
+ '7443P': '2.85',
+ '7413': '2.65',
+ '7373X': '3.05',
+ '73F3': '3.5',
+ '7343': '3.2',
+ '7313': '3.0',
+ '7313P': '3.0',
+ '72F3': '3.7',
-/***/ }),
+ // ZEN3
+ '5600X': '3.7',
+ '5800X': '3.8',
+ '5900X': '3.7',
+ '5950X': '3.4',
+ '5945WX': '4.1',
+ '5955WX': '4.0',
+ '5965WX': '3.8',
+ '5975WX': '3.6',
+ '5995WX': '2.7',
-/***/ 27460:
-/***/ ((module) => {
+ '7960X': '4.2',
+ '7970X': '4.0',
+ '7980X': '3.2',
-// Returns a wrapper function that returns a wrapped callback
-// The wrapper function should do some stuff, and return a
-// presumably different callback function.
-// This makes sure that own properties are retained, so that
-// decorations and such are not lost along the way.
-module.exports = wrappy
-function wrappy (fn, cb) {
- if (fn && cb) return wrappy(fn)(cb)
+ '7965WX': '4.2',
+ '7975WX': '4.0',
+ '7985WX': '3.2',
+ '7995WX': '2.5',
- if (typeof fn !== 'function')
- throw new TypeError('need wrapper function')
+ // ZEN4
+ '9754': '2.25',
+ '9754S': '2.25',
+ '9734': '2.2',
+ '9684X': '2.55',
+ '9384X': '3.1',
+ '9184X': '3.55',
+ '9654P': '2.4',
+ '9654': '2.4',
+ '9634': '2.25',
+ '9554P': '3.1',
+ '9554': '3.1',
+ '9534': '2.45',
+ '9474F': '3.6',
+ '9454P': '2.75',
+ '9454': '2.75',
+ '9374F': '3.85',
+ '9354P': '3.25',
+ '9354': '3.25',
+ '9334': '2.7',
+ '9274F': '4.05',
+ '9254': '2.9',
+ '9224': '2.5',
+ '9174F': '4.1',
+ '9124': '3.0'
+};
- Object.keys(fn).forEach(function (k) {
- wrapper[k] = fn[k]
- })
+const socketTypes = {
+ 1: 'Other',
+ 2: 'Unknown',
+ 3: 'Daughter Board',
+ 4: 'ZIF Socket',
+ 5: 'Replacement/Piggy Back',
+ 6: 'None',
+ 7: 'LIF Socket',
+ 8: 'Slot 1',
+ 9: 'Slot 2',
+ 10: '370 Pin Socket',
+ 11: 'Slot A',
+ 12: 'Slot M',
+ 13: '423',
+ 14: 'A (Socket 462)',
+ 15: '478',
+ 16: '754',
+ 17: '940',
+ 18: '939',
+ 19: 'mPGA604',
+ 20: 'LGA771',
+ 21: 'LGA775',
+ 22: 'S1',
+ 23: 'AM2',
+ 24: 'F (1207)',
+ 25: 'LGA1366',
+ 26: 'G34',
+ 27: 'AM3',
+ 28: 'C32',
+ 29: 'LGA1156',
+ 30: 'LGA1567',
+ 31: 'PGA988A',
+ 32: 'BGA1288',
+ 33: 'rPGA988B',
+ 34: 'BGA1023',
+ 35: 'BGA1224',
+ 36: 'LGA1155',
+ 37: 'LGA1356',
+ 38: 'LGA2011',
+ 39: 'FS1',
+ 40: 'FS2',
+ 41: 'FM1',
+ 42: 'FM2',
+ 43: 'LGA2011-3',
+ 44: 'LGA1356-3',
+ 45: 'LGA1150',
+ 46: 'BGA1168',
+ 47: 'BGA1234',
+ 48: 'BGA1364',
+ 49: 'AM4',
+ 50: 'LGA1151',
+ 51: 'BGA1356',
+ 52: 'BGA1440',
+ 53: 'BGA1515',
+ 54: 'LGA3647-1',
+ 55: 'SP3',
+ 56: 'SP3r2',
+ 57: 'LGA2066',
+ 58: 'BGA1392',
+ 59: 'BGA1510',
+ 60: 'BGA1528',
+ 61: 'LGA4189',
+ 62: 'LGA1200',
+ 63: 'LGA4677',
+ 64: 'LGA1700',
+ 65: 'BGA1744',
+ 66: 'BGA1781',
+ 67: 'BGA1211',
+ 68: 'BGA2422',
+ 69: 'LGA1211',
+ 70: 'LGA2422',
+ 71: 'LGA5773',
+ 72: 'BGA5773',
+};
- return wrapper
+const socketTypesByName = {
+ 'LGA1150': 'i7-5775C i3-4340 i3-4170 G3250 i3-4160T i3-4160 E3-1231 G3258 G3240 i7-4790S i7-4790K i7-4790 i5-4690K i5-4690 i5-4590T i5-4590S i5-4590 i5-4460 i3-4360 i3-4150 G1820 G3420 G3220 i7-4771 i5-4440 i3-4330 i3-4130T i3-4130 E3-1230 i7-4770S i7-4770K i7-4770 i5-4670K i5-4670 i5-4570T i5-4570S i5-4570 i5-4430',
+ 'LGA1151': 'i9-9900KS E-2288G E-2224 G5420 i9-9900T i9-9900 i7-9700T i7-9700F i7-9700E i7-9700 i5-9600 i5-9500T i5-9500F i5-9500 i5-9400T i3-9350K i3-9300 i3-9100T i3-9100F i3-9100 G4930 i9-9900KF i7-9700KF i5-9600KF i5-9400F i5-9400 i3-9350KF i9-9900K i7-9700K i5-9600K G5500 G5400 i7-8700T i7-8086K i5-8600 i5-8500T i5-8500 i5-8400T i3-8300 i3-8100T G4900 i7-8700K i7-8700 i5-8600K i5-8400 i3-8350K i3-8100 E3-1270 G4600 G4560 i7-7700T i7-7700K i7-7700 i5-7600K i5-7600 i5-7500T i5-7500 i5-7400 i3-7350K i3-7300 i3-7100T i3-7100 G3930 G3900 G4400 i7-6700T i7-6700K i7-6700 i5-6600K i5-6600 i5-6500T i5-6500 i5-6400T i5-6400 i3-6300 i3-6100T i3-6100 E3-1270 E3-1270 T4500 T4400',
+ '1155': 'G440 G460 G465 G470 G530T G540T G550T G1610T G1620T G530 G540 G1610 G550 G1620 G555 G1630 i3-2100T i3-2120T i3-3220T i3-3240T i3-3250T i3-2100 i3-2105 i3-2102 i3-3210 i3-3220 i3-2125 i3-2120 i3-3225 i3-2130 i3-3245 i3-3240 i3-3250 i5-3570T i5-2500T i5-2400S i5-2405S i5-2390T i5-3330S i5-2500S i5-3335S i5-2300 i5-3450S i5-3340S i5-3470S i5-3475S i5-3470T i5-2310 i5-3550S i5-2320 i5-3330 i5-3350P i5-3450 i5-2400 i5-3340 i5-3570S i5-2380P i5-2450P i5-3470 i5-2500K i5-3550 i5-2500 i5-3570 i5-3570K i5-2550K i7-3770T i7-2600S i7-3770S i7-2600K i7-2600 i7-3770 i7-3770K i7-2700K G620T G630T G640T G2020T G645T G2100T G2030T G622 G860T G620 G632 G2120T G630 G640 G2010 G840 G2020 G850 G645 G2030 G860 G2120 G870 G2130 G2140 E3-1220L E3-1220L E3-1260L E3-1265L E3-1220 E3-1225 E3-1220 E3-1235 E3-1225 E3-1230 E3-1230 E3-1240 E3-1245 E3-1270 E3-1275 E3-1240 E3-1245 E3-1270 E3-1280 E3-1275 E3-1290 E3-1280 E3-1290'
+};
- function wrapper() {
- var args = new Array(arguments.length)
- for (var i = 0; i < args.length; i++) {
- args[i] = arguments[i]
- }
- var ret = fn.apply(this, args)
- var cb = args[args.length-1]
- if (typeof ret === 'function' && ret !== cb) {
- Object.keys(cb).forEach(function (k) {
- ret[k] = cb[k]
- })
- }
- return ret
+function getSocketTypesByName(str) {
+ let result = '';
+ for (const key in socketTypesByName) {
+ const names = socketTypesByName[key].split(' ');
+ names.forEach(element => {
+ if (str.indexOf(element) >= 0) {
+ result = key;
+ }
+ });
}
+ return result;
}
+function cpuManufacturer(str) {
+ let result = str;
+ str = str.toLowerCase();
-/***/ }),
-
-/***/ 73700:
-/***/ ((module) => {
-
-module.exports = eval("require")("osx-temperature-sensor");
-
-
-/***/ }),
-
-/***/ 52704:
-/***/ ((module) => {
-
-module.exports = eval("require")("supports-color");
-
-
-/***/ }),
-
-/***/ 42613:
-/***/ ((module) => {
+ if (str.indexOf('intel') >= 0) { result = 'Intel'; }
+ if (str.indexOf('amd') >= 0) { result = 'AMD'; }
+ if (str.indexOf('qemu') >= 0) { result = 'QEMU'; }
+ if (str.indexOf('hygon') >= 0) { result = 'Hygon'; }
+ if (str.indexOf('centaur') >= 0) { result = 'WinChip/Via'; }
+ if (str.indexOf('vmware') >= 0) { result = 'VMware'; }
+ if (str.indexOf('Xen') >= 0) { result = 'Xen Hypervisor'; }
+ if (str.indexOf('tcg') >= 0) { result = 'QEMU'; }
+ if (str.indexOf('apple') >= 0) { result = 'Apple'; }
+ if (str.indexOf('sifive') >= 0) { result = 'SiFive'; }
+ if (str.indexOf('thead') >= 0) { result = 'T-Head'; }
+ if (str.indexOf('andestech') >= 0) { result = 'Andes Technology'; }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert");
+ return result;
+}
-/***/ }),
+function cpuBrandManufacturer(res) {
+ res.brand = res.brand.replace(/\(R\)+/g, '®').replace(/\s+/g, ' ').trim();
+ res.brand = res.brand.replace(/\(TM\)+/g, '™').replace(/\s+/g, ' ').trim();
+ res.brand = res.brand.replace(/\(C\)+/g, '©').replace(/\s+/g, ' ').trim();
+ res.brand = res.brand.replace(/CPU+/g, '').replace(/\s+/g, ' ').trim();
+ res.manufacturer = cpuManufacturer(res.brand);
-/***/ 90290:
-/***/ ((module) => {
+ let parts = res.brand.split(' ');
+ parts.shift();
+ res.brand = parts.join(' ');
+ return res;
+}
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks");
+function getAMDSpeed(brand) {
+ let result = '0';
+ for (let key in AMDBaseFrequencies) {
+ if ({}.hasOwnProperty.call(AMDBaseFrequencies, key)) {
+ let parts = key.split('|');
+ let found = 0;
+ parts.forEach(item => {
+ if (brand.indexOf(item) > -1) {
+ found++;
+ }
+ });
+ if (found === parts.length) {
+ result = AMDBaseFrequencies[key];
+ }
+ }
+ }
+ return parseFloat(result);
+}
-/***/ }),
+// --------------------------
+// CPU - brand, speed
-/***/ 20181:
-/***/ ((module) => {
+function getCpu() {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer");
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ const UNKNOWN = 'unknown';
+ let result = {
+ manufacturer: UNKNOWN,
+ brand: UNKNOWN,
+ vendor: '',
+ family: '',
+ model: '',
+ stepping: '',
+ revision: '',
+ voltage: '',
+ speed: 0,
+ speedMin: 0,
+ speedMax: 0,
+ governor: '',
+ cores: util.cores(),
+ physicalCores: util.cores(),
+ performanceCores: util.cores(),
+ efficiencyCores: 0,
+ processors: 1,
+ socket: '',
+ flags: '',
+ virtualization: false,
+ cache: {}
+ };
+ cpuFlags().then(flags => {
+ result.flags = flags;
+ result.virtualization = flags.indexOf('vmx') > -1 || flags.indexOf('svm') > -1;
+ if (_darwin) {
+ exec('sysctl machdep.cpu hw.cpufrequency_max hw.cpufrequency_min hw.packages hw.physicalcpu_max hw.ncpu hw.tbfrequency hw.cpufamily hw.cpusubfamily', function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ const modelline = util.getValue(lines, 'machdep.cpu.brand_string');
+ const modellineParts = modelline.split('@');
+ result.brand = modellineParts[0].trim();
+ const speed = modellineParts[1] ? modellineParts[1].trim() : '0';
+ result.speed = parseFloat(speed.replace(/GHz+/g, ''));
+ let tbFrequency = util.getValue(lines, 'hw.tbfrequency') / 1000000000.0;
+ tbFrequency = tbFrequency < 0.1 ? tbFrequency * 100 : tbFrequency;
+ result.speed = result.speed === 0 ? tbFrequency : result.speed;
-/***/ }),
+ _cpu_speed = result.speed;
+ result = cpuBrandManufacturer(result);
+ result.speedMin = util.getValue(lines, 'hw.cpufrequency_min') ? (util.getValue(lines, 'hw.cpufrequency_min') / 1000000000.0) : result.speed;
+ result.speedMax = util.getValue(lines, 'hw.cpufrequency_max') ? (util.getValue(lines, 'hw.cpufrequency_max') / 1000000000.0) : result.speed;
+ result.vendor = util.getValue(lines, 'machdep.cpu.vendor') || 'Apple';
+ result.family = util.getValue(lines, 'machdep.cpu.family') || util.getValue(lines, 'hw.cpufamily');
+ result.model = util.getValue(lines, 'machdep.cpu.model');
+ result.stepping = util.getValue(lines, 'machdep.cpu.stepping') || util.getValue(lines, 'hw.cpusubfamily');
+ result.virtualization = true;
+ const countProcessors = util.getValue(lines, 'hw.packages');
+ const countCores = util.getValue(lines, 'hw.physicalcpu_max');
+ const countThreads = util.getValue(lines, 'hw.ncpu');
+ if (os.arch() === 'arm64') {
+ result.socket = 'SOC';
+ try {
+ const clusters = execSync('ioreg -c IOPlatformDevice -d 3 -r | grep cluster-type').toString().split('\n');
+ const efficiencyCores = clusters.filter(line => line.indexOf('"E"') >= 0).length;
+ const performanceCores = clusters.filter(line => line.indexOf('"P"') >= 0).length;
+ result.efficiencyCores = efficiencyCores;
+ result.performanceCores = performanceCores;
+ } catch (e) {
+ util.noop();
+ }
+ }
+ if (countProcessors) {
+ result.processors = parseInt(countProcessors) || 1;
+ }
+ if (countCores && countThreads) {
+ result.cores = parseInt(countThreads) || util.cores();
+ result.physicalCores = parseInt(countCores) || util.cores();
+ }
+ cpuCache().then((res) => {
+ result.cache = res;
+ resolve(result);
+ });
+ });
+ }
+ if (_linux) {
+ let modelline = '';
+ let lines = [];
+ if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; }
+ exec('export LC_ALL=C; lscpu; echo -n "Governor: "; cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null; echo; unset LC_ALL', function (error, stdout) {
+ if (!error) {
+ lines = stdout.toString().split('\n');
+ }
+ modelline = util.getValue(lines, 'model name') || modelline;
+ modelline = util.getValue(lines, 'bios model name') || modelline;
+ modelline = util.cleanString(modelline);
+ const modellineParts = modelline.split('@');
+ result.brand = modellineParts[0].trim();
+ result.speed = modellineParts[1] ? parseFloat(modellineParts[1].trim()) : 0;
+ if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
+ result.speed = getAMDSpeed(result.brand);
+ }
+ if (result.speed === 0) {
+ const current = getCpuCurrentSpeedSync();
+ if (current.avg !== 0) { result.speed = current.avg; }
+ }
+ _cpu_speed = result.speed;
+ result.speedMin = Math.round(parseFloat(util.getValue(lines, 'cpu min mhz').replace(/,/g, '.')) / 10.0) / 100;
+ result.speedMax = Math.round(parseFloat(util.getValue(lines, 'cpu max mhz').replace(/,/g, '.')) / 10.0) / 100;
-/***/ 35317:
-/***/ ((module) => {
+ result = cpuBrandManufacturer(result);
+ result.vendor = cpuManufacturer(util.getValue(lines, 'vendor id'));
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process");
+ result.family = util.getValue(lines, 'cpu family');
+ result.model = util.getValue(lines, 'model:');
+ result.stepping = util.getValue(lines, 'stepping');
+ result.revision = util.getValue(lines, 'cpu revision');
+ result.cache.l1d = util.getValue(lines, 'l1d cache');
+ if (result.cache.l1d) { result.cache.l1d = parseInt(result.cache.l1d) * (result.cache.l1d.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1d.indexOf('K') !== -1 ? 1024 : 1)); }
+ result.cache.l1i = util.getValue(lines, 'l1i cache');
+ if (result.cache.l1i) { result.cache.l1i = parseInt(result.cache.l1i) * (result.cache.l1i.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l1i.indexOf('K') !== -1 ? 1024 : 1)); }
+ result.cache.l2 = util.getValue(lines, 'l2 cache');
+ if (result.cache.l2) { result.cache.l2 = parseInt(result.cache.l2) * (result.cache.l2.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l2.indexOf('K') !== -1 ? 1024 : 1)); }
+ result.cache.l3 = util.getValue(lines, 'l3 cache');
+ if (result.cache.l3) { result.cache.l3 = parseInt(result.cache.l3) * (result.cache.l3.indexOf('M') !== -1 ? 1024 * 1024 : (result.cache.l3.indexOf('K') !== -1 ? 1024 : 1)); }
-/***/ }),
+ const threadsPerCore = util.getValue(lines, 'thread(s) per core') || '1';
+ const processors = util.getValue(lines, 'socket(s)') || '1';
+ const threadsPerCoreInt = parseInt(threadsPerCore, 10); // threads per code (normally only for performance cores)
+ const processorsInt = parseInt(processors, 10) || 1; // number of sockets / processor units in machine (normally 1)
+ const coresPerSocket = parseInt(util.getValue(lines, 'core(s) per socket'), 10); // number of cores (e.g. 16 on i12900)
+ result.physicalCores = coresPerSocket ? coresPerSocket * processorsInt : result.cores / threadsPerCoreInt;
+ result.performanceCores = threadsPerCoreInt > 1 ? result.cores - result.physicalCores : result.cores;
+ result.efficiencyCores = threadsPerCoreInt > 1 ? result.cores - (threadsPerCoreInt * result.performanceCores) : 0;
+ result.processors = processorsInt;
+ result.governor = util.getValue(lines, 'governor') || '';
-/***/ 64236:
-/***/ ((module) => {
+ // Test Raspberry
+ if (result.vendor === 'ARM') {
+ const linesRpi = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
+ const rPIRevision = util.decodePiCpuinfo(linesRpi);
+ if (rPIRevision.model.toLowerCase().indexOf('raspberry') >= 0) {
+ result.family = result.manufacturer;
+ result.manufacturer = rPIRevision.manufacturer;
+ result.brand = rPIRevision.processor;
+ result.revision = rPIRevision.revisionCode;
+ result.socket = 'SOC';
+ }
+ }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console");
+ // Test RISC-V
+ if (util.getValue(lines, 'architecture') === 'riscv64') {
+ const linesRiscV = fs.readFileSync('/proc/cpuinfo').toString().split('\n');
+ const uarch = util.getValue(linesRiscV, 'uarch') || '';
+ if (uarch.indexOf(',') > -1) {
+ const split = uarch.split(',');
+ result.manufacturer = cpuManufacturer(split[0]);
+ result.brand = split[1];
+ }
+ }
-/***/ }),
+ // socket type
+ let lines2 = [];
+ exec('export LC_ALL=C; dmidecode –t 4 2>/dev/null | grep "Upgrade: Socket"; unset LC_ALL', function (error2, stdout2) {
+ lines2 = stdout2.toString().split('\n');
+ if (lines2 && lines2.length) {
+ result.socket = util.getValue(lines2, 'Upgrade').replace('Socket', '').trim() || result.socket;
+ }
+ resolve(result);
+ });
+ });
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ let modelline = '';
+ let lines = [];
+ if (os.cpus()[0] && os.cpus()[0].model) { modelline = os.cpus()[0].model; }
+ exec('export LC_ALL=C; dmidecode -t 4; dmidecode -t 7 unset LC_ALL', function (error, stdout) {
+ let cache = [];
+ if (!error) {
+ const data = stdout.toString().split('# dmidecode');
+ const processor = data.length > 1 ? data[1] : '';
+ cache = data.length > 2 ? data[2].split('Cache Information') : [];
-/***/ 76982:
-/***/ ((module) => {
+ lines = processor.split('\n');
+ }
+ result.brand = modelline.split('@')[0].trim();
+ result.speed = modelline.split('@')[1] ? parseFloat(modelline.split('@')[1].trim()) : 0;
+ if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
+ result.speed = getAMDSpeed(result.brand);
+ }
+ if (result.speed === 0) {
+ const current = getCpuCurrentSpeedSync();
+ if (current.avg !== 0) { result.speed = current.avg; }
+ }
+ _cpu_speed = result.speed;
+ result.speedMin = result.speed;
+ result.speedMax = Math.round(parseFloat(util.getValue(lines, 'max speed').replace(/Mhz/g, '')) / 10.0) / 100;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto");
+ result = cpuBrandManufacturer(result);
+ result.vendor = cpuManufacturer(util.getValue(lines, 'manufacturer'));
+ let sig = util.getValue(lines, 'signature');
+ sig = sig.split(',');
+ for (let i = 0; i < sig.length; i++) {
+ sig[i] = sig[i].trim();
+ }
+ result.family = util.getValue(sig, 'Family', ' ', true);
+ result.model = util.getValue(sig, 'Model', ' ', true);
+ result.stepping = util.getValue(sig, 'Stepping', ' ', true);
+ result.revision = '';
+ const voltage = parseFloat(util.getValue(lines, 'voltage'));
+ result.voltage = isNaN(voltage) ? '' : voltage.toFixed(2);
+ for (let i = 0; i < cache.length; i++) {
+ lines = cache[i].split('\n');
+ let cacheType = util.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-');
+ cacheType = cacheType.length ? cacheType[0] : '';
+ const sizeParts = util.getValue(lines, 'Installed Size').split(' ');
+ let size = parseInt(sizeParts[0], 10);
+ const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb';
+ size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1)));
+ if (cacheType) {
+ if (cacheType === 'l1') {
+ result.cache[cacheType + 'd'] = size / 2;
+ result.cache[cacheType + 'i'] = size / 2;
+ } else {
+ result.cache[cacheType] = size;
+ }
+ }
+ }
+ // socket type
+ result.socket = util.getValue(lines, 'Upgrade').replace('Socket', '').trim();
+ // # threads / # cores
+ const threadCount = util.getValue(lines, 'thread count').trim();
+ const coreCount = util.getValue(lines, 'core count').trim();
+ if (coreCount && threadCount) {
+ result.cores = parseInt(threadCount, 10);
+ result.physicalCores = parseInt(coreCount, 10);
+ }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ resolve(result);
+ }
+ if (_windows) {
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance Win32_processor | select Name, Revision, L2CacheSize, L3CacheSize, Manufacturer, MaxClockSpeed, Description, UpgradeMethod, Caption, NumberOfLogicalProcessors, NumberOfCores | fl'));
+ workload.push(util.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl'));
+ workload.push(util.powerShell('(Get-CimInstance Win32_ComputerSystem).HypervisorPresent'));
-/***/ }),
+ Promise.all(
+ workload
+ ).then((data) => {
+ let lines = data[0].split('\r\n');
+ let name = util.getValue(lines, 'name', ':') || '';
+ if (name.indexOf('@') >= 0) {
+ result.brand = name.split('@')[0].trim();
+ result.speed = name.split('@')[1] ? parseFloat(name.split('@')[1].trim()) : 0;
+ _cpu_speed = result.speed;
+ } else {
+ result.brand = name.trim();
+ result.speed = 0;
+ }
+ result = cpuBrandManufacturer(result);
+ result.revision = util.getValue(lines, 'revision', ':');
+ result.vendor = util.getValue(lines, 'manufacturer', ':');
+ result.speedMax = Math.round(parseFloat(util.getValue(lines, 'maxclockspeed', ':').replace(/,/g, '.')) / 10.0) / 100;
+ if (result.speed === 0 && (result.brand.indexOf('AMD') > -1 || result.brand.toLowerCase().indexOf('ryzen') > -1)) {
+ result.speed = getAMDSpeed(result.brand);
+ }
+ if (result.speed === 0) {
+ result.speed = result.speedMax;
+ }
+ result.speedMin = result.speed;
-/***/ 31637:
-/***/ ((module) => {
+ let description = util.getValue(lines, 'description', ':').split(' ');
+ for (let i = 0; i < description.length; i++) {
+ if (description[i].toLowerCase().startsWith('family') && (i + 1) < description.length && description[i + 1]) {
+ result.family = description[i + 1];
+ }
+ if (description[i].toLowerCase().startsWith('model') && (i + 1) < description.length && description[i + 1]) {
+ result.model = description[i + 1];
+ }
+ if (description[i].toLowerCase().startsWith('stepping') && (i + 1) < description.length && description[i + 1]) {
+ result.stepping = description[i + 1];
+ }
+ }
+ // socket type
+ const socketId = util.getValue(lines, 'UpgradeMethod', ':');
+ if (socketTypes[socketId]) {
+ result.socket = socketTypes[socketId];
+ }
+ const socketByName = getSocketTypesByName(name);
+ if (socketByName) {
+ result.socket = socketByName;
+ }
+ // # threads / # cores
+ const countProcessors = util.countLines(lines, 'Caption');
+ const countThreads = util.getValue(lines, 'NumberOfLogicalProcessors', ':');
+ const countCores = util.getValue(lines, 'NumberOfCores', ':');
+ if (countProcessors) {
+ result.processors = parseInt(countProcessors) || 1;
+ }
+ if (countCores && countThreads) {
+ result.cores = parseInt(countThreads) || util.cores();
+ result.physicalCores = parseInt(countCores) || util.cores();
+ }
+ if (countProcessors > 1) {
+ result.cores = result.cores * countProcessors;
+ result.physicalCores = result.physicalCores * countProcessors;
+ }
+ result.cache = parseWinCache(data[0], data[1]);
+ const hyperv = data[2] ? data[2].toString().toLowerCase() : '';
+ result.virtualization = hyperv.indexOf('true') !== -1;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel");
+ resolve(result);
+ });
+ } catch (e) {
+ resolve(result);
+ }
+ }
+ });
+ });
+ });
+}
-/***/ }),
+// --------------------------
+// CPU - Processor Data
-/***/ 24434:
-/***/ ((module) => {
+function cpu(callback) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events");
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ getCpu().then(result => {
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ });
+}
-/***/ }),
+exports.cpu = cpu;
-/***/ 79896:
-/***/ ((module) => {
+// --------------------------
+// CPU - current speed - in GHz
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs");
+function getCpuCurrentSpeedSync() {
-/***/ }),
+ let cpus = os.cpus();
+ let minFreq = 999999999;
+ let maxFreq = 0;
+ let avgFreq = 0;
+ let cores = [];
+ let speeds = [];
-/***/ 58611:
-/***/ ((module) => {
+ if (cpus && cpus.length && cpus[0].speed) {
+ for (let i in cpus) {
+ speeds.push(cpus[i].speed > 100 ? (cpus[i].speed + 1) / 1000 : cpus[i].speed / 10);
+ }
+ } else if (_linux) {
+ try {
+ const speedStrings = execSync('cat /proc/cpuinfo | grep "cpu MHz" | cut -d " " -f 3', util.execOptsLinux).toString().split('\n').filter((line) => line.length > 0);
+ for (let i in speedStrings) {
+ speeds.push(Math.floor(parseInt(speedStrings[i], 10) / 10) / 100);
+ }
+ } catch {
+ util.noop();
+ }
+ }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http");
+ if (speeds && speeds.length) {
+ for (let i in speeds) {
+ avgFreq = avgFreq + speeds[i];
+ if (speeds[i] > maxFreq) { maxFreq = speeds[i]; }
+ if (speeds[i] < minFreq) { minFreq = speeds[i]; }
+ cores.push(parseFloat(speeds[i].toFixed(2)));
+ }
+ avgFreq = avgFreq / speeds.length;
+ return {
+ min: parseFloat(minFreq.toFixed(2)),
+ max: parseFloat(maxFreq.toFixed(2)),
+ avg: parseFloat((avgFreq).toFixed(2)),
+ cores: cores
+ };
+ } else {
+ return {
+ min: 0,
+ max: 0,
+ avg: 0,
+ cores: cores
+ };
+ }
+}
-/***/ }),
+function cpuCurrentSpeed(callback) {
-/***/ 85675:
-/***/ ((module) => {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = getCpuCurrentSpeedSync();
+ if (result.avg === 0 && _cpu_speed !== 0) {
+ const currCpuSpeed = parseFloat(_cpu_speed);
+ result = {
+ min: currCpuSpeed,
+ max: currCpuSpeed,
+ avg: currCpuSpeed,
+ cores: []
+ };
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+}
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2");
+exports.cpuCurrentSpeed = cpuCurrentSpeed;
-/***/ }),
+// --------------------------
+// CPU - temperature
+// if sensors are installed
-/***/ 65692:
-/***/ ((module) => {
+function cpuTemperature(callback) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https");
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ main: null,
+ cores: [],
+ max: null,
+ socket: [],
+ chipset: null
+ };
+ if (_linux) {
+ // CPU Chipset, Socket
+ try {
+ const cmd = 'cat /sys/class/thermal/thermal_zone*/type 2>/dev/null; echo "-----"; cat /sys/class/thermal/thermal_zone*/temp 2>/dev/null;';
+ const parts = execSync(cmd, util.execOptsLinux).toString().split('-----\n');
+ if (parts.length === 2) {
+ const lines = parts[0].split('\n');
+ const lines2 = parts[1].split('\n');
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].trim();
+ if (line.startsWith('acpi') && lines2[i]) {
+ result.socket.push(Math.round(parseInt(lines2[i], 10) / 100) / 10);
+ }
+ if (line.startsWith('pch') && lines2[i]) {
+ result.chipset = Math.round(parseInt(lines2[i], 10) / 100) / 10;
+ }
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
-/***/ }),
+ const cmd = 'for mon in /sys/class/hwmon/hwmon*; do for label in "$mon"/temp*_label; do if [ -f $label ]; then value=${label%_*}_input; echo $(cat "$label")___$(cat "$value"); fi; done; done;';
+ try {
+ exec(cmd, function (error, stdout) {
+ stdout = stdout.toString();
+ const tdiePos = stdout.toLowerCase().indexOf('tdie');
+ if (tdiePos !== -1) {
+ stdout = stdout.substring(tdiePos);
+ }
+ let lines = stdout.split('\n');
+ let tctl = 0;
+ lines.forEach(line => {
+ const parts = line.split('___');
+ const label = parts[0];
+ const value = parts.length > 1 && parts[1] ? parts[1] : '0';
+ if (value && label && label.toLowerCase() === 'tctl') {
+ tctl = result.main = Math.round(parseInt(value, 10) / 100) / 10;
+ }
+ if (value && (label === undefined || (label && label.toLowerCase().startsWith('core')))) {
+ result.cores.push(Math.round(parseInt(value, 10) / 100) / 10);
+ } else if (value && label && result.main === null && (label.toLowerCase().indexOf('package') >= 0 || label.toLowerCase().indexOf('physical') >= 0 || label.toLowerCase() === 'tccd1')) {
+ result.main = Math.round(parseInt(value, 10) / 100) / 10;
+ }
+ });
+ if (tctl && result.main === null) {
+ result.main = tctl;
+ }
-/***/ 69278:
-/***/ ((module) => {
+ if (result.cores.length > 0) {
+ if (result.main === null) {
+ result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length);
+ }
+ let maxtmp = Math.max.apply(Math, result.cores);
+ result.max = (maxtmp > result.main) ? maxtmp : result.main;
+ }
+ if (result.main !== null) {
+ if (result.max === null) {
+ result.max = result.main;
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ return;
+ }
+ exec('sensors', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ let tdieTemp = null;
+ let newSectionStarts = true;
+ let section = '';
+ lines.forEach(function (line) {
+ // determine section
+ if (line.trim() === '') {
+ newSectionStarts = true;
+ } else if (newSectionStarts) {
+ if (line.trim().toLowerCase().startsWith('acpi')) { section = 'acpi'; }
+ if (line.trim().toLowerCase().startsWith('pch')) { section = 'pch'; }
+ if (line.trim().toLowerCase().startsWith('core')) { section = 'core'; }
+ newSectionStarts = false;
+ }
+ let regex = /[+-]([^°]*)/g;
+ let temps = line.match(regex);
+ let firstPart = line.split(':')[0].toUpperCase();
+ if (section === 'acpi') {
+ // socket temp
+ if (firstPart.indexOf('TEMP') !== -1) {
+ result.socket.push(parseFloat(temps));
+ }
+ } else if (section === 'pch') {
+ // chipset temp
+ if (firstPart.indexOf('TEMP') !== -1 && !result.chipset) {
+ result.chipset = parseFloat(temps);
+ }
+ }
+ // cpu temp
+ if (firstPart.indexOf('PHYSICAL') !== -1 || firstPart.indexOf('PACKAGE') !== -1) {
+ result.main = parseFloat(temps);
+ }
+ if (firstPart.indexOf('CORE ') !== -1) {
+ result.cores.push(parseFloat(temps));
+ }
+ if (firstPart.indexOf('TDIE') !== -1 && tdieTemp === null) {
+ tdieTemp = parseFloat(temps);
+ }
+ });
+ if (result.cores.length > 0) {
+ result.main = Math.round(result.cores.reduce((a, b) => a + b, 0) / result.cores.length);
+ let maxtmp = Math.max.apply(Math, result.cores);
+ result.max = (maxtmp > result.main) ? maxtmp : result.main;
+ } else {
+ if (result.main === null && tdieTemp !== null) {
+ result.main = tdieTemp;
+ result.max = tdieTemp;
+ }
+ }
+ if (result.main !== null || result.max !== null) {
+ if (callback) { callback(result); }
+ resolve(result);
+ return;
+ }
+ }
+ fs.stat('/sys/class/thermal/thermal_zone0/temp', function (err) {
+ if (err === null) {
+ fs.readFile('/sys/class/thermal/thermal_zone0/temp', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 0) {
+ result.main = parseFloat(lines[0]) / 1000.0;
+ result.max = result.main;
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ exec('/opt/vc/bin/vcgencmd measure_temp', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 0 && lines[0].indexOf('=')) {
+ result.main = parseFloat(lines[0].split('=')[1]);
+ result.max = result.main;
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ });
+ });
+ });
+ } catch (er) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ exec('sysctl dev.cpu | grep temp', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ let sum = 0;
+ lines.forEach(function (line) {
+ const parts = line.split(':');
+ if (parts.length > 1) {
+ const temp = parseFloat(parts[1].replace(',', '.'));
+ if (temp > result.max) { result.max = temp; }
+ sum = sum + temp;
+ result.cores.push(temp);
+ }
+ });
+ if (result.cores.length) {
+ result.main = Math.round(sum / result.cores.length * 100) / 100;
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ let osxTemp = null;
+ try {
+ osxTemp = __nccwpck_require__(73700);
+ } catch (er) {
+ osxTemp = null;
+ }
+ if (osxTemp) {
+ result = osxTemp.cpuTemperature();
+ // round to 2 digits
+ if (result.main) {
+ result.main = Math.round(result.main * 100) / 100;
+ }
+ if (result.max) {
+ result.max = Math.round(result.max * 100) / 100;
+ }
+ if (result.cores && result.cores.length) {
+ for (let i = 0; i < result.cores.length; i++) {
+ result.cores[i] = Math.round(result.cores[i] * 100) / 100;
+ }
+ }
+ }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net");
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_windows) {
+ try {
+ util.powerShell('Get-CimInstance MSAcpi_ThermalZoneTemperature -Namespace "root/wmi" | Select CurrentTemperature').then((stdout, error) => {
+ if (!error) {
+ let sum = 0;
+ let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
+ lines.forEach(function (line) {
+ let value = (parseInt(line, 10) - 2732) / 10;
+ if (!isNaN(value)) {
+ sum = sum + value;
+ if (value > result.max) { result.max = value; }
+ result.cores.push(value);
+ }
+ });
+ if (result.cores.length) {
+ result.main = sum / result.cores.length;
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ });
+ });
+}
-/***/ }),
+exports.cpuTemperature = cpuTemperature;
-/***/ 4573:
-/***/ ((module) => {
+// --------------------------
+// CPU Flags
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:buffer");
+function cpuFlags(callback) {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = '';
+ if (_windows) {
+ try {
+ exec('reg query "HKEY_LOCAL_MACHINE\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0" /v FeatureSet', util.execOptsWin, function (error, stdout) {
+ if (!error) {
+ let flag_hex = stdout.split('0x').pop().trim();
+ let flag_bin_unpadded = parseInt(flag_hex, 16).toString(2);
+ let flag_bin = '0'.repeat(32 - flag_bin_unpadded.length) + flag_bin_unpadded;
+ // empty flags are the reserved fields in the CPUID feature bit list
+ // as found on wikipedia:
+ // https://en.wikipedia.org/wiki/CPUID
+ let all_flags = [
+ 'fpu', 'vme', 'de', 'pse', 'tsc', 'msr', 'pae', 'mce', 'cx8', 'apic',
+ '', 'sep', 'mtrr', 'pge', 'mca', 'cmov', 'pat', 'pse-36', 'psn', 'clfsh',
+ '', 'ds', 'acpi', 'mmx', 'fxsr', 'sse', 'sse2', 'ss', 'htt', 'tm', 'ia64', 'pbe'
+ ];
+ for (let f = 0; f < all_flags.length; f++) {
+ if (flag_bin[f] === '1' && all_flags[f] !== '') {
+ result += ' ' + all_flags[f];
+ }
+ }
+ result = result.trim().toLowerCase();
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_linux) {
+ try {
-/***/ 78474:
-/***/ ((module) => {
+ exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ if (line.split(':')[0].toUpperCase().indexOf('FLAGS') !== -1) {
+ result = line.split(':')[1].trim().toLowerCase();
+ }
+ });
+ }
+ if (!result) {
+ fs.readFile('/proc/cpuinfo', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result = util.getValue(lines, 'features', ':', true).toLowerCase();
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ exec('export LC_ALL=C; dmidecode -t 4 2>/dev/null; unset LC_ALL', function (error, stdout) {
+ let flags = [];
+ if (!error) {
+ let parts = stdout.toString().split('\tFlags:');
+ const lines = parts.length > 1 ? parts[1].split('\tVersion:')[0].split('\n') : [];
+ lines.forEach(function (line) {
+ let flag = (line.indexOf('(') ? line.split('(')[0].toLowerCase() : '').trim().replace(/\t/g, '');
+ if (flag) {
+ flags.push(flag);
+ }
+ });
+ }
+ result = flags.join(' ').trim().toLowerCase();
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ exec('sysctl machdep.cpu.features', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 0 && lines[0].indexOf('machdep.cpu.features:') !== -1) {
+ result = lines[0].split(':')[1].trim().toLowerCase();
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+}
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events");
+exports.cpuFlags = cpuFlags;
-/***/ }),
+// --------------------------
+// CPU Cache
-/***/ 37067:
-/***/ ((module) => {
+function cpuCache(callback) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:http");
+ return new Promise((resolve) => {
+ process.nextTick(() => {
-/***/ }),
+ let result = {
+ l1d: null,
+ l1i: null,
+ l2: null,
+ l3: null,
+ };
+ if (_linux) {
+ try {
+ exec('export LC_ALL=C; lscpu; unset LC_ALL', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ let parts = line.split(':');
+ if (parts[0].toUpperCase().indexOf('L1D CACHE') !== -1) {
+ result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
+ }
+ if (parts[0].toUpperCase().indexOf('L1I CACHE') !== -1) {
+ result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
+ }
+ if (parts[0].toUpperCase().indexOf('L2 CACHE') !== -1) {
+ result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
+ }
+ if (parts[0].toUpperCase().indexOf('L3 CACHE') !== -1) {
+ result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('M') !== -1 ? 1024 * 1024 : (parts[1].indexOf('K') !== -1 ? 1024 : 1));
+ }
+ });
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ exec('export LC_ALL=C; dmidecode -t 7 2>/dev/null; unset LC_ALL', function (error, stdout) {
+ let cache = [];
+ if (!error) {
+ const data = stdout.toString();
+ cache = data.split('Cache Information');
+ cache.shift();
+ }
+ for (let i = 0; i < cache.length; i++) {
+ const lines = cache[i].split('\n');
+ let cacheType = util.getValue(lines, 'Socket Designation').toLowerCase().replace(' ', '-').split('-');
+ cacheType = cacheType.length ? cacheType[0] : '';
+ const sizeParts = util.getValue(lines, 'Installed Size').split(' ');
+ let size = parseInt(sizeParts[0], 10);
+ const unit = sizeParts.length > 1 ? sizeParts[1] : 'kb';
+ size = size * (unit === 'kb' ? 1024 : (unit === 'mb' ? 1024 * 1024 : (unit === 'gb' ? 1024 * 1024 * 1024 : 1)));
+ if (cacheType) {
+ if (cacheType === 'l1') {
+ result.cache[cacheType + 'd'] = size / 2;
+ result.cache[cacheType + 'i'] = size / 2;
+ } else {
+ result.cache[cacheType] = size;
+ }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ exec('sysctl hw.l1icachesize hw.l1dcachesize hw.l2cachesize hw.l3cachesize', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ let parts = line.split(':');
+ if (parts[0].toLowerCase().indexOf('hw.l1icachesize') !== -1) {
+ result.l1d = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
+ }
+ if (parts[0].toLowerCase().indexOf('hw.l1dcachesize') !== -1) {
+ result.l1i = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
+ }
+ if (parts[0].toLowerCase().indexOf('hw.l2cachesize') !== -1) {
+ result.l2 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
+ }
+ if (parts[0].toLowerCase().indexOf('hw.l3cachesize') !== -1) {
+ result.l3 = parseInt(parts[1].trim()) * (parts[1].indexOf('K') !== -1 ? 1024 : 1);
+ }
+ });
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_windows) {
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance Win32_processor | select L2CacheSize, L3CacheSize | fl'));
+ workload.push(util.powerShell('Get-CimInstance Win32_CacheMemory | select CacheType,InstalledSize,Level | fl'));
-/***/ 44708:
-/***/ ((module) => {
+ Promise.all(
+ workload
+ ).then((data) => {
+ result = parseWinCache(data[0], data[1]);
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:https");
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ });
+ });
+}
-/***/ }),
+function parseWinCache(linesProc, linesCache) {
+ let result = {
+ l1d: null,
+ l1i: null,
+ l2: null,
+ l3: null,
+ };
-/***/ 48161:
-/***/ ((module) => {
+ // Win32_processor
+ let lines = linesProc.split('\r\n');
+ result.l1d = 0;
+ result.l1i = 0;
+ result.l2 = util.getValue(lines, 'l2cachesize', ':');
+ result.l3 = util.getValue(lines, 'l3cachesize', ':');
+ if (result.l2) { result.l2 = parseInt(result.l2, 10) * 1024; } else { result.l2 = 0; }
+ if (result.l3) { result.l3 = parseInt(result.l3, 10) * 1024; } else { result.l3 = 0; }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:os");
+ // Win32_CacheMemory
+ const parts = linesCache.split(/\n\s*\n/);
+ let l1i = 0;
+ let l1d = 0;
+ let l2 = 0;
+ parts.forEach(function (part) {
+ const lines = part.split('\r\n');
+ const cacheType = util.getValue(lines, 'CacheType');
+ const level = util.getValue(lines, 'Level');
+ const installedSize = util.getValue(lines, 'InstalledSize');
+ // L1 Instructions
+ if (level === '3' && cacheType === '3') {
+ result.l1i = result.l1i + parseInt(installedSize, 10) * 1024;
+ }
+ // L1 Data
+ if (level === '3' && cacheType === '4') {
+ result.l1d = result.l1d + parseInt(installedSize, 10) * 1024;
+ }
+ // L1 all
+ if (level === '3' && cacheType === '5') {
+ l1i = parseInt(installedSize, 10) / 2;
+ l1d = parseInt(installedSize, 10) / 2;
+ }
+ // L2
+ if (level === '4' && cacheType === '5') {
+ l2 = l2 + parseInt(installedSize, 10) * 1024;
+ }
+ });
+ if (!result.l1i && !result.l1d) {
+ result.l1i = l1i;
+ result.l1d = l1d;
+ }
+ if (l2) {
+ result.l2 = l2;
+ }
+ return result;
+}
-/***/ }),
+exports.cpuCache = cpuCache;
-/***/ 1708:
-/***/ ((module) => {
+// --------------------------
+// CPU - current load - in %
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:process");
+function getLoad() {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let loads = os.loadavg().map(function (x) { return x / util.cores(); });
+ let avgLoad = parseFloat((Math.max.apply(Math, loads)).toFixed(2));
+ let result = {};
-/***/ 57075:
-/***/ ((module) => {
+ let now = Date.now() - _current_cpu.ms;
+ if (now >= 200) {
+ _current_cpu.ms = Date.now();
+ const cpus = os.cpus().map(function (cpu) {
+ cpu.times.steal = 0;
+ cpu.times.guest = 0;
+ return cpu;
+ });
+ let totalUser = 0;
+ let totalSystem = 0;
+ let totalNice = 0;
+ let totalIrq = 0;
+ let totalIdle = 0;
+ let totalSteal = 0;
+ let totalGuest = 0;
+ let cores = [];
+ _corecount = (cpus && cpus.length) ? cpus.length : 0;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream");
+ // linux: try to get other cpu stats
+ if (_linux) {
+ try {
+ const lines = execSync('cat /proc/stat 2>/dev/null | grep cpu', util.execOptsLinux).toString().split('\n');
+ if (lines.length > 1) {
+ lines.shift();
+ if (lines.length === cpus.length) {
+ for (let i = 0; i < lines.length; i++) {
+ let parts = lines[i].split(' ');
+ if (parts.length >= 10) {
+ const steal = parseFloat(parts[8]) || 0;
+ const guest = parseFloat(parts[9]) || 0;
+ cpus[i].times.steal = steal;
+ cpus[i].times.guest = guest;
+ }
+ }
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
+ }
-/***/ }),
+ for (let i = 0; i < _corecount; i++) {
+ const cpu = cpus[i].times;
+ totalUser += cpu.user;
+ totalSystem += cpu.sys;
+ totalNice += cpu.nice;
+ totalIdle += cpu.idle;
+ totalIrq += cpu.irq;
+ totalSteal += cpu.steal || 0;
+ totalGuest += cpu.guest || 0;
+ let tmpTick = (_cpus && _cpus[i] && _cpus[i].totalTick ? _cpus[i].totalTick : 0);
+ let tmpLoad = (_cpus && _cpus[i] && _cpus[i].totalLoad ? _cpus[i].totalLoad : 0);
+ let tmpUser = (_cpus && _cpus[i] && _cpus[i].user ? _cpus[i].user : 0);
+ let tmpSystem = (_cpus && _cpus[i] && _cpus[i].sys ? _cpus[i].sys : 0);
+ let tmpNice = (_cpus && _cpus[i] && _cpus[i].nice ? _cpus[i].nice : 0);
+ let tmpIdle = (_cpus && _cpus[i] && _cpus[i].idle ? _cpus[i].idle : 0);
+ let tmpIrq = (_cpus && _cpus[i] && _cpus[i].irq ? _cpus[i].irq : 0);
+ let tmpSteal = (_cpus && _cpus[i] && _cpus[i].steal ? _cpus[i].steal : 0);
+ let tmpGuest = (_cpus && _cpus[i] && _cpus[i].guest ? _cpus[i].guest : 0);
+ _cpus[i] = cpu;
+ _cpus[i].totalTick = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest + _cpus[i].idle;
+ _cpus[i].totalLoad = _cpus[i].user + _cpus[i].sys + _cpus[i].nice + _cpus[i].irq + _cpus[i].steal + _cpus[i].guest;
+ _cpus[i].currentTick = _cpus[i].totalTick - tmpTick;
+ _cpus[i].load = (_cpus[i].totalLoad - tmpLoad);
+ _cpus[i].loadUser = (_cpus[i].user - tmpUser);
+ _cpus[i].loadSystem = (_cpus[i].sys - tmpSystem);
+ _cpus[i].loadNice = (_cpus[i].nice - tmpNice);
+ _cpus[i].loadIdle = (_cpus[i].idle - tmpIdle);
+ _cpus[i].loadIrq = (_cpus[i].irq - tmpIrq);
+ _cpus[i].loadSteal = (_cpus[i].steal - tmpSteal);
+ _cpus[i].loadGuest = (_cpus[i].guest - tmpGuest);
+ cores[i] = {};
+ cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
+ cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100;
+ cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100;
+ cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100;
+ cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100;
+ cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100;
+ cores[i].loadSteal = _cpus[i].loadSteal / _cpus[i].currentTick * 100;
+ cores[i].loadGuest = _cpus[i].loadGuest / _cpus[i].currentTick * 100;
+ cores[i].rawLoad = _cpus[i].load;
+ cores[i].rawLoadUser = _cpus[i].loadUser;
+ cores[i].rawLoadSystem = _cpus[i].loadSystem;
+ cores[i].rawLoadNice = _cpus[i].loadNice;
+ cores[i].rawLoadIdle = _cpus[i].loadIdle;
+ cores[i].rawLoadIrq = _cpus[i].loadIrq;
+ cores[i].rawLoadSteal = _cpus[i].loadSteal;
+ cores[i].rawLoadGuest = _cpus[i].loadGuest;
+ }
+ let totalTick = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest + totalIdle;
+ let totalLoad = totalUser + totalSystem + totalNice + totalIrq + totalSteal + totalGuest;
+ let currentTick = totalTick - _current_cpu.tick;
+ result = {
+ avgLoad: avgLoad,
+ currentLoad: (totalLoad - _current_cpu.load) / currentTick * 100,
+ currentLoadUser: (totalUser - _current_cpu.user) / currentTick * 100,
+ currentLoadSystem: (totalSystem - _current_cpu.system) / currentTick * 100,
+ currentLoadNice: (totalNice - _current_cpu.nice) / currentTick * 100,
+ currentLoadIdle: (totalIdle - _current_cpu.idle) / currentTick * 100,
+ currentLoadIrq: (totalIrq - _current_cpu.irq) / currentTick * 100,
+ currentLoadSteal: (totalSteal - _current_cpu.steal) / currentTick * 100,
+ currentLoadGuest: (totalGuest - _current_cpu.guest) / currentTick * 100,
+ rawCurrentLoad: (totalLoad - _current_cpu.load),
+ rawCurrentLoadUser: (totalUser - _current_cpu.user),
+ rawCurrentLoadSystem: (totalSystem - _current_cpu.system),
+ rawCurrentLoadNice: (totalNice - _current_cpu.nice),
+ rawCurrentLoadIdle: (totalIdle - _current_cpu.idle),
+ rawCurrentLoadIrq: (totalIrq - _current_cpu.irq),
+ rawCurrentLoadSteal: (totalSteal - _current_cpu.steal),
+ rawCurrentLoadGuest: (totalGuest - _current_cpu.guest),
+ cpus: cores
+ };
+ _current_cpu = {
+ user: totalUser,
+ nice: totalNice,
+ system: totalSystem,
+ idle: totalIdle,
+ irq: totalIrq,
+ steal: totalSteal,
+ guest: totalGuest,
+ tick: totalTick,
+ load: totalLoad,
+ ms: _current_cpu.ms,
+ currentLoad: result.currentLoad,
+ currentLoadUser: result.currentLoadUser,
+ currentLoadSystem: result.currentLoadSystem,
+ currentLoadNice: result.currentLoadNice,
+ currentLoadIdle: result.currentLoadIdle,
+ currentLoadIrq: result.currentLoadIrq,
+ currentLoadSteal: result.currentLoadSteal,
+ currentLoadGuest: result.currentLoadGuest,
+ rawCurrentLoad: result.rawCurrentLoad,
+ rawCurrentLoadUser: result.rawCurrentLoadUser,
+ rawCurrentLoadSystem: result.rawCurrentLoadSystem,
+ rawCurrentLoadNice: result.rawCurrentLoadNice,
+ rawCurrentLoadIdle: result.rawCurrentLoadIdle,
+ rawCurrentLoadIrq: result.rawCurrentLoadIrq,
+ rawCurrentLoadSteal: result.rawCurrentLoadSteal,
+ rawCurrentLoadGuest: result.rawCurrentLoadGuest,
+ };
+ } else {
+ let cores = [];
+ for (let i = 0; i < _corecount; i++) {
+ cores[i] = {};
+ cores[i].load = _cpus[i].load / _cpus[i].currentTick * 100;
+ cores[i].loadUser = _cpus[i].loadUser / _cpus[i].currentTick * 100;
+ cores[i].loadSystem = _cpus[i].loadSystem / _cpus[i].currentTick * 100;
+ cores[i].loadNice = _cpus[i].loadNice / _cpus[i].currentTick * 100;
+ cores[i].loadIdle = _cpus[i].loadIdle / _cpus[i].currentTick * 100;
+ cores[i].loadIrq = _cpus[i].loadIrq / _cpus[i].currentTick * 100;
+ cores[i].rawLoad = _cpus[i].load;
+ cores[i].rawLoadUser = _cpus[i].loadUser;
+ cores[i].rawLoadSystem = _cpus[i].loadSystem;
+ cores[i].rawLoadNice = _cpus[i].loadNice;
+ cores[i].rawLoadIdle = _cpus[i].loadIdle;
+ cores[i].rawLoadIrq = _cpus[i].loadIrq;
+ cores[i].rawLoadSteal = _cpus[i].loadSteal;
+ cores[i].rawLoadGuest = _cpus[i].loadGuest;
+ }
+ result = {
+ avgLoad: avgLoad,
+ currentLoad: _current_cpu.currentLoad,
+ currentLoadUser: _current_cpu.currentLoadUser,
+ currentLoadSystem: _current_cpu.currentLoadSystem,
+ currentLoadNice: _current_cpu.currentLoadNice,
+ currentLoadIdle: _current_cpu.currentLoadIdle,
+ currentLoadIrq: _current_cpu.currentLoadIrq,
+ currentLoadSteal: _current_cpu.currentLoadSteal,
+ currentLoadGuest: _current_cpu.currentLoadGuest,
+ rawCurrentLoad: _current_cpu.rawCurrentLoad,
+ rawCurrentLoadUser: _current_cpu.rawCurrentLoadUser,
+ rawCurrentLoadSystem: _current_cpu.rawCurrentLoadSystem,
+ rawCurrentLoadNice: _current_cpu.rawCurrentLoadNice,
+ rawCurrentLoadIdle: _current_cpu.rawCurrentLoadIdle,
+ rawCurrentLoadIrq: _current_cpu.rawCurrentLoadIrq,
+ rawCurrentLoadSteal: _current_cpu.rawCurrentLoadSteal,
+ rawCurrentLoadGuest: _current_cpu.rawCurrentLoadGuest,
+ cpus: cores
+ };
+ }
+ resolve(result);
+ });
+ });
+}
-/***/ 57975:
-/***/ ((module) => {
+function currentLoad(callback) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util");
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ getLoad().then(result => {
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ });
+}
-/***/ }),
+exports.currentLoad = currentLoad;
-/***/ 38522:
-/***/ ((module) => {
+// --------------------------
+// PS - full load
+// since bootup
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:zlib");
+function getFullLoad() {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
-/***/ 70857:
-/***/ ((module) => {
+ const cpus = os.cpus();
+ let totalUser = 0;
+ let totalSystem = 0;
+ let totalNice = 0;
+ let totalIrq = 0;
+ let totalIdle = 0;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os");
+ let result = 0;
-/***/ }),
+ if (cpus && cpus.length) {
+ for (let i = 0, len = cpus.length; i < len; i++) {
+ const cpu = cpus[i].times;
+ totalUser += cpu.user;
+ totalSystem += cpu.sys;
+ totalNice += cpu.nice;
+ totalIrq += cpu.irq;
+ totalIdle += cpu.idle;
+ }
+ let totalTicks = totalIdle + totalIrq + totalNice + totalSystem + totalUser;
+ result = (totalTicks - totalIdle) / totalTicks * 100.0;
-/***/ 16928:
-/***/ ((module) => {
+ }
+ resolve(result);
+ });
+ });
+}
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path");
+function fullLoad(callback) {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ getFullLoad().then(result => {
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ });
+}
-/***/ 82987:
-/***/ ((module) => {
+exports.fullLoad = fullLoad;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks");
/***/ }),
-/***/ 83480:
-/***/ ((module) => {
+/***/ 81820:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring");
-/***/ }),
+// @ts-check
+// ==================================================================================
+// docker.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 13. Docker
+// ----------------------------------------------------------------------------------
-/***/ 2203:
-/***/ ((module) => {
+const util = __nccwpck_require__(77496);
+const DockerSocket = __nccwpck_require__(23945);
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream");
+let _platform = process.platform;
+const _windows = (_platform === 'win32');
-/***/ }),
+let _docker_container_stats = {};
+let _docker_socket;
+let _docker_last_read = 0;
-/***/ 63774:
-/***/ ((module) => {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web");
+// --------------------------
+// get containers (parameter all: get also inactive/exited containers)
-/***/ }),
+function dockerInfo(callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
+ const result = {};
-/***/ 13193:
-/***/ ((module) => {
+ _docker_socket.getInfo((data) => {
+ result.id = data.ID;
+ result.containers = data.Containers;
+ result.containersRunning = data.ContainersRunning;
+ result.containersPaused = data.ContainersPaused;
+ result.containersStopped = data.ContainersStopped;
+ result.images = data.Images;
+ result.driver = data.Driver;
+ result.memoryLimit = data.MemoryLimit;
+ result.swapLimit = data.SwapLimit;
+ result.kernelMemory = data.KernelMemory;
+ result.cpuCfsPeriod = data.CpuCfsPeriod;
+ result.cpuCfsQuota = data.CpuCfsQuota;
+ result.cpuShares = data.CPUShares;
+ result.cpuSet = data.CPUSet;
+ result.ipv4Forwarding = data.IPv4Forwarding;
+ result.bridgeNfIptables = data.BridgeNfIptables;
+ result.bridgeNfIp6tables = data.BridgeNfIp6tables;
+ result.debug = data.Debug;
+ result.nfd = data.NFd;
+ result.oomKillDisable = data.OomKillDisable;
+ result.ngoroutines = data.NGoroutines;
+ result.systemTime = data.SystemTime;
+ result.loggingDriver = data.LoggingDriver;
+ result.cgroupDriver = data.CgroupDriver;
+ result.nEventsListener = data.NEventsListener;
+ result.kernelVersion = data.KernelVersion;
+ result.operatingSystem = data.OperatingSystem;
+ result.osType = data.OSType;
+ result.architecture = data.Architecture;
+ result.ncpu = data.NCPU;
+ result.memTotal = data.MemTotal;
+ result.dockerRootDir = data.DockerRootDir;
+ result.httpProxy = data.HttpProxy;
+ result.httpsProxy = data.HttpsProxy;
+ result.noProxy = data.NoProxy;
+ result.name = data.Name;
+ result.labels = data.Labels;
+ result.experimentalBuild = data.ExperimentalBuild;
+ result.serverVersion = data.ServerVersion;
+ result.clusterStore = data.ClusterStore;
+ result.clusterAdvertise = data.ClusterAdvertise;
+ result.defaultRuntime = data.DefaultRuntime;
+ result.liveRestoreEnabled = data.LiveRestoreEnabled;
+ result.isolation = data.Isolation;
+ result.initBinary = data.InitBinary;
+ result.productLicense = data.ProductLicense;
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ });
+}
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder");
+exports.dockerInfo = dockerInfo;
-/***/ }),
+function dockerImages(all, callback) {
-/***/ 53557:
-/***/ ((module) => {
+ // fallback - if only callback is given
+ if (util.isFunction(all) && !callback) {
+ callback = all;
+ all = false;
+ }
+ if (typeof all === 'string' && all === 'true') {
+ all = true;
+ }
+ if (typeof all !== 'boolean' && all !== undefined) {
+ all = false;
+ }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers");
+ all = all || false;
+ let result = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
+ const workload = [];
-/***/ }),
+ _docker_socket.listImages(all, data => {
+ let dockerImages = {};
+ try {
+ dockerImages = data;
+ if (dockerImages && Object.prototype.toString.call(dockerImages) === '[object Array]' && dockerImages.length > 0) {
-/***/ 64756:
-/***/ ((module) => {
+ dockerImages.forEach(function (element) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls");
+ if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) {
+ element.Name = element.Names[0].replace(/^\/|\/$/g, '');
+ }
+ workload.push(dockerImagesInspect(element.Id.trim(), element));
+ });
+ if (workload.length) {
+ Promise.all(
+ workload
+ ).then((data) => {
+ if (callback) { callback(data); }
+ resolve(data);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } catch (err) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+ });
+}
-/***/ }),
+// --------------------------
+// container inspect (for one container)
-/***/ 52018:
-/***/ ((module) => {
+function dockerImagesInspect(imageID, payload) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ imageID = imageID || '';
+ if (typeof imageID !== 'string') {
+ return resolve();
+ }
+ const imageIDSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(imageID, true)).trim();
+ if (imageIDSanitized) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tty");
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
-/***/ }),
+ _docker_socket.inspectImage(imageIDSanitized.trim(), data => {
+ try {
+ resolve({
+ id: payload.Id,
+ container: data.Container,
+ comment: data.Comment,
+ os: data.Os,
+ architecture: data.Architecture,
+ parent: data.Parent,
+ dockerVersion: data.DockerVersion,
+ size: data.Size,
+ sharedSize: payload.SharedSize,
+ virtualSize: data.VirtualSize,
+ author: data.Author,
+ created: data.Created ? Math.round(new Date(data.Created).getTime() / 1000) : 0,
+ containerConfig: data.ContainerConfig ? data.ContainerConfig : {},
+ graphDriver: data.GraphDriver ? data.GraphDriver : {},
+ repoDigests: data.RepoDigests ? data.RepoDigests : {},
+ repoTags: data.RepoTags ? data.RepoTags : {},
+ config: data.Config ? data.Config : {},
+ rootFS: data.RootFS ? data.RootFS : {},
+ });
+ } catch (err) {
+ resolve();
+ }
+ });
+ } else {
+ resolve();
+ }
+ });
+ });
+}
-/***/ 87016:
-/***/ ((module) => {
+exports.dockerImages = dockerImages;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url");
+function dockerContainers(all, callback) {
-/***/ }),
+ function inContainers(containers, id) {
+ let filtered = containers.filter(obj => {
+ /**
+ * @namespace
+ * @property {string} Id
+ */
+ return (obj.Id && (obj.Id === id));
+ });
+ return (filtered.length > 0);
+ }
-/***/ 39023:
-/***/ ((module) => {
+ // fallback - if only callback is given
+ if (util.isFunction(all) && !callback) {
+ callback = all;
+ all = false;
+ }
+ if (typeof all === 'string' && all === 'true') {
+ all = true;
+ }
+ if (typeof all !== 'boolean' && all !== undefined) {
+ all = false;
+ }
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util");
+ all = all || false;
+ let result = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
+ const workload = [];
-/***/ }),
+ _docker_socket.listContainers(all, data => {
+ let docker_containers = {};
+ try {
+ docker_containers = data;
+ if (docker_containers && Object.prototype.toString.call(docker_containers) === '[object Array]' && docker_containers.length > 0) {
+ // GC in _docker_container_stats
+ for (let key in _docker_container_stats) {
+ if ({}.hasOwnProperty.call(_docker_container_stats, key)) {
+ if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; }
+ }
+ }
-/***/ 98253:
-/***/ ((module) => {
+ docker_containers.forEach(function (element) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types");
+ if (element.Names && Object.prototype.toString.call(element.Names) === '[object Array]' && element.Names.length > 0) {
+ element.Name = element.Names[0].replace(/^\/|\/$/g, '');
+ }
+ workload.push(dockerContainerInspect(element.Id.trim(), element));
+ });
+ if (workload.length) {
+ Promise.all(
+ workload
+ ).then((data) => {
+ if (callback) { callback(data); }
+ resolve(data);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } catch (err) {
+ // GC in _docker_container_stats
+ for (let key in _docker_container_stats) {
+ if ({}.hasOwnProperty.call(_docker_container_stats, key)) {
+ if (!inContainers(docker_containers, key)) { delete _docker_container_stats[key]; }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+ });
+}
-/***/ }),
+// --------------------------
+// container inspect (for one container)
-/***/ 28167:
-/***/ ((module) => {
+function dockerContainerInspect(containerID, payload) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ containerID = containerID || '';
+ if (typeof containerID !== 'string') {
+ return resolve();
+ }
+ const containerIdSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerID, true)).trim();
+ if (containerIdSanitized) {
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads");
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
-/***/ }),
+ _docker_socket.getInspect(containerIdSanitized.trim(), data => {
+ try {
+ resolve({
+ id: payload.Id,
+ name: payload.Name,
+ image: payload.Image,
+ imageID: payload.ImageID,
+ command: payload.Command,
+ created: payload.Created,
+ started: data.State && data.State.StartedAt ? Math.round(new Date(data.State.StartedAt).getTime() / 1000) : 0,
+ finished: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? Math.round(new Date(data.State.FinishedAt).getTime() / 1000) : 0,
+ createdAt: data.Created ? data.Created : '',
+ startedAt: data.State && data.State.StartedAt ? data.State.StartedAt : '',
+ finishedAt: data.State && data.State.FinishedAt && !data.State.FinishedAt.startsWith('0001-01-01') ? data.State.FinishedAt : '',
+ state: payload.State,
+ restartCount: data.RestartCount || 0,
+ platform: data.Platform || '',
+ driver: data.Driver || '',
+ ports: payload.Ports,
+ mounts: payload.Mounts,
+ // hostconfig: payload.HostConfig,
+ // network: payload.NetworkSettings
+ });
+ } catch (err) {
+ resolve();
+ }
+ });
+ } else {
+ resolve();
+ }
+ });
+ });
+}
-/***/ 43106:
-/***/ ((module) => {
+exports.dockerContainers = dockerContainers;
-module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib");
+// --------------------------
+// helper functions for calculation of docker stats
-/***/ }),
+function docker_calcCPUPercent(cpu_stats, precpu_stats) {
+ /**
+ * @namespace
+ * @property {object} cpu_usage
+ * @property {number} cpu_usage.total_usage
+ * @property {number} system_cpu_usage
+ * @property {object} cpu_usage
+ * @property {Array} cpu_usage.percpu_usage
+ */
-/***/ 85276:
-/***/ ((__unused_webpack_module, exports) => {
+ if (!_windows) {
+ let cpuPercent = 0.0;
+ // calculate the change for the cpu usage of the container in between readings
+ let cpuDelta = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
+ // calculate the change for the entire system between readings
+ let systemDelta = cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage;
+ if (systemDelta > 0.0 && cpuDelta > 0.0) {
+ // calculate the change for the cpu usage of the container in between readings
+ if (precpu_stats.online_cpus) {
+ cpuPercent = (cpuDelta / systemDelta) * precpu_stats.online_cpus * 100.0;
+ }
+ else {
+ cpuPercent = (cpuDelta / systemDelta) * cpu_stats.cpu_usage.percpu_usage.length * 100.0;
+ }
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AbortError = void 0;
-/**
- * This error is thrown when an asynchronous operation has been aborted.
- * Check for this error by testing the `name` that the name property of the
- * error matches `"AbortError"`.
- *
- * @example
- * ```ts
- * const controller = new AbortController();
- * controller.abort();
- * try {
- * doAsyncWork(controller.signal)
- * } catch (e) {
- * if (e.name === 'AbortError') {
- * // handle abort error here.
- * }
- * }
- * ```
- */
-class AbortError extends Error {
- constructor(message) {
- super(message);
- this.name = "AbortError";
+ return cpuPercent;
+ } else {
+ let nanoSecNow = util.nanoSeconds();
+ let cpuPercent = 0.0;
+ if (_docker_last_read > 0) {
+ let possIntervals = (nanoSecNow - _docker_last_read); // / 100 * os.cpus().length;
+ let intervalsUsed = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage;
+ if (possIntervals > 0) {
+ cpuPercent = 100.0 * intervalsUsed / possIntervals;
+ }
}
+ _docker_last_read = nanoSecNow;
+ return cpuPercent;
+ }
}
-exports.AbortError = AbortError;
-//# sourceMappingURL=AbortError.js.map
-/***/ }),
+function docker_calcNetworkIO(networks) {
+ let rx;
+ let wx;
+ for (let key in networks) {
+ // skip loop if the property is from prototype
+ if (!{}.hasOwnProperty.call(networks, key)) { continue; }
-/***/ 92242:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ /**
+ * @namespace
+ * @property {number} rx_bytes
+ * @property {number} tx_bytes
+ */
+ let obj = networks[key];
+ rx = +obj.rx_bytes;
+ wx = +obj.tx_bytes;
+ }
+ return {
+ rx,
+ wx
+ };
+}
+function docker_calcBlockIO(blkio_stats) {
+ let result = {
+ r: 0,
+ w: 0
+ };
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AbortError = void 0;
-var AbortError_js_1 = __nccwpck_require__(85276);
-Object.defineProperty(exports, "AbortError", ({ enumerable: true, get: function () { return AbortError_js_1.AbortError; } }));
-//# sourceMappingURL=index.js.map
+ /**
+ * @namespace
+ * @property {Array} io_service_bytes_recursive
+ */
+ if (blkio_stats && blkio_stats.io_service_bytes_recursive && Object.prototype.toString.call(blkio_stats.io_service_bytes_recursive) === '[object Array]' && blkio_stats.io_service_bytes_recursive.length > 0) {
+ blkio_stats.io_service_bytes_recursive.forEach(function (element) {
+ /**
+ * @namespace
+ * @property {string} op
+ * @property {number} value
+ */
-/***/ }),
+ if (element.op && element.op.toLowerCase() === 'read' && element.value) {
+ result.r += element.value;
+ }
+ if (element.op && element.op.toLowerCase() === 'write' && element.value) {
+ result.w += element.value;
+ }
+ });
+ }
+ return result;
+}
-/***/ 21746:
-/***/ ((__unused_webpack_module, exports) => {
+function dockerContainerStats(containerIDs, callback) {
+ let containerArray = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureKeyCredential = void 0;
-/**
- * A static-key-based credential that supports updating
- * the underlying key value.
- */
-class AzureKeyCredential {
- /**
- * The value of the key to be used in authentication
- */
- get key() {
- return this._key;
- }
- /**
- * Create an instance of an AzureKeyCredential for use
- * with a service client.
- *
- * @param key - The initial value of the key to use in authentication
- */
- constructor(key) {
- if (!key) {
- throw new Error("key must be a non-empty string");
+ // fallback - if only callback is given
+ if (util.isFunction(containerIDs) && !callback) {
+ callback = containerIDs;
+ containerArray = ['*'];
+ } else {
+ containerIDs = containerIDs || '*';
+ if (typeof containerIDs !== 'string') {
+ if (callback) { callback([]); }
+ return resolve([]);
+ }
+ let containerIDsSanitized = '';
+ try {
+ containerIDsSanitized.__proto__.toLowerCase = util.stringToLower;
+ containerIDsSanitized.__proto__.replace = util.stringReplace;
+ containerIDsSanitized.__proto__.toString = util.stringToString;
+ containerIDsSanitized.__proto__.substr = util.stringSubstr;
+ containerIDsSanitized.__proto__.substring = util.stringSubstring;
+ containerIDsSanitized.__proto__.trim = util.stringTrim;
+ containerIDsSanitized.__proto__.startsWith = util.stringStartWith;
+ } catch (e) {
+ Object.setPrototypeOf(containerIDsSanitized, util.stringObj);
}
- this._key = key;
- }
- /**
- * Change the value of the key.
- *
- * Updates will take effect upon the next request after
- * updating the key value.
- *
- * @param newKey - The new key value to be used
- */
- update(newKey) {
- this._key = newKey;
- }
-}
-exports.AzureKeyCredential = AzureKeyCredential;
-//# sourceMappingURL=azureKeyCredential.js.map
-/***/ }),
+ containerIDsSanitized = containerIDs;
+ containerIDsSanitized = containerIDsSanitized.trim();
+ if (containerIDsSanitized !== '*') {
+ containerIDsSanitized = '';
+ const s = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerIDs, true)).trim();
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ s[i].__proto__.toLowerCase = util.stringToLower;
+ const sl = s[i].toLowerCase();
+ if (sl && sl[0] && !sl[1]) {
+ containerIDsSanitized = containerIDsSanitized + sl[0];
+ }
+ }
+ }
+ }
-/***/ 37859:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ containerIDsSanitized = containerIDsSanitized.trim().toLowerCase().replace(/,+/g, '|');
+ containerArray = containerIDsSanitized.split('|');
+ }
+ const result = [];
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureNamedKeyCredential = void 0;
-exports.isNamedKeyCredential = isNamedKeyCredential;
-const core_util_1 = __nccwpck_require__(30991);
-/**
- * A static name/key-based credential that supports updating
- * the underlying name and key values.
- */
-class AzureNamedKeyCredential {
- /**
- * The value of the key to be used in authentication.
- */
- get key() {
- return this._key;
- }
- /**
- * The value of the name to be used in authentication.
- */
- get name() {
- return this._name;
- }
- /**
- * Create an instance of an AzureNamedKeyCredential for use
- * with a service client.
- *
- * @param name - The initial value of the name to use in authentication.
- * @param key - The initial value of the key to use in authentication.
- */
- constructor(name, key) {
- if (!name || !key) {
- throw new TypeError("name and key must be non-empty strings");
+ const workload = [];
+ if (containerArray.length && containerArray[0].trim() === '*') {
+ containerArray = [];
+ dockerContainers().then(allContainers => {
+ for (let container of allContainers) {
+ containerArray.push(container.id.substring(0, 12));
+ }
+ if (containerArray.length) {
+ dockerContainerStats(containerArray.join(',')).then(result => {
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ } else {
+ for (let containerID of containerArray) {
+ workload.push(dockerContainerStatsSingle(containerID.trim()));
}
- this._name = name;
- this._key = key;
- }
- /**
- * Change the value of the key.
- *
- * Updates will take effect upon the next request after
- * updating the key value.
- *
- * @param newName - The new name value to be used.
- * @param newKey - The new key value to be used.
- */
- update(newName, newKey) {
- if (!newName || !newKey) {
- throw new TypeError("newName and newKey must be non-empty strings");
+ if (workload.length) {
+ Promise.all(
+ workload
+ ).then((data) => {
+ if (callback) { callback(data); }
+ resolve(data);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
}
- this._name = newName;
- this._key = newKey;
- }
+ }
+ });
+ });
}
-exports.AzureNamedKeyCredential = AzureNamedKeyCredential;
-/**
- * Tests an object to determine whether it implements NamedKeyCredential.
- *
- * @param credential - The assumed NamedKeyCredential to be tested.
- */
-function isNamedKeyCredential(credential) {
- return ((0, core_util_1.isObjectWithProperties)(credential, ["name", "key"]) &&
- typeof credential.key === "string" &&
- typeof credential.name === "string");
+
+// --------------------------
+// container stats (for one container)
+
+function dockerContainerStatsSingle(containerID) {
+ containerID = containerID || '';
+ let result = {
+ id: containerID,
+ memUsage: 0,
+ memLimit: 0,
+ memPercent: 0,
+ cpuPercent: 0,
+ pids: 0,
+ netIO: {
+ rx: 0,
+ wx: 0
+ },
+ blockIO: {
+ r: 0,
+ w: 0
+ },
+ restartCount: 0,
+ cpuStats: {},
+ precpuStats: {},
+ memoryStats: {},
+ networks: {},
+ };
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (containerID) {
+
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
+
+ _docker_socket.getInspect(containerID, dataInspect => {
+ try {
+ _docker_socket.getStats(containerID, data => {
+ try {
+ let stats = data;
+ if (!stats.message) {
+ if (data.id) { result.id = data.id; }
+ result.memUsage = (stats.memory_stats && stats.memory_stats.usage ? stats.memory_stats.usage : 0);
+ result.memLimit = (stats.memory_stats && stats.memory_stats.limit ? stats.memory_stats.limit : 0);
+ result.memPercent = (stats.memory_stats && stats.memory_stats.usage && stats.memory_stats.limit ? stats.memory_stats.usage / stats.memory_stats.limit * 100.0 : 0);
+ result.cpuPercent = (stats.cpu_stats && stats.precpu_stats ? docker_calcCPUPercent(stats.cpu_stats, stats.precpu_stats) : 0);
+ result.pids = (stats.pids_stats && stats.pids_stats.current ? stats.pids_stats.current : 0);
+ result.restartCount = (dataInspect.RestartCount ? dataInspect.RestartCount : 0);
+ if (stats.networks) { result.netIO = docker_calcNetworkIO(stats.networks); }
+ if (stats.blkio_stats) { result.blockIO = docker_calcBlockIO(stats.blkio_stats); }
+ result.cpuStats = (stats.cpu_stats ? stats.cpu_stats : {});
+ result.precpuStats = (stats.precpu_stats ? stats.precpu_stats : {});
+ result.memoryStats = (stats.memory_stats ? stats.memory_stats : {});
+ result.networks = (stats.networks ? stats.networks : {});
+ }
+ } catch (err) {
+ util.noop();
+ }
+ // }
+ resolve(result);
+ });
+ } catch (err) {
+ util.noop();
+ }
+ });
+ } else {
+ resolve(result);
+ }
+ });
+ });
}
-//# sourceMappingURL=azureNamedKeyCredential.js.map
-/***/ }),
+exports.dockerContainerStats = dockerContainerStats;
-/***/ 52372:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// container processes (for one container)
+function dockerContainerProcesses(containerID, callback) {
+ let result = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ containerID = containerID || '';
+ if (typeof containerID !== 'string') {
+ return resolve(result);
+ }
+ const containerIdSanitized = (util.isPrototypePolluted() ? '' : util.sanitizeShellString(containerID, true)).trim();
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.AzureSASCredential = void 0;
-exports.isSASCredential = isSASCredential;
-const core_util_1 = __nccwpck_require__(30991);
-/**
- * A static-signature-based credential that supports updating
- * the underlying signature value.
- */
-class AzureSASCredential {
- /**
- * The value of the shared access signature to be used in authentication
- */
- get signature() {
- return this._signature;
- }
- /**
- * Create an instance of an AzureSASCredential for use
- * with a service client.
- *
- * @param signature - The initial value of the shared access signature to use in authentication
- */
- constructor(signature) {
- if (!signature) {
- throw new Error("shared access signature must be a non-empty string");
- }
- this._signature = signature;
- }
- /**
- * Change the value of the signature.
- *
- * Updates will take effect upon the next request after
- * updating the signature value.
- *
- * @param newSignature - The new shared access signature value to be used
- */
- update(newSignature) {
- if (!newSignature) {
- throw new Error("shared access signature must be a non-empty string");
- }
- this._signature = newSignature;
- }
-}
-exports.AzureSASCredential = AzureSASCredential;
-/**
- * Tests an object to determine whether it implements SASCredential.
- *
- * @param credential - The assumed SASCredential to be tested.
- */
-function isSASCredential(credential) {
- return ((0, core_util_1.isObjectWithProperties)(credential, ["signature"]) && typeof credential.signature === "string");
-}
-//# sourceMappingURL=azureSASCredential.js.map
+ if (containerIdSanitized) {
-/***/ }),
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
-/***/ 15269:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ _docker_socket.getProcesses(containerIdSanitized, data => {
+ /**
+ * @namespace
+ * @property {Array} Titles
+ * @property {Array} Processes
+ **/
+ try {
+ if (data && data.Titles && data.Processes) {
+ let titles = data.Titles.map(function (value) {
+ return value.toUpperCase();
+ });
+ let pos_pid = titles.indexOf('PID');
+ let pos_ppid = titles.indexOf('PPID');
+ let pos_pgid = titles.indexOf('PGID');
+ let pos_vsz = titles.indexOf('VSZ');
+ let pos_time = titles.indexOf('TIME');
+ let pos_elapsed = titles.indexOf('ELAPSED');
+ let pos_ni = titles.indexOf('NI');
+ let pos_ruser = titles.indexOf('RUSER');
+ let pos_user = titles.indexOf('USER');
+ let pos_rgroup = titles.indexOf('RGROUP');
+ let pos_group = titles.indexOf('GROUP');
+ let pos_stat = titles.indexOf('STAT');
+ let pos_rss = titles.indexOf('RSS');
+ let pos_command = titles.indexOf('COMMAND');
+ data.Processes.forEach(process => {
+ result.push({
+ pidHost: (pos_pid >= 0 ? process[pos_pid] : ''),
+ ppid: (pos_ppid >= 0 ? process[pos_ppid] : ''),
+ pgid: (pos_pgid >= 0 ? process[pos_pgid] : ''),
+ user: (pos_user >= 0 ? process[pos_user] : ''),
+ ruser: (pos_ruser >= 0 ? process[pos_ruser] : ''),
+ group: (pos_group >= 0 ? process[pos_group] : ''),
+ rgroup: (pos_rgroup >= 0 ? process[pos_rgroup] : ''),
+ stat: (pos_stat >= 0 ? process[pos_stat] : ''),
+ time: (pos_time >= 0 ? process[pos_time] : ''),
+ elapsed: (pos_elapsed >= 0 ? process[pos_elapsed] : ''),
+ nice: (pos_ni >= 0 ? process[pos_ni] : ''),
+ rss: (pos_rss >= 0 ? process[pos_rss] : ''),
+ vsz: (pos_vsz >= 0 ? process[pos_vsz] : ''),
+ command: (pos_command >= 0 ? process[pos_command] : '')
+ });
+ });
+ }
+ } catch (err) {
+ util.noop();
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+}
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isTokenCredential = exports.isSASCredential = exports.AzureSASCredential = exports.isNamedKeyCredential = exports.AzureNamedKeyCredential = exports.isKeyCredential = exports.AzureKeyCredential = void 0;
-var azureKeyCredential_js_1 = __nccwpck_require__(21746);
-Object.defineProperty(exports, "AzureKeyCredential", ({ enumerable: true, get: function () { return azureKeyCredential_js_1.AzureKeyCredential; } }));
-var keyCredential_js_1 = __nccwpck_require__(67415);
-Object.defineProperty(exports, "isKeyCredential", ({ enumerable: true, get: function () { return keyCredential_js_1.isKeyCredential; } }));
-var azureNamedKeyCredential_js_1 = __nccwpck_require__(37859);
-Object.defineProperty(exports, "AzureNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.AzureNamedKeyCredential; } }));
-Object.defineProperty(exports, "isNamedKeyCredential", ({ enumerable: true, get: function () { return azureNamedKeyCredential_js_1.isNamedKeyCredential; } }));
-var azureSASCredential_js_1 = __nccwpck_require__(52372);
-Object.defineProperty(exports, "AzureSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.AzureSASCredential; } }));
-Object.defineProperty(exports, "isSASCredential", ({ enumerable: true, get: function () { return azureSASCredential_js_1.isSASCredential; } }));
-var tokenCredential_js_1 = __nccwpck_require__(64381);
-Object.defineProperty(exports, "isTokenCredential", ({ enumerable: true, get: function () { return tokenCredential_js_1.isTokenCredential; } }));
-//# sourceMappingURL=index.js.map
+exports.dockerContainerProcesses = dockerContainerProcesses;
-/***/ }),
+function dockerVolumes(callback) {
-/***/ 67415:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ let result = [];
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (!_docker_socket) {
+ _docker_socket = new DockerSocket();
+ }
+ _docker_socket.listVolumes((data) => {
+ let dockerVolumes = {};
+ try {
+ dockerVolumes = data;
+ if (dockerVolumes && dockerVolumes.Volumes && Object.prototype.toString.call(dockerVolumes.Volumes) === '[object Array]' && dockerVolumes.Volumes.length > 0) {
+ dockerVolumes.Volumes.forEach(function (element) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isKeyCredential = isKeyCredential;
-const core_util_1 = __nccwpck_require__(30991);
-/**
- * Tests an object to determine whether it implements KeyCredential.
- *
- * @param credential - The assumed KeyCredential to be tested.
- */
-function isKeyCredential(credential) {
- return (0, core_util_1.isObjectWithProperties)(credential, ["key"]) && typeof credential.key === "string";
+ result.push({
+ name: element.Name,
+ driver: element.Driver,
+ labels: element.Labels,
+ mountpoint: element.Mountpoint,
+ options: element.Options,
+ scope: element.Scope,
+ created: element.CreatedAt ? Math.round(new Date(element.CreatedAt).getTime() / 1000) : 0,
+ });
+ });
+ if (callback) { callback(result); }
+ resolve(result);
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ } catch (err) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+ });
}
-//# sourceMappingURL=keyCredential.js.map
-/***/ }),
+exports.dockerVolumes = dockerVolumes;
-/***/ 64381:
-/***/ ((__unused_webpack_module, exports) => {
+function dockerAll(callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ dockerContainers(true).then(result => {
+ if (result && Object.prototype.toString.call(result) === '[object Array]' && result.length > 0) {
+ let l = result.length;
+ result.forEach(function (element) {
+ dockerContainerStats(element.id).then((res) => {
+ // include stats in array
+ element.memUsage = res[0].memUsage;
+ element.memLimit = res[0].memLimit;
+ element.memPercent = res[0].memPercent;
+ element.cpuPercent = res[0].cpuPercent;
+ element.pids = res[0].pids;
+ element.netIO = res[0].netIO;
+ element.blockIO = res[0].blockIO;
+ element.cpuStats = res[0].cpuStats;
+ element.precpuStats = res[0].precpuStats;
+ element.memoryStats = res[0].memoryStats;
+ element.networks = res[0].networks;
+ dockerContainerProcesses(element.id).then(processes => {
+ element.processes = processes;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT License.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.isBearerToken = isBearerToken;
-exports.isPopToken = isPopToken;
-exports.isTokenCredential = isTokenCredential;
-/**
- * @internal
- * @param accessToken - Access token
- * @returns Whether a token is bearer type or not
- */
-function isBearerToken(accessToken) {
- return !accessToken.tokenType || accessToken.tokenType === "Bearer";
-}
-/**
- * @internal
- * @param accessToken - Access token
- * @returns Whether a token is Pop token or not
- */
-function isPopToken(accessToken) {
- return accessToken.tokenType === "pop";
-}
-/**
- * Tests an object to determine whether it implements TokenCredential.
- *
- * @param credential - The assumed TokenCredential to be tested.
- */
-function isTokenCredential(credential) {
- // Check for an object with a 'getToken' function and possibly with
- // a 'signRequest' function. We do this check to make sure that
- // a ServiceClientCredentials implementor (like TokenClientCredentials
- // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
- // it doesn't actually implement TokenCredential also.
- const castCredential = credential;
- return (castCredential &&
- typeof castCredential.getToken === "function" &&
- (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
+ l -= 1;
+ if (l === 0) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ // all done??
+ });
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ });
+ });
+ });
}
-//# sourceMappingURL=tokenCredential.js.map
+
+exports.dockerAll = dockerAll;
+
/***/ }),
-/***/ 85110:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+/***/ 23945:
+/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.authorizeRequestOnClaimChallenge = exports.parseCAEChallenge = void 0;
-const log_js_1 = __nccwpck_require__(75630);
-const base64_js_1 = __nccwpck_require__(59793);
-/**
- * Converts: `Bearer a="b", c="d", Bearer d="e", f="g"`.
- * Into: `[ { a: 'b', c: 'd' }, { d: 'e', f: 'g' } ]`.
- *
- * @internal
- */
-function parseCAEChallenge(challenges) {
- const bearerChallenges = `, ${challenges.trim()}`.split(", Bearer ").filter((x) => x);
- return bearerChallenges.map((challenge) => {
- const challengeParts = `${challenge.trim()}, `.split('", ').filter((x) => x);
- const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split('="')));
- // Key-value pairs to plain object:
- return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
- });
-}
-exports.parseCAEChallenge = parseCAEChallenge;
-/**
- * This function can be used as a callback for the `bearerTokenAuthenticationPolicy` of `@azure/core-rest-pipeline`, to support CAE challenges:
- * [Continuous Access Evaluation](https://docs.microsoft.com/azure/active-directory/conditional-access/concept-continuous-access-evaluation).
- *
- * Call the `bearerTokenAuthenticationPolicy` with the following options:
- *
- * ```ts
- * import { bearerTokenAuthenticationPolicy } from "@azure/core-rest-pipeline";
- * import { authorizeRequestOnClaimChallenge } from "@azure/core-client";
- *
- * const bearerTokenAuthenticationPolicy = bearerTokenAuthenticationPolicy({
- * authorizeRequestOnChallenge: authorizeRequestOnClaimChallenge
- * });
- * ```
- *
- * Once provided, the `bearerTokenAuthenticationPolicy` policy will internally handle Continuous Access Evaluation (CAE) challenges.
- * When it can't complete a challenge it will return the 401 (unauthorized) response from ARM.
- *
- * Example challenge with claims:
- *
- * ```
- * Bearer authorization_uri="https://login.windows-ppe.net/", error="invalid_token",
- * error_description="User session has been revoked",
- * claims="eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwgInZhbHVlIjoiMTYwMzc0MjgwMCJ9fX0="
- * ```
- */
-async function authorizeRequestOnClaimChallenge(onChallengeOptions) {
- const { scopes, response } = onChallengeOptions;
- const logger = onChallengeOptions.logger || log_js_1.logger;
- const challenge = response.headers.get("WWW-Authenticate");
- if (!challenge) {
- logger.info(`The WWW-Authenticate header was missing. Failed to perform the Continuous Access Evaluation authentication flow.`);
- return false;
- }
- const challenges = parseCAEChallenge(challenge) || [];
- const parsedChallenge = challenges.find((x) => x.claims);
- if (!parsedChallenge) {
- logger.info(`The WWW-Authenticate header was missing the necessary "claims" to perform the Continuous Access Evaluation authentication flow.`);
- return false;
- }
- const accessToken = await onChallengeOptions.getAccessToken(parsedChallenge.scope ? [parsedChallenge.scope] : scopes, {
- claims: (0, base64_js_1.decodeStringToString)(parsedChallenge.claims),
- });
- if (!accessToken) {
- return false;
- }
- onChallengeOptions.request.headers.set("Authorization", `Bearer ${accessToken.token}`);
- return true;
-}
-exports.authorizeRequestOnClaimChallenge = authorizeRequestOnClaimChallenge;
-//# sourceMappingURL=authorizeRequestOnClaimChallenge.js.map
+// @ts-check
+// ==================================================================================
+// dockerSockets.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 13. DockerSockets
+// ----------------------------------------------------------------------------------
-/***/ }),
+const net = __nccwpck_require__(69278);
+const isWin = (__nccwpck_require__(70857).type)() === 'Windows_NT';
+const socketPath = isWin ? '//./pipe/docker_engine' : '/var/run/docker.sock';
-/***/ 75794:
-/***/ ((__unused_webpack_module, exports) => {
+class DockerSocket {
+ getInfo(callback) {
+ try {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.authorizeRequestOnTenantChallenge = void 0;
-/**
- * A set of constants used internally when processing requests.
- */
-const Constants = {
- DefaultScope: "/.default",
- /**
- * Defines constants for use with HTTP headers.
- */
- HeaderConstants: {
- /**
- * The Authorization header.
- */
- AUTHORIZATION: "authorization",
- },
-};
-function isUuid(text) {
- return /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/.test(text);
-}
-/**
- * Defines a callback to handle auth challenge for Storage APIs.
- * This implements the bearer challenge process described here: https://docs.microsoft.com/rest/api/storageservices/authorize-with-azure-active-directory#bearer-challenge
- * Handling has specific features for storage that departs to the general AAD challenge docs.
- **/
-const authorizeRequestOnTenantChallenge = async (challengeOptions) => {
- const requestOptions = requestToOptions(challengeOptions.request);
- const challenge = getChallenge(challengeOptions.response);
- if (challenge) {
- const challengeInfo = parseChallenge(challenge);
- const challengeScopes = buildScopes(challengeOptions, challengeInfo);
- const tenantId = extractTenantId(challengeInfo);
- if (!tenantId) {
- return false;
- }
- const accessToken = await challengeOptions.getAccessToken(challengeScopes, Object.assign(Object.assign({}, requestOptions), { tenantId }));
- if (!accessToken) {
- return false;
- }
- challengeOptions.request.headers.set(Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}`);
- return true;
- }
- return false;
-};
-exports.authorizeRequestOnTenantChallenge = authorizeRequestOnTenantChallenge;
-/**
- * Extracts the tenant id from the challenge information
- * The tenant id is contained in the authorization_uri as the first
- * path part.
- */
-function extractTenantId(challengeInfo) {
- const parsedAuthUri = new URL(challengeInfo.authorization_uri);
- const pathSegments = parsedAuthUri.pathname.split("/");
- const tenantId = pathSegments[1];
- if (tenantId && isUuid(tenantId)) {
- return tenantId;
- }
- return undefined;
-}
-/**
- * Builds the authentication scopes based on the information that comes in the
- * challenge information. Scopes url is present in the resource_id, if it is empty
- * we keep using the original scopes.
- */
-function buildScopes(challengeOptions, challengeInfo) {
- if (!challengeInfo.resource_id) {
- return challengeOptions.scopes;
- }
- const challengeScopes = new URL(challengeInfo.resource_id);
- challengeScopes.pathname = Constants.DefaultScope;
- let scope = challengeScopes.toString();
- if (scope === "https://disk.azure.com/.default") {
- // the extra slash is required by the service
- scope = "https://disk.azure.com//.default";
- }
- return [scope];
-}
-/**
- * We will retrieve the challenge only if the response status code was 401,
- * and if the response contained the header "WWW-Authenticate" with a non-empty value.
- */
-function getChallenge(response) {
- const challenge = response.headers.get("WWW-Authenticate");
- if (response.status === 401 && challenge) {
- return challenge;
- }
- return;
-}
-/**
- * Converts: `Bearer a="b" c="d"`.
- * Into: `[ { a: 'b', c: 'd' }]`.
- *
- * @internal
- */
-function parseChallenge(challenge) {
- const bearerChallenge = challenge.slice("Bearer ".length);
- const challengeParts = `${bearerChallenge.trim()} `.split(" ").filter((x) => x);
- const keyValuePairs = challengeParts.map((keyValue) => (([key, value]) => ({ [key]: value }))(keyValue.trim().split("=")));
- // Key-value pairs to plain object:
- return keyValuePairs.reduce((a, b) => (Object.assign(Object.assign({}, a), b)), {});
-}
-/**
- * Extracts the options form a Pipeline Request for later re-use
- */
-function requestToOptions(request) {
- return {
- abortSignal: request.abortSignal,
- requestOptions: {
- timeout: request.timeout,
- },
- tracingOptions: request.tracingOptions,
- };
-}
-//# sourceMappingURL=authorizeRequestOnTenantChallenge.js.map
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
-/***/ }),
+ socket.on('connect', () => {
+ socket.write('GET http:/info HTTP/1.0\r\n\r\n');
+ });
-/***/ 59793:
-/***/ ((__unused_webpack_module, exports) => {
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.decodeStringToString = exports.decodeString = exports.encodeByteArray = exports.encodeString = void 0;
-/**
- * Encodes a string in base64 format.
- * @param value - the string to encode
- * @internal
- */
-function encodeString(value) {
- return Buffer.from(value).toString("base64");
-}
-exports.encodeString = encodeString;
-/**
- * Encodes a byte array in base64 format.
- * @param value - the Uint8Aray to encode
- * @internal
- */
-function encodeByteArray(value) {
- const bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer);
- return bufferValue.toString("base64");
-}
-exports.encodeByteArray = encodeByteArray;
-/**
- * Decodes a base64 string into a byte array.
- * @param value - the base64 string to decode
- * @internal
- */
-function decodeString(value) {
- return Buffer.from(value, "base64");
-}
-exports.decodeString = decodeString;
-/**
- * Decodes a base64 string into a string.
- * @param value - the base64 string to decode
- * @internal
- */
-function decodeStringToString(value) {
- return Buffer.from(value, "base64").toString();
-}
-exports.decodeStringToString = decodeStringToString;
-//# sourceMappingURL=base64.js.map
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
+ }
+ });
+ } catch (err) {
+ callback({});
+ }
+ }
-/***/ }),
+ listImages(all, callback) {
+ try {
-/***/ 21795:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+ socket.on('connect', () => {
+ socket.write('GET http:/images/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n');
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.deserializationPolicy = exports.deserializationPolicyName = void 0;
-const interfaces_js_1 = __nccwpck_require__(35590);
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-const serializer_js_1 = __nccwpck_require__(66774);
-const operationHelpers_js_1 = __nccwpck_require__(17036);
-const defaultJsonContentTypes = ["application/json", "text/json"];
-const defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
-/**
- * The programmatic identifier of the deserializationPolicy.
- */
-exports.deserializationPolicyName = "deserializationPolicy";
-/**
- * This policy handles parsing out responses according to OperationSpecs on the request.
- */
-function deserializationPolicy(options = {}) {
- var _a, _b, _c, _d, _e, _f, _g;
- const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes;
- const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes;
- const parseXML = options.parseXML;
- const serializerOptions = options.serializerOptions;
- const updatedOptions = {
- xml: {
- rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "",
- includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false,
- xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : interfaces_js_1.XML_CHARKEY,
- },
- };
- return {
- name: exports.deserializationPolicyName,
- async sendRequest(request, next) {
- const response = await next(request);
- return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML);
- },
- };
-}
-exports.deserializationPolicy = deserializationPolicy;
-function getOperationResponseMap(parsedResponse) {
- let result;
- const request = parsedResponse.request;
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
- if (operationSpec) {
- if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) {
- result = operationSpec.responses[parsedResponse.status];
- }
- else {
- result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse);
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
}
+ });
+ } catch (err) {
+ callback({});
}
- return result;
-}
-function shouldDeserializeResponse(parsedResponse) {
- const request = parsedResponse.request;
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize;
- let result;
- if (shouldDeserialize === undefined) {
- result = true;
- }
- else if (typeof shouldDeserialize === "boolean") {
- result = shouldDeserialize;
- }
- else {
- result = shouldDeserialize(parsedResponse);
- }
- return result;
-}
-async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) {
- const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML);
- if (!shouldDeserializeResponse(parsedResponse)) {
- return parsedResponse;
- }
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(parsedResponse.request);
- const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
- if (!operationSpec || !operationSpec.responses) {
- return parsedResponse;
- }
- const responseSpec = getOperationResponseMap(parsedResponse);
- const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options);
- if (error) {
- throw error;
- }
- else if (shouldReturnResponse) {
- return parsedResponse;
- }
- // An operation response spec does exist for current status code, so
- // use it to deserialize the response.
- if (responseSpec) {
- if (responseSpec.bodyMapper) {
- let valueToDeserialize = parsedResponse.parsedBody;
- if (operationSpec.isXML && responseSpec.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
- valueToDeserialize =
- typeof valueToDeserialize === "object"
- ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
- : [];
- }
- try {
- parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options);
- }
- catch (deserializeError) {
- const restError = new core_rest_pipeline_1.RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, {
- statusCode: parsedResponse.status,
- request: parsedResponse.request,
- response: parsedResponse,
- });
- throw restError;
- }
- }
- else if (operationSpec.httpMethod === "HEAD") {
- // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
- parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
- }
- if (responseSpec.headersMapper) {
- parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true });
- }
+ }
+
+ inspectImage(id, callback) {
+ id = id || '';
+ if (id) {
+ try {
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/images/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
+ }
+ });
+ } catch (err) {
+ callback({});
+ }
+ } else {
+ callback({});
}
- return parsedResponse;
-}
-function isOperationSpecEmpty(operationSpec) {
- const expectedStatusCodes = Object.keys(operationSpec.responses);
- return (expectedStatusCodes.length === 0 ||
- (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
-}
-function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) {
- var _a;
- const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300;
- const isExpectedStatusCode = isOperationSpecEmpty(operationSpec)
- ? isSuccessByStatus
- : !!responseSpec;
- if (isExpectedStatusCode) {
- if (responseSpec) {
- if (!responseSpec.isError) {
- return { error: null, shouldReturnResponse: false };
- }
- }
- else {
- return { error: null, shouldReturnResponse: false };
+ }
+
+ listContainers(all, callback) {
+ try {
+
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/containers/json' + (all ? '?all=1' : '') + ' HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
}
+ });
+ } catch (err) {
+ callback({});
}
- const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default;
- const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status))
- ? `Unexpected status code: ${parsedResponse.status}`
- : parsedResponse.bodyAsText;
- const error = new core_rest_pipeline_1.RestError(initialErrorMessage, {
- statusCode: parsedResponse.status,
- request: parsedResponse.request,
- response: parsedResponse,
- });
- // If the item failed but there's no error spec or default spec to deserialize the error,
- // we should fail so we just throw the parsed response
- if (!errorResponseSpec) {
- throw error;
+ }
+
+ getStats(id, callback) {
+ id = id || '';
+ if (id) {
+ try {
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/containers/' + id + '/stats?stream=0 HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
+ }
+ });
+ } catch (err) {
+ callback({});
+ }
+ } else {
+ callback({});
}
- const defaultBodyMapper = errorResponseSpec.bodyMapper;
- const defaultHeadersMapper = errorResponseSpec.headersMapper;
- try {
- // If error response has a body, try to deserialize it using default body mapper.
- // Then try to extract error code & message from it
- if (parsedResponse.parsedBody) {
- const parsedBody = parsedResponse.parsedBody;
- let deserializedError;
- if (defaultBodyMapper) {
- let valueToDeserialize = parsedBody;
- if (operationSpec.isXML && defaultBodyMapper.type.name === serializer_js_1.MapperTypeNames.Sequence) {
- valueToDeserialize = [];
- const elementName = defaultBodyMapper.xmlElementName;
- if (typeof parsedBody === "object" && elementName) {
- valueToDeserialize = parsedBody[elementName];
- }
- }
- deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options);
- }
- const internalError = parsedBody.error || deserializedError || parsedBody;
- error.code = internalError.code;
- if (internalError.message) {
- error.message = internalError.message;
- }
- if (defaultBodyMapper) {
- error.response.parsedBody = deserializedError;
- }
- }
- // If error response has headers, try to deserialize it using default header mapper
- if (parsedResponse.headers && defaultHeadersMapper) {
- error.response.parsedHeaders =
- operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders");
- }
+ }
+
+ getInspect(id, callback) {
+ id = id || '';
+ if (id) {
+ try {
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/containers/' + id + '/json?stream=0 HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
+ }
+ });
+ } catch (err) {
+ callback({});
+ }
+ } else {
+ callback({});
}
- catch (defaultError) {
- error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`;
+ }
+
+ getProcesses(id, callback) {
+ id = id || '';
+ if (id) {
+ try {
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/containers/' + id + '/top?ps_args=-opid,ppid,pgid,vsz,time,etime,nice,ruser,user,rgroup,group,stat,rss,args HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
+ try {
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
+ }
+ });
+ } catch (err) {
+ callback({});
+ }
+ } else {
+ callback({});
}
- return { error, shouldReturnResponse: false };
-}
-async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) {
- var _a;
- if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) &&
- operationResponse.bodyAsText) {
- const text = operationResponse.bodyAsText;
- const contentType = operationResponse.headers.get("Content-Type") || "";
- const contentComponents = !contentType
- ? []
- : contentType.split(";").map((component) => component.toLowerCase());
+ }
+
+ listVolumes(callback) {
+ try {
+
+ let socket = net.createConnection({ path: socketPath });
+ let alldata = '';
+ let data;
+
+ socket.on('connect', () => {
+ socket.write('GET http:/volumes HTTP/1.0\r\n\r\n');
+ });
+
+ socket.on('data', data => {
+ alldata = alldata + data.toString();
+ });
+
+ socket.on('error', () => {
+ socket = false;
+ callback({});
+ });
+
+ socket.on('end', () => {
+ let startbody = alldata.indexOf('\r\n\r\n');
+ alldata = alldata.substring(startbody + 4);
+ socket = false;
try {
- if (contentComponents.length === 0 ||
- contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) {
- operationResponse.parsedBody = JSON.parse(text);
- return operationResponse;
- }
- else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) {
- if (!parseXML) {
- throw new Error("Parsing XML not supported.");
- }
- const body = await parseXML(text, opts.xml);
- operationResponse.parsedBody = body;
- return operationResponse;
- }
- }
- catch (err) {
- const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;
- const errCode = err.code || core_rest_pipeline_1.RestError.PARSE_ERROR;
- const e = new core_rest_pipeline_1.RestError(msg, {
- code: errCode,
- statusCode: operationResponse.status,
- request: operationResponse.request,
- response: operationResponse,
- });
- throw e;
+ data = JSON.parse(alldata);
+ callback(data);
+ } catch (err) {
+ callback({});
}
+ });
+ } catch (err) {
+ callback({});
}
- return operationResponse;
+ }
}
-//# sourceMappingURL=deserializationPolicy.js.map
+
+module.exports = DockerSocket;
+
/***/ }),
-/***/ 64663:
+/***/ 50223:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getCachedDefaultHttpClient = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-let cachedHttpClient;
-function getCachedDefaultHttpClient() {
- if (!cachedHttpClient) {
- cachedHttpClient = (0, core_rest_pipeline_1.createDefaultHttpClient)();
- }
- return cachedHttpClient;
-}
-exports.getCachedDefaultHttpClient = getCachedDefaultHttpClient;
-//# sourceMappingURL=httpClientCache.js.map
+// @ts-check
+// ==================================================================================
+// filesystem.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 8. File System
+// ----------------------------------------------------------------------------------
-/***/ }),
+const util = __nccwpck_require__(77496);
+const fs = __nccwpck_require__(79896);
-/***/ 6868:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const execPromiseSave = util.promisifySave((__nccwpck_require__(35317).exec));
+let _platform = process.platform;
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.authorizeRequestOnTenantChallenge = exports.authorizeRequestOnClaimChallenge = exports.serializationPolicyName = exports.serializationPolicy = exports.deserializationPolicyName = exports.deserializationPolicy = exports.XML_CHARKEY = exports.XML_ATTRKEY = exports.createClientPipeline = exports.ServiceClient = exports.MapperTypeNames = exports.createSerializer = void 0;
-var serializer_js_1 = __nccwpck_require__(66774);
-Object.defineProperty(exports, "createSerializer", ({ enumerable: true, get: function () { return serializer_js_1.createSerializer; } }));
-Object.defineProperty(exports, "MapperTypeNames", ({ enumerable: true, get: function () { return serializer_js_1.MapperTypeNames; } }));
-var serviceClient_js_1 = __nccwpck_require__(22732);
-Object.defineProperty(exports, "ServiceClient", ({ enumerable: true, get: function () { return serviceClient_js_1.ServiceClient; } }));
-var pipeline_js_1 = __nccwpck_require__(64524);
-Object.defineProperty(exports, "createClientPipeline", ({ enumerable: true, get: function () { return pipeline_js_1.createClientPipeline; } }));
-var interfaces_js_1 = __nccwpck_require__(35590);
-Object.defineProperty(exports, "XML_ATTRKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_ATTRKEY; } }));
-Object.defineProperty(exports, "XML_CHARKEY", ({ enumerable: true, get: function () { return interfaces_js_1.XML_CHARKEY; } }));
-var deserializationPolicy_js_1 = __nccwpck_require__(21795);
-Object.defineProperty(exports, "deserializationPolicy", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicy; } }));
-Object.defineProperty(exports, "deserializationPolicyName", ({ enumerable: true, get: function () { return deserializationPolicy_js_1.deserializationPolicyName; } }));
-var serializationPolicy_js_1 = __nccwpck_require__(87054);
-Object.defineProperty(exports, "serializationPolicy", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicy; } }));
-Object.defineProperty(exports, "serializationPolicyName", ({ enumerable: true, get: function () { return serializationPolicy_js_1.serializationPolicyName; } }));
-var authorizeRequestOnClaimChallenge_js_1 = __nccwpck_require__(85110);
-Object.defineProperty(exports, "authorizeRequestOnClaimChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnClaimChallenge_js_1.authorizeRequestOnClaimChallenge; } }));
-var authorizeRequestOnTenantChallenge_js_1 = __nccwpck_require__(75794);
-Object.defineProperty(exports, "authorizeRequestOnTenantChallenge", ({ enumerable: true, get: function () { return authorizeRequestOnTenantChallenge_js_1.authorizeRequestOnTenantChallenge; } }));
-//# sourceMappingURL=index.js.map
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
-/***/ }),
+let _fs_speed = {};
+let _disk_io = {};
-/***/ 91030:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// FS - mounted file systems
+function fsSize(drive, callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getPathStringFromParameter = exports.getStreamingResponseStatusCodes = void 0;
-const serializer_js_1 = __nccwpck_require__(66774);
-/**
- * Gets the list of status codes for streaming responses.
- * @internal
- */
-function getStreamingResponseStatusCodes(operationSpec) {
- const result = new Set();
- for (const statusCode in operationSpec.responses) {
- const operationResponse = operationSpec.responses[statusCode];
- if (operationResponse.bodyMapper &&
- operationResponse.bodyMapper.type.name === serializer_js_1.MapperTypeNames.Stream) {
- result.add(Number(statusCode));
- }
- }
+ if (util.isFunction(drive)) {
+ callback = drive;
+ drive = '';
+ }
+
+ let macOsDisks = [];
+ let osMounts = [];
+
+ function getmacOsFsType(fs) {
+ if (!fs.startsWith('/')) { return 'NFS'; }
+ const parts = fs.split('/');
+ const fsShort = parts[parts.length - 1];
+ const macOsDisksSingle = macOsDisks.filter(item => item.indexOf(fsShort) >= 0);
+ if (macOsDisksSingle.length === 1 && macOsDisksSingle[0].indexOf('APFS') >= 0) { return 'APFS'; }
+ return 'HFS';
+ }
+
+ function isLinuxTmpFs(fs) {
+ const linuxTmpFileSystems = ['rootfs', 'unionfs', 'squashfs', 'cramfs', 'initrd', 'initramfs', 'devtmpfs', 'tmpfs', 'udev', 'devfs', 'specfs', 'type', 'appimaged'];
+ let result = false;
+ linuxTmpFileSystems.forEach(linuxFs => {
+ if (fs.toLowerCase().indexOf(linuxFs) >= 0) { result = true; }
+ });
return result;
-}
-exports.getStreamingResponseStatusCodes = getStreamingResponseStatusCodes;
-/**
- * Get the path to this parameter's value as a dotted string (a.b.c).
- * @param parameter - The parameter to get the path string for.
- * @returns The path to this parameter's value as a dotted string.
- * @internal
- */
-function getPathStringFromParameter(parameter) {
- const { parameterPath, mapper } = parameter;
- let result;
- if (typeof parameterPath === "string") {
- result = parameterPath;
- }
- else if (Array.isArray(parameterPath)) {
- result = parameterPath.join(".");
- }
- else {
- result = mapper.serializedName;
+ }
+
+ function filterLines(stdout) {
+ let lines = stdout.toString().split('\n');
+ lines.shift();
+ if (stdout.toString().toLowerCase().indexOf('filesystem')) {
+ let removeLines = 0;
+ for (let i = 0; i < lines.length; i++) {
+ if (lines[i] && lines[i].toLowerCase().startsWith('filesystem')) {
+ removeLines = i;
+ }
+ }
+ for (let i = 0; i < removeLines; i++) {
+ lines.shift();
+ }
}
- return result;
+ return lines;
+ }
+
+ function parseDf(lines) {
+ let data = [];
+ lines.forEach(function (line) {
+ if (line !== '') {
+ line = line.replace(/ +/g, ' ').split(' ');
+ if (line && ((line[0].startsWith('/')) || (line[6] && line[6] === '/') || (line[0].indexOf('/') > 0) || (line[0].indexOf(':') === 1) || !_darwin && !isLinuxTmpFs(line[1]))) {
+ const fs = line[0];
+ const fsType = ((_linux || _freebsd || _openbsd || _netbsd) ? line[1] : getmacOsFsType(line[0]));
+ const size = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[2] : line[1])) * 1024;
+ const used = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[3] : line[2])) * 1024;
+ const available = parseInt(((_linux || _freebsd || _openbsd || _netbsd) ? line[4] : line[3])) * 1024;
+ const use = parseFloat((100.0 * (used / (used + available))).toFixed(2));
+ let rw = osMounts && Object.keys(osMounts).length > 0 ? osMounts[fs] || false : null;
+ line.splice(0, (_linux || _freebsd || _openbsd || _netbsd) ? 6 : 5);
+ const mount = line.join(' ');
+ if (!data.find(el => (el.fs === fs && el.type === fsType))) {
+ data.push({
+ fs,
+ type: fsType,
+ size,
+ used,
+ available,
+ use,
+ mount,
+ rw
+ });
+ }
+ }
+ }
+ });
+ return data;
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let data = [];
+ if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
+ let cmd = '';
+ macOsDisks = [];
+ osMounts = {};
+ if (_darwin) {
+ cmd = 'df -kP';
+ try {
+ macOsDisks = execSync('diskutil list').toString().split('\n').filter(line => {
+ return !line.startsWith('/') && line.indexOf(':') > 0;
+ });
+ execSync('mount').toString().split('\n').filter(line => {
+ return line.startsWith('/');
+ }).forEach((line) => {
+ osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1;
+ });
+ } catch (e) {
+ util.noop();
+ }
+ }
+ if (_linux) {
+ try {
+ cmd = 'export LC_ALL=C; df -lkPTx squashfs; unset LC_ALL';
+ execSync('cat /proc/mounts 2>/dev/null', util.execOptsLinux).toString().split('\n').filter(line => {
+ return line.startsWith('/');
+ }).forEach((line) => {
+ osMounts[line.split(' ')[0]] = osMounts[line.split(' ')[0]] || false;
+ if (line.toLowerCase().indexOf('/snap/') === -1) {
+ osMounts[line.split(' ')[0]] = ((line.toLowerCase().indexOf('rw,') >= 0 || line.toLowerCase().indexOf(' rw ') >= 0));
+ }
+ });
+ } catch (e) {
+ util.noop();
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ try {
+ cmd = 'df -lkPT';
+ execSync('mount').toString().split('\n').forEach((line) => {
+ osMounts[line.split(' ')[0]] = line.toLowerCase().indexOf('read-only') === -1;
+ });
+ } catch (e) {
+ util.noop();
+ }
+ }
+ exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ let lines = filterLines(stdout);
+ data = parseDf(lines);
+ if (drive) {
+ data = data.filter(item => {
+ return item.fs.toLowerCase().indexOf(drive.toLowerCase()) >= 0 || item.mount.toLowerCase().indexOf(drive.toLowerCase()) >= 0;
+ });
+ }
+ if ((!error || data.length) && stdout.toString().trim() !== '') {
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ } else {
+ exec('df -kPT', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = filterLines(stdout);
+ data = parseDf(lines);
+ }
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ });
+ }
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(data); }
+ resolve(data);
+ }
+ if (_windows) {
+ try {
+ const cmd = `Get-WmiObject Win32_logicaldisk | select Access,Caption,FileSystem,FreeSpace,Size ${drive ? '| where -property Caption -eq ' + drive : ''} | fl`;
+ util.powerShell(cmd).then((stdout, error) => {
+ if (!error) {
+ let devices = stdout.toString().split(/\n\s*\n/);
+ devices.forEach(function (device) {
+ let lines = device.split('\r\n');
+ const size = util.toInt(util.getValue(lines, 'size', ':'));
+ const free = util.toInt(util.getValue(lines, 'freespace', ':'));
+ const caption = util.getValue(lines, 'caption', ':');
+ const rwValue = util.getValue(lines, 'access', ':');
+ const rw = rwValue ? (util.toInt(rwValue) !== 1) : null;
+ if (size) {
+ data.push({
+ fs: caption,
+ type: util.getValue(lines, 'filesystem', ':'),
+ size,
+ used: size - free,
+ available: free,
+ use: parseFloat(((100.0 * (size - free)) / size).toFixed(2)),
+ mount: caption,
+ rw
+ });
+ }
+ });
+ }
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ });
+ } catch (e) {
+ if (callback) { callback(data); }
+ resolve(data);
+ }
+ }
+ });
+ });
}
-exports.getPathStringFromParameter = getPathStringFromParameter;
-//# sourceMappingURL=interfaceHelpers.js.map
-/***/ }),
+exports.fsSize = fsSize;
-/***/ 35590:
-/***/ ((__unused_webpack_module, exports) => {
+// --------------------------
+// FS - open files count
+function fsOpenFiles(callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.XML_CHARKEY = exports.XML_ATTRKEY = void 0;
-/**
- * Default key used to access the XML attributes.
- */
-exports.XML_ATTRKEY = "$";
-/**
- * Default key used to access the XML value content.
- */
-exports.XML_CHARKEY = "_";
-//# sourceMappingURL=interfaces.js.map
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ const result = {
+ max: null,
+ allocated: null,
+ available: null
+ };
+ if (_freebsd || _openbsd || _netbsd || _darwin) {
+ let cmd = 'sysctl -i kern.maxfiles kern.num_files kern.open_files';
+ exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result.max = parseInt(util.getValue(lines, 'kern.maxfiles', ':'), 10);
+ result.allocated = parseInt(util.getValue(lines, 'kern.num_files', ':'), 10) || parseInt(util.getValue(lines, 'kern.open_files', ':'), 10);
+ result.available = result.max - result.allocated;
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ if (_linux) {
+ fs.readFile('/proc/sys/fs/file-nr', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines[0]) {
+ const parts = lines[0].replace(/\s+/g, ' ').split(' ');
+ if (parts.length === 3) {
+ result.allocated = parseInt(parts[0], 10);
+ result.available = parseInt(parts[1], 10);
+ result.max = parseInt(parts[2], 10);
+ if (!result.available) { result.available = result.max - result.allocated; }
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ } else {
+ fs.readFile('/proc/sys/fs/file-max', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines[0]) {
+ result.max = parseInt(lines[0], 10);
+ }
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ }
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(null); }
+ resolve(null);
+ }
+ if (_windows) {
+ if (callback) { callback(null); }
+ resolve(null);
+ }
+ });
+ });
+}
-/***/ }),
+exports.fsOpenFiles = fsOpenFiles;
-/***/ 75630:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// disks
+function parseBytes(s) {
+ return parseInt(s.substr(s.indexOf(' (') + 2, s.indexOf(' Bytes)') - 10));
+}
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.logger = void 0;
-const logger_1 = __nccwpck_require__(50143);
-exports.logger = (0, logger_1.createClientLogger)("core-client");
-//# sourceMappingURL=log.js.map
+function parseDevices(lines) {
+ let devices = [];
+ let i = 0;
+ lines.forEach(line => {
+ if (line.length > 0) {
+ if (line[0] === '*') {
+ i++;
+ } else {
+ let parts = line.split(':');
+ if (parts.length > 1) {
+ if (!devices[i]) {
+ devices[i] = {
+ name: '',
+ identifier: '',
+ type: 'disk',
+ fsType: '',
+ mount: '',
+ size: 0,
+ physical: 'HDD',
+ uuid: '',
+ label: '',
+ model: '',
+ serial: '',
+ removable: false,
+ protocol: '',
+ group: '',
+ device: ''
+ };
+ }
+ parts[0] = parts[0].trim().toUpperCase().replace(/ +/g, '');
+ parts[1] = parts[1].trim();
+ if ('DEVICEIDENTIFIER' === parts[0]) { devices[i].identifier = parts[1]; }
+ if ('DEVICENODE' === parts[0]) { devices[i].name = parts[1]; }
+ if ('VOLUMENAME' === parts[0]) {
+ if (parts[1].indexOf('Not applicable') === -1) { devices[i].label = parts[1]; }
+ }
+ if ('PROTOCOL' === parts[0]) { devices[i].protocol = parts[1]; }
+ if ('DISKSIZE' === parts[0]) { devices[i].size = parseBytes(parts[1]); }
+ if ('FILESYSTEMPERSONALITY' === parts[0]) { devices[i].fsType = parts[1]; }
+ if ('MOUNTPOINT' === parts[0]) { devices[i].mount = parts[1]; }
+ if ('VOLUMEUUID' === parts[0]) { devices[i].uuid = parts[1]; }
+ if ('READ-ONLYMEDIA' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'CD/DVD'; }
+ if ('SOLIDSTATE' === parts[0] && parts[1] === 'Yes') { devices[i].physical = 'SSD'; }
+ if ('VIRTUAL' === parts[0]) { devices[i].type = 'virtual'; }
+ if ('REMOVABLEMEDIA' === parts[0]) { devices[i].removable = (parts[1] === 'Removable'); }
+ if ('PARTITIONTYPE' === parts[0]) { devices[i].type = 'part'; }
+ if ('DEVICE/MEDIANAME' === parts[0]) { devices[i].model = parts[1]; }
+ }
+ }
+ }
+ });
+ return devices;
+}
+
+function parseBlk(lines) {
+ let data = [];
+
+ lines.filter(line => line !== '').forEach((line) => {
+ try {
+ line = decodeURIComponent(line.replace(/\\x/g, '%'));
+ line = line.replace(/\\/g, '\\\\');
+ let disk = JSON.parse(line);
+ data.push({
+ 'name': disk.name,
+ 'type': disk.type,
+ 'fsType': disk.fsType,
+ 'mount': disk.mountpoint,
+ 'size': parseInt(disk.size),
+ 'physical': (disk.type === 'disk' ? (disk.rota === '0' ? 'SSD' : 'HDD') : (disk.type === 'rom' ? 'CD/DVD' : '')),
+ 'uuid': disk.uuid,
+ 'label': disk.label,
+ 'model': (disk.model || '').trim(),
+ 'serial': disk.serial,
+ 'removable': disk.rm === '1',
+ 'protocol': disk.tran,
+ 'group': disk.group || '',
+ });
+ } catch (e) {
+ util.noop();
+ }
+ });
+ data = util.unique(data);
+ data = util.sortByKey(data, ['type', 'name']);
+ return data;
+}
-/***/ }),
+function decodeMdabmData(lines) {
+ const raid = util.getValue(lines, 'md_level', '=');
+ const label = util.getValue(lines, 'md_name', '='); // <- get label info
+ const uuid = util.getValue(lines, 'md_uuid', '='); // <- get uuid info
+ const members = [];
+ lines.forEach(line => {
+ if (line.toLowerCase().startsWith('md_device_dev') && line.toLowerCase().indexOf('/dev/') > 0) {
+ members.push(line.split('/dev/')[1]);
+ }
+ });
+ return {
+ raid,
+ label,
+ uuid,
+ members
+ };
+}
-/***/ 17036:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function raidMatchLinux(data) {
+ // for all block devices of type "raid%"
+ let result = data;
+ try {
+ data.forEach(element => {
+ if (element.type.startsWith('raid')) {
+ const lines = execSync(`mdadm --export --detail /dev/${element.name}`, util.execOptsLinux).toString().split('\n');
+ const mdData = decodeMdabmData(lines);
+ element.label = mdData.label; // <- assign label info
+ element.uuid = mdData.uuid; // <- assign uuid info
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.getOperationRequestInfo = exports.getOperationArgumentValueFromParameter = void 0;
-const state_js_1 = __nccwpck_require__(35077);
-/**
- * @internal
- * Retrieves the value to use for a given operation argument
- * @param operationArguments - The arguments passed from the generated client
- * @param parameter - The parameter description
- * @param fallbackObject - If something isn't found in the arguments bag, look here.
- * Generally used to look at the service client properties.
- */
-function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) {
- let parameterPath = parameter.parameterPath;
- const parameterMapper = parameter.mapper;
- let value;
- if (typeof parameterPath === "string") {
- parameterPath = [parameterPath];
- }
- if (Array.isArray(parameterPath)) {
- if (parameterPath.length > 0) {
- if (parameterMapper.isConstant) {
- value = parameterMapper.defaultValue;
- }
- else {
- let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
- if (!propertySearchResult.propertyFound && fallbackObject) {
- propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath);
- }
- let useDefaultValue = false;
- if (!propertySearchResult.propertyFound) {
- useDefaultValue =
- parameterMapper.required ||
- (parameterPath[0] === "options" && parameterPath.length === 2);
- }
- value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
- }
- }
- }
- else {
- if (parameterMapper.required) {
- value = {};
- }
- for (const propertyName in parameterPath) {
- const propertyMapper = parameterMapper.type.modelProperties[propertyName];
- const propertyPath = parameterPath[propertyName];
- const propertyValue = getOperationArgumentValueFromParameter(operationArguments, {
- parameterPath: propertyPath,
- mapper: propertyMapper,
- }, fallbackObject);
- if (propertyValue !== undefined) {
- if (!value) {
- value = {};
- }
- value[propertyName] = propertyValue;
+ if (mdData.members && mdData.members.length && mdData.raid === element.type) {
+ result = result.map(blockdevice => {
+ if (blockdevice.fsType === 'linux_raid_member' && mdData.members.indexOf(blockdevice.name) >= 0) {
+ blockdevice.group = element.name;
}
+ return blockdevice;
+ });
}
+ }
+ });
+ } catch (e) {
+ util.noop();
+ }
+ return result;
+}
+
+function getDevicesLinux(data) {
+ const result = [];
+ data.forEach(element => {
+ if (element.type.startsWith('disk')) {
+ result.push(element.name);
}
- return value;
+ });
+ return result;
}
-exports.getOperationArgumentValueFromParameter = getOperationArgumentValueFromParameter;
-function getPropertyFromParameterPath(parent, parameterPath) {
- const result = { propertyFound: false };
- let i = 0;
- for (; i < parameterPath.length; ++i) {
- const parameterPathPart = parameterPath[i];
- // Make sure to check inherited properties too, so don't use hasOwnProperty().
- if (parent && parameterPathPart in parent) {
- parent = parent[parameterPathPart];
- }
- else {
- break;
- }
+
+function matchDevicesLinux(data) {
+ let result = data;
+ try {
+ const devices = getDevicesLinux(data);
+ result = result.map(blockdevice => {
+ if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk')) {
+ devices.forEach(element => {
+ if (blockdevice.name.startsWith(element)) {
+ blockdevice.device = '/dev/' + element;
+ }
+ });
+ }
+ return blockdevice;
+ });
+ } catch (e) {
+ util.noop();
+ }
+ return result;
+}
+
+function getDevicesMac(data) {
+ const result = [];
+ data.forEach(element => {
+ if (element.type.startsWith('disk')) {
+ result.push({ name: element.name, model: element.model, device: element.name });
}
- if (i === parameterPath.length) {
- result.propertyValue = parent;
- result.propertyFound = true;
+ if (element.type.startsWith('virtual')) {
+ let device = '';
+ result.forEach(e => {
+ if (e.model === element.model) {
+ device = e.device;
+ }
+ });
+ if (device) {
+ result.push({ name: element.name, model: element.model, device });
+ }
}
- return result;
+ });
+ return result;
}
-const originalRequestSymbol = Symbol.for("@azure/core-client original request");
-function hasOriginalRequest(request) {
- return originalRequestSymbol in request;
+
+function matchDevicesMac(data) {
+ let result = data;
+ try {
+ const devices = getDevicesMac(data);
+ result = result.map(blockdevice => {
+ if (blockdevice.type.startsWith('part') || blockdevice.type.startsWith('disk') || blockdevice.type.startsWith('virtual')) {
+ devices.forEach(element => {
+ if (blockdevice.name.startsWith(element.name)) {
+ blockdevice.device = element.device;
+ }
+ });
+ }
+ return blockdevice;
+ });
+ } catch (e) {
+ util.noop();
+ }
+ return result;
}
-function getOperationRequestInfo(request) {
- if (hasOriginalRequest(request)) {
- return getOperationRequestInfo(request[originalRequestSymbol]);
+
+function getDevicesWin(diskDrives) {
+ const result = [];
+ diskDrives.forEach(element => {
+ const lines = element.split('\r\n');
+ const device = util.getValue(lines, 'DeviceID', ':');
+ let partitions = element.split('@{DeviceID=');
+ if (partitions.length > 1) {
+ partitions = partitions.slice(1);
+ partitions.forEach(partition => {
+ result.push({ name: partition.split(';')[0].toUpperCase(), device });
+ });
}
- let info = state_js_1.state.operationRequestMap.get(request);
- if (!info) {
- info = {};
- state_js_1.state.operationRequestMap.set(request, info);
+ });
+ return result;
+}
+
+function matchDevicesWin(data, diskDrives) {
+ const devices = getDevicesWin(diskDrives);
+ data.map(element => {
+ const filteresDevices = devices.filter((e) => { return e.name === element.name.toUpperCase(); });
+ if (filteresDevices.length > 0) {
+ element.device = filteresDevices[0].device;
}
- return info;
+ return element;
+ });
+ return data;
}
-exports.getOperationRequestInfo = getOperationRequestInfo;
-//# sourceMappingURL=operationHelpers.js.map
-/***/ }),
+function blkStdoutToObject(stdout) {
+ return stdout.toString()
+ .replace(/NAME=/g, '{"name":')
+ .replace(/FSTYPE=/g, ',"fsType":')
+ .replace(/TYPE=/g, ',"type":')
+ .replace(/SIZE=/g, ',"size":')
+ .replace(/MOUNTPOINT=/g, ',"mountpoint":')
+ .replace(/UUID=/g, ',"uuid":')
+ .replace(/ROTA=/g, ',"rota":')
+ .replace(/RO=/g, ',"ro":')
+ .replace(/RM=/g, ',"rm":')
+ .replace(/TRAN=/g, ',"tran":')
+ .replace(/SERIAL=/g, ',"serial":')
+ .replace(/LABEL=/g, ',"label":')
+ .replace(/MODEL=/g, ',"model":')
+ .replace(/OWNER=/g, ',"owner":')
+ .replace(/GROUP=/g, ',"group":')
+ .replace(/\n/g, '}\n');
+}
-/***/ 64524:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+function blockDevices(callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let data = [];
+ if (_linux) {
+ // see https://wiki.ubuntuusers.de/lsblk/
+ // exec("lsblk -bo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,TRAN,SERIAL,LABEL,MODEL,OWNER,GROUP,MODE,ALIGNMENT,MIN-IO,OPT-IO,PHY-SEC,LOG-SEC,SCHED,RQ-SIZE,RA,WSAME", function (error, stdout) {
+ exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,TRAN,SERIAL,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = blkStdoutToObject(stdout).split('\n');
+ data = parseBlk(lines);
+ data = raidMatchLinux(data);
+ data = matchDevicesLinux(data);
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ } else {
+ exec('lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER 2>/dev/null', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = blkStdoutToObject(stdout).split('\n');
+ data = parseBlk(lines);
+ data = raidMatchLinux(data);
+ }
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ });
+ }
+ });
+ }
+ if (_darwin) {
+ exec('diskutil info -all', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ // parse lines into temp array of devices
+ data = parseDevices(lines);
+ data = matchDevicesMac(data);
+ }
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ });
+ }
+ if (_sunos) {
+ if (callback) { callback(data); }
+ resolve(data);
+ }
+ if (_windows) {
+ let drivetypes = ['Unknown', 'NoRoot', 'Removable', 'Local', 'Network', 'CD/DVD', 'RAM'];
+ try {
+ // util.wmic('logicaldisk get Caption,Description,DeviceID,DriveType,FileSystem,FreeSpace,Name,Size,VolumeName,VolumeSerialNumber /value').then((stdout, error) => {
+ // util.powerShell('Get-CimInstance Win32_logicaldisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl').then((stdout, error) => {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance -ClassName Win32_LogicalDisk | select Caption,DriveType,Name,FileSystem,Size,VolumeSerialNumber,VolumeName | fl'));
+ workload.push(util.powerShell('Get-WmiObject -Class Win32_diskdrive | Select-Object -Property PNPDeviceId,DeviceID, Model, Size, @{L=\'Partitions\'; E={$_.GetRelated(\'Win32_DiskPartition\').GetRelated(\'Win32_LogicalDisk\') | Select-Object -Property DeviceID, VolumeName, Size, FreeSpace}} | fl'));
+ util.promiseAll(
+ workload
+ ).then((res) => {
+ let logicalDisks = res.results[0].toString().split(/\n\s*\n/);
+ let diskDrives = res.results[1].toString().split(/\n\s*\n/);
+ logicalDisks.forEach(function (device) {
+ let lines = device.split('\r\n');
+ let drivetype = util.getValue(lines, 'drivetype', ':');
+ if (drivetype) {
+ data.push({
+ name: util.getValue(lines, 'name', ':'),
+ identifier: util.getValue(lines, 'caption', ':'),
+ type: 'disk',
+ fsType: util.getValue(lines, 'filesystem', ':').toLowerCase(),
+ mount: util.getValue(lines, 'caption', ':'),
+ size: util.getValue(lines, 'size', ':'),
+ physical: (drivetype >= 0 && drivetype <= 6) ? drivetypes[drivetype] : drivetypes[0],
+ uuid: util.getValue(lines, 'volumeserialnumber', ':'),
+ label: util.getValue(lines, 'volumename', ':'),
+ model: '',
+ serial: util.getValue(lines, 'volumeserialnumber', ':'),
+ removable: drivetype === '2',
+ protocol: '',
+ group: '',
+ device: ''
+ });
+ }
+ });
+ // match devices
+ data = matchDevicesWin(data, diskDrives);
+ if (callback) {
+ callback(data);
+ }
+ resolve(data);
+ });
+ } catch (e) {
+ if (callback) { callback(data); }
+ resolve(data);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ // will follow
+ if (callback) { callback(null); }
+ resolve(null);
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createClientPipeline = void 0;
-const deserializationPolicy_js_1 = __nccwpck_require__(21795);
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-const serializationPolicy_js_1 = __nccwpck_require__(87054);
-/**
- * Creates a new Pipeline for use with a Service Client.
- * Adds in deserializationPolicy by default.
- * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential.
- * @param options - Options to customize the created pipeline.
- */
-function createClientPipeline(options = {}) {
- const pipeline = (0, core_rest_pipeline_1.createPipelineFromOptions)(options !== null && options !== void 0 ? options : {});
- if (options.credentialOptions) {
- pipeline.addPolicy((0, core_rest_pipeline_1.bearerTokenAuthenticationPolicy)({
- credential: options.credentialOptions.credential,
- scopes: options.credentialOptions.credentialScopes,
- }));
- }
- pipeline.addPolicy((0, serializationPolicy_js_1.serializationPolicy)(options.serializationOptions), { phase: "Serialize" });
- pipeline.addPolicy((0, deserializationPolicy_js_1.deserializationPolicy)(options.deserializationOptions), {
- phase: "Deserialize",
});
- return pipeline;
+ });
}
-exports.createClientPipeline = createClientPipeline;
-//# sourceMappingURL=pipeline.js.map
-/***/ }),
+exports.blockDevices = blockDevices;
-/***/ 87054:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// FS - speed
+function calcFsSpeed(rx, wx) {
+ let result = {
+ rx: 0,
+ wx: 0,
+ tx: 0,
+ rx_sec: null,
+ wx_sec: null,
+ tx_sec: null,
+ ms: 0
+ };
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.serializeRequestBody = exports.serializeHeaders = exports.serializationPolicy = exports.serializationPolicyName = void 0;
-const interfaces_js_1 = __nccwpck_require__(35590);
-const operationHelpers_js_1 = __nccwpck_require__(17036);
-const serializer_js_1 = __nccwpck_require__(66774);
-const interfaceHelpers_js_1 = __nccwpck_require__(91030);
-/**
- * The programmatic identifier of the serializationPolicy.
- */
-exports.serializationPolicyName = "serializationPolicy";
-/**
- * This policy handles assembling the request body and headers using
- * an OperationSpec and OperationArguments on the request.
- */
-function serializationPolicy(options = {}) {
- const stringifyXML = options.stringifyXML;
- return {
- name: exports.serializationPolicyName,
- async sendRequest(request, next) {
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec;
- const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments;
- if (operationSpec && operationArguments) {
- serializeHeaders(request, operationArguments, operationSpec);
- serializeRequestBody(request, operationArguments, operationSpec, stringifyXML);
- }
- return next(request);
- },
- };
+ if (_fs_speed && _fs_speed.ms) {
+ result.rx = rx;
+ result.wx = wx;
+ result.tx = result.rx + result.wx;
+ result.ms = Date.now() - _fs_speed.ms;
+ result.rx_sec = (result.rx - _fs_speed.bytes_read) / (result.ms / 1000);
+ result.wx_sec = (result.wx - _fs_speed.bytes_write) / (result.ms / 1000);
+ result.tx_sec = result.rx_sec + result.wx_sec;
+ _fs_speed.rx_sec = result.rx_sec;
+ _fs_speed.wx_sec = result.wx_sec;
+ _fs_speed.tx_sec = result.tx_sec;
+ _fs_speed.bytes_read = result.rx;
+ _fs_speed.bytes_write = result.wx;
+ _fs_speed.bytes_overall = result.rx + result.wx;
+ _fs_speed.ms = Date.now();
+ _fs_speed.last_ms = result.ms;
+ } else {
+ result.rx = rx;
+ result.wx = wx;
+ result.tx = result.rx + result.wx;
+ _fs_speed.rx_sec = null;
+ _fs_speed.wx_sec = null;
+ _fs_speed.tx_sec = null;
+ _fs_speed.bytes_read = result.rx;
+ _fs_speed.bytes_write = result.wx;
+ _fs_speed.bytes_overall = result.rx + result.wx;
+ _fs_speed.ms = Date.now();
+ _fs_speed.last_ms = 0;
+ }
+ return result;
}
-exports.serializationPolicy = serializationPolicy;
-/**
- * @internal
- */
-function serializeHeaders(request, operationArguments, operationSpec) {
- var _a, _b;
- if (operationSpec.headerParameters) {
- for (const headerParameter of operationSpec.headerParameters) {
- let headerValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, headerParameter);
- if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) {
- headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter));
- const headerCollectionPrefix = headerParameter.mapper
- .headerCollectionPrefix;
- if (headerCollectionPrefix) {
- for (const key of Object.keys(headerValue)) {
- request.headers.set(headerCollectionPrefix + key, headerValue[key]);
+
+function fsStats(callback) {
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (_windows || _freebsd || _openbsd || _netbsd || _sunos) {
+ return resolve(null);
+ }
+
+ let result = {
+ rx: 0,
+ wx: 0,
+ tx: 0,
+ rx_sec: null,
+ wx_sec: null,
+ tx_sec: null,
+ ms: 0
+ };
+
+ let rx = 0;
+ let wx = 0;
+ if ((_fs_speed && !_fs_speed.ms) || (_fs_speed && _fs_speed.ms && Date.now() - _fs_speed.ms >= 500)) {
+ if (_linux) {
+ // exec("df -k | grep /dev/", function(error, stdout) {
+ exec('lsblk -r 2>/dev/null | grep /', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ let fs_filter = [];
+ lines.forEach(function (line) {
+ if (line !== '') {
+ line = line.trim().split(' ');
+ if (fs_filter.indexOf(line[0]) === -1) { fs_filter.push(line[0]); }
+ }
+ });
+
+ let output = fs_filter.join('|');
+ exec('cat /proc/diskstats | egrep "' + output + '"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ line = line.trim();
+ if (line !== '') {
+ line = line.replace(/ +/g, ' ').split(' ');
+
+ rx += parseInt(line[5]) * 512;
+ wx += parseInt(line[9]) * 512;
}
+ });
+ result = calcFsSpeed(rx, wx);
}
- else {
- request.headers.set(headerParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(headerParameter), headerValue);
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ });
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
}
+ });
}
- }
- const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders;
- if (customHeaders) {
- for (const customHeaderName of Object.keys(customHeaders)) {
- request.headers.set(customHeaderName, customHeaders[customHeaderName]);
- }
- }
-}
-exports.serializeHeaders = serializeHeaders;
-/**
- * @internal
- */
-function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () {
- throw new Error("XML serialization unsupported!");
-}) {
- var _a, _b, _c, _d, _e;
- const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions;
- const updatedOptions = {
- xml: {
- rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "",
- includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false,
- xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : interfaces_js_1.XML_CHARKEY,
- },
- };
- const xmlCharKey = updatedOptions.xml.xmlCharKey;
- if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
- request.body = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, operationSpec.requestBody);
- const bodyMapper = operationSpec.requestBody.mapper;
- const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper;
- const typeName = bodyMapper.type.name;
- try {
- if ((request.body !== undefined && request.body !== null) ||
- (nullable && request.body === null) ||
- required) {
- const requestBodyParameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(operationSpec.requestBody);
- request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions);
- const isStream = typeName === serializer_js_1.MapperTypeNames.Stream;
- if (operationSpec.isXML) {
- const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns";
- const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions);
- if (typeName === serializer_js_1.MapperTypeNames.Sequence) {
- request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey });
- }
- else if (!isStream) {
- request.body = stringifyXML(value, {
- rootName: xmlName || serializedName,
- xmlCharKey,
- });
- }
- }
- else if (typeName === serializer_js_1.MapperTypeNames.String &&
- (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) {
- // the String serializer has validated that request body is a string
- // so just send the string.
- return;
- }
- else if (!isStream) {
- request.body = JSON.stringify(request.body);
+ if (_darwin) {
+ exec('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ line = line.trim();
+ if (line !== '') {
+ line = line.split(',');
+
+ rx += parseInt(line[2]);
+ wx += parseInt(line[9]);
}
+ });
+ result = calcFsSpeed(rx, wx);
}
- }
- catch (error) {
- throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`);
- }
- }
- else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
- request.formData = {};
- for (const formDataParameter of operationSpec.formDataParameters) {
- const formDataParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, formDataParameter);
- if (formDataParameterValue !== undefined && formDataParameterValue !== null) {
- const formDataParameterPropertyName = formDataParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter);
- request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(formDataParameter), updatedOptions);
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ });
}
- }
-}
-exports.serializeRequestBody = serializeRequestBody;
-/**
- * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself
- */
-function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) {
- // Composite and Sequence schemas already got their root namespace set during serialization
- // We just need to add xmlns to the other schema types
- if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) {
- const result = {};
- result[options.xml.xmlCharKey] = serializedValue;
- result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace };
- return result;
- }
- return serializedValue;
+ } else {
+ result.ms = _fs_speed.last_ms;
+ result.rx = _fs_speed.bytes_read;
+ result.wx = _fs_speed.bytes_write;
+ result.tx = _fs_speed.bytes_read + _fs_speed.bytes_write;
+ result.rx_sec = _fs_speed.rx_sec;
+ result.wx_sec = _fs_speed.wx_sec;
+ result.tx_sec = _fs_speed.tx_sec;
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ }
+ });
+ });
}
-function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) {
- if (!Array.isArray(obj)) {
- obj = [obj];
- }
- if (!xmlNamespaceKey || !xmlNamespace) {
- return { [elementName]: obj };
- }
- const result = { [elementName]: obj };
- result[interfaces_js_1.XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace };
- return result;
+
+exports.fsStats = fsStats;
+
+function calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime) {
+ let result = {
+ rIO: 0,
+ wIO: 0,
+ tIO: 0,
+ rIO_sec: null,
+ wIO_sec: null,
+ tIO_sec: null,
+ rWaitTime: 0,
+ wWaitTime: 0,
+ tWaitTime: 0,
+ rWaitPercent: null,
+ wWaitPercent: null,
+ tWaitPercent: null,
+ ms: 0
+ };
+ if (_disk_io && _disk_io.ms) {
+ result.rIO = rIO;
+ result.wIO = wIO;
+ result.tIO = rIO + wIO;
+ result.ms = Date.now() - _disk_io.ms;
+ result.rIO_sec = (result.rIO - _disk_io.rIO) / (result.ms / 1000);
+ result.wIO_sec = (result.wIO - _disk_io.wIO) / (result.ms / 1000);
+ result.tIO_sec = result.rIO_sec + result.wIO_sec;
+ result.rWaitTime = rWaitTime;
+ result.wWaitTime = wWaitTime;
+ result.tWaitTime = tWaitTime;
+ result.rWaitPercent = (result.rWaitTime - _disk_io.rWaitTime) * 100 / (result.ms);
+ result.wWaitPercent = (result.wWaitTime - _disk_io.wWaitTime) * 100 / (result.ms);
+ result.tWaitPercent = (result.tWaitTime - _disk_io.tWaitTime) * 100 / (result.ms);
+ _disk_io.rIO = rIO;
+ _disk_io.wIO = wIO;
+ _disk_io.rIO_sec = result.rIO_sec;
+ _disk_io.wIO_sec = result.wIO_sec;
+ _disk_io.tIO_sec = result.tIO_sec;
+ _disk_io.rWaitTime = rWaitTime;
+ _disk_io.wWaitTime = wWaitTime;
+ _disk_io.tWaitTime = tWaitTime;
+ _disk_io.rWaitPercent = result.rWaitPercent;
+ _disk_io.wWaitPercent = result.wWaitPercent;
+ _disk_io.tWaitPercent = result.tWaitPercent;
+ _disk_io.last_ms = result.ms;
+ _disk_io.ms = Date.now();
+ } else {
+ result.rIO = rIO;
+ result.wIO = wIO;
+ result.tIO = rIO + wIO;
+ result.rWaitTime = rWaitTime;
+ result.wWaitTime = wWaitTime;
+ result.tWaitTime = tWaitTime;
+ _disk_io.rIO = rIO;
+ _disk_io.wIO = wIO;
+ _disk_io.rIO_sec = null;
+ _disk_io.wIO_sec = null;
+ _disk_io.tIO_sec = null;
+ _disk_io.rWaitTime = rWaitTime;
+ _disk_io.wWaitTime = wWaitTime;
+ _disk_io.tWaitTime = tWaitTime;
+ _disk_io.rWaitPercent = null;
+ _disk_io.wWaitPercent = null;
+ _disk_io.tWaitPercent = null;
+ _disk_io.last_ms = 0;
+ _disk_io.ms = Date.now();
+ }
+ return result;
}
-//# sourceMappingURL=serializationPolicy.js.map
-/***/ }),
+function disksIO(callback) {
-/***/ 66774:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (_windows) {
+ return resolve(null);
+ }
+ if (_sunos) {
+ return resolve(null);
+ }
+
+ let result = {
+ rIO: 0,
+ wIO: 0,
+ tIO: 0,
+ rIO_sec: null,
+ wIO_sec: null,
+ tIO_sec: null,
+ rWaitTime: 0,
+ wWaitTime: 0,
+ tWaitTime: 0,
+ rWaitPercent: null,
+ wWaitPercent: null,
+ tWaitPercent: null,
+ ms: 0
+ };
+ let rIO = 0;
+ let wIO = 0;
+ let rWaitTime = 0;
+ let wWaitTime = 0;
+ let tWaitTime = 0;
+ if ((_disk_io && !_disk_io.ms) || (_disk_io && _disk_io.ms && Date.now() - _disk_io.ms >= 500)) {
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ // prints Block layer statistics for all mounted volumes
+ // var cmd = "for mount in `lsblk | grep / | sed -r 's/│ └─//' | cut -d ' ' -f 1`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done";
+ // var cmd = "for mount in `lsblk | grep / | sed 's/[│└─├]//g' | awk '{$1=$1};1' | cut -d ' ' -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r 's/ +/;/g' | sed -r 's/^;//'; done";
+ let cmd = 'for mount in `lsblk 2>/dev/null | grep " disk " | sed "s/[│└─├]//g" | awk \'{$1=$1};1\' | cut -d " " -f 1 | sort -u`; do cat /sys/block/$mount/stat | sed -r "s/ +/;/g" | sed -r "s/^;//"; done';
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.MapperTypeNames = exports.createSerializer = void 0;
-const tslib_1 = __nccwpck_require__(94176);
-const base64 = tslib_1.__importStar(__nccwpck_require__(59793));
-const interfaces_js_1 = __nccwpck_require__(35590);
-const utils_js_1 = __nccwpck_require__(7805);
-class SerializerImpl {
- constructor(modelMappers = {}, isXML = false) {
- this.modelMappers = modelMappers;
- this.isXML = isXML;
- }
- /**
- * @deprecated Removing the constraints validation on client side.
- */
- validateConstraints(mapper, value, objectName) {
- const failValidation = (constraintName, constraintValue) => {
- throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`);
- };
- if (mapper.constraints && value !== undefined && value !== null) {
- const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints;
- if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) {
- failValidation("ExclusiveMaximum", ExclusiveMaximum);
- }
- if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) {
- failValidation("ExclusiveMinimum", ExclusiveMinimum);
- }
- if (InclusiveMaximum !== undefined && value > InclusiveMaximum) {
- failValidation("InclusiveMaximum", InclusiveMaximum);
- }
- if (InclusiveMinimum !== undefined && value < InclusiveMinimum) {
- failValidation("InclusiveMinimum", InclusiveMinimum);
- }
- if (MaxItems !== undefined && value.length > MaxItems) {
- failValidation("MaxItems", MaxItems);
- }
- if (MaxLength !== undefined && value.length > MaxLength) {
- failValidation("MaxLength", MaxLength);
- }
- if (MinItems !== undefined && value.length < MinItems) {
- failValidation("MinItems", MinItems);
- }
- if (MinLength !== undefined && value.length < MinLength) {
- failValidation("MinLength", MinLength);
- }
- if (MultipleOf !== undefined && value % MultipleOf !== 0) {
- failValidation("MultipleOf", MultipleOf);
+ exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.split('\n');
+ lines.forEach(function (line) {
+ // ignore empty lines
+ if (!line) { return; }
+
+ // sum r/wIO of all disks to compute all disks IO
+ let stats = line.split(';');
+ rIO += parseInt(stats[0]);
+ wIO += parseInt(stats[4]);
+ rWaitTime += parseInt(stats[3]);
+ wWaitTime += parseInt(stats[7]);
+ tWaitTime += parseInt(stats[10]);
+ });
+ result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime);
+
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ } else {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
}
- if (Pattern) {
- const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
- if (typeof value !== "string" || value.match(pattern) === null) {
- failValidation("Pattern", Pattern);
+ });
+ }
+ if (_darwin) {
+ exec('ioreg -c IOBlockStorageDriver -k Statistics -r -w0 | sed -n "/IOBlockStorageDriver/,/Statistics/p" | grep "Statistics" | tr -cd "01234567890,\n"', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(function (line) {
+ line = line.trim();
+ if (line !== '') {
+ line = line.split(',');
+
+ rIO += parseInt(line[10]);
+ wIO += parseInt(line[0]);
}
+ });
+ result = calcDiskIO(rIO, wIO, rWaitTime, wWaitTime, tWaitTime);
}
- if (UniqueItems &&
- value.some((item, i, ar) => ar.indexOf(item) !== i)) {
- failValidation("UniqueItems", UniqueItems);
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ });
}
- }
- /**
- * Serialize the given object based on its metadata defined in the mapper
- *
- * @param mapper - The mapper which defines the metadata of the serializable object
- *
- * @param object - A valid Javascript object to be serialized
- *
- * @param objectName - Name of the serialized object
- *
- * @param options - additional options to serialization
- *
- * @returns A valid serialized Javascript object
- */
- serialize(mapper, object, objectName, options = { xml: {} }) {
- var _a, _b, _c;
- const updatedOptions = {
- xml: {
- rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
- includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
- xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
- },
- };
- let payload = {};
- const mapperType = mapper.type.name;
- if (!objectName) {
- objectName = mapper.serializedName;
- }
- if (mapperType.match(/^Sequence$/i) !== null) {
- payload = [];
- }
- if (mapper.isConstant) {
- object = mapper.defaultValue;
- }
- // This table of allowed values should help explain
- // the mapper.required and mapper.nullable properties.
- // X means "neither undefined or null are allowed".
- // || required
- // || true | false
- // nullable || ==========================
- // true || null | undefined/null
- // false || X | undefined
- // undefined || X | undefined/null
- const { required, nullable } = mapper;
- if (required && nullable && object === undefined) {
- throw new Error(`${objectName} cannot be undefined.`);
- }
- if (required && !nullable && (object === undefined || object === null)) {
- throw new Error(`${objectName} cannot be null or undefined.`);
- }
- if (!required && nullable === false && object === null) {
- throw new Error(`${objectName} cannot be null.`);
- }
- if (object === undefined || object === null) {
- payload = object;
- }
- else {
- if (mapperType.match(/^any$/i) !== null) {
- payload = object;
- }
- else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) {
- payload = serializeBasicTypes(mapperType, objectName, object);
- }
- else if (mapperType.match(/^Enum$/i) !== null) {
- const enumMapper = mapper;
- payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
- }
- else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) {
- payload = serializeDateTypes(mapperType, object, objectName);
- }
- else if (mapperType.match(/^ByteArray$/i) !== null) {
- payload = serializeByteArrayType(objectName, object);
- }
- else if (mapperType.match(/^Base64Url$/i) !== null) {
- payload = serializeBase64UrlType(objectName, object);
- }
- else if (mapperType.match(/^Sequence$/i) !== null) {
- payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
- else if (mapperType.match(/^Dictionary$/i) !== null) {
- payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
- else if (mapperType.match(/^Composite$/i) !== null) {
- payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions);
- }
+ } else {
+ result.rIO = _disk_io.rIO;
+ result.wIO = _disk_io.wIO;
+ result.tIO = _disk_io.rIO + _disk_io.wIO;
+ result.ms = _disk_io.last_ms;
+ result.rIO_sec = _disk_io.rIO_sec;
+ result.wIO_sec = _disk_io.wIO_sec;
+ result.tIO_sec = _disk_io.tIO_sec;
+ result.rWaitTime = _disk_io.rWaitTime;
+ result.wWaitTime = _disk_io.wWaitTime;
+ result.tWaitTime = _disk_io.tWaitTime;
+ result.rWaitPercent = _disk_io.rWaitPercent;
+ result.wWaitPercent = _disk_io.wWaitPercent;
+ result.tWaitPercent = _disk_io.tWaitPercent;
+ if (callback) {
+ callback(result);
}
- return payload;
+ resolve(result);
+ }
+ });
+ });
+}
+
+exports.disksIO = disksIO;
+
+function diskLayout(callback) {
+
+ function getVendorFromModel(model) {
+ const diskManufacturers = [
+ { pattern: 'WESTERN.*', manufacturer: 'Western Digital' },
+ { pattern: '^WDC.*', manufacturer: 'Western Digital' },
+ { pattern: 'WD.*', manufacturer: 'Western Digital' },
+ { pattern: 'TOSHIBA.*', manufacturer: 'Toshiba' },
+ { pattern: 'HITACHI.*', manufacturer: 'Hitachi' },
+ { pattern: '^IC.*', manufacturer: 'Hitachi' },
+ { pattern: '^HTS.*', manufacturer: 'Hitachi' },
+ { pattern: 'SANDISK.*', manufacturer: 'SanDisk' },
+ { pattern: 'KINGSTON.*', manufacturer: 'Kingston Technology' },
+ { pattern: '^SONY.*', manufacturer: 'Sony' },
+ { pattern: 'TRANSCEND.*', manufacturer: 'Transcend' },
+ { pattern: 'SAMSUNG.*', manufacturer: 'Samsung' },
+ { pattern: '^ST(?!I\\ ).*', manufacturer: 'Seagate' },
+ { pattern: '^STI\\ .*', manufacturer: 'SimpleTech' },
+ { pattern: '^D...-.*', manufacturer: 'IBM' },
+ { pattern: '^IBM.*', manufacturer: 'IBM' },
+ { pattern: '^FUJITSU.*', manufacturer: 'Fujitsu' },
+ { pattern: '^MP.*', manufacturer: 'Fujitsu' },
+ { pattern: '^MK.*', manufacturer: 'Toshiba' },
+ { pattern: 'MAXTO.*', manufacturer: 'Maxtor' },
+ { pattern: 'PIONEER.*', manufacturer: 'Pioneer' },
+ { pattern: 'PHILIPS.*', manufacturer: 'Philips' },
+ { pattern: 'QUANTUM.*', manufacturer: 'Quantum Technology' },
+ { pattern: 'FIREBALL.*', manufacturer: 'Quantum Technology' },
+ { pattern: '^VBOX.*', manufacturer: 'VirtualBox' },
+ { pattern: 'CORSAIR.*', manufacturer: 'Corsair Components' },
+ { pattern: 'CRUCIAL.*', manufacturer: 'Crucial' },
+ { pattern: 'ECM.*', manufacturer: 'ECM' },
+ { pattern: 'INTEL.*', manufacturer: 'INTEL' },
+ { pattern: 'EVO.*', manufacturer: 'Samsung' },
+ { pattern: 'APPLE.*', manufacturer: 'Apple' },
+ ];
+
+ let result = '';
+ if (model) {
+ model = model.toUpperCase();
+ diskManufacturers.forEach((manufacturer) => {
+ const re = RegExp(manufacturer.pattern);
+ if (re.test(model)) { result = manufacturer.manufacturer; }
+ });
}
- /**
- * Deserialize the given object based on its metadata defined in the mapper
- *
- * @param mapper - The mapper which defines the metadata of the serializable object
- *
- * @param responseBody - A valid Javascript entity to be deserialized
- *
- * @param objectName - Name of the deserialized object
- *
- * @param options - Controls behavior of XML parser and builder.
- *
- * @returns A valid deserialized Javascript object
- */
- deserialize(mapper, responseBody, objectName, options = { xml: {} }) {
- var _a, _b, _c, _d;
- const updatedOptions = {
- xml: {
- rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "",
- includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false,
- xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : interfaces_js_1.XML_CHARKEY,
- },
- ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false,
- };
- if (responseBody === undefined || responseBody === null) {
- if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
- // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
- // between the list being empty versus being missing,
- // so let's do the more user-friendly thing and return an empty list.
- responseBody = [];
- }
- // specifically check for undefined as default value can be a falsey value `0, "", false, null`
- if (mapper.defaultValue !== undefined) {
- responseBody = mapper.defaultValue;
- }
- return responseBody;
- }
- let payload;
- const mapperType = mapper.type.name;
- if (!objectName) {
- objectName = mapper.serializedName;
+ return result;
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+
+ const commitResult = res => {
+ for (let i = 0; i < res.length; i++) {
+ delete res[i].BSDName;
}
- if (mapperType.match(/^Composite$/i) !== null) {
- payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions);
+ if (callback) {
+ callback(res);
}
- else {
- if (this.isXML) {
- const xmlCharKey = updatedOptions.xml.xmlCharKey;
- /**
- * If the mapper specifies this as a non-composite type value but the responseBody contains
- * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties,
- * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property.
- */
- if (responseBody[interfaces_js_1.XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) {
- responseBody = responseBody[xmlCharKey];
- }
- }
- if (mapperType.match(/^Number$/i) !== null) {
- payload = parseFloat(responseBody);
- if (isNaN(payload)) {
- payload = responseBody;
+ resolve(res);
+ };
+
+ let result = [];
+ let cmd = '';
+
+ if (_linux) {
+ let cmdFullSmart = '';
+
+ exec('export LC_ALL=C; lsblk -ablJO 2>/dev/null; unset LC_ALL', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ try {
+ const out = stdout.toString().trim();
+ let devices = [];
+ try {
+ const outJSON = JSON.parse(out);
+ if (outJSON && {}.hasOwnProperty.call(outJSON, 'blockdevices')) {
+ devices = outJSON.blockdevices.filter(item => { return (item.type === 'disk') && item.size > 0 && (item.model !== null || (item.mountpoint === null && item.label === null && item.fstype === null && item.parttype === null && item.path && item.path.indexOf('/ram') !== 0 && item.path.indexOf('/loop') !== 0 && item['disc-max'] && item['disc-max'] !== 0)); });
}
- }
- else if (mapperType.match(/^Boolean$/i) !== null) {
- if (responseBody === "true") {
- payload = true;
+ } catch (e) {
+ // fallback to older version of lsblk
+ try {
+ const out2 = execSync('export LC_ALL=C; lsblk -bPo NAME,TYPE,SIZE,FSTYPE,MOUNTPOINT,UUID,ROTA,RO,RM,LABEL,MODEL,OWNER,GROUP 2>/dev/null; unset LC_ALL', util.execOptsLinux).toString();
+ let lines = blkStdoutToObject(out2).split('\n');
+ const data = parseBlk(lines);
+ devices = data.filter(item => { return (item.type === 'disk') && item.size > 0 && ((item.model !== null && item.model !== '') || (item.mount === '' && item.label === '' && item.fsType === '')); });
+ } catch (e) {
+ util.noop();
}
- else if (responseBody === "false") {
- payload = false;
+ }
+ devices.forEach((device) => {
+ let mediumType = '';
+ const BSDName = '/dev/' + device.name;
+ const logical = device.name;
+ try {
+ mediumType = execSync('cat /sys/block/' + logical + '/queue/rotational 2>/dev/null', util.execOptsLinux).toString().split('\n')[0];
+ } catch (e) {
+ util.noop();
}
- else {
- payload = responseBody;
+ let interfaceType = device.tran ? device.tran.toUpperCase().trim() : '';
+ if (interfaceType === 'NVME') {
+ mediumType = '2';
+ interfaceType = 'PCIe';
}
+ result.push({
+ device: BSDName,
+ type: (mediumType === '0' ? 'SSD' : (mediumType === '1' ? 'HD' : (mediumType === '2' ? 'NVMe' : (device.model && device.model.indexOf('SSD') > -1 ? 'SSD' : (device.model && device.model.indexOf('NVM') > -1 ? 'NVMe' : 'HD'))))),
+ name: device.model || '',
+ vendor: getVendorFromModel(device.model) || (device.vendor ? device.vendor.trim() : ''),
+ size: device.size || 0,
+ bytesPerSector: null,
+ totalCylinders: null,
+ totalHeads: null,
+ totalSectors: null,
+ totalTracks: null,
+ tracksPerCylinder: null,
+ sectorsPerTrack: null,
+ firmwareRevision: device.rev ? device.rev.trim() : '',
+ serialNum: device.serial ? device.serial.trim() : '',
+ interfaceType: interfaceType,
+ smartStatus: 'unknown',
+ temperature: null,
+ BSDName: BSDName
+ });
+ cmd += `printf "\n${BSDName}|"; smartctl -H ${BSDName} | grep overall;`;
+ cmdFullSmart += `${cmdFullSmart ? 'printf ",";' : ''}smartctl -a -j ${BSDName};`;
+ });
+ } catch (e) {
+ util.noop();
}
- else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) {
- payload = responseBody;
- }
- else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) {
- payload = new Date(responseBody);
- }
- else if (mapperType.match(/^UnixTime$/i) !== null) {
- payload = unixTimeToDate(responseBody);
- }
- else if (mapperType.match(/^ByteArray$/i) !== null) {
- payload = base64.decodeString(responseBody);
- }
- else if (mapperType.match(/^Base64Url$/i) !== null) {
- payload = base64UrlToByteArray(responseBody);
- }
- else if (mapperType.match(/^Sequence$/i) !== null) {
- payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions);
- }
- else if (mapperType.match(/^Dictionary$/i) !== null) {
- payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions);
- }
- }
- if (mapper.isConstant) {
- payload = mapper.defaultValue;
- }
- return payload;
- }
-}
-/**
- * Method that creates and returns a Serializer.
- * @param modelMappers - Known models to map
- * @param isXML - If XML should be supported
- */
-function createSerializer(modelMappers = {}, isXML = false) {
- return new SerializerImpl(modelMappers, isXML);
-}
-exports.createSerializer = createSerializer;
-function trimEnd(str, ch) {
- let len = str.length;
- while (len - 1 >= 0 && str[len - 1] === ch) {
- --len;
- }
- return str.substr(0, len);
-}
-function bufferToBase64Url(buffer) {
- if (!buffer) {
- return undefined;
- }
- if (!(buffer instanceof Uint8Array)) {
- throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`);
- }
- // Uint8Array to Base64.
- const str = base64.encodeByteArray(buffer);
- // Base64 to Base64Url.
- return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
-}
-function base64UrlToByteArray(str) {
- if (!str) {
- return undefined;
- }
- if (str && typeof str.valueOf() !== "string") {
- throw new Error("Please provide an input of type string for converting to Uint8Array");
- }
- // Base64Url to Base64.
- str = str.replace(/-/g, "+").replace(/_/g, "/");
- // Base64 to Uint8Array.
- return base64.decodeString(str);
-}
-function splitSerializeName(prop) {
- const classes = [];
- let partialclass = "";
- if (prop) {
- const subwords = prop.split(".");
- for (const item of subwords) {
- if (item.charAt(item.length - 1) === "\\") {
- partialclass += item.substr(0, item.length - 1) + ".";
+ }
+ // check S.M.A.R.T. status
+ if (cmdFullSmart) {
+ exec(cmdFullSmart, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ try {
+ const data = JSON.parse(`[${stdout}]`);
+ data.forEach(disk => {
+ const diskBSDName = disk.smartctl.argv[disk.smartctl.argv.length - 1];
+
+ for (let i = 0; i < result.length; i++) {
+ if (result[i].BSDName === diskBSDName) {
+ result[i].smartStatus = (disk.smart_status.passed ? 'Ok' : (disk.smart_status.passed === false ? 'Predicted Failure' : 'unknown'));
+ if (disk.temperature && disk.temperature.current) {
+ result[i].temperature = disk.temperature.current;
+ }
+ result[i].smartData = disk;
+ }
+ }
+ });
+ commitResult(result);
+ } catch (e) {
+ if (cmd) {
+ cmd = cmd + 'printf "\n"';
+ exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(line => {
+ if (line) {
+ let parts = line.split('|');
+ if (parts.length === 2) {
+ let BSDName = parts[0];
+ parts[1] = parts[1].trim();
+ let parts2 = parts[1].split(':');
+ if (parts2.length === 2) {
+ parts2[1] = parts2[1].trim();
+ let status = parts2[1].toLowerCase();
+ for (let i = 0; i < result.length; i++) {
+ if (result[i].BSDName === BSDName) {
+ result[i].smartStatus = (status === 'passed' ? 'Ok' : (status === 'failed!' ? 'Predicted Failure' : 'unknown'));
+ }
+ }
+ }
+ }
+ }
+ });
+ commitResult(result);
+ });
+ } else {
+ commitResult(result);
+ }
+ }
+ });
+ } else {
+ commitResult(result);
+ }
+ });
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_darwin) {
+ exec('system_profiler SPSerialATADataType SPNVMeDataType SPUSBDataType', { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ if (!error) {
+ // split by type:
+ let lines = stdout.toString().split('\n');
+ let linesSATA = [];
+ let linesNVMe = [];
+ let linesUSB = [];
+ let dataType = 'SATA';
+ lines.forEach(line => {
+ if (line === 'NVMExpress:') { dataType = 'NVMe'; }
+ else if (line === 'USB:') { dataType = 'USB'; }
+ else if (line === 'SATA/SATA Express:') { dataType = 'SATA'; }
+ else if (dataType === 'SATA') { linesSATA.push(line); }
+ else if (dataType === 'NVMe') { linesNVMe.push(line); }
+ else if (dataType === 'USB') { linesUSB.push(line); }
+ });
+ try {
+ // Serial ATA Drives
+ let devices = linesSATA.join('\n').split(' Physical Interconnect: ');
+ devices.shift();
+ devices.forEach(function (device) {
+ device = 'InterfaceType: ' + device;
+ let lines = device.split('\n');
+ const mediumType = util.getValue(lines, 'Medium Type', ':', true).trim();
+ const sizeStr = util.getValue(lines, 'capacity', ':', true).trim();
+ const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
+ if (sizeStr) {
+ let sizeValue = 0;
+ if (sizeStr.indexOf('(') >= 0) {
+ sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
+ }
+ if (!sizeValue) {
+ sizeValue = parseInt(sizeStr);
+ }
+ if (sizeValue) {
+ const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
+ result.push({
+ device: BSDName,
+ type: mediumType.startsWith('Solid') ? 'SSD' : 'HD',
+ name: util.getValue(lines, 'Model', ':', true).trim(),
+ vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()) || util.getValue(lines, 'Manufacturer', ':', true),
+ size: sizeValue,
+ bytesPerSector: null,
+ totalCylinders: null,
+ totalHeads: null,
+ totalSectors: null,
+ totalTracks: null,
+ tracksPerCylinder: null,
+ sectorsPerTrack: null,
+ firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
+ serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
+ interfaceType: util.getValue(lines, 'InterfaceType', ':', true).trim(),
+ smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
+ temperature: null,
+ BSDName: BSDName
+ });
+ cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
+ }
+ }
+ });
+ } catch (e) {
+ util.noop();
}
- else {
- partialclass += item;
- classes.push(partialclass);
- partialclass = "";
+
+ // NVME Drives
+ try {
+ let devices = linesNVMe.join('\n').split('\n\n Capacity:');
+ devices.shift();
+ devices.forEach(function (device) {
+ device = '!Capacity: ' + device;
+ let lines = device.split('\n');
+ const linkWidth = util.getValue(lines, 'link width', ':', true).trim();
+ const sizeStr = util.getValue(lines, '!capacity', ':', true).trim();
+ const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
+ if (sizeStr) {
+ let sizeValue = 0;
+ if (sizeStr.indexOf('(') >= 0) {
+ sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
+ }
+ if (!sizeValue) {
+ sizeValue = parseInt(sizeStr);
+ }
+ if (sizeValue) {
+ const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
+ result.push({
+ device: BSDName,
+ type: 'NVMe',
+ name: util.getValue(lines, 'Model', ':', true).trim(),
+ vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()),
+ size: sizeValue,
+ bytesPerSector: null,
+ totalCylinders: null,
+ totalHeads: null,
+ totalSectors: null,
+ totalTracks: null,
+ tracksPerCylinder: null,
+ sectorsPerTrack: null,
+ firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
+ serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
+ interfaceType: ('PCIe ' + linkWidth).trim(),
+ smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
+ temperature: null,
+ BSDName: BSDName
+ });
+ cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
+ }
+ }
+ });
+ } catch (e) {
+ util.noop();
}
- }
- }
- return classes;
-}
-function dateToUnixTime(d) {
- if (!d) {
- return undefined;
- }
- if (typeof d.valueOf() === "string") {
- d = new Date(d);
- }
- return Math.floor(d.getTime() / 1000);
-}
-function unixTimeToDate(n) {
- if (!n) {
- return undefined;
- }
- return new Date(n * 1000);
-}
-function serializeBasicTypes(typeName, objectName, value) {
- if (value !== null && value !== undefined) {
- if (typeName.match(/^Number$/i) !== null) {
- if (typeof value !== "number") {
- throw new Error(`${objectName} with value ${value} must be of type number.`);
+ // USB Drives
+ try {
+ let devices = linesUSB.join('\n').replaceAll('Media:\n ', 'Model:').split('\n\n Product ID:');
+ devices.shift();
+ devices.forEach(function (device) {
+ let lines = device.split('\n');
+ const sizeStr = util.getValue(lines, 'Capacity', ':', true).trim();
+ const BSDName = util.getValue(lines, 'BSD Name', ':', true).trim();
+ if (sizeStr) {
+ let sizeValue = 0;
+ if (sizeStr.indexOf('(') >= 0) {
+ sizeValue = parseInt(sizeStr.match(/\(([^)]+)\)/)[1].replace(/\./g, '').replace(/,/g, '').replace(/\s/g, ''));
+ }
+ if (!sizeValue) {
+ sizeValue = parseInt(sizeStr);
+ }
+ if (sizeValue) {
+ const smartStatusString = util.getValue(lines, 'S.M.A.R.T. status', ':', true).trim().toLowerCase();
+ result.push({
+ device: BSDName,
+ type: 'USB',
+ name: util.getValue(lines, 'Model', ':', true).trim().replaceAll(':', ''),
+ vendor: getVendorFromModel(util.getValue(lines, 'Model', ':', true).trim()),
+ size: sizeValue,
+ bytesPerSector: null,
+ totalCylinders: null,
+ totalHeads: null,
+ totalSectors: null,
+ totalTracks: null,
+ tracksPerCylinder: null,
+ sectorsPerTrack: null,
+ firmwareRevision: util.getValue(lines, 'Revision', ':', true).trim(),
+ serialNum: util.getValue(lines, 'Serial Number', ':', true).trim(),
+ interfaceType: 'USB',
+ smartStatus: smartStatusString === 'verified' ? 'OK' : smartStatusString || 'unknown',
+ temperature: null,
+ BSDName: BSDName
+ });
+ cmd = cmd + 'printf "\n' + BSDName + '|"; diskutil info /dev/' + BSDName + ' | grep SMART;';
+ }
+ }
+ });
+ } catch (e) {
+ util.noop();
}
- }
- else if (typeName.match(/^String$/i) !== null) {
- if (typeof value.valueOf() !== "string") {
- throw new Error(`${objectName} with value "${value}" must be of type string.`);
+ if (cmd) {
+ cmd = cmd + 'printf "\n"';
+ exec(cmd, { maxBuffer: 1024 * 1024 }, function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ lines.forEach(line => {
+ if (line) {
+ let parts = line.split('|');
+ if (parts.length === 2) {
+ let BSDName = parts[0];
+ parts[1] = parts[1].trim();
+ let parts2 = parts[1].split(':');
+ if (parts2.length === 2) {
+ parts2[1] = parts2[1].trim();
+ let status = parts2[1].toLowerCase();
+ for (let i = 0; i < result.length; i++) {
+ if (result[i].BSDName === BSDName) {
+ result[i].smartStatus = (status === 'not supported' ? 'not supported' : (status === 'verified' ? 'Ok' : (status === 'failing' ? 'Predicted Failure' : 'unknown')));
+ }
+ }
+ }
+ }
+ }
+ });
+ for (let i = 0; i < result.length; i++) {
+ delete result[i].BSDName;
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } else {
+ for (let i = 0; i < result.length; i++) {
+ delete result[i].BSDName;
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
}
- }
- else if (typeName.match(/^Uuid$/i) !== null) {
- if (!(typeof value.valueOf() === "string" && (0, utils_js_1.isValidUuid)(value))) {
- throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`);
+ }
+ });
+ }
+ if (_windows) {
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance Win32_DiskDrive | select Caption,Size,Status,PNPDeviceId,DeviceId,BytesPerSector,TotalCylinders,TotalHeads,TotalSectors,TotalTracks,TracksPerCylinder,SectorsPerTrack,FirmwareRevision,SerialNumber,InterfaceType | fl'));
+ workload.push(util.powerShell('Get-PhysicalDisk | select BusType,MediaType,FriendlyName,Model,SerialNumber,Size | fl'));
+ if (util.smartMonToolsInstalled()) {
+ try {
+ const smartDev = JSON.parse(execSync('smartctl --scan -j').toString());
+ if (smartDev && smartDev.devices && smartDev.devices.length > 0) {
+ smartDev.devices.forEach((dev) => {
+ workload.push(execPromiseSave(`smartctl -j -a ${dev.name}`, util.execOptsWin));
+ });
+ }
+ } catch (e) {
+ util.noop();
}
- }
- else if (typeName.match(/^Boolean$/i) !== null) {
- if (typeof value !== "boolean") {
- throw new Error(`${objectName} with value ${value} must be of type boolean.`);
+ }
+ util.promiseAll(
+ workload
+ ).then((data) => {
+ let devices = data.results[0].toString().split(/\n\s*\n/);
+ devices.forEach(function (device) {
+ let lines = device.split('\r\n');
+ const size = util.getValue(lines, 'Size', ':').trim();
+ const status = util.getValue(lines, 'Status', ':').trim().toLowerCase();
+ if (size) {
+ result.push({
+ device: util.getValue(lines, 'DeviceId', ':'), // changed from PNPDeviceId to DeviceID (be be able to match devices)
+ type: device.indexOf('SSD') > -1 ? 'SSD' : 'HD', // just a starting point ... better: MSFT_PhysicalDisk - Media Type ... see below
+ name: util.getValue(lines, 'Caption', ':'),
+ vendor: getVendorFromModel(util.getValue(lines, 'Caption', ':', true).trim()),
+ size: parseInt(size),
+ bytesPerSector: parseInt(util.getValue(lines, 'BytesPerSector', ':')),
+ totalCylinders: parseInt(util.getValue(lines, 'TotalCylinders', ':')),
+ totalHeads: parseInt(util.getValue(lines, 'TotalHeads', ':')),
+ totalSectors: parseInt(util.getValue(lines, 'TotalSectors', ':')),
+ totalTracks: parseInt(util.getValue(lines, 'TotalTracks', ':')),
+ tracksPerCylinder: parseInt(util.getValue(lines, 'TracksPerCylinder', ':')),
+ sectorsPerTrack: parseInt(util.getValue(lines, 'SectorsPerTrack', ':')),
+ firmwareRevision: util.getValue(lines, 'FirmwareRevision', ':').trim(),
+ serialNum: util.getValue(lines, 'SerialNumber', ':').trim(),
+ interfaceType: util.getValue(lines, 'InterfaceType', ':').trim(),
+ smartStatus: (status === 'ok' ? 'Ok' : (status === 'degraded' ? 'Degraded' : (status === 'pred fail' ? 'Predicted Failure' : 'Unknown'))),
+ temperature: null,
+ });
+ }
+ });
+ devices = data.results[1].split(/\n\s*\n/);
+ devices.forEach(function (device) {
+ let lines = device.split('\r\n');
+ const serialNum = util.getValue(lines, 'SerialNumber', ':').trim();
+ const name = util.getValue(lines, 'FriendlyName', ':').trim().replace('Msft ', 'Microsoft');
+ const size = util.getValue(lines, 'Size', ':').trim();
+ const model = util.getValue(lines, 'Model', ':').trim();
+ const interfaceType = util.getValue(lines, 'BusType', ':').trim();
+ let mediaType = util.getValue(lines, 'MediaType', ':').trim();
+ if (mediaType === '3' || mediaType === 'HDD') { mediaType = 'HD'; }
+ if (mediaType === '4') { mediaType = 'SSD'; }
+ if (mediaType === '5') { mediaType = 'SCM'; }
+ if (mediaType === 'Unspecified' && (model.toLowerCase().indexOf('virtual') > -1 || model.toLowerCase().indexOf('vbox') > -1)) { mediaType = 'Virtual'; }
+ if (size) {
+ let i = util.findObjectByKey(result, 'serialNum', serialNum);
+ if (i === -1 || serialNum === '') {
+ i = util.findObjectByKey(result, 'name', name);
+ }
+ if (i != -1) {
+ result[i].type = mediaType;
+ result[i].interfaceType = interfaceType;
+ }
+ }
+ });
+ // S.M.A.R.T
+ data.results.shift();
+ data.results.shift();
+ if (data.results.length) {
+ data.results.forEach((smartStr) => {
+ try {
+ const smartData = JSON.parse(smartStr);
+ if (smartData.serial_number) {
+ const serialNum = smartData.serial_number;
+ let i = util.findObjectByKey(result, 'serialNum', serialNum);
+ if (i != -1) {
+ result[i].smartStatus = (smartData.smart_status && smartData.smart_status.passed ? 'Ok' : (smartData.smart_status && smartData.smart_status.passed === false ? 'Predicted Failure' : 'unknown'));
+ if (smartData.temperature && smartData.temperature.current) {
+ result[i].temperature = smartData.temperature.current;
+ }
+ result[i].smartData = smartData;
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
+ });
}
- }
- else if (typeName.match(/^Stream$/i) !== null) {
- const objectType = typeof value;
- if (objectType !== "string" &&
- typeof value.pipe !== "function" && // NodeJS.ReadableStream
- typeof value.tee !== "function" && // browser ReadableStream
- !(value instanceof ArrayBuffer) &&
- !ArrayBuffer.isView(value) &&
- // File objects count as a type of Blob, so we want to use instanceof explicitly
- !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) &&
- objectType !== "function") {
- throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`);
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- }
- return value;
+ }
+ });
+ });
}
-function serializeEnumType(objectName, allowedValues, value) {
- if (!allowedValues) {
- throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);
- }
- const isPresent = allowedValues.some((item) => {
- if (typeof item.valueOf() === "string") {
- return item.toLowerCase() === value.toLowerCase();
- }
- return item === value;
+
+exports.diskLayout = diskLayout;
+
+
+/***/ }),
+
+/***/ 64293:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+
+
+// @ts-check
+// ==================================================================================
+// graphics.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 7. Graphics (controller, display)
+// ----------------------------------------------------------------------------------
+
+const fs = __nccwpck_require__(79896);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const util = __nccwpck_require__(77496);
+
+let _platform = process.platform;
+let _nvidiaSmiPath = '';
+
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+
+let _resolutionX = 0;
+let _resolutionY = 0;
+let _pixelDepth = 0;
+let _refreshRate = 0;
+
+const videoTypes = {
+ '-2': 'UNINITIALIZED',
+ '-1': 'OTHER',
+ '0': 'HD15',
+ '1': 'SVIDEO',
+ '2': 'Composite video',
+ '3': 'Component video',
+ '4': 'DVI',
+ '5': 'HDMI',
+ '6': 'LVDS',
+ '8': 'D_JPN',
+ '9': 'SDI',
+ '10': 'DP',
+ '11': 'DP embedded',
+ '12': 'UDI',
+ '13': 'UDI embedded',
+ '14': 'SDTVDONGLE',
+ '15': 'MIRACAST',
+ '2147483648': 'INTERNAL'
+};
+
+function getVendorFromModel(model) {
+ const manufacturers = [
+ { pattern: '^LG.+', manufacturer: 'LG' },
+ { pattern: '^BENQ.+', manufacturer: 'BenQ' },
+ { pattern: '^ASUS.+', manufacturer: 'Asus' },
+ { pattern: '^DELL.+', manufacturer: 'Dell' },
+ { pattern: '^SAMSUNG.+', manufacturer: 'Samsung' },
+ { pattern: '^VIEWSON.+', manufacturer: 'ViewSonic' },
+ { pattern: '^SONY.+', manufacturer: 'Sony' },
+ { pattern: '^ACER.+', manufacturer: 'Acer' },
+ { pattern: '^AOC.+', manufacturer: 'AOC Monitors' },
+ { pattern: '^HP.+', manufacturer: 'HP' },
+ { pattern: '^EIZO.?', manufacturer: 'Eizo' },
+ { pattern: '^PHILIPS.?', manufacturer: 'Philips' },
+ { pattern: '^IIYAMA.?', manufacturer: 'Iiyama' },
+ { pattern: '^SHARP.?', manufacturer: 'Sharp' },
+ { pattern: '^NEC.?', manufacturer: 'NEC' },
+ { pattern: '^LENOVO.?', manufacturer: 'Lenovo' },
+ { pattern: 'COMPAQ.?', manufacturer: 'Compaq' },
+ { pattern: 'APPLE.?', manufacturer: 'Apple' },
+ { pattern: 'INTEL.?', manufacturer: 'Intel' },
+ { pattern: 'AMD.?', manufacturer: 'AMD' },
+ { pattern: 'NVIDIA.?', manufacturer: 'NVDIA' },
+ ];
+
+ let result = '';
+ if (model) {
+ model = model.toUpperCase();
+ manufacturers.forEach((manufacturer) => {
+ const re = RegExp(manufacturer.pattern);
+ if (re.test(model)) { result = manufacturer.manufacturer; }
});
- if (!isPresent) {
- throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`);
- }
- return value;
+ }
+ return result;
}
-function serializeByteArrayType(objectName, value) {
- if (value !== undefined && value !== null) {
- if (!(value instanceof Uint8Array)) {
- throw new Error(`${objectName} must be of type Uint8Array.`);
- }
- value = base64.encodeByteArray(value);
- }
- return value;
+
+function getVendorFromId(id) {
+ const vendors = {
+ '610': 'Apple',
+ '1e6d': 'LG',
+ '10ac': 'DELL',
+ '4dd9': 'Sony',
+ '38a3': 'NEC',
+ };
+ return vendors[id] || '';
}
-function serializeBase64UrlType(objectName, value) {
- if (value !== undefined && value !== null) {
- if (!(value instanceof Uint8Array)) {
- throw new Error(`${objectName} must be of type Uint8Array.`);
- }
- value = bufferToBase64Url(value);
- }
- return value;
+
+function vendorToId(str) {
+ let result = '';
+ str = (str || '').toLowerCase();
+ if (str.indexOf('apple') >= 0) { result = '0x05ac'; }
+ else if (str.indexOf('nvidia') >= 0) { result = '0x10de'; }
+ else if (str.indexOf('intel') >= 0) { result = '0x8086'; }
+ else if (str.indexOf('ati') >= 0 || str.indexOf('amd') >= 0) { result = '0x1002'; }
+
+ return result;
}
-function serializeDateTypes(typeName, value, objectName) {
- if (value !== undefined && value !== null) {
- if (typeName.match(/^Date$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
- }
- value =
- value instanceof Date
- ? value.toISOString().substring(0, 10)
- : new Date(value).toISOString().substring(0, 10);
- }
- else if (typeName.match(/^DateTime$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`);
- }
- value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
- }
- else if (typeName.match(/^DateTimeRfc1123$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`);
- }
- value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
- }
- else if (typeName.match(/^UnixTime$/i) !== null) {
- if (!(value instanceof Date ||
- (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
- throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` +
- `for it to be serialized in UnixTime/Epoch format.`);
- }
- value = dateToUnixTime(value);
- }
- else if (typeName.match(/^TimeSpan$/i) !== null) {
- if (!(0, utils_js_1.isDuration)(value)) {
- throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`);
- }
- }
- }
- return value;
+
+function getMetalVersion(id) {
+ const families = {
+ 'spdisplays_mtlgpufamilymac1': 'mac1',
+ 'spdisplays_mtlgpufamilymac2': 'mac2',
+ 'spdisplays_mtlgpufamilyapple1': 'apple1',
+ 'spdisplays_mtlgpufamilyapple2': 'apple2',
+ 'spdisplays_mtlgpufamilyapple3': 'apple3',
+ 'spdisplays_mtlgpufamilyapple4': 'apple4',
+ 'spdisplays_mtlgpufamilyapple5': 'apple5',
+ 'spdisplays_mtlgpufamilyapple6': 'apple6',
+ 'spdisplays_mtlgpufamilyapple7': 'apple7',
+ 'spdisplays_metalfeaturesetfamily11': 'family1_v1',
+ 'spdisplays_metalfeaturesetfamily12': 'family1_v2',
+ 'spdisplays_metalfeaturesetfamily13': 'family1_v3',
+ 'spdisplays_metalfeaturesetfamily14': 'family1_v4',
+ 'spdisplays_metalfeaturesetfamily21': 'family2_v1'
+ };
+ return families[id] || '';
}
-function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) {
- var _a;
- if (!Array.isArray(object)) {
- throw new Error(`${objectName} must be of type Array.`);
- }
- let elementType = mapper.type.element;
- if (!elementType || typeof elementType !== "object") {
- throw new Error(`element" metadata for an Array must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}.`);
- }
- // Quirk: Composite mappers referenced by `element` might
- // not have *all* properties declared (like uberParent),
- // so let's try to look up the full definition by name.
- if (elementType.type.name === "Composite" && elementType.type.className) {
- elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType;
- }
- const tempArray = [];
- for (let i = 0; i < object.length; i++) {
- const serializedValue = serializer.serialize(elementType, object[i], objectName, options);
- if (isXml && elementType.xmlNamespace) {
- const xmlnsKey = elementType.xmlNamespacePrefix
- ? `xmlns:${elementType.xmlNamespacePrefix}`
- : "xmlns";
- if (elementType.type.name === "Composite") {
- tempArray[i] = Object.assign({}, serializedValue);
- tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
- }
- else {
- tempArray[i] = {};
- tempArray[i][options.xml.xmlCharKey] = serializedValue;
- tempArray[i][interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace };
- }
- }
- else {
- tempArray[i] = serializedValue;
+
+function graphics(callback) {
+
+ function parseLinesDarwin(graphicsArr) {
+ const res = {
+ controllers: [],
+ displays: []
+ };
+ try {
+ graphicsArr.forEach(function (item) {
+ // controllers
+ const bus = ((item.sppci_bus || '').indexOf('builtin') > -1 ? 'Built-In' : ((item.sppci_bus || '').indexOf('pcie') > -1 ? 'PCIe' : ''));
+ const vram = (parseInt((item.spdisplays_vram || ''), 10) || 0) * (((item.spdisplays_vram || '').indexOf('GB') > -1) ? 1024 : 1);
+ const vramDyn = (parseInt((item.spdisplays_vram_shared || ''), 10) || 0) * (((item.spdisplays_vram_shared || '').indexOf('GB') > -1) ? 1024 : 1);
+ let metalVersion = getMetalVersion(item.spdisplays_metal || item.spdisplays_metalfamily || '');
+ res.controllers.push({
+ vendor: getVendorFromModel(item.spdisplays_vendor || '') || item.spdisplays_vendor || '',
+ model: item.sppci_model || '',
+ bus,
+ vramDynamic: bus === 'Built-In',
+ vram: vram || vramDyn || null,
+ deviceId: item['spdisplays_device-id'] || '',
+ vendorId: item['spdisplays_vendor-id'] || vendorToId((item['spdisplays_vendor'] || '') + (item.sppci_model || '')),
+ external: (item.sppci_device_type === 'spdisplays_egpu'),
+ cores: item['sppci_cores'] || null,
+ metalVersion
+ });
+
+ // displays
+ if (item.spdisplays_ndrvs && item.spdisplays_ndrvs.length) {
+ item.spdisplays_ndrvs.forEach(function (displayItem) {
+ const connectionType = displayItem['spdisplays_connection_type'] || '';
+ const currentResolutionParts = (displayItem['_spdisplays_resolution'] || '').split('@');
+ const currentResolution = currentResolutionParts[0].split('x');
+ const pixelParts = (displayItem['_spdisplays_pixels'] || '').split('x');
+ const pixelDepthString = displayItem['spdisplays_depth'] || '';
+ const serial = displayItem['_spdisplays_display-serial-number'] || displayItem['_spdisplays_display-serial-number2'] || null;
+ res.displays.push({
+ vendor: getVendorFromId(displayItem['_spdisplays_display-vendor-id'] || '') || getVendorFromModel(displayItem['_name'] || ''),
+ vendorId: displayItem['_spdisplays_display-vendor-id'] || '',
+ model: displayItem['_name'] || '',
+ productionYear: displayItem['_spdisplays_display-year'] || null,
+ serial: serial !== '0' ? serial : null,
+ displayId: displayItem['_spdisplays_displayID'] || null,
+ main: displayItem['spdisplays_main'] ? displayItem['spdisplays_main'] === 'spdisplays_yes' : false,
+ builtin: (displayItem['spdisplays_display_type'] || '').indexOf('built-in') > -1,
+ connection: ((connectionType.indexOf('_internal') > -1) ? 'Internal' : ((connectionType.indexOf('_displayport') > -1) ? 'Display Port' : ((connectionType.indexOf('_hdmi') > -1) ? 'HDMI' : null))),
+ sizeX: null,
+ sizeY: null,
+ pixelDepth: (pixelDepthString === 'CGSThirtyBitColor' ? 30 : (pixelDepthString === 'CGSThirtytwoBitColor' ? 32 : (pixelDepthString === 'CGSTwentyfourBitColor' ? 24 : null))),
+ resolutionX: pixelParts.length > 1 ? parseInt(pixelParts[0], 10) : null,
+ resolutionY: pixelParts.length > 1 ? parseInt(pixelParts[1], 10) : null,
+ currentResX: currentResolution.length > 1 ? parseInt(currentResolution[0], 10) : null,
+ currentResY: currentResolution.length > 1 ? parseInt(currentResolution[1], 10) : null,
+ positionX: 0,
+ positionY: 0,
+ currentRefreshRate: currentResolutionParts.length > 1 ? parseInt(currentResolutionParts[1], 10) : null,
+
+ });
+ });
}
+ });
+ return res;
+ } catch (e) {
+ return res;
}
- return tempArray;
-}
-function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) {
- if (typeof object !== "object") {
- throw new Error(`${objectName} must be of type object.`);
- }
- const valueType = mapper.type.value;
- if (!valueType || typeof valueType !== "object") {
- throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}.`);
- }
- const tempDictionary = {};
- for (const key of Object.keys(object)) {
- const serializedValue = serializer.serialize(valueType, object[key], objectName, options);
- // If the element needs an XML namespace we need to add it within the $ property
- tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options);
- }
- // Add the namespace to the root element if needed
- if (isXml && mapper.xmlNamespace) {
- const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns";
- const result = tempDictionary;
- result[interfaces_js_1.XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace };
- return result;
- }
- return tempDictionary;
-}
-/**
- * Resolves the additionalProperties property from a referenced mapper
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- * @param objectName - name of the object being serialized
- */
-function resolveAdditionalProperties(serializer, mapper, objectName) {
- const additionalProperties = mapper.type.additionalProperties;
- if (!additionalProperties && mapper.type.className) {
- const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
- return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties;
- }
- return additionalProperties;
-}
-/**
- * Finds the mapper referenced by className
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- * @param objectName - name of the object being serialized
- */
-function resolveReferencedMapper(serializer, mapper, objectName) {
- const className = mapper.type.className;
- if (!className) {
- throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`);
+ }
+
+ function parseLinesLinuxControllers(lines) {
+ let controllers = [];
+ let currentController = {
+ vendor: '',
+ subVendor: '',
+ model: '',
+ bus: '',
+ busAddress: '',
+ vram: null,
+ vramDynamic: false,
+ pciID: ''
+ };
+ let isGraphicsController = false;
+ // PCI bus IDs
+ let pciIDs = [];
+ try {
+ pciIDs = execSync('export LC_ALL=C; dmidecode -t 9 2>/dev/null; unset LC_ALL | grep "Bus Address: "', util.execOptsLinux).toString().split('\n');
+ for (let i = 0; i < pciIDs.length; i++) {
+ pciIDs[i] = pciIDs[i].replace('Bus Address:', '').replace('0000:', '').trim();
+ }
+ pciIDs = pciIDs.filter(function (el) {
+ return el != null && el;
+ });
+ } catch (e) {
+ util.noop();
}
- return serializer.modelMappers[className];
-}
-/**
- * Resolves a composite mapper's modelProperties.
- * @param serializer - the serializer containing the entire set of mappers
- * @param mapper - the composite mapper to resolve
- */
-function resolveModelProperties(serializer, mapper, objectName) {
- let modelProps = mapper.type.modelProperties;
- if (!modelProps) {
- const modelMapper = resolveReferencedMapper(serializer, mapper, objectName);
- if (!modelMapper) {
- throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`);
- }
- modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties;
- if (!modelProps) {
- throw new Error(`modelProperties cannot be null or undefined in the ` +
- `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`);
+ let i = 1;
+ lines.forEach((line) => {
+ let subsystem = '';
+ if (i < lines.length && lines[i]) { // get next line;
+ subsystem = lines[i];
+ if (subsystem.indexOf(':') > 0) {
+ subsystem = subsystem.split(':')[1];
}
- }
- return modelProps;
-}
-function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) {
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
- mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
- }
- if (object !== undefined && object !== null) {
- const payload = {};
- const modelProps = resolveModelProperties(serializer, mapper, objectName);
- for (const key of Object.keys(modelProps)) {
- const propertyMapper = modelProps[key];
- if (propertyMapper.readOnly) {
- continue;
+ }
+ if ('' !== line.trim()) {
+ if (' ' !== line[0] && '\t' !== line[0]) { // first line of new entry
+ let isExternal = (pciIDs.indexOf(line.split(' ')[0]) >= 0);
+ let vgapos = line.toLowerCase().indexOf(' vga ');
+ let _3dcontrollerpos = line.toLowerCase().indexOf('3d controller');
+ if (vgapos !== -1 || _3dcontrollerpos !== -1) { // VGA
+ if (_3dcontrollerpos !== -1 && vgapos === -1) {
+ vgapos = _3dcontrollerpos;
}
- let propName;
- let parentObject = payload;
- if (serializer.isXML) {
- if (propertyMapper.xmlIsWrapped) {
- propName = propertyMapper.xmlName;
- }
- else {
- propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
- }
+ if (currentController.vendor || currentController.model || currentController.bus || currentController.vram !== null || currentController.vramDynamic) { // already a controller found
+ controllers.push(currentController);
+ currentController = {
+ vendor: '',
+ model: '',
+ bus: '',
+ busAddress: '',
+ vram: null,
+ vramDynamic: false,
+ };
}
- else {
- const paths = splitSerializeName(propertyMapper.serializedName);
- propName = paths.pop();
- for (const pathName of paths) {
- const childObject = parentObject[pathName];
- if ((childObject === undefined || childObject === null) &&
- ((object[key] !== undefined && object[key] !== null) ||
- propertyMapper.defaultValue !== undefined)) {
- parentObject[pathName] = {};
- }
- parentObject = parentObject[pathName];
- }
+
+ const pciIDCandidate = line.split(' ')[0];
+ if (/[\da-fA-F]{2}:[\da-fA-F]{2}\.[\da-fA-F]/.test(pciIDCandidate)) {
+ currentController.busAddress = pciIDCandidate;
}
- if (parentObject !== undefined && parentObject !== null) {
- if (isXml && mapper.xmlNamespace) {
- const xmlnsKey = mapper.xmlNamespacePrefix
- ? `xmlns:${mapper.xmlNamespacePrefix}`
- : "xmlns";
- parentObject[interfaces_js_1.XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[interfaces_js_1.XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace });
+ isGraphicsController = true;
+ let endpos = line.search(/\[[0-9a-f]{4}:[0-9a-f]{4}]|$/);
+ let parts = line.substr(vgapos, endpos - vgapos).split(':');
+ currentController.busAddress = line.substr(0, vgapos).trim();
+ if (parts.length > 1) {
+ parts[1] = parts[1].trim();
+ if (parts[1].toLowerCase().indexOf('corporation') >= 0) {
+ currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf('corporation') + 11).trim();
+ currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf('corporation') + 11, 200).split('(')[0].trim();
+ currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard';
+ currentController.vram = null;
+ currentController.vramDynamic = false;
+ } else if (parts[1].toLowerCase().indexOf(' inc.') >= 0) {
+ if ((parts[1].match(/]/g) || []).length > 1) {
+ currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim();
+ currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim();
+ } else {
+ currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' inc.') + 5).trim();
+ currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' inc.') + 5, 200).trim().split('(')[0].trim();
}
- const propertyObjectName = propertyMapper.serializedName !== ""
- ? objectName + "." + propertyMapper.serializedName
- : objectName;
- let toSerialize = object[key];
- const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
- if (polymorphicDiscriminator &&
- polymorphicDiscriminator.clientName === key &&
- (toSerialize === undefined || toSerialize === null)) {
- toSerialize = mapper.serializedName;
+ currentController.bus = (pciIDs.length > 0 && isExternal) ? 'PCIe' : 'Onboard';
+ currentController.vram = null;
+ currentController.vramDynamic = false;
+ } else if (parts[1].toLowerCase().indexOf(' ltd.') >= 0) {
+ if ((parts[1].match(/]/g) || []).length > 1) {
+ currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(']') + 1).trim();
+ currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(']') + 1, 200).trim().split('(')[0].trim();
+ } else {
+ currentController.vendor = parts[1].substr(0, parts[1].toLowerCase().indexOf(' ltd.') + 5).trim();
+ currentController.model = parts[1].substr(parts[1].toLowerCase().indexOf(' ltd.') + 5, 200).trim().split('(')[0].trim();
}
- const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options);
- if (serializedValue !== undefined && propName !== undefined && propName !== null) {
- const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options);
- if (isXml && propertyMapper.xmlIsAttribute) {
- // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js.
- // This keeps things simple while preventing name collision
- // with names in user documents.
- parentObject[interfaces_js_1.XML_ATTRKEY] = parentObject[interfaces_js_1.XML_ATTRKEY] || {};
- parentObject[interfaces_js_1.XML_ATTRKEY][propName] = serializedValue;
- }
- else if (isXml && propertyMapper.xmlIsWrapped) {
- parentObject[propName] = { [propertyMapper.xmlElementName]: value };
- }
- else {
- parentObject[propName] = value;
- }
+ }
+ if (currentController.model && subsystem.indexOf(currentController.model) !== -1) {
+ const subVendor = subsystem.split(currentController.model)[0].trim();
+ if (subVendor) {
+ currentController.subVendor = subVendor;
}
+ }
}
+
+ } else {
+ isGraphicsController = false;
+ }
}
- const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName);
- if (additionalPropertiesMapper) {
- const propNames = Object.keys(modelProps);
- for (const clientPropName in object) {
- const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName);
- if (isAdditionalProperty) {
- payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options);
- }
+ if (isGraphicsController) { // within VGA details
+ let parts = line.split(':');
+ if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('devicename') !== -1 && parts[1].toLowerCase().indexOf('onboard') !== -1) { currentController.bus = 'Onboard'; }
+ if (parts.length > 1 && parts[0].replace(/ +/g, '').toLowerCase().indexOf('region') !== -1 && parts[1].toLowerCase().indexOf('memory') !== -1) {
+ let memparts = parts[1].split('=');
+ if (memparts.length > 1) {
+ currentController.vram = parseInt(memparts[1]);
}
+ }
}
- return payload;
- }
- return object;
-}
-function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) {
- if (!isXml || !propertyMapper.xmlNamespace) {
- return serializedValue;
+ }
+ i++;
+ });
+
+ if (currentController.vendor || currentController.model || currentController.bus || currentController.busAddress || currentController.vram !== null || currentController.vramDynamic) { // already a controller found
+ controllers.push(currentController);
}
- const xmlnsKey = propertyMapper.xmlNamespacePrefix
- ? `xmlns:${propertyMapper.xmlNamespacePrefix}`
- : "xmlns";
- const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace };
- if (["Composite"].includes(propertyMapper.type.name)) {
- if (serializedValue[interfaces_js_1.XML_ATTRKEY]) {
- return serializedValue;
+ return (controllers);
+ }
+
+ function parseLinesLinuxClinfo(controllers, lines) {
+ const fieldPattern = /\[([^\]]+)\]\s+(\w+)\s+(.*)/;
+ const devices = lines.reduce((devices, line) => {
+ const field = fieldPattern.exec(line.trim());
+ if (field) {
+ if (!devices[field[1]]) {
+ devices[field[1]] = {};
}
- else {
- const result = Object.assign({}, serializedValue);
- result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
- return result;
+ devices[field[1]][field[2]] = field[3];
+ }
+ return devices;
+ }, {});
+ for (let deviceId in devices) {
+ const device = devices[deviceId];
+ if (device['CL_DEVICE_TYPE'] === 'CL_DEVICE_TYPE_GPU') {
+ let busAddress;
+ if (device['CL_DEVICE_TOPOLOGY_AMD']) {
+ const bdf = device['CL_DEVICE_TOPOLOGY_AMD'].match(/[a-zA-Z0-9]+:\d+\.\d+/);
+ if (bdf) {
+ busAddress = bdf[0];
+ }
+ } else if (device['CL_DEVICE_PCI_BUS_ID_NV'] && device['CL_DEVICE_PCI_SLOT_ID_NV']) {
+ const bus = parseInt(device['CL_DEVICE_PCI_BUS_ID_NV']);
+ const slot = parseInt(device['CL_DEVICE_PCI_SLOT_ID_NV']);
+ if (!isNaN(bus) && !isNaN(slot)) {
+ const b = bus & 0xff;
+ const d = (slot >> 3) & 0xff;
+ const f = slot & 0x07;
+ busAddress = `${b.toString().padStart(2, '0')}:${d.toString().padStart(2, '0')}.${f}`;
+ }
+ }
+ if (busAddress) {
+ let controller = controllers.find(controller => controller.busAddress === busAddress);
+ if (!controller) {
+ controller = {
+ vendor: '',
+ model: '',
+ bus: '',
+ busAddress,
+ vram: null,
+ vramDynamic: false
+ };
+ controllers.push(controller);
+ }
+ controller.vendor = device['CL_DEVICE_VENDOR'];
+ if (device['CL_DEVICE_BOARD_NAME_AMD']) {
+ controller.model = device['CL_DEVICE_BOARD_NAME_AMD'];
+ } else {
+ controller.model = device['CL_DEVICE_NAME'];
+ }
+ const memory = parseInt(device['CL_DEVICE_GLOBAL_MEM_SIZE']);
+ if (!isNaN(memory)) {
+ controller.vram = Math.round(memory / 1024 / 1024);
+ }
}
+ }
}
- const result = {};
- result[options.xml.xmlCharKey] = serializedValue;
- result[interfaces_js_1.XML_ATTRKEY] = xmlNamespace;
- return result;
-}
-function isSpecialXmlProperty(propertyName, options) {
- return [interfaces_js_1.XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName);
-}
-function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) {
- var _a, _b;
- const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : interfaces_js_1.XML_CHARKEY;
- if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
- mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
+ return controllers;
+ }
+
+ function getNvidiaSmi() {
+ if (_nvidiaSmiPath) {
+ return _nvidiaSmiPath;
}
- const modelProps = resolveModelProperties(serializer, mapper, objectName);
- let instance = {};
- const handledPropertyNames = [];
- for (const key of Object.keys(modelProps)) {
- const propertyMapper = modelProps[key];
- const paths = splitSerializeName(modelProps[key].serializedName);
- handledPropertyNames.push(paths[0]);
- const { serializedName, xmlName, xmlElementName } = propertyMapper;
- let propertyObjectName = objectName;
- if (serializedName !== "" && serializedName !== undefined) {
- propertyObjectName = objectName + "." + serializedName;
- }
- const headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
- if (headerCollectionPrefix) {
- const dictionary = {};
- for (const headerKey of Object.keys(responseBody)) {
- if (headerKey.startsWith(headerCollectionPrefix)) {
- dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options);
- }
- handledPropertyNames.push(headerKey);
- }
- instance[key] = dictionary;
- }
- else if (serializer.isXML) {
- if (propertyMapper.xmlIsAttribute && responseBody[interfaces_js_1.XML_ATTRKEY]) {
- instance[key] = serializer.deserialize(propertyMapper, responseBody[interfaces_js_1.XML_ATTRKEY][xmlName], propertyObjectName, options);
- }
- else if (propertyMapper.xmlIsMsText) {
- if (responseBody[xmlCharKey] !== undefined) {
- instance[key] = responseBody[xmlCharKey];
- }
- else if (typeof responseBody === "string") {
- // The special case where xml parser parses "content" into JSON of
- // `{ name: "content"}` instead of `{ name: { "_": "content" }}`
- instance[key] = responseBody;
- }
- }
- else {
- const propertyName = xmlElementName || xmlName || serializedName;
- if (propertyMapper.xmlIsWrapped) {
- /* a list of wrapped by
- For the xml example below
-
- ...
- ...
-
- the responseBody has
- {
- Cors: {
- CorsRule: [{...}, {...}]
- }
- }
- xmlName is "Cors" and xmlElementName is"CorsRule".
- */
- const wrapped = responseBody[xmlName];
- const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : [];
- instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options);
- handledPropertyNames.push(xmlName);
- }
- else {
- const property = responseBody[propertyName];
- instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options);
- handledPropertyNames.push(propertyName);
- }
- }
- }
- else {
- // deserialize the property if it is present in the provided responseBody instance
- let propertyInstance;
- let res = responseBody;
- // traversing the object step by step.
- let steps = 0;
- for (const item of paths) {
- if (!res)
- break;
- steps++;
- res = res[item];
- }
- // only accept null when reaching the last position of object otherwise it would be undefined
- if (res === null && steps < paths.length) {
- res = undefined;
- }
- propertyInstance = res;
- const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
- // checking that the model property name (key)(ex: "fishtype") and the
- // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
- // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
- // is a better approach. The generator is not consistent with escaping '\.' in the
- // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
- // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
- // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
- // the transformation of model property name (ex: "fishtype") is done consistently.
- // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
- if (polymorphicDiscriminator &&
- key === polymorphicDiscriminator.clientName &&
- (propertyInstance === undefined || propertyInstance === null)) {
- propertyInstance = mapper.serializedName;
- }
- let serializedValue;
- // paging
- if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
- propertyInstance = responseBody[key];
- const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
- // Copy over any properties that have already been added into the instance, where they do
- // not exist on the newly de-serialized array
- for (const [k, v] of Object.entries(instance)) {
- if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) {
- arrayInstance[k] = v;
- }
- }
- instance = arrayInstance;
- }
- else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
- serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options);
- instance[key] = serializedValue;
- }
+
+ if (_windows) {
+ try {
+ const basePath = util.WINDIR + '\\System32\\DriverStore\\FileRepository';
+ // find all directories that have an nvidia-smi.exe file
+ const candidateDirs = fs.readdirSync(basePath).filter(dir => {
+ return fs.readdirSync([basePath, dir].join('/')).includes('nvidia-smi.exe');
+ });
+ // use the directory with the most recently created nvidia-smi.exe file
+ const targetDir = candidateDirs.reduce((prevDir, currentDir) => {
+ const previousNvidiaSmi = fs.statSync([basePath, prevDir, 'nvidia-smi.exe'].join('/'));
+ const currentNvidiaSmi = fs.statSync([basePath, currentDir, 'nvidia-smi.exe'].join('/'));
+ return (previousNvidiaSmi.ctimeMs > currentNvidiaSmi.ctimeMs) ? prevDir : currentDir;
+ });
+
+ if (targetDir) {
+ _nvidiaSmiPath = [basePath, targetDir, 'nvidia-smi.exe'].join('/');
}
+ } catch (e) {
+ util.noop();
+ }
+ } else if (_linux) {
+ _nvidiaSmiPath = 'nvidia-smi';
+ }
+ return _nvidiaSmiPath;
+ }
+
+ function nvidiaSmi(options) {
+ const nvidiaSmiExe = getNvidiaSmi();
+ options = options || util.execOptsWin;
+ if (nvidiaSmiExe) {
+ const nvidiaSmiOpts = '--query-gpu=driver_version,pci.sub_device_id,name,pci.bus_id,fan.speed,memory.total,memory.used,memory.free,utilization.gpu,utilization.memory,temperature.gpu,temperature.memory,power.draw,power.limit,clocks.gr,clocks.mem --format=csv,noheader,nounits';
+ const cmd = nvidiaSmiExe + ' ' + nvidiaSmiOpts + (_linux ? ' 2>/dev/null' : '');
+ if (_linux) {
+ options.stdio = ['pipe', 'pipe', 'ignore'];
+ }
+ try {
+ const res = execSync(cmd, options).toString();
+ return res;
+ } catch (e) {
+ util.noop();
+ }
+ }
+ return '';
+ }
+
+ function nvidiaDevices() {
+
+ function safeParseNumber(value) {
+ if ([null, undefined].includes(value)) {
+ return value;
+ }
+ return parseFloat(value);
+ }
+
+ const stdout = nvidiaSmi();
+ if (!stdout) {
+ return [];
+ }
+
+ const gpus = stdout.split('\n').filter(Boolean);
+ let results = gpus.map(gpu => {
+ const splittedData = gpu.split(', ').map(value => value.includes('N/A') ? undefined : value);
+ if (splittedData.length === 16) {
+ return {
+ driverVersion: splittedData[0],
+ subDeviceId: splittedData[1],
+ name: splittedData[2],
+ pciBus: splittedData[3],
+ fanSpeed: safeParseNumber(splittedData[4]),
+ memoryTotal: safeParseNumber(splittedData[5]),
+ memoryUsed: safeParseNumber(splittedData[6]),
+ memoryFree: safeParseNumber(splittedData[7]),
+ utilizationGpu: safeParseNumber(splittedData[8]),
+ utilizationMemory: safeParseNumber(splittedData[9]),
+ temperatureGpu: safeParseNumber(splittedData[10]),
+ temperatureMemory: safeParseNumber(splittedData[11]),
+ powerDraw: safeParseNumber(splittedData[12]),
+ powerLimit: safeParseNumber(splittedData[13]),
+ clockCore: safeParseNumber(splittedData[14]),
+ clockMemory: safeParseNumber(splittedData[15]),
+ };
+ } else {
+ return {};
+ }
+ });
+ results = results.filter((item) => {
+ return ('pciBus' in item);
+ });
+ return results;
+ }
+
+ function mergeControllerNvidia(controller, nvidia) {
+ if (nvidia.driverVersion) { controller.driverVersion = nvidia.driverVersion; }
+ if (nvidia.subDeviceId) { controller.subDeviceId = nvidia.subDeviceId; }
+ if (nvidia.name) { controller.name = nvidia.name; }
+ if (nvidia.pciBus) { controller.pciBus = nvidia.pciBus; }
+ if (nvidia.fanSpeed) { controller.fanSpeed = nvidia.fanSpeed; }
+ if (nvidia.memoryTotal) {
+ controller.memoryTotal = nvidia.memoryTotal;
+ controller.vram = nvidia.memoryTotal;
+ controller.vramDynamic = false;
+ }
+ if (nvidia.memoryUsed) { controller.memoryUsed = nvidia.memoryUsed; }
+ if (nvidia.memoryFree) { controller.memoryFree = nvidia.memoryFree; }
+ if (nvidia.utilizationGpu) { controller.utilizationGpu = nvidia.utilizationGpu; }
+ if (nvidia.utilizationMemory) { controller.utilizationMemory = nvidia.utilizationMemory; }
+ if (nvidia.temperatureGpu) { controller.temperatureGpu = nvidia.temperatureGpu; }
+ if (nvidia.temperatureMemory) { controller.temperatureMemory = nvidia.temperatureMemory; }
+ if (nvidia.powerDraw) { controller.powerDraw = nvidia.powerDraw; }
+ if (nvidia.powerLimit) { controller.powerLimit = nvidia.powerLimit; }
+ if (nvidia.clockCore) { controller.clockCore = nvidia.clockCore; }
+ if (nvidia.clockMemory) { controller.clockMemory = nvidia.clockMemory; }
+ return controller;
+ }
+
+ function parseLinesLinuxEdid(edid) {
+ // parsen EDID
+ // --> model
+ // --> resolutionx
+ // --> resolutiony
+ // --> builtin = false
+ // --> pixeldepth (?)
+ // --> sizex
+ // --> sizey
+ let result = {
+ vendor: '',
+ model: '',
+ deviceName: '',
+ main: false,
+ builtin: false,
+ connection: '',
+ sizeX: null,
+ sizeY: null,
+ pixelDepth: null,
+ resolutionX: null,
+ resolutionY: null,
+ currentResX: null,
+ currentResY: null,
+ positionX: 0,
+ positionY: 0,
+ currentRefreshRate: null
+ };
+ // find first "Detailed Timing Description"
+ let start = 108;
+ if (edid.substr(start, 6) === '000000') {
+ start += 36;
}
- const additionalPropertiesMapper = mapper.type.additionalProperties;
- if (additionalPropertiesMapper) {
- const isAdditionalProperty = (responsePropName) => {
- for (const clientPropName in modelProps) {
- const paths = splitSerializeName(modelProps[clientPropName].serializedName);
- if (paths[0] === responsePropName) {
- return false;
- }
- }
- return true;
- };
- for (const responsePropName in responseBody) {
- if (isAdditionalProperty(responsePropName)) {
- instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options);
- }
- }
+ if (edid.substr(start, 6) === '000000') {
+ start += 36;
}
- else if (responseBody && !options.ignoreUnknownProperties) {
- for (const key of Object.keys(responseBody)) {
- if (instance[key] === undefined &&
- !handledPropertyNames.includes(key) &&
- !isSpecialXmlProperty(key, options)) {
- instance[key] = responseBody[key];
- }
- }
+ if (edid.substr(start, 6) === '000000') {
+ start += 36;
}
- return instance;
-}
-function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) {
- /* jshint validthis: true */
- const value = mapper.type.value;
- if (!value || typeof value !== "object") {
- throw new Error(`"value" metadata for a Dictionary must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}`);
+ if (edid.substr(start, 6) === '000000') {
+ start += 36;
}
- if (responseBody) {
- const tempDictionary = {};
- for (const key of Object.keys(responseBody)) {
- tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options);
+ result.resolutionX = parseInt('0x0' + edid.substr(start + 8, 1) + edid.substr(start + 4, 2));
+ result.resolutionY = parseInt('0x0' + edid.substr(start + 14, 1) + edid.substr(start + 10, 2));
+ result.sizeX = parseInt('0x0' + edid.substr(start + 28, 1) + edid.substr(start + 24, 2));
+ result.sizeY = parseInt('0x0' + edid.substr(start + 29, 1) + edid.substr(start + 26, 2));
+ // monitor name
+ start = edid.indexOf('000000fc00'); // find first "Monitor Description Data"
+ if (start >= 0) {
+ let model_raw = edid.substr(start + 10, 26);
+ if (model_raw.indexOf('0a') !== -1) {
+ model_raw = model_raw.substr(0, model_raw.indexOf('0a'));
+ }
+ try {
+ if (model_raw.length > 2) {
+ result.model = model_raw.match(/.{1,2}/g).map(function (v) {
+ return String.fromCharCode(parseInt(v, 16));
+ }).join('');
}
- return tempDictionary;
- }
- return responseBody;
-}
-function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) {
- var _a;
- let element = mapper.type.element;
- if (!element || typeof element !== "object") {
- throw new Error(`element" metadata for an Array must be defined in the ` +
- `mapper and it must of type "object" in ${objectName}`);
+ } catch (e) {
+ util.noop();
+ }
+ } else {
+ result.model = '';
}
- if (responseBody) {
- if (!Array.isArray(responseBody)) {
- // xml2js will interpret a single element array as just the element, so force it to be an array
- responseBody = [responseBody];
- }
- // Quirk: Composite mappers referenced by `element` might
- // not have *all* properties declared (like uberParent),
- // so let's try to look up the full definition by name.
- if (element.type.name === "Composite" && element.type.className) {
- element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element;
+ return result;
+ }
+
+ function parseLinesLinuxDisplays(lines, depth) {
+ let displays = [];
+ let currentDisplay = {
+ vendor: '',
+ model: '',
+ deviceName: '',
+ main: false,
+ builtin: false,
+ connection: '',
+ sizeX: null,
+ sizeY: null,
+ pixelDepth: null,
+ resolutionX: null,
+ resolutionY: null,
+ currentResX: null,
+ currentResY: null,
+ positionX: 0,
+ positionY: 0,
+ currentRefreshRate: null
+ };
+ let is_edid = false;
+ let is_current = false;
+ let edid_raw = '';
+ let start = 0;
+ for (let i = 1; i < lines.length; i++) { // start with second line
+ if ('' !== lines[i].trim()) {
+ if (' ' !== lines[i][0] && '\t' !== lines[i][0] && lines[i].toLowerCase().indexOf(' connected ') !== -1) { // first line of new entry
+ if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // push last display to array
+ displays.push(currentDisplay);
+ currentDisplay = {
+ vendor: '',
+ model: '',
+ main: false,
+ builtin: false,
+ connection: '',
+ sizeX: null,
+ sizeY: null,
+ pixelDepth: null,
+ resolutionX: null,
+ resolutionY: null,
+ currentResX: null,
+ currentResY: null,
+ positionX: 0,
+ positionY: 0,
+ currentRefreshRate: null
+ };
+ }
+ let parts = lines[i].split(' ');
+ currentDisplay.connection = parts[0];
+ currentDisplay.main = lines[i].toLowerCase().indexOf(' primary ') >= 0;
+ currentDisplay.builtin = (parts[0].toLowerCase().indexOf('edp') >= 0);
}
- const tempArray = [];
- for (let i = 0; i < responseBody.length; i++) {
- tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options);
+
+ // try to read EDID information
+ if (is_edid) {
+ if (lines[i].search(/\S|$/) > start) {
+ edid_raw += lines[i].toLowerCase().trim();
+ } else {
+ // parsen EDID
+ let edid_decoded = parseLinesLinuxEdid(edid_raw);
+ currentDisplay.vendor = edid_decoded.vendor;
+ currentDisplay.model = edid_decoded.model;
+ currentDisplay.resolutionX = edid_decoded.resolutionX;
+ currentDisplay.resolutionY = edid_decoded.resolutionY;
+ currentDisplay.sizeX = edid_decoded.sizeX;
+ currentDisplay.sizeY = edid_decoded.sizeY;
+ currentDisplay.pixelDepth = depth;
+ is_edid = false;
+ }
}
- return tempArray;
- }
- return responseBody;
-}
-function getIndexDiscriminator(discriminators, discriminatorValue, typeName) {
- const typeNamesToCheck = [typeName];
- while (typeNamesToCheck.length) {
- const currentName = typeNamesToCheck.shift();
- const indexDiscriminator = discriminatorValue === currentName
- ? discriminatorValue
- : currentName + "." + discriminatorValue;
- if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) {
- return discriminators[indexDiscriminator];
+ if (lines[i].toLowerCase().indexOf('edid:') >= 0) {
+ is_edid = true;
+ start = lines[i].search(/\S|$/);
}
- else {
- for (const [name, mapper] of Object.entries(discriminators)) {
- if (name.startsWith(currentName + ".") &&
- mapper.type.uberParent === currentName &&
- mapper.type.className) {
- typeNamesToCheck.push(mapper.type.className);
- }
- }
+ if (lines[i].toLowerCase().indexOf('*current') >= 0) {
+ const parts1 = lines[i].split('(');
+ if (parts1 && parts1.length > 1 && parts1[0].indexOf('x') >= 0) {
+ const resParts = parts1[0].trim().split('x');
+ currentDisplay.currentResX = util.toInt(resParts[0]);
+ currentDisplay.currentResY = util.toInt(resParts[1]);
+ }
+ is_current = true;
}
- }
- return undefined;
-}
-function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
- var _a;
- const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
- if (polymorphicDiscriminator) {
- let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
- if (discriminatorName) {
- // The serializedName might have \\, which we just want to ignore
- if (polymorphicPropertyName === "serializedName") {
- discriminatorName = discriminatorName.replace(/\\/gi, "");
- }
- const discriminatorValue = object[discriminatorName];
- const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className;
- if (typeof discriminatorValue === "string" && typeName) {
- const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName);
- if (polymorphicMapper) {
- mapper = polymorphicMapper;
- }
- }
+ if (is_current && lines[i].toLowerCase().indexOf('clock') >= 0 && lines[i].toLowerCase().indexOf('hz') >= 0 && lines[i].toLowerCase().indexOf('v: height') >= 0) {
+ const parts1 = lines[i].split('clock');
+ if (parts1 && parts1.length > 1 && parts1[1].toLowerCase().indexOf('hz') >= 0) {
+ currentDisplay.currentRefreshRate = util.toInt(parts1[1]);
+ }
+ is_current = false;
}
+ }
}
- return mapper;
-}
-function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
- return (mapper.type.polymorphicDiscriminator ||
- getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
- getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
-}
-function getPolymorphicDiscriminatorSafely(serializer, typeName) {
- return (typeName &&
- serializer.modelMappers[typeName] &&
- serializer.modelMappers[typeName].type.polymorphicDiscriminator);
-}
-/**
- * Known types of Mappers
- */
-exports.MapperTypeNames = {
- Base64Url: "Base64Url",
- Boolean: "Boolean",
- ByteArray: "ByteArray",
- Composite: "Composite",
- Date: "Date",
- DateTime: "DateTime",
- DateTimeRfc1123: "DateTimeRfc1123",
- Dictionary: "Dictionary",
- Enum: "Enum",
- Number: "Number",
- Object: "Object",
- Sequence: "Sequence",
- String: "String",
- Stream: "Stream",
- TimeSpan: "TimeSpan",
- UnixTime: "UnixTime",
-};
-//# sourceMappingURL=serializer.js.map
-
-/***/ }),
-
-/***/ 22732:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // pushen displays
+ if (currentDisplay.model || currentDisplay.main || currentDisplay.builtin || currentDisplay.connection || currentDisplay.sizeX !== null || currentDisplay.pixelDepth !== null || currentDisplay.resolutionX !== null) { // still information there
+ displays.push(currentDisplay);
+ }
+ return displays;
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ServiceClient = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-const pipeline_js_1 = __nccwpck_require__(64524);
-const utils_js_1 = __nccwpck_require__(7805);
-const httpClientCache_js_1 = __nccwpck_require__(64663);
-const operationHelpers_js_1 = __nccwpck_require__(17036);
-const urlHelpers_js_1 = __nccwpck_require__(36580);
-const interfaceHelpers_js_1 = __nccwpck_require__(91030);
-const log_js_1 = __nccwpck_require__(75630);
-/**
- * Initializes a new instance of the ServiceClient.
- */
-class ServiceClient {
- /**
- * The ServiceClient constructor
- * @param credential - The credentials used for authentication with the service.
- * @param options - The service client options that govern the behavior of the client.
- */
- constructor(options = {}) {
- var _a, _b;
- this._requestContentType = options.requestContentType;
- this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri;
- if (options.baseUri) {
- log_js_1.logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead.");
- }
- this._allowInsecureConnection = options.allowInsecureConnection;
- this._httpClient = options.httpClient || (0, httpClientCache_js_1.getCachedDefaultHttpClient)();
- this.pipeline = options.pipeline || createDefaultPipeline(options);
- if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) {
- for (const { policy, position } of options.additionalPolicies) {
- // Sign happens after Retry and is commonly needed to occur
- // before policies that intercept post-retry.
- const afterPhase = position === "perRetry" ? "Sign" : undefined;
- this.pipeline.addPolicy(policy, {
- afterPhase,
+ // function starts here
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ controllers: [],
+ displays: []
+ };
+ if (_darwin) {
+ let cmd = 'system_profiler -xml -detailLevel full SPDisplaysDataType';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ try {
+ const output = stdout.toString();
+ result = parseLinesDarwin(util.plistParser(output)[0]._items);
+ } catch (e) {
+ util.noop();
+ }
+ try {
+ stdout = execSync('defaults read /Library/Preferences/com.apple.windowserver.plist 2>/dev/null;defaults read /Library/Preferences/com.apple.windowserver.displays.plist 2>/dev/null; echo ""', { maxBuffer: 1024 * 20000 });
+ const output = (stdout || '').toString();
+ const obj = util.plistReader(output);
+ if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets']['Configs'] && obj['DisplayAnyUserSets']['Configs'][0] && obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig']) {
+ const current = obj['DisplayAnyUserSets']['Configs'][0]['DisplayConfig'];
+ let i = 0;
+ current.forEach((o) => {
+ if (o['CurrentInfo'] && o['CurrentInfo']['OriginX'] !== undefined && result.displays && result.displays[i]) {
+ result.displays[i].positionX = o['CurrentInfo']['OriginX'];
+ }
+ if (o['CurrentInfo'] && o['CurrentInfo']['OriginY'] !== undefined && result.displays && result.displays[i]) {
+ result.displays[i].positionY = o['CurrentInfo']['OriginY'];
+ }
+ i++;
+ });
+ }
+ if (obj['DisplayAnyUserSets'] && obj['DisplayAnyUserSets'].length > 0 && obj['DisplayAnyUserSets'][0].length > 0 && obj['DisplayAnyUserSets'][0][0]['DisplayID']) {
+ const current = obj['DisplayAnyUserSets'][0];
+ let i = 0;
+ current.forEach((o) => {
+ if ('OriginX' in o && result.displays && result.displays[i]) {
+ result.displays[i].positionX = o['OriginX'];
+ }
+ if ('OriginY' in o && result.displays && result.displays[i]) {
+ result.displays[i].positionY = o['OriginY'];
+ }
+ if (o['Mode'] && o['Mode']['BitsPerPixel'] !== undefined && result.displays && result.displays[i]) {
+ result.displays[i].pixelDepth = o['Mode']['BitsPerPixel'];
+ }
+ i++;
});
+ }
+ } catch (e) {
+ util.noop();
}
- }
- }
- /**
- * Send the provided httpRequest.
- */
- async sendRequest(request) {
- return this.pipeline.sendRequest(this._httpClient, request);
- }
- /**
- * Send an HTTP request that is populated using the provided OperationSpec.
- * @typeParam T - The typed result of the request, based on the OperationSpec.
- * @param operationArguments - The arguments that the HTTP request's templated values will be populated from.
- * @param operationSpec - The OperationSpec to use to populate the httpRequest.
- */
- async sendOperationRequest(operationArguments, operationSpec) {
- const endpoint = operationSpec.baseUrl || this._endpoint;
- if (!endpoint) {
- throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use.");
- }
- // Templatized URLs sometimes reference properties on the ServiceClient child class,
- // so we have to pass `this` below in order to search these properties if they're
- // not part of OperationArguments
- const url = (0, urlHelpers_js_1.getRequestUrl)(endpoint, operationSpec, operationArguments, this);
- const request = (0, core_rest_pipeline_1.createPipelineRequest)({
- url,
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
});
- request.method = operationSpec.httpMethod;
- const operationInfo = (0, operationHelpers_js_1.getOperationRequestInfo)(request);
- operationInfo.operationSpec = operationSpec;
- operationInfo.operationArguments = operationArguments;
- const contentType = operationSpec.contentType || this._requestContentType;
- if (contentType && operationSpec.requestBody) {
- request.headers.set("Content-Type", contentType);
- }
- const options = operationArguments.options;
- if (options) {
- const requestOptions = options.requestOptions;
- if (requestOptions) {
- if (requestOptions.timeout) {
- request.timeout = requestOptions.timeout;
- }
- if (requestOptions.onUploadProgress) {
- request.onUploadProgress = requestOptions.onUploadProgress;
- }
- if (requestOptions.onDownloadProgress) {
- request.onDownloadProgress = requestOptions.onDownloadProgress;
- }
- if (requestOptions.shouldDeserialize !== undefined) {
- operationInfo.shouldDeserialize = requestOptions.shouldDeserialize;
- }
- if (requestOptions.allowInsecureConnection) {
- request.allowInsecureConnection = true;
- }
+ }
+ if (_linux) {
+ // Raspberry: https://elinux.org/RPI_vcgencmd_usage
+ if (util.isRaspberry() && util.isRaspbian()) {
+ let cmd = 'fbset -s | grep \'mode "\'; vcgencmd get_mem gpu; tvservice -s; tvservice -n;';
+ exec(cmd, function (error, stdout) {
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 3 && lines[0].indexOf('mode "') >= -1 && lines[2].indexOf('0x12000a') > -1) {
+ const parts = lines[0].replace('mode', '').replace(/"/g, '').trim().split('x');
+ if (parts.length === 2) {
+ result.displays.push({
+ vendor: '',
+ model: util.getValue(lines, 'device_name', '='),
+ main: true,
+ builtin: false,
+ connection: 'HDMI',
+ sizeX: null,
+ sizeY: null,
+ pixelDepth: null,
+ resolutionX: parseInt(parts[0], 10),
+ resolutionY: parseInt(parts[1], 10),
+ currentResX: null,
+ currentResY: null,
+ positionX: 0,
+ positionY: 0,
+ currentRefreshRate: null
+ });
+ }
}
- if (options.abortSignal) {
- request.abortSignal = options.abortSignal;
+ if (lines.length > 1 && stdout.toString().indexOf('gpu=') >= -1) {
+ result.controllers.push({
+ vendor: 'Broadcom',
+ model: util.getRpiGpu(),
+ bus: '',
+ vram: util.getValue(lines, 'gpu', '=').replace('M', ''),
+ vramDynamic: true
+ });
}
- if (options.tracingOptions) {
- request.tracingOptions = options.tracingOptions;
+ if (callback) {
+ callback(result);
}
- }
- if (this._allowInsecureConnection) {
- request.allowInsecureConnection = true;
- }
- if (request.streamResponseStatusCodes === undefined) {
- request.streamResponseStatusCodes = (0, interfaceHelpers_js_1.getStreamingResponseStatusCodes)(operationSpec);
- }
- try {
- const rawResponse = await this.sendRequest(request);
- const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[rawResponse.status]);
- if (options === null || options === void 0 ? void 0 : options.onResponse) {
- options.onResponse(rawResponse, flatResponse);
+ resolve(result);
+ });
+ } else {
+ let cmd = 'lspci -vvv 2>/dev/null';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result.controllers = parseLinesLinuxControllers(lines);
+ const nvidiaData = nvidiaDevices();
+ // needs to be rewritten ... using no spread operators
+ result.controllers = result.controllers.map((controller) => { // match by busAddress
+ return mergeControllerNvidia(controller, nvidiaData.find((contr) => contr.pciBus.toLowerCase().endsWith(controller.busAddress.toLowerCase())) || {});
+ });
}
- return flatResponse;
- }
- catch (error) {
- if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) {
- const rawResponse = error.response;
- const flatResponse = (0, utils_js_1.flattenResponse)(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]);
- error.details = flatResponse;
- if (options === null || options === void 0 ? void 0 : options.onResponse) {
- options.onResponse(rawResponse, flatResponse, error);
+ let cmd = 'clinfo --raw';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result.controllers = parseLinesLinuxClinfo(result.controllers, lines);
+ }
+ let cmd = 'xdpyinfo 2>/dev/null | grep \'depth of root window\' | awk \'{ print $5 }\'';
+ exec(cmd, function (error, stdout) {
+ let depth = 0;
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ depth = parseInt(lines[0]) || 0;
}
- }
- throw error;
+ let cmd = 'xrandr --verbose 2>/dev/null';
+ exec(cmd, function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ result.displays = parseLinesLinuxDisplays(lines, depth);
+ }
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ });
+ });
+ });
}
- }
-}
-exports.ServiceClient = ServiceClient;
-function createDefaultPipeline(options) {
- const credentialScopes = getCredentialScopes(options);
- const credentialOptions = options.credential && credentialScopes
- ? { credentialScopes, credential: options.credential }
- : undefined;
- return (0, pipeline_js_1.createClientPipeline)(Object.assign(Object.assign({}, options), { credentialOptions }));
-}
-function getCredentialScopes(options) {
- if (options.credentialScopes) {
- return options.credentialScopes;
- }
- if (options.endpoint) {
- return `${options.endpoint}/.default`;
- }
- if (options.baseUri) {
- return `${options.baseUri}/.default`;
- }
- if (options.credential && !options.credentialScopes) {
- throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`);
- }
- return undefined;
-}
-//# sourceMappingURL=serviceClient.js.map
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ if (callback) { callback(null); }
+ resolve(null);
+ }
+ if (_sunos) {
+ if (callback) { callback(null); }
+ resolve(null);
+ }
+ if (_windows) {
-/***/ }),
+ // https://blogs.technet.microsoft.com/heyscriptingguy/2013/10/03/use-powershell-to-discover-multi-monitor-information/
+ // https://devblogs.microsoft.com/scripting/use-powershell-to-discover-multi-monitor-information/
+ try {
+ const workload = [];
+ workload.push(util.powerShell('Get-CimInstance win32_VideoController | fl *'));
+ workload.push(util.powerShell('gp "HKLM:\\SYSTEM\\ControlSet001\\Control\\Class\\{4d36e968-e325-11ce-bfc1-08002be10318}\\*" -ErrorAction SilentlyContinue | where MatchingDeviceId $null -NE | select MatchingDeviceId,HardwareInformation.qwMemorySize | fl'));
+ workload.push(util.powerShell('Get-CimInstance win32_desktopmonitor | fl *'));
+ workload.push(util.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorBasicDisplayParams | fl'));
+ workload.push(util.powerShell('Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Screen]::AllScreens'));
+ workload.push(util.powerShell('Get-CimInstance -Namespace root\\wmi -ClassName WmiMonitorConnectionParams | fl'));
+ workload.push(util.powerShell('gwmi WmiMonitorID -Namespace root\\wmi | ForEach-Object {(($_.ManufacturerName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.ProductCodeID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.UserFriendlyName -notmatch 0 | foreach {[char]$_}) -join "") + "|" + (($_.SerialNumberID -notmatch 0 | foreach {[char]$_}) -join "") + "|" + $_.InstanceName}'));
-/***/ 35077:
-/***/ ((__unused_webpack_module, exports) => {
+ const nvidiaData = nvidiaDevices();
+ Promise.all(
+ workload
+ ).then((data) => {
+ // controller + vram
+ let csections = data[0].replace(/\r/g, '').split(/\n\s*\n/);
+ let vsections = data[1].replace(/\r/g, '').split(/\n\s*\n/);
+ result.controllers = parseLinesWindowsControllers(csections, vsections);
+ result.controllers = result.controllers.map((controller) => { // match by subDeviceId
+ if (controller.vendor.toLowerCase() === 'nvidia') {
+ return mergeControllerNvidia(controller, nvidiaData.find(device => {
+ let windowsSubDeviceId = (controller.subDeviceId || '').toLowerCase();
+ const nvidiaSubDeviceIdParts = device.subDeviceId.split('x');
+ let nvidiaSubDeviceId = nvidiaSubDeviceIdParts.length > 1 ? nvidiaSubDeviceIdParts[1].toLowerCase() : nvidiaSubDeviceIdParts[0].toLowerCase();
+ const lengthDifference = Math.abs(windowsSubDeviceId.length - nvidiaSubDeviceId.length);
+ if (windowsSubDeviceId.length > nvidiaSubDeviceId.length) {
+ for (let i = 0; i < lengthDifference; i++) {
+ nvidiaSubDeviceId = '0' + nvidiaSubDeviceId;
+ }
+ } else if (windowsSubDeviceId.length < nvidiaSubDeviceId.length) {
+ for (let i = 0; i < lengthDifference; i++) {
+ windowsSubDeviceId = '0' + windowsSubDeviceId;
+ }
+ }
+ return windowsSubDeviceId === nvidiaSubDeviceId;
+ }) || {});
+ } else {
+ return controller;
+ }
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.state = void 0;
-/**
- * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports.
- */
-exports.state = {
- operationRequestMap: new WeakMap(),
-};
-//# sourceMappingURL=state-cjs.cjs.map
+ // displays
+ let dsections = data[2].replace(/\r/g, '').split(/\n\s*\n/);
+ // result.displays = parseLinesWindowsDisplays(dsections);
+ if (dsections[0].trim() === '') { dsections.shift(); }
+ if (dsections.length && dsections[dsections.length - 1].trim() === '') { dsections.pop(); }
-/***/ }),
+ // monitor (powershell)
+ let msections = data[3].replace(/\r/g, '').split('Active ');
+ msections.shift();
-/***/ 36580:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // forms.screens (powershell)
+ let ssections = data[4].replace(/\r/g, '').split('BitsPerPixel ');
+ ssections.shift();
+ // connection params (powershell) - video type
+ let tsections = data[5].replace(/\r/g, '').split(/\n\s*\n/);
+ tsections.shift();
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.appendQueryParams = exports.getRequestUrl = void 0;
-const operationHelpers_js_1 = __nccwpck_require__(17036);
-const interfaceHelpers_js_1 = __nccwpck_require__(91030);
-const CollectionFormatToDelimiterMap = {
- CSV: ",",
- SSV: " ",
- Multi: "Multi",
- TSV: "\t",
- Pipes: "|",
-};
-function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) {
- const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject);
- let isAbsolutePath = false;
- let requestUrl = replaceAll(baseUri, urlReplacements);
- if (operationSpec.path) {
- let path = replaceAll(operationSpec.path, urlReplacements);
- // QUIRK: sometimes we get a path component like /{nextLink}
- // which may be a fully formed URL with a leading /. In that case, we should
- // remove the leading /
- if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) {
- path = path.substring(1);
- }
- // QUIRK: sometimes we get a path component like {nextLink}
- // which may be a fully formed URL. In that case, we should
- // ignore the baseUri.
- if (isAbsoluteUrl(path)) {
- requestUrl = path;
- isAbsolutePath = true;
- }
- else {
- requestUrl = appendPath(requestUrl, path);
- }
- }
- const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject);
- /**
- * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl`
- * is an absolute path. This ensures that existing query parameter values in `requestUrl`
- * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it
- * is still being built so there is nothing to overwrite.
- */
- requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath);
- return requestUrl;
-}
-exports.getRequestUrl = getRequestUrl;
-function replaceAll(input, replacements) {
- let result = input;
- for (const [searchValue, replaceValue] of replacements) {
- result = result.split(searchValue).join(replaceValue);
- }
- return result;
-}
-function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) {
- var _a;
- const result = new Map();
- if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) {
- for (const urlParameter of operationSpec.urlParameters) {
- let urlParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, urlParameter, fallbackObject);
- const parameterPathString = (0, interfaceHelpers_js_1.getPathStringFromParameter)(urlParameter);
- urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString);
- if (!urlParameter.skipEncoding) {
- urlParameterValue = encodeURIComponent(urlParameterValue);
- }
- result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue);
- }
- }
- return result;
-}
-function isAbsoluteUrl(url) {
- return url.includes("://");
-}
-function appendPath(url, pathToAppend) {
- if (!pathToAppend) {
- return url;
- }
- const parsedUrl = new URL(url);
- let newPath = parsedUrl.pathname;
- if (!newPath.endsWith("/")) {
- newPath = `${newPath}/`;
- }
- if (pathToAppend.startsWith("/")) {
- pathToAppend = pathToAppend.substring(1);
- }
- const searchStart = pathToAppend.indexOf("?");
- if (searchStart !== -1) {
- const path = pathToAppend.substring(0, searchStart);
- const search = pathToAppend.substring(searchStart + 1);
- newPath = newPath + path;
- if (search) {
- parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search;
- }
- }
- else {
- newPath = newPath + pathToAppend;
- }
- parsedUrl.pathname = newPath;
- return parsedUrl.toString();
-}
-function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) {
- var _a;
- const result = new Map();
- const sequenceParams = new Set();
- if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) {
- for (const queryParameter of operationSpec.queryParameters) {
- if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) {
- sequenceParams.add(queryParameter.mapper.serializedName);
- }
- let queryParameterValue = (0, operationHelpers_js_1.getOperationArgumentValueFromParameter)(operationArguments, queryParameter, fallbackObject);
- if ((queryParameterValue !== undefined && queryParameterValue !== null) ||
- queryParameter.mapper.required) {
- queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter));
- const delimiter = queryParameter.collectionFormat
- ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat]
- : "";
- if (Array.isArray(queryParameterValue)) {
- // replace null and undefined
- queryParameterValue = queryParameterValue.map((item) => {
- if (item === null || item === undefined) {
- return "";
- }
- return item;
- });
- }
- if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) {
- continue;
- }
- else if (Array.isArray(queryParameterValue) &&
- (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) {
- queryParameterValue = queryParameterValue.join(delimiter);
- }
- if (!queryParameter.skipEncoding) {
- if (Array.isArray(queryParameterValue)) {
- queryParameterValue = queryParameterValue.map((item) => {
- return encodeURIComponent(item);
- });
- }
- else {
- queryParameterValue = encodeURIComponent(queryParameterValue);
- }
+ // monitor ID (powershell) - model / vendor
+ const res = data[6].replace(/\r/g, '').split(/\n/);
+ let isections = [];
+ res.forEach(element => {
+ const parts = element.split('|');
+ if (parts.length === 5) {
+ isections.push({
+ vendor: parts[0],
+ code: parts[1],
+ model: parts[2],
+ serial: parts[3],
+ instanceId: parts[4]
+ });
+ }
+ });
+
+ result.displays = parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections);
+
+ if (result.displays.length === 1) {
+ if (_resolutionX) {
+ result.displays[0].resolutionX = _resolutionX;
+ if (!result.displays[0].currentResX) {
+ result.displays[0].currentResX = _resolutionX;
}
- // Join pipes and CSV *after* encoding, or the server will be upset.
- if (Array.isArray(queryParameterValue) &&
- (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) {
- queryParameterValue = queryParameterValue.join(delimiter);
+ }
+ if (_resolutionY) {
+ result.displays[0].resolutionY = _resolutionY;
+ if (result.displays[0].currentResY === 0) {
+ result.displays[0].currentResY = _resolutionY;
}
- result.set(queryParameter.mapper.serializedName || (0, interfaceHelpers_js_1.getPathStringFromParameter)(queryParameter), queryParameterValue);
- }
- }
- }
- return {
- queryParams: result,
- sequenceParams,
- };
-}
-function simpleParseQueryParams(queryString) {
- const result = new Map();
- if (!queryString || queryString[0] !== "?") {
- return result;
- }
- // remove the leading ?
- queryString = queryString.slice(1);
- const pairs = queryString.split("&");
- for (const pair of pairs) {
- const [name, value] = pair.split("=", 2);
- const existingValue = result.get(name);
- if (existingValue) {
- if (Array.isArray(existingValue)) {
- existingValue.push(value);
+ }
+ if (_pixelDepth) {
+ result.displays[0].pixelDepth = _pixelDepth;
+ }
}
- else {
- result.set(name, [existingValue, value]);
+ result.displays = result.displays.map(element => {
+ if (_refreshRate && !element.currentRefreshRate) {
+ element.currentRefreshRate = _refreshRate;
+ }
+ return element;
+ });
+
+ if (callback) {
+ callback(result);
}
+ resolve(result);
+ })
+ .catch(() => {
+ if (callback) {
+ callback(result);
+ }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- else {
- result.set(name, value);
+ }
+ });
+ });
+
+ function parseLinesWindowsControllers(sections, vections) {
+ const memorySizes = {};
+ for (const i in vections) {
+ if ({}.hasOwnProperty.call(vections, i)) {
+ if (vections[i].trim() !== '') {
+ const lines = vections[i].trim().split('\n');
+ const matchingDeviceId = util.getValue(lines, 'MatchingDeviceId').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i);
+ if (matchingDeviceId) {
+ const quadWordmemorySize = parseInt(util.getValue(lines, 'HardwareInformation.qwMemorySize'));
+ if (!isNaN(quadWordmemorySize)) {
+ let deviceId = matchingDeviceId[1].toUpperCase() + '&' + matchingDeviceId[2].toUpperCase();
+ if (matchingDeviceId[3]) {
+ deviceId += '&' + matchingDeviceId[3].toUpperCase();
+ }
+ if (matchingDeviceId[4]) {
+ deviceId += '&' + matchingDeviceId[4].toUpperCase();
+ }
+ memorySizes[deviceId] = quadWordmemorySize;
+ }
+ }
}
+ }
}
- return result;
-}
-/** @internal */
-function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) {
- if (queryParams.size === 0) {
- return url;
- }
- const parsedUrl = new URL(url);
- // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which
- // can change their meaning to the server, such as in the case of a SAS signature.
- // To avoid accidentally un-encoding a query param, we parse the key/values ourselves
- const combinedParams = simpleParseQueryParams(parsedUrl.search);
- for (const [name, value] of queryParams) {
- const existingValue = combinedParams.get(name);
- if (Array.isArray(existingValue)) {
- if (Array.isArray(value)) {
- existingValue.push(...value);
- const valueSet = new Set(existingValue);
- combinedParams.set(name, Array.from(valueSet));
+
+ let controllers = [];
+ for (let i in sections) {
+ if ({}.hasOwnProperty.call(sections, i)) {
+ if (sections[i].trim() !== '') {
+ let lines = sections[i].trim().split('\n');
+ let pnpDeviceId = util.getValue(lines, 'PNPDeviceID', ':').match(/PCI\\(VEN_[0-9A-F]{4})&(DEV_[0-9A-F]{4})(?:&(SUBSYS_[0-9A-F]{8}))?(?:&(REV_[0-9A-F]{2}))?/i);
+ let subDeviceId = null;
+ let memorySize = null;
+ if (pnpDeviceId) {
+ subDeviceId = pnpDeviceId[3] || '';
+ if (subDeviceId) {
+ subDeviceId = subDeviceId.split('_')[1];
}
- else {
- existingValue.push(value);
+
+ // Match PCI device identifier (there's an order of increasing generality):
+ // https://docs.microsoft.com/en-us/windows-hardware/drivers/install/identifiers-for-pci-devices
+
+ // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4)&REV_r(2)
+ if (memorySize == null && pnpDeviceId[3] && pnpDeviceId[4]) {
+ const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase();
+ if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
+ memorySize = memorySizes[deviceId];
+ }
}
- }
- else if (existingValue) {
- if (Array.isArray(value)) {
- value.unshift(existingValue);
+
+ // PCI\VEN_v(4)&DEV_d(4)&SUBSYS_s(4)n(4)
+ if (memorySize == null && pnpDeviceId[3]) {
+ const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[3].toUpperCase();
+ if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
+ memorySize = memorySizes[deviceId];
+ }
}
- else if (sequenceParams.has(name)) {
- combinedParams.set(name, [existingValue, value]);
+
+ // PCI\VEN_v(4)&DEV_d(4)&REV_r(2)
+ if (memorySize == null && pnpDeviceId[4]) {
+ const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase() + '&' + pnpDeviceId[4].toUpperCase();
+ if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
+ memorySize = memorySizes[deviceId];
+ }
}
- if (!noOverwrite) {
- combinedParams.set(name, value);
+
+ // PCI\VEN_v(4)&DEV_d(4)
+ if (memorySize == null) {
+ const deviceId = pnpDeviceId[1].toUpperCase() + '&' + pnpDeviceId[2].toUpperCase();
+ if ({}.hasOwnProperty.call(memorySizes, deviceId)) {
+ memorySize = memorySizes[deviceId];
+ }
}
+ }
+
+ controllers.push({
+ vendor: util.getValue(lines, 'AdapterCompatibility', ':'),
+ model: util.getValue(lines, 'name', ':'),
+ bus: util.getValue(lines, 'PNPDeviceID', ':').startsWith('PCI') ? 'PCI' : '',
+ vram: (memorySize == null ? util.toInt(util.getValue(lines, 'AdapterRAM', ':')) : memorySize) / 1024 / 1024,
+ vramDynamic: (util.getValue(lines, 'VideoMemoryType', ':') === '2'),
+ subDeviceId
+ });
+ _resolutionX = util.toInt(util.getValue(lines, 'CurrentHorizontalResolution', ':')) || _resolutionX;
+ _resolutionY = util.toInt(util.getValue(lines, 'CurrentVerticalResolution', ':')) || _resolutionY;
+ _refreshRate = util.toInt(util.getValue(lines, 'CurrentRefreshRate', ':')) || _refreshRate;
+ _pixelDepth = util.toInt(util.getValue(lines, 'CurrentBitsPerPixel', ':')) || _pixelDepth;
}
- else {
- combinedParams.set(name, value);
- }
+ }
}
- const searchPieces = [];
- for (const [name, value] of combinedParams) {
- if (typeof value === "string") {
- searchPieces.push(`${name}=${value}`);
- }
- else if (Array.isArray(value)) {
- // QUIRK: If we get an array of values, include multiple key/value pairs
- for (const subValue of value) {
- searchPieces.push(`${name}=${subValue}`);
- }
- }
- else {
- searchPieces.push(`${name}=${value}`);
+ return controllers;
+ }
+
+ function parseLinesWindowsDisplaysPowershell(ssections, msections, dsections, tsections, isections) {
+ let displays = [];
+ let vendor = '';
+ let model = '';
+ let deviceID = '';
+ let resolutionX = 0;
+ let resolutionY = 0;
+ if (dsections && dsections.length) {
+ let linesDisplay = dsections[0].split('\n');
+ vendor = util.getValue(linesDisplay, 'MonitorManufacturer', ':');
+ model = util.getValue(linesDisplay, 'Name', ':');
+ deviceID = util.getValue(linesDisplay, 'PNPDeviceID', ':').replace(/&/g, '&').toLowerCase();
+ resolutionX = util.toInt(util.getValue(linesDisplay, 'ScreenWidth', ':'));
+ resolutionY = util.toInt(util.getValue(linesDisplay, 'ScreenHeight', ':'));
+ }
+ for (let i = 0; i < ssections.length; i++) {
+ if (ssections[i].trim() !== '') {
+ ssections[i] = 'BitsPerPixel ' + ssections[i];
+ msections[i] = 'Active ' + msections[i];
+ // tsections can be empty OR undefined on earlier versions of powershell (<=2.0)
+ // Tag connection type as UNKNOWN by default if this information is missing
+ if (tsections.length === 0 || tsections[i] === undefined) {
+ tsections[i] = 'Unknown';
}
+ let linesScreen = ssections[i].split('\n');
+ let linesMonitor = msections[i].split('\n');
+
+ let linesConnection = tsections[i].split('\n');
+ const bitsPerPixel = util.getValue(linesScreen, 'BitsPerPixel');
+ const bounds = util.getValue(linesScreen, 'Bounds').replace('{', '').replace('}', '').replace(/=/g, ':').split(',');
+ const primary = util.getValue(linesScreen, 'Primary');
+ const sizeX = util.getValue(linesMonitor, 'MaxHorizontalImageSize');
+ const sizeY = util.getValue(linesMonitor, 'MaxVerticalImageSize');
+ const instanceName = util.getValue(linesMonitor, 'InstanceName').toLowerCase();
+ const videoOutputTechnology = util.getValue(linesConnection, 'VideoOutputTechnology');
+ const deviceName = util.getValue(linesScreen, 'DeviceName');
+ let displayVendor = '';
+ let displayModel = '';
+ isections.forEach(element => {
+ if (element.instanceId.toLowerCase().startsWith(instanceName) && vendor.startsWith('(') && model.startsWith('PnP')) {
+ displayVendor = element.vendor;
+ displayModel = element.model;
+ }
+ });
+ displays.push({
+ vendor: instanceName.startsWith(deviceID) && displayVendor === '' ? vendor : displayVendor,
+ model: instanceName.startsWith(deviceID) && displayModel === '' ? model : displayModel,
+ deviceName,
+ main: primary.toLowerCase() === 'true',
+ builtin: videoOutputTechnology === '2147483648',
+ connection: videoOutputTechnology && videoTypes[videoOutputTechnology] ? videoTypes[videoOutputTechnology] : '',
+ resolutionX: util.toInt(util.getValue(bounds, 'Width', ':')),
+ resolutionY: util.toInt(util.getValue(bounds, 'Height', ':')),
+ sizeX: sizeX ? parseInt(sizeX, 10) : null,
+ sizeY: sizeY ? parseInt(sizeY, 10) : null,
+ pixelDepth: bitsPerPixel,
+ currentResX: util.toInt(util.getValue(bounds, 'Width', ':')),
+ currentResY: util.toInt(util.getValue(bounds, 'Height', ':')),
+ positionX: util.toInt(util.getValue(bounds, 'X', ':')),
+ positionY: util.toInt(util.getValue(bounds, 'Y', ':')),
+ });
+ }
}
- // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't.
- parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : "";
- return parsedUrl.toString();
+ if (ssections.length === 0) {
+ displays.push({
+ vendor,
+ model,
+ main: true,
+ sizeX: null,
+ sizeY: null,
+ resolutionX,
+ resolutionY,
+ pixelDepth: null,
+ currentResX: resolutionX,
+ currentResY: resolutionY,
+ positionX: 0,
+ positionY: 0
+ });
+ }
+ return displays;
+ }
}
-exports.appendQueryParams = appendQueryParams;
-//# sourceMappingURL=urlHelpers.js.map
+
+exports.graphics = graphics;
+
/***/ }),
-/***/ 7805:
-/***/ ((__unused_webpack_module, exports) => {
+/***/ 8134:
+/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.flattenResponse = exports.isValidUuid = exports.isDuration = exports.isPrimitiveBody = void 0;
-/**
- * A type guard for a primitive response body.
- * @param value - Value to test
- *
- * @internal
- */
-function isPrimitiveBody(value, mapperTypeName) {
- return (mapperTypeName !== "Composite" &&
- mapperTypeName !== "Dictionary" &&
- (typeof value === "string" ||
- typeof value === "number" ||
- typeof value === "boolean" ||
- (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !==
- null ||
- value === undefined ||
- value === null));
-}
-exports.isPrimitiveBody = isPrimitiveBody;
-const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
-/**
- * Returns true if the given string is in ISO 8601 format.
- * @param value - The value to be validated for ISO 8601 duration format.
- * @internal
- */
-function isDuration(value) {
- return validateISODuration.test(value);
-}
-exports.isDuration = isDuration;
-const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i;
-/**
- * Returns true if the provided uuid is valid.
- *
- * @param uuid - The uuid that needs to be validated.
- *
- * @internal
- */
-function isValidUuid(uuid) {
- return validUuidRegex.test(uuid);
+// @ts-check
+// ==================================================================================
+// index.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// Contributors: Guillaume Legrain (https://github.com/glegrain)
+// Riccardo Novaglia (https://github.com/richy24)
+// Quentin Busuttil (https://github.com/Buzut)
+// Lapsio (https://github.com/lapsio)
+// csy (https://github.com/csy1983)
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+
+// ----------------------------------------------------------------------------------
+// Dependencies
+// ----------------------------------------------------------------------------------
+
+const lib_version = (__nccwpck_require__(15460)/* .version */ .rE);
+const util = __nccwpck_require__(77496);
+const system = __nccwpck_require__(97505);
+const osInfo = __nccwpck_require__(20330);
+const cpu = __nccwpck_require__(16832);
+const memory = __nccwpck_require__(84247);
+const battery = __nccwpck_require__(63179);
+const graphics = __nccwpck_require__(64293);
+const filesystem = __nccwpck_require__(50223);
+const network = __nccwpck_require__(61972);
+const wifi = __nccwpck_require__(76037);
+const processes = __nccwpck_require__(82999);
+const users = __nccwpck_require__(69318);
+const internet = __nccwpck_require__(81997);
+const docker = __nccwpck_require__(81820);
+const vbox = __nccwpck_require__(91404);
+const printer = __nccwpck_require__(93338);
+const usb = __nccwpck_require__(76748);
+const audio = __nccwpck_require__(74352);
+const bluetooth = __nccwpck_require__(6588);
+
+let _platform = process.platform;
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+
+// ----------------------------------------------------------------------------------
+// init
+// ----------------------------------------------------------------------------------
+
+if (_windows) {
+ util.getCodepage();
+ util.getPowershell();
}
-exports.isValidUuid = isValidUuid;
-/**
- * Maps the response as follows:
- * - wraps the response body if needed (typically if its type is primitive).
- * - returns null if the combination of the headers and the body is empty.
- * - otherwise, returns the combination of the headers and the body.
- *
- * @param responseObject - a representation of the parsed response
- * @returns the response that will be returned to the user which can be null and/or wrapped
- *
- * @internal
- */
-function handleNullableResponseAndWrappableBody(responseObject) {
- const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body);
- if (responseObject.hasNullableType &&
- Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) {
- return responseObject.shouldWrapBody ? { body: null } : null;
- }
- else {
- return responseObject.shouldWrapBody
- ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody;
- }
+
+// ----------------------------------------------------------------------------------
+// General
+// ----------------------------------------------------------------------------------
+
+function version() {
+ return lib_version;
}
-/**
- * Take a `FullOperationResponse` and turn it into a flat
- * response object to hand back to the consumer.
- * @param fullResponse - The processed response from the operation request
- * @param responseSpec - The response map from the OperationSpec
- *
- * @internal
- */
-function flattenResponse(fullResponse, responseSpec) {
- var _a, _b;
- const parsedHeaders = fullResponse.parsedHeaders;
- // head methods never have a body, but we return a boolean set to body property
- // to indicate presence/absence of the resource
- if (fullResponse.request.method === "HEAD") {
- return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody });
- }
- const bodyMapper = responseSpec && responseSpec.bodyMapper;
- const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable);
- const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name;
- /** If the body is asked for, we look at the expected body type to handle it */
- if (expectedBodyTypeName === "Stream") {
- return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody });
- }
- const modelProperties = (expectedBodyTypeName === "Composite" &&
- bodyMapper.type.modelProperties) ||
- {};
- const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === "");
- if (expectedBodyTypeName === "Sequence" || isPageableResponse) {
- const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : [];
- for (const key of Object.keys(modelProperties)) {
- if (modelProperties[key].serializedName) {
- arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key];
- }
- }
- if (parsedHeaders) {
- for (const key of Object.keys(parsedHeaders)) {
- arrayResponse[key] = parsedHeaders[key];
- }
- }
- return isNullable &&
- !fullResponse.parsedBody &&
- !parsedHeaders &&
- Object.getOwnPropertyNames(modelProperties).length === 0
- ? null
- : arrayResponse;
- }
- return handleNullableResponseAndWrappableBody({
- body: fullResponse.parsedBody,
- headers: parsedHeaders,
- hasNullableType: isNullable,
- shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName),
+
+// ----------------------------------------------------------------------------------
+// Get static and dynamic data (all)
+// ----------------------------------------------------------------------------------
+
+// --------------------------
+// get static data - they should not change until restarted
+
+function getStaticData(callback) {
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+
+ let data = {};
+
+ data.version = version();
+
+ Promise.all([
+ system.system(),
+ system.bios(),
+ system.baseboard(),
+ system.chassis(),
+ osInfo.osInfo(),
+ osInfo.uuid(),
+ osInfo.versions(),
+ cpu.cpu(),
+ cpu.cpuFlags(),
+ graphics.graphics(),
+ network.networkInterfaces(),
+ memory.memLayout(),
+ filesystem.diskLayout()
+ ]).then((res) => {
+ data.system = res[0];
+ data.bios = res[1];
+ data.baseboard = res[2];
+ data.chassis = res[3];
+ data.os = res[4];
+ data.uuid = res[5];
+ data.versions = res[6];
+ data.cpu = res[7];
+ data.cpu.flags = res[8];
+ data.graphics = res[9];
+ data.net = res[10];
+ data.memLayout = res[11];
+ data.diskLayout = res[12];
+ if (callback) { callback(data); }
+ resolve(data);
+ });
});
+ });
}
-exports.flattenResponse = flattenResponse;
-//# sourceMappingURL=utils.js.map
-/***/ }),
-/***/ 39448:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// get all dynamic data - e.g. for monitoring agents
+// may take some seconds to get all data
+// --------------------------
+// 2 additional parameters needed
+// - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql"
+// - iface: define network interface for which you like to monitor network speed e.g. "eth0"
+function getDynamicData(srv, iface, callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.ExtendedServiceClient = void 0;
-const disableKeepAlivePolicy_js_1 = __nccwpck_require__(56531);
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-const core_client_1 = __nccwpck_require__(6868);
-const response_js_1 = __nccwpck_require__(79093);
-/**
- * Client to provide compatability between core V1 & V2.
- */
-class ExtendedServiceClient extends core_client_1.ServiceClient {
- constructor(options) {
- var _a, _b;
- super(options);
- if (((_a = options.keepAliveOptions) === null || _a === void 0 ? void 0 : _a.enable) === false &&
- !(0, disableKeepAlivePolicy_js_1.pipelineContainsDisableKeepAlivePolicy)(this.pipeline)) {
- this.pipeline.addPolicy((0, disableKeepAlivePolicy_js_1.createDisableKeepAlivePolicy)());
- }
- if (((_b = options.redirectOptions) === null || _b === void 0 ? void 0 : _b.handleRedirects) === false) {
- this.pipeline.removePolicy({
- name: core_rest_pipeline_1.redirectPolicyName,
- });
- }
- }
- /**
- * Compatible send operation request function.
- *
- * @param operationArguments - Operation arguments
- * @param operationSpec - Operation Spec
- * @returns
- */
- async sendOperationRequest(operationArguments, operationSpec) {
- var _a;
- const userProvidedCallBack = (_a = operationArguments === null || operationArguments === void 0 ? void 0 : operationArguments.options) === null || _a === void 0 ? void 0 : _a.onResponse;
- let lastResponse;
- function onResponse(rawResponse, flatResponse, error) {
- lastResponse = rawResponse;
- if (userProvidedCallBack) {
- userProvidedCallBack(rawResponse, flatResponse, error);
+ if (util.isFunction(iface)) {
+ callback = iface;
+ iface = '';
+ }
+ if (util.isFunction(srv)) {
+ callback = srv;
+ srv = '';
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+
+ iface = iface || network.getDefaultNetworkInterface();
+ srv = srv || '';
+
+ // use closure to track ƒ completion
+ let functionProcessed = (function () {
+ let totalFunctions = 15;
+ if (_windows) { totalFunctions = 13; }
+ if (_freebsd || _openbsd || _netbsd) { totalFunctions = 11; }
+ if (_sunos) { totalFunctions = 6; }
+
+ return function () {
+ if (--totalFunctions === 0) {
+ if (callback) {
+ callback(data);
}
- }
- operationArguments.options = Object.assign(Object.assign({}, operationArguments.options), { onResponse });
- const result = await super.sendOperationRequest(operationArguments, operationSpec);
- if (lastResponse) {
- Object.defineProperty(result, "_response", {
- value: (0, response_js_1.toCompatResponse)(lastResponse),
- });
- }
- return result;
- }
-}
-exports.ExtendedServiceClient = ExtendedServiceClient;
-//# sourceMappingURL=extendedClient.js.map
+ resolve(data);
+ }
+ };
+ })();
-/***/ }),
+ let data = {};
-/***/ 22842:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ // get time
+ data.time = osInfo.time();
+
+ /**
+ * @namespace
+ * @property {Object} versions
+ * @property {string} versions.node
+ * @property {string} versions.v8
+ */
+ data.node = process.versions.node;
+ data.v8 = process.versions.v8;
+ cpu.cpuCurrentSpeed().then((res) => {
+ data.cpuCurrentSpeed = res;
+ functionProcessed();
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.convertHttpClient = void 0;
-const response_js_1 = __nccwpck_require__(79093);
-const util_js_1 = __nccwpck_require__(46);
-/**
- * Converts a RequestPolicy based HttpClient to a PipelineRequest based HttpClient.
- * @param requestPolicyClient - A HttpClient compatible with core-http
- * @returns A HttpClient compatible with core-rest-pipeline
- */
-function convertHttpClient(requestPolicyClient) {
- return {
- sendRequest: async (request) => {
- const response = await requestPolicyClient.sendRequest((0, util_js_1.toWebResourceLike)(request, { createProxy: true }));
- return (0, response_js_1.toPipelineResponse)(response);
- },
- };
-}
-exports.convertHttpClient = convertHttpClient;
-//# sourceMappingURL=httpClientAdapter.js.map
+ users.users().then((res) => {
+ data.users = res;
+ functionProcessed();
+ });
-/***/ }),
+ processes.processes().then((res) => {
+ data.processes = res;
+ functionProcessed();
+ });
-/***/ 14508:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ cpu.currentLoad().then((res) => {
+ data.currentLoad = res;
+ functionProcessed();
+ });
+ if (!_sunos) {
+ cpu.cpuTemperature().then((res) => {
+ data.temp = res;
+ functionProcessed();
+ });
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toHttpHeadersLike = exports.convertHttpClient = exports.disableKeepAlivePolicyName = exports.HttpPipelineLogLevel = exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.ExtendedServiceClient = void 0;
-/**
- * A Shim Library that provides compatibility between Core V1 & V2 Packages.
- *
- * @packageDocumentation
- */
-var extendedClient_js_1 = __nccwpck_require__(39448);
-Object.defineProperty(exports, "ExtendedServiceClient", ({ enumerable: true, get: function () { return extendedClient_js_1.ExtendedServiceClient; } }));
-var requestPolicyFactoryPolicy_js_1 = __nccwpck_require__(15190);
-Object.defineProperty(exports, "requestPolicyFactoryPolicyName", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.requestPolicyFactoryPolicyName; } }));
-Object.defineProperty(exports, "createRequestPolicyFactoryPolicy", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.createRequestPolicyFactoryPolicy; } }));
-Object.defineProperty(exports, "HttpPipelineLogLevel", ({ enumerable: true, get: function () { return requestPolicyFactoryPolicy_js_1.HttpPipelineLogLevel; } }));
-var disableKeepAlivePolicy_js_1 = __nccwpck_require__(56531);
-Object.defineProperty(exports, "disableKeepAlivePolicyName", ({ enumerable: true, get: function () { return disableKeepAlivePolicy_js_1.disableKeepAlivePolicyName; } }));
-var httpClientAdapter_js_1 = __nccwpck_require__(22842);
-Object.defineProperty(exports, "convertHttpClient", ({ enumerable: true, get: function () { return httpClientAdapter_js_1.convertHttpClient; } }));
-var util_js_1 = __nccwpck_require__(46);
-Object.defineProperty(exports, "toHttpHeadersLike", ({ enumerable: true, get: function () { return util_js_1.toHttpHeadersLike; } }));
-//# sourceMappingURL=index.js.map
+ if (!_openbsd && !_freebsd && !_netbsd && !_sunos) {
+ network.networkStats(iface).then((res) => {
+ data.networkStats = res;
+ functionProcessed();
+ });
+ }
-/***/ }),
+ if (!_sunos) {
+ network.networkConnections().then((res) => {
+ data.networkConnections = res;
+ functionProcessed();
+ });
+ }
-/***/ 56531:
-/***/ ((__unused_webpack_module, exports) => {
+ memory.mem().then((res) => {
+ data.mem = res;
+ functionProcessed();
+ });
+ if (!_sunos) {
+ battery().then((res) => {
+ data.battery = res;
+ functionProcessed();
+ });
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.pipelineContainsDisableKeepAlivePolicy = exports.createDisableKeepAlivePolicy = exports.disableKeepAlivePolicyName = void 0;
-exports.disableKeepAlivePolicyName = "DisableKeepAlivePolicy";
-function createDisableKeepAlivePolicy() {
- return {
- name: exports.disableKeepAlivePolicyName,
- async sendRequest(request, next) {
- request.disableKeepAlive = true;
- return next(request);
- },
- };
-}
-exports.createDisableKeepAlivePolicy = createDisableKeepAlivePolicy;
-/**
- * @internal
- */
-function pipelineContainsDisableKeepAlivePolicy(pipeline) {
- return pipeline.getOrderedPolicies().some((policy) => policy.name === exports.disableKeepAlivePolicyName);
-}
-exports.pipelineContainsDisableKeepAlivePolicy = pipelineContainsDisableKeepAlivePolicy;
-//# sourceMappingURL=disableKeepAlivePolicy.js.map
+ if (!_sunos) {
+ processes.services(srv).then((res) => {
+ data.services = res;
+ functionProcessed();
+ });
+ }
+
+ if (!_sunos) {
+ filesystem.fsSize().then((res) => {
+ data.fsSize = res;
+ functionProcessed();
+ });
+ }
-/***/ }),
+ if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) {
+ filesystem.fsStats().then((res) => {
+ data.fsStats = res;
+ functionProcessed();
+ });
+ }
-/***/ 15190:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (!_windows && !_openbsd && !_freebsd && !_netbsd && !_sunos) {
+ filesystem.disksIO().then((res) => {
+ data.disksIO = res;
+ functionProcessed();
+ });
+ }
+ if (!_openbsd && !_freebsd && !_netbsd && !_sunos) {
+ wifi.wifiNetworks().then((res) => {
+ data.wifiNetworks = res;
+ functionProcessed();
+ });
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createRequestPolicyFactoryPolicy = exports.requestPolicyFactoryPolicyName = exports.HttpPipelineLogLevel = void 0;
-const util_js_1 = __nccwpck_require__(46);
-const response_js_1 = __nccwpck_require__(79093);
-/**
- * An enum for compatibility with RequestPolicy
- */
-var HttpPipelineLogLevel;
-(function (HttpPipelineLogLevel) {
- HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
- HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
- HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
- HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
-})(HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = HttpPipelineLogLevel = {}));
-const mockRequestPolicyOptions = {
- log(_logLevel, _message) {
- /* do nothing */
- },
- shouldLog(_logLevel) {
- return false;
- },
-};
-/**
- * The name of the RequestPolicyFactoryPolicy
- */
-exports.requestPolicyFactoryPolicyName = "RequestPolicyFactoryPolicy";
-/**
- * A policy that wraps policies written for core-http.
- * @param factories - An array of `RequestPolicyFactory` objects from a core-http pipeline
- */
-function createRequestPolicyFactoryPolicy(factories) {
- const orderedFactories = factories.slice().reverse();
- return {
- name: exports.requestPolicyFactoryPolicyName,
- async sendRequest(request, next) {
- let httpPipeline = {
- async sendRequest(httpRequest) {
- const response = await next((0, util_js_1.toPipelineRequest)(httpRequest));
- return (0, response_js_1.toCompatResponse)(response, { createProxy: true });
- },
- };
- for (const factory of orderedFactories) {
- httpPipeline = factory.create(httpPipeline, mockRequestPolicyOptions);
- }
- const webResourceLike = (0, util_js_1.toWebResourceLike)(request, { createProxy: true });
- const response = await httpPipeline.sendRequest(webResourceLike);
- return (0, response_js_1.toPipelineResponse)(response);
- },
- };
+ internet.inetLatency().then((res) => {
+ data.inetLatency = res;
+ functionProcessed();
+ });
+ });
+ });
}
-exports.createRequestPolicyFactoryPolicy = createRequestPolicyFactoryPolicy;
-//# sourceMappingURL=requestPolicyFactoryPolicy.js.map
-
-/***/ }),
-
-/***/ 79093:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// --------------------------
+// get all data at once
+// --------------------------
+// 2 additional parameters needed
+// - srv: comma separated list of services to monitor e.g. "mysql, apache, postgresql"
+// - iface: define network interface for which you like to monitor network speed e.g. "eth0"
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.toPipelineResponse = exports.toCompatResponse = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-const util_js_1 = __nccwpck_require__(46);
-const originalResponse = Symbol("Original FullOperationResponse");
-/**
- * A helper to convert response objects from the new pipeline back to the old one.
- * @param response - A response object from core-client.
- * @returns A response compatible with `HttpOperationResponse` from core-http.
- */
-function toCompatResponse(response, options) {
- let request = (0, util_js_1.toWebResourceLike)(response.request);
- let headers = (0, util_js_1.toHttpHeadersLike)(response.headers);
- if (options === null || options === void 0 ? void 0 : options.createProxy) {
- return new Proxy(response, {
- get(target, prop, receiver) {
- if (prop === "headers") {
- return headers;
- }
- else if (prop === "request") {
- return request;
- }
- else if (prop === originalResponse) {
- return response;
- }
- return Reflect.get(target, prop, receiver);
- },
- set(target, prop, value, receiver) {
- if (prop === "headers") {
- headers = value;
- }
- else if (prop === "request") {
- request = value;
- }
- return Reflect.set(target, prop, value, receiver);
- },
- });
- }
- else {
- return Object.assign(Object.assign({}, response), { request,
- headers });
- }
-}
-exports.toCompatResponse = toCompatResponse;
-/**
- * A helper to convert back to a PipelineResponse
- * @param compatResponse - A response compatible with `HttpOperationResponse` from core-http.
- */
-function toPipelineResponse(compatResponse) {
- const extendedCompatResponse = compatResponse;
- const response = extendedCompatResponse[originalResponse];
- const headers = (0, core_rest_pipeline_1.createHttpHeaders)(compatResponse.headers.toJson({ preserveCase: true }));
- if (response) {
- response.headers = headers;
- return response;
- }
- else {
- return Object.assign(Object.assign({}, compatResponse), { headers, request: (0, util_js_1.toPipelineRequest)(compatResponse.request) });
- }
-}
-exports.toPipelineResponse = toPipelineResponse;
-//# sourceMappingURL=response.js.map
+function getAllData(srv, iface, callback) {
-/***/ }),
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let data = {};
-/***/ 46:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ if (iface && util.isFunction(iface) && !callback) {
+ callback = iface;
+ iface = '';
+ }
+ if (srv && util.isFunction(srv) && !iface && !callback) {
+ callback = srv;
+ srv = '';
+ iface = '';
+ }
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.HttpHeaders = exports.toHttpHeadersLike = exports.toWebResourceLike = exports.toPipelineRequest = void 0;
-const core_rest_pipeline_1 = __nccwpck_require__(95582);
-// We use a custom symbol to cache a reference to the original request without
-// exposing it on the public interface.
-const originalRequestSymbol = Symbol("Original PipelineRequest");
-// Symbol.for() will return the same symbol if it's already been created
-// This particular one is used in core-client to handle the case of when a request is
-// cloned but we need to retrieve the OperationSpec and OperationArguments from the
-// original request.
-const originalClientRequestSymbol = Symbol.for("@azure/core-client original request");
-function toPipelineRequest(webResource, options = {}) {
- const compatWebResource = webResource;
- const request = compatWebResource[originalRequestSymbol];
- const headers = (0, core_rest_pipeline_1.createHttpHeaders)(webResource.headers.toJson({ preserveCase: true }));
- if (request) {
- request.headers = headers;
- return request;
- }
- else {
- const newRequest = (0, core_rest_pipeline_1.createPipelineRequest)({
- url: webResource.url,
- method: webResource.method,
- headers,
- withCredentials: webResource.withCredentials,
- timeout: webResource.timeout,
- requestId: webResource.requestId,
- abortSignal: webResource.abortSignal,
- body: webResource.body,
- formData: webResource.formData,
- disableKeepAlive: !!webResource.keepAlive,
- onDownloadProgress: webResource.onDownloadProgress,
- onUploadProgress: webResource.onUploadProgress,
- proxySettings: webResource.proxySettings,
- streamResponseStatusCodes: webResource.streamResponseStatusCodes,
+ getStaticData().then((res) => {
+ data = res;
+ getDynamicData(srv, iface).then((res) => {
+ for (let key in res) {
+ if ({}.hasOwnProperty.call(res, key)) {
+ data[key] = res[key];
+ }
+ }
+ if (callback) { callback(data); }
+ resolve(data);
});
- if (options.originalRequest) {
- newRequest[originalClientRequestSymbol] =
- options.originalRequest;
- }
- return newRequest;
- }
+ });
+ });
+ });
}
-exports.toPipelineRequest = toPipelineRequest;
-function toWebResourceLike(request, options) {
- var _a;
- const originalRequest = (_a = options === null || options === void 0 ? void 0 : options.originalRequest) !== null && _a !== void 0 ? _a : request;
- const webResource = {
- url: request.url,
- method: request.method,
- headers: toHttpHeadersLike(request.headers),
- withCredentials: request.withCredentials,
- timeout: request.timeout,
- requestId: request.headers.get("x-ms-client-request-id") || request.requestId,
- abortSignal: request.abortSignal,
- body: request.body,
- formData: request.formData,
- keepAlive: !!request.disableKeepAlive,
- onDownloadProgress: request.onDownloadProgress,
- onUploadProgress: request.onUploadProgress,
- proxySettings: request.proxySettings,
- streamResponseStatusCodes: request.streamResponseStatusCodes,
- clone() {
- throw new Error("Cannot clone a non-proxied WebResourceLike");
- },
- prepare() {
- throw new Error("WebResourceLike.prepare() is not supported by @azure/core-http-compat");
- },
- validateRequestProperties() {
- /** do nothing */
- },
- };
- if (options === null || options === void 0 ? void 0 : options.createProxy) {
- return new Proxy(webResource, {
- get(target, prop, receiver) {
- if (prop === originalRequestSymbol) {
- return request;
- }
- else if (prop === "clone") {
- return () => {
- return toWebResourceLike(toPipelineRequest(webResource, { originalRequest }), {
- createProxy: true,
- originalRequest,
- });
- };
- }
- return Reflect.get(target, prop, receiver);
- },
- set(target, prop, value, receiver) {
- if (prop === "keepAlive") {
- request.disableKeepAlive = !value;
- }
- const passThroughProps = [
- "url",
- "method",
- "withCredentials",
- "timeout",
- "requestId",
- "abortSignal",
- "body",
- "formData",
- "onDownloadProgress",
- "onUploadProgress",
- "proxySettings",
- "streamResponseStatusCodes",
- ];
- if (typeof prop === "string" && passThroughProps.includes(prop)) {
- request[prop] = value;
- }
- return Reflect.set(target, prop, value, receiver);
- },
+
+function get(valueObject, callback) {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ const allPromises = Object.keys(valueObject)
+ .filter(func => ({}.hasOwnProperty.call(exports, func)))
+ .map(func => {
+ const params = valueObject[func].substring(valueObject[func].lastIndexOf('(') + 1, valueObject[func].lastIndexOf(')'));
+ let funcWithoutParams = func.indexOf(')') >= 0 ? func.split(')')[1].trim() : func;
+ funcWithoutParams = func.indexOf('|') >= 0 ? func.split('|')[0].trim() : funcWithoutParams;
+ if (params) {
+ return exports[funcWithoutParams](params);
+ } else {
+ return exports[funcWithoutParams]('');
+ }
});
- }
- else {
- return webResource;
- }
-}
-exports.toWebResourceLike = toWebResourceLike;
-/**
- * Converts HttpHeaders from core-rest-pipeline to look like
- * HttpHeaders from core-http.
- * @param headers - HttpHeaders from core-rest-pipeline
- * @returns HttpHeaders as they looked in core-http
- */
-function toHttpHeadersLike(headers) {
- return new HttpHeaders(headers.toJSON({ preserveCase: true }));
-}
-exports.toHttpHeadersLike = toHttpHeadersLike;
-/**
- * A collection of HttpHeaders that can be sent with a HTTP request.
- */
-function getHeaderKey(headerName) {
- return headerName.toLowerCase();
-}
-/**
- * A collection of HTTP header key/value pairs.
- */
-class HttpHeaders {
- constructor(rawHeaders) {
- this._headersMap = {};
- if (rawHeaders) {
- for (const headerName in rawHeaders) {
- this.set(headerName, rawHeaders[headerName]);
- }
- }
- }
- /**
- * Set a header in this collection with the provided name and value. The name is
- * case-insensitive.
- * @param headerName - The name of the header to set. This value is case-insensitive.
- * @param headerValue - The value of the header to set.
- */
- set(headerName, headerValue) {
- this._headersMap[getHeaderKey(headerName)] = {
- name: headerName,
- value: headerValue.toString(),
- };
- }
- /**
- * Get the header value for the provided header name, or undefined if no header exists in this
- * collection with the provided name.
- * @param headerName - The name of the header.
- */
- get(headerName) {
- const header = this._headersMap[getHeaderKey(headerName)];
- return !header ? undefined : header.value;
- }
- /**
- * Get whether or not this header collection contains a header entry for the provided header name.
- */
- contains(headerName) {
- return !!this._headersMap[getHeaderKey(headerName)];
- }
- /**
- * Remove the header with the provided headerName. Return whether or not the header existed and
- * was removed.
- * @param headerName - The name of the header to remove.
- */
- remove(headerName) {
- const result = this.contains(headerName);
- delete this._headersMap[getHeaderKey(headerName)];
- return result;
- }
- /**
- * Get the headers that are contained this collection as an object.
- */
- rawHeaders() {
- return this.toJson({ preserveCase: true });
- }
- /**
- * Get the headers that are contained in this collection as an array.
- */
- headersArray() {
- const headers = [];
- for (const headerKey in this._headersMap) {
- headers.push(this._headersMap[headerKey]);
- }
- return headers;
- }
- /**
- * Get the header names that are contained in this collection.
- */
- headerNames() {
- const headerNames = [];
- const headers = this.headersArray();
- for (let i = 0; i < headers.length; ++i) {
- headerNames.push(headers[i].name);
- }
- return headerNames;
- }
- /**
- * Get the header values that are contained in this collection.
- */
- headerValues() {
- const headerValues = [];
- const headers = this.headersArray();
- for (let i = 0; i < headers.length; ++i) {
- headerValues.push(headers[i].value);
- }
- return headerValues;
- }
- /**
- * Get the JSON object representation of this HTTP header collection.
- */
- toJson(options = {}) {
+
+ Promise.all(allPromises).then((data) => {
const result = {};
- if (options.preserveCase) {
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- result[header.name] = header.value;
- }
- }
- else {
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- result[getHeaderKey(header.name)] = header.value;
- }
- }
- return result;
- }
- /**
- * Get the string representation of this HTTP header collection.
- */
- toString() {
- return JSON.stringify(this.toJson({ preserveCase: true }));
- }
- /**
- * Create a deep clone/copy of this HttpHeaders collection.
- */
- clone() {
- const resultPreservingCasing = {};
- for (const headerKey in this._headersMap) {
- const header = this._headersMap[headerKey];
- resultPreservingCasing[header.name] = header.value;
+ let i = 0;
+ for (let key in valueObject) {
+ if ({}.hasOwnProperty.call(valueObject, key) && {}.hasOwnProperty.call(exports, key) && data.length > i) {
+ if (valueObject[key] === '*' || valueObject[key] === 'all') {
+ result[key] = data[i];
+ } else {
+ let keys = valueObject[key];
+ let filter = '';
+ let filterParts = [];
+ // remove params
+ if (keys.indexOf(')') >= 0) {
+ keys = keys.split(')')[1].trim();
+ }
+ // extract filter and remove it from keys
+ if (keys.indexOf('|') >= 0) {
+ filter = keys.split('|')[1].trim();
+ filterParts = filter.split(':');
+
+ keys = keys.split('|')[0].trim();
+ }
+ keys = keys.replace(/,/g, ' ').replace(/ +/g, ' ').split(' ');
+ if (data[i]) {
+ if (Array.isArray(data[i])) {
+ // result is in an array, go through all elements of array and pick only the right ones
+ const partialArray = [];
+ data[i].forEach(element => {
+ let partialRes = {};
+ if (keys.length === 1 && (keys[0] === '*' || keys[0] === 'all')) {
+ partialRes = element;
+ } else {
+ keys.forEach(k => {
+ if ({}.hasOwnProperty.call(element, k)) {
+ partialRes[k] = element[k];
+ }
+ });
+ }
+ // if there is a filter, then just take those elements
+ if (filter && filterParts.length === 2) {
+ if ({}.hasOwnProperty.call(partialRes, filterParts[0].trim())) {
+ const val = partialRes[filterParts[0].trim()];
+ if (typeof val == 'number') {
+ if (val === parseFloat(filterParts[1].trim())) {
+ partialArray.push(partialRes);
+ }
+ } else if (typeof val == 'string') {
+ if (val.toLowerCase() === filterParts[1].trim().toLowerCase()) {
+ partialArray.push(partialRes);
+ }
+ }
+ }
+ } else {
+ partialArray.push(partialRes);
+ }
+
+ });
+ result[key] = partialArray;
+ } else {
+ const partialRes = {};
+ keys.forEach(k => {
+ if ({}.hasOwnProperty.call(data[i], k)) {
+ partialRes[k] = data[i][k];
+ }
+ });
+ result[key] = partialRes;
+ }
+ } else {
+ result[key] = {};
+ }
+ }
+ i++;
+ }
}
- return new HttpHeaders(resultPreservingCasing);
- }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ });
}
-exports.HttpHeaders = HttpHeaders;
-//# sourceMappingURL=util.js.map
+
+function observe(valueObject, interval, callback) {
+ let _data = null;
+
+ const result = setInterval(() => {
+ get(valueObject).then((data) => {
+ if (JSON.stringify(_data) !== JSON.stringify(data)) {
+ _data = Object.assign({}, data);
+ callback(data);
+ }
+ });
+ }, interval);
+ return result;
+}
+
+// ----------------------------------------------------------------------------------
+// export all libs
+// ----------------------------------------------------------------------------------
+
+exports.version = version;
+exports.system = system.system;
+exports.bios = system.bios;
+exports.baseboard = system.baseboard;
+exports.chassis = system.chassis;
+
+exports.time = osInfo.time;
+exports.osInfo = osInfo.osInfo;
+exports.versions = osInfo.versions;
+exports.shell = osInfo.shell;
+exports.uuid = osInfo.uuid;
+
+exports.cpu = cpu.cpu;
+exports.cpuFlags = cpu.cpuFlags;
+exports.cpuCache = cpu.cpuCache;
+exports.cpuCurrentSpeed = cpu.cpuCurrentSpeed;
+exports.cpuTemperature = cpu.cpuTemperature;
+exports.currentLoad = cpu.currentLoad;
+exports.fullLoad = cpu.fullLoad;
+
+exports.mem = memory.mem;
+exports.memLayout = memory.memLayout;
+
+exports.battery = battery;
+
+exports.graphics = graphics.graphics;
+
+exports.fsSize = filesystem.fsSize;
+exports.fsOpenFiles = filesystem.fsOpenFiles;
+exports.blockDevices = filesystem.blockDevices;
+exports.fsStats = filesystem.fsStats;
+exports.disksIO = filesystem.disksIO;
+exports.diskLayout = filesystem.diskLayout;
+
+exports.networkInterfaceDefault = network.networkInterfaceDefault;
+exports.networkGatewayDefault = network.networkGatewayDefault;
+exports.networkInterfaces = network.networkInterfaces;
+exports.networkStats = network.networkStats;
+exports.networkConnections = network.networkConnections;
+
+exports.wifiNetworks = wifi.wifiNetworks;
+exports.wifiInterfaces = wifi.wifiInterfaces;
+exports.wifiConnections = wifi.wifiConnections;
+
+exports.services = processes.services;
+exports.processes = processes.processes;
+exports.processLoad = processes.processLoad;
+
+exports.users = users.users;
+
+exports.inetChecksite = internet.inetChecksite;
+exports.inetLatency = internet.inetLatency;
+
+exports.dockerInfo = docker.dockerInfo;
+exports.dockerImages = docker.dockerImages;
+exports.dockerContainers = docker.dockerContainers;
+exports.dockerContainerStats = docker.dockerContainerStats;
+exports.dockerContainerProcesses = docker.dockerContainerProcesses;
+exports.dockerVolumes = docker.dockerVolumes;
+exports.dockerAll = docker.dockerAll;
+
+exports.vboxInfo = vbox.vboxInfo;
+
+exports.printer = printer.printer;
+
+exports.usb = usb.usb;
+
+exports.audio = audio.audio;
+exports.bluetoothDevices = bluetooth.bluetoothDevices;
+
+exports.getStaticData = getStaticData;
+exports.getDynamicData = getDynamicData;
+exports.getAllData = getAllData;
+exports.get = get;
+exports.observe = observe;
+
+exports.powerShellStart = util.powerShellStart;
+exports.powerShellRelease = util.powerShellRelease;
+
/***/ }),
-/***/ 27826:
+/***/ 81997:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.pollHttpOperation = exports.isOperationError = exports.getResourceLocation = exports.getOperationStatus = exports.getOperationLocation = exports.initHttpOperation = exports.getStatusFromInitialResponse = exports.getErrorFromResponse = exports.parseRetryAfter = exports.inferLroMode = void 0;
-const operation_js_1 = __nccwpck_require__(26588);
-const logger_js_1 = __nccwpck_require__(80692);
-function getOperationLocationPollingUrl(inputs) {
- const { azureAsyncOperation, operationLocation } = inputs;
- return operationLocation !== null && operationLocation !== void 0 ? operationLocation : azureAsyncOperation;
-}
-function getLocationHeader(rawResponse) {
- return rawResponse.headers["location"];
-}
-function getOperationLocationHeader(rawResponse) {
- return rawResponse.headers["operation-location"];
-}
-function getAzureAsyncOperationHeader(rawResponse) {
- return rawResponse.headers["azure-asyncoperation"];
-}
-function findResourceLocation(inputs) {
- var _a;
- const { location, requestMethod, requestPath, resourceLocationConfig } = inputs;
- switch (requestMethod) {
- case "PUT": {
- return requestPath;
- }
- case "DELETE": {
- return undefined;
- }
- case "PATCH": {
- return (_a = getDefault()) !== null && _a !== void 0 ? _a : requestPath;
- }
- default: {
- return getDefault();
- }
- }
- function getDefault() {
- switch (resourceLocationConfig) {
- case "azure-async-operation": {
- return undefined;
- }
- case "original-uri": {
- return requestPath;
- }
- case "location":
- default: {
- return location;
- }
- }
- }
-}
-function inferLroMode(inputs) {
- const { rawResponse, requestMethod, requestPath, resourceLocationConfig } = inputs;
- const operationLocation = getOperationLocationHeader(rawResponse);
- const azureAsyncOperation = getAzureAsyncOperationHeader(rawResponse);
- const pollingUrl = getOperationLocationPollingUrl({ operationLocation, azureAsyncOperation });
- const location = getLocationHeader(rawResponse);
- const normalizedRequestMethod = requestMethod === null || requestMethod === void 0 ? void 0 : requestMethod.toLocaleUpperCase();
- if (pollingUrl !== undefined) {
- return {
- mode: "OperationLocation",
- operationLocation: pollingUrl,
- resourceLocation: findResourceLocation({
- requestMethod: normalizedRequestMethod,
- location,
- requestPath,
- resourceLocationConfig,
- }),
- };
- }
- else if (location !== undefined) {
- return {
- mode: "ResourceLocation",
- operationLocation: location,
- };
- }
- else if (normalizedRequestMethod === "PUT" && requestPath) {
- return {
- mode: "Body",
- operationLocation: requestPath,
- };
- }
- else {
- return undefined;
- }
-}
-exports.inferLroMode = inferLroMode;
-function transformStatus(inputs) {
- const { status, statusCode } = inputs;
- if (typeof status !== "string" && status !== undefined) {
- throw new Error(`Polling was unsuccessful. Expected status to have a string value or no value but it has instead: ${status}. This doesn't necessarily indicate the operation has failed. Check your Azure subscription or resource status for more information.`);
- }
- switch (status === null || status === void 0 ? void 0 : status.toLocaleLowerCase()) {
- case undefined:
- return toOperationStatus(statusCode);
- case "succeeded":
- return "succeeded";
- case "failed":
- return "failed";
- case "running":
- case "accepted":
- case "started":
- case "canceling":
- case "cancelling":
- return "running";
- case "canceled":
- case "cancelled":
- return "canceled";
- default: {
- logger_js_1.logger.verbose(`LRO: unrecognized operation status: ${status}`);
- return status;
+// @ts-check
+// ==================================================================================
+// internet.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 12. Internet
+// ----------------------------------------------------------------------------------
+
+const util = __nccwpck_require__(77496);
+
+let _platform = process.platform;
+
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
+
+// --------------------------
+// check if external site is available
+
+function inetChecksite(url, callback) {
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ url: url,
+ ok: false,
+ status: 404,
+ ms: null
+ };
+ if (typeof url !== 'string') {
+ if (callback) { callback(result); }
+ return resolve(result);
+ }
+ let urlSanitized = '';
+ const s = util.sanitizeShellString(url, true);
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (s[i] !== undefined) {
+ try {
+ s[i].__proto__.toLowerCase = util.stringToLower;
+ } catch (e) {
+ Object.setPrototypeOf(s[i], util.stringObj);
+ }
+
+ const sl = s[i].toLowerCase();
+ if (sl && sl[0] && !sl[1] && sl[0].length === 1) {
+ urlSanitized = urlSanitized + sl[0];
+ }
}
- }
-}
-function getStatus(rawResponse) {
- var _a;
- const { status } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
- return transformStatus({ status, statusCode: rawResponse.statusCode });
-}
-function getProvisioningState(rawResponse) {
- var _a, _b;
- const { properties, provisioningState } = (_a = rawResponse.body) !== null && _a !== void 0 ? _a : {};
- const status = (_b = properties === null || properties === void 0 ? void 0 : properties.provisioningState) !== null && _b !== void 0 ? _b : provisioningState;
- return transformStatus({ status, statusCode: rawResponse.statusCode });
-}
-function toOperationStatus(statusCode) {
- if (statusCode === 202) {
- return "running";
- }
- else if (statusCode < 300) {
- return "succeeded";
- }
- else {
- return "failed";
- }
-}
-function parseRetryAfter({ rawResponse }) {
- const retryAfter = rawResponse.headers["retry-after"];
- if (retryAfter !== undefined) {
- // Retry-After header value is either in HTTP date format, or in seconds
- const retryAfterInSeconds = parseInt(retryAfter);
- return isNaN(retryAfterInSeconds)
- ? calculatePollingIntervalFromDate(new Date(retryAfter))
- : retryAfterInSeconds * 1000;
- }
- return undefined;
-}
-exports.parseRetryAfter = parseRetryAfter;
-function getErrorFromResponse(response) {
- const error = accessBodyProperty(response, "error");
- if (!error) {
- logger_js_1.logger.warning(`The long-running operation failed but there is no error property in the response's body`);
- return;
- }
- if (!error.code || !error.message) {
- logger_js_1.logger.warning(`The long-running operation failed but the error property in the response's body doesn't contain code or message`);
- return;
- }
- return error;
-}
-exports.getErrorFromResponse = getErrorFromResponse;
-function calculatePollingIntervalFromDate(retryAfterDate) {
- const timeNow = Math.floor(new Date().getTime());
- const retryAfterTime = retryAfterDate.getTime();
- if (timeNow < retryAfterTime) {
- return retryAfterTime - timeNow;
- }
- return undefined;
-}
-function getStatusFromInitialResponse(inputs) {
- const { response, state, operationLocation } = inputs;
- function helper() {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case undefined:
- return toOperationStatus(response.rawResponse.statusCode);
- case "Body":
- return getOperationStatus(response, state);
- default:
- return "running";
+ }
+ result.url = urlSanitized;
+ try {
+ if (urlSanitized && !util.isPrototypePolluted()) {
+ try {
+ urlSanitized.__proto__.startsWith = util.stringStartWith;
+ } catch (e) {
+ Object.setPrototypeOf(urlSanitized, util.stringObj);
+ }
+
+ if (urlSanitized.startsWith('file:') || urlSanitized.startsWith('gopher:') || urlSanitized.startsWith('telnet:') || urlSanitized.startsWith('mailto:') || urlSanitized.startsWith('news:') || urlSanitized.startsWith('nntp:')) {
+ if (callback) { callback(result); }
+ return resolve(result);
+ }
+
+ util.checkWebsite(urlSanitized).then((res) => {
+ result.status = res.statusCode;
+ result.ok = res.statusCode >= 200 && res.statusCode <= 399;;
+ result.ms = (result.ok ? res.time : null);
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } else {
+ if (callback) { callback(result); }
+ resolve(result);
}
- }
- const status = helper();
- return status === "running" && operationLocation === undefined ? "succeeded" : status;
-}
-exports.getStatusFromInitialResponse = getStatusFromInitialResponse;
-/**
- * Initiates the long-running operation.
- */
-async function initHttpOperation(inputs) {
- const { stateProxy, resourceLocationConfig, processResult, lro, setErrorAsResult } = inputs;
- return (0, operation_js_1.initOperation)({
- init: async () => {
- const response = await lro.sendInitialRequest();
- const config = inferLroMode({
- rawResponse: response.rawResponse,
- requestPath: lro.requestPath,
- requestMethod: lro.requestMethod,
- resourceLocationConfig,
- });
- return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
- },
- stateProxy,
- processResult: processResult
- ? ({ flatResponse }, state) => processResult(flatResponse, state)
- : ({ flatResponse }) => flatResponse,
- getOperationStatus: getStatusFromInitialResponse,
- setErrorAsResult,
+ } catch (err) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
});
+ });
}
-exports.initHttpOperation = initHttpOperation;
-function getOperationLocation({ rawResponse }, state) {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case "OperationLocation": {
- return getOperationLocationPollingUrl({
- operationLocation: getOperationLocationHeader(rawResponse),
- azureAsyncOperation: getAzureAsyncOperationHeader(rawResponse),
- });
- }
- case "ResourceLocation": {
- return getLocationHeader(rawResponse);
+
+exports.inetChecksite = inetChecksite;
+
+// --------------------------
+// check inet latency
+
+function inetLatency(host, callback) {
+
+ // fallback - if only callback is given
+ if (util.isFunction(host) && !callback) {
+ callback = host;
+ host = '';
+ }
+
+ host = host || '8.8.8.8';
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ if (typeof host !== 'string') {
+ if (callback) { callback(null); }
+ return resolve(null);
+ }
+ let hostSanitized = '';
+ const s = (util.isPrototypePolluted() ? '8.8.8.8' : util.sanitizeShellString(host, true)).trim();
+ const l = util.mathMin(s.length, 2000);
+ for (let i = 0; i <= l; i++) {
+ if (!(s[i] === undefined)) {
+ try {
+ s[i].__proto__.toLowerCase = util.stringToLower;
+ } catch (e) {
+ Object.setPrototypeOf(s[i], util.stringObj);
+ }
+
+ const sl = s[i].toLowerCase();
+ if (sl && sl[0] && !sl[1]) {
+ hostSanitized = hostSanitized + sl[0];
+ }
}
- case "Body":
- default: {
- return undefined;
+ }
+ try {
+ hostSanitized.__proto__.startsWith = util.stringStartWith;
+ } catch (e) {
+ Object.setPrototypeOf(hostSanitized, util.stringObj);
+ }
+
+ if (hostSanitized.startsWith('file:') || hostSanitized.startsWith('gopher:') || hostSanitized.startsWith('telnet:') || hostSanitized.startsWith('mailto:') || hostSanitized.startsWith('news:') || hostSanitized.startsWith('nntp:')) {
+ if (callback) { callback(null); }
+ return resolve(null);
+ }
+ let params;
+ if (_linux || _freebsd || _openbsd || _netbsd || _darwin) {
+ if (_linux) {
+ params = ['-c', '2', '-w', '3', hostSanitized];
}
- }
-}
-exports.getOperationLocation = getOperationLocation;
-function getOperationStatus({ rawResponse }, state) {
- var _a;
- const mode = (_a = state.config.metadata) === null || _a === void 0 ? void 0 : _a["mode"];
- switch (mode) {
- case "OperationLocation": {
- return getStatus(rawResponse);
+ if (_freebsd || _openbsd || _netbsd) {
+ params = ['-c', '2', '-t', '3', hostSanitized];
}
- case "ResourceLocation": {
- return toOperationStatus(rawResponse.statusCode);
+ if (_darwin) {
+ params = ['-c2', '-t3', hostSanitized];
}
- case "Body": {
- return getProvisioningState(rawResponse);
+ util.execSafe('ping', params).then((stdout) => {
+ let result = null;
+ if (stdout) {
+ const lines = stdout.split('\n').filter((line) => (line.indexOf('rtt') >= 0 || line.indexOf('round-trip') >= 0 || line.indexOf('avg') >= 0)).join('\n');
+
+ const line = lines.split('=');
+ if (line.length > 1) {
+ const parts = line[1].split('/');
+ if (parts.length > 1) {
+ result = parseFloat(parts[1]);
+ }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_sunos) {
+ const params = ['-s', '-a', hostSanitized, '56', '2'];
+ const filt = 'avg';
+ util.execSafe('ping', params, { timeout: 3000 }).then((stdout) => {
+ let result = null;
+ if (stdout) {
+ const lines = stdout.split('\n').filter(line => line.indexOf(filt) >= 0).join('\n');
+ const line = lines.split('=');
+ if (line.length > 1) {
+ const parts = line[1].split('/');
+ if (parts.length > 1) {
+ result = parseFloat(parts[1].replace(',', '.'));
+ }
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_windows) {
+ let result = null;
+ try {
+ const params = [hostSanitized, '-n', '1'];
+ util.execSafe('ping', params, util.execOptsWin).then((stdout) => {
+ if (stdout) {
+ let lines = stdout.split('\r\n');
+ lines.shift();
+ lines.forEach(function (line) {
+ if ((line.toLowerCase().match(/ms/g) || []).length === 3) {
+ let l = line.replace(/ +/g, ' ').split(' ');
+ if (l.length > 6) {
+ result = parseFloat(l[l.length - 1]);
+ }
+ }
+ });
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
}
- default:
- throw new Error(`Internal error: Unexpected operation mode: ${mode}`);
- }
-}
-exports.getOperationStatus = getOperationStatus;
-function accessBodyProperty({ flatResponse, rawResponse }, prop) {
- var _a, _b;
- return (_a = flatResponse === null || flatResponse === void 0 ? void 0 : flatResponse[prop]) !== null && _a !== void 0 ? _a : (_b = rawResponse.body) === null || _b === void 0 ? void 0 : _b[prop];
-}
-function getResourceLocation(res, state) {
- const loc = accessBodyProperty(res, "resourceLocation");
- if (loc && typeof loc === "string") {
- state.config.resourceLocation = loc;
- }
- return state.config.resourceLocation;
-}
-exports.getResourceLocation = getResourceLocation;
-function isOperationError(e) {
- return e.name === "RestError";
-}
-exports.isOperationError = isOperationError;
-/** Polls the long-running operation. */
-async function pollHttpOperation(inputs) {
- const { lro, stateProxy, options, processResult, updateState, setDelay, state, setErrorAsResult, } = inputs;
- return (0, operation_js_1.pollOperation)({
- state,
- stateProxy,
- setDelay,
- processResult: processResult
- ? ({ flatResponse }, inputState) => processResult(flatResponse, inputState)
- : ({ flatResponse }) => flatResponse,
- getError: getErrorFromResponse,
- updateState,
- getPollingInterval: parseRetryAfter,
- getOperationLocation,
- getOperationStatus,
- isOperationError,
- getResourceLocation,
- options,
- /**
- * The expansion here is intentional because `lro` could be an object that
- * references an inner this, so we need to preserve a reference to it.
- */
- poll: async (location, inputOptions) => lro.sendPollRequest(location, inputOptions),
- setErrorAsResult,
+ }
});
+ });
}
-exports.pollHttpOperation = pollHttpOperation;
-//# sourceMappingURL=operation.js.map
+
+exports.inetLatency = inetLatency;
+
/***/ }),
-/***/ 74681:
+/***/ 84247:
/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createHttpPoller = void 0;
-const operation_js_1 = __nccwpck_require__(27826);
-const poller_js_1 = __nccwpck_require__(81327);
-/**
- * Creates a poller that can be used to poll a long-running operation.
- * @param lro - Description of the long-running operation
- * @param options - options to configure the poller
- * @returns an initialized poller
- */
-async function createHttpPoller(lro, options) {
- const { resourceLocationConfig, intervalInMs, processResult, restoreFrom, updateState, withOperationLocation, resolveOnUnsuccessful = false, } = options || {};
- return (0, poller_js_1.buildCreatePoller)({
- getStatusFromInitialResponse: operation_js_1.getStatusFromInitialResponse,
- getStatusFromPollResponse: operation_js_1.getOperationStatus,
- isOperationError: operation_js_1.isOperationError,
- getOperationLocation: operation_js_1.getOperationLocation,
- getResourceLocation: operation_js_1.getResourceLocation,
- getPollingInterval: operation_js_1.parseRetryAfter,
- getError: operation_js_1.getErrorFromResponse,
- resolveOnUnsuccessful,
- })({
- init: async () => {
- const response = await lro.sendInitialRequest();
- const config = (0, operation_js_1.inferLroMode)({
- rawResponse: response.rawResponse,
- requestPath: lro.requestPath,
- requestMethod: lro.requestMethod,
- resourceLocationConfig,
- });
- return Object.assign({ response, operationLocation: config === null || config === void 0 ? void 0 : config.operationLocation, resourceLocation: config === null || config === void 0 ? void 0 : config.resourceLocation }, ((config === null || config === void 0 ? void 0 : config.mode) ? { metadata: { mode: config.mode } } : {}));
- },
- poll: lro.sendPollRequest,
- }, {
- intervalInMs,
- withOperationLocation,
- restoreFrom,
- updateState,
- processResult: processResult
- ? ({ flatResponse }, state) => processResult(flatResponse, state)
- : ({ flatResponse }) => flatResponse,
- });
-}
-exports.createHttpPoller = createHttpPoller;
-//# sourceMappingURL=poller.js.map
+// @ts-check
+// ==================================================================================
+// memory.js
+// ----------------------------------------------------------------------------------
+// Description: System Information - library
+// for Node.js
+// Copyright: (c) 2014 - 2025
+// Author: Sebastian Hildebrandt
+// ----------------------------------------------------------------------------------
+// License: MIT
+// ==================================================================================
+// 5. Memory
+// ----------------------------------------------------------------------------------
-/***/ }),
+const os = __nccwpck_require__(70857);
+const exec = (__nccwpck_require__(35317).exec);
+const execSync = (__nccwpck_require__(35317).execSync);
+const util = __nccwpck_require__(77496);
+const fs = __nccwpck_require__(79896);
-/***/ 1814:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+let _platform = process.platform;
+const _linux = (_platform === 'linux' || _platform === 'android');
+const _darwin = (_platform === 'darwin');
+const _windows = (_platform === 'win32');
+const _freebsd = (_platform === 'freebsd');
+const _openbsd = (_platform === 'openbsd');
+const _netbsd = (_platform === 'netbsd');
+const _sunos = (_platform === 'sunos');
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.createHttpPoller = void 0;
-const tslib_1 = __nccwpck_require__(94176);
-var poller_js_1 = __nccwpck_require__(74681);
-Object.defineProperty(exports, "createHttpPoller", ({ enumerable: true, get: function () { return poller_js_1.createHttpPoller; } }));
-/**
- * This can be uncommented to expose the protocol-agnostic poller
- */
-// export {
-// BuildCreatePollerOptions,
-// Operation,
-// CreatePollerOptions,
-// OperationConfig,
-// RestorableOperationState,
-// } from "./poller/models";
-// export { buildCreatePoller } from "./poller/poller";
-/** legacy */
-tslib_1.__exportStar(__nccwpck_require__(5618), exports);
-tslib_1.__exportStar(__nccwpck_require__(25796), exports);
-tslib_1.__exportStar(__nccwpck_require__(67130), exports);
-//# sourceMappingURL=index.js.map
+const OSX_RAM_manufacturers = {
+ '0x014F': 'Transcend Information',
+ '0x2C00': 'Micron Technology Inc.',
+ '0x802C': 'Micron Technology Inc.',
+ '0x80AD': 'Hynix Semiconductor Inc.',
+ '0x80CE': 'Samsung Electronics Inc.',
+ '0xAD00': 'Hynix Semiconductor Inc.',
+ '0xCE00': 'Samsung Electronics Inc.',
+ '0x02FE': 'Elpida',
+ '0x5105': 'Qimonda AG i. In.',
+ '0x8551': 'Qimonda AG i. In.',
+ '0x859B': 'Crucial',
+ '0x04CD': 'G-Skill'
+};
-/***/ }),
+const LINUX_RAM_manufacturers = {
+ '017A': 'Apacer',
+ '0198': 'HyperX',
+ '029E': 'Corsair',
+ '04CB': 'A-DATA',
+ '04CD': 'G-Skill',
+ '059B': 'Crucial',
+ '00CE': 'Samsung',
+ '1315': 'Crucial',
+ '014F': 'Transcend Information',
+ '2C00': 'Micron Technology Inc.',
+ '802C': 'Micron Technology Inc.',
+ '80AD': 'Hynix Semiconductor Inc.',
+ '80CE': 'Samsung Electronics Inc.',
+ 'AD00': 'Hynix Semiconductor Inc.',
+ 'CE00': 'Samsung Electronics Inc.',
+ '02FE': 'Elpida',
+ '5105': 'Qimonda AG i. In.',
+ '8551': 'Qimonda AG i. In.',
+ '859B': 'Crucial'
+};
-/***/ 5618:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+// _______________________________________________________________________________________
+// | R A M | H D |
+// |______________________|_________________________| | |
+// | active buffers/cache | | |
+// |________________________________________________|___________|_________|______________|
+// | used free | used free |
+// |____________________________________________________________|________________________|
+// | total | swap |
+// |____________________________________________________________|________________________|
+
+// free (older versions)
+// ----------------------------------
+// # free
+// total used free shared buffers cached
+// Mem: 16038 (1) 15653 (2) 384 (3) 0 (4) 236 (5) 14788 (6)
+// -/+ buffers/cache: 628 (7) 15409 (8)
+// Swap: 16371 83 16288
+//
+// |------------------------------------------------------------|
+// | R A M |
+// |______________________|_____________________________________|
+// | active (2-(5+6) = 7) | available (3+5+6 = 8) |
+// |______________________|_________________________|___________|
+// | active | buffers/cache (5+6) | |
+// |________________________________________________|___________|
+// | used (2) | free (3) |
+// |____________________________________________________________|
+// | total (1) |
+// |____________________________________________________________|
+//
+// free (since free von procps-ng 3.3.10)
+// ----------------------------------
+// # free
+// total used free shared buffers/cache available
+// Mem: 16038 (1) 628 (2) 386 (3) 0 (4) 15024 (5) 14788 (6)
+// Swap: 16371 83 16288
+//
+// |------------------------------------------------------------|
+// | R A M |
+// |______________________|_____________________________________|
+// | | available (6) estimated |
+// |______________________|_________________________|___________|
+// | active (2) | buffers/cache (5) | free (3) |
+// |________________________________________________|___________|
+// | total (1) |
+// |____________________________________________________________|
+//
+// Reference: http://www.software-architect.net/blog/article/date/2015/06/12/-826c6e5052.html
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.LroEngine = void 0;
-var lroEngine_js_1 = __nccwpck_require__(24203);
-Object.defineProperty(exports, "LroEngine", ({ enumerable: true, get: function () { return lroEngine_js_1.LroEngine; } }));
-//# sourceMappingURL=index.js.map
+// /procs/meminfo - sample (all in kB)
+//
+// MemTotal: 32806380 kB
+// MemFree: 17977744 kB
+// MemAvailable: 19768972 kB
+// Buffers: 517028 kB
+// Cached: 2161876 kB
+// SwapCached: 456 kB
+// Active: 12081176 kB
+// Inactive: 2164616 kB
+// Active(anon): 10832884 kB
+// Inactive(anon): 1477272 kB
+// Active(file): 1248292 kB
+// Inactive(file): 687344 kB
+// Unevictable: 0 kB
+// Mlocked: 0 kB
+// SwapTotal: 16768892 kB
+// SwapFree: 16768304 kB
+// Dirty: 268 kB
+// Writeback: 0 kB
+// AnonPages: 11568832 kB
+// Mapped: 719992 kB
+// Shmem: 743272 kB
+// Slab: 335716 kB
+// SReclaimable: 256364 kB
+// SUnreclaim: 79352 kB
-/***/ }),
+function mem(callback) {
-/***/ 24203:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+ let result = {
+ total: os.totalmem(),
+ free: os.freemem(),
+ used: os.totalmem() - os.freemem(),
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.LroEngine = void 0;
-const operation_js_1 = __nccwpck_require__(52175);
-const constants_js_1 = __nccwpck_require__(94288);
-const poller_js_1 = __nccwpck_require__(25796);
-const operation_js_2 = __nccwpck_require__(26588);
-/**
- * The LRO Engine, a class that performs polling.
- */
-class LroEngine extends poller_js_1.Poller {
- constructor(lro, options) {
- const { intervalInMs = constants_js_1.POLL_INTERVAL_IN_MS, resumeFrom, resolveOnUnsuccessful = false, isDone, lroResourceLocationConfig, processResult, updateState, } = options || {};
- const state = resumeFrom
- ? (0, operation_js_2.deserializeState)(resumeFrom)
- : {};
- const operation = new operation_js_1.GenericPollOperation(state, lro, !resolveOnUnsuccessful, lroResourceLocationConfig, processResult, updateState, isDone);
- super(operation);
- this.resolveOnUnsuccessful = resolveOnUnsuccessful;
- this.config = { intervalInMs: intervalInMs };
- operation.setPollerConfig(this.config);
- }
- /**
- * The method used by the poller to wait before attempting to update its operation.
- */
- delay() {
- return new Promise((resolve) => setTimeout(() => resolve(), this.config.intervalInMs));
- }
-}
-exports.LroEngine = LroEngine;
-//# sourceMappingURL=lroEngine.js.map
+ active: os.totalmem() - os.freemem(), // temporarily (fallback)
+ available: os.freemem(), // temporarily (fallback)
+ buffers: 0,
+ cached: 0,
+ slab: 0,
+ buffcache: 0,
-/***/ }),
+ swaptotal: 0,
+ swapused: 0,
+ swapfree: 0,
+ writeback: null,
+ dirty: null
+ };
+
+ if (_linux) {
+ try {
+ fs.readFile('/proc/meminfo', function (error, stdout) {
+ if (!error) {
+ const lines = stdout.toString().split('\n');
+ result.total = parseInt(util.getValue(lines, 'memtotal'), 10);
+ result.total = result.total ? result.total * 1024 : os.totalmem();
+ result.free = parseInt(util.getValue(lines, 'memfree'), 10);
+ result.free = result.free ? result.free * 1024 : os.freemem();
+ result.used = result.total - result.free;
+
+ result.buffers = parseInt(util.getValue(lines, 'buffers'), 10);
+ result.buffers = result.buffers ? result.buffers * 1024 : 0;
+ result.cached = parseInt(util.getValue(lines, 'cached'), 10);
+ result.cached = result.cached ? result.cached * 1024 : 0;
+ result.slab = parseInt(util.getValue(lines, 'slab'), 10);
+ result.slab = result.slab ? result.slab * 1024 : 0;
+ result.buffcache = result.buffers + result.cached + result.slab;
+
+ let available = parseInt(util.getValue(lines, 'memavailable'), 10);
+ result.available = available ? available * 1024 : result.free + result.buffcache;
+ result.active = result.total - result.available;
+
+ result.swaptotal = parseInt(util.getValue(lines, 'swaptotal'), 10);
+ result.swaptotal = result.swaptotal ? result.swaptotal * 1024 : 0;
+ result.swapfree = parseInt(util.getValue(lines, 'swapfree'), 10);
+ result.swapfree = result.swapfree ? result.swapfree * 1024 : 0;
+ result.swapused = result.swaptotal - result.swapfree;
+ result.writeback = parseInt(util.getValue(lines, 'writeback'), 10);
+ result.writeback = result.writeback ? result.writeback * 1024 : 0;
+ result.dirty = parseInt(util.getValue(lines, 'dirty'), 10);
+ result.dirty = result.dirty ? result.dirty * 1024 : 0;
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_freebsd || _openbsd || _netbsd) {
+ try {
+ exec('/sbin/sysctl hw.realmem hw.physmem vm.stats.vm.v_page_count vm.stats.vm.v_wire_count vm.stats.vm.v_active_count vm.stats.vm.v_inactive_count vm.stats.vm.v_cache_count vm.stats.vm.v_free_count vm.stats.vm.v_page_size', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ const pagesize = parseInt(util.getValue(lines, 'vm.stats.vm.v_page_size'), 10);
+ const inactive = parseInt(util.getValue(lines, 'vm.stats.vm.v_inactive_count'), 10) * pagesize;
+ const cache = parseInt(util.getValue(lines, 'vm.stats.vm.v_cache_count'), 10) * pagesize;
+
+ result.total = parseInt(util.getValue(lines, 'hw.realmem'), 10);
+ if (isNaN(result.total)) { result.total = parseInt(util.getValue(lines, 'hw.physmem'), 10); }
+ result.free = parseInt(util.getValue(lines, 'vm.stats.vm.v_free_count'), 10) * pagesize;
+ result.buffcache = inactive + cache;
+ result.available = result.buffcache + result.free;
+ result.active = result.total - result.free - result.buffcache;
+
+ result.swaptotal = 0;
+ result.swapfree = 0;
+ result.swapused = 0;
+
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_sunos) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ if (_darwin) {
+ let pageSize = 4096;
+ try {
+ let sysPpageSize = util.toInt(execSync('sysctl -n vm.pagesize').toString());
+ pageSize = sysPpageSize || pageSize;
+ } catch (e) {
+ util.noop();
+ }
+ try {
+ exec('vm_stat 2>/dev/null | grep "Pages active"', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+
+ result.active = parseInt(lines[0].split(':')[1], 10) * pageSize;
+ result.buffcache = result.used - result.active;
+ result.available = result.free + result.buffcache;
+ }
+ exec('sysctl -n vm.swapusage 2>/dev/null', function (error, stdout) {
+ if (!error) {
+ let lines = stdout.toString().split('\n');
+ if (lines.length > 0) {
+ let firstline = lines[0].replace(/,/g, '.').replace(/M/g, '');
+ let lineArray = firstline.trim().split(' ');
+ lineArray.forEach(line => {
+ if (line.toLowerCase().indexOf('total') !== -1) { result.swaptotal = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
+ if (line.toLowerCase().indexOf('used') !== -1) { result.swapused = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
+ if (line.toLowerCase().indexOf('free') !== -1) { result.swapfree = parseFloat(line.split('=')[1].trim()) * 1024 * 1024; }
+ });
+ }
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ if (_windows) {
+ let swaptotal = 0;
+ let swapused = 0;
+ try {
+ util.powerShell('Get-CimInstance Win32_PageFileUsage | Select AllocatedBaseSize, CurrentUsage').then((stdout, error) => {
+ if (!error) {
+ let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
+ lines.forEach(function (line) {
+ if (line !== '') {
+ line = line.trim().split(/\s\s+/);
+ swaptotal = swaptotal + (parseInt(line[0], 10) || 0);
+ swapused = swapused + (parseInt(line[1], 10) || 0);
+ }
+ });
+ }
+ result.swaptotal = swaptotal * 1024 * 1024;
+ result.swapused = swapused * 1024 * 1024;
+ result.swapfree = result.swaptotal - result.swapused;
+
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ } catch (e) {
+ if (callback) { callback(result); }
+ resolve(result);
+ }
+ }
+ });
+ });
+}
-/***/ 52175:
-/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => {
+exports.mem = mem;
+function memLayout(callback) {
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.GenericPollOperation = void 0;
-const operation_js_1 = __nccwpck_require__(27826);
-const logger_js_1 = __nccwpck_require__(80692);
-const createStateProxy = () => ({
- initState: (config) => ({ config, isStarted: true }),
- setCanceled: (state) => (state.isCancelled = true),
- setError: (state, error) => (state.error = error),
- setResult: (state, result) => (state.result = result),
- setRunning: (state) => (state.isStarted = true),
- setSucceeded: (state) => (state.isCompleted = true),
- setFailed: () => {
- /** empty body */
- },
- getError: (state) => state.error,
- getResult: (state) => state.result,
- isCanceled: (state) => !!state.isCancelled,
- isFailed: (state) => !!state.error,
- isRunning: (state) => !!state.isStarted,
- isSucceeded: (state) => Boolean(state.isCompleted && !state.isCancelled && !state.error),
-});
-class GenericPollOperation {
- constructor(state, lro, setErrorAsResult, lroResourceLocationConfig, processResult, updateState, isDone) {
- this.state = state;
- this.lro = lro;
- this.setErrorAsResult = setErrorAsResult;
- this.lroResourceLocationConfig = lroResourceLocationConfig;
- this.processResult = processResult;
- this.updateState = updateState;
- this.isDone = isDone;
+ function getManufacturerDarwin(manId) {
+ if ({}.hasOwnProperty.call(OSX_RAM_manufacturers, manId)) {
+ return (OSX_RAM_manufacturers[manId]);
}
- setPollerConfig(pollerConfig) {
- this.pollerConfig = pollerConfig;
+ return manId;
+ }
+
+ function getManufacturerLinux(manId) {
+ const manIdSearch = manId.replace('0x', '').toUpperCase();
+ if (manIdSearch.length === 4 && {}.hasOwnProperty.call(LINUX_RAM_manufacturers, manIdSearch)) {
+ return (LINUX_RAM_manufacturers[manIdSearch]);
}
- async update(options) {
- var _a;
- const stateProxy = createStateProxy();
- if (!this.state.isStarted) {
- this.state = Object.assign(Object.assign({}, this.state), (await (0, operation_js_1.initHttpOperation)({
- lro: this.lro,
- stateProxy,
- resourceLocationConfig: this.lroResourceLocationConfig,
- processResult: this.processResult,
- setErrorAsResult: this.setErrorAsResult,
- })));
- }
- const updateState = this.updateState;
- const isDone = this.isDone;
- if (!this.state.isCompleted && this.state.error === undefined) {
- await (0, operation_js_1.pollHttpOperation)({
- lro: this.lro,
- state: this.state,
- stateProxy,
- processResult: this.processResult,
- updateState: updateState
- ? (state, { rawResponse }) => updateState(state, rawResponse)
- : undefined,
- isDone: isDone
- ? ({ flatResponse }, state) => isDone(flatResponse, state)
- : undefined,
- options,
- setDelay: (intervalInMs) => {
- this.pollerConfig.intervalInMs = intervalInMs;
- },
- setErrorAsResult: this.setErrorAsResult,
+ return manId;
+ }
+
+ return new Promise((resolve) => {
+ process.nextTick(() => {
+
+ let result = [];
+
+ if (_linux || _freebsd || _openbsd || _netbsd) {
+ exec('export LC_ALL=C; dmidecode -t memory 2>/dev/null | grep -iE "Size:|Type|Speed|Manufacturer|Form Factor|Locator|Memory Device|Serial Number|Voltage|Part Number"; unset LC_ALL', function (error, stdout) {
+ if (!error) {
+ let devices = stdout.toString().split('Memory Device');
+ devices.shift();
+ devices.forEach(function (device) {
+ let lines = device.split('\n');
+ const sizeString = util.getValue(lines, 'Size');
+ const size = sizeString.indexOf('GB') >= 0 ? parseInt(sizeString, 10) * 1024 * 1024 * 1024 : parseInt(sizeString, 10) * 1024 * 1024;
+ let bank = util.getValue(lines, 'Bank Locator');
+ if (bank.toLowerCase().indexOf('bad') >= 0) {
+ bank = '';
+ }
+ if (parseInt(util.getValue(lines, 'Size'), 10) > 0) {
+ const totalWidth = util.toInt(util.getValue(lines, 'Total Width'));
+ const dataWidth = util.toInt(util.getValue(lines, 'Data Width'));
+ result.push({
+ size,
+ bank,
+ type: util.getValue(lines, 'Type:'),
+ ecc: dataWidth && totalWidth ? totalWidth > dataWidth : false,
+ clockSpeed: (util.getValue(lines, 'Configured Clock Speed:') ? parseInt(util.getValue(lines, 'Configured Clock Speed:'), 10) : (util.getValue(lines, 'Speed:') ? parseInt(util.getValue(lines, 'Speed:'), 10) : null)),
+ formFactor: util.getValue(lines, 'Form Factor:'),
+ manufacturer: getManufacturerLinux(util.getValue(lines, 'Manufacturer:')),
+ partNum: util.getValue(lines, 'Part Number:'),
+ serialNum: util.getValue(lines, 'Serial Number:'),
+ voltageConfigured: parseFloat(util.getValue(lines, 'Configured Voltage:')) || null,
+ voltageMin: parseFloat(util.getValue(lines, 'Minimum Voltage:')) || null,
+ voltageMax: parseFloat(util.getValue(lines, 'Maximum Voltage:')) || null,
+ });
+ } else {
+ result.push({
+ size: 0,
+ bank,
+ type: 'Empty',
+ ecc: null,
+ clockSpeed: 0,
+ formFactor: util.getValue(lines, 'Form Factor:'),
+ partNum: '',
+ serialNum: '',
+ voltageConfigured: null,
+ voltageMin: null,
+ voltageMax: null,
+ });
+ }
+ });
+ }
+ if (!result.length) {
+ result.push({
+ size: os.totalmem(),
+ bank: '',
+ type: '',
+ ecc: null,
+ clockSpeed: 0,
+ formFactor: '',
+ partNum: '',
+ serialNum: '',
+ voltageConfigured: null,
+ voltageMin: null,
+ voltageMax: null,
});
- }
- (_a = options === null || options === void 0 ? void 0 : options.fireProgress) === null || _a === void 0 ? void 0 : _a.call(options, this.state);
- return this;
- }
- async cancel() {
- logger_js_1.logger.error("`cancelOperation` is deprecated because it wasn't implemented");
- return this;
- }
- /**
- * Serializes the Poller operation.
- */
- toString() {
- return JSON.stringify({
- state: this.state,
- });
- }
-}
-exports.GenericPollOperation = GenericPollOperation;
-//# sourceMappingURL=operation.js.map
-/***/ }),
+ // Try Raspberry PI
+ try {
+ let stdout = execSync('cat /proc/cpuinfo 2>/dev/null', util.execOptsLinux);
+ let lines = stdout.toString().split('\n');
+ let model = util.getValue(lines, 'hardware', ':', true).toUpperCase();
+ let version = util.getValue(lines, 'revision', ':', true).toLowerCase();
-/***/ 67130:
-/***/ ((__unused_webpack_module, exports) => {
+ if (model === 'BCM2835' || model === 'BCM2708' || model === 'BCM2709' || model === 'BCM2835' || model === 'BCM2837') {
+ const clockSpeed = {
+ '0': 400,
+ '1': 450,
+ '2': 450,
+ '3': 3200
+ };
+ result[0].type = 'LPDDR2';
+ result[0].type = version && version[2] && version[2] === '3' ? 'LPDDR4' : result[0].type;
+ result[0].ecc = false;
+ result[0].clockSpeed = version && version[2] && clockSpeed[version[2]] || 400;
+ result[0].clockSpeed = version && version[4] && version[4] === 'd' ? 500 : result[0].clockSpeed;
+ result[0].formFactor = 'SoC';
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-//# sourceMappingURL=pollOperation.js.map
+ stdout = execSync('vcgencmd get_config sdram_freq 2>/dev/null', util.execOptsLinux);
+ lines = stdout.toString().split('\n');
+ let freq = parseInt(util.getValue(lines, 'sdram_freq', '=', true), 10) || 0;
+ if (freq) {
+ result[0].clockSpeed = freq;
+ }
-/***/ }),
+ stdout = execSync('vcgencmd measure_volts sdram_p 2>/dev/null', util.execOptsLinux);
+ lines = stdout.toString().split('\n');
+ let voltage = parseFloat(util.getValue(lines, 'volt', '=', true)) || 0;
+ if (voltage) {
+ result[0].voltageConfigured = voltage;
+ result[0].voltageMin = voltage;
+ result[0].voltageMax = voltage;
+ }
+ }
+ } catch (e) {
+ util.noop();
+ }
-/***/ 25796:
-/***/ ((__unused_webpack_module, exports) => {
+ }
+ if (callback) { callback(result); }
+ resolve(result);
+ });
+ }
+ if (_darwin) {
+ exec('system_profiler SPMemoryDataType', function (error, stdout) {
+ if (!error) {
+ const allLines = stdout.toString().split('\n');
+ const eccStatus = util.getValue(allLines, 'ecc', ':', true).toLowerCase();
+ let devices = stdout.toString().split(' BANK ');
+ let hasBank = true;
+ if (devices.length === 1) {
+ devices = stdout.toString().split(' DIMM');
+ hasBank = false;
+ }
+ devices.shift();
+ devices.forEach(function (device) {
+ let lines = device.split('\n');
+ const bank = (hasBank ? 'BANK ' : 'DIMM') + lines[0].trim().split('/')[0];
+ const size = parseInt(util.getValue(lines, ' Size'));
+ if (size) {
+ result.push({
+ size: size * 1024 * 1024 * 1024,
+ bank: bank,
+ type: util.getValue(lines, ' Type:'),
+ ecc: eccStatus ? eccStatus === 'enabled' : null,
+ clockSpeed: parseInt(util.getValue(lines, ' Speed:'), 10),
+ formFactor: '',
+ manufacturer: getManufacturerDarwin(util.getValue(lines, ' Manufacturer:')),
+ partNum: util.getValue(lines, ' Part Number:'),
+ serialNum: util.getValue(lines, ' Serial Number:'),
+ voltageConfigured: null,
+ voltageMin: null,
+ voltageMax: null,
+ });
+ } else {
+ result.push({
+ size: 0,
+ bank: bank,
+ type: 'Empty',
+ ecc: null,
+ clockSpeed: 0,
+ formFactor: '',
+ manufacturer: '',
+ partNum: '',
+ serialNum: '',
+ voltageConfigured: null,
+ voltageMin: null,
+ voltageMax: null,
+ });
+ }
+ });
+ }
+ if (!result.length) {
+ const lines = stdout.toString().split('\n');
+ const size = parseInt(util.getValue(lines, ' Memory:'));
+ const type = util.getValue(lines, ' Type:');
+ const manufacturerId = util.getValue(lines, ' Manufacturer:');
+ if (size && type) {
+ result.push({
+ size: size * 1024 * 1024 * 1024,
+ bank: '0',
+ type,
+ ecc: false,
+ clockSpeed: null,
+ formFactor: 'SOC',
+ manufacturer: getManufacturerDarwin(manufacturerId),
+ partNum: '',
+ serialNum: '',
+ voltageConfigured: null,
+ voltageMin: null,
+ voltageMax: null,
+ });
-// Copyright (c) Microsoft Corporation.
-// Licensed under the MIT license.
-Object.defineProperty(exports, "__esModule", ({ value: true }));
-exports.Poller = exports.PollerCancelledError = exports.PollerStoppedError = void 0;
-/**
- * When a poller is manually stopped through the `stopPolling` method,
- * the poller will be rejected with an instance of the PollerStoppedError.
- */
-class PollerStoppedError extends Error {
- constructor(message) {
- super(message);
- this.name = "PollerStoppedError";
- Object.setPrototypeOf(this, PollerStoppedError.prototype);
- }
-}
-exports.PollerStoppedError = PollerStoppedError;
-/**
- * When the operation is cancelled, the poller will be rejected with an instance
- * of the PollerCancelledError.
- */
-class PollerCancelledError extends Error {
- constructor(message) {
- super(message);
- this.name = "PollerCancelledError";
- Object.setPrototypeOf(this, PollerCancelledError.prototype);
- }
-}
-exports.PollerCancelledError = PollerCancelledError;
-/**
- * A class that represents the definition of a program that polls through consecutive requests
- * until it reaches a state of completion.
- *
- * A poller can be executed manually, by polling request by request by calling to the `poll()` method repeatedly, until its operation is completed.
- * It also provides a way to wait until the operation completes, by calling `pollUntilDone()` and waiting until the operation finishes.
- * Pollers can also request the cancellation of the ongoing process to whom is providing the underlying long running operation.
- *
- * ```ts
- * const poller = new MyPoller();
- *
- * // Polling just once:
- * await poller.poll();
- *
- * // We can try to cancel the request here, by calling:
- * //
- * // await poller.cancelOperation();
- * //
- *
- * // Getting the final result:
- * const result = await poller.pollUntilDone();
- * ```
- *
- * The Poller is defined by two types, a type representing the state of the poller, which
- * must include a basic set of properties from `PollOperationState`,
- * and a return type defined by `TResult`, which can be anything.
- *
- * The Poller class implements the `PollerLike` interface, which allows poller implementations to avoid having
- * to export the Poller's class directly, and instead only export the already instantiated poller with the PollerLike type.
- *
- * ```ts
- * class Client {
- * public async makePoller: PollerLike {
- * const poller = new MyPoller({});
- * // It might be preferred to return the poller after the first request is made,
- * // so that some information can be obtained right away.
- * await poller.poll();
- * return poller;
- * }
- * }
- *
- * const poller: PollerLike = myClient.makePoller();
- * ```
- *
- * A poller can be created through its constructor, then it can be polled until it's completed.
- * At any point in time, the state of the poller can be obtained without delay through the getOperationState method.
- * At any point in time, the intermediate forms of the result type can be requested without delay.
- * Once the underlying operation is marked as completed, the poller will stop and the final value will be returned.
- *
- * ```ts
- * const poller = myClient.makePoller();
- * const state: MyOperationState = poller.getOperationState();
- *
- * // The intermediate result can be obtained at any time.
- * const result: MyResult | undefined = poller.getResult();
- *
- * // The final result can only be obtained after the poller finishes.
- * const result: MyResult = await poller.pollUntilDone();
- * ```
- *
- */
-// eslint-disable-next-line no-use-before-define
-class Poller {
- /**
- * A poller needs to be initialized by passing in at least the basic properties of the `PollOperation