expressions.js (2204B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */ 4 5 import { correctIndentation } from "./indentation"; 6 import { getGrip, getFront } from "./evaluation-result"; 7 8 const UNAVAILABLE_GRIP = { unavailable: true }; 9 10 /* 11 * wrap the expression input in a try/catch so that it can be safely 12 * evaluated. 13 * 14 * NOTE: we add line after the expression to protect against comments. 15 */ 16 export function wrapExpression(input) { 17 return correctIndentation(` 18 try { 19 ${input} 20 } catch (e) { 21 e 22 } 23 `); 24 } 25 26 function isUnavailable(value) { 27 return ( 28 value && 29 !!value.isError && 30 (value.class === "ReferenceError" || value.class === "TypeError") 31 ); 32 } 33 34 /** 35 * 36 * @param {object} expression: Expression item as stored in state.expressions in reducers/expressions.js 37 * @param {string} expression.input: evaluated expression string 38 * @param {object} expression.value: evaluated expression result object as returned from ScriptCommand#execute 39 * @param {object} expression.value.result: expression result, might be a primitive, a grip or a front 40 * @param {object} expression.value.exception: expression result error, might be a primitive, a grip or a front 41 * @returns {object} an object of the following shape: 42 * - expressionResultGrip: A primitive or a grip 43 * - expressionResultFront: An object front if it exists, or undefined 44 */ 45 export function getExpressionResultGripAndFront(expression) { 46 const { value } = expression; 47 48 if (!value) { 49 return { expressionResultGrip: UNAVAILABLE_GRIP }; 50 } 51 52 const expressionResultReturn = value.exception || value.result; 53 const valueGrip = getGrip(expressionResultReturn); 54 if (valueGrip == null || isUnavailable(valueGrip)) { 55 return { expressionResultGrip: UNAVAILABLE_GRIP }; 56 } 57 58 if (valueGrip.isError) { 59 const { name, message } = valueGrip.preview; 60 return { expressionResultGrip: `${name}: ${message}` }; 61 } 62 63 return { 64 expressionResultGrip: valueGrip, 65 expressionResultFront: getFront(expressionResultReturn), 66 }; 67 }