All files / node_modules/js-yaml/lib/js-yaml/type/js function.js

36.36% Statements 4/11
0% Branches 0/8
0% Functions 0/1
36.36% Lines 4/11
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 851x                         1x             1x                                                                                                                 1x              
'use strict';
 
var esprima;
 
// Browserified version does not have esprima
//
// 1. For node.js just require module as deps
// 2. For browser try to require mudule via external AMD system.
//    If not found - try to fallback to window.esprima. If not
//    found too - then fail to parse.
//
try {
  // workaround to exclude package from browserify list.
  var _require = require;
  esprima = _require('esprima');
} catch (_) {
  /*global window */
  if (typeof window !== 'undefined') esprima = window.esprima;
}
 
var Type = require('../../type');
 
function resolveJavascriptFunction(data) {
  if (data === null) return false;
 
  try {
    var source = '(' + data + ')',
        ast    = esprima.parse(source, { range: true });
 
    if (ast.type                    !== 'Program'             ||
        ast.body.length             !== 1                     ||
        ast.body[0].type            !== 'ExpressionStatement' ||
        ast.body[0].expression.type !== 'FunctionExpression') {
      return false;
    }
 
    return true;
  } catch (err) {
    return false;
  }
}
 
function constructJavascriptFunction(data) {
  /*jslint evil:true*/
 
  var source = '(' + data + ')',
      ast    = esprima.parse(source, { range: true }),
      params = [],
      body;
 
  if (ast.type                    !== 'Program'             ||
      ast.body.length             !== 1                     ||
      ast.body[0].type            !== 'ExpressionStatement' ||
      ast.body[0].expression.type !== 'FunctionExpression') {
    throw new Error('Failed to resolve function');
  }
 
  ast.body[0].expression.params.forEach(function (param) {
    params.push(param.name);
  });
 
  body = ast.body[0].expression.body.range;
 
  // Esprima's ranges include the first '{' and the last '}' characters on
  // function expressions. So cut them out.
  /*eslint-disable no-new-func*/
  return new Function(params, source.slice(body[0] + 1, body[1] - 1));
}
 
function representJavascriptFunction(object /*, style*/) {
  return object.toString();
}
 
function isFunction(object) {
  return Object.prototype.toString.call(object) === '[object Function]';
}
 
module.exports = new Type('tag:yaml.org,2002:js/function', {
  kind: 'scalar',
  resolve: resolveJavascriptFunction,
  construct: constructJavascriptFunction,
  predicate: isFunction,
  represent: representJavascriptFunction
});