11'use strict'
22const { JSONEncoder } = require ( '../../encode/json-encoder' )
33const { getEnvironmentVariable } = require ( '../../../config-helper' )
4+ const log = require ( '../../../log' )
5+ const {
6+ VITEST_WORKER_TRACE_PAYLOAD_CODE ,
7+ VITEST_WORKER_LOGS_PAYLOAD_CODE
8+ } = require ( '../../../plugins/util/test' )
49
510class Writer {
611 constructor ( interprocessCode ) {
@@ -26,25 +31,42 @@ class Writer {
2631 _sendPayload ( data , onDone = ( ) => { } ) {
2732 // ## Jest
2833 // Only available when `child_process` is used for the jest worker.
29- // https://github.com/facebook/jest/blob/bb39cb2c617a3334bf18daeca66bd87b7ccab28b/packages/jest-worker/README.md#experimental-worker
3034 // If worker_threads is used, this will not work
31- // TODO: make it compatible with worker_threads
35+ // TODO: make `jest` instrumentation compatible with worker_threads
36+ // https://github.com/facebook/jest/blob/bb39cb2c617a3334bf18daeca66bd87b7ccab28b/packages/jest-worker/README.md#experimental-worker
3237
3338 // ## Cucumber
3439 // This reports to the test's main process the same way test data is reported by Cucumber
3540 // See cucumber code:
3641 // https://github.com/cucumber/cucumber-js/blob/5ce371870b677fe3d1a14915dc535688946f734c/src/runtime/parallel/run_worker.ts#L13
37- if ( process . send ) { // it only works if process.send is available
38- // Old because vitest@>=4 use DD_VITEST_WORKER and report arrays just like other frameworks
39- const isVitestWorkerOld = ! ! getEnvironmentVariable ( 'TINYPOOL_WORKER_ID' )
4042
41- const payload = isVitestWorkerOld
42- ? { __tinypool_worker_message__ : true , interprocessCode : this . _interprocessCode , data }
43- : [ this . _interprocessCode , data ]
43+ // Old because vitest@>=4 uses `DD_VITEST_WORKER` and reports arrays just like other frameworks
44+ // Before vitest@>=4, we need the `__tinypool_worker_message__` property, or tinypool will crash
45+ const isVitestWorkerOld = ! ! getEnvironmentVariable ( 'TINYPOOL_WORKER_ID' )
46+ const payload = isVitestWorkerOld
47+ ? { __tinypool_worker_message__ : true , interprocessCode : this . _interprocessCode , data }
48+ : [ this . _interprocessCode , data ]
4449
50+ const isVitestTestWorker =
51+ this . _interprocessCode === VITEST_WORKER_TRACE_PAYLOAD_CODE ||
52+ this . _interprocessCode === VITEST_WORKER_LOGS_PAYLOAD_CODE
53+
54+ if ( process . send ) {
4555 process . send ( payload , ( ) => {
4656 onDone ( )
4757 } )
58+ } else if ( isVitestTestWorker ) { // TODO: worker_threads are only supported in vitest right now
59+ const { isMainThread, parentPort } = require ( 'worker_threads' )
60+ if ( isMainThread ) {
61+ return onDone ( )
62+ }
63+ try {
64+ parentPort . postMessage ( payload )
65+ } catch ( error ) {
66+ log . error ( 'Error posting message to parent port' , error )
67+ } finally {
68+ onDone ( )
69+ }
4870 } else {
4971 onDone ( )
5072 }
0 commit comments