import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
  require_ci_info,
  require_index_node,
  wixCliCliCommand,
  wixCliCliCommandStatus
} from "./chunk-IVQPYJ5M.js";
import {
  __assign,
  __awaiter,
  __generator,
  init_tslib_es6
} from "./chunk-RPTAJN5Y.js";
import {
  readUserConfig
} from "./chunk-DGJS6KZB.js";
import {
  getTestOverrides
} from "./chunk-XZUGLEBK.js";
import {
  isCliError,
  isCliSystemError
} from "./chunk-WGV2XQSB.js";
import {
  __commonJS,
  __toESM,
  init_esm_shims
} from "./chunk-EXLZF52D.js";

// ../../node_modules/is-ci/index.js
var require_is_ci = __commonJS({
  "../../node_modules/is-ci/index.js"(exports, module) {
    "use strict";
    init_esm_shims();
    module.exports = require_ci_info().isCI;
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/assert.js
var require_assert = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/assert.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
      return typeof obj;
    } : function(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
    function _classCallCheck(instance, Constructor) {
      if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }
    function _possibleConstructorReturn(self, call) {
      if (!self) {
        throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      }
      return call && (typeof call === "object" || typeof call === "function") ? call : self;
    }
    function _inherits(subClass, superClass) {
      if (typeof superClass !== "function" && superClass !== null) {
        throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
      }
      subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } });
      if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
    }
    var AssertionError = function(_Error) {
      _inherits(AssertionError2, _Error);
      function AssertionError2(message) {
        _classCallCheck(this, AssertionError2);
        var _this = _possibleConstructorReturn(this, (AssertionError2.__proto__ || Object.getPrototypeOf(AssertionError2)).call(this, message));
        _this.name = _this.constructor.name;
        return _this;
      }
      return AssertionError2;
    }(Error);
    function assertDefined(target, message) {
      if (target === void 0) {
        throw new AssertionError(message);
      }
    }
    function assertObject(target, message) {
      if (target !== void 0 && ((typeof target === "undefined" ? "undefined" : _typeof(target)) !== "object" || Array.isArray(target) || target === null)) {
        throw new AssertionError(message);
      }
    }
    function assertOk(target, message) {
      if (!target) {
        throw new AssertionError(message);
      }
    }
    function assertFunc(target, message) {
      if (target !== void 0 && typeof target !== "function") {
        throw new AssertionError(message);
      }
    }
    function assertBoolean(target, message) {
      if (target !== void 0 && typeof target !== "boolean") {
        throw new AssertionError(message);
      }
    }
    function assertNumber(target, message) {
      if (target !== void 0 && typeof target !== "number") {
        throw new AssertionError(message);
      }
    }
    function assertArray(target, message) {
      if (typeof Array.isArray === "function") {
        if (!Array.isArray(target)) {
          throw new AssertionError(message);
        }
      } else if (Object.prototype.toString.call(target) !== "[object Array]") {
        throw new AssertionError(message);
      }
    }
    module.exports.defined = assertDefined;
    module.exports.object = assertObject;
    module.exports.ok = assertOk;
    module.exports.func = assertFunc;
    module.exports.boolean = assertBoolean;
    module.exports.number = assertNumber;
    module.exports.array = assertArray;
    module.exports.AssertionError = AssertionError;
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/utils/collections.js
var require_collections = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/utils/collections.js"(exports, module) {
    "use strict";
    init_esm_shims();
    module.exports.mapValues = function(collection, iteratee) {
      if (!collection) {
        return {};
      }
      return Object.keys(collection).reduce(function(acc, key) {
        acc[key] = iteratee(collection[key], key, collection);
        return acc;
      }, {});
    };
    module.exports.filterValues = function(collection, iteratee) {
      if (!collection) {
        return {};
      }
      return Object.keys(collection).reduce(function(acc, key) {
        var keep = iteratee(collection[key], key, collection);
        if (keep) {
          acc[key] = collection[key];
        }
        return acc;
      }, {});
    };
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/utils/promise.js
var require_promise = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/utils/promise.js"(exports, module) {
    "use strict";
    init_esm_shims();
    module.exports.timedPromise = function(promise, _ref) {
      var message = _ref.message, timeout = _ref.timeout;
      var timeoutPromise = new Promise(function(resolve, reject) {
        setTimeout(reject, timeout, message ? "Timeout: " + message : "Timeout");
      });
      return Promise.race([promise, timeoutPromise]);
    };
    module.exports.allAsObject = function(promiseObject) {
      var keys = Object.keys(promiseObject);
      return Promise.all(keys.map(function(key) {
        return promiseObject[key];
      })).then(function(resolved) {
        return resolved.reduce(function(acc, value, i) {
          acc[keys[i]] = value;
          return acc;
        }, {});
      });
    };
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/utils/log.js
var require_log = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/utils/log.js"(exports, module) {
    "use strict";
    init_esm_shims();
    module.exports = {
      error: function error() {
        if (console && console.error) {
          var _console;
          (_console = console).error.apply(_console, arguments);
        }
      }
    };
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/utils/debounce.js
var require_debounce = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/utils/debounce.js"(exports, module) {
    "use strict";
    init_esm_shims();
    function debounce(func, wait, immediate) {
      var timeout = void 0;
      return function() {
        var context = this;
        var args = arguments;
        var later = function later2() {
          timeout = null;
          if (!immediate) {
            func.apply(context, args);
          }
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) {
          func.apply(context, args);
        }
      };
    }
    module.exports = debounce;
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/utils/throttle.js
var require_throttle = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/utils/throttle.js"(exports, module) {
    "use strict";
    init_esm_shims();
    function throttle(func, wait) {
      var timeout = void 0;
      return function() {
        for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        if (!timeout) {
          timeout = setTimeout(function() {
            func.apply(void 0, args);
            timeout = null;
          }, wait);
        }
      };
    }
    module.exports = throttle;
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/utils/batch-queue.js
var require_batch_queue = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/utils/batch-queue.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var _createClass = /* @__PURE__ */ function() {
      function defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
          var descriptor = props[i];
          descriptor.enumerable = descriptor.enumerable || false;
          descriptor.configurable = true;
          if ("value" in descriptor) descriptor.writable = true;
          Object.defineProperty(target, descriptor.key, descriptor);
        }
      }
      return function(Constructor, protoProps, staticProps) {
        if (protoProps) defineProperties(Constructor.prototype, protoProps);
        if (staticProps) defineProperties(Constructor, staticProps);
        return Constructor;
      };
    }();
    var _slicedToArray = /* @__PURE__ */ function() {
      function sliceIterator(arr, i) {
        var _arr = [];
        var _n = true;
        var _d = false;
        var _e = void 0;
        try {
          for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
          }
        } catch (err) {
          _d = true;
          _e = err;
        } finally {
          try {
            if (!_n && _i["return"]) _i["return"]();
          } finally {
            if (_d) throw _e;
          }
        }
        return _arr;
      }
      return function(arr, i) {
        if (Array.isArray(arr)) {
          return arr;
        } else if (Symbol.iterator in Object(arr)) {
          return sliceIterator(arr, i);
        } else {
          throw new TypeError("Invalid attempt to destructure non-iterable instance");
        }
      };
    }();
    var _extends = Object.assign || function(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i];
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    };
    function _classCallCheck(instance, Constructor) {
      if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }
    var debounce = require_debounce();
    var throttle = require_throttle();
    var createEvent = function createEvent2(event, context, startTime) {
      return {
        dt: Date.now() - startTime,
        f: event,
        context
      };
    };
    var createBatch = function createBatch2(events, startTime) {
      return {
        dt: Date.now() - startTime,
        e: events,
        g: {}
      };
    };
    var optimizeBatch = function optimizeBatch2(batch) {
      var fieldCounts = {};
      var batchLen = batch.e.length;
      var events = batch.e.map(function(event) {
        var fields = Object.keys(event.f).map(function(field) {
          var value = event.f[field];
          var key = field + "|" + value;
          fieldCounts[key] = fieldCounts[key] || 0;
          fieldCounts[key]++;
          return [field, value, key];
        });
        return _extends({}, event, {
          f: fields
        });
      });
      var globalFields = {};
      events = events.map(function(event) {
        var fields = event.f.reduce(function(res, _ref) {
          var _ref2 = _slicedToArray(_ref, 3), field = _ref2[0], value = _ref2[1], key = _ref2[2];
          if (fieldCounts[key] === batchLen) {
            globalFields[field] = value;
          } else {
            res[field] = value;
          }
          return res;
        }, {});
        return _extends({}, event, {
          f: fields
        });
      });
      return _extends({}, batch, {
        e: events,
        g: globalFields
      });
    };
    var BatchQueue = function() {
      function BatchQueue2() {
        _classCallCheck(this, BatchQueue2);
        this._initilized = false;
      }
      _createClass(BatchQueue2, [{
        key: "_reset",
        value: function _reset() {
          var _this = this;
          this._startTime = Date.now();
          this._resolve = null;
          this._promise = new Promise(function(resolve) {
            return _this._resolve = resolve;
          });
        }
      }, {
        key: "init",
        value: function init(_ref3, flushHandler) {
          var _this2 = this;
          var delayMs = _ref3.delayMs, maxBatchSize = _ref3.maxBatchSize, useThrottle = _ref3.useThrottle, optimizeBatch2 = _ref3.optimizeBatch;
          if (this._initilized) {
            return;
          }
          this._maxBatchSize = maxBatchSize;
          this._optimizeBatch = optimizeBatch2;
          this._queue = [];
          this._flushHandler = flushHandler;
          this._flushDebounced = useThrottle ? throttle(function() {
            return _this2.flush();
          }, delayMs) : debounce(function() {
            return _this2.flush();
          }, delayMs);
          this._initilized = true;
          this._reset();
        }
      }, {
        key: "flush",
        value: function flush() {
          if (!this._queue.length) {
            return Promise.resolve();
          }
          var events = this._queue.splice(0, this._queue.length);
          var resolve = this._resolve;
          var startTime = this._startTime;
          this._reset();
          var batch = createBatch(events, startTime);
          if (this._optimizeBatch) {
            batch = optimizeBatch(batch);
          }
          return this._flushHandler(batch).then(resolve);
        }
      }, {
        key: "feed",
        value: function feed(event, context) {
          this._queue.push(createEvent(event, context, this._startTime));
          if (this._queue.length === this._maxBatchSize) {
            return this.flush();
          }
          this._flushDebounced();
          return this._promise;
        }
      }]);
      return BatchQueue2;
    }();
    module.exports = BatchQueue;
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/consent-policy.js
var require_consent_policy = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/consent-policy.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var DefaultConsentPolicy = {
      functional: true,
      analytics: true,
      __default: true
    };
    var getPolicy = function getPolicy2(consentPolicyGetter) {
      return typeof consentPolicyGetter === "function" && consentPolicyGetter() || DefaultConsentPolicy;
    };
    var shouldMuteNonEssentials = function shouldMuteNonEssentials2(policy) {
      return policy.functional === false || policy.analytics === false;
    };
    var shouldMuteByCategory = function shouldMuteByCategory2(policy, category) {
      if (category === "essential") {
        return false;
      }
      if (category === "functional" || category === "analytics") {
        return policy[category] === false;
      }
      return shouldMuteNonEssentials(policy);
    };
    module.exports = {
      shouldMuteNonEssentials,
      shouldMuteByCategory,
      getPolicy
    };
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/bi-logger.js
var require_bi_logger = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/bi-logger.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var _extends = Object.assign || function(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i];
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    };
    var _createClass = /* @__PURE__ */ function() {
      function defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
          var descriptor = props[i];
          descriptor.enumerable = descriptor.enumerable || false;
          descriptor.configurable = true;
          if ("value" in descriptor) descriptor.writable = true;
          Object.defineProperty(target, descriptor.key, descriptor);
        }
      }
      return function(Constructor, protoProps, staticProps) {
        if (protoProps) defineProperties(Constructor.prototype, protoProps);
        if (staticProps) defineProperties(Constructor, staticProps);
        return Constructor;
      };
    }();
    function _objectWithoutProperties(obj, keys) {
      var target = {};
      for (var i in obj) {
        if (keys.indexOf(i) >= 0) continue;
        if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
        target[i] = obj[i];
      }
      return target;
    }
    function _classCallCheck(instance, Constructor) {
      if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }
    var assert = require_assert();
    var _require = require_collections();
    var mapValues = _require.mapValues;
    var filterValues = _require.filterValues;
    var promise = require_promise();
    var log = require_log();
    var BatchQueue = require_batch_queue();
    var _require2 = require_consent_policy();
    var shouldMuteByCategory = _require2.shouldMuteByCategory;
    var shouldMuteNonEssentials = _require2.shouldMuteNonEssentials;
    var getPolicy = _require2.getPolicy;
    var BiLogger = function() {
      function BiLogger2(options, context) {
        _classCallCheck(this, BiLogger2);
        this._publishers = options.publishers;
        this._validators = options.validators || [];
        this._defaults = options.defaults;
        this._ownDefaults = {};
        this._events = options.events || {};
        this._context = context || {};
        this._defaultValueTimeout = options.defaultValueTimeout || 5e3;
        this._defaultContinueOnFail = options.defaultContinueOnFail || false;
        this._onPublisherFailHandler = options.onPublisherFailHandler || BiLogger2._defaultPublisherFailHandler;
        this._isMuted = options.isMuted || function() {
          return false;
        };
        this._eventTransformer = options.eventTransformer || function(event) {
          return event;
        };
        this._payloadTransformer = options.payloadTransformer || function(payload) {
          return payload;
        };
        this._consentPolicyGetter = options.consentPolicyGetter || function() {
          return null;
        };
        this._nonEssentialDefaults = options.nonEssentialDefaults || {};
        this._maxBatchSize = options.maxBatchSize || 100;
        this._globalBatchQueue = options.globalBatchQueue;
      }
      _createClass(BiLogger2, [{
        key: "report",
        value: function report(data) {
          assert.defined(data, "Data must be provided");
          assert.object(data, "Data must be an object");
          var src = data.src, evid = data.evid, params = data.params, context = _objectWithoutProperties(data, ["src", "evid", "params"]);
          return this.log(_extends({ src, evid }, params), context);
        }
      }, {
        key: "log",
        value: function log2(eventOrKey, eventOrContextOrUndefined, contextOrUndefined) {
          var _this = this;
          assert.defined(eventOrKey, "Event object or event key must be provided.");
          var _extractEventAndConte = this._extractEventAndContext(eventOrKey, eventOrContextOrUndefined, contextOrUndefined), event = _extractEventAndConte.event, context = _extractEventAndConte.context;
          var policy = getPolicy(this._consentPolicyGetter);
          var fullContext = _extends({}, this._context, context);
          if (this._isMuted() || shouldMuteByCategory(policy, fullContext.category)) {
            return Promise.resolve();
          }
          if (fullContext.useBatch) {
            var queue = this._initQueue(fullContext, policy);
            var transformAndQueue = function transformAndQueue2(_event) {
              var transformedEvent = _this._eventTransformer(_event, fullContext);
              return queue.feed(transformedEvent, fullContext);
            };
            if (this._globalBatchQueue) {
              return this._getDefaults(this._defaults).then(function(defaults) {
                var fullEvent2 = _extends({}, defaults, _this._getDynamicNonEssentialDefaults(policy), _this._getStaticNonEssentialDefaults(policy), event, _this._getPolicyFields(policy, fullContext.category));
                return transformAndQueue(fullEvent2);
              });
            } else {
              var fullEvent = _extends({}, this._getDynamicDefaults(this._defaults), this._getDynamicNonEssentialDefaults(policy), event, this._getPolicyFields(policy, fullContext.category));
              return transformAndQueue(fullEvent);
            }
          }
          return this._getDefaults(this._defaults).then(function(defaults) {
            var fullEvent2 = Object.assign(defaults, _this._getDynamicNonEssentialDefaults(policy), _this._getStaticNonEssentialDefaults(policy), event, _this._getPolicyFields(policy, fullContext.category));
            var validatorsResult = _this._validators.length === 0 ? true : _this._validators.some(function(validator) {
              return validator.match(fullEvent2) && (validator.execute(fullEvent2) || true);
            });
            if (!validatorsResult) {
              throw new Error("No validator accepted the event. Source: " + fullEvent2.src + " Evid: " + (fullEvent2.evid || fullEvent2.evtId));
            }
            var transformedEvent = _this._eventTransformer(fullEvent2, fullContext);
            transformedEvent = _this._payloadTransformer(transformedEvent, fullContext);
            return _this._send(transformedEvent, fullContext);
          });
        }
      }, {
        key: "flush",
        value: function flush() {
          if (!this._queue) {
            return Promise.resolve();
          }
          return this._queue.flush();
        }
      }, {
        key: "updateDefaults",
        value: function updateDefaults(defaults) {
          assert.defined(defaults, "Defaults must be provided");
          assert.object(defaults, "Defaults must be an object");
          Object.assign(this._ownDefaults, defaults);
          return this;
        }
      }, {
        key: "_send",
        value: function _send(payload) {
          var _this2 = this;
          var context = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
          return Promise.all(this._publishers.map(function(publisher) {
            var cloned = _extends({}, payload);
            return Promise.resolve().then(function() {
              return publisher(cloned, context);
            }).catch(function(error) {
              return _this2._onPublisherFailHandler(error, {
                publisherName: publisher.name,
                payload
              });
            });
          })).then(function() {
            return void 0;
          });
        }
      }, {
        key: "_extractEventAndContext",
        value: function _extractEventAndContext(eventOrKey, eventOrContextOrUndefined, contextOrUndefined) {
          var event = void 0;
          var context = {};
          if (typeof eventOrKey !== "string") {
            event = eventOrKey;
            context = eventOrContextOrUndefined || context;
          } else {
            event = this._events[eventOrKey];
            if (!event) {
              throw new assert.AssertionError("Event with key '" + eventOrKey + "' not found in event map.");
            }
            if (eventOrContextOrUndefined) {
              event = _extends({}, event, eventOrContextOrUndefined);
              context = contextOrUndefined || context;
            }
          }
          return { event, context };
        }
      }, {
        key: "_initQueue",
        value: function _initQueue(context, policy) {
          var _this3 = this;
          if (this._queue) {
            return this._queue;
          }
          this._queue = this._globalBatchQueue || new BatchQueue();
          var onFlush = function onFlush2(batch) {
            if (!_this3._globalBatchQueue) {
              batch.g = Object.assign(_this3._getStaticDefaults(_this3._defaults), _this3._getStaticNonEssentialDefaults(policy));
            }
            var transformedPayload = _this3._payloadTransformer(batch, context);
            return _this3._send(transformedPayload, context);
          };
          this._queue.init({
            delayMs: context.useBatch === true ? 300 : context.useBatch,
            maxBatchSize: this._maxBatchSize,
            useThrottle: !!this._globalBatchQueue,
            optimizeBatch: !!this._globalBatchQueue
          }, onFlush);
          return this._queue;
        }
      }, {
        key: "_handleDefaultsError",
        value: function _handleDefaultsError(err) {
          if (this._defaultContinueOnFail) {
            log.error(err);
            return null;
          }
          return Promise.reject(err);
        }
      }, {
        key: "_getDynamicNonEssentialDefaults",
        value: function _getDynamicNonEssentialDefaults(policy) {
          if (!shouldMuteNonEssentials(policy)) {
            return this._getDynamicDefaults(this._nonEssentialDefaults);
          }
        }
      }, {
        key: "_getStaticNonEssentialDefaults",
        value: function _getStaticNonEssentialDefaults(policy) {
          if (!shouldMuteNonEssentials(policy)) {
            return this._getStaticDefaults(this._nonEssentialDefaults);
          }
        }
      }, {
        key: "_withOwnDefaults",
        value: function _withOwnDefaults(defaults) {
          return Object.assign({}, defaults, this._ownDefaults);
        }
      }, {
        key: "_getDynamicDefaults",
        value: function _getDynamicDefaults(defaults) {
          defaults = this._withOwnDefaults(defaults);
          var dynamicDefaults = filterValues(defaults, function(v) {
            return typeof v === "function";
          });
          return mapValues(dynamicDefaults, function(v) {
            return v();
          });
        }
      }, {
        key: "_getStaticDefaults",
        value: function _getStaticDefaults(defaults) {
          defaults = this._withOwnDefaults(defaults);
          var staticDefaults = filterValues(defaults, function(v) {
            return typeof v !== "function";
          });
          return staticDefaults;
        }
      }, {
        key: "_getDefaults",
        value: function _getDefaults(defaults) {
          var _this4 = this;
          defaults = this._withOwnDefaults(defaults);
          if (!defaults) {
            return Promise.resolve({});
          }
          var promises = mapValues(defaults, function(value, key) {
            if (typeof value === "function") {
              try {
                value = value();
              } catch (err) {
                return _this4._handleDefaultsError(err);
              }
            }
            if (value && typeof value.then === "function") {
              return promise.timedPromise(value, {
                message: "Cannot get default value '" + key + " for BI Event'",
                timeout: _this4._defaultValueTimeout
              }).catch(function(err) {
                return _this4._handleDefaultsError(err);
              });
            }
            return value;
          });
          return promise.allAsObject(promises);
        }
      }, {
        key: "_encodePolicyValue",
        value: function _encodePolicyValue(policy, key) {
          if (!policy) {
            return 1;
          }
          if (typeof policy[key] === "boolean") {
            return policy[key] ? 1 : 0;
          }
          return policy[key];
        }
      }, {
        key: "_getPolicyFields",
        value: function _getPolicyFields(policy, category) {
          return {
            _isca: this._encodePolicyValue(policy, "analytics"),
            _iscf: this._encodePolicyValue(policy, "functional"),
            _ispd: policy.__default ? 1 : 0,
            _ise: category === "essential" ? 1 : 0
          };
        }
      }], [{
        key: "_defaultPublisherFailHandler",
        value: function _defaultPublisherFailHandler(error, _ref) {
          var publisherName = _ref.publisherName;
          return publisherName;
        }
      }]);
      return BiLogger2;
    }();
    module.exports = BiLogger;
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/bi-logger-manager.js
var require_bi_logger_manager = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/bi-logger-manager.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var _createClass = /* @__PURE__ */ function() {
      function defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
          var descriptor = props[i];
          descriptor.enumerable = descriptor.enumerable || false;
          descriptor.configurable = true;
          if ("value" in descriptor) descriptor.writable = true;
          Object.defineProperty(target, descriptor.key, descriptor);
        }
      }
      return function(Constructor, protoProps, staticProps) {
        if (protoProps) defineProperties(Constructor.prototype, protoProps);
        if (staticProps) defineProperties(Constructor, staticProps);
        return Constructor;
      };
    }();
    function _classCallCheck(instance, Constructor) {
      if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }
    var assert = require_assert();
    var BiLoggerManager = function() {
      function BiLoggerManager2() {
        _classCallCheck(this, BiLoggerManager2);
        this.reset();
      }
      _createClass(BiLoggerManager2, [{
        key: "reset",
        value: function reset() {
          this._handlers = [];
        }
      }, {
        key: "onLoggerCreated",
        value: function onLoggerCreated(handler) {
          var _this = this;
          assert.defined(handler, "Handler must be provided.");
          assert.func(handler, "Handler must be a function.");
          this._handlers.push(handler);
          return function() {
            var index = _this._handlers.indexOf(handler);
            if (index !== -1) {
              _this._handlers.splice(index, 1);
            }
          };
        }
      }, {
        key: "notifyLoggerCreated",
        value: function notifyLoggerCreated(logger) {
          this._handlers.forEach(function(handler) {
            return handler(logger);
          });
        }
      }]);
      return BiLoggerManager2;
    }();
    module.exports = {
      manager: new BiLoggerManager(),
      BiLoggerManager
    };
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/bi-logger-factory.js
var require_bi_logger_factory = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/bi-logger-factory.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
      return typeof obj;
    } : function(obj) {
      return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
    };
    var _createClass = /* @__PURE__ */ function() {
      function defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
          var descriptor = props[i];
          descriptor.enumerable = descriptor.enumerable || false;
          descriptor.configurable = true;
          if ("value" in descriptor) descriptor.writable = true;
          Object.defineProperty(target, descriptor.key, descriptor);
        }
      }
      return function(Constructor, protoProps, staticProps) {
        if (protoProps) defineProperties(Constructor.prototype, protoProps);
        if (staticProps) defineProperties(Constructor, staticProps);
        return Constructor;
      };
    }();
    function _classCallCheck(instance, Constructor) {
      if (!(instance instanceof Constructor)) {
        throw new TypeError("Cannot call a class as a function");
      }
    }
    var assert = require_assert();
    var BiLogger = require_bi_logger();
    var biLoggerManager = require_bi_logger_manager();
    var BatchQueue = require_batch_queue();
    var BiLoggerFactory = function() {
      function BiLoggerFactory2() {
        _classCallCheck(this, BiLoggerFactory2);
        this._publishers = [];
        this._validators = [];
        this._defaults = {};
        this._nonEssentialDefaults = {};
        this._events = {};
        this._isMuted = false;
        this._eventTransformer = null;
        this._payloadTransformer = null;
        this._consentPolicyGetter = null;
        this._maxBatchSize = null;
        this._batchQueue = null;
      }
      _createClass(BiLoggerFactory2, [{
        key: "addPublisher",
        value: function addPublisher(publisher) {
          assert.defined(publisher, "Publisher must be provided");
          assert.ok(typeof publisher === "function", "Expected a publisher function");
          this._publishers.push(publisher);
          return this;
        }
      }, {
        key: "addValidator",
        value: function addValidator(validator) {
          assert.defined(validator, "Validator must be provided");
          assert.ok((typeof validator === "undefined" ? "undefined" : _typeof(validator)) === "object" && validator, "Expected a validator object");
          assert.ok(validator.execute && validator.match, "Provided validator does not match the interface");
          this._validators.push(validator);
          return this;
        }
      }, {
        key: "setDefaults",
        value: function setDefaults(defaults) {
          assert.defined(defaults, "Defaults must be provided");
          assert.object(defaults, "Defaults must be an object");
          this._defaults = defaults;
          return this;
        }
      }, {
        key: "updateDefaults",
        value: function updateDefaults(defaults) {
          assert.defined(defaults, "Defaults must be provided");
          assert.object(defaults, "Defaults must be an object");
          Object.assign(this._defaults, defaults);
          return this;
        }
      }, {
        key: "updateNonEssentialDefaults",
        value: function updateNonEssentialDefaults(defaults) {
          assert.defined(defaults, "Non-essential Defaults must be provided");
          assert.object(defaults, "Non-essential Defaults must be an object");
          Object.assign(this._nonEssentialDefaults, defaults);
          return this;
        }
      }, {
        key: "setEvents",
        value: function setEvents(events) {
          assert.defined(events, "Events must be provided");
          assert.object(events, "Events must be an object");
          this._events = events;
          return this;
        }
      }, {
        key: "setDefaultValueTimeout",
        value: function setDefaultValueTimeout(defaultValueTimeout) {
          assert.defined(defaultValueTimeout, "Default Value Timeout must be provided");
          this._defaultValueTimeout = defaultValueTimeout;
          return this;
        }
      }, {
        key: "setDefaultContinueOnFail",
        value: function setDefaultContinueOnFail(defaultContinueOnFail) {
          assert.defined(defaultContinueOnFail, "Default Continue On Fail must be provided");
          this._defaultContinueOnFail = defaultContinueOnFail;
          return this;
        }
      }, {
        key: "setPublisherFailHandler",
        value: function setPublisherFailHandler(onPublisherFailHandler) {
          assert.defined(onPublisherFailHandler, "Publisher Fail Handler must be provided");
          this._onPublisherFailHandler = onPublisherFailHandler;
          return this;
        }
      }, {
        key: "setMuted",
        value: function setMuted(isMuted) {
          assert.defined(isMuted, "Is Muted must be provided");
          assert.boolean(isMuted, "Is Muted must be a boolean");
          this._isMuted = isMuted;
          return this;
        }
      }, {
        key: "setMaxBatchSize",
        value: function setMaxBatchSize(maxBatchSize) {
          assert.defined(maxBatchSize, "Max Batch Size must be provided");
          assert.number(maxBatchSize, "Max Batch Size must be a number");
          assert.ok(maxBatchSize > 0, "Max Batch Size must be higher than 0");
          this._maxBatchSize = maxBatchSize;
          return this;
        }
      }, {
        key: "setGlobalBatchQueue",
        value: function setGlobalBatchQueue(batchQueue) {
          assert.defined(batchQueue, "Global Batch Queue must be provided");
          assert.ok(batchQueue instanceof BatchQueue, "Global Batch Queue must be an instance of BatchQueue");
          this._globalBatchQueue = batchQueue;
          return this;
        }
      }, {
        key: "withEventTransformer",
        value: function withEventTransformer(transformer) {
          assert.defined(transformer, "Event Transformer must be provided");
          assert.func(transformer, "Event Transformer must be a function");
          this._eventTransformer = transformer;
          return this;
        }
      }, {
        key: "withPayloadTransformer",
        value: function withPayloadTransformer(transformer) {
          assert.defined(transformer, "Payload Transformer must be provided");
          assert.func(transformer, "Payload Transformer must be a function");
          this._payloadTransformer = transformer;
          return this;
        }
      }, {
        key: "withConsentPolicyGetter",
        value: function withConsentPolicyGetter(getter) {
          assert.defined(getter, "Consent Policy Getter must be provided");
          assert.func(getter, "Consent Policy Getter must be a function");
          this._consentPolicyGetter = getter;
          return this;
        }
      }, {
        key: "logger",
        value: function logger(context) {
          var _this = this;
          var logger2 = new BiLogger({
            publishers: this._publishers,
            validators: this._validators,
            defaults: this._defaults,
            events: this._events,
            defaultValueTimeout: this._defaultValueTimeout,
            defaultContinueOnFail: this._defaultContinueOnFail,
            onPublisherFailHandler: this._onPublisherFailHandler,
            isMuted: function isMuted() {
              return _this._isMuted;
            },
            eventTransformer: this._eventTransformer,
            payloadTransformer: this._payloadTransformer,
            consentPolicyGetter: this._consentPolicyGetter,
            nonEssentialDefaults: this._nonEssentialDefaults,
            maxBatchSize: this._maxBatchSize,
            globalBatchQueue: this._globalBatchQueue
          }, context);
          biLoggerManager.manager.notifyLoggerCreated(logger2);
          return logger2;
        }
      }]);
      return BiLoggerFactory2;
    }();
    module.exports = BiLoggerFactory;
  }
});

// ../../node_modules/@wix/wix-bi-logger-client/dist/index.js
var require_dist = __commonJS({
  "../../node_modules/@wix/wix-bi-logger-client/dist/index.js"(exports, module) {
    "use strict";
    init_esm_shims();
    var BiLoggerClientFactory = require_bi_logger_factory();
    var BiLogger = require_bi_logger();
    var biLoggerManager = require_bi_logger_manager();
    var BatchQueue = require_batch_queue();
    module.exports.BiLoggerFactory = BiLoggerClientFactory;
    module.exports.BiLogger = BiLogger;
    module.exports.BiLoggerManager = biLoggerManager.BiLoggerManager;
    module.exports.factory = function() {
      return new BiLoggerClientFactory();
    };
    module.exports.manager = biLoggerManager.manager;
    module.exports.createBatchQueue = function() {
      return new BatchQueue();
    };
  }
});

// ../cli-telemetry/src/add-user-fields.ts
init_esm_shims();
import { randomUUID } from "node:crypto";
function addUserFields(logger, userId) {
  logger.updateDefaults(resolveUserFields(userId));
}
function resolveUserFields(userId) {
  if (!userId) {
    return {
      _client_id: randomUUID()
    };
  }
  return {
    _client_id: userId,
    _uuid: userId,
    logged_user_id: userId,
    logged_account_id: userId,
    target_account_id: userId
  };
}

// ../cli-telemetry/src/command-bi-event.ts
init_esm_shims();
import { uptime } from "node:process";

// ../cli-telemetry/src/environment.ts
init_esm_shims();
var import_is_ci = __toESM(require_is_ci(), 1);
import os from "node:os";
import { platform, version as nodeVersion } from "node:process";
function getEnvironmentInfo({
  cliVersion,
  flow
}) {
  return {
    ...flow ? { flow } : {},
    cliVersion,
    isCI: import_is_ci.default,
    nodeVersion,
    osName: getOsName(),
    osVersion: os.release()
  };
}
function getOsName() {
  switch (platform) {
    case "darwin":
      return "mac";
    case "win32":
      return "windows";
    default:
      return "linux";
  }
}

// ../cli-telemetry/src/command-bi-event.ts
var getDuration = () => Math.round(uptime() * 1e3);
function reportCommandStartEvent({
  biLogger,
  command,
  flow,
  cliVersion,
  projectId,
  extensions,
  extraFields
}) {
  const options = command.opts();
  const args = command.args;
  const privateOptions = /* @__PURE__ */ new Set(["apiKey", "refreshToken"]);
  const sanitizedOptions = Object.fromEntries(
    Object.entries(options).map(([flagName, flagValue]) => {
      const value = privateOptions.has(flagName) ? "<censored>" : flagValue;
      return [flagName, value];
    })
  );
  const commandFields = {
    command: command.name(),
    arguments: args.join(","),
    flags: Object.keys(sanitizedOptions).length ? JSON.stringify(sanitizedOptions) : ""
  };
  void biLogger.report(
    wixCliCliCommand({
      ...getEnvironmentInfo({ cliVersion, flow }),
      ...commandFields,
      ...projectId ? { projectId } : {},
      ...extraFields ? { extraFields: JSON.stringify(extraFields) } : {},
      isValid: true
    })
  );
  return {
    succeed() {
      void biLogger.report(
        wixCliCliCommandStatus({
          ...commandFields,
          ...extensions ? { extensions: JSON.stringify(extensions) } : {},
          duration: getDuration(),
          isSuccess: true,
          isValid: true
        })
      );
    },
    failed(error) {
      const errorFields = isCliError(error) ? {
        errorType: isCliSystemError(error) ? "SystemError" : "UserError",
        errorName: error.name,
        errorMessage: error.message
      } : error instanceof Error ? {
        errorType: "UnknownError",
        errorName: error.name,
        errorMessage: error.message
      } : {
        errorType: "UnknownError",
        errorMessage: JSON.stringify(error)
      };
      void biLogger.report(
        wixCliCliCommandStatus({
          ...commandFields,
          ...errorFields,
          ...extensions ? { extensions: JSON.stringify(extensions) } : {},
          duration: getDuration(),
          isSuccess: false,
          isValid: true
        })
      );
    }
  };
}

// ../cli-telemetry/src/index.ts
init_esm_shims();

// ../cli-telemetry/src/create-bi-logger.ts
init_esm_shims();

// ../../node_modules/@wix/standalone-node-bi-logger/dist/es/src/index.js
init_esm_shims();
init_tslib_es6();
var import_wix_bi_logger_client = __toESM(require_dist());
var import_http_client = __toESM(require_index_node());
var defaultOptions = {
  baseUrl: process.env.BI_BASE_URL || "https://frog.wix.com",
  endpoint: "",
  logError: false
};
var StandaloneNodeLogger = (
  /** @class */
  function() {
    function StandaloneNodeLogger2() {
    }
    StandaloneNodeLogger2.prototype.factory = function(options) {
      var _this = this;
      if (options === void 0) {
        options = {};
      }
      var fullOptions = __assign(__assign({}, defaultOptions), options);
      var biLoggerFactory = import_wix_bi_logger_client.default.factory();
      if (fullOptions.onError) {
        biLoggerFactory.setPublisherFailHandler(fullOptions.onError);
      }
      biLoggerFactory.addPublisher(function(eventParams, context) {
        return __awaiter(_this, void 0, void 0, function() {
          var endpoint, baseUrl, userAgent, logError, headers;
          return __generator(this, function(_a) {
            switch (_a.label) {
              case 0:
                endpoint = context.endpoint || fullOptions.endpoint;
                baseUrl = fullOptions.baseUrl, userAgent = fullOptions.userAgent, logError = fullOptions.logError;
                headers = userAgent ? { headers: { "User-Agent": userAgent } } : {};
                return [4, new import_http_client.HttpClient({ baseURL: baseUrl }).get(endpoint, {
                  headers,
                  params: eventParams,
                  timeout: 30 * 1e3
                }).catch(function(e) {
                  return logError ? console.error(e.toJSON()) : Promise.reject(e);
                })];
              case 1:
                _a.sent();
                return [
                  2
                  /*return*/
                ];
            }
          });
        });
      });
      return biLoggerFactory;
    };
    return StandaloneNodeLogger2;
  }()
);
var src_default = new StandaloneNodeLogger();

// ../cli-telemetry/src/create-bi-logger.ts
async function createBiLogger(defaultFields = {}) {
  const testBaseUrl = getTestOverrides().biLoggerBaseUrl;
  const options = testBaseUrl ? { baseUrl: testBaseUrl } : {};
  const { telemetry: isTelemetryOn } = await readUserConfig();
  return new StandaloneNodeLogger().factory(options).updateDefaults({
    localTime: () => Date.now(),
    ...defaultFieldsToBiEvent(defaultFields)
  }).setMuted(!isTelemetryOn).logger();
}
function defaultFieldsToBiEvent(defaultFields) {
  const { cliEnvName, aiAgentName, userId, cliTrackingId, ...rest } = defaultFields;
  const result = {};
  for (const [key, value] of Object.entries(rest)) {
    if (value != null) {
      result[key] = value;
    }
  }
  if (cliEnvName) {
    result.environment = cliEnvName;
  }
  if (aiAgentName) {
    result.ai_agent_name = aiAgentName;
  }
  if (cliTrackingId) {
    result.tracking_id = cliTrackingId;
  }
  return { ...result, ...resolveUserFields(userId) };
}

export {
  addUserFields,
  createBiLogger,
  reportCommandStartEvent
};
//# sourceMappingURL=chunk-HENH75UF.js.map