All files / lib ConsoleAgent.js

96.18% Statements 126/131
85.51% Branches 59/69
100% Functions 19/19
96.09% Lines 123/128

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341  2x 2x 2x 2x 2x   2x 2x 2x 2x           2x       2x   2x 2x     650x 650x     2x                               2x 651x 377x   274x 274x 274x   252x       2x 22x         365x   365x 365x 365x       365x                             638x   638x     638x 638x                             650x   650x 650x   650x 650x   650x 650x   650x 1x 1x       650x 329x   329x   329x 329x 329x       329x 322x 322x     329x 157x 157x     329x       321x           329x           650x 649x                     650x     650x             165x 456x 456x         456x 291x               650x   650x 650x 650x   650x 9x             641x 641x   641x               641x 641x   641x 641x 639x     639x       930x           639x 639x   639x       724x 724x     724x 605x 605x 605x 605x 605x       724x         353x       651x 651x 651x   651x 651x   651x     234264x 3835x     234264x   2455x   73x       234264x       651x     651x   651x     651x 651x       651x       651x   651x 22x     629x         244x     34x       2x         2x    
'use strict';
const cp = require('child_process');
const fs = require('fs');
const path = require('path');
const recast = require('recast');
const uniqueTempDir = require('unique-temp-dir');
 
const Agent = require('./Agent');
const inception = require('./inception');
const writeSources = require('./write-sources');
const ErrorParser = require('./parse-error');
const {
  getDependencies,
  // escapeModuleSpecifier,
  hasModuleSpecifier,
  rawSource
} = require('./dependencies');
 
const {
  ChildProcess
} = cp;
 
const CHILD_PROCESS = Symbol.for('cp');
const TEMP_PATH = Symbol.for('tp');
 
function generateTempFileName() {
  const now = Date.now();
  return `f-${now}-${process.pid}-${(Math.random() * 0x100000000 + 1).toString(36)}.js`;
}
 
const ESHostErrorSource = `
function ESHostError(message) {
  this.message = message || "";
}
ESHostError.prototype.toString = function () {
  return "ESHostError: " + this.message;
};
ESHostError.thrower = (...args) => {
  throw new ESHostError(...args);
};
var $ERROR = ESHostError.thrower;
function $DONOTEVALUATE() {
  throw "ESHost: This statement should not be evaluated.";
}
`;
 
const isMissingTest262ErrorDefinition = header => {
  if (!header.includes('Test262Error')) {
    return false;
  }
  try {
    const f = new Function(`${header}; return typeof Test262Error == 'undefined';`);
    return f();
  } catch (error) {
    return false;
  }
};
 
const useESHostError = (code) => {
  return `${ESHostErrorSource}${code}`.replace(/Test262Error/gm, 'ESHostError');
};
 
class ConsoleAgent extends Agent {
  constructor(options) {
    super(options);
 
    this.isStopped = false;
    this.printCommand = 'print';
    this.cpOptions = {};
    // Promise for the child process created by the most
    // recent invocation of `evalScript`
 
    Object.defineProperties(this, {
      [CHILD_PROCESS]: {
        value: null,
        writable: true,
        enumerable: false
      },
      [TEMP_PATH]: {
        value: uniqueTempDir(),
        writable: true,
        enumerable: false
      }
    });
  }
 
  async createChildProcess(args = [], options = {}) {
    this.hasFinishedCreatingChildProcess = false;
 
    Iif (this.isStopped) {
      return null;
    }
    try {
      return cp.spawn(
        this.hostPath,
        this.args.concat(args),
        {
          ...this.cpOptions,
          ...options,
          detached: true
        }
      );
    } catch (error) {
      return this.createChildProcess(args, options);
    }
  }
 
  async evalScript(code, options = {}) {
    this.isStopped = false;
 
    let tempfile = path.join(this[TEMP_PATH], generateTempFileName());
    let temppath = this[TEMP_PATH];
 
    let isExpectingRawSource = false;
    let hasDependencies = false;
 
    const sources = [];
    const dependencies = [];
 
    if (this.out) {
      tempfile = tempfile.replace(temppath, this.out);
      temppath = this.out;
    }
 
    // When evalScript is called with a test262-stream test record:
    if (typeof code === 'object' && code.contents) {
      let {attrs, contents, file} = code;
 
      isExpectingRawSource = !!attrs.flags.raw;
 
      let { phase = '', type = '' } = attrs.negative || {};
      let isEarlySyntaxError = (phase === 'early' || phase === 'parse') && type === 'SyntaxError';
      let sourcebase = path.basename(file);
 
      // If the main test file isn't a negative: SyntaxError,
      // then we can proceed with checking for importable files
      if (!isEarlySyntaxError) {
        dependencies.push(...getDependencies(file, [sourcebase]));
        hasDependencies = dependencies.length > 0;
      }
 
      if (dependencies.length === 1 && dependencies[0] === sourcebase) {
        dependencies.length = 0;
        hasDependencies = false;
      }
 
      if (options.module || attrs.flags.module ||
          hasModuleSpecifier(contents)) {
        // When testing module or dynamic import code that imports itself,
        // we must copy the test file with its actual name.
        tempfile = path.join(temppath, sourcebase);
      }
 
      // The test record in "code" is no longer needed and
      // all further operations expect the "code" argument to be
      // a string, make that true for back-compat.
      code = contents;
    }
 
    // If test record explicitly indicates that this test should be
    // treated as raw source only, then it does not need to be
    // further "compiled".
    if (!isExpectingRawSource) {
      code = this.compile(code);
    }
 
    // Add the entry point source to the list of source to create.
    //
    //  "tempfile" will be either:
    //
    //    - A generated temporary file name, if evalScript received
    //      raw source code.
    //    - The file name of the test being executed, but within
    //      the os's temporary file directory
    sources.push([ tempfile, code ]);
 
    // If any dependencies were discovered, there will be
    if (hasDependencies) {
      // Prepare dependencies for use:
      //
      // 1. Make an absolute path for the dependency file.
      // 2. Get the dependency's source from the rawSource cache
      // 3. Push the dependency and source into the sources to be written.
      //
      dependencies.forEach(file => {
        let absname = path.join(temppath, file);
        let depsource = rawSource.get(path.basename(file));
 
        // Sometimes a test file might want to import itself,
        // which is a valid exercise of the import semantics.
        // Here we avoid adding the test file more than once.
        if (absname !== tempfile) {
          sources.push([
            absname,
            depsource
          ]);
        }
      });
    }
 
    await writeSources(sources);
 
    let stdout = '';
    let stderr = '';
    let error = null;
 
    if (this.isStopped) {
      return {
        stderr,
        stdout,
        error
      };
    }
 
    this[CHILD_PROCESS] = await this.createChildProcess([tempfile]);
    this.hasFinishedCreatingChildProcess = true;
 
    Iif (this.isStopped && this[CHILD_PROCESS] === null) {
      return {
        stderr,
        stdout,
        error
      };
    }
 
    this[CHILD_PROCESS].stdout.on('data', str => { stdout += str; });
    this[CHILD_PROCESS].stderr.on('data', str => { stderr += str; });
 
    await new Promise(resolve => {
      this[CHILD_PROCESS].on('close', (code, signal) => {
        Iif (signal && signal !== 'SIGKILL') {
          stderr += `\nError: Received unexpected signal: ${signal}`;
        }
        resolve();
      });
    });
 
    sources.forEach(({0: file}) => fs.unlink(file, () => { /* ignore */ }));
 
    // try {
    //   process.kill(this[CHILD_PROCESS].pid + 1);
    // } catch (error) {}
 
    const result = this.normalizeResult({ stderr, stdout });
    result.error = this.parseError(result.stderr);
 
    return result;
  }
 
  stop() {
    let stoppedAnActiveChildProcess = false;
    this.isStopped = true;
 
    // This must be sync
    if (this.hasFinishedCreatingChildProcess && this[CHILD_PROCESS] instanceof ChildProcess) {
      this[CHILD_PROCESS].stdin.end();
      this[CHILD_PROCESS].stdout.destroy();
      this[CHILD_PROCESS].stderr.destroy();
      this[CHILD_PROCESS].kill('SIGKILL');
      stoppedAnActiveChildProcess = true;
    }
 
    // killing is fast, don't bother waiting for it
    return Promise.resolve(stoppedAnActiveChildProcess);
  }
 
  // console agents need to kill the process before exiting.
  async destroy() {
    return this.stop();
  }
 
  compile(code, options) {
    code = super.compile(code, options);
    let runtime = this.constructor.runtime;
    let { options: hostOptions } = this;
 
    Eif (runtime) {
      let ast = recast.parse(runtime);
 
      recast.visit(ast, {
        visitNode(node) {
          // Remove comments from runtime source
          if (node.value.comments) {
            node.value.comments.length = 0;
          }
 
          if (hostOptions.shortName) {
            // Replace $ in runtime source
            if (node.value.type === 'Identifier' &&
                node.value.name === '$262') {
              node.value.name = hostOptions.shortName;
            }
          }
 
          this.traverse(node);
        }
      });
 
      runtime = recast.print(ast).code;
    }
 
    runtime = inception(runtime.replace(/\r?\n/g, '').replace(/\s+/gm, ' '));
 
    Iif (!runtime) {
      return code;
    } else {
      const prologue = code.match(/^("[^\r\n"]*"|'[^\r\n']*'|[\s\r\n;]*|\/\*[\w\W]*?\*\/|\/\/[^\n]*\n)*/);
      const header = prologue
        ? prologue[0] + runtime
        : runtime;
 
      const body = prologue
        ? code.slice(prologue[0].length)
        : code;
 
      const compiledCode = `${header}${body}`;
 
      if (isMissingTest262ErrorDefinition(header)) {
        return useESHostError(compiledCode);
      }
 
      return compiledCode;
    }
  }
 
  // Normalizes raw output from a console host. Default is no normalization.
  normalizeResult(result) { return result; }
 
  parseError(str) {
    return ErrorParser.parse(str);
  }
}
 
ConsoleAgent.runtime = `
  /* This is not the agent you're looking for */
  const name = 'ConsoleAgent';
`;
 
module.exports = ConsoleAgent;