()
| 93 | } |
| 94 | |
| 95 | function initWorkerThreadsWorker(): ImplementationExport { |
| 96 | // Webpack hack |
| 97 | const NativeWorker = typeof __non_webpack_require__ === "function" |
| 98 | ? __non_webpack_require__("worker_threads").Worker |
| 99 | : eval("require")("worker_threads").Worker |
| 100 | |
| 101 | let allWorkers: Array<typeof NativeWorker> = [] |
| 102 | |
| 103 | class Worker extends NativeWorker { |
| 104 | private mappedEventListeners: WeakMap<EventListener, EventListener> |
| 105 | |
| 106 | constructor(scriptPath: string, options?: ThreadsWorkerOptions & { fromSource: boolean }) { |
| 107 | const resolvedScriptPath = options && options.fromSource |
| 108 | ? null |
| 109 | : resolveScriptPath(scriptPath, (options || {})._baseURL) |
| 110 | |
| 111 | if (!resolvedScriptPath) { |
| 112 | // `options.fromSource` is true |
| 113 | const sourceCode = scriptPath |
| 114 | super(sourceCode, { ...options, eval: true }) |
| 115 | } else if (resolvedScriptPath.match(/\.tsx?$/i) && detectTsNode()) { |
| 116 | super(createTsNodeModule(resolvedScriptPath), { ...options, eval: true }) |
| 117 | } else if (resolvedScriptPath.match(/\.asar[\/\\]/)) { |
| 118 | // See <https://github.com/andywer/threads-plugin/issues/17> |
| 119 | super(resolvedScriptPath.replace(/\.asar([\/\\])/, ".asar.unpacked$1"), options) |
| 120 | } else { |
| 121 | super(resolvedScriptPath, options) |
| 122 | } |
| 123 | |
| 124 | this.mappedEventListeners = new WeakMap() |
| 125 | allWorkers.push(this) |
| 126 | } |
| 127 | |
| 128 | public addEventListener(eventName: string, rawListener: EventListener) { |
| 129 | const listener = (message: any) => { |
| 130 | rawListener({ data: message } as any) |
| 131 | } |
| 132 | this.mappedEventListeners.set(rawListener, listener) |
| 133 | this.on(eventName, listener) |
| 134 | } |
| 135 | |
| 136 | public removeEventListener(eventName: string, rawListener: EventListener) { |
| 137 | const listener = this.mappedEventListeners.get(rawListener) || rawListener |
| 138 | this.off(eventName, listener) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | const terminateWorkersAndMaster = () => { |
| 143 | // we should terminate all workers and then gracefully shutdown self process |
| 144 | Promise.all(allWorkers.map(worker => worker.terminate())).then( |
| 145 | () => process.exit(0), |
| 146 | () => process.exit(1), |
| 147 | ) |
| 148 | allWorkers = [] |
| 149 | } |
| 150 | |
| 151 | // Take care to not leave orphaned processes behind. See #147. |
| 152 | process.on("SIGINT", () => terminateWorkersAndMaster()) |
no test coverage detected