11cb0ef41Sopenharmony_ci'use strict';
21cb0ef41Sopenharmony_ciconst common = require('../common');
31cb0ef41Sopenharmony_ci
41cb0ef41Sopenharmony_ciconst { Worker } = require('worker_threads');
51cb0ef41Sopenharmony_ciconst { createHook } = require('async_hooks');
61cb0ef41Sopenharmony_ciconst { deepStrictEqual, strictEqual } = require('assert');
71cb0ef41Sopenharmony_ci
81cb0ef41Sopenharmony_ciconst m = new Map();
91cb0ef41Sopenharmony_cicreateHook({
101cb0ef41Sopenharmony_ci  init(asyncId, type, triggerAsyncId, resource) {
111cb0ef41Sopenharmony_ci    if (['WORKER', 'MESSAGEPORT'].includes(type)) {
121cb0ef41Sopenharmony_ci      m.set(asyncId, { type, resource });
131cb0ef41Sopenharmony_ci    }
141cb0ef41Sopenharmony_ci  },
151cb0ef41Sopenharmony_ci  destroy(asyncId) {
161cb0ef41Sopenharmony_ci    m.delete(asyncId);
171cb0ef41Sopenharmony_ci  }
181cb0ef41Sopenharmony_ci}).enable();
191cb0ef41Sopenharmony_ci
201cb0ef41Sopenharmony_cifunction getActiveWorkerAndMessagePortTypes() {
211cb0ef41Sopenharmony_ci  const activeWorkerAndMessagePortTypes = [];
221cb0ef41Sopenharmony_ci  for (const asyncId of m.keys()) {
231cb0ef41Sopenharmony_ci    const { type, resource } = m.get(asyncId);
241cb0ef41Sopenharmony_ci    // Same logic as https://github.com/mafintosh/why-is-node-running/blob/24fb4c878753390a05d00959e6173d0d3c31fddd/index.js#L31-L32.
251cb0ef41Sopenharmony_ci    if (typeof resource.hasRef !== 'function' || resource.hasRef() === true) {
261cb0ef41Sopenharmony_ci      activeWorkerAndMessagePortTypes.push(type);
271cb0ef41Sopenharmony_ci    }
281cb0ef41Sopenharmony_ci  }
291cb0ef41Sopenharmony_ci  return activeWorkerAndMessagePortTypes;
301cb0ef41Sopenharmony_ci}
311cb0ef41Sopenharmony_ci
321cb0ef41Sopenharmony_ciconst w = new Worker('', { eval: true });
331cb0ef41Sopenharmony_cideepStrictEqual(getActiveWorkerAndMessagePortTypes(), ['WORKER']);
341cb0ef41Sopenharmony_ciw.unref();
351cb0ef41Sopenharmony_cideepStrictEqual(getActiveWorkerAndMessagePortTypes(), []);
361cb0ef41Sopenharmony_ciw.ref();
371cb0ef41Sopenharmony_cideepStrictEqual(getActiveWorkerAndMessagePortTypes(), ['WORKER', 'MESSAGEPORT']);
381cb0ef41Sopenharmony_ci
391cb0ef41Sopenharmony_ciw.on('exit', common.mustCall((exitCode) => {
401cb0ef41Sopenharmony_ci  strictEqual(exitCode, 0);
411cb0ef41Sopenharmony_ci  deepStrictEqual(getActiveWorkerAndMessagePortTypes(), ['WORKER']);
421cb0ef41Sopenharmony_ci  setTimeout(common.mustCall(() => {
431cb0ef41Sopenharmony_ci    deepStrictEqual(getActiveWorkerAndMessagePortTypes(), []);
441cb0ef41Sopenharmony_ci  }), 0);
451cb0ef41Sopenharmony_ci}));
46