var __bare_os_bundle_exports__ = (() => { var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x + '" is not supported'); }); var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require2() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // ../../node_modules/bare-prom-client/lib/util.js var require_util = __commonJS({ "../../node_modules/bare-prom-client/lib/util.js"(exports) { "use strict"; exports.getValueAsString = function getValueString(value) { if (Number.isNaN(value)) { return "Nan"; } else if (!Number.isFinite(value)) { if (value < 0) { return "-Inf"; } else { return "+Inf"; } } else { return `${value}`; } }; exports.removeLabels = function removeLabels(hashMap, labels, sortedLabelNames) { const hash = hashObject(labels, sortedLabelNames); delete hashMap[hash]; }; exports.setValue = function setValue(hashMap, value, labels) { const hash = hashObject(labels); hashMap[hash] = { value: typeof value === "number" ? value : 0, labels: labels || {} }; return hashMap; }; exports.setValueDelta = function setValueDelta(hashMap, deltaValue, labels, hash = "") { const value = typeof deltaValue === "number" ? deltaValue : 0; if (hashMap[hash]) { hashMap[hash].value += value; } else { hashMap[hash] = { value, labels }; } return hashMap; }; exports.getLabels = function(labelNames, args) { if (typeof args[0] === "object") { return args[0]; } if (labelNames.length !== args.length) { throw new Error( `Invalid number of arguments (${args.length}): "${args.join( ", " )}" for label names (${labelNames.length}): "${labelNames.join(", ")}".` ); } const acc = {}; for (let i = 0; i < labelNames.length; i++) { acc[labelNames[i]] = args[i]; } return acc; }; function fastHashObject(keys, labels) { if (keys.length === 0) { return ""; } let hash = ""; for (let i = 0; i < keys.length; i++) { const key = keys[i]; const value = labels[key]; if (value === void 0) continue; hash += `${key}:${value},`; } return hash; } function hashObject(labels, labelNames) { if (labelNames) { return fastHashObject(labelNames, labels); } const keys = Object.keys(labels); if (keys.length > 1) { keys.sort(); } return fastHashObject(keys, labels); } exports.hashObject = hashObject; exports.isObject = function isObject(obj) { return obj !== null && typeof obj === "object"; }; exports.nowTimestamp = function nowTimestamp() { return Date.now() / 1e3; }; var Grouper = class extends Map { /** * Adds the `value` to the `key`'s array of values. * @param {*} key Key to set. * @param {*} value Value to add to `key`'s array. * @returns {undefined} undefined. */ add(key, value) { if (this.has(key)) { this.get(key).push(value); } else { this.set(key, [value]); } } }; exports.Grouper = Grouper; } }); // ../../node_modules/bare-prom-client/lib/registry.js var require_registry = __commonJS({ "../../node_modules/bare-prom-client/lib/registry.js"(exports, module) { "use strict"; var { getValueAsString } = require_util(); var Registry = class _Registry { static get PROMETHEUS_CONTENT_TYPE() { return "text/plain; version=0.0.4; charset=utf-8"; } static get OPENMETRICS_CONTENT_TYPE() { return "application/openmetrics-text; version=1.0.0; charset=utf-8"; } constructor(regContentType = _Registry.PROMETHEUS_CONTENT_TYPE) { this._metrics = {}; this._collectors = []; this._defaultLabels = {}; if (regContentType !== _Registry.PROMETHEUS_CONTENT_TYPE && regContentType !== _Registry.OPENMETRICS_CONTENT_TYPE) { throw new TypeError(`Content type ${regContentType} is unsupported`); } this._contentType = regContentType; } getMetricsAsArray() { return Object.values(this._metrics); } async getMetricsAsString(metrics2) { const metric = typeof metrics2.getForPromString === "function" ? await metrics2.getForPromString() : await metrics2.get(); const name = escapeString(metric.name); const help = `# HELP ${name} ${escapeString(metric.help)}`; const type = `# TYPE ${name} ${metric.type}`; const values = [help, type]; const defaultLabels = Object.keys(this._defaultLabels).length > 0 ? this._defaultLabels : null; const isOpenMetrics = this.contentType === _Registry.OPENMETRICS_CONTENT_TYPE; for (const val of metric.values || []) { let { metricName = name, labels = {} } = val; const { sharedLabels = {} } = val; if (isOpenMetrics && metric.type === "counter") { metricName = `${metricName}_total`; } if (defaultLabels) { labels = { ...labels, ...defaultLabels, ...labels }; } const formattedLabels = formatLabels(labels, sharedLabels); const flattenedShared = flattenSharedLabels(sharedLabels); const labelParts = [...formattedLabels, flattenedShared].filter(Boolean); const labelsString = labelParts.length ? `{${labelParts.join(",")}}` : ""; let fullMetricLine = `${metricName}${labelsString} ${getValueAsString( val.value )}`; const { exemplar } = val; if (exemplar && isOpenMetrics) { const formattedExemplars = formatLabels(exemplar.labelSet); fullMetricLine += ` # {${formattedExemplars.join( "," )}} ${getValueAsString(exemplar.value)} ${exemplar.timestamp}`; } values.push(fullMetricLine); } return values.join("\n"); } async metrics() { const isOpenMetrics = this.contentType === _Registry.OPENMETRICS_CONTENT_TYPE; const promises = this.getMetricsAsArray().map((metric) => { if (isOpenMetrics && metric.type === "counter") { metric.name = standardizeCounterName(metric.name); } return this.getMetricsAsString(metric); }); const resolves = await Promise.all(promises); return isOpenMetrics ? `${resolves.join("\n")} # EOF ` : `${resolves.join("\n\n")} `; } registerMetric(metric) { if (this._metrics[metric.name] && this._metrics[metric.name] !== metric) { throw new Error( `A metric with the name ${metric.name} has already been registered.` ); } this._metrics[metric.name] = metric; } clear() { this._metrics = {}; this._defaultLabels = {}; } async getMetricsAsJSON() { const metrics2 = []; const defaultLabelNames = Object.keys(this._defaultLabels); const promises = []; for (const metric of this.getMetricsAsArray()) { promises.push(metric.get()); } const resolves = await Promise.all(promises); for (const item of resolves) { if (item.values && defaultLabelNames.length > 0) { for (const val of item.values) { val.labels = Object.assign({}, val.labels); for (const labelName of defaultLabelNames) { val.labels[labelName] = val.labels[labelName] || this._defaultLabels[labelName]; } } } metrics2.push(item); } return metrics2; } removeSingleMetric(name) { delete this._metrics[name]; } getSingleMetricAsString(name) { return this.getMetricsAsString(this._metrics[name]); } getSingleMetric(name) { return this._metrics[name]; } setDefaultLabels(labels) { this._defaultLabels = labels; } resetMetrics() { for (const metric in this._metrics) { this._metrics[metric].reset(); } } get contentType() { return this._contentType; } setContentType(metricsContentType) { if (metricsContentType === _Registry.OPENMETRICS_CONTENT_TYPE || metricsContentType === _Registry.PROMETHEUS_CONTENT_TYPE) { this._contentType = metricsContentType; } else { throw new Error(`Content type ${metricsContentType} is unsupported`); } } static merge(registers) { const regType = registers[0].contentType; for (const reg of registers) { if (reg.contentType !== regType) { throw new Error( "Registers can only be merged if they have the same content type" ); } } const mergedRegistry = new _Registry(regType); const metricsToMerge = registers.reduce( (acc, reg) => acc.concat(reg.getMetricsAsArray()), [] ); metricsToMerge.forEach(mergedRegistry.registerMetric, mergedRegistry); return mergedRegistry; } }; function formatLabels(labels, exclude) { const { hasOwnProperty } = Object.prototype; const formatted = []; for (const [name, value] of Object.entries(labels)) { if (!exclude || !hasOwnProperty.call(exclude, name)) { formatted.push(`${name}="${escapeLabelValue(value)}"`); } } return formatted; } var sharedLabelCache = /* @__PURE__ */ new WeakMap(); function flattenSharedLabels(labels) { const cached = sharedLabelCache.get(labels); if (cached) { return cached; } const formattedLabels = formatLabels(labels); const flattened = formattedLabels.join(","); sharedLabelCache.set(labels, flattened); return flattened; } function escapeLabelValue(str) { if (typeof str !== "string") { return str; } return escapeString(str).replace(/"/g, '\\"'); } function escapeString(str) { return str.replace(/\\/g, "\\\\").replace(/\n/g, "\\n"); } function standardizeCounterName(name) { return name.replace(/_total$/, ""); } module.exports = Registry; module.exports.globalRegistry = new Registry(); } }); // ../../node_modules/bare-prom-client/lib/validation.js var require_validation = __commonJS({ "../../node_modules/bare-prom-client/lib/validation.js"(exports) { "use strict"; var util = __require("util"); var metricRegexp = /^[a-zA-Z_:][a-zA-Z0-9_:]*$/; var labelRegexp = /^[a-zA-Z_][a-zA-Z0-9_]*$/; exports.validateMetricName = function(name) { return metricRegexp.test(name); }; exports.validateLabelName = function(names = []) { return names.every((name) => labelRegexp.test(name)); }; exports.validateLabel = function validateLabel(savedLabels, labels) { for (const label in labels) { if (!savedLabels.includes(label)) { throw new Error( `Added label "${label}" is not included in initial labelset: ${util.inspect( savedLabels )}` ); } } }; } }); // ../../node_modules/bare-prom-client/lib/metric.js var require_metric = __commonJS({ "../../node_modules/bare-prom-client/lib/metric.js"(exports, module) { "use strict"; var Registry = require_registry(); var { isObject } = require_util(); var { validateMetricName, validateLabelName } = require_validation(); var Metric = class { constructor(config, defaults = {}) { if (!isObject(config)) { throw new TypeError("constructor expected a config object"); } Object.assign( this, { labelNames: [], registers: [Registry.globalRegistry], aggregator: "sum", enableExemplars: false }, defaults, config ); if (!this.registers) { this.registers = [Registry.globalRegistry]; } if (!this.help) { throw new Error("Missing mandatory help parameter"); } if (!this.name) { throw new Error("Missing mandatory name parameter"); } if (!validateMetricName(this.name)) { throw new Error("Invalid metric name"); } if (!validateLabelName(this.labelNames)) { throw new Error("Invalid label name"); } if (this.collect && typeof this.collect !== "function") { throw new Error('Optional "collect" parameter must be a function'); } if (this.labelNames) { this.sortedLabelNames = [...this.labelNames].sort(); } else { this.sortedLabelNames = []; } this.reset(); for (const register of this.registers) { if (this.enableExemplars && register.contentType === Registry.PROMETHEUS_CONTENT_TYPE) { throw new TypeError( "Exemplars are supported only on OpenMetrics registries" ); } register.registerMetric(this); } } reset() { } }; module.exports = { Metric }; } }); // ../../node_modules/bare-prom-client/lib/exemplar.js var require_exemplar = __commonJS({ "../../node_modules/bare-prom-client/lib/exemplar.js"(exports, module) { "use strict"; var Exemplar = class { constructor(labelSet = {}, value = null) { this.labelSet = labelSet; this.value = value; } /** * Validation for the label set format. * https://github.com/OpenObservability/OpenMetrics/blob/d99b705f611b75fec8f450b05e344e02eea6921d/specification/OpenMetrics.md#exemplars * * @param {object} labelSet - Exemplar labels. * @throws {RangeError} * @return {void} */ validateExemplarLabelSet(labelSet) { let res = ""; for (const [labelName, labelValue] of Object.entries(labelSet)) { res += `${labelName}${labelValue}`; } if (res.length > 128) { throw new RangeError( "Label set size must be smaller than 128 UTF-8 chars" ); } } }; module.exports = Exemplar; } }); // ../../node_modules/bare-prom-client/lib/counter.js var require_counter = __commonJS({ "../../node_modules/bare-prom-client/lib/counter.js"(exports, module) { "use strict"; var util = __require("util"); var { hashObject, isObject, getLabels, removeLabels, nowTimestamp } = require_util(); var { validateLabel } = require_validation(); var { Metric } = require_metric(); var Exemplar = require_exemplar(); var Counter = class extends Metric { constructor(config) { super(config); this.type = "counter"; this.defaultLabels = {}; this.defaultValue = 1; this.defaultExemplarLabelSet = {}; if (config.enableExemplars) { this.enableExemplars = true; this.inc = this.incWithExemplar; } else { this.inc = this.incWithoutExemplar; } } /** * Increment counter * @param {object} labels - What label you want to be incremented * @param {Number} value - Value to increment, if omitted increment with 1 * @returns {object} results - object with information about the inc operation * @returns {string} results.labelHash - hash representation of the labels */ incWithoutExemplar(labels, value) { let hash = ""; if (isObject(labels)) { hash = hashObject(labels, this.sortedLabelNames); validateLabel(this.labelNames, labels); } else { value = labels; labels = {}; } if (value && !Number.isFinite(value)) { throw new TypeError(`Value is not a valid number: ${util.format(value)}`); } if (value < 0) { throw new Error("It is not possible to decrease a counter"); } if (value === null || value === void 0) value = 1; setValue(this.hashMap, value, labels, hash); return { labelHash: hash }; } /** * Increment counter with exemplar, same as inc but accepts labels for an * exemplar. * If no label is provided the current exemplar labels are kept unchanged * (defaults to empty set). * * @param {object} incOpts - Object with options about what metric to increase * @param {object} incOpts.labels - What label you want to be incremented, * defaults to null (metric with no labels) * @param {Number} incOpts.value - Value to increment, defaults to 1 * @param {object} incOpts.exemplarLabels - Key-value labels for the * exemplar, defaults to empty set {} * @returns {void} */ incWithExemplar({ labels = this.defaultLabels, value = this.defaultValue, exemplarLabels = this.defaultExemplarLabelSet } = {}) { const res = this.incWithoutExemplar(labels, value); this.updateExemplar(exemplarLabels, value, res.labelHash); } updateExemplar(exemplarLabels, value, hash) { if (exemplarLabels === this.defaultExemplarLabelSet) return; if (!isObject(this.hashMap[hash].exemplar)) { this.hashMap[hash].exemplar = new Exemplar(); } this.hashMap[hash].exemplar.validateExemplarLabelSet(exemplarLabels); this.hashMap[hash].exemplar.labelSet = exemplarLabels; this.hashMap[hash].exemplar.value = value ? value : 1; this.hashMap[hash].exemplar.timestamp = nowTimestamp(); } /** * Reset counter * @returns {void} */ reset() { this.hashMap = {}; if (this.labelNames.length === 0) { setValue(this.hashMap, 0); } } async get() { if (this.collect) { const v = this.collect(); if (v instanceof Promise) await v; } return { help: this.help, name: this.name, type: this.type, values: Object.values(this.hashMap), aggregator: this.aggregator }; } labels(...args) { const labels = getLabels(this.labelNames, args) || {}; return { inc: this.inc.bind(this, labels) }; } remove(...args) { const labels = getLabels(this.labelNames, args) || {}; validateLabel(this.labelNames, labels); return removeLabels.call(this, this.hashMap, labels, this.sortedLabelNames); } }; function setValue(hashMap, value, labels = {}, hash = "") { if (hashMap[hash]) { hashMap[hash].value += value; } else { hashMap[hash] = { value, labels }; } return hashMap; } module.exports = Counter; } }); // ../../node_modules/bare-prom-client/lib/gauge.js var require_gauge = __commonJS({ "../../node_modules/bare-prom-client/lib/gauge.js"(exports, module) { "use strict"; var process = __require("process"); var util = __require("util"); var { setValue, setValueDelta, getLabels, hashObject, isObject, removeLabels } = require_util(); var { validateLabel } = require_validation(); var { Metric } = require_metric(); var Gauge = class extends Metric { constructor(config) { super(config); this.type = "gauge"; } /** * Set a gauge to a value * @param {object} labels - Object with labels and their values * @param {Number} value - Value to set the gauge to, must be positive * @returns {void} */ set(labels, value) { value = getValueArg(labels, value); labels = getLabelArg(labels); set(this, labels, value); } /** * Reset gauge * @returns {void} */ reset() { this.hashMap = {}; if (this.labelNames.length === 0) { setValue(this.hashMap, 0, {}); } } /** * Increment a gauge value * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep * @param {Number} value - Value to increment - if omitted, increment with 1 * @returns {void} */ inc(labels, value) { value = getValueArg(labels, value); labels = getLabelArg(labels); if (value === void 0) value = 1; setDelta(this, labels, value); } /** * Decrement a gauge value * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep * @param {Number} value - Value to decrement - if omitted, decrement with 1 * @returns {void} */ dec(labels, value) { value = getValueArg(labels, value); labels = getLabelArg(labels); if (value === void 0) value = 1; setDelta(this, labels, -value); } /** * Set the gauge to current unix epoch * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep * @returns {void} */ setToCurrentTime(labels) { const now = Date.now() / 1e3; if (labels === void 0) { this.set(now); } else { this.set(labels, now); } } /** * Start a timer * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep * @returns {function} - Invoke this function to set the duration in seconds since you started the timer. * @example * var done = gauge.startTimer(); * makeXHRRequest(function(err, response) { * done(); //Duration of the request will be saved * }); */ startTimer(labels) { const start = process.hrtime(); return (endLabels) => { const delta = process.hrtime(start); const value = delta[0] + delta[1] / 1e9; this.set(Object.assign({}, labels, endLabels), value); return value; }; } async get() { if (this.collect) { const v = this.collect(); if (v instanceof Promise) await v; } return { help: this.help, name: this.name, type: this.type, values: Object.values(this.hashMap), aggregator: this.aggregator }; } _getValue(labels) { const hash = hashObject(labels || {}, this.sortedLabelNames); return this.hashMap[hash] ? this.hashMap[hash].value : 0; } labels(...args) { const labels = getLabels(this.labelNames, args); validateLabel(this.labelNames, labels); return { inc: this.inc.bind(this, labels), dec: this.dec.bind(this, labels), set: this.set.bind(this, labels), setToCurrentTime: this.setToCurrentTime.bind(this, labels), startTimer: this.startTimer.bind(this, labels) }; } remove(...args) { const labels = getLabels(this.labelNames, args); validateLabel(this.labelNames, labels); removeLabels.call(this, this.hashMap, labels, this.sortedLabelNames); } }; function set(gauge, labels, value) { if (typeof value !== "number") { throw new TypeError(`Value is not a valid number: ${util.format(value)}`); } validateLabel(gauge.labelNames, labels); setValue(gauge.hashMap, value, labels); } function setDelta(gauge, labels, delta) { if (typeof delta !== "number") { throw new TypeError(`Delta is not a valid number: ${util.format(delta)}`); } validateLabel(gauge.labelNames, labels); const hash = hashObject(labels, gauge.sortedLabelNames); setValueDelta(gauge.hashMap, delta, labels, hash); } function getLabelArg(labels) { return isObject(labels) ? labels : {}; } function getValueArg(labels, value) { return isObject(labels) ? value : labels; } module.exports = Gauge; } }); // ../../node_modules/bare-prom-client/lib/histogram.js var require_histogram = __commonJS({ "../../node_modules/bare-prom-client/lib/histogram.js"(exports, module) { "use strict"; var process = __require("process"); var util = __require("util"); var { getLabels, hashObject, isObject, removeLabels, nowTimestamp } = require_util(); var { validateLabel } = require_validation(); var { Metric } = require_metric(); var Exemplar = require_exemplar(); var Histogram = class extends Metric { constructor(config) { super(config, { buckets: [5e-3, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10] }); this.type = "histogram"; this.defaultLabels = {}; this.defaultExemplarLabelSet = {}; this.enableExemplars = false; for (const label of this.labelNames) { if (label === "le") { throw new Error("le is a reserved label keyword"); } } this.upperBounds = this.buckets; this.bucketValues = this.upperBounds.reduce((acc, upperBound) => { acc[upperBound] = 0; return acc; }, {}); if (config.enableExemplars) { this.enableExemplars = true; this.bucketExemplars = this.upperBounds.reduce((acc, upperBound) => { acc[upperBound] = null; return acc; }, {}); Object.freeze(this.bucketExemplars); this.observe = this.observeWithExemplar; } else { this.observe = this.observeWithoutExemplar; } Object.freeze(this.bucketValues); Object.freeze(this.upperBounds); if (this.labelNames.length === 0) { this.hashMap = { [hashObject({})]: createBaseValues( {}, this.bucketValues, this.bucketExemplars ) }; } } /** * Observe a value in histogram * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep * @param {Number} value - Value to observe in the histogram * @returns {void} */ observeWithoutExemplar(labels, value) { observe.call(this, labels === 0 ? 0 : labels || {})(value); } observeWithExemplar({ labels = this.defaultLabels, value, exemplarLabels = this.defaultExemplarLabelSet } = {}) { observe.call(this, labels === 0 ? 0 : labels || {})(value); this.updateExemplar(labels, value, exemplarLabels); } updateExemplar(labels, value, exemplarLabels) { if (Object.keys(exemplarLabels).length === 0) return; const hash = hashObject(labels, this.sortedLabelNames); const bound = findBound(this.upperBounds, value); const { bucketExemplars } = this.hashMap[hash]; let exemplar = bucketExemplars[bound]; if (!isObject(exemplar)) { exemplar = new Exemplar(); bucketExemplars[bound] = exemplar; } exemplar.validateExemplarLabelSet(exemplarLabels); exemplar.labelSet = exemplarLabels; exemplar.value = value; exemplar.timestamp = nowTimestamp(); } async get() { const data = await this.getForPromString(); data.values = data.values.map(splayLabels); return data; } async getForPromString() { if (this.collect) { const v = this.collect(); if (v instanceof Promise) await v; } const data = Object.values(this.hashMap); const values = data.map(extractBucketValuesForExport(this)).reduce(addSumAndCountForExport(this), []); return { name: this.name, help: this.help, type: this.type, values, aggregator: this.aggregator }; } reset() { this.hashMap = {}; } /** * Initialize the metrics for the given combination of labels to zero * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep * @returns {void} */ zero(labels) { const hash = hashObject(labels, this.sortedLabelNames); this.hashMap[hash] = createBaseValues( labels, this.bucketValues, this.bucketExemplars ); } /** * Start a timer that could be used to logging durations * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep * @param {object} exemplarLabels - Object with labels for exemplar where key is the label key and value is label value. Can only be one level deep * @returns {function} - Function to invoke when you want to stop the timer and observe the duration in seconds * @example * var end = histogram.startTimer(); * makeExpensiveXHRRequest(function(err, res) { * const duration = end(); //Observe the duration of expensiveXHRRequest and returns duration in seconds * console.log('Duration', duration); * }); */ startTimer(labels, exemplarLabels) { return this.enableExemplars ? startTimerWithExemplar.call(this, labels, exemplarLabels)() : startTimer.call(this, labels)(); } labels(...args) { const labels = getLabels(this.labelNames, args); validateLabel(this.labelNames, labels); return { observe: observe.call(this, labels), startTimer: startTimer.call(this, labels) }; } remove(...args) { const labels = getLabels(this.labelNames, args); validateLabel(this.labelNames, labels); removeLabels.call(this, this.hashMap, labels, this.sortedLabelNames); } }; function startTimer(startLabels) { return () => { const start = process.hrtime(); return (endLabels) => { const delta = process.hrtime(start); const value = delta[0] + delta[1] / 1e9; this.observe(Object.assign({}, startLabels, endLabels), value); return value; }; }; } function startTimerWithExemplar(startLabels, startExemplarLabels) { return () => { const start = process.hrtime(); return (endLabels, endExemplarLabels) => { const delta = process.hrtime(start); const value = delta[0] + delta[1] / 1e9; this.observe({ labels: Object.assign({}, startLabels, endLabels), value, exemplarLabels: Object.assign( {}, startExemplarLabels, endExemplarLabels ) }); return value; }; }; } function setValuePair(labels, value, metricName, exemplar, sharedLabels = {}) { return { labels, sharedLabels, value, metricName, exemplar }; } function findBound(upperBounds, value) { for (let i = 0; i < upperBounds.length; i++) { const bound = upperBounds[i]; if (value <= bound) { return bound; } } return -1; } function observe(labels) { return (value) => { const labelValuePair = convertLabelsAndValues(labels, value); validateLabel(this.labelNames, labelValuePair.labels); if (!Number.isFinite(labelValuePair.value)) { throw new TypeError( `Value is not a valid number: ${util.format(labelValuePair.value)}` ); } const hash = hashObject(labelValuePair.labels, this.sortedLabelNames); let valueFromMap = this.hashMap[hash]; if (!valueFromMap) { valueFromMap = createBaseValues( labelValuePair.labels, this.bucketValues, this.bucketExemplars ); } const b = findBound(this.upperBounds, labelValuePair.value); valueFromMap.sum += labelValuePair.value; valueFromMap.count += 1; if (Object.prototype.hasOwnProperty.call(valueFromMap.bucketValues, b)) { valueFromMap.bucketValues[b] += 1; } this.hashMap[hash] = valueFromMap; }; } function createBaseValues(labels, bucketValues, bucketExemplars) { const result = { labels, bucketValues: { ...bucketValues }, sum: 0, count: 0 }; if (bucketExemplars) { result.bucketExemplars = { ...bucketExemplars }; } return result; } function convertLabelsAndValues(labels, value) { return isObject(labels) ? { labels, value } : { value: labels, labels: {} }; } function extractBucketValuesForExport(histogram) { const name = `${histogram.name}_bucket`; return (bucketData) => { let acc = 0; const buckets = histogram.upperBounds.map((upperBound) => { acc += bucketData.bucketValues[upperBound]; return setValuePair( { le: upperBound }, acc, name, bucketData.bucketExemplars ? bucketData.bucketExemplars[upperBound] : null, bucketData.labels ); }); return { buckets, data: bucketData }; }; } function addSumAndCountForExport(histogram) { return (acc, d) => { acc.push(...d.buckets); const infLabel = { le: "+Inf" }; acc.push( setValuePair( infLabel, d.data.count, `${histogram.name}_bucket`, d.data.bucketExemplars ? d.data.bucketExemplars["-1"] : null, d.data.labels ), setValuePair( {}, d.data.sum, `${histogram.name}_sum`, void 0, d.data.labels ), setValuePair( {}, d.data.count, `${histogram.name}_count`, void 0, d.data.labels ) ); return acc; }; } function splayLabels(bucket) { const { sharedLabels, labels, ...newBucket } = bucket; for (const label of Object.keys(sharedLabels)) { labels[label] = sharedLabels[label]; } newBucket.labels = labels; return newBucket; } module.exports = Histogram; } }); // ../../node_modules/bintrees/lib/treebase.js var require_treebase = __commonJS({ "../../node_modules/bintrees/lib/treebase.js"(exports, module) { function TreeBase() { } TreeBase.prototype.clear = function() { this._root = null; this.size = 0; }; TreeBase.prototype.find = function(data) { var res = this._root; while (res !== null) { var c = this._comparator(data, res.data); if (c === 0) { return res.data; } else { res = res.get_child(c > 0); } } return null; }; TreeBase.prototype.findIter = function(data) { var res = this._root; var iter = this.iterator(); while (res !== null) { var c = this._comparator(data, res.data); if (c === 0) { iter._cursor = res; return iter; } else { iter._ancestors.push(res); res = res.get_child(c > 0); } } return null; }; TreeBase.prototype.lowerBound = function(item) { var cur = this._root; var iter = this.iterator(); var cmp = this._comparator; while (cur !== null) { var c = cmp(item, cur.data); if (c === 0) { iter._cursor = cur; return iter; } iter._ancestors.push(cur); cur = cur.get_child(c > 0); } for (var i = iter._ancestors.length - 1; i >= 0; --i) { cur = iter._ancestors[i]; if (cmp(item, cur.data) < 0) { iter._cursor = cur; iter._ancestors.length = i; return iter; } } iter._ancestors.length = 0; return iter; }; TreeBase.prototype.upperBound = function(item) { var iter = this.lowerBound(item); var cmp = this._comparator; while (iter.data() !== null && cmp(iter.data(), item) === 0) { iter.next(); } return iter; }; TreeBase.prototype.min = function() { var res = this._root; if (res === null) { return null; } while (res.left !== null) { res = res.left; } return res.data; }; TreeBase.prototype.max = function() { var res = this._root; if (res === null) { return null; } while (res.right !== null) { res = res.right; } return res.data; }; TreeBase.prototype.iterator = function() { return new Iterator(this); }; TreeBase.prototype.each = function(cb) { var it = this.iterator(), data; while ((data = it.next()) !== null) { if (cb(data) === false) { return; } } }; TreeBase.prototype.reach = function(cb) { var it = this.iterator(), data; while ((data = it.prev()) !== null) { if (cb(data) === false) { return; } } }; function Iterator(tree) { this._tree = tree; this._ancestors = []; this._cursor = null; } Iterator.prototype.data = function() { return this._cursor !== null ? this._cursor.data : null; }; Iterator.prototype.next = function() { if (this._cursor === null) { var root = this._tree._root; if (root !== null) { this._minNode(root); } } else { if (this._cursor.right === null) { var save; do { save = this._cursor; if (this._ancestors.length) { this._cursor = this._ancestors.pop(); } else { this._cursor = null; break; } } while (this._cursor.right === save); } else { this._ancestors.push(this._cursor); this._minNode(this._cursor.right); } } return this._cursor !== null ? this._cursor.data : null; }; Iterator.prototype.prev = function() { if (this._cursor === null) { var root = this._tree._root; if (root !== null) { this._maxNode(root); } } else { if (this._cursor.left === null) { var save; do { save = this._cursor; if (this._ancestors.length) { this._cursor = this._ancestors.pop(); } else { this._cursor = null; break; } } while (this._cursor.left === save); } else { this._ancestors.push(this._cursor); this._maxNode(this._cursor.left); } } return this._cursor !== null ? this._cursor.data : null; }; Iterator.prototype._minNode = function(start) { while (start.left !== null) { this._ancestors.push(start); start = start.left; } this._cursor = start; }; Iterator.prototype._maxNode = function(start) { while (start.right !== null) { this._ancestors.push(start); start = start.right; } this._cursor = start; }; module.exports = TreeBase; } }); // ../../node_modules/bintrees/lib/rbtree.js var require_rbtree = __commonJS({ "../../node_modules/bintrees/lib/rbtree.js"(exports, module) { var TreeBase = require_treebase(); function Node(data) { this.data = data; this.left = null; this.right = null; this.red = true; } Node.prototype.get_child = function(dir) { return dir ? this.right : this.left; }; Node.prototype.set_child = function(dir, val) { if (dir) { this.right = val; } else { this.left = val; } }; function RBTree(comparator) { this._root = null; this._comparator = comparator; this.size = 0; } RBTree.prototype = new TreeBase(); RBTree.prototype.insert = function(data) { var ret2 = false; if (this._root === null) { this._root = new Node(data); ret2 = true; this.size++; } else { var head = new Node(void 0); var dir = 0; var last = 0; var gp = null; var ggp = head; var p = null; var node = this._root; ggp.right = this._root; while (true) { if (node === null) { node = new Node(data); p.set_child(dir, node); ret2 = true; this.size++; } else if (is_red(node.left) && is_red(node.right)) { node.red = true; node.left.red = false; node.right.red = false; } if (is_red(node) && is_red(p)) { var dir2 = ggp.right === gp; if (node === p.get_child(last)) { ggp.set_child(dir2, single_rotate(gp, !last)); } else { ggp.set_child(dir2, double_rotate(gp, !last)); } } var cmp = this._comparator(node.data, data); if (cmp === 0) { break; } last = dir; dir = cmp < 0; if (gp !== null) { ggp = gp; } gp = p; p = node; node = node.get_child(dir); } this._root = head.right; } this._root.red = false; return ret2; }; RBTree.prototype.remove = function(data) { if (this._root === null) { return false; } var head = new Node(void 0); var node = head; node.right = this._root; var p = null; var gp = null; var found = null; var dir = 1; while (node.get_child(dir) !== null) { var last = dir; gp = p; p = node; node = node.get_child(dir); var cmp = this._comparator(data, node.data); dir = cmp > 0; if (cmp === 0) { found = node; } if (!is_red(node) && !is_red(node.get_child(dir))) { if (is_red(node.get_child(!dir))) { var sr = single_rotate(node, dir); p.set_child(last, sr); p = sr; } else if (!is_red(node.get_child(!dir))) { var sibling = p.get_child(!last); if (sibling !== null) { if (!is_red(sibling.get_child(!last)) && !is_red(sibling.get_child(last))) { p.red = false; sibling.red = true; node.red = true; } else { var dir2 = gp.right === p; if (is_red(sibling.get_child(last))) { gp.set_child(dir2, double_rotate(p, last)); } else if (is_red(sibling.get_child(!last))) { gp.set_child(dir2, single_rotate(p, last)); } var gpc = gp.get_child(dir2); gpc.red = true; node.red = true; gpc.left.red = false; gpc.right.red = false; } } } } } if (found !== null) { found.data = node.data; p.set_child(p.right === node, node.get_child(node.left === null)); this.size--; } this._root = head.right; if (this._root !== null) { this._root.red = false; } return found !== null; }; function is_red(node) { return node !== null && node.red; } function single_rotate(root, dir) { var save = root.get_child(!dir); root.set_child(!dir, save.get_child(dir)); save.set_child(dir, root); root.red = true; save.red = false; return save; } function double_rotate(root, dir) { root.set_child(!dir, single_rotate(root.get_child(!dir), !dir)); return single_rotate(root, dir); } module.exports = RBTree; } }); // ../../node_modules/bintrees/lib/bintree.js var require_bintree = __commonJS({ "../../node_modules/bintrees/lib/bintree.js"(exports, module) { var TreeBase = require_treebase(); function Node(data) { this.data = data; this.left = null; this.right = null; } Node.prototype.get_child = function(dir) { return dir ? this.right : this.left; }; Node.prototype.set_child = function(dir, val) { if (dir) { this.right = val; } else { this.left = val; } }; function BinTree(comparator) { this._root = null; this._comparator = comparator; this.size = 0; } BinTree.prototype = new TreeBase(); BinTree.prototype.insert = function(data) { if (this._root === null) { this._root = new Node(data); this.size++; return true; } var dir = 0; var p = null; var node = this._root; while (true) { if (node === null) { node = new Node(data); p.set_child(dir, node); ret = true; this.size++; return true; } if (this._comparator(node.data, data) === 0) { return false; } dir = this._comparator(node.data, data) < 0; p = node; node = node.get_child(dir); } }; BinTree.prototype.remove = function(data) { if (this._root === null) { return false; } var head = new Node(void 0); var node = head; node.right = this._root; var p = null; var found = null; var dir = 1; while (node.get_child(dir) !== null) { p = node; node = node.get_child(dir); var cmp = this._comparator(data, node.data); dir = cmp > 0; if (cmp === 0) { found = node; } } if (found !== null) { found.data = node.data; p.set_child(p.right === node, node.get_child(node.left === null)); this._root = head.right; this.size--; return true; } else { return false; } }; module.exports = BinTree; } }); // ../../node_modules/bintrees/index.js var require_bintrees = __commonJS({ "../../node_modules/bintrees/index.js"(exports, module) { module.exports = { RBTree: require_rbtree(), BinTree: require_bintree() }; } }); // ../../node_modules/tdigest/tdigest.js var require_tdigest = __commonJS({ "../../node_modules/tdigest/tdigest.js"(exports, module) { var RBTree = require_bintrees().RBTree; function TDigest(delta, K, CX) { this.discrete = delta === false; this.delta = delta || 0.01; this.K = K === void 0 ? 25 : K; this.CX = CX === void 0 ? 1.1 : CX; this.centroids = new RBTree(compare_centroid_means); this.nreset = 0; this.reset(); } TDigest.prototype.reset = function() { this.centroids.clear(); this.n = 0; this.nreset += 1; this.last_cumulate = 0; }; TDigest.prototype.size = function() { return this.centroids.size; }; TDigest.prototype.toArray = function(everything) { var result = []; if (everything) { this._cumulate(true); this.centroids.each(function(c) { result.push(c); }); } else { this.centroids.each(function(c) { result.push({ mean: c.mean, n: c.n }); }); } return result; }; TDigest.prototype.summary = function() { var approx = this.discrete ? "exact " : "approximating "; var s = [ approx + this.n + " samples using " + this.size() + " centroids", "min = " + this.percentile(0), "Q1 = " + this.percentile(0.25), "Q2 = " + this.percentile(0.5), "Q3 = " + this.percentile(0.75), "max = " + this.percentile(1) ]; return s.join("\n"); }; function compare_centroid_means(a, b) { return a.mean > b.mean ? 1 : a.mean < b.mean ? -1 : 0; } function compare_centroid_mean_cumns(a, b) { return a.mean_cumn - b.mean_cumn; } TDigest.prototype.push = function(x, n) { n = n || 1; x = Array.isArray(x) ? x : [x]; for (var i = 0; i < x.length; i++) { this._digest(x[i], n); } }; TDigest.prototype.push_centroid = function(c) { c = Array.isArray(c) ? c : [c]; for (var i = 0; i < c.length; i++) { this._digest(c[i].mean, c[i].n); } }; TDigest.prototype._cumulate = function(exact) { if (this.n === this.last_cumulate || !exact && this.CX && this.CX > this.n / this.last_cumulate) { return; } var cumn = 0; this.centroids.each(function(c) { c.mean_cumn = cumn + c.n / 2; cumn = c.cumn = cumn + c.n; }); this.n = this.last_cumulate = cumn; }; TDigest.prototype.find_nearest = function(x) { if (this.size() === 0) { return null; } var iter = this.centroids.lowerBound({ mean: x }); var c = iter.data() === null ? iter.prev() : iter.data(); if (c.mean === x || this.discrete) { return c; } var prev = iter.prev(); if (prev && Math.abs(prev.mean - x) < Math.abs(c.mean - x)) { return prev; } else { return c; } }; TDigest.prototype._new_centroid = function(x, n, cumn) { var c = { mean: x, n, cumn }; this.centroids.insert(c); this.n += n; return c; }; TDigest.prototype._addweight = function(nearest, x, n) { if (x !== nearest.mean) { nearest.mean += n * (x - nearest.mean) / (nearest.n + n); } nearest.cumn += n; nearest.mean_cumn += n / 2; nearest.n += n; this.n += n; }; TDigest.prototype._digest = function(x, n) { var min = this.centroids.min(); var max = this.centroids.max(); var nearest = this.find_nearest(x); if (nearest && nearest.mean === x) { this._addweight(nearest, x, n); } else if (nearest === min) { this._new_centroid(x, n, 0); } else if (nearest === max) { this._new_centroid(x, n, this.n); } else if (this.discrete) { this._new_centroid(x, n, nearest.cumn); } else { var p = nearest.mean_cumn / this.n; var max_n = Math.floor(4 * this.n * this.delta * p * (1 - p)); if (max_n - nearest.n >= n) { this._addweight(nearest, x, n); } else { this._new_centroid(x, n, nearest.cumn); } } this._cumulate(false); if (!this.discrete && this.K && this.size() > this.K / this.delta) { this.compress(); } }; TDigest.prototype.bound_mean = function(x) { var iter = this.centroids.upperBound({ mean: x }); var lower = iter.prev(); var upper = lower.mean === x ? lower : iter.next(); return [lower, upper]; }; TDigest.prototype.p_rank = function(x_or_xlist) { var xs = Array.isArray(x_or_xlist) ? x_or_xlist : [x_or_xlist]; var ps = xs.map(this._p_rank, this); return Array.isArray(x_or_xlist) ? ps : ps[0]; }; TDigest.prototype._p_rank = function(x) { if (this.size() === 0) { return void 0; } else if (x < this.centroids.min().mean) { return 0; } else if (x > this.centroids.max().mean) { return 1; } this._cumulate(true); var bound = this.bound_mean(x); var lower = bound[0], upper = bound[1]; if (this.discrete) { return lower.cumn / this.n; } else { var cumn = lower.mean_cumn; if (lower !== upper) { cumn += (x - lower.mean) * (upper.mean_cumn - lower.mean_cumn) / (upper.mean - lower.mean); } return cumn / this.n; } }; TDigest.prototype.bound_mean_cumn = function(cumn) { this.centroids._comparator = compare_centroid_mean_cumns; var iter = this.centroids.upperBound({ mean_cumn: cumn }); this.centroids._comparator = compare_centroid_means; var lower = iter.prev(); var upper = lower && lower.mean_cumn === cumn ? lower : iter.next(); return [lower, upper]; }; TDigest.prototype.percentile = function(p_or_plist) { var ps = Array.isArray(p_or_plist) ? p_or_plist : [p_or_plist]; var qs = ps.map(this._percentile, this); return Array.isArray(p_or_plist) ? qs : qs[0]; }; TDigest.prototype._percentile = function(p) { if (this.size() === 0) { return void 0; } this._cumulate(true); var h = this.n * p; var bound = this.bound_mean_cumn(h); var lower = bound[0], upper = bound[1]; if (upper === lower || lower === null || upper === null) { return (lower || upper).mean; } else if (!this.discrete) { return lower.mean + (h - lower.mean_cumn) * (upper.mean - lower.mean) / (upper.mean_cumn - lower.mean_cumn); } else if (h <= lower.cumn) { return lower.mean; } else { return upper.mean; } }; function pop_random(choices) { var idx = Math.floor(Math.random() * choices.length); return choices.splice(idx, 1)[0]; } TDigest.prototype.compress = function() { if (this.compressing) { return; } var points = this.toArray(); this.reset(); this.compressing = true; while (points.length > 0) { this.push_centroid(pop_random(points)); } this._cumulate(true); this.compressing = false; }; function Digest(config) { this.config = config || {}; this.mode = this.config.mode || "auto"; TDigest.call(this, this.mode === "cont" ? config.delta : false); this.digest_ratio = this.config.ratio || 0.9; this.digest_thresh = this.config.thresh || 1e3; this.n_unique = 0; } Digest.prototype = Object.create(TDigest.prototype); Digest.prototype.constructor = Digest; Digest.prototype.push = function(x_or_xlist) { TDigest.prototype.push.call(this, x_or_xlist); this.check_continuous(); }; Digest.prototype._new_centroid = function(x, n, cumn) { this.n_unique += 1; TDigest.prototype._new_centroid.call(this, x, n, cumn); }; Digest.prototype._addweight = function(nearest, x, n) { if (nearest.n === 1) { this.n_unique -= 1; } TDigest.prototype._addweight.call(this, nearest, x, n); }; Digest.prototype.check_continuous = function() { if (this.mode !== "auto" || this.size() < this.digest_thresh) { return false; } if (this.n_unique / this.size() > this.digest_ratio) { this.mode = "cont"; this.discrete = false; this.delta = this.config.delta || 0.01; this.compress(); return true; } return false; }; module.exports = { "TDigest": TDigest, "Digest": Digest }; } }); // ../../node_modules/bare-prom-client/lib/timeWindowQuantiles.js var require_timeWindowQuantiles = __commonJS({ "../../node_modules/bare-prom-client/lib/timeWindowQuantiles.js"(exports, module) { "use strict"; var { TDigest } = require_tdigest(); var TimeWindowQuantiles = class { constructor(maxAgeSeconds, ageBuckets) { this.maxAgeSeconds = maxAgeSeconds || 0; this.ageBuckets = ageBuckets || 0; this.shouldRotate = maxAgeSeconds && ageBuckets; this.ringBuffer = Array(ageBuckets).fill(new TDigest()); this.currentBuffer = 0; this.lastRotateTimestampMillis = Date.now(); this.durationBetweenRotatesMillis = maxAgeSeconds * 1e3 / ageBuckets || Infinity; } size() { const bucket = rotate.call(this); return bucket.size(); } percentile(quantile) { const bucket = rotate.call(this); return bucket.percentile(quantile); } push(value) { rotate.call(this); this.ringBuffer.forEach((bucket) => { bucket.push(value); }); } reset() { this.ringBuffer.forEach((bucket) => { bucket.reset(); }); } compress() { this.ringBuffer.forEach((bucket) => { bucket.compress(); }); } }; function rotate() { let timeSinceLastRotateMillis = Date.now() - this.lastRotateTimestampMillis; while (timeSinceLastRotateMillis > this.durationBetweenRotatesMillis && this.shouldRotate) { this.ringBuffer[this.currentBuffer] = new TDigest(); if (++this.currentBuffer >= this.ringBuffer.length) { this.currentBuffer = 0; } timeSinceLastRotateMillis -= this.durationBetweenRotatesMillis; this.lastRotateTimestampMillis += this.durationBetweenRotatesMillis; } return this.ringBuffer[this.currentBuffer]; } module.exports = TimeWindowQuantiles; } }); // ../../node_modules/bare-prom-client/lib/summary.js var require_summary = __commonJS({ "../../node_modules/bare-prom-client/lib/summary.js"(exports, module) { "use strict"; var process = __require("process"); var util = __require("util"); var { getLabels, hashObject, removeLabels } = require_util(); var { validateLabel } = require_validation(); var { Metric } = require_metric(); var timeWindowQuantiles = require_timeWindowQuantiles(); var DEFAULT_COMPRESS_COUNT = 1e3; var Summary = class extends Metric { constructor(config) { super(config, { percentiles: [0.01, 0.05, 0.5, 0.9, 0.95, 0.99, 0.999], compressCount: DEFAULT_COMPRESS_COUNT, hashMap: {} }); this.type = "summary"; for (const label of this.labelNames) { if (label === "quantile") throw new Error("quantile is a reserved label keyword"); } if (this.labelNames.length === 0) { this.hashMap = { [hashObject({})]: { labels: {}, td: new timeWindowQuantiles(this.maxAgeSeconds, this.ageBuckets), count: 0, sum: 0 } }; } } /** * Observe a value * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep * @param {Number} value - Value to observe * @returns {void} */ observe(labels, value) { observe.call(this, labels === 0 ? 0 : labels || {})(value); } async get() { if (this.collect) { const v = this.collect(); if (v instanceof Promise) await v; } const hashKeys = Object.keys(this.hashMap); const values = []; hashKeys.forEach((hashKey) => { const s = this.hashMap[hashKey]; if (s) { if (this.pruneAgedBuckets && s.td.size() === 0) { delete this.hashMap[hashKey]; } else { extractSummariesForExport(s, this.percentiles).forEach((v) => { values.push(v); }); values.push(getSumForExport(s, this)); values.push(getCountForExport(s, this)); } } }); return { name: this.name, help: this.help, type: this.type, values, aggregator: this.aggregator }; } reset() { const data = Object.values(this.hashMap); data.forEach((s) => { s.td.reset(); s.count = 0; s.sum = 0; }); } /** * Start a timer that could be used to logging durations * @param {object} labels - Object with labels where key is the label key and value is label value. Can only be one level deep * @returns {function} - Function to invoke when you want to stop the timer and observe the duration in seconds * @example * var end = summary.startTimer(); * makeExpensiveXHRRequest(function(err, res) { * end(); //Observe the duration of expensiveXHRRequest * }); */ startTimer(labels) { return startTimer.call(this, labels)(); } labels(...args) { const labels = getLabels(this.labelNames, args); validateLabel(this.labelNames, labels); return { observe: observe.call(this, labels), startTimer: startTimer.call(this, labels) }; } remove(...args) { const labels = getLabels(this.labelNames, args); validateLabel(this.labelNames, labels); removeLabels.call(this, this.hashMap, labels, this.sortedLabelNames); } }; function extractSummariesForExport(summaryOfLabels, percentiles) { summaryOfLabels.td.compress(); return percentiles.map((percentile) => { const percentileValue = summaryOfLabels.td.percentile(percentile); return { labels: Object.assign({ quantile: percentile }, summaryOfLabels.labels), value: percentileValue ? percentileValue : 0 }; }); } function getCountForExport(value, summary) { return { metricName: `${summary.name}_count`, labels: value.labels, value: value.count }; } function getSumForExport(value, summary) { return { metricName: `${summary.name}_sum`, labels: value.labels, value: value.sum }; } function startTimer(startLabels) { return () => { const start = process.hrtime(); return (endLabels) => { const delta = process.hrtime(start); const value = delta[0] + delta[1] / 1e9; this.observe(Object.assign({}, startLabels, endLabels), value); return value; }; }; } function observe(labels) { return (value) => { const labelValuePair = convertLabelsAndValues(labels, value); validateLabel(this.labelNames, labels); if (!Number.isFinite(labelValuePair.value)) { throw new TypeError( `Value is not a valid number: ${util.format(labelValuePair.value)}` ); } const hash = hashObject(labelValuePair.labels, this.sortedLabelNames); let summaryOfLabel = this.hashMap[hash]; if (!summaryOfLabel) { summaryOfLabel = { labels: labelValuePair.labels, td: new timeWindowQuantiles(this.maxAgeSeconds, this.ageBuckets), count: 0, sum: 0 }; } summaryOfLabel.td.push(labelValuePair.value); summaryOfLabel.count++; if (summaryOfLabel.count % this.compressCount === 0) { summaryOfLabel.td.compress(); } summaryOfLabel.sum += labelValuePair.value; this.hashMap[hash] = summaryOfLabel; }; } function convertLabelsAndValues(labels, value) { if (value === void 0) { return { value: labels, labels: {} }; } return { labels, value }; } module.exports = Summary; } }); // ../../node_modules/bare-os/binding.js var require_binding = __commonJS({ "../../node_modules/bare-os/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-os/lib/errors.js var require_errors = __commonJS({ "../../node_modules/bare-os/lib/errors.js"(exports, module) { module.exports = class OSError extends Error { constructor(msg, code, fn = OSError) { super(`${code}: ${msg}`); this.code = code; if (Error.captureStackTrace) { Error.captureStackTrace(this, fn); } } get name() { return "OSError"; } static UNKNOWN_SIGNAL(msg) { return new OSError(msg, "UNKNOWN_SIGNAL", OSError.UNKNOWN_SIGNAL); } static TITLE_OVERFLOW(msg) { return new OSError(msg, "TITLE_OVERFLOW", OSError.TITLE_OVERFLOW); } }; } }); // ../../node_modules/bare-os/lib/constants.js var require_constants = __commonJS({ "../../node_modules/bare-os/lib/constants.js"(exports, module) { var binding = require_binding(); module.exports = { signals: binding.signals, errnos: binding.errnos, priority: binding.priority }; } }); // ../../node_modules/bare-os/index.js var require_bare_os = __commonJS({ "../../node_modules/bare-os/index.js"(exports) { var binding = require_binding(); var errors = require_errors(); var constants = require_constants(); exports.constants = constants; exports.EOL = binding.platform === "win32" ? "\r\n" : "\n"; exports.devNull = binding.platform === "win32" ? "\\\\.\\nul" : "/dev/null"; exports.platform = function platform() { return binding.platform; }; exports.arch = function arch() { return binding.arch; }; exports.type = binding.type; exports.version = binding.version; exports.release = binding.release; exports.machine = binding.machine; exports.execPath = binding.execPath; exports.pid = binding.pid; exports.ppid = binding.ppid; exports.cwd = binding.cwd; exports.chdir = binding.chdir; exports.tmpdir = binding.tmpdir; exports.homedir = binding.homedir; exports.hostname = binding.hostname; exports.userInfo = binding.userInfo; exports.networkInterfaces = function networkInterfaces() { const result = {}; for (const entry of binding.networkInterfaces()) { const { name, ...properties } = entry; if (result[name]) result[name].push(properties); else result[name] = [properties]; } return result; }; exports.kill = function kill(pid, signal = constants.signals.SIGTERM) { if (typeof signal === "string") { if (signal in constants.signals === false) { throw errors.UNKNOWN_SIGNAL("Unknown signal: " + signal); } signal = constants.signals[signal]; } binding.kill(pid, signal); }; exports.endianness = function endianness() { return binding.isLittleEndian ? "LE" : "BE"; }; exports.availableParallelism = binding.availableParallelism; exports.cpuUsage = function cpuUsage(previous) { const current = binding.cpuUsage(); if (previous) { return { user: current.user - previous.user, system: current.system - previous.system }; } return current; }; exports.threadCpuUsage = function threadCpuUsage(previous) { const current = binding.threadCpuUsage(); if (previous) { return { user: current.user - previous.user, system: current.system - previous.system }; } return current; }; exports.resourceUsage = binding.resourceUsage; exports.memoryUsage = binding.memoryUsage; exports.freemem = binding.freemem; exports.totalmem = binding.totalmem; exports.availableMemory = binding.availableMemory; exports.constrainedMemory = binding.constrainedMemory; exports.uptime = binding.uptime; exports.loadavg = binding.loadavg; exports.cpus = binding.cpus; exports.getProcessTitle = binding.getProcessTitle; exports.setProcessTitle = function setProcessTitle(title) { if (typeof title !== "string") title = title.toString(); if (title.length >= 256) { throw errors.TITLE_OVERFLOW("Process title is too long"); } binding.setProcessTitle(title); }; exports.getPriority = function getPriority(pid = 0) { return binding.getPriority(pid); }; exports.setPriority = function setPriority(pid, priority) { if (priority === void 0) { priority = pid; pid = 0; } binding.setPriority(pid, priority); }; exports.getEnvKeys = binding.getEnvKeys; exports.getEnv = binding.getEnv; exports.hasEnv = binding.hasEnv; exports.setEnv = binding.setEnv; exports.unsetEnv = binding.unsetEnv; } }); // ../../node_modules/bare-path/lib/constants.js var require_constants2 = __commonJS({ "../../node_modules/bare-path/lib/constants.js"(exports, module) { module.exports = { CHAR_UPPERCASE_A: 65, CHAR_LOWERCASE_A: 97, CHAR_UPPERCASE_Z: 90, CHAR_LOWERCASE_Z: 122, CHAR_DOT: 46, CHAR_FORWARD_SLASH: 47, CHAR_BACKWARD_SLASH: 92, CHAR_COLON: 58, CHAR_QUESTION_MARK: 63 }; } }); // ../../node_modules/bare-path/lib/shared.js var require_shared = __commonJS({ "../../node_modules/bare-path/lib/shared.js"(exports) { var { CHAR_DOT, CHAR_FORWARD_SLASH } = require_constants2(); exports.normalizeString = function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { let res = ""; let lastSegmentLength = 0; let lastSlash = -1; let dots = 0; let code = 0; for (let i = 0; i <= path.length; ++i) { if (i < path.length) { code = path.charCodeAt(i); } else if (isPathSeparator(code)) { break; } else { code = CHAR_FORWARD_SLASH; } if (isPathSeparator(code)) { if (lastSlash === i - 1 || dots === 1) ; else if (dots === 2) { if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) { if (res.length > 2) { const lastSlashIndex = res.lastIndexOf(separator); if (lastSlashIndex === -1) { res = ""; lastSegmentLength = 0; } else { res = res.substring(0, lastSlashIndex); lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); } lastSlash = i; dots = 0; continue; } else if (res.length !== 0) { res = ""; lastSegmentLength = 0; lastSlash = i; dots = 0; continue; } } if (allowAboveRoot) { res += res.length > 0 ? `${separator}..` : ".."; lastSegmentLength = 2; } } else { if (res.length > 0) { res += `${separator}${path.substring(lastSlash + 1, i)}`; } else { res = path.substring(lastSlash + 1, i); } lastSegmentLength = i - lastSlash - 1; } lastSlash = i; dots = 0; } else if (code === CHAR_DOT && dots !== -1) { ++dots; } else { dots = -1; } } return res; }; } }); // ../../node_modules/bare-path/lib/posix.js var require_posix = __commonJS({ "../../node_modules/bare-path/lib/posix.js"(exports) { var os = require_bare_os(); var { normalizeString } = require_shared(); var { CHAR_DOT, CHAR_FORWARD_SLASH } = require_constants2(); function isPosixPathSeparator(code) { return code === CHAR_FORWARD_SLASH; } exports.win32 = require_win32(); exports.posix = exports; exports.sep = "/"; exports.delimiter = ":"; exports.resolve = function resolve(...args) { let resolvedPath = ""; let resolvedAbsolute = false; for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { const path = i >= 0 ? args[i] : os.cwd(); if (path.length === 0) { continue; } resolvedPath = `${path}/${resolvedPath}`; resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; } resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, "/", isPosixPathSeparator); if (resolvedAbsolute) { return `/${resolvedPath}`; } return resolvedPath.length > 0 ? resolvedPath : "."; }; exports.normalize = function normalize(path) { if (path.length === 0) return "."; const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator); if (path.length === 0) { if (isAbsolute) return "/"; return trailingSeparator ? "./" : "."; } if (trailingSeparator) path += "/"; return isAbsolute ? `/${path}` : path; }; exports.isAbsolute = function isAbsolute(path) { return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; }; exports.join = function join(...args) { if (args.length === 0) return "."; let joined; for (let i = 0; i < args.length; ++i) { const arg = args[i]; if (arg.length > 0) { if (joined === void 0) joined = arg; else joined += `/${arg}`; } } if (joined === void 0) return "."; return exports.normalize(joined); }; exports.relative = function relative(from, to) { if (from === to) return ""; from = exports.resolve(from); to = exports.resolve(to); if (from === to) return ""; const fromStart = 1; const fromEnd = from.length; const fromLen = fromEnd - fromStart; const toStart = 1; const toLen = to.length - toStart; const length = fromLen < toLen ? fromLen : toLen; let lastCommonSep = -1; let i = 0; for (; i < length; i++) { const fromCode = from.charCodeAt(fromStart + i); if (fromCode !== to.charCodeAt(toStart + i)) { break; } else if (fromCode === CHAR_FORWARD_SLASH) { lastCommonSep = i; } } if (i === length) { if (toLen > length) { if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) { return to.substring(toStart + i + 1); } if (i === 0) { return to.substring(toStart + i); } } else if (fromLen > length) { if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { lastCommonSep = i; } else if (i === 0) { lastCommonSep = 0; } } } let out = ""; for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) { out += out.length === 0 ? ".." : "/.."; } } return `${out}${to.substring(toStart + lastCommonSep)}`; }; exports.toNamespacedPath = function toNamespacedPath(path) { return path; }; exports.dirname = function dirname(path) { if (path.length === 0) return "."; const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; let end = -1; let matchedSlash = true; for (let i = path.length - 1; i >= 1; --i) { if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { if (!matchedSlash) { end = i; break; } } else { matchedSlash = false; } } if (end === -1) return hasRoot ? "/" : "."; if (hasRoot && end === 1) return "//"; return path.substring(0, end); }; exports.basename = function basename(path, suffix) { let start = 0; let end = -1; let matchedSlash = true; if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) { if (suffix === path) { return ""; } let extIdx = suffix.length - 1; let firstNonSlashEnd = -1; for (let i = path.length - 1; i >= 0; --i) { const code = path.charCodeAt(i); if (code === CHAR_FORWARD_SLASH) { if (!matchedSlash) { start = i + 1; break; } } else { if (firstNonSlashEnd === -1) { matchedSlash = false; firstNonSlashEnd = i + 1; } if (extIdx >= 0) { if (code === suffix.charCodeAt(extIdx)) { if (--extIdx === -1) { end = i; } } else { extIdx = -1; end = firstNonSlashEnd; } } } } if (start === end) end = firstNonSlashEnd; else if (end === -1) end = path.length; return path.substring(start, end); } for (let i = path.length - 1; i >= 0; --i) { if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { if (!matchedSlash) { start = i + 1; break; } } else if (end === -1) { matchedSlash = false; end = i + 1; } } if (end === -1) return ""; return path.substring(start, end); }; exports.extname = function extname(path) { let startDot = -1; let startPart = 0; let end = -1; let matchedSlash = true; let preDotState = 0; for (let i = path.length - 1; i >= 0; --i) { const code = path.charCodeAt(i); if (code === CHAR_FORWARD_SLASH) { if (!matchedSlash) { startPart = i + 1; break; } continue; } if (end === -1) { matchedSlash = false; end = i + 1; } if (code === CHAR_DOT) { if (startDot === -1) startDot = i; else if (preDotState !== 1) preDotState = 1; } else if (startDot !== -1) { preDotState = -1; } } if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { return ""; } return path.substring(startDot, end); }; } }); // ../../node_modules/bare-path/lib/win32.js var require_win32 = __commonJS({ "../../node_modules/bare-path/lib/win32.js"(exports) { var os = require_bare_os(); var { normalizeString } = require_shared(); var { CHAR_UPPERCASE_A, CHAR_LOWERCASE_A, CHAR_UPPERCASE_Z, CHAR_LOWERCASE_Z, CHAR_DOT, CHAR_FORWARD_SLASH, CHAR_BACKWARD_SLASH, CHAR_COLON, CHAR_QUESTION_MARK } = require_constants2(); function isWindowsPathSeparator(code) { return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; } function isWindowsDeviceRoot(code) { return code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z || code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z; } exports.posix = require_posix(); exports.win32 = exports; exports.sep = "\\"; exports.delimiter = ";"; exports.resolve = function resolve(...args) { let resolvedDevice = ""; let resolvedTail = ""; let resolvedAbsolute = false; for (let i = args.length - 1; i >= -1; i--) { let path; if (i >= 0) { path = args[i]; if (path.length === 0) continue; } else if (resolvedDevice.length === 0) { path = os.cwd(); } else { path = os.getEnv(`=${resolvedDevice}`) || os.cwd(); if (path === void 0 || path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH) { path = `${resolvedDevice}\\`; } } const len = path.length; let rootEnd = 0; let device = ""; let isAbsolute = false; const code = path.charCodeAt(0); if (len === 1) { if (isWindowsPathSeparator(code)) { rootEnd = 1; isAbsolute = true; } } else if (isWindowsPathSeparator(code)) { isAbsolute = true; if (isWindowsPathSeparator(path.charCodeAt(1))) { let j = 2; let last = j; while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { const firstPart = path.substring(last, j); last = j; while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { last = j; while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) { j++; } if (j === len || j !== last) { device = `\\\\${firstPart}\\${path.substring(last, j)}`; rootEnd = j; } } } } else { rootEnd = 1; } } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { device = path.substring(0, 2); rootEnd = 2; if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) { isAbsolute = true; rootEnd = 3; } } if (device.length > 0) { if (resolvedDevice.length > 0) { if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { continue; } } else { resolvedDevice = device; } } if (resolvedAbsolute) { if (resolvedDevice.length > 0) { break; } } else { resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`; resolvedAbsolute = isAbsolute; if (isAbsolute && resolvedDevice.length > 0) { break; } } } resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, "\\", isWindowsPathSeparator); return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || "."; }; exports.normalize = function normalize(path) { const len = path.length; if (len === 0) return "."; let rootEnd = 0; let device; let isAbsolute = false; const code = path.charCodeAt(0); if (len === 1) { return code === CHAR_FORWARD_SLASH ? "\\" : path; } if (isWindowsPathSeparator(code)) { isAbsolute = true; if (isWindowsPathSeparator(path.charCodeAt(1))) { let j = 2; let last = j; while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { const firstPart = path.substring(last, j); last = j; while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { last = j; while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) { j++; } if (j === len) { return `\\\\${firstPart}\\${path.substring(last)}\\`; } if (j !== last) { device = `\\\\${firstPart}\\${path.substring(last, j)}`; rootEnd = j; } } } } else { rootEnd = 1; } } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { device = path.substring(0, 2); rootEnd = 2; if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) { isAbsolute = true; rootEnd = 3; } } let tail = rootEnd < len ? normalizeString(path.substring(rootEnd), !isAbsolute, "\\", isWindowsPathSeparator) : ""; if (tail.length === 0 && !isAbsolute) { tail = "."; } if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) { tail += "\\"; } if (device === void 0) { return isAbsolute ? `\\${tail}` : tail; } return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`; }; exports.isAbsolute = function isAbsolute(path) { const len = path.length; if (len === 0) return false; const code = path.charCodeAt(0); return isWindowsPathSeparator(code) || len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isWindowsPathSeparator(path.charCodeAt(2)); }; exports.join = function join(...args) { if (args.length === 0) return "."; let joined; let firstPart; for (let i = 0; i < args.length; ++i) { const arg = args[i]; if (arg.length > 0) { if (joined === void 0) joined = firstPart = arg; else joined += `\\${arg}`; } } if (joined === void 0) return "."; let needsReplace = true; let slashCount = 0; if (isWindowsPathSeparator(firstPart.charCodeAt(0))) { ++slashCount; const firstLen = firstPart.length; if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) { ++slashCount; if (firstLen > 2) { if (isWindowsPathSeparator(firstPart.charCodeAt(2))) { ++slashCount; } else { needsReplace = false; } } } } if (needsReplace) { while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) { slashCount++; } if (slashCount >= 2) { joined = `\\${joined.substring(slashCount)}`; } } return exports.normalize(joined); }; exports.relative = function relative(from, to) { if (from === to) return ""; const fromOrig = exports.resolve(from); const toOrig = exports.resolve(to); if (fromOrig === toOrig) return ""; from = fromOrig.toLowerCase(); to = toOrig.toLowerCase(); if (from === to) return ""; let fromStart = 0; while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) { fromStart++; } let fromEnd = from.length; while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) { fromEnd--; } const fromLen = fromEnd - fromStart; let toStart = 0; while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { toStart++; } let toEnd = to.length; while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) { toEnd--; } const toLen = toEnd - toStart; const length = fromLen < toLen ? fromLen : toLen; let lastCommonSep = -1; let i = 0; for (; i < length; i++) { const fromCode = from.charCodeAt(fromStart + i); if (fromCode !== to.charCodeAt(toStart + i)) { break; } else if (fromCode === CHAR_BACKWARD_SLASH) { lastCommonSep = i; } } if (i !== length) { if (lastCommonSep === -1) return toOrig; } else { if (toLen > length) { if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { return toOrig.substring(toStart + i + 1); } if (i === 2) { return toOrig.substring(toStart + i); } } if (fromLen > length) { if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { lastCommonSep = i; } else if (i === 2) { lastCommonSep = 3; } } if (lastCommonSep === -1) lastCommonSep = 0; } let out = ""; for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { out += out.length === 0 ? ".." : "\\.."; } } toStart += lastCommonSep; if (out.length > 0) { return `${out}${toOrig.substring(toStart, toEnd)}`; } if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) { ++toStart; } return toOrig.substring(toStart, toEnd); }; exports.toNamespacedPath = function toNamespacedPath(path) { if (path.length === 0) return path; const resolvedPath = exports.resolve(path); if (resolvedPath.length <= 2) return path; if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { const code = resolvedPath.charCodeAt(2); if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { return `\\\\?\\UNC\\${resolvedPath.substring(2)}`; } } } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) && resolvedPath.charCodeAt(1) === CHAR_COLON && resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH) { return `\\\\?\\${resolvedPath}`; } return path; }; exports.dirname = function dirname(path) { const len = path.length; if (len === 0) return "."; let rootEnd = -1; let offset = 0; const code = path.charCodeAt(0); if (len === 1) { return isWindowsPathSeparator(code) ? path : "."; } if (isWindowsPathSeparator(code)) { rootEnd = offset = 1; if (isWindowsPathSeparator(path.charCodeAt(1))) { let j = 2; let last = j; while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { last = j; while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) { j++; } if (j < len && j !== last) { last = j; while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) { j++; } if (j === len) { return path; } if (j !== last) { rootEnd = offset = j + 1; } } } } } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2; offset = rootEnd; } let end = -1; let matchedSlash = true; for (let i = len - 1; i >= offset; --i) { if (isWindowsPathSeparator(path.charCodeAt(i))) { if (!matchedSlash) { end = i; break; } } else { matchedSlash = false; } } if (end === -1) { if (rootEnd === -1) return "."; end = rootEnd; } return path.substring(0, end); }; exports.basename = function basename(path, suffix) { let start = 0; let end = -1; let matchedSlash = true; if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) { start = 2; } if (suffix !== void 0 && suffix.length > 0 && suffix.length <= path.length) { if (suffix === path) return ""; let extIdx = suffix.length - 1; let firstNonSlashEnd = -1; for (let i = path.length - 1; i >= start; --i) { const code = path.charCodeAt(i); if (isWindowsPathSeparator(code)) { if (!matchedSlash) { start = i + 1; break; } } else { if (firstNonSlashEnd === -1) { matchedSlash = false; firstNonSlashEnd = i + 1; } if (extIdx >= 0) { if (code === suffix.charCodeAt(extIdx)) { if (--extIdx === -1) { end = i; } } else { extIdx = -1; end = firstNonSlashEnd; } } } } if (start === end) end = firstNonSlashEnd; else if (end === -1) end = path.length; return path.substring(start, end); } for (let i = path.length - 1; i >= start; --i) { if (isWindowsPathSeparator(path.charCodeAt(i))) { if (!matchedSlash) { start = i + 1; break; } } else if (end === -1) { matchedSlash = false; end = i + 1; } } if (end === -1) return ""; return path.substring(start, end); }; exports.extname = function extname(path) { let start = 0; let startDot = -1; let startPart = 0; let end = -1; let matchedSlash = true; let preDotState = 0; if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) { start = startPart = 2; } for (let i = path.length - 1; i >= start; --i) { const code = path.charCodeAt(i); if (isWindowsPathSeparator(code)) { if (!matchedSlash) { startPart = i + 1; break; } continue; } if (end === -1) { matchedSlash = false; end = i + 1; } if (code === CHAR_DOT) { if (startDot === -1) startDot = i; else if (preDotState !== 1) preDotState = 1; } else if (startDot !== -1) { preDotState = -1; } } if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { return ""; } return path.substring(startDot, end); }; } }); // ../../node_modules/bare-path/index.js var require_bare_path = __commonJS({ "../../node_modules/bare-path/index.js"(exports, module) { if (Bare.platform === "win32") { module.exports = require_win32(); } else { module.exports = require_posix(); } } }); // ../../node_modules/bare-url/binding.js var require_binding2 = __commonJS({ "../../node_modules/bare-url/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-url/lib/errors.js var require_errors2 = __commonJS({ "../../node_modules/bare-url/lib/errors.js"(exports, module) { module.exports = class URLError extends Error { constructor(msg, fn = URLError, code = fn.name) { super(`${code}: ${msg}`); this.code = code; if (Error.captureStackTrace) Error.captureStackTrace(this, fn); } get name() { return "URLError"; } static INVALID_URL(msg, input) { const err = new URLError(msg, URLError.INVALID_URL); err.input = input; return err; } static INVALID_URL_SCHEME(msg = "Invalid URL") { return new URLError(msg, URLError.INVALID_URL_SCHEME); } static INVALID_FILE_URL_HOST(msg = "Invalid file: URL host") { return new URLError(msg, URLError.INVALID_FILE_URL_HOST); } static INVALID_FILE_URL_PATH(msg = "Invalid file: URL path") { return new URLError(msg, URLError.INVALID_FILE_URL_PATH); } }; } }); // ../../node_modules/bare-url/lib/url-search-params.js var require_url_search_params = __commonJS({ "../../node_modules/bare-url/lib/url-search-params.js"(exports, module) { var kind = Symbol.for("bare.url.search-params.kind"); var URLSearchParams = class _URLSearchParams { static _urls = /* @__PURE__ */ new WeakMap(); static get [kind]() { return 0; } // https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams constructor(init, url = null) { this._params = /* @__PURE__ */ new Map(); if (url) _URLSearchParams._urls.set(this, url); if (typeof init === "string") { this._parse(init); } else if (init) { for (const [name, value] of typeof init[Symbol.iterator] === "function" ? init : Object.entries(init)) { this.append(name, value); } } } get [kind]() { return _URLSearchParams[kind]; } // https://url.spec.whatwg.org/#dom-urlsearchparams-size get size() { return this._params.length; } // https://url.spec.whatwg.org/#dom-urlsearchparams-append append(name, value = null) { if (value === null) return; let list = this._params.get(name); if (list === void 0) { list = []; this._params.set(name, list); } list.push(value); this._update(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-delete delete(name, value = null) { if (value === null) this._params.delete(name); else { let list = this._params.get(name); if (list === void 0) return; list = list.filter((found) => found !== value); if (list.length === 0) this._params.delete(name); else this._params.set(name, list); } this._update(); } // https://url.spec.whatwg.org/#dom-urlsearchparams-get get(name) { const list = this._params.get(name); if (list === void 0) return null; return list[0]; } // https://url.spec.whatwg.org/#dom-urlsearchparams-getall getAll(name) { const list = this._params.get(name); if (list === void 0) return []; return Array.from(list); } // https://url.spec.whatwg.org/#dom-urlsearchparams-has has(name, value = null) { const list = this._params.get(name); if (list === void 0) return false; if (value === null) return true; return list.includes(value); } // https://url.spec.whatwg.org/#dom-urlsearchparams-set set(name, value = null) { if (value === null) this._params.delete(name); else this._params.set(name, [value]); this._update(); } toString() { return this._serialize(); } toJSON() { return [...this]; } *[Symbol.iterator]() { for (const [name, values] of this._params) { for (const value of values) yield [name, value]; } } [Symbol.for("bare.inspect")]() { const object = { __proto__: { constructor: _URLSearchParams } }; for (const [name, values] of this._params) { if (values.length === 1) object[name] = values[0]; else object[name] = values; } return object; } // https://url.spec.whatwg.org/#concept-urlsearchparams-update _update() { const url = _URLSearchParams._urls.get(this); if (url === void 0) return; url.search = this._serialize(); } // https://url.spec.whatwg.org/#concept-urlencoded-parser _parse(input) { if (input[0] === "?") input = input.substring(1); this._params = /* @__PURE__ */ new Map(); for (const sequence of input.split("&")) { if (sequence.length === 0) continue; let i = sequence.indexOf("="); if (i === -1) i = sequence.length; const name = decodeURIComponent(sequence.substring(0, i)); const value = decodeURIComponent(sequence.substring(i + 1, sequence.length)); let list = this._params.get(name); if (list === void 0) { list = []; this._params.set(name, list); } list.push(value); } } // https://url.spec.whatwg.org/#concept-urlencoded-serializer _serialize() { let output = ""; for (let [name, values] of this._params) { name = encodeURIComponent(name); for (const value of values) { if (output) output += "&"; output += name + "=" + encodeURIComponent(value); } } return output; } }; module.exports = exports = URLSearchParams; exports.isURLSearchParams = function isURLSearchParams(value) { if (value instanceof URLSearchParams) return true; return typeof value === "object" && value !== null && value[kind] === URLSearchParams[kind]; }; } }); // ../../node_modules/bare-url/index.js var require_bare_url = __commonJS({ "../../node_modules/bare-url/index.js"(exports, module) { var path = require_bare_path(); var binding = require_binding2(); var errors = require_errors2(); var URLSearchParams = require_url_search_params(); var kind = Symbol.for("bare.url.kind"); var isWindows = Bare.platform === "win32"; var URL = class _URL { static get [kind]() { return 0; } constructor(input, base, opts = {}) { if (arguments.length === 0) throw errors.INVALID_URL(); input = String(input); if (base !== void 0) base = String(base); this._components = new Uint32Array(8); this._parse(input, base, opts.throw !== false); if (this._href) this._params = new URLSearchParams(this.search, this); } get [kind]() { return _URL[kind]; } // https://url.spec.whatwg.org/#dom-url-href get href() { return this._href; } set href(value) { this._update(value); this._params._parse(this.search); } // https://url.spec.whatwg.org/#dom-url-protocol get protocol() { return this._slice(0, this._components[0]) + ":"; } set protocol(value) { this._update(this._replace(value.replace(/:+$/, ""), 0, this._components[0])); } // https://url.spec.whatwg.org/#dom-url-username get username() { return this._slice(this._components[0] + 3, this._components[1]); } set username(value) { if (cannotHaveCredentialsOrPort(this)) { return; } if (this.username === "") value += "@"; this._update(this._replace(value, this._components[0] + 3, this._components[1])); } // https://url.spec.whatwg.org/#dom-url-password get password() { return this._href.slice( this._components[1] + 1, this._components[2] - 1 /* @ */ ); } set password(value) { if (cannotHaveCredentialsOrPort(this)) { return; } let start = this._components[1] + 1; let end = this._components[2] - 1; if (this.password === "") { value = ":" + value; start--; } if (this.username === "") { value += "@"; end++; } this._update(this._replace(value, start, end)); } // https://url.spec.whatwg.org/#dom-url-host get host() { return this._slice(this._components[2], this._components[5]); } set host(value) { if (hasOpaquePath(this)) { return; } this._update( this._replace(value, this._components[2], this._components[value.includes(":") ? 5 : 3]) ); } // https://url.spec.whatwg.org/#dom-url-hostname get hostname() { return this._slice(this._components[2], this._components[3]); } set hostname(value) { if (hasOpaquePath(this)) { return; } this._update(this._replace(value, this._components[2], this._components[3])); } // https://url.spec.whatwg.org/#dom-url-port get port() { return this._slice(this._components[3] + 1, this._components[5]); } set port(value) { if (cannotHaveCredentialsOrPort(this)) { return; } let start = this._components[3] + 1; if (this.port === "") { value = ":" + value; start--; } this._update(this._replace(value, start, this._components[5])); } // https://url.spec.whatwg.org/#dom-url-pathname get pathname() { return this._slice( this._components[5], this._components[6] - 1 /* ? */ ); } set pathname(value) { if (hasOpaquePath(this)) { return; } if (value[0] !== "/" && value[0] !== "\\") { value = "/" + value; } this._update(this._replace( value, this._components[5], this._components[6] - 1 /* ? */ )); } // https://url.spec.whatwg.org/#dom-url-search get search() { return this._slice( this._components[6] - 1, this._components[7] - 1 /* # */ ); } set search(value) { if (value && value[0] !== "?") value = "?" + value; this._update( this._replace( value, this._components[6] - 1, this._components[7] - 1 /* # */ ) ); this._params._parse(this.search); } // https://url.spec.whatwg.org/#dom-url-searchparams get searchParams() { return this._params; } // https://url.spec.whatwg.org/#dom-url-hash get hash() { return this._slice( this._components[7] - 1 /* # */ ); } set hash(value) { if (value && value[0] !== "#") value = "#" + value; this._update(this._replace( value, this._components[7] - 1 /* # */ )); } toString() { return this._href; } toJSON() { return this._href; } [Symbol.for("bare.inspect")]() { return { __proto__: { constructor: _URL }, href: this.href, protocol: this.protocol, username: this.username, password: this.password, host: this.host, hostname: this.hostname, port: this.port, pathname: this.pathname, search: this.search, searchParams: this.searchParams, hash: this.hash }; } _slice(start, end = this._href.length) { return this._href.slice(start, end); } _replace(replacement, start, end = this._href.length) { return this._slice(0, start) + replacement + this._slice(end); } _parse(input, base, shouldThrow) { try { this._href = binding.parse( String(input), base ? String(base) : null, this._components, shouldThrow ); } catch (err) { if (err instanceof TypeError) throw err; throw errors.INVALID_URL(`Invalid URL '${input}'`, input); } } _update(input) { try { this._parse(input, null, true); } catch (err) { if (err instanceof TypeError) throw err; } } }; module.exports = exports = URL; function hasOpaquePath(url) { return url.pathname[0] !== "/"; } function cannotHaveCredentialsOrPort(url) { return url.hostname === "" || url.protocol === "file:"; } exports.URL = URL; exports.URLSearchParams = URLSearchParams; exports.errors = errors; exports.isURL = function isURL(value) { if (value instanceof URL) return true; return typeof value === "object" && value !== null && value[kind] === URL[kind]; }; exports.isURLSearchParams = URLSearchParams.isURLSearchParams; exports.parse = function parse(input, base) { const url = new URL(input, base, { throw: false }); return url._href ? url : null; }; exports.canParse = function canParse(input, base) { return binding.canParse(String(input), base ? String(base) : null); }; exports.fileURLToPath = function fileURLToPath(url) { if (typeof url === "string") { url = new URL(url); } if (url.protocol !== "file:") { throw errors.INVALID_URL_SCHEME("The URL must use the file: protocol"); } if (isWindows) { if (/%2f|%5c/i.test(url.pathname)) { throw errors.INVALID_FILE_URL_PATH( "The file: URL path must not include encoded \\ or / characters" ); } } else { if (url.hostname) { throw errors.INVALID_FILE_URL_HOST("The file: URL host must be 'localhost' or empty"); } if (/%2f/i.test(url.pathname)) { throw errors.INVALID_FILE_URL_PATH("The file: URL path must not include encoded / characters"); } } const pathname = path.normalize(decodeURIComponent(url.pathname)); if (isWindows) { if (url.hostname) return "\\\\" + url.hostname + pathname; const letter = pathname.charCodeAt(1) | 32; if (letter < 97 || letter > 122 || pathname.charCodeAt(2) !== 58) { throw errors.INVALID_FILE_URL_PATH("The file: URL path must be absolute"); } return pathname.slice(1); } return pathname; }; exports.pathToFileURL = function pathToFileURL(pathname) { let resolved = path.resolve(pathname); if (pathname[pathname.length - 1] === "/") { resolved += "/"; } else if (isWindows && pathname[pathname.length - 1] === "\\") { resolved += "\\"; } resolved = resolved.replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("?", "%3f").replaceAll("\n", "%0a").replaceAll("\r", "%0d").replaceAll(" ", "%09"); if (!isWindows) { resolved = resolved.replaceAll("\\", "%5c"); } return new URL("file:" + resolved); }; exports.format = function format(parts) { const { protocol, auth, host, hostname, port, pathname, search, query, hash, slashes } = parts; let result = ""; if (typeof protocol === "string") { result += protocol; if (protocol[protocol.length - 1] !== ":") { result += ":"; } if (slashes === true || /https?|ftp|gopher|file/.test(protocol)) { result += "//"; } } if (typeof auth === "string") { if (host || hostname) result += auth + "@"; } if (typeof host === "string") result += host; else { result += hostname; if (port) result += ":" + port; } if (typeof pathname === "string" && pathname !== "") { if (pathname[0] !== "/") result += "/"; result += pathname; } if (typeof search === "string") { if (search[0] !== "?") result += "?"; result += search; } else if (typeof query === "object" && query !== null) { result += "?" + new URLSearchParams(query); } if (typeof hash === "string") { if (hash[0] !== "#") result += "#"; result += hash; } return result; }; } }); // ../../node_modules/bare-prom-client/lib/pushgateway.js var require_pushgateway = __commonJS({ "../../node_modules/bare-prom-client/lib/pushgateway.js"(exports, module) { "use strict"; var url = require_bare_url(); var http = __require("http"); var https = __require("https"); var { gzipSync } = __require("zlib"); var { globalRegistry } = require_registry(); var Pushgateway = class { constructor(gatewayUrl, options, registry) { if (!registry) { registry = globalRegistry; } this.registry = registry; this.gatewayUrl = gatewayUrl; const { requireJobName, ...requestOptions } = { requireJobName: true, ...options }; this.requireJobName = requireJobName; this.requestOptions = requestOptions; } pushAdd(params = {}) { if (this.requireJobName && !params.jobName) { throw new Error("Missing jobName parameter"); } return useGateway.call(this, "POST", params.jobName, params.groupings); } push(params = {}) { if (this.requireJobName && !params.jobName) { throw new Error("Missing jobName parameter"); } return useGateway.call(this, "PUT", params.jobName, params.groupings); } delete(params = {}) { if (this.requireJobName && !params.jobName) { throw new Error("Missing jobName parameter"); } return useGateway.call(this, "DELETE", params.jobName, params.groupings); } }; async function useGateway(method, job, groupings) { const gatewayUrlParsed = url.parse(this.gatewayUrl); const gatewayUrlPath = gatewayUrlParsed.pathname && gatewayUrlParsed.pathname !== "/" ? gatewayUrlParsed.pathname : ""; const jobPath = job ? `/job/${encodeURIComponent(job)}${generateGroupings(groupings)}` : ""; const path = `${gatewayUrlPath}/metrics${jobPath}`; const target = url.resolve(this.gatewayUrl, path); const requestParams = url.parse(target); const httpModule = isHttps(requestParams.href) ? https : http; const options = Object.assign(requestParams, this.requestOptions, { method }); return new Promise((resolve, reject) => { if (method === "DELETE" && options.headers) { delete options.headers["Content-Encoding"]; } const req = httpModule.request(options, (resp) => { let body = ""; resp.setEncoding("utf8"); resp.on("data", (chunk) => { body += chunk; }); resp.on("end", () => { if (resp.statusCode >= 400) { reject( new Error(`push failed with status ${resp.statusCode}, ${body}`) ); } else { resolve({ resp, body }); } }); }); req.on("error", (err) => { reject(err); }); req.on("timeout", () => { req.destroy(new Error("Pushgateway request timed out")); }); if (method !== "DELETE") { this.registry.metrics().then((metrics2) => { if (options.headers && options.headers["Content-Encoding"] === "gzip") { metrics2 = gzipSync(metrics2); } req.write(metrics2); req.end(); }).catch((err) => { reject(err); }); } else { req.end(); } }); } function generateGroupings(groupings) { if (!groupings) { return ""; } return Object.keys(groupings).map( (key) => `/${encodeURIComponent(key)}/${encodeURIComponent(groupings[key])}` ).join(""); } function isHttps(href) { return href.search(/^https/) !== -1; } module.exports = Pushgateway; } }); // ../../node_modules/bare-prom-client/lib/bucketGenerators.js var require_bucketGenerators = __commonJS({ "../../node_modules/bare-prom-client/lib/bucketGenerators.js"(exports) { "use strict"; exports.linearBuckets = (start, width, count) => { if (count < 1) { throw new Error("Linear buckets needs a positive count"); } const buckets = new Array(count); for (let i = 0; i < count; i++) { buckets[i] = start + i * width; } return buckets; }; exports.exponentialBuckets = (start, factor, count) => { if (start <= 0) { throw new Error("Exponential buckets needs a positive start"); } if (count < 1) { throw new Error("Exponential buckets needs a positive count"); } if (factor <= 1) { throw new Error("Exponential buckets needs a factor greater than 1"); } const buckets = new Array(count); for (let i = 0; i < count; i++) { buckets[i] = start; start *= factor; } return buckets; }; } }); // ../../node_modules/@opentelemetry/api/build/esm/version.js var VERSION; var init_version = __esm({ "../../node_modules/@opentelemetry/api/build/esm/version.js"() { VERSION = "1.9.1"; } }); // ../../node_modules/@opentelemetry/api/build/esm/internal/semver.js function _makeCompatibilityCheck(ownVersion) { const acceptedVersions = /* @__PURE__ */ new Set([ownVersion]); const rejectedVersions = /* @__PURE__ */ new Set(); const myVersionMatch = ownVersion.match(re); if (!myVersionMatch) { return () => false; } const ownVersionParsed = { major: +myVersionMatch[1], minor: +myVersionMatch[2], patch: +myVersionMatch[3], prerelease: myVersionMatch[4] }; if (ownVersionParsed.prerelease != null) { return function isExactmatch(globalVersion) { return globalVersion === ownVersion; }; } function _reject(v) { rejectedVersions.add(v); return false; } function _accept(v) { acceptedVersions.add(v); return true; } return function isCompatible2(globalVersion) { if (acceptedVersions.has(globalVersion)) { return true; } if (rejectedVersions.has(globalVersion)) { return false; } const globalVersionMatch = globalVersion.match(re); if (!globalVersionMatch) { return _reject(globalVersion); } const globalVersionParsed = { major: +globalVersionMatch[1], minor: +globalVersionMatch[2], patch: +globalVersionMatch[3], prerelease: globalVersionMatch[4] }; if (globalVersionParsed.prerelease != null) { return _reject(globalVersion); } if (ownVersionParsed.major !== globalVersionParsed.major) { return _reject(globalVersion); } if (ownVersionParsed.major === 0) { if (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) { return _accept(globalVersion); } return _reject(globalVersion); } if (ownVersionParsed.minor <= globalVersionParsed.minor) { return _accept(globalVersion); } return _reject(globalVersion); }; } var re, isCompatible; var init_semver = __esm({ "../../node_modules/@opentelemetry/api/build/esm/internal/semver.js"() { init_version(); re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; isCompatible = _makeCompatibilityCheck(VERSION); } }); // ../../node_modules/@opentelemetry/api/build/esm/internal/global-utils.js function registerGlobal(type, instance, diag3, allowOverride = false) { var _a; const api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: VERSION }; if (!allowOverride && api[type]) { const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); diag3.error(err.stack || err.message); return false; } if (api.version !== VERSION) { const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION}`); diag3.error(err.stack || err.message); return false; } api[type] = instance; diag3.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION}.`); return true; } function getGlobal(type) { var _a, _b; const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; if (!globalVersion || !isCompatible(globalVersion)) { return; } return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; } function unregisterGlobal(type, diag3) { diag3.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION}.`); const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; if (api) { delete api[type]; } } var major, GLOBAL_OPENTELEMETRY_API_KEY, _global; var init_global_utils = __esm({ "../../node_modules/@opentelemetry/api/build/esm/internal/global-utils.js"() { init_version(); init_semver(); major = VERSION.split(".")[0]; GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); _global = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {}; } }); // ../../node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js function logProxy(funcName, namespace, args) { const logger = getGlobal("diag"); if (!logger) { return; } return logger[funcName](namespace, ...args); } var DiagComponentLogger; var init_ComponentLogger = __esm({ "../../node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js"() { init_global_utils(); DiagComponentLogger = class { constructor(props) { this._namespace = props.namespace || "DiagComponentLogger"; } debug(...args) { return logProxy("debug", this._namespace, args); } error(...args) { return logProxy("error", this._namespace, args); } info(...args) { return logProxy("info", this._namespace, args); } warn(...args) { return logProxy("warn", this._namespace, args); } verbose(...args) { return logProxy("verbose", this._namespace, args); } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/diag/types.js var DiagLogLevel; var init_types = __esm({ "../../node_modules/@opentelemetry/api/build/esm/diag/types.js"() { (function(DiagLogLevel2) { DiagLogLevel2[DiagLogLevel2["NONE"] = 0] = "NONE"; DiagLogLevel2[DiagLogLevel2["ERROR"] = 30] = "ERROR"; DiagLogLevel2[DiagLogLevel2["WARN"] = 50] = "WARN"; DiagLogLevel2[DiagLogLevel2["INFO"] = 60] = "INFO"; DiagLogLevel2[DiagLogLevel2["DEBUG"] = 70] = "DEBUG"; DiagLogLevel2[DiagLogLevel2["VERBOSE"] = 80] = "VERBOSE"; DiagLogLevel2[DiagLogLevel2["ALL"] = 9999] = "ALL"; })(DiagLogLevel || (DiagLogLevel = {})); } }); // ../../node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js function createLogLevelDiagLogger(maxLevel, logger) { if (maxLevel < DiagLogLevel.NONE) { maxLevel = DiagLogLevel.NONE; } else if (maxLevel > DiagLogLevel.ALL) { maxLevel = DiagLogLevel.ALL; } logger = logger || {}; function _filterFunc(funcName, theLevel) { const theFunc = logger[funcName]; if (typeof theFunc === "function" && maxLevel >= theLevel) { return theFunc.bind(logger); } return function() { }; } return { error: _filterFunc("error", DiagLogLevel.ERROR), warn: _filterFunc("warn", DiagLogLevel.WARN), info: _filterFunc("info", DiagLogLevel.INFO), debug: _filterFunc("debug", DiagLogLevel.DEBUG), verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE) }; } var init_logLevelLogger = __esm({ "../../node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js"() { init_types(); } }); // ../../node_modules/@opentelemetry/api/build/esm/api/diag.js var API_NAME, DiagAPI; var init_diag = __esm({ "../../node_modules/@opentelemetry/api/build/esm/api/diag.js"() { init_ComponentLogger(); init_logLevelLogger(); init_types(); init_global_utils(); API_NAME = "diag"; DiagAPI = class _DiagAPI { /** Get the singleton instance of the DiagAPI API */ static instance() { if (!this._instance) { this._instance = new _DiagAPI(); } return this._instance; } /** * Private internal constructor * @private */ constructor() { function _logProxy(funcName) { return function(...args) { const logger = getGlobal("diag"); if (!logger) return; return logger[funcName](...args); }; } const self2 = this; const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => { var _a, _b, _c; if (logger === self2) { const err = new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation"); self2.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); return false; } if (typeof optionsOrLogLevel === "number") { optionsOrLogLevel = { logLevel: optionsOrLogLevel }; } const oldLogger = getGlobal("diag"); const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger); if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ""; oldLogger.warn(`Current logger will be overwritten from ${stack}`); newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); } return registerGlobal("diag", newLogger, self2, true); }; self2.setLogger = setLogger; self2.disable = () => { unregisterGlobal(API_NAME, self2); }; self2.createComponentLogger = (options) => { return new DiagComponentLogger(options); }; self2.verbose = _logProxy("verbose"); self2.debug = _logProxy("debug"); self2.info = _logProxy("info"); self2.warn = _logProxy("warn"); self2.error = _logProxy("error"); } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js var BaggageImpl; var init_baggage_impl = __esm({ "../../node_modules/@opentelemetry/api/build/esm/baggage/internal/baggage-impl.js"() { BaggageImpl = class _BaggageImpl { constructor(entries) { this._entries = entries ? new Map(entries) : /* @__PURE__ */ new Map(); } getEntry(key) { const entry = this._entries.get(key); if (!entry) { return void 0; } return Object.assign({}, entry); } getAllEntries() { return Array.from(this._entries.entries()); } setEntry(key, entry) { const newBaggage = new _BaggageImpl(this._entries); newBaggage._entries.set(key, entry); return newBaggage; } removeEntry(key) { const newBaggage = new _BaggageImpl(this._entries); newBaggage._entries.delete(key); return newBaggage; } removeEntries(...keys) { const newBaggage = new _BaggageImpl(this._entries); for (const key of keys) { newBaggage._entries.delete(key); } return newBaggage; } clear() { return new _BaggageImpl(); } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js var baggageEntryMetadataSymbol; var init_symbol = __esm({ "../../node_modules/@opentelemetry/api/build/esm/baggage/internal/symbol.js"() { baggageEntryMetadataSymbol = Symbol("BaggageEntryMetadata"); } }); // ../../node_modules/@opentelemetry/api/build/esm/baggage/utils.js function createBaggage(entries = {}) { return new BaggageImpl(new Map(Object.entries(entries))); } function baggageEntryMetadataFromString(str) { if (typeof str !== "string") { diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); str = ""; } return { __TYPE__: baggageEntryMetadataSymbol, toString() { return str; } }; } var diag; var init_utils = __esm({ "../../node_modules/@opentelemetry/api/build/esm/baggage/utils.js"() { init_diag(); init_baggage_impl(); init_symbol(); diag = DiagAPI.instance(); } }); // ../../node_modules/@opentelemetry/api/build/esm/context/context.js function createContextKey(description) { return Symbol.for(description); } var BaseContext, ROOT_CONTEXT; var init_context = __esm({ "../../node_modules/@opentelemetry/api/build/esm/context/context.js"() { BaseContext = class _BaseContext { /** * Construct a new context which inherits values from an optional parent context. * * @param parentContext a context from which to inherit values */ constructor(parentContext) { const self2 = this; self2._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map(); self2.getValue = (key) => self2._currentContext.get(key); self2.setValue = (key, value) => { const context2 = new _BaseContext(self2._currentContext); context2._currentContext.set(key, value); return context2; }; self2.deleteValue = (key) => { const context2 = new _BaseContext(self2._currentContext); context2._currentContext.delete(key); return context2; }; } }; ROOT_CONTEXT = new BaseContext(); } }); // ../../node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js var consoleMap, _originalConsoleMethods, DiagConsoleLogger; var init_consoleLogger = __esm({ "../../node_modules/@opentelemetry/api/build/esm/diag/consoleLogger.js"() { consoleMap = [ { n: "error", c: "error" }, { n: "warn", c: "warn" }, { n: "info", c: "info" }, { n: "debug", c: "debug" }, { n: "verbose", c: "trace" } ]; _originalConsoleMethods = {}; if (typeof console !== "undefined") { const keys = [ "error", "warn", "info", "debug", "trace", "log" ]; for (const key of keys) { if (typeof console[key] === "function") { _originalConsoleMethods[key] = console[key]; } } } DiagConsoleLogger = class { constructor() { function _consoleFunc(funcName) { return function(...args) { let theFunc = _originalConsoleMethods[funcName]; if (typeof theFunc !== "function") { theFunc = _originalConsoleMethods["log"]; } if (typeof theFunc !== "function" && console) { theFunc = console[funcName]; if (typeof theFunc !== "function") { theFunc = console.log; } } if (typeof theFunc === "function") { return theFunc.apply(console, args); } }; } for (let i = 0; i < consoleMap.length; i++) { this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); } } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js function createNoopMeter() { return NOOP_METER; } var NoopMeter, NoopMetric, NoopCounterMetric, NoopUpDownCounterMetric, NoopGaugeMetric, NoopHistogramMetric, NoopObservableMetric, NoopObservableCounterMetric, NoopObservableGaugeMetric, NoopObservableUpDownCounterMetric, NOOP_METER, NOOP_COUNTER_METRIC, NOOP_GAUGE_METRIC, NOOP_HISTOGRAM_METRIC, NOOP_UP_DOWN_COUNTER_METRIC, NOOP_OBSERVABLE_COUNTER_METRIC, NOOP_OBSERVABLE_GAUGE_METRIC, NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; var init_NoopMeter = __esm({ "../../node_modules/@opentelemetry/api/build/esm/metrics/NoopMeter.js"() { NoopMeter = class { constructor() { } /** * @see {@link Meter.createGauge} */ createGauge(_name, _options) { return NOOP_GAUGE_METRIC; } /** * @see {@link Meter.createHistogram} */ createHistogram(_name, _options) { return NOOP_HISTOGRAM_METRIC; } /** * @see {@link Meter.createCounter} */ createCounter(_name, _options) { return NOOP_COUNTER_METRIC; } /** * @see {@link Meter.createUpDownCounter} */ createUpDownCounter(_name, _options) { return NOOP_UP_DOWN_COUNTER_METRIC; } /** * @see {@link Meter.createObservableGauge} */ createObservableGauge(_name, _options) { return NOOP_OBSERVABLE_GAUGE_METRIC; } /** * @see {@link Meter.createObservableCounter} */ createObservableCounter(_name, _options) { return NOOP_OBSERVABLE_COUNTER_METRIC; } /** * @see {@link Meter.createObservableUpDownCounter} */ createObservableUpDownCounter(_name, _options) { return NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; } /** * @see {@link Meter.addBatchObservableCallback} */ addBatchObservableCallback(_callback, _observables) { } /** * @see {@link Meter.removeBatchObservableCallback} */ removeBatchObservableCallback(_callback) { } }; NoopMetric = class { }; NoopCounterMetric = class extends NoopMetric { add(_value, _attributes) { } }; NoopUpDownCounterMetric = class extends NoopMetric { add(_value, _attributes) { } }; NoopGaugeMetric = class extends NoopMetric { record(_value, _attributes) { } }; NoopHistogramMetric = class extends NoopMetric { record(_value, _attributes) { } }; NoopObservableMetric = class { addCallback(_callback) { } removeCallback(_callback) { } }; NoopObservableCounterMetric = class extends NoopObservableMetric { }; NoopObservableGaugeMetric = class extends NoopObservableMetric { }; NoopObservableUpDownCounterMetric = class extends NoopObservableMetric { }; NOOP_METER = new NoopMeter(); NOOP_COUNTER_METRIC = new NoopCounterMetric(); NOOP_GAUGE_METRIC = new NoopGaugeMetric(); NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); } }); // ../../node_modules/@opentelemetry/api/build/esm/metrics/Metric.js var ValueType; var init_Metric = __esm({ "../../node_modules/@opentelemetry/api/build/esm/metrics/Metric.js"() { (function(ValueType2) { ValueType2[ValueType2["INT"] = 0] = "INT"; ValueType2[ValueType2["DOUBLE"] = 1] = "DOUBLE"; })(ValueType || (ValueType = {})); } }); // ../../node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js var defaultTextMapGetter, defaultTextMapSetter; var init_TextMapPropagator = __esm({ "../../node_modules/@opentelemetry/api/build/esm/propagation/TextMapPropagator.js"() { defaultTextMapGetter = { get(carrier, key) { if (carrier == null) { return void 0; } return carrier[key]; }, keys(carrier) { if (carrier == null) { return []; } return Object.keys(carrier); } }; defaultTextMapSetter = { set(carrier, key, value) { if (carrier == null) { return; } carrier[key] = value; } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js var NoopContextManager; var init_NoopContextManager = __esm({ "../../node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js"() { init_context(); NoopContextManager = class { active() { return ROOT_CONTEXT; } with(_context, fn, thisArg, ...args) { return fn.call(thisArg, ...args); } bind(_context, target) { return target; } enable() { return this; } disable() { return this; } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/api/context.js var API_NAME2, NOOP_CONTEXT_MANAGER, ContextAPI; var init_context2 = __esm({ "../../node_modules/@opentelemetry/api/build/esm/api/context.js"() { init_NoopContextManager(); init_global_utils(); init_diag(); API_NAME2 = "context"; NOOP_CONTEXT_MANAGER = new NoopContextManager(); ContextAPI = class _ContextAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { } /** Get the singleton instance of the Context API */ static getInstance() { if (!this._instance) { this._instance = new _ContextAPI(); } return this._instance; } /** * Set the current context manager. * * @returns true if the context manager was successfully registered, else false */ setGlobalContextManager(contextManager) { return registerGlobal(API_NAME2, contextManager, DiagAPI.instance()); } /** * Get the currently active context */ active() { return this._getContextManager().active(); } /** * Execute a function with an active context * * @param context context to be active during function execution * @param fn function to execute in a context * @param thisArg optional receiver to be used for calling fn * @param args optional arguments forwarded to fn */ with(context2, fn, thisArg, ...args) { return this._getContextManager().with(context2, fn, thisArg, ...args); } /** * Bind a context to a target function or event emitter * * @param context context to bind to the event emitter or function. Defaults to the currently active context * @param target function or event emitter to bind */ bind(context2, target) { return this._getContextManager().bind(context2, target); } _getContextManager() { return getGlobal(API_NAME2) || NOOP_CONTEXT_MANAGER; } /** Disable and remove the global context manager */ disable() { this._getContextManager().disable(); unregisterGlobal(API_NAME2, DiagAPI.instance()); } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js var TraceFlags; var init_trace_flags = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js"() { (function(TraceFlags2) { TraceFlags2[TraceFlags2["NONE"] = 0] = "NONE"; TraceFlags2[TraceFlags2["SAMPLED"] = 1] = "SAMPLED"; })(TraceFlags || (TraceFlags = {})); } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js var INVALID_SPANID, INVALID_TRACEID, INVALID_SPAN_CONTEXT; var init_invalid_span_constants = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/invalid-span-constants.js"() { init_trace_flags(); INVALID_SPANID = "0000000000000000"; INVALID_TRACEID = "00000000000000000000000000000000"; INVALID_SPAN_CONTEXT = { traceId: INVALID_TRACEID, spanId: INVALID_SPANID, traceFlags: TraceFlags.NONE }; } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js var NonRecordingSpan; var init_NonRecordingSpan = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js"() { init_invalid_span_constants(); NonRecordingSpan = class { constructor(spanContext = INVALID_SPAN_CONTEXT) { this._spanContext = spanContext; } // Returns a SpanContext. spanContext() { return this._spanContext; } // By default does nothing setAttribute(_key, _value) { return this; } // By default does nothing setAttributes(_attributes) { return this; } // By default does nothing addEvent(_name, _attributes) { return this; } addLink(_link) { return this; } addLinks(_links) { return this; } // By default does nothing setStatus(_status) { return this; } // By default does nothing updateName(_name) { return this; } // By default does nothing end(_endTime) { } // isRecording always returns false for NonRecordingSpan. isRecording() { return false; } // By default does nothing recordException(_exception, _time) { } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/context-utils.js function getSpan(context2) { return context2.getValue(SPAN_KEY) || void 0; } function getActiveSpan() { return getSpan(ContextAPI.getInstance().active()); } function setSpan(context2, span) { return context2.setValue(SPAN_KEY, span); } function deleteSpan(context2) { return context2.deleteValue(SPAN_KEY); } function setSpanContext(context2, spanContext) { return setSpan(context2, new NonRecordingSpan(spanContext)); } function getSpanContext(context2) { var _a; return (_a = getSpan(context2)) === null || _a === void 0 ? void 0 : _a.spanContext(); } var SPAN_KEY; var init_context_utils = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/context-utils.js"() { init_context(); init_NonRecordingSpan(); init_context2(); SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN"); } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js function isValidHex(id, length) { if (typeof id !== "string" || id.length !== length) return false; let r = 0; for (let i = 0; i < id.length; i += 4) { r += (isHex[id.charCodeAt(i)] | 0) + (isHex[id.charCodeAt(i + 1)] | 0) + (isHex[id.charCodeAt(i + 2)] | 0) + (isHex[id.charCodeAt(i + 3)] | 0); } return r === length; } function isValidTraceId(traceId) { return isValidHex(traceId, 32) && traceId !== INVALID_TRACEID; } function isValidSpanId(spanId) { return isValidHex(spanId, 16) && spanId !== INVALID_SPANID; } function isSpanContextValid(spanContext) { return isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId); } function wrapSpanContext(spanContext) { return new NonRecordingSpan(spanContext); } var isHex; var init_spancontext_utils = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js"() { init_invalid_span_constants(); init_NonRecordingSpan(); isHex = new Uint8Array([ 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 ]); } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js function isSpanContext(spanContext) { return spanContext !== null && typeof spanContext === "object" && "spanId" in spanContext && typeof spanContext["spanId"] === "string" && "traceId" in spanContext && typeof spanContext["traceId"] === "string" && "traceFlags" in spanContext && typeof spanContext["traceFlags"] === "number"; } var contextApi, NoopTracer; var init_NoopTracer = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js"() { init_context2(); init_context_utils(); init_NonRecordingSpan(); init_spancontext_utils(); contextApi = ContextAPI.getInstance(); NoopTracer = class { // startSpan starts a noop span. startSpan(name, options, context2 = contextApi.active()) { const root = Boolean(options === null || options === void 0 ? void 0 : options.root); if (root) { return new NonRecordingSpan(); } const parentFromContext = context2 && getSpanContext(context2); if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) { return new NonRecordingSpan(parentFromContext); } else { return new NonRecordingSpan(); } } startActiveSpan(name, arg2, arg3, arg4) { let opts; let ctx; let fn; if (arguments.length < 2) { return; } else if (arguments.length === 2) { fn = arg2; } else if (arguments.length === 3) { opts = arg2; fn = arg3; } else { opts = arg2; ctx = arg3; fn = arg4; } const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); const span = this.startSpan(name, opts, parentContext); const contextWithSpanSet = setSpan(parentContext, span); return contextApi.with(contextWithSpanSet, fn, void 0, span); } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js var NOOP_TRACER, ProxyTracer; var init_ProxyTracer = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js"() { init_NoopTracer(); NOOP_TRACER = new NoopTracer(); ProxyTracer = class { constructor(provider, name, version, options) { this._provider = provider; this.name = name; this.version = version; this.options = options; } startSpan(name, options, context2) { return this._getTracer().startSpan(name, options, context2); } startActiveSpan(_name, _options, _context, _fn) { const tracer = this._getTracer(); return Reflect.apply(tracer.startActiveSpan, tracer, arguments); } /** * Try to get a tracer from the proxy tracer provider. * If the proxy tracer provider has no delegate, return a noop tracer. */ _getTracer() { if (this._delegate) { return this._delegate; } const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); if (!tracer) { return NOOP_TRACER; } this._delegate = tracer; return this._delegate; } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js var NoopTracerProvider; var init_NoopTracerProvider = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js"() { init_NoopTracer(); NoopTracerProvider = class { getTracer(_name, _version, _options) { return new NoopTracer(); } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js var NOOP_TRACER_PROVIDER, ProxyTracerProvider; var init_ProxyTracerProvider = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js"() { init_ProxyTracer(); init_NoopTracerProvider(); NOOP_TRACER_PROVIDER = new NoopTracerProvider(); ProxyTracerProvider = class { /** * Get a {@link ProxyTracer} */ getTracer(name, version, options) { var _a; return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options); } getDelegate() { var _a; return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; } /** * Set the delegate tracer provider */ setDelegate(delegate) { this._delegate = delegate; } getDelegateTracer(name, version, options) { var _a; return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js var SamplingDecision; var init_SamplingResult = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/SamplingResult.js"() { (function(SamplingDecision2) { SamplingDecision2[SamplingDecision2["NOT_RECORD"] = 0] = "NOT_RECORD"; SamplingDecision2[SamplingDecision2["RECORD"] = 1] = "RECORD"; SamplingDecision2[SamplingDecision2["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; })(SamplingDecision || (SamplingDecision = {})); } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/span_kind.js var SpanKind; var init_span_kind = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/span_kind.js"() { (function(SpanKind2) { SpanKind2[SpanKind2["INTERNAL"] = 0] = "INTERNAL"; SpanKind2[SpanKind2["SERVER"] = 1] = "SERVER"; SpanKind2[SpanKind2["CLIENT"] = 2] = "CLIENT"; SpanKind2[SpanKind2["PRODUCER"] = 3] = "PRODUCER"; SpanKind2[SpanKind2["CONSUMER"] = 4] = "CONSUMER"; })(SpanKind || (SpanKind = {})); } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/status.js var SpanStatusCode; var init_status = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/status.js"() { (function(SpanStatusCode2) { SpanStatusCode2[SpanStatusCode2["UNSET"] = 0] = "UNSET"; SpanStatusCode2[SpanStatusCode2["OK"] = 1] = "OK"; SpanStatusCode2[SpanStatusCode2["ERROR"] = 2] = "ERROR"; })(SpanStatusCode || (SpanStatusCode = {})); } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js function validateKey(key) { return VALID_KEY_REGEX.test(key); } function validateValue(value) { return VALID_VALUE_BASE_REGEX.test(value) && !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value); } var VALID_KEY_CHAR_RANGE, VALID_KEY, VALID_VENDOR_KEY, VALID_KEY_REGEX, VALID_VALUE_BASE_REGEX, INVALID_VALUE_COMMA_EQUAL_REGEX; var init_tracestate_validators = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-validators.js"() { VALID_KEY_CHAR_RANGE = "[_0-9a-z-*/]"; VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js var MAX_TRACE_STATE_ITEMS, MAX_TRACE_STATE_LEN, LIST_MEMBERS_SEPARATOR, LIST_MEMBER_KEY_VALUE_SPLITTER, TraceStateImpl; var init_tracestate_impl = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/internal/tracestate-impl.js"() { init_tracestate_validators(); MAX_TRACE_STATE_ITEMS = 32; MAX_TRACE_STATE_LEN = 512; LIST_MEMBERS_SEPARATOR = ","; LIST_MEMBER_KEY_VALUE_SPLITTER = "="; TraceStateImpl = class _TraceStateImpl { constructor(rawTraceState) { this._internalState = /* @__PURE__ */ new Map(); if (rawTraceState) this._parse(rawTraceState); } set(key, value) { const traceState = this._clone(); if (traceState._internalState.has(key)) { traceState._internalState.delete(key); } traceState._internalState.set(key, value); return traceState; } unset(key) { const traceState = this._clone(); traceState._internalState.delete(key); return traceState; } get(key) { return this._internalState.get(key); } serialize() { return Array.from(this._internalState.keys()).reduceRight((agg, key) => { agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); return agg; }, []).join(LIST_MEMBERS_SEPARATOR); } _parse(rawTraceState) { if (rawTraceState.length > MAX_TRACE_STATE_LEN) return; this._internalState = rawTraceState.split(LIST_MEMBERS_SEPARATOR).reduceRight((agg, part) => { const listMember = part.trim(); const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); if (i !== -1) { const key = listMember.slice(0, i); const value = listMember.slice(i + 1, part.length); if (validateKey(key) && validateValue(value)) { agg.set(key, value); } else { } } return agg; }, /* @__PURE__ */ new Map()); if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { this._internalState = new Map(Array.from(this._internalState.entries()).reverse().slice(0, MAX_TRACE_STATE_ITEMS)); } } // @ts-expect-error TS6133 Accessed in tests only. _keys() { return Array.from(this._internalState.keys()).reverse(); } _clone() { const traceState = new _TraceStateImpl(); traceState._internalState = new Map(this._internalState); return traceState; } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js function createTraceState(rawTraceState) { return new TraceStateImpl(rawTraceState); } var init_utils2 = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace/internal/utils.js"() { init_tracestate_impl(); } }); // ../../node_modules/@opentelemetry/api/build/esm/context-api.js var context; var init_context_api = __esm({ "../../node_modules/@opentelemetry/api/build/esm/context-api.js"() { init_context2(); context = ContextAPI.getInstance(); } }); // ../../node_modules/@opentelemetry/api/build/esm/diag-api.js var diag2; var init_diag_api = __esm({ "../../node_modules/@opentelemetry/api/build/esm/diag-api.js"() { init_diag(); diag2 = DiagAPI.instance(); } }); // ../../node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js var NoopMeterProvider, NOOP_METER_PROVIDER; var init_NoopMeterProvider = __esm({ "../../node_modules/@opentelemetry/api/build/esm/metrics/NoopMeterProvider.js"() { init_NoopMeter(); NoopMeterProvider = class { getMeter(_name, _version, _options) { return NOOP_METER; } }; NOOP_METER_PROVIDER = new NoopMeterProvider(); } }); // ../../node_modules/@opentelemetry/api/build/esm/api/metrics.js var API_NAME3, MetricsAPI; var init_metrics = __esm({ "../../node_modules/@opentelemetry/api/build/esm/api/metrics.js"() { init_NoopMeterProvider(); init_global_utils(); init_diag(); API_NAME3 = "metrics"; MetricsAPI = class _MetricsAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { } /** Get the singleton instance of the Metrics API */ static getInstance() { if (!this._instance) { this._instance = new _MetricsAPI(); } return this._instance; } /** * Set the current global meter provider. * Returns true if the meter provider was successfully registered, else false. */ setGlobalMeterProvider(provider) { return registerGlobal(API_NAME3, provider, DiagAPI.instance()); } /** * Returns the global meter provider. */ getMeterProvider() { return getGlobal(API_NAME3) || NOOP_METER_PROVIDER; } /** * Returns a meter from the global meter provider. */ getMeter(name, version, options) { return this.getMeterProvider().getMeter(name, version, options); } /** Remove the global meter provider */ disable() { unregisterGlobal(API_NAME3, DiagAPI.instance()); } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/metrics-api.js var metrics; var init_metrics_api = __esm({ "../../node_modules/@opentelemetry/api/build/esm/metrics-api.js"() { init_metrics(); metrics = MetricsAPI.getInstance(); } }); // ../../node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js var NoopTextMapPropagator; var init_NoopTextMapPropagator = __esm({ "../../node_modules/@opentelemetry/api/build/esm/propagation/NoopTextMapPropagator.js"() { NoopTextMapPropagator = class { /** Noop inject function does nothing */ inject(_context, _carrier) { } /** Noop extract function does nothing and returns the input context */ extract(context2, _carrier) { return context2; } fields() { return []; } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js function getBaggage(context2) { return context2.getValue(BAGGAGE_KEY) || void 0; } function getActiveBaggage() { return getBaggage(ContextAPI.getInstance().active()); } function setBaggage(context2, baggage) { return context2.setValue(BAGGAGE_KEY, baggage); } function deleteBaggage(context2) { return context2.deleteValue(BAGGAGE_KEY); } var BAGGAGE_KEY; var init_context_helpers = __esm({ "../../node_modules/@opentelemetry/api/build/esm/baggage/context-helpers.js"() { init_context2(); init_context(); BAGGAGE_KEY = createContextKey("OpenTelemetry Baggage Key"); } }); // ../../node_modules/@opentelemetry/api/build/esm/api/propagation.js var API_NAME4, NOOP_TEXT_MAP_PROPAGATOR, PropagationAPI; var init_propagation = __esm({ "../../node_modules/@opentelemetry/api/build/esm/api/propagation.js"() { init_global_utils(); init_NoopTextMapPropagator(); init_TextMapPropagator(); init_context_helpers(); init_utils(); init_diag(); API_NAME4 = "propagation"; NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator(); PropagationAPI = class _PropagationAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { this.createBaggage = createBaggage; this.getBaggage = getBaggage; this.getActiveBaggage = getActiveBaggage; this.setBaggage = setBaggage; this.deleteBaggage = deleteBaggage; } /** Get the singleton instance of the Propagator API */ static getInstance() { if (!this._instance) { this._instance = new _PropagationAPI(); } return this._instance; } /** * Set the current propagator. * * @returns true if the propagator was successfully registered, else false */ setGlobalPropagator(propagator) { return registerGlobal(API_NAME4, propagator, DiagAPI.instance()); } /** * Inject context into a carrier to be propagated inter-process * * @param context Context carrying tracing data to inject * @param carrier carrier to inject context into * @param setter Function used to set values on the carrier */ inject(context2, carrier, setter = defaultTextMapSetter) { return this._getGlobalPropagator().inject(context2, carrier, setter); } /** * Extract context from a carrier * * @param context Context which the newly created context will inherit from * @param carrier Carrier to extract context from * @param getter Function used to extract keys from a carrier */ extract(context2, carrier, getter = defaultTextMapGetter) { return this._getGlobalPropagator().extract(context2, carrier, getter); } /** * Return a list of all fields which may be used by the propagator. */ fields() { return this._getGlobalPropagator().fields(); } /** Remove the global propagator */ disable() { unregisterGlobal(API_NAME4, DiagAPI.instance()); } _getGlobalPropagator() { return getGlobal(API_NAME4) || NOOP_TEXT_MAP_PROPAGATOR; } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/propagation-api.js var propagation; var init_propagation_api = __esm({ "../../node_modules/@opentelemetry/api/build/esm/propagation-api.js"() { init_propagation(); propagation = PropagationAPI.getInstance(); } }); // ../../node_modules/@opentelemetry/api/build/esm/api/trace.js var API_NAME5, TraceAPI; var init_trace = __esm({ "../../node_modules/@opentelemetry/api/build/esm/api/trace.js"() { init_global_utils(); init_ProxyTracerProvider(); init_spancontext_utils(); init_context_utils(); init_diag(); API_NAME5 = "trace"; TraceAPI = class _TraceAPI { /** Empty private constructor prevents end users from constructing a new instance of the API */ constructor() { this._proxyTracerProvider = new ProxyTracerProvider(); this.wrapSpanContext = wrapSpanContext; this.isSpanContextValid = isSpanContextValid; this.deleteSpan = deleteSpan; this.getSpan = getSpan; this.getActiveSpan = getActiveSpan; this.getSpanContext = getSpanContext; this.setSpan = setSpan; this.setSpanContext = setSpanContext; } /** Get the singleton instance of the Trace API */ static getInstance() { if (!this._instance) { this._instance = new _TraceAPI(); } return this._instance; } /** * Set the current global tracer. * * @returns true if the tracer provider was successfully registered, else false */ setGlobalTracerProvider(provider) { const success = registerGlobal(API_NAME5, this._proxyTracerProvider, DiagAPI.instance()); if (success) { this._proxyTracerProvider.setDelegate(provider); } return success; } /** * Returns the global tracer provider. */ getTracerProvider() { return getGlobal(API_NAME5) || this._proxyTracerProvider; } /** * Returns a tracer from the global tracer provider. */ getTracer(name, version) { return this.getTracerProvider().getTracer(name, version); } /** Remove the global tracer provider */ disable() { unregisterGlobal(API_NAME5, DiagAPI.instance()); this._proxyTracerProvider = new ProxyTracerProvider(); } }; } }); // ../../node_modules/@opentelemetry/api/build/esm/trace-api.js var trace; var init_trace_api = __esm({ "../../node_modules/@opentelemetry/api/build/esm/trace-api.js"() { init_trace(); trace = TraceAPI.getInstance(); } }); // ../../node_modules/@opentelemetry/api/build/esm/index.js var esm_exports = {}; __export(esm_exports, { DiagConsoleLogger: () => DiagConsoleLogger, DiagLogLevel: () => DiagLogLevel, INVALID_SPANID: () => INVALID_SPANID, INVALID_SPAN_CONTEXT: () => INVALID_SPAN_CONTEXT, INVALID_TRACEID: () => INVALID_TRACEID, ProxyTracer: () => ProxyTracer, ProxyTracerProvider: () => ProxyTracerProvider, ROOT_CONTEXT: () => ROOT_CONTEXT, SamplingDecision: () => SamplingDecision, SpanKind: () => SpanKind, SpanStatusCode: () => SpanStatusCode, TraceFlags: () => TraceFlags, ValueType: () => ValueType, baggageEntryMetadataFromString: () => baggageEntryMetadataFromString, context: () => context, createContextKey: () => createContextKey, createNoopMeter: () => createNoopMeter, createTraceState: () => createTraceState, default: () => esm_default, defaultTextMapGetter: () => defaultTextMapGetter, defaultTextMapSetter: () => defaultTextMapSetter, diag: () => diag2, isSpanContextValid: () => isSpanContextValid, isValidSpanId: () => isValidSpanId, isValidTraceId: () => isValidTraceId, metrics: () => metrics, propagation: () => propagation, trace: () => trace }); var esm_default; var init_esm = __esm({ "../../node_modules/@opentelemetry/api/build/esm/index.js"() { init_utils(); init_context(); init_consoleLogger(); init_types(); init_NoopMeter(); init_Metric(); init_TextMapPropagator(); init_ProxyTracer(); init_ProxyTracerProvider(); init_SamplingResult(); init_span_kind(); init_status(); init_trace_flags(); init_utils2(); init_spancontext_utils(); init_invalid_span_constants(); init_context_api(); init_diag_api(); init_metrics_api(); init_propagation_api(); init_trace_api(); esm_default = { context, diag: diag2, metrics, propagation, trace }; } }); // ../../node_modules/bare-prom-client/lib/metrics/processCpuTotal.js var require_processCpuTotal = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/processCpuTotal.js"(exports, module) { "use strict"; var process = __require("process"); var OtelApi = (init_esm(), __toCommonJS(esm_exports)); var Counter = require_counter(); var PROCESS_CPU_USER_SECONDS = "process_cpu_user_seconds_total"; var PROCESS_CPU_SYSTEM_SECONDS = "process_cpu_system_seconds_total"; var PROCESS_CPU_SECONDS = "process_cpu_seconds_total"; module.exports = (registry, config = {}) => { const registers = registry ? [registry] : void 0; const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const exemplars = config.enableExemplars ? config.enableExemplars : false; const labelNames = Object.keys(labels); let lastCpuUsage = process.cpuUsage(); const cpuUserUsageCounter = new Counter({ name: namePrefix + PROCESS_CPU_USER_SECONDS, help: "Total user CPU time spent in seconds.", enableExemplars: exemplars, registers, labelNames, // Use this one metric's `collect` to set all metrics' values. collect() { const cpuUsage = process.cpuUsage(); const userUsageMicros = cpuUsage.user - lastCpuUsage.user; const systemUsageMicros = cpuUsage.system - lastCpuUsage.system; lastCpuUsage = cpuUsage; if (this.enableExemplars) { let exemplarLabels = {}; const currentSpan = OtelApi.trace.getSpan(OtelApi.context.active()); if (currentSpan) { exemplarLabels = { traceId: currentSpan.spanContext().traceId, spanId: currentSpan.spanContext().spanId }; } cpuUserUsageCounter.inc({ labels, value: userUsageMicros / 1e6, exemplarLabels }); cpuSystemUsageCounter.inc({ labels, value: systemUsageMicros / 1e6, exemplarLabels }); cpuUsageCounter.inc({ labels, value: (userUsageMicros + systemUsageMicros) / 1e6, exemplarLabels }); } else { cpuUserUsageCounter.inc(labels, userUsageMicros / 1e6); cpuSystemUsageCounter.inc(labels, systemUsageMicros / 1e6); cpuUsageCounter.inc( labels, (userUsageMicros + systemUsageMicros) / 1e6 ); } } }); const cpuSystemUsageCounter = new Counter({ name: namePrefix + PROCESS_CPU_SYSTEM_SECONDS, help: "Total system CPU time spent in seconds.", enableExemplars: exemplars, registers, labelNames }); const cpuUsageCounter = new Counter({ name: namePrefix + PROCESS_CPU_SECONDS, help: "Total user and system CPU time spent in seconds.", enableExemplars: exemplars, registers, labelNames }); }; module.exports.metricNames = [ PROCESS_CPU_USER_SECONDS, PROCESS_CPU_SYSTEM_SECONDS, PROCESS_CPU_SECONDS ]; } }); // ../../node_modules/bare-prom-client/lib/metrics/processStartTime.js var require_processStartTime = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/processStartTime.js"(exports, module) { "use strict"; var process = __require("process"); var Gauge = require_gauge(); var startInSeconds = Math.round(Date.now() / 1e3 - process.uptime()); var PROCESS_START_TIME = "process_start_time_seconds"; module.exports = (registry, config = {}) => { const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); new Gauge({ name: namePrefix + PROCESS_START_TIME, help: "Start time of the process since unix epoch in seconds.", registers: registry ? [registry] : void 0, labelNames, aggregator: "omit", collect() { this.set(labels, startInSeconds); } }); }; module.exports.metricNames = [PROCESS_START_TIME]; } }); // ../../node_modules/fast-fifo/fixed-size.js var require_fixed_size = __commonJS({ "../../node_modules/fast-fifo/fixed-size.js"(exports, module) { module.exports = class FixedFIFO { constructor(hwm) { if (!(hwm > 0) || (hwm - 1 & hwm) !== 0) throw new Error("Max size for a FixedFIFO should be a power of two"); this.buffer = new Array(hwm); this.mask = hwm - 1; this.top = 0; this.btm = 0; this.next = null; } clear() { this.top = this.btm = 0; this.next = null; this.buffer.fill(void 0); } push(data) { if (this.buffer[this.top] !== void 0) return false; this.buffer[this.top] = data; this.top = this.top + 1 & this.mask; return true; } shift() { const last = this.buffer[this.btm]; if (last === void 0) return void 0; this.buffer[this.btm] = void 0; this.btm = this.btm + 1 & this.mask; return last; } peek() { return this.buffer[this.btm]; } isEmpty() { return this.buffer[this.btm] === void 0; } }; } }); // ../../node_modules/fast-fifo/index.js var require_fast_fifo = __commonJS({ "../../node_modules/fast-fifo/index.js"(exports, module) { var FixedFIFO = require_fixed_size(); module.exports = class FastFIFO { constructor(hwm) { this.hwm = hwm || 16; this.head = new FixedFIFO(this.hwm); this.tail = this.head; this.length = 0; } clear() { this.head = this.tail; this.head.clear(); this.length = 0; } push(val) { this.length++; if (!this.head.push(val)) { const prev = this.head; this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length); this.head.push(val); } } shift() { if (this.length !== 0) this.length--; const val = this.tail.shift(); if (val === void 0 && this.tail.next) { const next = this.tail.next; this.tail.next = null; this.tail = next; return this.tail.shift(); } return val; } peek() { const val = this.tail.peek(); if (val === void 0 && this.tail.next) return this.tail.next.peek(); return val; } isEmpty() { return this.length === 0; } }; } }); // ../../node_modules/bare-events/lib/errors.js var require_errors3 = __commonJS({ "../../node_modules/bare-events/lib/errors.js"(exports, module) { module.exports = class EventEmitterError extends Error { constructor(msg, code, fn = EventEmitterError, opts) { super(`${code}: ${msg}`, opts); this.code = code; if (Error.captureStackTrace) { Error.captureStackTrace(this, fn); } } get name() { return "EventEmitterError"; } static OPERATION_ABORTED(cause, msg = "Operation aborted") { return new EventEmitterError(msg, "OPERATION_ABORTED", EventEmitterError.OPERATION_ABORTED, { cause }); } static UNHANDLED_ERROR(cause, msg = "Unhandled error") { return new EventEmitterError(msg, "UNHANDLED_ERROR", EventEmitterError.UNHANDLED_ERROR, { cause }); } }; } }); // ../../node_modules/bare-events/index.js var require_bare_events = __commonJS({ "../../node_modules/bare-events/index.js"(exports, module) { var errors = require_errors3(); var EventListener = class { constructor() { this.list = []; this.count = 0; } append(ctx, name, fn, once) { this.count++; ctx.emit("newListener", name, fn); this.list.push([fn, once]); } prepend(ctx, name, fn, once) { this.count++; ctx.emit("newListener", name, fn); this.list.unshift([fn, once]); } remove(ctx, name, fn) { for (let i = 0, n = this.list.length; i < n; i++) { const l = this.list[i]; if (l[0] === fn) { this.list.splice(i, 1); if (this.count === 1) delete ctx._events[name]; ctx.emit("removeListener", name, fn); this.count--; return; } } } removeAll(ctx, name) { const list = [...this.list]; this.list = []; if (this.count === list.length) delete ctx._events[name]; for (let i = list.length - 1; i >= 0; i--) { ctx.emit("removeListener", name, list[i][0]); } this.count -= list.length; } emit(ctx, name, ...args) { const list = [...this.list]; for (let i = 0, n = list.length; i < n; i++) { const l = list[i]; if (l[1] === true) this.remove(ctx, name, l[0]); Reflect.apply(l[0], ctx, args); } return list.length > 0; } }; function appendListener(ctx, name, fn, once) { if (ctx._events === void 0) ctx._events = /* @__PURE__ */ Object.create(null); const e = ctx._events[name] || (ctx._events[name] = new EventListener()); e.append(ctx, name, fn, once); return ctx; } function prependListener(ctx, name, fn, once) { if (ctx._events === void 0) ctx._events = /* @__PURE__ */ Object.create(null); const e = ctx._events[name] || (ctx._events[name] = new EventListener()); e.prepend(ctx, name, fn, once); return ctx; } function removeListener(ctx, name, fn) { if (ctx._events === void 0) return ctx; const e = ctx._events[name]; if (e !== void 0) e.remove(ctx, name, fn); return ctx; } function throwUnhandledError(...args) { let err; if (args.length > 0) err = args[0]; if (err instanceof Error === false) err = errors.UNHANDLED_ERROR(err); if (Error.captureStackTrace) { Error.captureStackTrace(err, exports.prototype.emit); } queueMicrotask(() => { throw err; }); } module.exports = exports = class EventEmitter { constructor() { this._events = /* @__PURE__ */ Object.create(null); } addListener(name, fn) { return appendListener(this, name, fn, false); } addOnceListener(name, fn) { return appendListener(this, name, fn, true); } prependListener(name, fn) { return prependListener(this, name, fn, false); } prependOnceListener(name, fn) { return prependListener(this, name, fn, true); } removeListener(name, fn) { return removeListener(this, name, fn); } on(name, fn) { return appendListener(this, name, fn, false); } once(name, fn) { return appendListener(this, name, fn, true); } off(name, fn) { return removeListener(this, name, fn); } emit(name, ...args) { if (name === "error" && this._events !== void 0 && this._events.error === void 0) { throwUnhandledError(...args); } if (this._events === void 0) return false; const e = this._events[name]; return e === void 0 ? false : e.emit(this, name, ...args); } listeners(name) { if (this._events === void 0) return []; const e = this._events[name]; return e === void 0 ? [] : [...e.list]; } listenerCount(name) { if (this._events === void 0) return 0; const e = this._events[name]; return e === void 0 ? 0 : e.list.length; } getMaxListeners() { return EventEmitter.defaultMaxListeners; } setMaxListeners(n) { } removeAllListeners(name) { if (arguments.length === 0) { for (const key of Reflect.ownKeys(this._events)) { if (key === "removeListener") continue; this.removeAllListeners(key); } this.removeAllListeners("removeListener"); } else { const e = this._events[name]; if (e !== void 0) e.removeAll(this, name); } return this; } }; exports.EventEmitter = exports; exports.errors = errors; exports.defaultMaxListeners = 10; exports.on = function on(emitter, name, opts = {}) { const { signal } = opts; if (signal && signal.aborted) { throw errors.OPERATION_ABORTED(signal.reason); } let error = null; let done = false; const events = []; const promises = []; if (name !== "error") emitter.on("error", onerror); if (signal) signal.addEventListener("abort", onabort); emitter.on(name, onevent); return { next() { if (events.length) { return Promise.resolve({ value: events.shift(), done: false }); } if (error) { const err = error; error = null; return Promise.reject(err); } if (done) return onclose(); return new Promise((resolve, reject) => promises.push({ resolve, reject })); }, return() { return onclose(); }, throw(err) { return onerror(err); }, [Symbol.asyncIterator]() { return this; } }; function onevent(...args) { if (promises.length) { promises.shift().resolve({ value: args, done: false }); } else { events.push(args); } } function onerror(err) { emitter.off(name, onevent).off("error", onerror); if (promises.length) { promises.shift().reject(err); } else { error = err; } return Promise.resolve({ done: true }); } function onabort() { signal.removeEventListener("abort", onabort); onerror(errors.OPERATION_ABORTED(signal.reason)); } function onclose() { emitter.off(name, onevent); if (name !== "error") emitter.off("error", onerror); if (signal) signal.removeEventListener("abort", onabort); done = true; if (promises.length) promises.shift().resolve({ done: true }); return Promise.resolve({ done: true }); } }; exports.once = function once(emitter, name, opts = {}) { const { signal } = opts; if (signal && signal.aborted) { return Promise.reject(errors.OPERATION_ABORTED(signal.reason)); } return new Promise((resolve, reject) => { if (name !== "error") emitter.on("error", onerror); if (signal) signal.addEventListener("abort", onabort); emitter.once(name, onevent); function onevent(...args) { if (name !== "error") emitter.off("error", onerror); if (signal) signal.removeEventListener("abort", onabort); resolve(args); } function onerror(err) { emitter.off(name, onevent); if (name !== "error") emitter.off("error", onerror); reject(err); } function onabort() { signal.removeEventListener("abort", onabort); onerror(errors.OPERATION_ABORTED(signal.reason)); } }); }; exports.forward = function forward(from, to, names, opts = {}) { if (typeof names === "string") names = [names]; const { emit = to.emit.bind(to) } = opts; const listeners = names.map( (name) => function onevent(...args) { emit(name, ...args); } ); to.on("newListener", (name) => { const i = names.indexOf(name); if (i !== -1 && to.listenerCount(name) === 0) { from.on(name, listeners[i]); } }).on("removeListener", (name) => { const i = names.indexOf(name); if (i !== -1 && to.listenerCount(name) === 0) { from.off(name, listeners[i]); } }); }; exports.listenerCount = function listenerCount(emitter, name) { return emitter.listenerCount(name); }; exports.getMaxListeners = function getMaxListeners(emitter) { if (typeof emitter.getMaxListeners === "function") { return emitter.getMaxListeners(); } return exports.defaultMaxListeners; }; exports.setMaxListeners = function setMaxListeners(n, ...emitters) { if (emitters.length === 0) exports.defaultMaxListeners = n; else { for (const emitter of emitters) { if (typeof emitter.setMaxListeners === "function") { emitter.setMaxListeners(n); } } } }; } }); // ../bare-os-openssh/vendor/bare-node-shims/bare-node-events/index.js var require_bare_node_events = __commonJS({ "../bare-os-openssh/vendor/bare-node-shims/bare-node-events/index.js"(exports, module) { module.exports = require_bare_events(); } }); // ../../node_modules/events-universal/default.js var require_default = __commonJS({ "../../node_modules/events-universal/default.js"(exports, module) { module.exports = require_bare_node_events(); } }); // ../../node_modules/b4a/index.js var require_b4a = __commonJS({ "../../node_modules/b4a/index.js"(exports, module) { function isBuffer(value) { return Buffer.isBuffer(value) || value instanceof Uint8Array; } function isEncoding(encoding) { return Buffer.isEncoding(encoding); } function alloc(size, fill2, encoding) { return Buffer.alloc(size, fill2, encoding); } function allocUnsafe(size) { return Buffer.allocUnsafe(size); } function allocUnsafeSlow(size) { return Buffer.allocUnsafeSlow(size); } function byteLength(string, encoding) { return Buffer.byteLength(string, encoding); } function compare(a, b) { return Buffer.compare(a, b); } function concat(buffers, totalLength) { return Buffer.concat(buffers, totalLength); } function copy(source, target, targetStart, start, end) { return toBuffer(source).copy(target, targetStart, start, end); } function equals(a, b) { return toBuffer(a).equals(b); } function fill(buffer, value, offset, end, encoding) { return toBuffer(buffer).fill(value, offset, end, encoding); } function from(value, encodingOrOffset, length) { return Buffer.from(value, encodingOrOffset, length); } function includes(buffer, value, byteOffset, encoding) { return toBuffer(buffer).includes(value, byteOffset, encoding); } function indexOf(buffer, value, byfeOffset, encoding) { return toBuffer(buffer).indexOf(value, byfeOffset, encoding); } function lastIndexOf(buffer, value, byteOffset, encoding) { return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding); } function swap16(buffer) { return toBuffer(buffer).swap16(); } function swap32(buffer) { return toBuffer(buffer).swap32(); } function swap64(buffer) { return toBuffer(buffer).swap64(); } function toBuffer(buffer) { if (Buffer.isBuffer(buffer)) return buffer; return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); } function toString(buffer, encoding, start, end) { return toBuffer(buffer).toString(encoding, start, end); } function write(buffer, string, offset, length, encoding) { return toBuffer(buffer).write(string, offset, length, encoding); } function readDoubleBE(buffer, offset) { return toBuffer(buffer).readDoubleBE(offset); } function readDoubleLE(buffer, offset) { return toBuffer(buffer).readDoubleLE(offset); } function readFloatBE(buffer, offset) { return toBuffer(buffer).readFloatBE(offset); } function readFloatLE(buffer, offset) { return toBuffer(buffer).readFloatLE(offset); } function readInt32BE(buffer, offset) { return toBuffer(buffer).readInt32BE(offset); } function readInt32LE(buffer, offset) { return toBuffer(buffer).readInt32LE(offset); } function readUInt32BE(buffer, offset) { return toBuffer(buffer).readUInt32BE(offset); } function readUInt32LE(buffer, offset) { return toBuffer(buffer).readUInt32LE(offset); } function writeDoubleBE(buffer, value, offset) { return toBuffer(buffer).writeDoubleBE(value, offset); } function writeDoubleLE(buffer, value, offset) { return toBuffer(buffer).writeDoubleLE(value, offset); } function writeFloatBE(buffer, value, offset) { return toBuffer(buffer).writeFloatBE(value, offset); } function writeFloatLE(buffer, value, offset) { return toBuffer(buffer).writeFloatLE(value, offset); } function writeInt32BE(buffer, value, offset) { return toBuffer(buffer).writeInt32BE(value, offset); } function writeInt32LE(buffer, value, offset) { return toBuffer(buffer).writeInt32LE(value, offset); } function writeUInt32BE(buffer, value, offset) { return toBuffer(buffer).writeUInt32BE(value, offset); } function writeUInt32LE(buffer, value, offset) { return toBuffer(buffer).writeUInt32LE(value, offset); } module.exports = { isBuffer, isEncoding, alloc, allocUnsafe, allocUnsafeSlow, byteLength, compare, concat, copy, equals, fill, from, includes, indexOf, lastIndexOf, swap16, swap32, swap64, toBuffer, toString, write, readDoubleBE, readDoubleLE, readFloatBE, readFloatLE, readInt32BE, readInt32LE, readUInt32BE, readUInt32LE, writeDoubleBE, writeDoubleLE, writeFloatBE, writeFloatLE, writeInt32BE, writeInt32LE, writeUInt32BE, writeUInt32LE }; } }); // ../../node_modules/text-decoder/lib/pass-through-decoder.js var require_pass_through_decoder = __commonJS({ "../../node_modules/text-decoder/lib/pass-through-decoder.js"(exports, module) { var b4a = require_b4a(); module.exports = class PassThroughDecoder { constructor(encoding) { this.encoding = encoding; } get remaining() { return 0; } decode(data) { return b4a.toString(data, this.encoding); } flush() { return ""; } }; } }); // ../../node_modules/text-decoder/lib/utf8-decoder.js var require_utf8_decoder = __commonJS({ "../../node_modules/text-decoder/lib/utf8-decoder.js"(exports, module) { var b4a = require_b4a(); module.exports = class UTF8Decoder { constructor() { this._reset(); } get remaining() { return this.bytesSeen; } decode(data) { if (data.byteLength === 0) return ""; if (this.bytesNeeded === 0 && trailingIncomplete(data, 0) === 0) { this.bytesSeen = trailingBytesSeen(data); return b4a.toString(data, "utf8"); } let result = ""; let start = 0; if (this.bytesNeeded > 0) { while (start < data.byteLength) { const byte = data[start]; if (byte < this.lowerBoundary || byte > this.upperBoundary) { result += "\uFFFD"; this._reset(); break; } this.lowerBoundary = 128; this.upperBoundary = 191; this.codePoint = this.codePoint << 6 | byte & 63; this.bytesSeen++; start++; if (this.bytesSeen === this.bytesNeeded) { result += String.fromCodePoint(this.codePoint); this._reset(); break; } } if (this.bytesNeeded > 0) return result; } const trailing = trailingIncomplete(data, start); const end = data.byteLength - trailing; if (end > start) result += b4a.toString(data, "utf8", start, end); for (let i = end; i < data.byteLength; i++) { const byte = data[i]; if (this.bytesNeeded === 0) { if (byte <= 127) { this.bytesSeen = 0; result += String.fromCharCode(byte); } else if (byte >= 194 && byte <= 223) { this.bytesNeeded = 2; this.bytesSeen = 1; this.codePoint = byte & 31; } else if (byte >= 224 && byte <= 239) { if (byte === 224) this.lowerBoundary = 160; else if (byte === 237) this.upperBoundary = 159; this.bytesNeeded = 3; this.bytesSeen = 1; this.codePoint = byte & 15; } else if (byte >= 240 && byte <= 244) { if (byte === 240) this.lowerBoundary = 144; else if (byte === 244) this.upperBoundary = 143; this.bytesNeeded = 4; this.bytesSeen = 1; this.codePoint = byte & 7; } else { this.bytesSeen = 1; result += "\uFFFD"; } continue; } if (byte < this.lowerBoundary || byte > this.upperBoundary) { result += "\uFFFD"; i--; this._reset(); continue; } this.lowerBoundary = 128; this.upperBoundary = 191; this.codePoint = this.codePoint << 6 | byte & 63; this.bytesSeen++; if (this.bytesSeen === this.bytesNeeded) { result += String.fromCodePoint(this.codePoint); this._reset(); } } return result; } flush() { const result = this.bytesNeeded > 0 ? "\uFFFD" : ""; this._reset(); return result; } _reset() { this.codePoint = 0; this.bytesNeeded = 0; this.bytesSeen = 0; this.lowerBoundary = 128; this.upperBoundary = 191; } }; function trailingIncomplete(data, start) { const len = data.byteLength; if (len <= start) return 0; const limit = Math.max(start, len - 4); let i = len - 1; while (i > limit && (data[i] & 192) === 128) i--; if (i < start) return 0; const byte = data[i]; let needed; if (byte <= 127) return 0; if (byte >= 194 && byte <= 223) needed = 2; else if (byte >= 224 && byte <= 239) needed = 3; else if (byte >= 240 && byte <= 244) needed = 4; else return 0; const available = len - i; return available < needed ? available : 0; } function trailingBytesSeen(data) { const len = data.byteLength; if (len === 0) return 0; const last = data[len - 1]; if (last <= 127) return 0; if ((last & 192) !== 128) return 1; const limit = Math.max(0, len - 4); let i = len - 2; while (i >= limit && (data[i] & 192) === 128) i--; if (i < 0) return 1; const first = data[i]; let needed; if (first >= 194 && first <= 223) needed = 2; else if (first >= 224 && first <= 239) needed = 3; else if (first >= 240 && first <= 244) needed = 4; else return 1; if (len - i !== needed) return 1; if (needed >= 3) { const second = data[i + 1]; if (first === 224 && second < 160) return 1; if (first === 237 && second > 159) return 1; if (first === 240 && second < 144) return 1; if (first === 244 && second > 143) return 1; } return 0; } } }); // ../../node_modules/text-decoder/index.js var require_text_decoder = __commonJS({ "../../node_modules/text-decoder/index.js"(exports, module) { var PassThroughDecoder = require_pass_through_decoder(); var UTF8Decoder = require_utf8_decoder(); module.exports = class TextDecoder { constructor(encoding = "utf8") { this.encoding = normalizeEncoding(encoding); switch (this.encoding) { case "utf8": this.decoder = new UTF8Decoder(); break; case "utf16le": case "base64": throw new Error("Unsupported encoding: " + this.encoding); default: this.decoder = new PassThroughDecoder(this.encoding); } } get remaining() { return this.decoder.remaining; } push(data) { if (typeof data === "string") return data; return this.decoder.decode(data); } // For Node.js compatibility write(data) { return this.push(data); } end(data) { let result = ""; if (data) result = this.push(data); result += this.decoder.flush(); return result; } }; function normalizeEncoding(encoding) { encoding = encoding.toLowerCase(); switch (encoding) { case "utf8": case "utf-8": return "utf8"; case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return "utf16le"; case "latin1": case "binary": return "latin1"; case "base64": case "ascii": case "hex": return encoding; default: throw new Error("Unknown encoding: " + encoding); } } } }); // ../../node_modules/streamx/index.js var require_streamx = __commonJS({ "../../node_modules/streamx/index.js"(exports, module) { var { EventEmitter } = require_default(); var STREAM_DESTROYED = new Error("Stream was destroyed"); var PREMATURE_CLOSE = new Error("Premature close"); var FIFO = require_fast_fifo(); var TextDecoder = require_text_decoder(); var qmt = typeof queueMicrotask === "undefined" ? (fn) => global.process.nextTick(fn) : queueMicrotask; var MAX = (1 << 29) - 1; var OPENING = 1; var PREDESTROYING = 2; var DESTROYING = 4; var DESTROYED = 8; var NOT_OPENING = MAX ^ OPENING; var NOT_PREDESTROYING = MAX ^ PREDESTROYING; var READ_ACTIVE = 1 << 4; var READ_UPDATING = 2 << 4; var READ_PRIMARY = 4 << 4; var READ_QUEUED = 8 << 4; var READ_RESUMED = 16 << 4; var READ_PIPE_DRAINED = 32 << 4; var READ_ENDING = 64 << 4; var READ_EMIT_DATA = 128 << 4; var READ_EMIT_READABLE = 256 << 4; var READ_EMITTED_READABLE = 512 << 4; var READ_DONE = 1024 << 4; var READ_NEXT_TICK = 2048 << 4; var READ_NEEDS_PUSH = 4096 << 4; var READ_READ_AHEAD = 8192 << 4; var READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED; var READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH; var READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE; var READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED; var READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD; var READ_NOT_ACTIVE = MAX ^ READ_ACTIVE; var READ_NON_PRIMARY = MAX ^ READ_PRIMARY; var READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH); var READ_PUSHED = MAX ^ READ_NEEDS_PUSH; var READ_PAUSED = MAX ^ READ_RESUMED; var READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE); var READ_NOT_ENDING = MAX ^ READ_ENDING; var READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING; var READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK; var READ_NOT_UPDATING = MAX ^ READ_UPDATING; var READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD; var READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD; var WRITE_ACTIVE = 1 << 18; var WRITE_UPDATING = 2 << 18; var WRITE_PRIMARY = 4 << 18; var WRITE_QUEUED = 8 << 18; var WRITE_UNDRAINED = 16 << 18; var WRITE_DONE = 32 << 18; var WRITE_EMIT_DRAIN = 64 << 18; var WRITE_NEXT_TICK = 128 << 18; var WRITE_WRITING = 256 << 18; var WRITE_FINISHING = 512 << 18; var WRITE_CORKED = 1024 << 18; var WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING); var WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY; var WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING); var WRITE_DRAINED = MAX ^ WRITE_UNDRAINED; var WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED; var WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK; var WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING; var WRITE_NOT_CORKED = MAX ^ WRITE_CORKED; var ACTIVE = READ_ACTIVE | WRITE_ACTIVE; var NOT_ACTIVE = MAX ^ ACTIVE; var DONE = READ_DONE | WRITE_DONE; var DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING; var OPEN_STATUS = DESTROY_STATUS | OPENING; var AUTO_DESTROY = DESTROY_STATUS | DONE; var NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY; var ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK; var TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE; var IS_OPENING = OPEN_STATUS | TICKING; var READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE; var READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED; var READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED; var READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE; var SHOULD_NOT_READ = OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD; var READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE; var READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY; var READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING; var WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE; var WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED; var WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE; var WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE; var WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED; var WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE; var WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING; var WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE; var WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE; var WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY; var WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS; var asyncIterator = Symbol.asyncIterator || Symbol("asyncIterator"); var WritableState = class { constructor(stream, { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {}) { this.stream = stream; this.queue = new FIFO(); this.highWaterMark = highWaterMark; this.buffered = 0; this.error = null; this.pipeline = null; this.drains = null; this.byteLength = byteLengthWritable || byteLength || defaultByteLength; this.map = mapWritable || map; this.afterWrite = afterWrite.bind(this); this.afterUpdateNextTick = updateWriteNT.bind(this); } get ending() { return (this.stream._duplexState & WRITE_FINISHING) !== 0; } get ended() { return (this.stream._duplexState & WRITE_DONE) !== 0; } push(data) { if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false; if (this.map !== null) data = this.map(data); this.buffered += this.byteLength(data); this.queue.push(data); if (this.buffered < this.highWaterMark) { this.stream._duplexState |= WRITE_QUEUED; return true; } this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED; return false; } shift() { const data = this.queue.shift(); this.buffered -= this.byteLength(data); if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED; return data; } end(data) { if (typeof data === "function") this.stream.once("finish", data); else if (data !== void 0 && data !== null) this.push(data); this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY; } autoBatch(data, cb) { const buffer = []; const stream = this.stream; buffer.push(data); while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) { buffer.push(stream._writableState.shift()); } if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null); stream._writev(buffer, cb); } update() { const stream = this.stream; stream._duplexState |= WRITE_UPDATING; do { while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) { const data = this.shift(); stream._duplexState |= WRITE_ACTIVE_AND_WRITING; stream._write(data, this.afterWrite); } if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary(); } while (this.continueUpdate() === true); stream._duplexState &= WRITE_NOT_UPDATING; } updateNonPrimary() { const stream = this.stream; if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) { stream._duplexState = stream._duplexState | WRITE_ACTIVE; stream._final(afterFinal.bind(this)); return; } if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) { if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) { stream._duplexState |= ACTIVE; stream._destroy(afterDestroy.bind(this)); } return; } if ((stream._duplexState & IS_OPENING) === OPENING) { stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING; stream._open(afterOpen.bind(this)); } } continueUpdate() { if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false; this.stream._duplexState &= WRITE_NOT_NEXT_TICK; return true; } updateCallback() { if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) this.update(); else this.updateNextTick(); } updateNextTick() { if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return; this.stream._duplexState |= WRITE_NEXT_TICK; if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick); } }; var ReadableState = class { constructor(stream, { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {}) { this.stream = stream; this.queue = new FIFO(); this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark; this.buffered = 0; this.readAhead = highWaterMark > 0; this.error = null; this.pipeline = null; this.byteLength = byteLengthReadable || byteLength || defaultByteLength; this.map = mapReadable || map; this.pipeTo = null; this.afterRead = afterRead.bind(this); this.afterUpdateNextTick = updateReadNT.bind(this); } get ending() { return (this.stream._duplexState & READ_ENDING) !== 0; } get ended() { return (this.stream._duplexState & READ_DONE) !== 0; } pipe(pipeTo, cb) { if (this.pipeTo !== null) throw new Error("Can only pipe to one destination"); if (typeof cb !== "function") cb = null; this.stream._duplexState |= READ_PIPE_DRAINED; this.pipeTo = pipeTo; this.pipeline = new Pipeline(this.stream, pipeTo, cb); if (cb) this.stream.on("error", noop); if (isStreamx(pipeTo)) { pipeTo._writableState.pipeline = this.pipeline; if (cb) pipeTo.on("error", noop); pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline)); } else { const onerror = this.pipeline.done.bind(this.pipeline, pipeTo); const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null); pipeTo.on("error", onerror); pipeTo.on("close", onclose); pipeTo.on("finish", this.pipeline.finished.bind(this.pipeline)); } pipeTo.on("drain", afterDrain.bind(this)); this.stream.emit("piping", pipeTo); pipeTo.emit("pipe", this.stream); } push(data) { const stream = this.stream; if (data === null) { this.highWaterMark = 0; stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED; return false; } if (this.map !== null) { data = this.map(data); if (data === null) { stream._duplexState &= READ_PUSHED; return this.buffered < this.highWaterMark; } } this.buffered += this.byteLength(data); this.queue.push(data); stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED; return this.buffered < this.highWaterMark; } shift() { const data = this.queue.shift(); this.buffered -= this.byteLength(data); if (this.buffered === 0) this.stream._duplexState &= READ_NOT_QUEUED; return data; } unshift(data) { const pending = [this.map !== null ? this.map(data) : data]; while (this.buffered > 0) pending.push(this.shift()); for (let i = 0; i < pending.length - 1; i++) { const data2 = pending[i]; this.buffered += this.byteLength(data2); this.queue.push(data2); } this.push(pending[pending.length - 1]); } read() { const stream = this.stream; if ((stream._duplexState & READ_STATUS) === READ_QUEUED) { const data = this.shift(); if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED; if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data); return data; } if (this.readAhead === false) { stream._duplexState |= READ_READ_AHEAD; this.updateNextTick(); } return null; } drain() { const stream = this.stream; while ((stream._duplexState & READ_STATUS) === READ_QUEUED && (stream._duplexState & READ_FLOWING) !== 0) { const data = this.shift(); if (this.pipeTo !== null && this.pipeTo.write(data) === false) stream._duplexState &= READ_PIPE_NOT_DRAINED; if ((stream._duplexState & READ_EMIT_DATA) !== 0) stream.emit("data", data); } } update() { const stream = this.stream; stream._duplexState |= READ_UPDATING; do { this.drain(); while (this.buffered < this.highWaterMark && (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD) { stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH; stream._read(this.afterRead); this.drain(); } if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) { stream._duplexState |= READ_EMITTED_READABLE; stream.emit("readable"); } if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary(); } while (this.continueUpdate() === true); stream._duplexState &= READ_NOT_UPDATING; } updateNonPrimary() { const stream = this.stream; if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) { stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING; stream.emit("end"); if ((stream._duplexState & AUTO_DESTROY) === DONE) stream._duplexState |= DESTROYING; if (this.pipeTo !== null) this.pipeTo.end(); } if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) { if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) { stream._duplexState |= ACTIVE; stream._destroy(afterDestroy.bind(this)); } return; } if ((stream._duplexState & IS_OPENING) === OPENING) { stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING; stream._open(afterOpen.bind(this)); } } continueUpdate() { if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false; this.stream._duplexState &= READ_NOT_NEXT_TICK; return true; } updateCallback() { if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) this.update(); else this.updateNextTick(); } updateNextTickIfOpen() { if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return; this.stream._duplexState |= READ_NEXT_TICK; if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick); } updateNextTick() { if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return; this.stream._duplexState |= READ_NEXT_TICK; if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick); } }; var TransformState = class { constructor(stream) { this.data = null; this.afterTransform = afterTransform.bind(stream); this.afterFinal = null; } }; var Pipeline = class { constructor(src, dst, cb) { this.from = src; this.to = dst; this.afterPipe = cb; this.error = null; this.pipeToFinished = false; } finished() { this.pipeToFinished = true; } done(stream, err) { if (err) this.error = err; if (stream === this.to) { this.to = null; if (this.from !== null) { if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) { this.from.destroy(this.error || new Error("Writable stream closed prematurely")); } return; } } if (stream === this.from) { this.from = null; if (this.to !== null) { if ((stream._duplexState & READ_DONE) === 0) { this.to.destroy(this.error || new Error("Readable stream closed before ending")); } return; } } if (this.afterPipe !== null) this.afterPipe(this.error); this.to = this.from = this.afterPipe = null; } }; function afterDrain() { this.stream._duplexState |= READ_PIPE_DRAINED; this.updateCallback(); } function afterFinal(err) { const stream = this.stream; if (err) stream.destroy(err); if ((stream._duplexState & DESTROY_STATUS) === 0) { stream._duplexState |= WRITE_DONE; stream.emit("finish"); } if ((stream._duplexState & AUTO_DESTROY) === DONE) { stream._duplexState |= DESTROYING; } stream._duplexState &= WRITE_NOT_FINISHING; if ((stream._duplexState & WRITE_UPDATING) === 0) this.update(); else this.updateNextTick(); } function afterDestroy(err) { const stream = this.stream; if (!err && this.error !== STREAM_DESTROYED) err = this.error; if (err) stream.emit("error", err); stream._duplexState |= DESTROYED; stream.emit("close"); const rs = stream._readableState; const ws = stream._writableState; if (rs !== null && rs.pipeline !== null) rs.pipeline.done(stream, err); if (ws !== null) { while (ws.drains !== null && ws.drains.length > 0) ws.drains.shift().resolve(false); if (ws.pipeline !== null) ws.pipeline.done(stream, err); } } function afterWrite(err) { const stream = this.stream; if (err) stream.destroy(err); stream._duplexState &= WRITE_NOT_ACTIVE; if (this.drains !== null) tickDrains(this.drains); if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) { stream._duplexState &= WRITE_DRAINED; if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) { stream.emit("drain"); } } this.updateCallback(); } function afterRead(err) { if (err) this.stream.destroy(err); this.stream._duplexState &= READ_NOT_ACTIVE; if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) this.stream._duplexState &= READ_NO_READ_AHEAD; this.updateCallback(); } function updateReadNT() { if ((this.stream._duplexState & READ_UPDATING) === 0) { this.stream._duplexState &= READ_NOT_NEXT_TICK; this.update(); } } function updateWriteNT() { if ((this.stream._duplexState & WRITE_UPDATING) === 0) { this.stream._duplexState &= WRITE_NOT_NEXT_TICK; this.update(); } } function tickDrains(drains) { for (let i = 0; i < drains.length; i++) { if (--drains[i].writes === 0) { drains.shift().resolve(true); i--; } } } function afterOpen(err) { const stream = this.stream; if (err) stream.destroy(err); if ((stream._duplexState & DESTROYING) === 0) { if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) stream._duplexState |= READ_PRIMARY; if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) stream._duplexState |= WRITE_PRIMARY; stream.emit("open"); } stream._duplexState &= NOT_ACTIVE; if (stream._writableState !== null) { stream._writableState.updateCallback(); } if (stream._readableState !== null) { stream._readableState.updateCallback(); } } function afterTransform(err, data) { if (data !== void 0 && data !== null) this.push(data); this._writableState.afterWrite(err); } function newListener(name) { if (this._readableState !== null) { if (name === "data") { this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD; this._readableState.updateNextTick(); } if (name === "readable") { this._duplexState |= READ_EMIT_READABLE; this._readableState.updateNextTick(); } } if (this._writableState !== null) { if (name === "drain") { this._duplexState |= WRITE_EMIT_DRAIN; this._writableState.updateNextTick(); } } } var Stream = class extends EventEmitter { constructor(opts) { super(); this._duplexState = 0; this._readableState = null; this._writableState = null; if (opts) { if (opts.open) this._open = opts.open; if (opts.destroy) this._destroy = opts.destroy; if (opts.predestroy) this._predestroy = opts.predestroy; if (opts.signal) { opts.signal.addEventListener("abort", abort.bind(this)); } } this.on("newListener", newListener); } _open(cb) { cb(null); } _destroy(cb) { cb(null); } _predestroy() { } get readable() { return this._readableState !== null ? true : void 0; } get writable() { return this._writableState !== null ? true : void 0; } get destroyed() { return (this._duplexState & DESTROYED) !== 0; } get destroying() { return (this._duplexState & DESTROY_STATUS) !== 0; } destroy(err) { if ((this._duplexState & DESTROY_STATUS) === 0) { if (!err) err = STREAM_DESTROYED; this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY; if (this._readableState !== null) { this._readableState.highWaterMark = 0; this._readableState.error = err; } if (this._writableState !== null) { this._writableState.highWaterMark = 0; this._writableState.error = err; } this._duplexState |= PREDESTROYING; this._predestroy(); this._duplexState &= NOT_PREDESTROYING; if (this._readableState !== null) this._readableState.updateNextTick(); if (this._writableState !== null) this._writableState.updateNextTick(); } } }; var Readable = class _Readable extends Stream { constructor(opts) { super(opts); this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD; this._readableState = new ReadableState(this, opts); if (opts) { if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD; if (opts.read) this._read = opts.read; if (opts.eagerOpen) this._readableState.updateNextTick(); if (opts.encoding) this.setEncoding(opts.encoding); } } setEncoding(encoding) { const dec = new TextDecoder(encoding); const map = this._readableState.map || echo; this._readableState.map = mapOrSkip; return this; function mapOrSkip(data) { const next = dec.push(data); return next === "" && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next); } } _read(cb) { cb(null); } pipe(dest, cb) { this._readableState.updateNextTick(); this._readableState.pipe(dest, cb); return dest; } read() { this._readableState.updateNextTick(); return this._readableState.read(); } push(data) { this._readableState.updateNextTickIfOpen(); return this._readableState.push(data); } unshift(data) { this._readableState.updateNextTickIfOpen(); return this._readableState.unshift(data); } resume() { this._duplexState |= READ_RESUMED_READ_AHEAD; this._readableState.updateNextTick(); return this; } pause() { this._duplexState &= this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED; return this; } static _fromAsyncIterator(ite, opts) { let destroy; const rs = new _Readable({ ...opts, read(cb) { ite.next().then(push).then(cb.bind(null, null)).catch(cb); }, predestroy() { destroy = ite.return(); }, destroy(cb) { if (!destroy) return cb(null); destroy.then(cb.bind(null, null)).catch(cb); } }); return rs; function push(data) { if (data.done) rs.push(null); else rs.push(data.value); } } static from(data, opts) { if (isReadStreamx(data)) return data; if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts); if (!Array.isArray(data)) data = data === void 0 ? [] : [data]; let i = 0; return new _Readable({ ...opts, read(cb) { this.push(i === data.length ? null : data[i++]); cb(null); } }); } static isBackpressured(rs) { return (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || rs._readableState.buffered >= rs._readableState.highWaterMark; } static isPaused(rs) { return (rs._duplexState & READ_RESUMED) === 0; } [asyncIterator]() { const stream = this; let error = null; let promiseResolve = null; let promiseReject = null; this.on("error", (err) => { error = err; }); this.on("readable", onreadable); this.on("close", onclose); return { [asyncIterator]() { return this; }, next() { return new Promise(function(resolve, reject) { promiseResolve = resolve; promiseReject = reject; const data = stream.read(); if (data !== null) ondata(data); else if ((stream._duplexState & DESTROYED) !== 0) ondata(null); }); }, return() { return destroy(null); }, throw(err) { return destroy(err); } }; function onreadable() { if (promiseResolve !== null) ondata(stream.read()); } function onclose() { if (promiseResolve !== null) ondata(null); } function ondata(data) { if (promiseReject === null) return; if (error) promiseReject(error); else if (data === null && (stream._duplexState & READ_DONE) === 0) promiseReject(STREAM_DESTROYED); else promiseResolve({ value: data, done: data === null }); promiseReject = promiseResolve = null; } function destroy(err) { stream.destroy(err); return new Promise((resolve, reject) => { if (stream._duplexState & DESTROYED) return resolve({ value: void 0, done: true }); stream.once("close", function() { if (err) reject(err); else resolve({ value: void 0, done: true }); }); }); } } }; var Writable = class extends Stream { constructor(opts) { super(opts); this._duplexState |= OPENING | READ_DONE; this._writableState = new WritableState(this, opts); if (opts) { if (opts.writev) this._writev = opts.writev; if (opts.write) this._write = opts.write; if (opts.final) this._final = opts.final; if (opts.eagerOpen) this._writableState.updateNextTick(); } } cork() { this._duplexState |= WRITE_CORKED; } uncork() { this._duplexState &= WRITE_NOT_CORKED; this._writableState.updateNextTick(); } _writev(batch, cb) { cb(null); } _write(data, cb) { this._writableState.autoBatch(data, cb); } _final(cb) { cb(null); } static isBackpressured(ws) { return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0; } static drained(ws) { if (ws.destroyed) return Promise.resolve(false); const state = ws._writableState; const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length; const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0); if (writes === 0) return Promise.resolve(true); if (state.drains === null) state.drains = []; return new Promise((resolve) => { state.drains.push({ writes, resolve }); }); } write(data) { this._writableState.updateNextTick(); return this._writableState.push(data); } end(data) { this._writableState.updateNextTick(); this._writableState.end(data); return this; } }; var Duplex = class extends Readable { // and Writable constructor(opts) { super(opts); this._duplexState = OPENING | this._duplexState & READ_READ_AHEAD; this._writableState = new WritableState(this, opts); if (opts) { if (opts.writev) this._writev = opts.writev; if (opts.write) this._write = opts.write; if (opts.final) this._final = opts.final; } } cork() { this._duplexState |= WRITE_CORKED; } uncork() { this._duplexState &= WRITE_NOT_CORKED; this._writableState.updateNextTick(); } _writev(batch, cb) { cb(null); } _write(data, cb) { this._writableState.autoBatch(data, cb); } _final(cb) { cb(null); } write(data) { this._writableState.updateNextTick(); return this._writableState.push(data); } end(data) { this._writableState.updateNextTick(); this._writableState.end(data); return this; } }; var Transform = class extends Duplex { constructor(opts) { super(opts); this._transformState = new TransformState(this); if (opts) { if (opts.transform) this._transform = opts.transform; if (opts.flush) this._flush = opts.flush; } } _write(data, cb) { if (this._readableState.buffered >= this._readableState.highWaterMark) { this._transformState.data = data; } else { this._transform(data, this._transformState.afterTransform); } } _read(cb) { if (this._transformState.data !== null) { const data = this._transformState.data; this._transformState.data = null; cb(null); this._transform(data, this._transformState.afterTransform); } else { cb(null); } } destroy(err) { super.destroy(err); if (this._transformState.data !== null) { this._transformState.data = null; this._transformState.afterTransform(); } } _transform(data, cb) { cb(null, data); } _flush(cb) { cb(null); } _final(cb) { this._transformState.afterFinal = cb; this._flush(transformAfterFlush.bind(this)); } }; var PassThrough = class extends Transform { }; function transformAfterFlush(err, data) { const cb = this._transformState.afterFinal; if (err) return cb(err); if (data !== null && data !== void 0) this.push(data); this.push(null); cb(null); } function pipelinePromise(...streams) { return new Promise((resolve, reject) => { return pipeline(...streams, (err) => { if (err) return reject(err); resolve(); }); }); } function pipeline(stream, ...streams) { const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams]; const done = all.length && typeof all[all.length - 1] === "function" ? all.pop() : null; if (all.length < 2) throw new Error("Pipeline requires at least 2 streams"); let src = all[0]; let dest = null; let error = null; for (let i = 1; i < all.length; i++) { dest = all[i]; if (isStreamx(src)) { src.pipe(dest, onerror); } else { errorHandle(src, true, i > 1, onerror); src.pipe(dest); } src = dest; } if (done) { let fin = false; const autoDestroy = isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy); dest.on("error", (err) => { if (error === null) error = err; }); dest.on("finish", () => { fin = true; if (!autoDestroy) done(error); }); if (autoDestroy) { dest.on("close", () => done(error || (fin ? null : PREMATURE_CLOSE))); } } return dest; function errorHandle(s, rd, wr, onerror2) { s.on("error", onerror2); s.on("close", onclose); function onclose() { if (rd && s._readableState && !s._readableState.ended) return onerror2(PREMATURE_CLOSE); if (wr && s._writableState && !s._writableState.ended) return onerror2(PREMATURE_CLOSE); } } function onerror(err) { if (!err || error) return; error = err; for (const s of all) { s.destroy(err); } } } function echo(s) { return s; } function isStream(stream) { return !!stream._readableState || !!stream._writableState; } function isStreamx(stream) { return typeof stream._duplexState === "number" && isStream(stream); } function isEnding(stream) { return !!stream._readableState && stream._readableState.ending; } function isEnded(stream) { return !!stream._readableState && stream._readableState.ended; } function isFinishing(stream) { return !!stream._writableState && stream._writableState.ending; } function isFinished(stream) { return !!stream._writableState && stream._writableState.ended; } function getStreamError(stream, opts = {}) { const err = stream._readableState && stream._readableState.error || stream._writableState && stream._writableState.error; return !opts.all && err === STREAM_DESTROYED ? null : err; } function isReadStreamx(stream) { return isStreamx(stream) && stream.readable; } function isDisturbed(stream) { return (stream._duplexState & OPENING) !== OPENING || (stream._duplexState & DESTROYING) === DESTROYING || (stream._duplexState & ACTIVE_OR_TICKING) !== 0; } function isTypedArray(data) { return typeof data === "object" && data !== null && typeof data.byteLength === "number"; } function defaultByteLength(data) { return isTypedArray(data) ? data.byteLength : 1024; } function noop() { } function abort() { this.destroy(new Error("Stream aborted.")); } function isWritev(s) { return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev; } module.exports = { pipeline, pipelinePromise, isStream, isStreamx, isEnding, isEnded, isFinishing, isFinished, isDisturbed, getStreamError, Stream, Writable, Readable, Duplex, Transform, // Export PassThrough for compatibility with Node.js core's stream module PassThrough }; } }); // ../../node_modules/teex/index.js var require_teex = __commonJS({ "../../node_modules/teex/index.js"(exports, module) { var { Readable } = require_streamx(); module.exports = function(s, forks = 2) { const streams = new Array(forks); const status = new Array(forks).fill(true); let ended = false; for (let i = 0; i < forks; i++) { streams[i] = new Readable({ read(cb) { const check = !status[i]; status[i] = true; if (check && allReadable()) s.resume(); cb(null); } }); } s.on("end", function() { ended = true; for (const stream of streams) stream.push(null); }); s.on("error", function(err) { for (const stream of streams) stream.destroy(err); }); s.on("close", function() { if (ended) return; for (const stream of streams) stream.destroy(); }); s.on("data", function(data) { let needsPause = false; for (let i = 0; i < streams.length; i++) { if (!(status[i] = streams[i].push(data))) { needsPause = true; } } if (needsPause) s.pause(); }); return streams; function allReadable() { for (let j = 0; j < status.length; j++) { if (!status[j]) return false; } return true; } }; } }); // ../../node_modules/bare-stream/web.js var require_web = __commonJS({ "../../node_modules/bare-stream/web.js"(exports) { var { Readable, Writable, Transform, getStreamError, isStreamx, isDisturbed } = require_streamx(); var tee = require_teex(); var readableKind = Symbol.for("bare.stream.readable.kind"); var writableKind = Symbol.for("bare.stream.writable.kind"); var transformKind = Symbol.for("bare.stream.transform.kind"); exports.ReadableStreamDefaultReader = class ReadableStreamDefaultReader { constructor(stream) { this._stream = stream; this._stream._stream.once("close", onclose).once("error", onerror); const closed = Promise.withResolvers(); closed.promise.catch(noop); this._closed = closed; function onclose() { closed.resolve(); } function onerror(err) { closed.reject(err); } } get closed() { return this._closed.promise; } read() { const stream = this._stream._stream; return new Promise((resolve, reject) => { const err = getStreamError(stream); if (err) return reject(err); if (stream.destroyed) { return resolve({ value: void 0, done: true }); } const value = stream.read(); if (value !== null) { return resolve({ value, done: false }); } stream.once("readable", onreadable).once("close", onclose).once("error", onerror); function onreadable() { const value2 = stream.read(); ondone(null, value2 === null ? { value: void 0, done: true } : { value: value2, done: false }); } function onclose() { ondone(null, { value: void 0, done: true }); } function onerror(err2) { ondone(err2, null); } function ondone(err2, value2) { stream.off("readable", onreadable).off("close", onclose).off("error", onerror); if (err2) reject(err2); else resolve(value2); } }); } releaseLock() { this._closed.reject(new TypeError("Reader was released")); this._stream._releaseLock(); this._stream = null; } cancel(reason = new TypeError("Stream was cancelled")) { const stream = this._stream._stream; if (stream.destroyed) return Promise.resolve(); return new Promise( (resolve) => stream.once("close", resolve).once("error", noop).destroy(reason) ); } }; exports.ReadableStreamDefaultController = class ReadableStreamDefaultController { constructor(stream) { this._stream = stream; } get desiredSize() { const stream = this._stream._stream; return stream._readableState.highWaterMark - stream._readableState.buffered; } enqueue(data) { this._stream._stream.push(data); } close() { this._stream._stream.push(null); } error(err) { this._stream._stream.destroy(err); } }; var ReadableStream = class _ReadableStream { static get [readableKind]() { return 0; } static from(iterable) { return new _ReadableStream(Readable.from(iterable)); } constructor(underlyingSource = {}, queuingStrategy) { if (isStreamx(underlyingSource)) { this._stream = underlyingSource; } else { if (queuingStrategy === void 0) { queuingStrategy = new exports.CountQueuingStrategy(); } const { start, pull, cancel } = underlyingSource; const { highWaterMark = 1, size = defaultSize } = queuingStrategy; this._stream = new Readable({ highWaterMark, byteLength: size }); const controller = new exports.ReadableStreamDefaultController(this); if (start) { this._stream._open = this._open.bind(this, start.call(this, controller)); } if (pull) { this._stream._read = this._read.bind(this, pull.bind(this, controller)); } if (cancel) { this._stream.once("error", cancel); } } this._reader = null; } get [readableKind]() { return _ReadableStream[readableKind]; } get locked() { return this._reader !== null; } getReader() { if (this.locked) throw new TypeError("Stream is locked"); this._reader = new exports.ReadableStreamDefaultReader(this); return this._reader; } cancel(reason = new TypeError("Stream was cancelled")) { const stream = this._stream; if (stream.destroyed) return Promise.resolve(); if (this.locked) return Promise.reject(new TypeError("Stream is locked")); return new Promise( (resolve) => stream.once("close", resolve).once("error", noop).destroy(reason) ); } tee() { const [a, b] = tee(this._stream); return [new _ReadableStream(a), new _ReadableStream(b)]; } pipeTo(destination) { return new Promise( (resolve, reject) => this._stream.pipe(destination._stream, (err) => { err ? reject(err) : resolve(); }) ); } [Symbol.asyncIterator]() { return this._stream[Symbol.asyncIterator](); } _releaseLock() { this._reader = null; } async _open(starting, cb) { let err = null; try { await starting; } catch (e) { err = e; } cb(err); } async _read(pull, cb) { let err = null; try { await pull(); } catch (e) { err = e; } cb(err); } }; function defaultSize() { return 1; } exports.ReadableStream = ReadableStream; exports.CountQueuingStrategy = class CountQueuingStrategy { constructor(opts = {}) { const { highWaterMark = 1 } = opts; this.highWaterMark = highWaterMark; } size(chunk) { return 1; } }; exports.ByteLengthQueuingStrategy = class ByteLengthQueuingStrategy { constructor(opts = {}) { const { highWaterMark = 16384 } = opts; this.highWaterMark = highWaterMark; } size(chunk) { return chunk.byteLength; } }; exports.isReadableStream = function isReadableStream(value) { if (value instanceof ReadableStream) return true; return typeof value === "object" && value !== null && value[readableKind] === ReadableStream[readableKind]; }; exports.isReadableStreamErrored = function isReadableStreamErrored(stream) { return getStreamError(stream._stream) !== null; }; exports.isReadableStreamDisturbed = function isReadableStreamDisturbed(stream) { return isDisturbed(stream._stream); }; exports.WritableStreamDefaultWriter = class WritableStreamDefaultWriter { constructor(stream) { this._stream = stream; this._stream._stream.once("close", onclose).once("error", onerror); const closed = Promise.withResolvers(); closed.promise.catch(noop); this._closed = closed; function onclose() { closed.resolve(); } function onerror(err) { closed.reject(err); } } get desiredSize() { const stream = this._stream._stream; return stream._writableState.highWaterMark - stream._writableState.buffered; } get closed() { return this._closed.promise; } get ready() { const stream = this._stream._stream; if (getStreamError(stream)) return Promise.reject(); return Writable.drained(stream).then(); } async write(chunk) { const stream = this._stream._stream; let err = getStreamError(stream); if (err) return Promise.reject(err); stream.write(chunk); await Writable.drained(stream); err = getStreamError(stream); if (err) return Promise.reject(err); } releaseLock() { this._closed.reject(new TypeError("Writer was released")); this._stream._releaseLock(); this._stream = null; } close() { const stream = this._stream._stream; if (stream.destroyed) return Promise.resolve(); return new Promise((resolve) => stream.once("close", resolve).end()); } abort(reason = new TypeError("Stream was aborted")) { const stream = this._stream._stream; if (stream.destroyed) return Promise.resolve(); return new Promise((resolve) => stream.once("close", resolve).destroy(reason)); } }; exports.WritableStreamDefaultController = class WritableStreamDefaultController { constructor(stream) { this._stream = stream; } error(err) { this._stream._stream.destroy(err); } }; var WritableStream = class _WritableStream { static get [writableKind]() { return 0; } constructor(underlyingSink = {}, queuingStrategy = {}) { if (isStreamx(underlyingSink)) { this._stream = underlyingSink; } else { if (queuingStrategy === void 0) { queuingStrategy = new exports.CountQueuingStrategy(); } const { start, write, close, abort } = underlyingSink; const { highWaterMark = 1, size = defaultSize } = queuingStrategy; this._stream = new Writable({ highWaterMark, byteLength: size }); this._controller = new exports.WritableStreamDefaultController(this); if (start) { this._stream._open = this._open.bind(this, start.call(this, this._controller)); } if (write) { this._stream._write = this._write.bind(this, write); } if (close) { this._stream._destroy = this._destroy.bind(this, close.call(this)); } if (abort) { this._stream.once("error", abort); } } this._writer = null; } get [writableKind]() { return _WritableStream[writableKind]; } get locked() { return this._writer !== null; } getWriter() { if (this.locked) throw new TypeError("Stream is locked"); this._writer = new exports.WritableStreamDefaultWriter(this); return this._writer; } abort(reason = new TypeError("Stream was aborted")) { if (this._stream.destroyed) return Promise.resolve(); if (this.locked) return Promise.reject(new TypeError("Stream is locked")); return new Promise((resolve) => this._stream.once("close", resolve).destroy(reason)); } close() { if (this._stream.destroyed) return Promise.resolve(); if (this.locked) return Promise.reject(new TypeError("Stream is locked")); return new Promise((resolve) => this._stream.once("close", resolve).end()); } _releaseLock() { this._writer = null; } async _open(starting, cb) { let err = null; try { await starting; } catch (e) { err = e; } cb(err); } async _write(write, data, cb) { let err = null; try { await write(data, this._controller); } catch (e) { err = e; } cb(err); } async _destroy(closing, cb) { let err = null; try { await closing; } catch (e) { err = e; } cb(err); } }; exports.WritableStream = WritableStream; exports.isWritableStream = function isWritableStream(value) { if (value instanceof WritableStream) return true; return typeof value === "object" && value !== null && value[writableKind] === WritableStream[writableKind]; }; exports.TransformStreamDefaultController = class TransformStreamDefaultController { constructor(stream) { this._stream = stream; } get desiredSize() { const stream = this._stream._stream; return stream._readableState.highWaterMark - stream._readableState.buffered; } enqueue(data) { this._stream._stream.push(data); } error(err) { this._stream._stream.destroy(err); } terminate() { const stream = this._stream._stream; stream.push(null); stream.destroy(new TypeError("Stream has been terminated")); } }; var TransformStream = class _TransformStream { static get [transformKind]() { return 0; } constructor(transformer = {}, writableStrategy = {}, readableStrategy = {}) { const { start, transform, flush } = transformer; this._stream = new Transform({ ...writableStrategy, ...readableStrategy }); this._writable = new WritableStream(this._stream); this._readable = new ReadableStream(this._stream); this._controller = new exports.TransformStreamDefaultController(this); if (start) { this._stream._open = this._open.bind(this, start.call(this, this._controller)); } if (transform) { this._stream._write = this._transform.bind(this, transform); } if (flush) { this._stream._flush = this._flush.bind(this, flush.call(this, this._controller)); } } get [transformKind]() { return _TransformStream[transformKind]; } get writable() { return this._writable; } get readable() { return this._readable; } async _open(starting, cb) { let err = null; try { await starting; } catch (e) { err = e; } cb(err); } async _transform(transform, data, cb) { let err = null; try { await transform(data, this._controller); } catch (e) { err = e; } cb(err); } async _flush(flush, cb) { let err = null; try { await flush; } catch (e) { err = e; } cb(err); } }; exports.TransformStream = TransformStream; exports.isTransformStream = function isTransformStream(value) { if (value instanceof TransformStream) return true; return typeof value === "object" && value !== null && value[transformKind] === TransformStream[transformKind]; }; function noop() { } } }); // ../../node_modules/bare-stream/index.js var require_bare_stream = __commonJS({ "../../node_modules/bare-stream/index.js"(exports, module) { var stream = require_streamx(); var { ReadableStream, WritableStream } = require_web(); var defaultEncoding = "utf8"; module.exports = exports = stream.Stream; exports.pipeline = stream.pipeline; exports.isStream = stream.isStream; exports.isEnding = stream.isEnding; exports.isEnded = stream.isEnded; exports.isFinishing = stream.isFinishing; exports.isFinished = stream.isFinished; exports.isDisturbed = stream.isDisturbed; exports.isErrored = function isErrored(stream2) { return exports.getStreamError(stream2) !== null; }; exports.isReadable = function isReadable(stream2) { return stream2.readable && !stream2.destroying && !exports.isEnded(stream2); }; exports.isWritable = function isWritable(stream2) { return stream2.writable && !stream2.destroying && !exports.isFinishing(stream2); }; exports.getStreamError = stream.getStreamError; exports.addAbortSignal = function addAbortSignal(signal, stream2) { function onAbort() { stream2.destroy(signal.reason); } if (signal.aborted) onAbort(); else signal.addEventListener("abort", onAbort); return stream2; }; exports.Stream = exports; exports.Readable = class Readable extends stream.Readable { constructor(opts = {}) { super({ ...opts, byteLength: null, byteLengthReadable: null, map: null, mapReadable: null }); if (this._construct) this._open = this._construct; if (this._read !== stream.Readable.prototype._read) { this._read = read.bind(this, this._read); } if (this._destroy !== stream.Stream.prototype._destroy) { this._destroy = destroy.bind(this, this._destroy); } } get closed() { return !exports.isReadable(this); } get errored() { return stream.getStreamError(this); } push(chunk, encoding) { if (typeof chunk === "string") { chunk = Buffer.from(chunk, encoding || defaultEncoding); } return super.push(chunk); } unshift(chunk, encoding) { if (typeof chunk === "string") { chunk = Buffer.from(chunk, encoding || defaultEncoding); } super.unshift(chunk); } static fromWeb(readableStream, opts = {}) { const stream2 = readableStream._stream; if (opts.encoding) stream2.setEncoding(opts.encoding); if (opts.signal) exports.addAbortSignal(opts.signal, stream2); return stream2; } static toWeb(readable, opts = {}) { return new ReadableStream(readable, opts.strategy); } async [Symbol.asyncDispose]() { if (!this.destroyed) this.destroy(); await new Promise((resolve) => exports.finished(this, resolve)); } }; exports.Writable = class Writable extends stream.Writable { constructor(opts = {}) { super({ ...opts, byteLength: null, byteLengthWritable, map: null, mapWritable: null }); if (this._construct) this._open = this._construct; if (this._write !== stream.Writable.prototype._write) { this._write = write.bind(this, this._write); } if (this._destroy !== stream.Stream.prototype._destroy) { this._destroy = destroy.bind(this, this._destroy); } } get closed() { return !exports.isWritable(this); } get errored() { return stream.getStreamError(this); } write(chunk, encoding, cb) { if (typeof encoding === "function") { cb = encoding; encoding = null; } if (typeof chunk === "string") { encoding = encoding || defaultEncoding; chunk = Buffer.from(chunk, encoding); } else { encoding = "buffer"; } const result = super.write({ chunk, encoding }); if (cb) stream.Writable.drained(this).then(() => cb(null), cb); return result; } end(chunk, encoding, cb) { if (typeof chunk === "function") { cb = chunk; chunk = null; } else if (typeof encoding === "function") { cb = encoding; encoding = null; } if (typeof chunk === "string") { encoding = encoding || defaultEncoding; chunk = Buffer.from(chunk, encoding || defaultEncoding); } else { encoding = "buffer"; } const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end(); if (cb) this.once("finish", () => cb(null)); return result; } static fromWeb(writableStream, opts = {}) { const stream2 = writableStream._stream; if (opts.signal) exports.addAbortSignal(opts.signal, stream2); return stream2; } static toWeb(writable) { return new WritableStream(writable); } async [Symbol.asyncDispose]() { if (!this.destroyed) this.destroy(); await new Promise((resolve) => exports.finished(this, resolve)); } }; exports.Duplex = class Duplex extends stream.Duplex { constructor(opts = {}) { super({ ...opts, byteLength: null, byteLengthReadable: null, byteLengthWritable, map: null, mapReadable: null, mapWritable: null }); if (this._construct) this._open = this._construct; if (this._read !== stream.Readable.prototype._read) { this._read = read.bind(this, this._read); } if (this._write !== stream.Duplex.prototype._write) { this._write = write.bind(this, this._write); } if (this._destroy !== stream.Stream.prototype._destroy) { this._destroy = destroy.bind(this, this._destroy); } } push(chunk, encoding) { if (typeof chunk === "string") { chunk = Buffer.from(chunk, encoding || defaultEncoding); } return super.push(chunk); } unshift(chunk, encoding) { if (typeof chunk === "string") { chunk = Buffer.from(chunk, encoding || defaultEncoding); } super.unshift(chunk); } write(chunk, encoding, cb) { if (typeof encoding === "function") { cb = encoding; encoding = null; } if (typeof chunk === "string") { encoding = encoding || defaultEncoding; chunk = Buffer.from(chunk, encoding); } else { encoding = "buffer"; } const result = super.write({ chunk, encoding }); if (cb) stream.Writable.drained(this).then(() => cb(null), cb); return result; } end(chunk, encoding, cb) { if (typeof chunk === "function") { cb = chunk; chunk = null; } else if (typeof encoding === "function") { cb = encoding; encoding = null; } if (typeof chunk === "string") { encoding = encoding || defaultEncoding; chunk = Buffer.from(chunk, encoding); } else { encoding = "buffer"; } const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end(); if (cb) this.once("finish", () => cb(null)); return result; } static fromWeb({ readable: readableStream, writable: writableStream }, opts) { const readable = exports.Readable.fromWeb(readableStream, opts); const writable = exports.Readable.fromWeb(writableStream, opts); const duplex = new exports.Duplex({ write(data, encoding, cb) { writable.write(data, encoding, cb); } }); readable.on("data", (data) => duplex.push(data)).on("end", () => duplex.push(null)).on("error", (err) => duplex.destroy(err)); writable.on("finish", () => duplex.end()).on("error", (err) => duplex.destroy(err)); return duplex; } static toWeb(duplex) { const readableStream = exports.Readable.toWeb(duplex); const writableStream = exports.Writable.toWeb(duplex); return { readable: readableStream, writable: writableStream }; } }; var DuplexSide = class extends exports.Duplex { constructor(opts) { super(opts); this._otherSide = null; this._cb = null; } _read() { const cb = this._cb; if (!cb) return; this._cb = null; cb(); } _write(chunk, encoding, cb) { this._otherSide.push(chunk, encoding); this._otherSide._cb = cb; } _final(cb) { this._otherSide.on("end", cb); this._otherSide.push(null); } }; exports.duplexPair = function duplexPair(opts) { const sideA = new DuplexSide(opts); const sideB = new DuplexSide(opts); sideA._otherSide = sideB; sideB._otherSide = sideA; return [sideA, sideB]; }; exports.Transform = class Transform extends stream.Transform { constructor(opts = {}) { super({ ...opts, byteLength: null, byteLengthReadable: null, byteLengthWritable, map: null, mapReadable: null, mapWritable: null }); if (this._transform !== stream.Transform.prototype._transform) { this._transform = transform.bind(this, this._transform); } else { this._transform = passthrough; } } push(chunk, encoding) { if (typeof chunk === "string") { chunk = Buffer.from(chunk, encoding || defaultEncoding); } return super.push(chunk); } unshift(chunk, encoding) { if (typeof chunk === "string") { chunk = Buffer.from(chunk, encoding || defaultEncoding); } super.unshift(chunk); } write(chunk, encoding, cb) { if (typeof encoding === "function") { cb = encoding; encoding = null; } if (typeof chunk === "string") { encoding = encoding || defaultEncoding; chunk = Buffer.from(chunk, encoding); } else { encoding = "buffer"; } const result = super.write({ chunk, encoding }); if (cb) stream.Writable.drained(this).then(() => cb(null), cb); return result; } end(chunk, encoding, cb) { if (typeof chunk === "function") { cb = chunk; chunk = null; } else if (typeof encoding === "function") { cb = encoding; encoding = null; } if (typeof chunk === "string") { encoding = encoding || defaultEncoding; chunk = Buffer.from(chunk, encoding); } else { encoding = "buffer"; } const result = chunk !== void 0 && chunk !== null ? super.end({ chunk, encoding }) : super.end(); if (cb) this.once("finish", () => cb(null)); return result; } }; exports.PassThrough = class PassThrough extends exports.Transform { }; exports.finished = function finished(stream2, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (!opts) opts = {}; const { cleanup = false } = opts; const done = () => { cb(exports.getStreamError(stream2, { all: true })); if (cleanup) detach(); }; const detach = () => { stream2.off("close", done); stream2.off("error", noop); }; if (stream2.destroyed) { done(); } else { stream2.on("close", done); stream2.on("error", noop); } return detach; }; function read(read2, cb) { read2.call(this, 65536); cb(null); } function write(write2, data, cb) { write2.call(this, data.chunk, data.encoding, cb); } function transform(transform2, data, cb) { transform2.call(this, data.chunk, data.encoding, cb); } function destroy(destroy2, cb) { destroy2.call(this, exports.getStreamError(this), cb); } function passthrough(data, cb) { cb(null, data.chunk); } function byteLengthWritable(data) { return data.chunk.byteLength; } function noop() { } } }); // ../../node_modules/bare-fs/binding.js var require_binding3 = __commonJS({ "../../node_modules/bare-fs/binding.js"(exports, module) { module.exports = __require.addon(); } }); // ../../node_modules/bare-fs/lib/constants.js var require_constants3 = __commonJS({ "../../node_modules/bare-fs/lib/constants.js"(exports, module) { var binding = require_binding3(); module.exports = { O_RDWR: binding.O_RDWR, O_RDONLY: binding.O_RDONLY, O_WRONLY: binding.O_WRONLY, O_CREAT: binding.O_CREAT, O_TRUNC: binding.O_TRUNC, O_APPEND: binding.O_APPEND, F_OK: binding.F_OK || 0, R_OK: binding.R_OK || 0, W_OK: binding.W_OK || 0, X_OK: binding.X_OK || 0, S_IFMT: binding.S_IFMT, S_IFREG: binding.S_IFREG, S_IFDIR: binding.S_IFDIR, S_IFCHR: binding.S_IFCHR, S_IFLNK: binding.S_IFLNK, S_IFBLK: binding.S_IFBLK || 0, S_IFIFO: binding.S_IFIFO || 0, S_IFSOCK: binding.S_IFSOCK || 0, S_IRUSR: binding.S_IRUSR || 0, S_IWUSR: binding.S_IWUSR || 0, S_IXUSR: binding.S_IXUSR || 0, S_IRGRP: binding.S_IRGRP || 0, S_IWGRP: binding.S_IWGRP || 0, S_IXGRP: binding.S_IXGRP || 0, S_IROTH: binding.S_IROTH || 0, S_IWOTH: binding.S_IWOTH || 0, S_IXOTH: binding.S_IXOTH || 0, UV_DIRENT_UNKNOWN: binding.UV_DIRENT_UNKNOWN, UV_DIRENT_FILE: binding.UV_DIRENT_FILE, UV_DIRENT_DIR: binding.UV_DIRENT_DIR, UV_DIRENT_LINK: binding.UV_DIRENT_LINK, UV_DIRENT_FIFO: binding.UV_DIRENT_FIFO, UV_DIRENT_SOCKET: binding.UV_DIRENT_SOCKET, UV_DIRENT_CHAR: binding.UV_DIRENT_CHAR, UV_DIRENT_BLOCK: binding.UV_DIRENT_BLOCK, COPYFILE_EXCL: binding.UV_FS_COPYFILE_EXCL, COPYFILE_FICLONE: binding.UV_FS_COPYFILE_FICLONE, COPYFILE_FICLONE_FORCE: binding.UV_FS_COPYFILE_FICLONE_FORCE, UV_FS_SYMLINK_DIR: binding.UV_FS_SYMLINK_DIR, UV_FS_SYMLINK_JUNCTION: binding.UV_FS_SYMLINK_JUNCTION }; } }); // ../../node_modules/bare-fs/lib/errors.js var require_errors4 = __commonJS({ "../../node_modules/bare-fs/lib/errors.js"(exports, module) { var os = require_bare_os(); module.exports = class FileError extends Error { constructor(msg, opts = {}) { const { code, operation = null, path = null, destination = null, fd = -1 } = opts; if (operation !== null) msg += describe(operation, opts); super(`${code}: ${msg}`); this.code = code; if (operation !== null) this.operation = operation; if (path !== null) this.path = path; if (destination !== null) this.destination = destination; if (fd !== -1) this.fd = fd; } get name() { return "FileError"; } // For Node.js compatibility get errno() { return os.constants.errnos[this.code]; } // For Node.js compatibility get syscall() { return this.operation; } // For Node.js compatibility get dest() { return this.destination; } }; function describe(operation, opts) { const { path = null, destination = null, fd = -1 } = opts; let result = `, ${operation}`; if (path !== null) { result += ` ${JSON.stringify(path)}`; if (destination !== null) { result += ` -> ${JSON.stringify(destination)}`; } } else if (fd !== -1) { result += ` ${fd}`; } return result; } } }); // ../../node_modules/bare-fs/promises.js var require_promises = __commonJS({ "../../node_modules/bare-fs/promises.js"(exports) { var EventEmitter = require_bare_events(); var fs = require_bare_fs(); var FileHandle = class extends EventEmitter { constructor(fd) { super(); this.fd = fd; } async close() { await fs.close(this.fd); this.fd = -1; this.emit("close"); } async read(buffer, ...args) { return { bytesRead: await fs.read(this.fd, buffer, ...args), buffer }; } async readv(buffers, ...args) { return { bytesRead: await fs.readv(this.fd, buffers, ...args), buffers }; } async write(buffer, ...args) { return { bytesWritten: await fs.write(this.fd, buffer, ...args), buffer }; } async writev(buffers, ...args) { return { bytesWritten: await fs.writev(this.fd, buffers, ...args), buffers }; } async stat() { return fs.fstat(this.fd); } async chmod(mode) { await fs.fchmod(this.fd, mode); } createReadStream(opts) { return fs.createReadStream(null, { ...opts, fd: this.fd }); } createWriteStream(opts) { return fs.createWriteStream(null, { ...opts, fd: this.fd }); } async [Symbol.asyncDispose]() { await this.close(); } }; exports.open = async function open(filepath, flags, mode) { return new FileHandle(await fs.open(filepath, flags, mode)); }; exports.access = fs.access; exports.appendFile = fs.appendFile; exports.chmod = fs.chmod; exports.constants = fs.constants; exports.copyFile = fs.copyFile; exports.cp = fs.cp; exports.lstat = fs.lstat; exports.mkdir = fs.mkdir; exports.opendir = fs.opendir; exports.readFile = fs.readFile; exports.readdir = fs.readdir; exports.readlink = fs.readlink; exports.realpath = fs.realpath; exports.rename = fs.rename; exports.rm = fs.rm; exports.rmdir = fs.rmdir; exports.stat = fs.stat; exports.symlink = fs.symlink; exports.unlink = fs.unlink; exports.utimes = fs.utimes; exports.watch = fs.watch; exports.writeFile = fs.writeFile; } }); // ../../node_modules/bare-fs/index.js var require_bare_fs = __commonJS({ "../../node_modules/bare-fs/index.js"(exports) { var FIFO = require_fast_fifo(); var EventEmitter = require_bare_events(); var path = require_bare_path(); var { isURL, fileURLToPath } = require_bare_url(); var { Readable, Writable } = require_bare_stream(); var binding = require_binding3(); var constants = require_constants3(); var FileError = require_errors4(); var isWindows = Bare.platform === "win32"; exports.constants = constants; var FileRequest = class _FileRequest { static borrow() { if (this._free.length > 0) return this._free.pop(); return new _FileRequest(); } static return(req) { if (this._free.length < 32) this._free.push(req.reset()); else req.destroy(); } constructor() { this._reset(); this._handle = binding.requestInit(this, this._onresult); } get handle() { return this._handle; } retain(value) { this._retain = value; } reset() { if (this._handle === null) return this; binding.requestReset(this._handle); this._reset(); return this; } destroy() { if (this._handle === null) return this; binding.requestDestroy(this._handle); this._reset(); this._handle = null; return this; } then(resolve, reject) { return this._promise.then(resolve, reject); } return() { if (this._handle === null) return this; _FileRequest.return(this); return this; } _reset() { this._promise = new Promise((resolve, reject) => { this._resolve = resolve; this._reject = reject; }); this._retain = null; } _onresult(err, status) { if (err) this._reject(err); else this._resolve(status); } }; FileRequest._free = []; function ok(result, cb) { if (typeof result === "function") { cb = result; result = void 0; } if (cb) cb(null, result); else return result; } function fail(err, cb) { if (cb) cb(err); else throw err; } function done(err, result, cb) { if (typeof result === "function") { cb = result; result = void 0; } if (err) fail(err, cb); else return ok(result, cb); } async function open(filepath, flags = "r", mode = 438, cb) { if (typeof flags === "function") { cb = flags; flags = "r"; mode = 438; } else if (typeof mode === "function") { cb = mode; mode = 438; } if (typeof flags === "string") flags = toFlags(flags); if (typeof mode === "string") mode = toMode(mode); filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let fd; let err = null; try { binding.open(req.handle, filepath, flags, mode); fd = await req; } catch (e) { err = new FileError(e.message, { operation: "open", code: e.code, path: filepath }); } finally { req.return(); } return done(err, fd, cb); } function openSync(filepath, flags = "r", mode = 438) { if (typeof flags === "string") flags = toFlags(flags); if (typeof mode === "string") mode = toMode(mode); filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { return binding.openSync(req.handle, filepath, flags, mode); } catch (e) { throw new FileError(e.message, { operation: "open", code: e.code, path: filepath }); } finally { req.return(); } } async function close(fd, cb) { const req = FileRequest.borrow(); let err = null; try { binding.close(req.handle, fd); await req; } catch (e) { err = new FileError(e.message, { operation: "close", code: e.code, fd }); } finally { req.return(); } return done(err, cb); } function closeSync(fd) { const req = FileRequest.borrow(); try { binding.closeSync(req.handle, fd); } catch (e) { throw new FileError(e.message, { operation: "close", code: e.code, fd }); } finally { req.return(); } } async function access(filepath, mode = constants.F_OK, cb) { if (typeof mode === "function") { cb = mode; mode = constants.F_OK; } filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let err = null; try { binding.access(req.handle, filepath, mode); await req; } catch (e) { err = new FileError(e.message, { operation: "access", code: e.code, path: filepath }); } finally { req.return(); } return done(err, cb); } function accessSync(filepath, mode = constants.F_OK) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.accessSync(req.handle, filepath, mode); } catch (e) { throw new FileError(e.message, { operation: "access", code: e.code, path: filepath }); } finally { req.return(); } } async function exists(filepath, cb) { let ok2 = true; try { await access(filepath); } catch { ok2 = false; } return done(null, ok2, cb); } function existsSync(filepath) { try { accessSync(filepath); } catch { return false; } return true; } async function read(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1, cb) { if (typeof offset === "function") { cb = offset; offset = 0; len = buffer.byteLength; pos = -1; } else if (typeof len === "function") { cb = len; len = buffer.byteLength - offset; pos = -1; } else if (typeof pos === "function") { cb = pos; pos = -1; } if (typeof pos !== "number") pos = -1; const req = FileRequest.borrow(); let bytes; let err = null; try { binding.read(req.handle, fd, buffer, offset, len, pos); bytes = await req; } catch (e) { err = new FileError(e.message, { operation: "read", code: e.code, fd }); } finally { req.return(); } return done(err, bytes, cb); } function readSync(fd, buffer, offset = 0, len = buffer.byteLength - offset, pos = -1) { const req = FileRequest.borrow(); try { return binding.readSync(req.handle, fd, buffer, offset, len, pos); } catch (e) { throw new FileError(e.message, { operation: "read", code: e.code, fd }); } finally { req.return(); } } async function readv(fd, buffers, pos = -1, cb) { if (typeof pos === "function") { cb = pos; pos = -1; } if (typeof pos !== "number") pos = -1; const req = FileRequest.borrow(); let bytes; let err = null; try { binding.readv(req.handle, fd, buffers, pos); bytes = await req; } catch (e) { err = new FileError(e.message, { operation: "readv", code: e.code, fd }); } finally { req.return(); } return done(err, bytes, cb); } function readvSync(fd, buffers, pos = -1) { if (typeof pos !== "number") pos = -1; const req = FileRequest.borrow(); try { return binding.readvSync(req.handle, fd, buffers, pos); } catch (e) { throw new FileError(e.message, { operation: "readv", code: e.code, fd }); } finally { req.return(); } } async function write(fd, data, offset, len, pos = -1, cb) { if (typeof data === "string") { let encoding = len; cb = pos; pos = offset; if (typeof pos === "function") { cb = pos; pos = -1; encoding = "utf8"; } else if (typeof encoding === "function") { cb = encoding; encoding = "utf8"; } if (typeof pos === "string") { encoding = pos; pos = -1; } data = Buffer.from(data, encoding); offset = 0; len = data.byteLength; } else if (typeof offset === "function") { cb = offset; offset = 0; len = data.byteLength; pos = -1; } else if (typeof len === "function") { cb = len; len = data.byteLength - offset; pos = -1; } else if (typeof pos === "function") { cb = pos; pos = -1; } if (typeof offset !== "number") offset = 0; if (typeof len !== "number") len = data.byteLength - offset; if (typeof pos !== "number") pos = -1; const req = FileRequest.borrow(); let bytes; let err = null; try { binding.write(req.handle, fd, data, offset, len, pos); bytes = await req; } catch (e) { err = new FileError(e.message, { operation: "write", code: e.code, fd }); } finally { req.return(); } return done(err, bytes, cb); } function writeSync(fd, data, offset, len, pos = -1) { if (typeof data === "string") { let encoding = len; pos = offset; if (typeof pos === "string") { encoding = pos; pos = -1; } data = Buffer.from(data, encoding); offset = 0; len = data.byteLength; } if (typeof offset !== "number") offset = 0; if (typeof len !== "number") len = data.byteLength - offset; if (typeof pos !== "number") pos = -1; const req = FileRequest.borrow(); try { return binding.writeSync(req.handle, fd, data, offset, len, pos); } catch (e) { throw new FileError(e.message, { operation: "write", code: e.code, fd }); } finally { req.return(); } } async function writev(fd, buffers, pos = -1, cb) { if (typeof pos === "function") { cb = pos; pos = -1; } if (typeof pos !== "number") pos = -1; const req = FileRequest.borrow(); let bytes; let err = null; try { binding.writev(req.handle, fd, buffers, pos); bytes = await req; } catch (e) { err = new FileError(e.message, { operation: "writev", code: e.code, fd }); } finally { req.return(); } return done(err, bytes, cb); } function writevSync(fd, buffers, pos = -1) { if (typeof pos !== "number") pos = -1; const req = FileRequest.borrow(); try { return binding.writevSync(req.handle, fd, buffers, pos); } catch (e) { throw new FileError(e.message, { operation: "writev", code: e.code, fd }); } finally { req.return(); } } async function stat(filepath, cb) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let st; let err = null; try { binding.stat(req.handle, filepath); await req; st = new Stats(...binding.requestResultStat(req.handle)); } catch (e) { err = new FileError(e.message, { operation: "stat", code: e.code, path: filepath }); } finally { req.return(); } return done(err, st, cb); } function statSync(filepath) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.statSync(req.handle, filepath); return new Stats(...binding.requestResultStat(req.handle)); } catch (e) { throw new FileError(e.message, { operation: "stat", code: e.code, path: filepath }); } finally { req.return(); } } async function lstat(filepath, cb) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let st; let err = null; try { binding.lstat(req.handle, filepath); await req; st = new Stats(...binding.requestResultStat(req.handle)); } catch (e) { err = new FileError(e.message, { operation: "lstat", code: e.code, path: filepath }); } finally { req.return(); } return done(err, st, cb); } function lstatSync(filepath) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.lstatSync(req.handle, filepath); return new Stats(...binding.requestResultStat(req.handle)); } catch (e) { throw new FileError(e.message, { operation: "lstat", code: e.code, path: filepath }); } finally { req.return(); } } async function fstat(fd, cb) { const req = FileRequest.borrow(); let st; let err = null; try { binding.fstat(req.handle, fd); await req; st = new Stats(...binding.requestResultStat(req.handle)); } catch (e) { err = new FileError(e.message, { operation: "fstat", code: e.code, fd }); } finally { req.return(); } return done(err, st, cb); } function fstatSync(fd) { const req = FileRequest.borrow(); try { binding.fstatSync(req.handle, fd); return new Stats(...binding.requestResultStat(req.handle)); } catch (e) { throw new FileError(e.message, { operation: "fstat", code: e.code, fd }); } finally { req.return(); } } async function ftruncate(fd, len = 0, cb) { if (typeof len === "function") { cb = len; len = 0; } if (typeof len !== "number") len = 0; const req = FileRequest.borrow(); let err = null; try { binding.ftruncate(req.handle, fd, len); await req; } catch (e) { err = new FileError(e.message, { operation: "ftruncate", code: e.code, fd }); } finally { req.return(); } return done(err, cb); } function ftruncateSync(fd, len = 0) { if (typeof len !== "number") len = 0; const req = FileRequest.borrow(); try { binding.ftruncateSync(req.handle, fd, len); } catch (e) { throw new FileError(e.message, { operation: "ftruncate", code: e.code, fd }); } finally { req.return(); } } async function chmod(filepath, mode, cb) { if (typeof mode === "string") mode = toMode(mode); filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let err = null; try { binding.chmod(req.handle, filepath, mode); await req; } catch (e) { err = new FileError(e.message, { operation: "chmod", code: e.code, path: filepath }); } finally { req.return(); } return done(err, cb); } function chmodSync(filepath, mode) { if (typeof mode === "string") mode = toMode(mode); filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.chmodSync(req.handle, filepath, mode); } catch (e) { throw new FileError(e.message, { operation: "chmod", code: e.code, path: filepath }); } finally { req.return(); } } async function fchmod(fd, mode, cb) { if (typeof mode === "string") mode = toMode(mode); const req = FileRequest.borrow(); let err = null; try { binding.fchmod(req.handle, fd, mode); await req; } catch (e) { err = new FileError(e.message, { operation: "fchmod", code: e.code, fd }); } finally { req.return(); } return done(err, cb); } function fchmodSync(fd, mode) { if (typeof mode === "string") mode = toMode(mode); const req = FileRequest.borrow(); try { binding.fchmodSync(req.handle, fd, mode); } catch (e) { throw new FileError(e.message, { operation: "fchmod", code: e.code, fd }); } finally { req.return(); } } async function utimes(filepath, atime, mtime, cb) { if (typeof atime !== "number") atime = atime.getTime() / 1e3; if (typeof mtime !== "number") mtime = mtime.getTime() / 1e3; filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let err = null; try { binding.utimes(req.handle, filepath, atime, mtime); await req; } catch (e) { err = new FileError(e.message, { operation: "utimes", code: e.code, path: filepath }); } finally { req.return(); } return done(err, cb); } function utimesSync(filepath, atime, mtime) { if (typeof atime !== "number") atime = atime.getTime() / 1e3; if (typeof mtime !== "number") mtime = mtime.getTime() / 1e3; filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.utimesSync(req.handle, filepath, atime, mtime); } catch (e) { throw new FileError(e.message, { operation: "utimes", code: e.code, path: filepath }); } finally { req.return(); } } async function mkdir(filepath, opts, cb) { if (typeof opts === "function") { cb = opts; opts = { mode: 511 }; } if (typeof opts === "number") opts = { mode: opts }; else if (!opts) opts = {}; const mode = typeof opts.mode === "number" ? opts.mode : 511; filepath = toNamespacedPath(filepath); if (opts.recursive) { let err2 = null; try { try { await mkdir(filepath, { mode }); } catch (err3) { if (err3.code !== "ENOENT") { if (!(await stat(filepath)).isDirectory()) throw err3; } else { while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1); const i = filepath.lastIndexOf(path.sep); if (i <= 0) throw err3; await mkdir(filepath.slice(0, i), { mode, recursive: true }); try { await mkdir(filepath, { mode }); } catch (err4) { if (!(await stat(filepath)).isDirectory()) throw err4; } } } } catch (e) { err2 = e; } return done(err2, cb); } const req = FileRequest.borrow(); let err = null; try { binding.mkdir(req.handle, filepath, mode); await req; } catch (e) { err = new FileError(e.message, { operation: "mkdir", code: e.code, path: filepath }); } finally { req.return(); } return done(err, cb); } function mkdirSync(filepath, opts) { if (typeof opts === "number") opts = { mode: opts }; else if (!opts) opts = {}; const mode = typeof opts.mode === "number" ? opts.mode : 511; filepath = toNamespacedPath(filepath); if (opts.recursive) { try { mkdirSync(filepath, { mode }); } catch (err) { if (err.code !== "ENOENT") { if (!statSync(filepath).isDirectory()) throw err; } else { while (filepath.endsWith(path.sep)) filepath = filepath.slice(0, -1); const i = filepath.lastIndexOf(path.sep); if (i <= 0) throw err; mkdirSync(filepath.slice(0, i), { mode, recursive: true }); try { mkdirSync(filepath, { mode }); } catch (err2) { if (!statSync(filepath).isDirectory()) throw err2; } } } return; } const req = FileRequest.borrow(); try { binding.mkdirSync(req.handle, filepath, mode); } catch (e) { throw new FileError(e.message, { operation: "mkdir", code: e.code, path: filepath }); } finally { req.return(); } } async function rmdir(filepath, cb) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let err = null; try { binding.rmdir(req.handle, filepath); await req; } catch (e) { err = new FileError(e.message, { operation: "rmdir", code: e.code, path: filepath }); } finally { req.return(); } return done(err, cb); } function rmdirSync(filepath) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.rmdirSync(req.handle, filepath); } catch (e) { throw new FileError(e.message, { operation: "rmdir", code: e.code, path: filepath }); } finally { req.return(); } } async function rm(filepath, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (!opts) opts = {}; filepath = toNamespacedPath(filepath); let err = null; try { const st = await lstat(filepath); if (st.isDirectory()) { if (opts.recursive) { try { await rmdir(filepath); } catch (err2) { if (err2.code !== "ENOTEMPTY") throw err2; const files = await readdir(filepath); for (const file of files) { await rm(filepath + path.sep + file, opts); } await rmdir(filepath); } } else { throw new FileError("is a directory", { operation: "rm", code: "EISDIR", path: filepath }); } } else { await unlink(filepath); } } catch (e) { if (e.code !== "ENOENT" || !opts.force) err = e; } return done(err, cb); } function rmSync(filepath, opts) { if (!opts) opts = {}; filepath = toNamespacedPath(filepath); try { const st = lstatSync(filepath); if (st.isDirectory()) { if (opts.recursive) { try { rmdirSync(filepath); } catch (err) { if (err.code !== "ENOTEMPTY") throw err; const files = readdirSync(filepath); for (const file of files) { rmSync(filepath + path.sep + file, opts); } rmdirSync(filepath); } } else { throw new FileError("is a directory", { operation: "rm", code: "EISDIR", path: filepath }); } } else { unlinkSync(filepath); } } catch (err) { if (err.code !== "ENOENT" || !opts.force) throw err; } } async function unlink(filepath, cb) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let err = null; try { binding.unlink(req.handle, filepath); await req; } catch (e) { err = new FileError(e.message, { operation: "unlink", code: e.code, path: filepath }); } finally { req.return(); } return done(err, cb); } function unlinkSync(filepath) { filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.unlinkSync(req.handle, filepath); } catch (e) { throw new FileError(e.message, { operation: "unlink", code: e.code, path: filepath }); } finally { req.return(); } } async function rename(src, dst, cb) { src = toNamespacedPath(src); dst = toNamespacedPath(dst); const req = FileRequest.borrow(); let err = null; try { binding.rename(req.handle, src, dst); await req; } catch (e) { err = new FileError(e.message, { operation: "rename", code: e.code, path: src, destination: dst }); } finally { req.return(); } return done(err, cb); } function renameSync(src, dst) { src = toNamespacedPath(src); dst = toNamespacedPath(dst); const req = FileRequest.borrow(); try { binding.renameSync(req.handle, src, dst); } catch (e) { throw new FileError(e.message, { operation: "rename", code: e.code, path: src, destination: dst }); } finally { req.return(); } } async function copyFile(src, dst, mode = 0, cb) { if (typeof mode === "function") { cb = mode; mode = 0; } src = toNamespacedPath(src); dst = toNamespacedPath(dst); const req = FileRequest.borrow(); let err = null; try { binding.copyfile(req.handle, src, dst, mode); await req; } catch (e) { err = new FileError(e.message, { operation: "copyfile", code: e.code, path: src, destination: dst }); } finally { req.return(); } return done(err, cb); } function copyFileSync(src, dst, mode = 0) { src = toNamespacedPath(src); dst = toNamespacedPath(dst); const req = FileRequest.borrow(); try { binding.copyfileSync(req.handle, src, dst, mode); } catch (e) { throw new FileError(e.message, { operation: "copyfile", code: e.code, path: src, destination: dst }); } finally { req.return(); } } async function cp(src, dst, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (!opts) opts = {}; src = toNamespacedPath(src); dst = toNamespacedPath(dst); let err = null; try { const st = await lstat(src); if (st.isDirectory()) { if (opts.recursive !== true) { throw new FileError("is a directory", { operation: "cp", code: "EISDIR", path: src }); } try { await lstat(dst); } catch (e) { if (e.code !== "ENOENT") throw e; await mkdir(dst, { mode: st.mode, recursive: true }); } const dir = await opendir(src); for await (const { name } of dir) { await cp(path.join(src, name), path.join(dst, name), opts); } } else if (st.isFile()) { await copyFile(src, dst); await chmod(dst, st.mode); } } catch (e) { err = e; } return done(err, cb); } function cpSync(src, dst, opts = {}) { src = toNamespacedPath(src); dst = toNamespacedPath(dst); const st = lstatSync(src); if (st.isDirectory()) { if (opts.recursive !== true) { throw new FileError("is a directory", { operation: "cp", code: "EISDIR", path: src }); } try { lstatSync(dst); } catch (e) { if (e.code !== "ENOENT") throw e; mkdirSync(dst, { mode: st.mode, recursive: true }); } const dir = opendirSync(src); for (const { name } of dir) { cpSync(path.join(src, name), path.join(dst, name), opts); } } else if (st.isFile()) { copyFileSync(src, dst); chmodSync(dst, st.mode); } } async function realpath(filepath, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; const { encoding = "utf8" } = opts; filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let res; let err = null; try { binding.realpath(req.handle, filepath); await req; res = Buffer.from(binding.requestResultString(req.handle)); if (encoding !== "buffer") res = res.toString(encoding); } catch (e) { err = new FileError(e.message, { operation: "realpath", code: e.code, path: filepath }); } finally { req.return(); } return done(err, res, cb); } function realpathSync(filepath, opts) { if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; const { encoding = "utf8" } = opts; filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.realpathSync(req.handle, filepath); let res = Buffer.from(binding.requestResultString(req.handle)); if (encoding !== "buffer") res = res.toString(encoding); return res; } catch (e) { throw new FileError(e.message, { operation: "realpath", code: e.code, path: filepath }); } finally { req.return(); } } async function readlink(filepath, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; const { encoding = "utf8" } = opts; filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let res; let err = null; try { binding.readlink(req.handle, filepath); await req; res = Buffer.from(binding.requestResultString(req.handle)); if (encoding !== "buffer") res = res.toString(encoding); } catch (e) { err = new FileError(e.message, { operation: "readlink", code: e.code, path: filepath }); } finally { req.return(); } return done(err, res, cb); } function readlinkSync(filepath, opts) { if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; const { encoding = "utf8" } = opts; filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.readlinkSync(req.handle, filepath); let res = Buffer.from(binding.requestResultString(req.handle)); if (encoding !== "buffer") res = res.toString(encoding); return res; } catch (e) { throw new FileError(e.message, { operation: "readlink", code: e.code, path: filepath }); } finally { req.return(); } } function normalizeSymlinkTarget(target, type, filepath) { if (isWindows) { if (type === constants.UV_FS_SYMLINK_JUNCTION) target = path.resolve(filepath, "..", target); if (path.isAbsolute(target)) return path.toNamespacedPath(target); return target.replace(/\//g, path.sep); } return target; } async function symlink(target, filepath, type, cb) { if (typeof type === "function") { cb = type; type = null; } filepath = toNamespacedPath(filepath); if (typeof type === "string") { switch (type) { case "dir": type = constants.UV_FS_SYMLINK_DIR; break; case "junction": type = constants.UV_FS_SYMLINK_JUNCTION; break; case "file": default: type = 0; break; } } else if (typeof type !== "number") { if (isWindows) { target = path.resolve(filepath, "..", target); try { type = (await stat(target)).isDirectory() ? constants.UV_FS_SYMLINK_DIR : constants.UV_FS_SYMLINK_JUNCTION; } catch { type = 0; } } else { type = 0; } } target = normalizeSymlinkTarget(target, type, filepath); const req = FileRequest.borrow(); let err = null; try { binding.symlink(req.handle, target, filepath, type); await req; } catch (e) { err = new FileError(e.message, { operation: "symlink", code: e.code, path: target, destination: filepath }); } finally { req.return(); } return done(err, cb); } function symlinkSync(target, filepath, type) { filepath = toNamespacedPath(filepath); if (typeof type === "string") { switch (type) { case "dir": type = constants.UV_FS_SYMLINK_DIR; break; case "junction": type = constants.UV_FS_SYMLINK_JUNCTION; break; case "file": default: type = 0; break; } } else if (typeof type !== "number") { if (isWindows) { target = path.resolve(filepath, "..", target); try { type = statSync(target).isDirectory() ? constants.UV_FS_SYMLINK_DIR : constants.UV_FS_SYMLINK_JUNCTION; } catch { type = 0; } } else { type = 0; } } target = normalizeSymlinkTarget(target, type, filepath); const req = FileRequest.borrow(); try { binding.symlinkSync(req.handle, target, filepath, type); } catch (e) { throw new FileError(e.message, { operation: "symlink", code: e.code, path: target, destination: filepath }); } finally { req.return(); } } async function opendir(filepath, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); let dir; let err = null; try { binding.opendir(req.handle, filepath); await req; dir = new Dir(filepath, binding.requestResultDir(req.handle), opts); } catch (e) { err = new FileError(e.message, { operation: "opendir", code: e.code, path: filepath }); } finally { req.return(); } return done(err, dir, cb); } function opendirSync(filepath, opts) { if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; filepath = toNamespacedPath(filepath); const req = FileRequest.borrow(); try { binding.opendirSync(req.handle, filepath); return new Dir(filepath, binding.requestResultDir(req.handle), opts); } catch (e) { throw new FileError(e.message, { operation: "opendir", code: e.code, path: filepath }); } finally { req.return(); } } async function readdir(filepath, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; const { withFileTypes = false } = opts; filepath = toNamespacedPath(filepath); let result = []; let err = null; try { const dir = await opendir(filepath); for await (const entry of dir) { result.push(withFileTypes ? entry : entry.name); } } catch (e) { result = []; err = e; } return done(err, result, cb); } function readdirSync(filepath, opts) { if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; const { withFileTypes = false } = opts; filepath = toNamespacedPath(filepath); const dir = opendirSync(filepath, opts); const result = []; for (const entry of dir) { result.push(withFileTypes ? entry : entry.name); } return result; } async function readFile(filepath, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; const { encoding = "buffer" } = opts; let fd = -1; let buffer = null; let err = null; try { fd = await open(filepath, opts.flag || "r"); const st = await fstat(fd); let len = 0; if (st.size === 0) { const buffers = []; while (true) { buffer = Buffer.allocUnsafe(8192); const r = await read(fd, buffer); len += r; if (r === 0) break; buffers.push(buffer.subarray(0, r)); } buffer = Buffer.concat(buffers); } else { buffer = Buffer.allocUnsafe(st.size); while (true) { const r = await read(fd, len ? buffer.subarray(len) : buffer); len += r; if (r === 0 || len === buffer.byteLength) break; } if (len !== buffer.byteLength) buffer = buffer.subarray(0, len); } if (encoding !== "buffer") buffer = buffer.toString(encoding); } catch (e) { err = e; } finally { if (fd !== -1) await close(fd); } return done(err, buffer, cb); } function readFileSync(filepath, opts) { if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; const { encoding = "buffer" } = opts; let fd = -1; try { fd = openSync(filepath, opts.flag || "r"); const st = fstatSync(fd); let buffer; let len = 0; if (st.size === 0) { const buffers = []; while (true) { buffer = Buffer.allocUnsafe(8192); const r = readSync(fd, buffer); len += r; if (r === 0) break; buffers.push(buffer.subarray(0, r)); } buffer = Buffer.concat(buffers); } else { buffer = Buffer.allocUnsafe(st.size); while (true) { const r = readSync(fd, len ? buffer.subarray(len) : buffer); len += r; if (r === 0 || len === buffer.byteLength) break; } if (len !== buffer.byteLength) buffer = buffer.subarray(0, len); } if (encoding !== "buffer") buffer = buffer.toString(encoding); return buffer; } finally { if (fd !== -1) closeSync(fd); } } async function writeFile(filepath, data, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; if (typeof data === "string") data = Buffer.from(data, opts.encoding); let fd = -1; let len = 0; let err = null; try { fd = await open(filepath, opts.flag || "w", opts.mode || 438); while (true) { len += await write(fd, len ? data.subarray(len) : data); if (len === data.byteLength) break; } } catch (e) { err = e; } finally { if (fd !== -1) await close(fd); } return done(err, len, cb); } function writeFileSync(filepath, data, opts) { if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; if (typeof data === "string") data = Buffer.from(data, opts.encoding); let fd = -1; try { fd = openSync(filepath, opts.flag || "w", opts.mode || 438); let len = 0; while (true) { len += writeSync(fd, len ? data.subarray(len) : data); if (len === data.byteLength) break; } } finally { if (fd !== -1) closeSync(fd); } } function appendFile(filepath, data, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; if (!opts.flag) opts = { ...opts, flag: "a" }; return writeFile(filepath, data, opts, cb); } function appendFileSync(filepath, data, opts) { if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; if (!opts.flag) opts = { ...opts, flag: "a" }; return writeFileSync(filepath, data, opts); } function watch(filepath, opts, cb) { if (typeof opts === "function") { cb = opts; opts = {}; } if (typeof opts === "string") opts = { encoding: opts }; else if (!opts) opts = {}; filepath = toNamespacedPath(filepath); return new Watcher(filepath, opts, cb); } var Stats = class { constructor(dev, mode, nlink, uid, gid, rdev, blksize, ino, size, blocks, atimeMs, mtimeMs, ctimeMs, birthtimeMs) { this.dev = dev; this.mode = mode; this.nlink = nlink; this.uid = uid; this.gid = gid; this.rdev = rdev; this.blksize = blksize; this.ino = ino; this.size = size; this.blocks = blocks; this.atimeMs = atimeMs; this.mtimeMs = mtimeMs; this.ctimeMs = ctimeMs; this.birthtimeMs = birthtimeMs; this.atime = new Date(atimeMs); this.mtime = new Date(mtimeMs); this.ctime = new Date(ctimeMs); this.birthtime = new Date(birthtimeMs); } isDirectory() { return (this.mode & constants.S_IFMT) === constants.S_IFDIR; } isFile() { return (this.mode & constants.S_IFMT) === constants.S_IFREG; } isBlockDevice() { return (this.mode & constants.S_IFMT) === constants.S_IFBLK; } isCharacterDevice() { return (this.mode & constants.S_IFMT) === constants.S_IFCHR; } isFIFO() { return (this.mode & constants.S_IFMT) === constants.S_IFIFO; } isSymbolicLink() { return (this.mode & constants.S_IFMT) === constants.S_IFLNK; } isSocket() { return (this.mode & constants.S_IFMT) === constants.S_IFSOCK; } }; var Dir = class { constructor(path2, handle, opts = {}) { const { encoding = "utf8", bufferSize = 32 } = opts; this.path = path2; this._encoding = encoding; this._capacity = bufferSize; this._buffer = new FIFO(); this._ended = false; this._handle = handle; } async read(cb) { if (this._buffer.length) return ok(this._buffer.shift(), cb); if (this._ended) return ok(null, cb); const req = FileRequest.borrow(); let entries; let err = null; try { req.retain(binding.readdir(req.handle, this._handle, this._capacity)); await req; entries = binding.requestResultDirents(req.handle); } catch (e) { err = new FileError(e.message, { operation: "readdir", code: e.code, path: this.path }); } finally { req.return(); } if (err) return fail(err, cb); if (entries.length === 0) { this._ended = true; return ok(null, cb); } for (const entry of entries) { let name = Buffer.from(entry.name); if (this._encoding !== "buffer") name = name.toString(this._encoding); this._buffer.push(new Dirent(this.path, name, entry.type)); } return ok(this._buffer.shift(), cb); } readSync() { if (this._buffer.length) return this._buffer.shift(); if (this._ended) return null; const req = FileRequest.borrow(); let entries; try { req.retain(binding.readdirSync(req.handle, this._handle, this._capacity)); entries = binding.requestResultDirents(req.handle); } catch (e) { throw new FileError(e.message, { operation: "readdir", code: e.code, path: this.path }); } finally { req.return(); } if (entries.length === 0) { this._ended = true; return null; } for (const entry of entries) { let name = Buffer.from(entry.name); if (this._encoding !== "buffer") name = name.toString(this._encoding); this._buffer.push(new Dirent(this.path, name, entry.type)); } return this._buffer.shift(); } async close(cb) { const req = FileRequest.borrow(); let err = null; try { binding.closedir(req.handle, this._handle); await req; } catch (e) { err = new FileError(e.message, { operation: "closedir", code: e.code, path: this.path }); } finally { req.return(); } this._handle = null; return done(err, cb); } closeSync() { const req = FileRequest.borrow(); try { binding.closedirSync(req.handle, this._handle); } catch (e) { throw new FileError(e.message, { operation: "closedir", code: e.code, path: this.path }); } finally { req.return(); } this._handle = null; } [Symbol.dispose]() { this.closeSync(); } async [Symbol.asyncDispose]() { await this.close(); } *[Symbol.iterator]() { while (true) { const entry = this.readSync(); if (entry === null) break; yield entry; } this.closeSync(); } async *[Symbol.asyncIterator]() { while (true) { const entry = await this.read(); if (entry === null) break; yield entry; } await this.close(); } }; var Dirent = class { constructor(parentPath, name, type) { this.parentPath = parentPath; this.name = name; this.type = type; } isFile() { return this.type === constants.UV_DIRENT_FILE; } isDirectory() { return this.type === constants.UV_DIRENT_DIR; } isSymbolicLink() { return this.type === constants.UV_DIRENT_LINK; } isFIFO() { return this.type === constants.UV_DIRENT_FIFO; } isSocket() { return this.type === constants.UV_DIRENT_SOCKET; } isCharacterDevice() { return this.type === constants.UV_DIRENT_CHAR; } isBlockDevice() { return this.type === constants.UV_DIRENT_BLOCK; } }; var FileReadStream = class extends Readable { constructor(path2, opts = {}) { const { eagerOpen = true } = opts; super({ eagerOpen, ...opts }); this.path = path2; this.fd = typeof opts.fd === "number" ? opts.fd : -1; this.flags = opts.flags || "r"; this.mode = opts.mode || 438; this._offset = opts.start || 0; this._missing = 0; if (opts.length) { this._missing = opts.length; } else if (typeof opts.end === "number") { this._missing = opts.end - this._offset + 1; } else { this._missing = -1; } } async _open(cb) { let err; if (this.fd === -1) { err = null; try { this.fd = await open(this.path, this.flags, this.mode); } catch (e) { err = e; } if (err) return cb(err); } let st; err = null; try { st = await fstat(this.fd); } catch (e) { err = e; } if (err) return cb(err); if (this._missing === -1) this._missing = st.size; if (st.size < this._offset) { this._offset = st.size; this._missing = 0; } else if (st.size < this._offset + this._missing) { this._missing = st.size - this._offset; } cb(null); } async _read(size) { if (this._missing <= 0) return this.push(null); const data = Buffer.allocUnsafe(Math.min(this._missing, size)); let len; let err = null; try { len = await read(this.fd, data, 0, data.byteLength, this._offset); } catch (e) { err = e; } if (err) return this.destroy(err); if (len === 0) return this.push(null); if (this._missing < len) len = this._missing; this._missing -= len; this._offset += len; this.push(data.subarray(0, len)); } async _destroy(err, cb) { if (this.fd === -1) return cb(err); try { await close(this.fd); } catch (e) { err = err || e; } cb(err); } }; var FileWriteStream = class extends Writable { constructor(path2, opts = {}) { const { eagerOpen = true } = opts; super({ eagerOpen, ...opts }); this.path = path2; this.fd = typeof opts.fd === "number" ? opts.fd : -1; this.flags = opts.flags || "w"; this.mode = opts.mode || 438; } async _open(cb) { if (this.fd !== -1) return cb(null); let err = null; try { this.fd = await open(this.path, this.flags, this.mode); } catch (e) { err = e; } cb(err); } async _writev(batch, cb) { let err = null; try { await writev( this.fd, batch.map(({ chunk }) => chunk) ); } catch (e) { err = e; } cb(err); } async _destroy(err, cb) { if (this.fd === -1) return cb(err); try { await close(this.fd); } catch (e) { err = err || e; } cb(err); } }; var Watcher = class extends EventEmitter { constructor(path2, opts, onchange) { if (typeof opts === "function") { onchange = opts; opts = {}; } if (!opts) opts = {}; const { persistent = true, recursive = false, encoding = "utf8" } = opts; super(); this._closed = false; this._encoding = encoding; this._handle = binding.watcherInit(path2, recursive, this, this._onevent, this._onclose); if (!persistent) this.unref(); if (onchange) this.on("change", onchange); } close() { if (this._closed) return; this._closed = true; binding.watcherClose(this._handle); } ref() { if (this._handle) binding.watcherRef(this._handle); return this; } unref() { if (this._handle) binding.watcherUnref(this._handle); return this; } [Symbol.asyncIterator]() { const buffer = []; let done2 = false; let error = null; let next = null; this.on("change", (eventType, filename) => { if (next) { next.resolve({ done: false, value: { eventType, filename } }); next = null; } else { buffer.push({ eventType, filename }); } }).on("error", (err) => { done2 = true; error = err; if (next) { next.reject(error); next = null; } }).on("close", () => { done2 = true; if (next) { next.resolve({ done: done2 }); next = null; } }); return { next: () => new Promise((resolve, reject) => { if (error) return reject(error); if (buffer.length) return resolve({ done: false, value: buffer.shift() }); if (done2) return resolve({ done: done2 }); next = { resolve, reject }; }) }; } _onevent(err, events, filename) { if (err) { this.close(); this.emit("error", err); } else { const path2 = this._encoding === "buffer" ? Buffer.from(filename) : Buffer.from(filename).toString(this._encoding); if (events & binding.UV_RENAME) { this.emit("change", "rename", path2); } if (events & binding.UV_CHANGE) { this.emit("change", "change", path2); } } } _onclose() { this._handle = null; this.emit("close"); } }; exports.access = access; exports.appendFile = appendFile; exports.chmod = chmod; exports.close = close; exports.copyFile = copyFile; exports.cp = cp; exports.exists = exists; exports.fchmod = fchmod; exports.fstat = fstat; exports.ftruncate = ftruncate; exports.lstat = lstat; exports.mkdir = mkdir; exports.open = open; exports.opendir = opendir; exports.read = read; exports.readFile = readFile; exports.readdir = readdir; exports.readlink = readlink; exports.readv = readv; exports.realpath = realpath; exports.rename = rename; exports.rm = rm; exports.rmdir = rmdir; exports.stat = stat; exports.symlink = symlink; exports.unlink = unlink; exports.utimes = utimes; exports.watch = watch; exports.write = write; exports.writeFile = writeFile; exports.writev = writev; exports.accessSync = accessSync; exports.appendFileSync = appendFileSync; exports.chmodSync = chmodSync; exports.closeSync = closeSync; exports.copyFileSync = copyFileSync; exports.cpSync = cpSync; exports.existsSync = existsSync; exports.fchmodSync = fchmodSync; exports.fstatSync = fstatSync; exports.ftruncateSync = ftruncateSync; exports.lstatSync = lstatSync; exports.mkdirSync = mkdirSync; exports.openSync = openSync; exports.opendirSync = opendirSync; exports.readFileSync = readFileSync; exports.readSync = readSync; exports.readdirSync = readdirSync; exports.readlinkSync = readlinkSync; exports.readvSync = readvSync; exports.realpathSync = realpathSync; exports.renameSync = renameSync; exports.rmSync = rmSync; exports.rmdirSync = rmdirSync; exports.statSync = statSync; exports.symlinkSync = symlinkSync; exports.unlinkSync = unlinkSync; exports.utimesSync = utimesSync; exports.writeFileSync = writeFileSync; exports.writeSync = writeSync; exports.writevSync = writevSync; exports.promises = require_promises(); exports.Stats = Stats; exports.Dir = Dir; exports.Dirent = Dirent; exports.Watcher = Watcher; exports.ReadStream = FileReadStream; exports.createReadStream = function createReadStream(path2, opts) { return new FileReadStream(path2, opts); }; exports.WriteStream = FileWriteStream; exports.createWriteStream = function createWriteStream(path2, opts) { return new FileWriteStream(path2, opts); }; function toNamespacedPath(filepath) { if (typeof filepath !== "string") { if (isURL(filepath)) filepath = fileURLToPath(filepath); else filepath = filepath.toString(); } return path.toNamespacedPath(filepath); } function toFlags(flags) { switch (flags) { case "r": return constants.O_RDONLY; case "rs": // Fall through. case "sr": return constants.O_RDONLY | constants.O_SYNC; case "r+": return constants.O_RDWR; case "rs+": // Fall through. case "sr+": return constants.O_RDWR | constants.O_SYNC; case "w": return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY; case "wx": // Fall through. case "xw": return constants.O_TRUNC | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL; case "w+": return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR; case "wx+": // Fall through. case "xw+": return constants.O_TRUNC | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL; case "a": return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY; case "ax": // Fall through. case "xa": return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_EXCL; case "as": // Fall through. case "sa": return constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_SYNC; case "a+": return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR; case "ax+": // Fall through. case "xa+": return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_EXCL; case "as+": // Fall through. case "sa+": return constants.O_APPEND | constants.O_CREAT | constants.O_RDWR | constants.O_SYNC; default: return 0; } } function toMode(mode) { return parseInt(mode, 8); } } }); // ../bare-os-openssh/vendor/bare-node-shims/bare-node-fs/index.js var require_bare_node_fs = __commonJS({ "../bare-os-openssh/vendor/bare-node-shims/bare-node-fs/index.js"(exports, module) { module.exports = require_bare_fs(); } }); // ../../node_modules/bare-prom-client/lib/metrics/osMemoryHeapLinux.js var require_osMemoryHeapLinux = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/osMemoryHeapLinux.js"(exports, module) { "use strict"; var Gauge = require_gauge(); var fs = require_bare_node_fs(); var values = ["VmSize", "VmRSS", "VmData"]; var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; var PROCESS_VIRTUAL_MEMORY = "process_virtual_memory_bytes"; var PROCESS_HEAP = "process_heap_bytes"; function structureOutput(input) { return input.split("\n").reduce((acc, string) => { if (!values.some((value2) => string.startsWith(value2))) { return acc; } const split = string.split(":"); let value = split[1].trim(); value = value.substr(0, value.length - 3); value = Number(value) * 1024; acc[split[0]] = value; return acc; }, {}); } module.exports = (registry, config = {}) => { const registers = registry ? [registry] : void 0; const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); const residentMemGauge = new Gauge({ name: namePrefix + PROCESS_RESIDENT_MEMORY, help: "Resident memory size in bytes.", registers, labelNames, // Use this one metric's `collect` to set all metrics' values. collect() { try { const stat = fs.readFileSync("/proc/self/status", "utf8"); const structuredOutput = structureOutput(stat); residentMemGauge.set(labels, structuredOutput.VmRSS); virtualMemGauge.set(labels, structuredOutput.VmSize); heapSizeMemGauge.set(labels, structuredOutput.VmData); } catch { } } }); const virtualMemGauge = new Gauge({ name: namePrefix + PROCESS_VIRTUAL_MEMORY, help: "Virtual memory size in bytes.", registers, labelNames }); const heapSizeMemGauge = new Gauge({ name: namePrefix + PROCESS_HEAP, help: "Process heap size in bytes.", registers, labelNames }); }; module.exports.metricNames = [ PROCESS_RESIDENT_MEMORY, PROCESS_VIRTUAL_MEMORY, PROCESS_HEAP ]; } }); // ../../node_modules/bare-prom-client/lib/metrics/helpers/safeMemoryUsage.js var require_safeMemoryUsage = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/helpers/safeMemoryUsage.js"(exports, module) { "use strict"; var process = __require("process"); function safeMemoryUsage() { try { return process.memoryUsage(); } catch { return; } } module.exports = safeMemoryUsage; } }); // ../../node_modules/bare-prom-client/lib/metrics/osMemoryHeap.js var require_osMemoryHeap = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/osMemoryHeap.js"(exports, module) { "use strict"; var process = __require("process"); var Gauge = require_gauge(); var linuxVariant = require_osMemoryHeapLinux(); var safeMemoryUsage = require_safeMemoryUsage(); var PROCESS_RESIDENT_MEMORY = "process_resident_memory_bytes"; function notLinuxVariant(registry, config = {}) { const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); new Gauge({ name: namePrefix + PROCESS_RESIDENT_MEMORY, help: "Resident memory size in bytes.", registers: registry ? [registry] : void 0, labelNames, collect() { const memUsage = safeMemoryUsage(); if (memUsage) { this.set(labels, memUsage.rss); } } }); } module.exports = (registry, config) => process.platform === "linux" ? linuxVariant(registry, config) : notLinuxVariant(registry, config); module.exports.metricNames = process.platform === "linux" ? linuxVariant.metricNames : [PROCESS_RESIDENT_MEMORY]; } }); // ../../node_modules/bare-prom-client/lib/metrics/processOpenFileDescriptors.js var require_processOpenFileDescriptors = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/processOpenFileDescriptors.js"(exports, module) { "use strict"; var Gauge = require_gauge(); var fs = require_bare_node_fs(); var process = __require("process"); var PROCESS_OPEN_FDS = "process_open_fds"; module.exports = (registry, config = {}) => { if (process.platform !== "linux") { return; } const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); new Gauge({ name: namePrefix + PROCESS_OPEN_FDS, help: "Number of open file descriptors.", registers: registry ? [registry] : void 0, labelNames, collect() { try { const fds = fs.readdirSync("/proc/self/fd"); this.set(labels, fds.length - 1); } catch { } } }); }; module.exports.metricNames = [PROCESS_OPEN_FDS]; } }); // ../../node_modules/bare-prom-client/lib/metrics/processMaxFileDescriptors.js var require_processMaxFileDescriptors = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/processMaxFileDescriptors.js"(exports, module) { "use strict"; var Gauge = require_gauge(); var fs = require_bare_node_fs(); var PROCESS_MAX_FDS = "process_max_fds"; var maxFds; module.exports = (registry, config = {}) => { if (maxFds === void 0) { try { const limits = fs.readFileSync("/proc/self/limits", "utf8"); const lines = limits.split("\n"); for (const line of lines) { if (line.startsWith("Max open files")) { const parts = line.split(/ +/); maxFds = Number(parts[1]); break; } } } catch { return; } } if (maxFds === void 0) return; const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); new Gauge({ name: namePrefix + PROCESS_MAX_FDS, help: "Maximum number of open file descriptors.", registers: registry ? [registry] : void 0, labelNames, collect() { if (maxFds !== void 0) this.set(labels, maxFds); } }); }; module.exports.metricNames = [PROCESS_MAX_FDS]; } }); // ../../node_modules/bare-prom-client/lib/metrics/eventLoopLag.js var require_eventLoopLag = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/eventLoopLag.js"(exports, module) { "use strict"; var process = __require("process"); var Gauge = require_gauge(); var perf_hooks; try { perf_hooks = __require("perf_hooks"); } catch { } var NODEJS_EVENTLOOP_LAG = "nodejs_eventloop_lag_seconds"; var NODEJS_EVENTLOOP_LAG_MIN = "nodejs_eventloop_lag_min_seconds"; var NODEJS_EVENTLOOP_LAG_MAX = "nodejs_eventloop_lag_max_seconds"; var NODEJS_EVENTLOOP_LAG_MEAN = "nodejs_eventloop_lag_mean_seconds"; var NODEJS_EVENTLOOP_LAG_STDDEV = "nodejs_eventloop_lag_stddev_seconds"; var NODEJS_EVENTLOOP_LAG_P50 = "nodejs_eventloop_lag_p50_seconds"; var NODEJS_EVENTLOOP_LAG_P90 = "nodejs_eventloop_lag_p90_seconds"; var NODEJS_EVENTLOOP_LAG_P99 = "nodejs_eventloop_lag_p99_seconds"; function reportEventloopLag(start, gauge, labels) { const delta = process.hrtime(start); const nanosec = delta[0] * 1e9 + delta[1]; const seconds = nanosec / 1e9; gauge.set(labels, seconds); } module.exports = (registry, config = {}) => { const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); const registers = registry ? [registry] : void 0; let collect = () => { const start = process.hrtime(); setImmediate(reportEventloopLag, start, lag, labels); }; if (perf_hooks && perf_hooks.monitorEventLoopDelay) { try { const histogram = perf_hooks.monitorEventLoopDelay({ resolution: config.eventLoopMonitoringPrecision }); histogram.enable(); collect = () => { const start = process.hrtime(); setImmediate(reportEventloopLag, start, lag, labels); lagMin.set(labels, histogram.min / 1e9); lagMax.set(labels, histogram.max / 1e9); lagMean.set(labels, histogram.mean / 1e9); lagStddev.set(labels, histogram.stddev / 1e9); lagP50.set(labels, histogram.percentile(50) / 1e9); lagP90.set(labels, histogram.percentile(90) / 1e9); lagP99.set(labels, histogram.percentile(99) / 1e9); histogram.reset(); }; } catch (e) { if (e.code === "ERR_NOT_IMPLEMENTED") { return; } throw e; } } const lag = new Gauge({ name: namePrefix + NODEJS_EVENTLOOP_LAG, help: "Lag of event loop in seconds.", registers, labelNames, aggregator: "average", // Use this one metric's `collect` to set all metrics' values. collect }); const lagMin = new Gauge({ name: namePrefix + NODEJS_EVENTLOOP_LAG_MIN, help: "The minimum recorded event loop delay.", registers, labelNames, aggregator: "min" }); const lagMax = new Gauge({ name: namePrefix + NODEJS_EVENTLOOP_LAG_MAX, help: "The maximum recorded event loop delay.", registers, labelNames, aggregator: "max" }); const lagMean = new Gauge({ name: namePrefix + NODEJS_EVENTLOOP_LAG_MEAN, help: "The mean of the recorded event loop delays.", registers, labelNames, aggregator: "average" }); const lagStddev = new Gauge({ name: namePrefix + NODEJS_EVENTLOOP_LAG_STDDEV, help: "The standard deviation of the recorded event loop delays.", registers, labelNames, aggregator: "average" }); const lagP50 = new Gauge({ name: namePrefix + NODEJS_EVENTLOOP_LAG_P50, help: "The 50th percentile of the recorded event loop delays.", registers, labelNames, aggregator: "average" }); const lagP90 = new Gauge({ name: namePrefix + NODEJS_EVENTLOOP_LAG_P90, help: "The 90th percentile of the recorded event loop delays.", registers, labelNames, aggregator: "average" }); const lagP99 = new Gauge({ name: namePrefix + NODEJS_EVENTLOOP_LAG_P99, help: "The 99th percentile of the recorded event loop delays.", registers, labelNames, aggregator: "average" }); }; module.exports.metricNames = [ NODEJS_EVENTLOOP_LAG, NODEJS_EVENTLOOP_LAG_MIN, NODEJS_EVENTLOOP_LAG_MAX, NODEJS_EVENTLOOP_LAG_MEAN, NODEJS_EVENTLOOP_LAG_STDDEV, NODEJS_EVENTLOOP_LAG_P50, NODEJS_EVENTLOOP_LAG_P90, NODEJS_EVENTLOOP_LAG_P99 ]; } }); // ../../node_modules/bare-prom-client/lib/metrics/helpers/processMetricsHelpers.js var require_processMetricsHelpers = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/helpers/processMetricsHelpers.js"(exports, module) { "use strict"; function aggregateByObjectName(list) { const data = {}; for (let i = 0; i < list.length; i++) { const listElement = list[i]; if (!listElement || typeof listElement.constructor === "undefined") { continue; } if (Object.hasOwnProperty.call(data, listElement.constructor.name)) { data[listElement.constructor.name] += 1; } else { data[listElement.constructor.name] = 1; } } return data; } function updateMetrics(gauge, data, labels) { gauge.reset(); for (const key in data) { gauge.set(Object.assign({ type: key }, labels || {}), data[key]); } } module.exports = { aggregateByObjectName, updateMetrics }; } }); // ../../node_modules/bare-prom-client/lib/metrics/processHandles.js var require_processHandles = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/processHandles.js"(exports, module) { "use strict"; var process = __require("process"); var { aggregateByObjectName } = require_processMetricsHelpers(); var { updateMetrics } = require_processMetricsHelpers(); var Gauge = require_gauge(); var NODEJS_ACTIVE_HANDLES = "nodejs_active_handles"; var NODEJS_ACTIVE_HANDLES_TOTAL = "nodejs_active_handles_total"; module.exports = (registry, config = {}) => { if (typeof process._getActiveHandles !== "function") { return; } const registers = registry ? [registry] : void 0; const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); new Gauge({ name: namePrefix + NODEJS_ACTIVE_HANDLES, help: "Number of active libuv handles grouped by handle type. Every handle type is C++ class name.", labelNames: ["type", ...labelNames], registers, collect() { const handles = process._getActiveHandles(); updateMetrics(this, aggregateByObjectName(handles), labels); } }); new Gauge({ name: namePrefix + NODEJS_ACTIVE_HANDLES_TOTAL, help: "Total number of active handles.", registers, labelNames, collect() { const handles = process._getActiveHandles(); this.set(labels, handles.length); } }); }; module.exports.metricNames = [ NODEJS_ACTIVE_HANDLES, NODEJS_ACTIVE_HANDLES_TOTAL ]; } }); // ../../node_modules/bare-prom-client/lib/metrics/processRequests.js var require_processRequests = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/processRequests.js"(exports, module) { "use strict"; var process = __require("process"); var Gauge = require_gauge(); var { aggregateByObjectName } = require_processMetricsHelpers(); var { updateMetrics } = require_processMetricsHelpers(); var NODEJS_ACTIVE_REQUESTS = "nodejs_active_requests"; var NODEJS_ACTIVE_REQUESTS_TOTAL = "nodejs_active_requests_total"; module.exports = (registry, config = {}) => { if (typeof process._getActiveRequests !== "function") { return; } const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); new Gauge({ name: namePrefix + NODEJS_ACTIVE_REQUESTS, help: "Number of active libuv requests grouped by request type. Every request type is C++ class name.", labelNames: ["type", ...labelNames], registers: registry ? [registry] : void 0, collect() { const requests = process._getActiveRequests(); updateMetrics(this, aggregateByObjectName(requests), labels); } }); new Gauge({ name: namePrefix + NODEJS_ACTIVE_REQUESTS_TOTAL, help: "Total number of active requests.", registers: registry ? [registry] : void 0, labelNames, collect() { const requests = process._getActiveRequests(); this.set(labels, requests.length); } }); }; module.exports.metricNames = [ NODEJS_ACTIVE_REQUESTS, NODEJS_ACTIVE_REQUESTS_TOTAL ]; } }); // ../../node_modules/bare-prom-client/lib/metrics/processResources.js var require_processResources = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/processResources.js"(exports, module) { "use strict"; var process = __require("process"); var Gauge = require_gauge(); var { updateMetrics } = require_processMetricsHelpers(); var NODEJS_ACTIVE_RESOURCES = "nodejs_active_resources"; var NODEJS_ACTIVE_RESOURCES_TOTAL = "nodejs_active_resources_total"; module.exports = (registry, config = {}) => { if (typeof process.getActiveResourcesInfo !== "function") { return; } const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); new Gauge({ name: namePrefix + NODEJS_ACTIVE_RESOURCES, help: "Number of active resources that are currently keeping the event loop alive, grouped by async resource type.", labelNames: ["type", ...labelNames], registers: registry ? [registry] : void 0, collect() { const resources = process.getActiveResourcesInfo(); const data = {}; for (let i = 0; i < resources.length; i++) { const resource = resources[i]; if (Object.hasOwn(data, resource)) { data[resource] += 1; } else { data[resource] = 1; } } updateMetrics(this, data, labels); } }); new Gauge({ name: namePrefix + NODEJS_ACTIVE_RESOURCES_TOTAL, help: "Total number of active resources.", registers: registry ? [registry] : void 0, labelNames, collect() { const resources = process.getActiveResourcesInfo(); this.set(labels, resources.length); } }); }; module.exports.metricNames = [ NODEJS_ACTIVE_RESOURCES, NODEJS_ACTIVE_RESOURCES_TOTAL ]; } }); // ../../node_modules/bare-prom-client/lib/metrics/heapSizeAndUsed.js var require_heapSizeAndUsed = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/heapSizeAndUsed.js"(exports, module) { "use strict"; var process = __require("process"); var Gauge = require_gauge(); var safeMemoryUsage = require_safeMemoryUsage(); var NODEJS_HEAP_SIZE_TOTAL = "nodejs_heap_size_total_bytes"; var NODEJS_HEAP_SIZE_USED = "nodejs_heap_size_used_bytes"; var NODEJS_EXTERNAL_MEMORY = "nodejs_external_memory_bytes"; module.exports = (registry, config = {}) => { if (typeof process.memoryUsage !== "function") { return; } const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); const registers = registry ? [registry] : void 0; const namePrefix = config.prefix ? config.prefix : ""; const collect = () => { const memUsage = safeMemoryUsage(); if (memUsage) { heapSizeTotal.set(labels, memUsage.heapTotal); heapSizeUsed.set(labels, memUsage.heapUsed); if (memUsage.external !== void 0) { externalMemUsed.set(labels, memUsage.external); } } }; const heapSizeTotal = new Gauge({ name: namePrefix + NODEJS_HEAP_SIZE_TOTAL, help: "Process heap size from Node.js in bytes.", registers, labelNames, // Use this one metric's `collect` to set all metrics' values. collect }); const heapSizeUsed = new Gauge({ name: namePrefix + NODEJS_HEAP_SIZE_USED, help: "Process heap size used from Node.js in bytes.", registers, labelNames }); const externalMemUsed = new Gauge({ name: namePrefix + NODEJS_EXTERNAL_MEMORY, help: "Node.js external memory size in bytes.", registers, labelNames }); }; module.exports.metricNames = [ NODEJS_HEAP_SIZE_TOTAL, NODEJS_HEAP_SIZE_USED, NODEJS_EXTERNAL_MEMORY ]; } }); // ../../node_modules/bare-prom-client/lib/metrics/heapSpacesSizeAndUsed.js var require_heapSpacesSizeAndUsed = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/heapSpacesSizeAndUsed.js"(exports, module) { "use strict"; var Gauge = require_gauge(); var v8 = __require("v8"); var METRICS = ["total", "used", "available"]; var NODEJS_HEAP_SIZE = {}; METRICS.forEach((metricType) => { NODEJS_HEAP_SIZE[metricType] = `nodejs_heap_space_size_${metricType}_bytes`; }); module.exports = (registry, config = {}) => { try { v8.getHeapSpaceStatistics(); } catch (e) { if (e.code === "ERR_NOT_IMPLEMENTED") { return; } throw e; } const registers = registry ? [registry] : void 0; const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = ["space", ...Object.keys(labels)]; const gauges = {}; METRICS.forEach((metricType) => { gauges[metricType] = new Gauge({ name: namePrefix + NODEJS_HEAP_SIZE[metricType], help: `Process heap space size ${metricType} from Node.js in bytes.`, labelNames, registers }); }); gauges.total.collect = () => { for (const space of v8.getHeapSpaceStatistics()) { const spaceName = space.space_name.substr( 0, space.space_name.indexOf("_space") ); gauges.total.set({ space: spaceName, ...labels }, space.space_size); gauges.used.set({ space: spaceName, ...labels }, space.space_used_size); gauges.available.set( { space: spaceName, ...labels }, space.space_available_size ); } }; }; module.exports.metricNames = Object.values(NODEJS_HEAP_SIZE); } }); // ../../node_modules/bare-prom-client/lib/metrics/version.js var require_version = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/version.js"(exports, module) { "use strict"; var process = __require("process"); var Gauge = require_gauge(); var version = process.version; var versionSegments = version.slice(1).split(".").map(Number); var NODE_VERSION_INFO = "nodejs_version_info"; module.exports = (registry, config = {}) => { const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); new Gauge({ name: namePrefix + NODE_VERSION_INFO, help: "Node.js version info.", labelNames: ["version", "major", "minor", "patch", ...labelNames], registers: registry ? [registry] : void 0, aggregator: "first", collect() { this.labels( version, versionSegments[0], versionSegments[1], versionSegments[2], ...Object.values(labels) ).set(1); } }); }; module.exports.metricNames = [NODE_VERSION_INFO]; } }); // ../../node_modules/bare-prom-client/lib/metrics/gc.js var require_gc = __commonJS({ "../../node_modules/bare-prom-client/lib/metrics/gc.js"(exports, module) { "use strict"; var Histogram = require_histogram(); var perf_hooks; try { perf_hooks = __require("perf_hooks"); } catch { } var NODEJS_GC_DURATION_SECONDS = "nodejs_gc_duration_seconds"; var DEFAULT_GC_DURATION_BUCKETS = [1e-3, 0.01, 0.1, 1, 2, 5]; var kinds = []; if (perf_hooks && perf_hooks.constants) { kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_MAJOR] = "major"; kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_MINOR] = "minor"; kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_INCREMENTAL] = "incremental"; kinds[perf_hooks.constants.NODE_PERFORMANCE_GC_WEAKCB] = "weakcb"; } module.exports = (registry, config = {}) => { if (!perf_hooks) { return; } const namePrefix = config.prefix ? config.prefix : ""; const labels = config.labels ? config.labels : {}; const labelNames = Object.keys(labels); const buckets = config.gcDurationBuckets ? config.gcDurationBuckets : DEFAULT_GC_DURATION_BUCKETS; const gcHistogram = new Histogram({ name: namePrefix + NODEJS_GC_DURATION_SECONDS, help: "Garbage collection duration by kind, one of major, minor, incremental or weakcb.", labelNames: ["kind", ...labelNames], enableExemplars: false, buckets, registers: registry ? [registry] : void 0 }); const obs = new perf_hooks.PerformanceObserver((list) => { const entry = list.getEntries()[0]; const kind = entry.detail ? kinds[entry.detail.kind] : kinds[entry.kind]; gcHistogram.observe(Object.assign({ kind }, labels), entry.duration / 1e3); }); obs.observe({ entryTypes: ["gc"] }); }; module.exports.metricNames = [NODEJS_GC_DURATION_SECONDS]; } }); // ../../node_modules/bare-prom-client/lib/defaultMetrics.js var require_defaultMetrics = __commonJS({ "../../node_modules/bare-prom-client/lib/defaultMetrics.js"(exports, module) { "use strict"; var process = __require("process"); var { isObject } = require_util(); var processCpuTotal = require_processCpuTotal(); var processStartTime = require_processStartTime(); var osMemoryHeap = require_osMemoryHeap(); var processOpenFileDescriptors = require_processOpenFileDescriptors(); var processMaxFileDescriptors = require_processMaxFileDescriptors(); var eventLoopLag = require_eventLoopLag(); var processHandles = require_processHandles(); var processRequests = require_processRequests(); var processResources = require_processResources(); var heapSizeAndUsed = require_heapSizeAndUsed(); var heapSpacesSizeAndUsed = require_heapSpacesSizeAndUsed(); var version = require_version(); var gc = require_gc(); var metrics2 = { processCpuTotal, processStartTime, osMemoryHeap, processOpenFileDescriptors, processMaxFileDescriptors, eventLoopLag, ...typeof process.getActiveResourcesInfo === "function" ? { processResources } : {}, processHandles, processRequests, heapSizeAndUsed, heapSpacesSizeAndUsed, version, gc }; var metricsList = Object.keys(metrics2); module.exports = function collectDefaultMetrics(config) { if (config !== null && config !== void 0 && !isObject(config)) { throw new TypeError("config must be null, undefined, or an object"); } config = { eventLoopMonitoringPrecision: 10, ...config }; for (const metric of Object.values(metrics2)) { metric(config.register, config); } }; module.exports.metricsList = metricsList; } }); // ../../node_modules/bare-prom-client/lib/metricAggregators.js var require_metricAggregators = __commonJS({ "../../node_modules/bare-prom-client/lib/metricAggregators.js"(exports) { "use strict"; var { Grouper, hashObject } = require_util(); function AggregatorFactory(aggregatorFn) { return (metrics2) => { if (metrics2.length === 0) return; const result = { help: metrics2[0].help, name: metrics2[0].name, type: metrics2[0].type, values: [], aggregator: metrics2[0].aggregator }; const byLabels = new Grouper(); metrics2.forEach((metric) => { metric.values.forEach((value) => { const key = hashObject(value.labels); byLabels.add(`${value.metricName}_${key}`, value); }); }); byLabels.forEach((values) => { if (values.length === 0) return; const valObj = { value: aggregatorFn(values), labels: values[0].labels }; if (values[0].metricName) { valObj.metricName = values[0].metricName; } result.values.push(valObj); }); return result; }; } exports.AggregatorFactory = AggregatorFactory; exports.aggregators = { /** * @return The sum of values. */ sum: AggregatorFactory((v) => v.reduce((p, c) => p + c.value, 0)), /** * @return The first value. */ first: AggregatorFactory((v) => v[0].value), /** * @return {undefined} Undefined; omits the metric. */ omit: () => { }, /** * @return The arithmetic mean of the values. */ average: AggregatorFactory( (v) => v.reduce((p, c) => p + c.value, 0) / v.length ), /** * @return The minimum of the values. */ min: AggregatorFactory( (v) => v.reduce((p, c) => Math.min(p, c.value), Infinity) ), /** * @return The maximum of the values. */ max: AggregatorFactory( (v) => v.reduce((p, c) => Math.max(p, c.value), -Infinity) ) }; } }); // ../../node_modules/bare-prom-client/lib/cluster.js var require_cluster = __commonJS({ "../../node_modules/bare-prom-client/lib/cluster.js"(exports, module) { "use strict"; var process = __require("process"); var Registry = require_registry(); var { Grouper } = require_util(); var { aggregators } = require_metricAggregators(); var cluster = () => { const data = __require("cluster"); cluster = () => data; return data; }; var GET_METRICS_REQ = "prom-client:getMetricsReq"; var GET_METRICS_RES = "prom-client:getMetricsRes"; var registries = [Registry.globalRegistry]; var requestCtr = 0; var listenersAdded = false; var requests = /* @__PURE__ */ new Map(); var AggregatorRegistry = class extends Registry { constructor(regContentType = Registry.PROMETHEUS_CONTENT_TYPE) { super(regContentType); addListeners(); } /** * Gets aggregated metrics for all workers. The optional callback and * returned Promise resolve with the same value; either may be used. * @return {Promise} Promise that resolves with the aggregated * metrics. */ clusterMetrics() { const requestId = requestCtr++; return new Promise((resolve, reject) => { let settled = false; function done(err, result) { if (settled) return; settled = true; if (err) reject(err); else resolve(result); } const request = { responses: [], pending: 0, done, errorTimeout: setTimeout(() => { const err = new Error("Operation timed out."); request.done(err); }, 5e3) }; requests.set(requestId, request); const message = { type: GET_METRICS_REQ, requestId }; for (const id in cluster().workers) { if (cluster().workers[id].isConnected()) { cluster().workers[id].send(message); request.pending++; } } if (request.pending === 0) { clearTimeout(request.errorTimeout); process.nextTick(() => done(null, "")); } }); } get contentType() { return super.contentType; } /** * Creates a new Registry instance from an array of metrics that were * created by `registry.getMetricsAsJSON()`. Metrics are aggregated using * the method specified by their `aggregator` property, or by summation if * `aggregator` is undefined. * @param {Array} metricsArr Array of metrics, each of which created by * `registry.getMetricsAsJSON()`. * @param {string} registryType content type of the new registry. Defaults * to PROMETHEUS_CONTENT_TYPE. * @return {Registry} aggregated registry. */ static aggregate(metricsArr, registryType = Registry.PROMETHEUS_CONTENT_TYPE) { const aggregatedRegistry = new Registry(); const metricsByName = new Grouper(); aggregatedRegistry.setContentType(registryType); metricsArr.forEach((metrics2) => { metrics2.forEach((metric) => { metricsByName.add(metric.name, metric); }); }); metricsByName.forEach((metrics2) => { const aggregatorName = metrics2[0].aggregator; const aggregatorFn = aggregators[aggregatorName]; if (typeof aggregatorFn !== "function") { throw new Error(`'${aggregatorName}' is not a defined aggregator.`); } const aggregatedMetric = aggregatorFn(metrics2); if (aggregatedMetric) { const aggregatedMetricWrapper = Object.assign( { get: () => aggregatedMetric }, aggregatedMetric ); aggregatedRegistry.registerMetric(aggregatedMetricWrapper); } }); return aggregatedRegistry; } /** * Sets the registry or registries to be aggregated. Call from workers to * use a registry/registries other than the default global registry. * @param {Array|Registry} regs Registry or registries to be * aggregated. * @return {void} */ static setRegistries(regs) { if (!Array.isArray(regs)) regs = [regs]; regs.forEach((reg) => { if (!(reg instanceof Registry)) { throw new TypeError(`Expected Registry, got ${typeof reg}`); } }); registries = regs; } }; function addListeners() { if (listenersAdded) return; listenersAdded = true; if (cluster().isMaster) { cluster().on("message", (worker, message) => { if (message.type === GET_METRICS_RES) { const request = requests.get(message.requestId); if (message.error) { request.done(new Error(message.error)); return; } message.metrics.forEach((registry) => request.responses.push(registry)); request.pending--; if (request.pending === 0) { requests.delete(message.requestId); clearTimeout(request.errorTimeout); const registry = AggregatorRegistry.aggregate(request.responses); const promString = registry.metrics(); request.done(null, promString); } } }); } if (cluster().isWorker) { process.on("message", (message) => { if (message.type === GET_METRICS_REQ) { Promise.all(registries.map((r) => r.getMetricsAsJSON())).then((metrics2) => { process.send({ type: GET_METRICS_RES, requestId: message.requestId, metrics: metrics2 }); }).catch((error) => { process.send({ type: GET_METRICS_RES, requestId: message.requestId, error: error.message }); }); } }); } } module.exports = AggregatorRegistry; } }); // ../../node_modules/bare-prom-client/index.js var require_bare_prom_client = __commonJS({ "../../node_modules/bare-prom-client/index.js"(exports) { "use strict"; exports.register = require_registry().globalRegistry; exports.Registry = require_registry(); Object.defineProperty(exports, "contentType", { configurable: false, enumerable: true, get() { return exports.register.contentType; }, set(value) { exports.register.setContentType(value); } }); exports.prometheusContentType = exports.Registry.PROMETHEUS_CONTENT_TYPE; exports.openMetricsContentType = exports.Registry.OPENMETRICS_CONTENT_TYPE; exports.validateMetricName = require_validation().validateMetricName; exports.Counter = require_counter(); exports.Gauge = require_gauge(); exports.Histogram = require_histogram(); exports.Summary = require_summary(); exports.Pushgateway = require_pushgateway(); exports.linearBuckets = require_bucketGenerators().linearBuckets; exports.exponentialBuckets = require_bucketGenerators().exponentialBuckets; exports.collectDefaultMetrics = require_defaultMetrics(); exports.aggregators = require_metricAggregators().aggregators; exports.AggregatorRegistry = require_cluster(); } }); // ../../bare-lib-entry-barePromClient.js var bare_lib_entry_barePromClient_exports = {}; __export(bare_lib_entry_barePromClient_exports, { default: () => bare_lib_entry_barePromClient_default }); var import_bare_prom_client = __toESM(require_bare_prom_client()); var bare_lib_entry_barePromClient_default = import_bare_prom_client.default; return __toCommonJS(bare_lib_entry_barePromClient_exports); })(); ;(function(){var g=globalThis;var s="__bare_os_stdlib__";g[s]=g[s]||{};var e=typeof __bare_os_bundle_exports__!=="undefined"?__bare_os_bundle_exports__:void 0;var v=e!=null&&typeof e==="object"&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e;g[s]["barePromClient"]=v;})();