1'use strict';
2const common = require('../common');
3const child_process = require('child_process');
4const assert = require('assert');
5const { Worker, workerData } = require('worker_threads');
6
7// Test for https://github.com/nodejs/node/issues/24947.
8
9if (!workerData && process.argv[2] !== 'child') {
10  process.env.SET_IN_PARENT = 'set';
11  assert.strictEqual(process.env.SET_IN_PARENT, 'set');
12
13  new Worker(__filename, { workerData: 'runInWorker' })
14    .on('exit', common.mustCall(() => {
15      // Env vars from the child thread are not set globally.
16      assert.strictEqual(process.env.SET_IN_WORKER, undefined);
17    }));
18
19  process.env.SET_IN_PARENT_AFTER_CREATION = 'set';
20
21  new Worker(__filename, {
22    workerData: 'resetEnv',
23    env: { 'MANUALLY_SET': true }
24  });
25
26  assert.throws(() => {
27    new Worker(__filename, { env: 42 });
28  }, {
29    name: 'TypeError',
30    code: 'ERR_INVALID_ARG_TYPE',
31    message: 'The "options.env" property must be of type object or ' +
32      'one of undefined, null, or worker_threads.SHARE_ENV. Received type ' +
33      'number (42)'
34  });
35} else if (workerData === 'runInWorker') {
36  // Env vars from the parent thread are inherited.
37  assert.strictEqual(process.env.SET_IN_PARENT, 'set');
38  assert.strictEqual(process.env.SET_IN_PARENT_AFTER_CREATION, undefined);
39  process.env.SET_IN_WORKER = 'set';
40  assert.strictEqual(process.env.SET_IN_WORKER, 'set');
41
42  assert.throws(
43    () => {
44      Object.defineProperty(process.env, 'DEFINED_IN_WORKER', {
45        value: 42
46      });
47    },
48    {
49      code: 'ERR_INVALID_OBJECT_DEFINE_PROPERTY',
50      name: 'TypeError',
51      message: '\'process.env\' only accepts a configurable, ' +
52          'writable, and enumerable data descriptor'
53    }
54  );
55
56
57  const { stderr } =
58    child_process.spawnSync(process.execPath, [__filename, 'child']);
59  assert.strictEqual(stderr.toString(), '', stderr.toString());
60} else if (workerData === 'resetEnv') {
61  assert.deepStrictEqual(Object.keys(process.env), ['MANUALLY_SET']);
62  assert.strictEqual(process.env.MANUALLY_SET, 'true');
63} else {
64  // Child processes inherit the parent's env, even from Workers.
65  assert.strictEqual(process.env.SET_IN_PARENT, 'set');
66  assert.strictEqual(process.env.SET_IN_WORKER, 'set');
67}
68