All files / pdf.js/external/builder preprocessor2.js

0% Statements 0/147
0% Branches 0/151
0% Functions 0/9
0% Lines 0/147
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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
'use strict';
 
var acorn = require('acorn');
var escodegen = require('escodegen');
var vm = require('vm');
var fs = require('fs');
var path = require('path');
 
var PDFJS_PREPROCESSOR_NAME = 'PDFJSDev';
var ROOT_PREFIX = '$ROOT/';
 
function isLiteral(obj, value) {
  return obj.type === 'Literal' && obj.value === value;
}
 
function isPDFJSPreprocessor(obj) {
  return obj.type === 'Identifier' &&
         obj.name === PDFJS_PREPROCESSOR_NAME;
}
 
function evalWithDefines(code, defines, loc) {
  if (!code || !code.trim()) {
    throw new Error('No JavaScript expression given');
  }
  return vm.runInNewContext(code, defines, { displayErrors: false, });
}
 
function handlePreprocessorAction(ctx, actionName, args, loc) {
  try {
    var arg;
    switch (actionName) {
      case 'test':
        arg = args[0];
        if (!arg || arg.type !== 'Literal' ||
            typeof arg.value !== 'string') {
          throw new Error('No code for testing is given');
        }
        var isTrue = !!evalWithDefines(arg.value, ctx.defines);
        return { type: 'Literal', value: isTrue, loc: loc, };
      case 'eval':
        arg = args[0];
        if (!arg || arg.type !== 'Literal' ||
            typeof arg.value !== 'string') {
          throw new Error('No code for eval is given');
        }
        var result = evalWithDefines(arg.value, ctx.defines);
        if (typeof result === 'boolean' || typeof result === 'string' ||
            typeof result === 'number') {
          return { type: 'Literal', value: result, loc: loc, };
        }
        if (typeof result === 'object') {
          var parsedObj = acorn.parse('(' + JSON.stringify(result) + ')');
          parsedObj.body[0].expression.loc = loc;
          return parsedObj.body[0].expression;
        }
        break;
      case 'json':
        arg = args[0];
        if (!arg || arg.type !== 'Literal' ||
            typeof arg.value !== 'string') {
          throw new Error('Path to JSON is not provided');
        }
        var jsonPath = arg.value;
        if (jsonPath.indexOf(ROOT_PREFIX) === 0) {
          jsonPath = path.join(ctx.rootPath,
                               jsonPath.substring(ROOT_PREFIX.length));
        }
        var jsonContent = fs.readFileSync(jsonPath).toString();
        var parsedJSON = acorn.parse('(' + jsonContent + ')');
        parsedJSON.body[0].expression.loc = loc;
        return parsedJSON.body[0].expression;
    }
    throw new Error('Unsupported action');
  } catch (e) {
    throw new Error('Could not process ' + PDFJS_PREPROCESSOR_NAME + '.' +
                    actionName + ' at ' + JSON.stringify(loc) + '\n' +
                    e.name + ': ' + e.message);
  }
}
 
function postprocessNode(ctx, node) {
  switch (node.type) {
    case 'ExportNamedDeclaration':
    case 'ImportDeclaration':
      if (node.source && node.source.type === 'Literal' &&
          ctx.map && ctx.map[node.source.value]) {
        var newValue = ctx.map[node.source.value];
        node.source.value = node.source.raw = newValue;
      }
      break;
    case 'IfStatement':
      if (isLiteral(node.test, true)) {
        // if (true) stmt1; => stmt1
        return node.consequent;
      } else if (isLiteral(node.test, false)) {
        // if (false) stmt1; else stmt2; => stmt2
        return node.alternate || { type: 'EmptyStatement', loc: node.loc, };
      }
      break;
    case 'ConditionalExpression':
      if (isLiteral(node.test, true)) {
        // true ? stmt1 : stmt2 => stmt1
        return node.consequent;
      } else if (isLiteral(node.test, false)) {
        // false ? stmt1 : stmt2 => stmt2
        return node.alternate;
      }
      break;
    case 'UnaryExpression':
      if (node.operator === 'typeof' &&
          isPDFJSPreprocessor(node.argument)) {
        // typeof PDFJSDev => 'object'
        return { type: 'Literal', value: 'object', loc: node.loc, };
      }
      if (node.operator === '!' &&
          node.argument.type === 'Literal' &&
          typeof node.argument.value === 'boolean') {
        // !true => false,  !false => true
        return { type: 'Literal', value: !node.argument.value, loc: node.loc, };
      }
      break;
    case 'LogicalExpression':
      switch (node.operator) {
        case '&&':
          if (isLiteral(node.left, true)) {
            return node.right;
          }
          if (isLiteral(node.left, false)) {
            return node.left;
          }
          break;
        case '||':
          if (isLiteral(node.left, true)) {
            return node.left;
          }
          if (isLiteral(node.left, false)) {
            return node.right;
          }
          break;
      }
      break;
    case 'BinaryExpression':
      switch (node.operator) {
        case '==':
        case '===':
        case '!=':
        case '!==':
          if (node.left.type === 'Literal' &&
              node.right.type === 'Literal' &&
              typeof node.left.value === typeof node.right.value) {
             // folding two literals == and != check
             switch (typeof node.left.value) {
               case 'string':
               case 'boolean':
               case 'number':
                 var equal = node.left.value === node.right.value;
                 return {
                   type: 'Literal',
                   value: (node.operator[0] === '=') === equal,
                   loc: node.loc,
                 };
             }
          }
          break;
      }
      break;
    case 'CallExpression':
      if (node.callee.type === 'MemberExpression' &&
          isPDFJSPreprocessor(node.callee.object) &&
          node.callee.property.type === 'Identifier') {
        // PDFJSDev.xxxx(arg1, arg2, ...) => tranform
        var action = node.callee.property.name;
        return handlePreprocessorAction(ctx, action,
                                        node.arguments, node.loc);
      }
      // require('string')
      if (node.callee.type === 'Identifier' && node.callee.name === 'require' &&
          node.arguments.length === 1 && node.arguments[0].type === 'Literal' &&
          ctx.map && ctx.map[node.arguments[0].value]) {
        var requireName = node.arguments[0];
        requireName.value = requireName.raw = ctx.map[requireName.value];
      }
      break;
    case 'BlockStatement':
      var subExpressionIndex = 0;
      while (subExpressionIndex < node.body.length) {
        switch (node.body[subExpressionIndex].type) {
          case 'EmptyStatement':
            // Removing empty statements from the blocks.
            node.body.splice(subExpressionIndex, 1);
            continue;
          case 'BlockStatement':
            // Block statements inside a block are moved to the parent one.
            var subChildren = node.body[subExpressionIndex].body;
            Array.prototype.splice.apply(node.body,
              [subExpressionIndex, 1].concat(subChildren));
            subExpressionIndex += Math.max(subChildren.length - 1, 0);
            continue;
          case 'ReturnStatement':
          case 'ThrowStatement':
            // Removing dead code after return or throw.
            node.body.splice(subExpressionIndex + 1,
                             node.body.length - subExpressionIndex - 1);
            break;
        }
        subExpressionIndex++;
      }
      break;
    case 'FunctionDeclaration':
    case 'FunctionExpression':
      var block = node.body;
      if (block.body.length > 0 &&
          block.body[block.body.length - 1].type === 'ReturnStatement' &&
          !block.body[block.body.length - 1].argument) {
        // Function body ends with return without arg -- removing it.
        block.body.pop();
      }
      break;
  }
  return node;
}
 
function fixComments(ctx, node) {
  if (!ctx.saveComments) {
    return;
  }
  // Fixes double comments in the escodegen output.
  delete node.trailingComments;
  // Removes ESLint and other service comments.
  if (node.leadingComments) {
    var CopyrightRegExp = /\bcopyright\b/i;
    var BlockCommentRegExp = /^\s*(globals|eslint|falls through)\b/;
    var LineCommentRegExp = /^\s*eslint\b/;
 
    var i = 0;
    while (i < node.leadingComments.length) {
      var type = node.leadingComments[i].type;
      var value = node.leadingComments[i].value;
 
      if (ctx.saveComments === 'copyright') {
        // Remove all comments, except Copyright notices and License headers.
        if (!(type === 'Block' && CopyrightRegExp.test(value))) {
          node.leadingComments.splice(i, 1);
          continue;
        }
      } else if ((type === 'Block' && BlockCommentRegExp.test(value)) ||
                 (type === 'Line' && LineCommentRegExp.test(value))) {
        node.leadingComments.splice(i, 1);
        continue;
      }
      i++;
    }
  }
}
 
function traverseTree(ctx, node) {
  // generic node processing
  for (var i in node) {
    var child = node[i];
    if (typeof child === 'object' && child !== null && child.type) {
      var result = traverseTree(ctx, child);
      if (result !== child) {
        node[i] = result;
      }
    } else if (Array.isArray(child)) {
      child.forEach(function (childItem, index) {
        if (typeof childItem === 'object' && childItem !== null &&
            childItem.type) {
          var result = traverseTree(ctx, childItem);
          if (result !== childItem) {
            child[index] = result;
          }
        }
      });
    }
  }
 
  node = postprocessNode(ctx, node) || node;
 
  fixComments(ctx, node);
  return node;
}
 
function preprocessPDFJSCode(ctx, code) {
  var format = ctx.format || {
    indent: {
      style: ' ',
    },
  };
  var parseOptions = {
    locations: true,
    sourceFile: ctx.sourceFile,
    sourceType: 'module',
  };
  var codegenOptions = {
    format: format,
    parse: acorn.parse,
    sourceMap: ctx.sourceMap,
    sourceMapWithCode: ctx.sourceMap,
  };
  var syntax = acorn.parse(code, parseOptions);
  traverseTree(ctx, syntax);
  return escodegen.generate(syntax, codegenOptions);
}
 
exports.preprocessPDFJSCode = preprocessPDFJSCode;