1/* global port */ 2'use strict'; 3const common = require('../common'); 4const assert = require('assert'); 5const vm = require('vm'); 6const { 7 MessagePort, MessageChannel, moveMessagePortToContext 8} = require('worker_threads'); 9 10const context = vm.createContext(); 11const { port1, port2 } = new MessageChannel(); 12context.port = moveMessagePortToContext(port1, context); 13context.global = context; 14Object.assign(context, { 15 global: context, 16 assert, 17 MessagePort, 18 MessageChannel 19}); 20 21vm.runInContext('(' + function() { 22 { 23 assert(port.postMessage instanceof Function); 24 assert(port.constructor instanceof Function); 25 for (let obj = port; obj !== null; obj = Object.getPrototypeOf(obj)) { 26 for (const key of Object.getOwnPropertyNames(obj)) { 27 if (typeof obj[key] === 'object' && obj[key] !== null) { 28 assert(obj[key] instanceof Object); 29 } else if (typeof obj[key] === 'function') { 30 assert(obj[key] instanceof Function); 31 } 32 } 33 } 34 35 assert(!(port instanceof MessagePort)); 36 assert.strictEqual(port.onmessage, undefined); 37 port.onmessage = function({ data, ports }) { 38 assert(data instanceof Object); 39 assert(ports instanceof Array); 40 assert.strictEqual(ports.length, 1); 41 assert.strictEqual(ports[0], data.p); 42 assert(!(data.p instanceof MessagePort)); 43 port.postMessage({}); 44 }; 45 port.start(); 46 } 47 48 { 49 let threw = false; 50 try { 51 port.postMessage(global); 52 } catch (e) { 53 assert.strictEqual(e.constructor.name, 'DOMException'); 54 assert(e instanceof Object); 55 assert(e instanceof Error); 56 threw = true; 57 } 58 assert(threw); 59 } 60} + ')()', context); 61 62const otherChannel = new MessageChannel(); 63port2.on('message', common.mustCall((msg) => { 64 assert(msg instanceof Object); 65 port2.close(); 66 otherChannel.port2.close(); 67})); 68port2.postMessage({ p: otherChannel.port1 }, [ otherChannel.port1 ]); 69