All files / src core.js

100% Statements 99/99
100% Branches 33/33
100% Functions 27/27
100% Lines 83/83
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 25310x     123x 122x 121x 121x 121x 121x 121x             121x 182x 182x   121x 121x 121x   79x 1x 1x                 1x     42x 42x 3x 3x                 3x         238x 238x 194x 115x 115x 115x   81x 81x 81x                     36x 36x     44x         121x           81x       238x 194x       115x 115x 120x 115x 115x               120x 120x                 120x 120x 120x 1x     119x   17x   119x   86x 2x 2x                     2x     33x 33x 1x 1x                     1x         120x 4x               4x       75x 3x   2x 2x                           3x                       3x       121x 1x         1x       4x                 4x       1x 1x 1x 1x 1x     1x     10x        
const { toArray, toPromise, delay } = require("./util");
 
function call(context, interpreters, fn, ...args) {
  if (!context) return Promise.reject(new Error("context required"));
  if (!fn) return Promise.reject(new Error("function required"));
  const gen = fn.apply(null, args);
  const el = newExecutionLog();
  const childContext = Object.assign({}, context);
  childContext.stack = childContext.stack || [];
  childContext.stack.push({
    context: childContext,
    interpreters,
    fn,
    args
  });
  // clean up circular references to allow for serialization
  childContext.stack = childContext.stack.map(s => {
    s.context = Object.assign({}, s.context, { stack: undefined });
    return s;
  });
  const start = Date.now();
  onCall({ args, fn, context: childContext });
  return run(childContext, interpreters, fn, gen, null, el)
    .then(result => {
      if (!childContext.onCallComplete) return result;
      const end = Date.now();
      onCallComplete({
        success: true,
        fn,
        result,
        context: childContext,
        start,
        end,
        latency: end - start
      });
      return result;
    })
    .catch(e => {
      onError(e, childContext);
      if (!childContext.onCallComplete) return Promise.reject(e);
      const end = Date.now();
      onCallComplete({
        success: false,
        fn,
        result: e,
        context: childContext,
        start,
        end,
        latency: end - start
      });
      return Promise.reject(e);
    });
}
 
function run(context, interpreters, fn, gen, input, el, genOperation = "next") {
  try {
    const { output, done } = getNextOutput(gen, input, genOperation);
    if (done) return toPromise(output);
    const isList = Array.isArray(output);
    const commandsList = toArray(output);
    return processCommands(context, interpreters, fn, commandsList, el)
      .then(results => {
        const unwrappedResults = unwrapResults(isList, results);
        el.step++;
        return run(
          context,
          interpreters,
          fn,
          gen,
          unwrappedResults,
          el,
          "next"
        );
      })
      .catch(e => {
        el.step++;
        return run(context, interpreters, fn, gen, e, el, "throw");
      });
  } catch (e) {
    return Promise.reject(e);
  }
}
 
function newExecutionLog() {
  return {
    step: 0
  };
}
 
function unwrapResults(isList, results) {
  return isList ? results : results[0];
}
 
function getNextOutput(fn, input, op) {
  const { value: output, done } = fn[op](input);
  return { output, done };
}
 
function processCommands(context, interpreters, fn, commands, el) {
  try {
    const pc = (c, index) =>
      processCommand(context, interpreters, fn, c, el, index);
    const promises = commands.map(pc);
    return Promise.all(promises);
  } catch (e) {
    // istanbul ignore next
    return Promise.reject(e);
  }
}
 
function processCommand(context, interpreters, fn, command, el, index) {
  const start = Date.now();
  onCommand({
    command,
    fn,
    start,
    index,
    step: el.step,
    context
  });
  let result;
  try {
    const interpreter = interpreters[command.type];
    if (!interpreter)
      return Promise.reject(
        new Error(`Interpreter of type "${command.type}" is not registered.`)
      );
    result = interpreter(command, { call, context, interpreters });
  } catch (e) {
    result = Promise.reject(e);
  }
  return toPromise(result)
    .then(r => {
      if (!context.onCommandComplete) return r;
      const end = Date.now();
      onCommandComplete({
        success: true,
        context,
        command,
        fn,
        step: el.step,
        index,
        result: r,
        start,
        end
      });
      return r;
    })
    .catch(e => {
      onError(e, context);
      if (!context.onCommandComplete) return Promise.reject(e);
      const end = Date.now();
      onCommandComplete({
        success: false,
        context,
        command,
        fn,
        step: el.step,
        index,
        result: e,
        start,
        end
      });
      return Promise.reject(e);
    });
}
 
function onCommand({ command, index, step, context, start, fn }) {
  if (!context.onCommand || typeof context.onCommand !== "function") return;
  const r = {
    command,
    start,
    index,
    step,
    context,
    fn
  };
  delay(() => context.onCommand(r));
}
 
function onError(error, context) {
  if (!context.onError) return;
  if (error.eadReported) return;
  // tag error to prevent multiple reports as the error bubbles up
  error.eadReported = true;
  delay(() => context.onError(error, context));
}
 
function onCommandComplete({
  success,
  command,
  index,
  step,
  result,
  context,
  start,
  end,
  fn
}) {
  const r = {
    success,
    command,
    latency: end - start,
    start,
    end,
    index,
    step,
    result,
    context,
    fn
  };
  delay(() => context.onCommandComplete(r));
}
 
function onCall({ args, fn, context }) {
  if (!context.onCall || typeof context.onCall !== "function") return;
  const r = {
    args,
    fn,
    context
  };
  delay(() => context.onCall(r));
}
 
function onCallComplete({ success, result, fn, context, start, end, latency }) {
  const r = {
    success,
    fn,
    context,
    end,
    latency,
    result,
    start
  };
  delay(() => context.onCallComplete(r));
}
 
function buildFunctions(context, interpreters, functions) {
  let promiseFunctions = {};
  for (let i in functions) {
    promiseFunctions[i] = function(...args) {
      const localContext = Object.assign({ name: i }, context);
      return call(localContext, interpreters, functions[i], ...args);
    };
  }
  return promiseFunctions;
}
 
module.exports = {
  call,
  buildFunctions
};