import {
  __commonJS,
  __name,
  __toESM,
  init_define_process
} from "./chunk-chunk-5RXWZEI4.mjs";

// ../../node_modules/microevent.ts/lib/Event.js
var require_Event = __commonJS({
  "../../node_modules/microevent.ts/lib/Event.js"(exports) {
    "use strict";
    init_define_process();
    Object.defineProperty(exports, "__esModule", { value: true });
    var factories = [];
    factories[0] = function() {
      return /* @__PURE__ */ __name(function dispatcher0() {
      }, "dispatcher0");
    };
    factories[1] = function(callback, context) {
      if (typeof context === "undefined")
        return callback;
      return /* @__PURE__ */ __name(function dispatcher1(payload) {
        callback(payload, context);
      }, "dispatcher1");
    };
    function getFactory(handlerCount) {
      if (!factories[handlerCount])
        factories[handlerCount] = compileFactory(handlerCount);
      return factories[handlerCount];
    }
    __name(getFactory, "getFactory");
    function compileFactory(handlerCount) {
      var src = "return function dispatcher" + handlerCount + "(payload) {\n";
      var argsHandlers = [], argsContexts = [];
      for (var i = 0; i < handlerCount; i++) {
        argsHandlers.push("cb" + i);
        argsContexts.push("ctx" + i);
        src += "    cb" + i + "(payload, ctx" + i + ");\n";
      }
      src += "};";
      return new (Function.bind.apply(Function, [void 0].concat(argsHandlers.concat(argsContexts), [src])))();
    }
    __name(compileFactory, "compileFactory");
    var Event = (
      /** @class */
      function() {
        function Event2() {
          this.hasHandlers = false;
          this._handlers = [];
          this._contexts = [];
          this._createDispatcher();
        }
        __name(Event2, "Event");
        Event2.prototype.addHandler = function(handler, context) {
          if (!this.isHandlerAttached(handler, context)) {
            this._handlers.push(handler);
            this._contexts.push(context);
            this._createDispatcher();
            this._updateHasHandlers();
          }
          return this;
        };
        Event2.prototype.removeHandler = function(handler, context) {
          var idx = this._getHandlerIndex(handler, context);
          if (typeof idx !== "undefined") {
            this._handlers.splice(idx, 1);
            this._contexts.splice(idx, 1);
            this._createDispatcher();
            this._updateHasHandlers();
          }
          return this;
        };
        Event2.prototype.isHandlerAttached = function(handler, context) {
          return typeof this._getHandlerIndex(handler, context) !== "undefined";
        };
        Event2.prototype._updateHasHandlers = function() {
          this.hasHandlers = !!this._handlers.length;
        };
        Event2.prototype._getHandlerIndex = function(handler, context) {
          var handlerCount = this._handlers.length;
          var idx;
          for (idx = 0; idx < handlerCount; idx++) {
            if (this._handlers[idx] === handler && this._contexts[idx] === context)
              break;
          }
          return idx < handlerCount ? idx : void 0;
        };
        Event2.prototype._createDispatcher = function() {
          this.dispatch = getFactory(this._handlers.length).apply(this, this._handlers.concat(this._contexts));
        };
        return Event2;
      }()
    );
    exports.default = Event;
  }
});

// ../../node_modules/microevent.ts/lib/index.js
var require_lib = __commonJS({
  "../../node_modules/microevent.ts/lib/index.js"(exports) {
    "use strict";
    init_define_process();
    Object.defineProperty(exports, "__esModule", { value: true });
    var Event_1 = require_Event();
    exports.Event = Event_1.default;
  }
});

// ../../node_modules/worker-rpc/lib/RpcProvider.js
var require_RpcProvider = __commonJS({
  "../../node_modules/worker-rpc/lib/RpcProvider.js"(exports) {
    "use strict";
    init_define_process();
    Object.defineProperty(exports, "__esModule", { value: true });
    var microevent_ts_1 = require_lib();
    var MSG_RESOLVE_TRANSACTION = "resolve_transaction";
    var MSG_REJECT_TRANSACTION = "reject_transaction";
    var MSG_ERROR = "error";
    var RpcProvider2 = (
      /** @class */
      function() {
        function RpcProvider3(_dispatch, _rpcTimeout) {
          if (_rpcTimeout === void 0) {
            _rpcTimeout = 0;
          }
          this._dispatch = _dispatch;
          this._rpcTimeout = _rpcTimeout;
          this.error = new microevent_ts_1.Event();
          this._rpcHandlers = {};
          this._signalHandlers = {};
          this._pendingTransactions = {};
          this._nextTransactionId = 0;
        }
        __name(RpcProvider3, "RpcProvider");
        RpcProvider3.prototype.dispatch = function(payload) {
          var message = payload;
          switch (message.type) {
            case RpcProvider3.MessageType.signal:
              return this._handleSignal(message);
            case RpcProvider3.MessageType.rpc:
              return this._handeRpc(message);
            case RpcProvider3.MessageType.internal:
              return this._handleInternal(message);
            default:
              this._raiseError("invalid message type " + message.type);
          }
        };
        RpcProvider3.prototype.rpc = function(id, payload, transfer) {
          var _this = this;
          var transactionId = this._nextTransactionId++;
          this._dispatch({
            type: RpcProvider3.MessageType.rpc,
            transactionId,
            id,
            payload
          }, transfer ? transfer : void 0);
          return new Promise(function(resolve, reject) {
            var transaction = _this._pendingTransactions[transactionId] = {
              id: transactionId,
              resolve,
              reject
            };
            if (_this._rpcTimeout > 0) {
              _this._pendingTransactions[transactionId].timeoutHandle = setTimeout(function() {
                return _this._transactionTimeout(transaction);
              }, _this._rpcTimeout);
            }
          });
        };
        ;
        RpcProvider3.prototype.signal = function(id, payload, transfer) {
          this._dispatch({
            type: RpcProvider3.MessageType.signal,
            id,
            payload
          }, transfer ? transfer : void 0);
          return this;
        };
        RpcProvider3.prototype.registerRpcHandler = function(id, handler) {
          if (this._rpcHandlers[id]) {
            throw new Error("rpc handler for " + id + " already registered");
          }
          this._rpcHandlers[id] = handler;
          return this;
        };
        ;
        RpcProvider3.prototype.registerSignalHandler = function(id, handler) {
          if (!this._signalHandlers[id]) {
            this._signalHandlers[id] = [];
          }
          this._signalHandlers[id].push(handler);
          return this;
        };
        RpcProvider3.prototype.deregisterRpcHandler = function(id, handler) {
          if (this._rpcHandlers[id]) {
            delete this._rpcHandlers[id];
          }
          return this;
        };
        ;
        RpcProvider3.prototype.deregisterSignalHandler = function(id, handler) {
          if (this._signalHandlers[id]) {
            this._signalHandlers[id] = this._signalHandlers[id].filter(function(h2) {
              return handler !== h2;
            });
          }
          return this;
        };
        RpcProvider3.prototype._raiseError = function(error) {
          this.error.dispatch(new Error(error));
          this._dispatch({
            type: RpcProvider3.MessageType.internal,
            id: MSG_ERROR,
            payload: error
          });
        };
        RpcProvider3.prototype._handleSignal = function(message) {
          if (!this._signalHandlers[message.id]) {
            return this._raiseError("invalid signal " + message.id);
          }
          this._signalHandlers[message.id].forEach(function(handler) {
            return handler(message.payload);
          });
        };
        RpcProvider3.prototype._handeRpc = function(message) {
          var _this = this;
          if (!this._rpcHandlers[message.id]) {
            return this._raiseError("invalid rpc " + message.id);
          }
          Promise.resolve(this._rpcHandlers[message.id](message.payload)).then(function(result) {
            return _this._dispatch({
              type: RpcProvider3.MessageType.internal,
              id: MSG_RESOLVE_TRANSACTION,
              transactionId: message.transactionId,
              payload: result
            });
          }, function(reason) {
            return _this._dispatch({
              type: RpcProvider3.MessageType.internal,
              id: MSG_REJECT_TRANSACTION,
              transactionId: message.transactionId,
              payload: reason
            });
          });
        };
        RpcProvider3.prototype._handleInternal = function(message) {
          var transaction = typeof message.transactionId !== "undefined" ? this._pendingTransactions[message.transactionId] : void 0;
          switch (message.id) {
            case MSG_RESOLVE_TRANSACTION:
              if (!transaction || typeof message.transactionId === "undefined") {
                return this._raiseError("no pending transaction with id " + message.transactionId);
              }
              transaction.resolve(message.payload);
              this._clearTransaction(this._pendingTransactions[message.transactionId]);
              break;
            case MSG_REJECT_TRANSACTION:
              if (!transaction || typeof message.transactionId === "undefined") {
                return this._raiseError("no pending transaction with id " + message.transactionId);
              }
              this._pendingTransactions[message.transactionId].reject(message.payload);
              this._clearTransaction(this._pendingTransactions[message.transactionId]);
              break;
            case MSG_ERROR:
              this.error.dispatch(new Error("remote error: " + message.payload));
              break;
            default:
              this._raiseError("unhandled internal message " + message.id);
              break;
          }
        };
        RpcProvider3.prototype._transactionTimeout = function(transaction) {
          transaction.reject("transaction timed out");
          this._raiseError("transaction " + transaction.id + " timed out");
          delete this._pendingTransactions[transaction.id];
          return;
        };
        RpcProvider3.prototype._clearTransaction = function(transaction) {
          if (typeof transaction.timeoutHandle !== "undefined") {
            clearTimeout(transaction.timeoutHandle);
          }
          delete this._pendingTransactions[transaction.id];
        };
        return RpcProvider3;
      }()
    );
    (function(RpcProvider3) {
      var MessageType;
      (function(MessageType2) {
        MessageType2[MessageType2["signal"] = 0] = "signal";
        MessageType2[MessageType2["rpc"] = 1] = "rpc";
        MessageType2[MessageType2["internal"] = 2] = "internal";
      })(MessageType = RpcProvider3.MessageType || (RpcProvider3.MessageType = {}));
      ;
    })(RpcProvider2 || (RpcProvider2 = {}));
    exports.default = RpcProvider2;
  }
});

// ../../node_modules/worker-rpc/lib/index.js
var require_lib2 = __commonJS({
  "../../node_modules/worker-rpc/lib/index.js"(exports) {
    "use strict";
    init_define_process();
    Object.defineProperty(exports, "__esModule", { value: true });
    var RpcProvider_1 = require_RpcProvider();
    exports.RpcProvider = RpcProvider_1.default;
  }
});

// ../../node_modules/transferables/lib/index.mjs
init_define_process();
var k = Object.getPrototypeOf(Int8Array);
var q = globalThis.AudioData;
var I = globalThis.ImageBitmap;
var V = globalThis.VideoFrame;
var F = globalThis.OffscreenCanvas;
var W = globalThis.RTCDataChannel;
var h = globalThis.MessageChannel;
var B = globalThis.ReadableStream;
var R = globalThis.WritableStream;
var D = globalThis.TransformStream;
var p = "ReadableStream" in globalThis;
var d = "WritableStream" in globalThis;
var y = "TransformStream" in globalThis;
var g = "MessageChannel" in globalThis;
var b = "MessagePort" in globalThis;
var T = "ArrayBuffer" in globalThis;
var C = "AudioData" in globalThis;
var A = "ImageBitmap" in globalThis;
var w = "VideoFrame" in globalThis;
var S = "OffscreenCanvas" in globalThis;
var E = "RTCDataChannel" in globalThis;
var m = "structuredClone" in globalThis;
function x(t) {
  return typeof t == "object" && t !== null || typeof t == "function";
}
__name(x, "x");
function O(t) {
  return ArrayBuffer.isView(t);
}
__name(O, "O");
function u(t) {
  return p && t instanceof B || d && t instanceof R || y && t instanceof D;
}
__name(u, "u");
function M(t) {
  return g && t instanceof h;
}
__name(M, "M");
function v(t) {
  return T && t instanceof ArrayBuffer || b && t instanceof MessagePort || C && t instanceof q || A && t instanceof I || w && t instanceof V || S && t instanceof F || E && t instanceof W;
}
__name(v, "v");
function N(t, c = false, f = 1e4) {
  const r2 = /* @__PURE__ */ new Set([]), n = [[t]];
  for (let o = 0; o < n.length; o++) {
    const i = n[o], a = i.length;
    for (let s = 0; s < a; s++) {
      const e2 = i[s];
      if (O(e2))
        r2.add(e2.buffer);
      else if (v(e2) || c && u(e2))
        r2.add(e2);
      else if (M(e2))
        r2.add(e2.port1), r2.add(e2.port2);
      else if (!u(e2) && x(e2)) {
        const l = Array.isArray(e2) ? e2 : Object.values(e2);
        l.length && n.push(l);
      }
    }
    if (--f <= 0)
      break;
  }
  return Array.from(r2);
}
__name(N, "N");
function G(t, c = false, f = 1e4) {
  const r2 = [[t]];
  for (let n = 0; n < r2.length; n++) {
    const o = r2[n], i = o.length;
    for (let a = 0; a < i; a++) {
      const s = o[a];
      if (O(s))
        return true;
      if (v(s) || c && u(s))
        return true;
      if (M(s))
        return true;
      if (!u(s) && x(s)) {
        const e2 = Array.isArray(s) ? s : Object.values(s);
        e2.length && r2.push(e2);
      }
    }
    if (--f <= 0)
      break;
  }
  return false;
}
__name(G, "G");

// src/shared.ts
init_define_process();

// ../../node_modules/@okikio/sharedworker/lib/index.mjs
init_define_process();
var r = "SharedWorker" in globalThis;
var e = class {
  ActualWorker;
  constructor(e2, t) {
    this.ActualWorker = r ? new SharedWorker(e2, t) : new Worker(e2, t);
  }
  get onmessage() {
    var _a;
    return r ? (_a = this.ActualWorker) == null ? void 0 : _a.port.onmessage : this.ActualWorker.onmessage;
  }
  set onmessage(e2) {
    r ? this.ActualWorker.port.onmessage = e2 : this.ActualWorker.onmessage = e2;
  }
  get onmessageerror() {
    var _a;
    return r ? (_a = this.ActualWorker) == null ? void 0 : _a.port.onmessageerror : this.ActualWorker.onmessageerror;
  }
  set onmessageerror(e2) {
    r ? this.ActualWorker.port.onmessageerror = e2 : this.ActualWorker.onmessageerror = e2;
  }
  start() {
    var _a;
    if (r)
      return (_a = this.ActualWorker) == null ? void 0 : _a.port.start();
  }
  postMessage(e2, t) {
    var _a;
    return r ? (_a = this.ActualWorker) == null ? void 0 : _a.port.postMessage(e2, t) : this.ActualWorker.postMessage(e2, t);
  }
  terminate() {
    var _a;
    return r ? (_a = this.ActualWorker) == null ? void 0 : _a.port.close() : this.ActualWorker.terminate();
  }
  close() {
    return this.terminate();
  }
  get port() {
    return r ? this.ActualWorker.port : this.ActualWorker;
  }
  get onerror() {
    return this.ActualWorker.onerror;
  }
  set onerror(r2) {
    this.ActualWorker.onerror = r2;
  }
  addEventListener(e2, t, o) {
    var _a;
    return r && "error" !== e2 ? (_a = this.ActualWorker) == null ? void 0 : _a.port.addEventListener(e2, t, o) : this.ActualWorker.addEventListener(e2, t, o);
  }
  removeEventListener(e2, t, o) {
    var _a;
    return r && "error" !== e2 ? (_a = this.ActualWorker) == null ? void 0 : _a.port.removeEventListener(e2, t, o) : this.ActualWorker.removeEventListener(e2, t, o);
  }
  dispatchEvent(r2) {
    return this.ActualWorker.dispatchEvent(r2);
  }
};
__name(e, "e");

// src/shared.ts
var import_worker_rpc = __toESM(require_lib2(), 1);
var rpc = null;
var workerPort;
var getPort = /* @__PURE__ */ __name(() => workerPort, "getPort");
var init = /* @__PURE__ */ __name((swVersion2, port = null) => {
  if (rpc !== null)
    return rpc;
  workerPort = port || new e(`/workerScripts/ataWorker.js?v=${swVersion2}`).port;
  rpc = new import_worker_rpc.RpcProvider(
    (message) => workerPort.postMessage(
      message,
      G(message) ? N(message) : void 0
    ),
    0
  );
  workerPort.onmessage = ({ data }) => rpc.dispatch(data);
  return rpc;
}, "init");
var prettier = /* @__PURE__ */ __name((code) => init(swVersion).rpc("prettierJs", code), "prettier");
var ata = /* @__PURE__ */ __name(({ code, originToUse }) => init(swVersion).rpc("ata", { code, originToUse }), "ata");
var transpile = /* @__PURE__ */ __name(({ code, originToUse }) => init(swVersion).rpc("transpile", { code, originToUse }), "transpile");
var connect = /* @__PURE__ */ __name((codeSpace) => init(swVersion).signal("connect", codeSpace), "connect");

export {
  N,
  G,
  getPort,
  init,
  prettier,
  ata,
  transpile,
  connect
};
