workboots
Version:
a lightweight message proxy for webworkers and worker threads
678 lines (646 loc) • 29.8 kB
JavaScript
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.WorkBoots = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
},{}],2:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],3:[function(require,module,exports){
(function (process,global){(function (){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WorkBoots = exports.Socks = void 0;
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, "default": e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t3 in e) "default" !== _t3 && {}.hasOwnProperty.call(e, _t3) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, _t3)) && (i.get || i.set) ? o(f, _t3, i) : f[_t3] = e[_t3]); return f; })(e, t); }
/**
* Universal entry point for work-÷boots
* Compatible with Browserify, Node.js, and ES modules
*/
// Detect environment
var isNode = typeof process !== 'undefined' && process.versions && process.versions.node;
var isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined';
// Universal require/import function
function universalRequire(moduleName) {
if (isNode) {
// In Node.js, use dynamic import
return function (specifier) {
return new Promise(function (r) {
return r("".concat(specifier));
}).then(function (s) {
return _interopRequireWildcard(require(s));
});
}(moduleName);
} else {
// In browser, assume it's available globally or bundled
return Promise.resolve({
"default": global[moduleName]
});
}
}
// Enhanced WorkBoots with Browserify compatibility
var WorkBoots = exports.WorkBoots = /*#__PURE__*/function () {
function WorkBoots(_ref) {
var _this = this;
var socksFile = _ref.socksFile,
_ref$instantiateWorke = _ref.instantiateWorker,
instantiateWorker = _ref$instantiateWorke === void 0 ? null : _ref$instantiateWorke;
_classCallCheck(this, WorkBoots);
if (socksFile === undefined) {
this.readyPromise = Promise.reject(new Error('no socksFile defined!'));
return;
}
// Determine worker support based on environment
this.supportsWorker = this.detectWorkerSupport();
this.receivedBeforeReady = [];
this.isReady = false;
// Create default worker instantiation function based on environment
if (!instantiateWorker) {
instantiateWorker = this.createDefaultWorkerFactory();
}
this.readyPromise = new Promise(function (resolve) {
var velcroAndLaces = function velcroAndLaces(message) {
if ((message === null || message === void 0 ? void 0 : message.data) === 'socks loaded') {
resolve(_this);
} else {
for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
console.log('received message before socks.ready() was called, ' + JSON.stringify([message].concat(rest)));
_this.receivedBeforeReady.push([message].concat(rest));
}
};
_this.onMessage(velcroAndLaces);
if (_this.supportsWorker) {
try {
_this.worker = instantiateWorker(socksFile);
_this.supportsWorker = true;
_this.isReady = true;
} catch (e) {
_this.worker = undefined;
_this.supportsWorker = false;
console.log('background worker not supported, switching to shorter socks (main thread eval).', e);
}
}
if (!_this.supportsWorker) {
_this.supportsWorker = false;
// Handle import errors gracefully with Browserify compatibility
_this.loadSocksFile(socksFile).then(function (_ref2) {
var socks = _ref2.socks;
_this.socks = socks;
_this.socks.enterBoots(_this);
_this.isReady = true;
resolve(_this);
})["catch"](function (error) {
console.log('Failed to import socks file, creating mock socks:', error.message);
// Create a mock socks for testing
_this.socks = {
enterBoots: function enterBoots(boots) {
_this.boots = boots;
},
onMessageLocal: function onMessageLocal(message) {
if (_this.onMessageCallback) {
_this.onMessageCallback({
data: message.data
});
}
},
terminate: function terminate() {}
};
_this.socks.enterBoots(_this);
_this.isReady = true;
resolve(_this);
});
}
});
}
// Browserify-compatible module loading
return _createClass(WorkBoots, [{
key: "loadSocksFile",
value: function () {
var _loadSocksFile = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(socksFile) {
var _t;
return _regenerator().w(function (_context) {
while (1) switch (_context.p = _context.n) {
case 0:
_context.p = 0;
_context.n = 1;
return function (specifier) {
return new Promise(function (r) {
return r("".concat(specifier));
}).then(function (s) {
return _interopRequireWildcard(require(s));
});
}(socksFile);
case 1:
return _context.a(2, _context.v);
case 2:
_context.p = 2;
_t = _context.v;
if (!(typeof require !== 'undefined')) {
_context.n = 3;
break;
}
return _context.a(2, require(socksFile));
case 3:
throw _t;
case 4:
return _context.a(2);
}
}, _callee, null, [[0, 2]]);
}));
function loadSocksFile(_x) {
return _loadSocksFile.apply(this, arguments);
}
return loadSocksFile;
}()
}, {
key: "detectWorkerSupport",
value: function detectWorkerSupport() {
if (isBrowser) {
return typeof Worker !== 'undefined';
} else if (isNode) {
try {
// Use dynamic import for worker_threads in ES modules
return true; // We'll check this in createDefaultWorkerFactory
} catch (e) {
return false;
}
}
return false;
}
}, {
key: "createDefaultWorkerFactory",
value: function createDefaultWorkerFactory() {
if (isBrowser) {
return function (socksFile) {
return new Worker(socksFile);
};
} else if (isNode) {
return /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(socksFile) {
var _yield$import, _Worker, _t2;
return _regenerator().w(function (_context2) {
while (1) switch (_context2.p = _context2.n) {
case 0:
_context2.p = 0;
_context2.n = 1;
return Promise.resolve().then(function () {
return _interopRequireWildcard(require('worker_threads'));
});
case 1:
_yield$import = _context2.v;
_Worker = _yield$import.Worker;
return _context2.a(2, new _Worker(socksFile, {
type: 'module'
}));
case 2:
_context2.p = 2;
_t2 = _context2.v;
throw new Error('Worker threads not available');
case 3:
return _context2.a(2);
}
}, _callee2, null, [[0, 2]]);
}));
return function (_x2) {
return _ref3.apply(this, arguments);
};
}();
}
return function () {
throw new Error('No worker support available');
};
}
}, {
key: "ready",
value: function ready() {
return this.readyPromise;
}
}, {
key: "postMessage",
value: function postMessage(data) {
var origin = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var transfer = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
if (!this.isReady) {
if (this.onMessageCallback) {
this.onMessageCallback(data, origin, transfer);
}
return;
}
// Handle undefined/null data
if (data === undefined || data === null) {
data = {
data: null
};
}
var message = data && _typeof(data) === 'object' && 'data' in data ? data : {
data: data
};
console.log("supports worker: ".concat(this.supportsWorker));
if (this.supportsWorker && this.worker && typeof this.worker.postMessage === 'function') {
// Handle different worker types
if (isBrowser) {
var _this$worker;
(_this$worker = this.worker).postMessage.apply(_this$worker, _toConsumableArray([data, transfer.length > 0 ? transfer : undefined].filter(function (arg) {
return !!arg;
})));
} else if (isNode) {
this.worker.postMessage(data, transfer);
}
} else if (this.socks && typeof this.socks.onMessageLocal === 'function') {
this.socks.onMessageLocal(message, transfer);
}
}
}, {
key: "onMessage",
value: function onMessage(callback) {
var _this2 = this;
this.onMessageCallback = callback;
if (this.worker) {
if (isBrowser) {
this.worker.onmessage = callback;
} else if (isNode) {
// Check if worker has 'on' method (Node.js worker threads)
if (typeof this.worker.on === 'function') {
this.worker.on('message', callback);
} else {
// Fallback for mock workers or other implementations
this.worker.onmessage = callback;
}
}
}
if (this.receivedBeforeReady.length) {
console.log('messages received before socks loaded now replaying (not necessarily a problem, but loading out of order):');
this.receivedBeforeReady.forEach(function (m) {
return _this2.onMessageCallback && _this2.onMessageCallback.apply(_this2, _toConsumableArray(m));
});
}
}
}, {
key: "onMessageLocal",
value: function onMessageLocal(data, origin) {
var transfer = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
console.log("sending local message that would have been to origin ".concat(origin));
if ((transfer === null || transfer === void 0 ? void 0 : transfer.length) > 0) {
console.log("transfer ignored for ".concat(transfer.length, " transfer references"));
}
console.log("onMessageCallback ".concat(this.onMessageCallback));
if (this.onMessageCallback) {
this.onMessageCallback({
data: data
});
} else {
throw new Error('onMessageLocal should not be called without onMessageCallback defined');
}
}
}, {
key: "terminate",
value: function terminate() {
if (this.supportsWorker && this.worker && typeof this.worker.terminate === 'function') {
if (isBrowser) {
this.worker.terminate();
} else if (isNode) {
this.worker.terminate();
}
} else if (this.socks && typeof this.socks.terminate === 'function') {
this.socks.terminate();
}
}
}]);
}(); // Enhanced Socks with Browserify compatibility
var Socks = exports.Socks = /*#__PURE__*/function () {
function Socks() {
var self = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
_classCallCheck(this, Socks);
this.self = self;
this.postsBeforeReady = [];
this.isReady = false;
this.sentReadyMessage = false;
}
return _createClass(Socks, [{
key: "ready",
value: function ready() {
if (this.isWorkerSupported()) {
this.postMessage("socks loaded");
this.sentReadyMessage = true;
} else {
if (this.boots) {
this.boots.onMessageLocal("socks loaded");
this.sentReadyMessage = true;
}
}
this.isReady = true;
this.processReadyMessages();
}
}, {
key: "processReadyMessages",
value: function processReadyMessages() {
var _this3 = this;
if (this.sentReadyMessage) {
this.postsBeforeReady.forEach(function (args) {
return _this3.postMessage.apply(_this3, _toConsumableArray(args));
});
this.postsBeforeReady = [];
}
}
}, {
key: "enterBoots",
value: function enterBoots(boots) {
var _this$self;
this.boots = boots;
if (this.isReady && !this.sentReadyMessage) {
this.ready();
}
// if enter boots is called, we don't have background worker support
// so set self to undefined as we want to keep this entirely local.
if ((_this$self = this.self) !== null && _this$self !== void 0 && _this$self.onmessage) {
this.onMessageCallback = this.self.onmessage;
}
this.self = undefined;
}
}, {
key: "postMessage",
value: function postMessage(data, origin /* = window?.document?.location?.origin*/) {
var transfer = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
if (!this.isReady) {
this.postsBeforeReady.push([data, origin, transfer]);
return;
}
var message = _typeof(data) === 'object' && 'data' in data ? data : {
data: data
};
if (this.isWorkerSupported()) {
if (isBrowser) {
var _this$self2;
(_this$self2 = this.self).postMessage.apply(_this$self2, _toConsumableArray([data, origin, transfer.length > 0 ? transfer : undefined].filter(function (arg) {
return !!arg;
})));
} else if (isNode) {
this.self.postMessage(data, transfer);
}
} else {
this.boots.onMessageLocal(message, origin, transfer);
}
}
}, {
key: "onMessage",
value: function onMessage(callback) {
console.log('support ' + this.isWorkerSupported());
if (this.isWorkerSupported()) {
if (isBrowser) {
this.self.onmessage = callback;
} else if (isNode) {
// Check if self has 'on' method (Node.js worker threads)
if (typeof this.self.on === 'function') {
this.self.on('message', callback);
} else {
// Fallback for mock workers or other implementations
this.self.onmessage = callback;
}
}
} else {
this.onMessageCallback = callback;
}
}
}, {
key: "onMessageLocal",
value: function onMessageLocal(data, origin) {
var transfer = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
console.log("sending local message that would have been to origin ".concat(origin));
if ((transfer === null || transfer === void 0 ? void 0 : transfer.length) > 0) {
console.log("transfer ignored for ".concat(transfer.length, " transfer references"));
}
console.log(this.onMessageCallback);
if (this.onMessageCallback) {
this.onMessageCallback(data);
} else {
throw new Error('onMessageLocal should not be called without onMessageCallback defined');
}
}
}, {
key: "terminate",
value: function terminate() {
var _this$self3, _this$self4;
this.terminateCallback && this.terminateCallback();
if (typeof ((_this$self3 = this.self) === null || _this$self3 === void 0 ? void 0 : _this$self3.terminate) === 'function') (_this$self4 = this.self) === null || _this$self4 === void 0 || _this$self4.terminate();
}
}, {
key: "onTerminate",
value: function onTerminate(callback) {
// this is only called when we don't support service workers... beware1!!!1
this.terminateCallback = callback;
}
}, {
key: "isWorkerSupported",
value: function isWorkerSupported() {
if (isBrowser) {
return typeof Worker !== 'undefined' && !!this.self;
} else if (isNode) {
return !!this.self;
}
return false;
}
}]);
}(); // Universal exports for all environments
// CommonJS compatibility for Browserify
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
WorkBoots: WorkBoots,
Socks: Socks
};
}
// AMD compatibility
if (typeof define === 'function' && define.amd) {
define([], function () {
return {
WorkBoots: WorkBoots,
Socks: Socks
};
});
}
// Global compatibility for browser
if (typeof window !== 'undefined') {
window.WorkBoots = WorkBoots;
window.Socks = Socks;
}
}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":2,"worker_threads":1}]},{},[3])(3)
});